@readmagic/workmate 0.0.14 → 0.0.15

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 (277) hide show
  1. package/dist/chunks/AddWorkspaceDirectory-DcVnvL_u.js +1 -0
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-0Qdg3Rh7.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-D58Vn3SK.js → AgentsMdExternalIncludesDialog-D6DopTxc.js} +1 -1
  4. package/dist/chunks/{App-CeC-2dzL.js → App-BoI5EJry.js} +1 -1
  5. package/dist/chunks/{ApproveApiKey-DFpddLyp.js → ApproveApiKey-BjlQDcMx.js} +1 -1
  6. package/dist/chunks/ApproveApiKey-PWFcscjY.js +1 -0
  7. package/dist/chunks/{BackgroundTasksDialog-9ruzl1jm.js → BackgroundTasksDialog-ClSMkcGp.js} +1 -1
  8. package/dist/chunks/BypassPermissionsModeDialog-KCZv-PXl.js +1 -0
  9. package/dist/chunks/{DiffDialog-LTdtTqsC.js → DiffDialog-BGBkuVIn.js} +1 -1
  10. package/dist/chunks/{Doctor-Yvrzcrvx.js → Doctor-CI04juFO.js} +1 -1
  11. package/dist/chunks/Doctor-DCrqcW68.js +1 -0
  12. package/dist/chunks/{ExitFlow-DH0L3tyY.js → ExitFlow-qrCDVA9i.js} +1 -1
  13. package/dist/chunks/Grove-B-M3DWD3.js +11 -0
  14. package/dist/chunks/{HybridTransport-CEWG9ZRi.js → HybridTransport-n5jji6SI.js} +1 -1
  15. package/dist/chunks/{InvalidConfigDialog-Ue3kJUPJ.js → InvalidConfigDialog-By-j6fHE.js} +1 -1
  16. package/dist/chunks/{InvalidSettingsDialog-BO2AOTVf.js → InvalidSettingsDialog-C_reeMzL.js} +1 -1
  17. package/dist/chunks/{MCPConnectionManager-Ciy9y9VV.js → MCPConnectionManager-BNG7iSlw.js} +1 -1
  18. package/dist/chunks/MCPToolListView-jw0tITfc.js +1 -0
  19. package/dist/chunks/{McpParsingWarnings-BsCDFWci.js → McpParsingWarnings-BeZ3Bn8N.js} +1 -1
  20. package/dist/chunks/{MessageSelector-DY5K0NHd.js → MessageSelector-Ci6N-gCw.js} +1 -1
  21. package/dist/chunks/{Messages-LD6ZO301.js → Messages-D6CRTH2m.js} +2 -2
  22. package/dist/chunks/{Onboarding-w0-VVsDz.js → Onboarding-DDkVEq-G.js} +1 -1
  23. package/dist/chunks/{PromptInputFooterSuggestions-OEXx0Abp.js → PromptInputFooterSuggestions-BlhZuQ5F.js} +1 -1
  24. package/dist/chunks/{PromptInputHelpMenu-DyaUsvNx.js → PromptInputHelpMenu-kKyPIMau.js} +1 -1
  25. package/dist/chunks/{QueryEngine-sH-KjJIq.js → QueryEngine-DXpS0Ytq.js} +1 -1
  26. package/dist/chunks/{REPL-BMH_RItw.js → REPL-D1BCm7cR.js} +15 -15
  27. package/dist/chunks/REPL-JQgCrSEv.js +1 -0
  28. package/dist/chunks/RemoteSessionManager-mWVrdNfS.js +2 -0
  29. package/dist/chunks/{ResumeConversation-BbNrpSFB.js → ResumeConversation-BzTn_1jS.js} +1 -1
  30. package/dist/chunks/{SSETransport-CLiI2qnD.js → SSETransport-D86IVNn1.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-BXIja1MR.js +1 -0
  32. package/dist/chunks/{Settings-B1EI5LOU.js → Settings-D_i8HzEW.js} +2 -2
  33. package/dist/chunks/{TeleportProgress-IB--CbqZ.js → TeleportProgress-CW8mLRy2.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-KjdlS_gA.js → TeleportRepoMismatchDialog-DZD32R-l.js} +1 -1
  35. package/dist/chunks/TeleportResumeWrapper-BhuUE1aq.js +1 -0
  36. package/dist/chunks/{ThemePicker-BrD_T7xF.js → ThemePicker-ByQZgIbH.js} +1 -1
  37. package/dist/chunks/{TrustDialog-L0rvvpit.js → TrustDialog-BzwibD_8.js} +1 -1
  38. package/dist/chunks/{ValidationErrorsList-QZvtUrAy.js → ValidationErrorsList-Cuq6W2yc.js} +1 -1
  39. package/dist/chunks/{add-dir-CpWXReCi.js → add-dir-BQ-ljgk6.js} +1 -1
  40. package/dist/chunks/{agentDisplay-CrQvGkTT.js → agentDisplay-tRprY4gB.js} +1 -1
  41. package/dist/chunks/agents-DMyQUXwl.js +101 -0
  42. package/dist/chunks/{agents-C99yMsVF.js → agents-Dq4BCf0H.js} +1 -1
  43. package/dist/chunks/{allErrors-uyOMiF9U.js → allErrors-CQWZ6BPw.js} +1 -1
  44. package/dist/chunks/{api-C5I2xwgd.js → api-ClAyS7cQ.js} +1 -1
  45. package/dist/chunks/api-CpD5jeKe.js +1 -0
  46. package/dist/chunks/{auth-BYCRa_mb.js → auth-CWAvPfX7.js} +1 -1
  47. package/dist/chunks/auth-DG5bkWDc.js +1 -0
  48. package/dist/chunks/auth-DuHfQBuH.js +1 -0
  49. package/dist/chunks/backgroundHousekeeping-kf_v7Vfr.js +1 -0
  50. package/dist/chunks/{backgroundHousekeeping-CjD8bACB.js → backgroundHousekeeping-rzQFJiND.js} +2 -2
  51. package/dist/chunks/{branch-BOWBZo5K.js → branch-BWbCrXBJ.js} +1 -1
  52. package/dist/chunks/bridgeConfig-CABsoOum.js +1 -0
  53. package/dist/chunks/{bridgeConfig-CgAVrQfz.js → bridgeConfig-CPHAyzdg.js} +1 -1
  54. package/dist/chunks/{bridgeMessaging-cOFtbkf_.js → bridgeMessaging-vR7uQXB9.js} +1 -1
  55. package/dist/chunks/bridgeStatusUtil-CHTx7XwJ.js +1 -0
  56. package/dist/chunks/{btw-B0UmiVKl.js → btw-IGcgP-Qq.js} +1 -1
  57. package/dist/chunks/caches-Dj1YhqrG.js +1 -0
  58. package/dist/chunks/{caches-wN3JyvNE.js → caches-FP8mGB4k.js} +1 -1
  59. package/dist/chunks/{ccrClient-wtUIz75R.js → ccrClient--8aPutWE.js} +1 -1
  60. package/dist/chunks/claudeDesktop-CB3UCt7U.js +1 -0
  61. package/dist/chunks/{clear-CNzBoL7O.js → clear-CF-FZwpe.js} +1 -1
  62. package/dist/chunks/client-BU7upHOb.js +1 -0
  63. package/dist/chunks/commands-Cr1p7OPH.js +1 -0
  64. package/dist/chunks/{compact-Bj8mdDYN.js → compact-BrJGpEFZ.js} +1 -1
  65. package/dist/chunks/{config-BkbL2e5Q.js → config-BSkuQZNf.js} +1 -1
  66. package/dist/chunks/config-BohF3_IV.js +1 -0
  67. package/dist/chunks/{config-WMxn2jLl.js → config-D78R57VA.js} +1 -1
  68. package/dist/chunks/{context-DB1Ar85E.js → context-DADnwl4t.js} +1 -1
  69. package/dist/chunks/context-noninteractive-BAbzwNxu.js +1 -0
  70. package/dist/chunks/{context-noninteractive-CqnJTDcI.js → context-noninteractive-kACWzgS1.js} +1 -1
  71. package/dist/chunks/{conversation-DOgBzrm0.js → conversation-C8w1DtXk.js} +1 -1
  72. package/dist/chunks/conversation-Ds7zRD0x.js +1 -0
  73. package/dist/chunks/{createSSHSession-Cf2tOgK_.js → createSSHSession-B71Plec6.js} +1 -1
  74. package/dist/chunks/{createSession-DD5YaQKM.js → createSession-BJeDECzt.js} +1 -1
  75. package/dist/chunks/createSession-Bozo4Bu8.js +1 -0
  76. package/dist/chunks/{crossProjectResume-CkiPQYYE.js → crossProjectResume-B1I6YzXr.js} +1 -1
  77. package/dist/chunks/{datadog-DcLf1QpG.js → datadog-C9uqPA6N.js} +1 -1
  78. package/dist/chunks/{diff-dfXWiuLA.js → diff-CzChvQyK.js} +1 -1
  79. package/dist/chunks/{directoryCompletion-BtlRKLzw.js → directoryCompletion-i2oWpaUe.js} +1 -1
  80. package/dist/chunks/doctor-DdvdGkNX.js +1 -0
  81. package/dist/chunks/{entry-wISucmYc.js → entry-BoL8sy1Y.js} +2 -2
  82. package/dist/chunks/{esm-CrJVXrKW.js → esm-DtcV71xh.js} +1 -1
  83. package/dist/chunks/{exit-pjN4EJHV.js → exit-Af27f74w.js} +1 -1
  84. package/dist/chunks/{extraUsage-CwDhpClH.js → extraUsage-DsFwXMAj.js} +1 -1
  85. package/dist/chunks/extractMemories-B1KbTMY0.js +1 -0
  86. package/dist/chunks/{fast-Cuj3bfFm.js → fast-BGU8p2uY.js} +1 -1
  87. package/dist/chunks/fast-CuUjONVV.js +1 -0
  88. package/dist/chunks/{fileSuggestions-Dy2BUZzd.js → fileSuggestions-DU7gmksK.js} +1 -1
  89. package/dist/chunks/{firstPartyEventLogger-D4yuDP-n.js → firstPartyEventLogger-7pAyUdbp.js} +2 -2
  90. package/dist/chunks/firstPartyEventLogger-sMeCTEUW.js +1 -0
  91. package/dist/chunks/{flushGate-B6ecrC4j.js → flushGate-4DfYr-Ru.js} +1 -1
  92. package/dist/chunks/{gemini-BC-BxZmj.js → gemini-Cll4fVQn.js} +1 -1
  93. package/dist/chunks/{generateSessionName-JTR8nPYD.js → generateSessionName-BgGMwpps.js} +1 -1
  94. package/dist/chunks/{githubRepoPathMapping-Bk4FZrng.js → githubRepoPathMapping-Px3_GeD1.js} +1 -1
  95. package/dist/chunks/{goal-B09SOyra.js → goal-D4E2WQVn.js} +1 -1
  96. package/dist/chunks/{grok-BBo3jGfP.js → grok-HF1PHxXb.js} +1 -1
  97. package/dist/chunks/{grove-DsAIY-rZ.js → grove-Bck1zFaD.js} +1 -1
  98. package/dist/chunks/help-DJp61Job.js +1 -0
  99. package/dist/chunks/{hooks-BI4NY5IC.js → hooks-CJ17byYD.js} +7 -7
  100. package/dist/chunks/hooks-CjR3Eq0Z.js +1 -0
  101. package/dist/chunks/{initReplBridge-BYrL6ou1.js → initReplBridge-D09JEKHt.js} +1 -1
  102. package/dist/chunks/install-Dd5fw0cA.js +1 -0
  103. package/dist/chunks/{instrumentation-5cSwEKaF.js → instrumentation-jsPu6qqs.js} +3 -3
  104. package/dist/chunks/{job-rW1mEYtm.js → job-BHhkQbvu.js} +1 -1
  105. package/dist/chunks/{keybindings-B5kUoxvg.js → keybindings-Ch5lzNB8.js} +1 -1
  106. package/dist/chunks/{launchLocalMemory-CPucX8Xj.js → launchLocalMemory-DsaijVcO.js} +1 -1
  107. package/dist/chunks/{launchOnboarding--GCJWeeS.js → launchOnboarding-DHOylaqn.js} +1 -1
  108. package/dist/chunks/loadAgentsDir-8FioUEwX.js +1 -0
  109. package/dist/chunks/{loadAgentsDir-JrGMJN05.js → loadAgentsDir-CwEfQDOw.js} +44 -44
  110. package/dist/chunks/{loadPluginHooks-C4zrlV0u.js → loadPluginHooks-C-Yk5KlI.js} +1 -1
  111. package/dist/chunks/{localSearch-C-stDP9C.js → localSearch-BEnlgSB7.js} +1 -1
  112. package/dist/chunks/localSearch-LcgRjjl3.js +1 -0
  113. package/dist/chunks/{logoV2Utils-J2Sqfube.js → logoV2Utils-DG9GwFjl.js} +1 -1
  114. package/dist/chunks/{magicDocs-Dpe3YhyL.js → magicDocs-qGHR3Cqh.js} +1 -1
  115. package/dist/chunks/{main-C_PDzJdv.js → main-CBVQ8bRm.js} +10 -10
  116. package/dist/chunks/{managedEnv-C8SisyLk.js → managedEnv-3MbOWrVs.js} +1 -1
  117. package/dist/chunks/managedEnv-B4YV3A_y.js +1 -0
  118. package/dist/chunks/{mappers-CMJorgSL.js → mappers-CdY45PDA.js} +1 -1
  119. package/dist/chunks/{mcp-_tBxhPV-.js → mcp-BA8XQ6h1.js} +1 -1
  120. package/dist/chunks/{mcp-SuAh71Ht.js → mcp-DI8pGrqi.js} +1 -1
  121. package/dist/chunks/{mcp-B2mJmWKt.js → mcp-DvY_FibT.js} +3 -3
  122. package/dist/chunks/{memory-DK8bOrUr.js → memory-C2U7CCmM.js} +1 -1
  123. package/dist/chunks/{mode-BhfhEpnW.js → mode-ByV6NqmB.js} +1 -1
  124. package/dist/chunks/{model-BCM7RpVk.js → model-C73ETGu9.js} +1 -1
  125. package/dist/chunks/model-CVG_RRTy.js +1 -0
  126. package/dist/chunks/model-CeG-iOKF.js +1 -0
  127. package/dist/chunks/{modelOptions-DEQat7lU.js → modelOptions-A5jrCUBp.js} +1 -1
  128. package/dist/chunks/{nativeInstaller-xxyUjXbl.js → nativeInstaller-CXFD8LDV.js} +1 -1
  129. package/dist/chunks/{omit-od_CYp5o.js → omit-B65XeX8r.js} +1 -1
  130. package/dist/chunks/{onChangeAppState-CqTb0yEa.js → onChangeAppState-EtUxsgYz.js} +1 -1
  131. package/dist/chunks/{openai-qW8mATAs.js → openai-Dx5mvMjY.js} +1 -1
  132. package/dist/chunks/{partition-CYoWXLNU.js → partition-8vZDG3rY.js} +1 -1
  133. package/dist/chunks/{permissions--iKUbWBw.js → permissions-CJUBfBTr.js} +2 -2
  134. package/dist/chunks/{pidLock-BR4hzYgp.js → pidLock-tjm2n1Nd.js} +2 -2
  135. package/dist/chunks/{plan-DiHCGXhM.js → plan-eFur8bdH.js} +1 -1
  136. package/dist/chunks/{plugin-BeC4D7XF.js → plugin-fYLRLdOY.js} +1 -1
  137. package/dist/chunks/{pluginAutoupdate-Bj-CrFuO.js → pluginAutoupdate-B4w7SSYc.js} +1 -1
  138. package/dist/chunks/{pluginBlocklist-DzOs-RS1.js → pluginBlocklist-CMwb7gmY.js} +1 -1
  139. package/dist/chunks/{pluginCliCommands-DwIGn58t.js → pluginCliCommands-3YCj7Y3Q.js} +1 -1
  140. package/dist/chunks/{pluginFlagging-BzuymJuf.js → pluginFlagging-srvq9H7p.js} +1 -1
  141. package/dist/chunks/{pluginOperations-CP1v-nu0.js → pluginOperations-C7BCR7pw.js} +1 -1
  142. package/dist/chunks/{pluginStartupCheck-BUeBiYVq.js → pluginStartupCheck-BLc0U7W7.js} +1 -1
  143. package/dist/chunks/pluginStartupCheck-nzVDPI1k.js +1 -0
  144. package/dist/chunks/{plugins-D1N31THW.js → plugins-CPtmmDDi.js} +1 -1
  145. package/dist/chunks/poorMode-DD88nPJ4.js +1 -0
  146. package/dist/chunks/{poorMode-D4L_-yWS.js → poorMode-wm2WkPF0.js} +1 -1
  147. package/dist/chunks/{print-DaJi1wF_.js → print-BCud0ukQ.js} +3 -3
  148. package/dist/chunks/{processBashCommand-BGCIqxc9.js → processBashCommand-C9-FonuX.js} +1 -1
  149. package/dist/chunks/{processSlashCommand-qR_j1DE8.js → processSlashCommand-Bi8_1MRC.js} +1 -1
  150. package/dist/chunks/{prompt-DnPppVz8.js → prompt-Bm2EEG4F.js} +1 -1
  151. package/dist/chunks/prompt-CX_v9F3s.js +1 -0
  152. package/dist/chunks/prompt-V0WQJrkO2.js +1 -0
  153. package/dist/chunks/{promptEditor-Cilc9N3L.js → promptEditor-DQ9fpdQD.js} +1 -1
  154. package/dist/chunks/{protocolHandler-DdbiucQa.js → protocolHandler--eQQuSyx.js} +1 -1
  155. package/dist/chunks/{reconciler-Bte4gdP-.js → reconciler-DgQ4y1Vn.js} +1 -1
  156. package/dist/chunks/{refresh-MiZ0acBm.js → refresh-CayVRWUY.js} +1 -1
  157. package/dist/chunks/{registerProtocol-Bpte9dly.js → registerProtocol-DrWIX3Lb.js} +1 -1
  158. package/dist/chunks/{reload-plugins-GdqFZblC.js → reload-plugins-6xcH3dLg.js} +1 -1
  159. package/dist/chunks/{remoteBridgeCore-CAl3_H-O.js → remoteBridgeCore-BnZYGaMH.js} +1 -1
  160. package/dist/chunks/{remoteManagedSettings-BcLJLEr7.js → remoteManagedSettings-CfFmrRze.js} +1 -1
  161. package/dist/chunks/{rename-BDo5qIK0.js → rename-mDtCTbnD.js} +1 -1
  162. package/dist/chunks/{resume-Bbweh2hA.js → resume-DRvz4QFs.js} +1 -1
  163. package/dist/chunks/ripgrep-Di-2j8Ws.js +1 -0
  164. package/dist/chunks/{ripgrep-X5m4gJ-3.js → ripgrep-DsLUmulz.js} +1 -1
  165. package/dist/chunks/{runtimeObserver-CxXxUcrm.js → runtimeObserver-Ba6SM-sI.js} +1 -1
  166. package/dist/chunks/{runtimeObserver-Hjbo43xj.js → runtimeObserver-Dt5sGJVb.js} +2 -2
  167. package/dist/chunks/sandbox-adapter-Cmrd6tBj.js +1 -0
  168. package/dist/chunks/{sandbox-toggle-DmNSThQK.js → sandbox-toggle-DKcw3SbO.js} +1 -1
  169. package/dist/chunks/searchExtraTools-DIgC0CFB.js +1 -0
  170. package/dist/chunks/{session-CkuTMD_4.js → session-COVyD8UU.js} +1 -1
  171. package/dist/chunks/sessionFileAccessHooks-yAPDTrbm.js +1 -0
  172. package/dist/chunks/sessionObserver-BizdPx8P.js +1 -0
  173. package/dist/chunks/{sessionObserver-CvQ6oyoj.js → sessionObserver-iAgSetlC.js} +1 -1
  174. package/dist/chunks/{sessionState-C2REgUrs.js → sessionState-zhvcDpb2.js} +1 -1
  175. package/dist/chunks/sessionStorage-LMY409Ji.js +1 -0
  176. package/dist/chunks/{sessionTitle-2IWcNB8H.js → sessionTitle-QPRly1tZ.js} +1 -1
  177. package/dist/chunks/{sessionTracing-Bm7hQKHA.js → sessionTracing-C4uqAdud.js} +1 -1
  178. package/dist/chunks/settings-BgHApyGL.js +1 -0
  179. package/dist/chunks/{settings-aUygByiZ.js → settings-CvhsRFaT.js} +1 -1
  180. package/dist/chunks/{settingsSync-DgzCU1BZ.js → settingsSync-BGo6dHJo.js} +1 -1
  181. package/dist/chunks/{setup-CvaG4nl5.js → setup-Bjw5VS6x.js} +2 -2
  182. package/dist/chunks/{shadowedRuleDetection-CWCQ5dZ0.js → shadowedRuleDetection-CzRAzcC1.js} +1 -1
  183. package/dist/chunks/{sideQuestion-BoW-xYkh.js → sideQuestion-oIYrx5ar.js} +1 -1
  184. package/dist/chunks/{sinks-ZHKfs6gv.js → sinks-Bje3hCkR.js} +1 -1
  185. package/dist/chunks/sinks-FaljTZ-c.js +1 -0
  186. package/dist/chunks/{skillChangeDetector-C-HWR_8v.js → skillChangeDetector-v6mAYzXX.js} +1 -1
  187. package/dist/chunks/{skillGapStore-CCNeSjIb.js → skillGapStore-CJjt3IW7.js} +2 -2
  188. package/dist/chunks/{skillLifecycle-wU4JDNYQ.js → skillLifecycle-BsgH84vl.js} +2 -2
  189. package/dist/chunks/{skillSearchPanel-Cxr1QQn4.js → skillSearchPanel-CneXymsb.js} +2 -2
  190. package/dist/chunks/{skills-BghnKnNo.js → skills-DZRBy7vT.js} +1 -1
  191. package/dist/chunks/{stats-unp6R0Ah.js → stats-Dq-5qizS.js} +1 -1
  192. package/dist/chunks/{status-BraYBx4N.js → status-BP_R8051.js} +1 -1
  193. package/dist/chunks/status-CZYD3NGb.js +1 -0
  194. package/dist/chunks/{statusNoticeHelpers-Dm1aiibR.js → statusNoticeHelpers-ODrnrLAZ.js} +1 -1
  195. package/dist/chunks/{switcher-BUNSEJ-7.js → switcher-BkGOeIzI.js} +1 -1
  196. package/dist/chunks/switcher-DwKN9daN.js +1 -0
  197. package/dist/chunks/{syncCache-1s9xV8WV.js → syncCache-CpmpvjfC.js} +1 -1
  198. package/dist/chunks/{tasks-BjFot03S.js → tasks-CIUuwrX4.js} +1 -1
  199. package/dist/chunks/{teleport-Dj2Kvbmx.js → teleport-IzyDplC7.js} +1 -1
  200. package/dist/chunks/{templateJobs-CY7GNRo5.js → templateJobs-De57J461.js} +1 -1
  201. package/dist/chunks/{terminalSetup-Ty8T8ePM.js → terminalSetup-DDvQ0K5e.js} +1 -1
  202. package/dist/chunks/{terminalSetup-CpMNk6dc.js → terminalSetup-JJiXmszo.js} +1 -1
  203. package/dist/chunks/{theme-c6grxWNn.js → theme-Nwii7354.js} +1 -1
  204. package/dist/chunks/{toolEventObserver-D7WbjgFR.js → toolEventObserver-Cq-uBb0-.js} +1 -1
  205. package/dist/chunks/{toolPool-O5nkEFb1.js → toolPool-BBU4ll_p.js} +1 -1
  206. package/dist/chunks/trustedDevice-BKzkA7fq.js +1 -0
  207. package/dist/chunks/{trustedDevice-BF78PNK8.js → trustedDevice-DWZxDUxS.js} +1 -1
  208. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-qLfN0tc-.js → useExitOnCtrlCDWithKeybindings-D48aDPG9.js} +1 -1
  209. package/dist/chunks/useMainLoopModel-89eUU13X.js +1 -0
  210. package/dist/chunks/{useManagePlugins-E0Qzj-ws.js → useManagePlugins-EqoQELMT.js} +1 -1
  211. package/dist/chunks/{useMergedTools-B7iYaNwM.js → useMergedTools-BJ4L9QSK.js} +1 -1
  212. package/dist/chunks/{useSearchInput-CsxiM9i0.js → useSearchInput-DkVER3cm.js} +1 -1
  213. package/dist/chunks/{useSettingsErrors-DdVTahNa.js → useSettingsErrors-D3MlQ1GF.js} +1 -1
  214. package/dist/chunks/{userAgent-BggRZ-ZE.js → userAgent-aoe_xVAb.js} +1 -1
  215. package/dist/chunks/{util-Xdy1nOjj.js → util-g-5UX5gH.js} +1 -1
  216. package/dist/chunks/{validatePlugin-Be5aSSnP.js → validatePlugin-CSE8zjZn.js} +1 -1
  217. package/dist/chunks/{vim-cFcxfuac.js → vim-s-wmybpU.js} +1 -1
  218. package/dist/chunks/{workerRegistry-GrD7IAVQ.js → workerRegistry-DGwy0YHB.js} +2 -2
  219. package/dist/chunks/worktree-jjuORs7p.js +1 -0
  220. package/dist/cli.js +1 -1
  221. package/package.json +1 -1
  222. package/dist/chunks/AddWorkspaceDirectory-m2d3nOQJ.js +0 -1
  223. package/dist/chunks/AgentsMdExternalIncludesDialog-BRXGkHO4.js +0 -1
  224. package/dist/chunks/ApproveApiKey-NXTWIAMj.js +0 -1
  225. package/dist/chunks/BypassPermissionsModeDialog-C4QGpcBT.js +0 -1
  226. package/dist/chunks/Doctor-DmiDH-lg.js +0 -1
  227. package/dist/chunks/Grove-BhhnrFX9.js +0 -11
  228. package/dist/chunks/MCPToolListView-Ddmu2UcL.js +0 -1
  229. package/dist/chunks/REPL-DkPd3vk5.js +0 -1
  230. package/dist/chunks/RemoteSessionManager-DJhrR1dz.js +0 -2
  231. package/dist/chunks/SearchExtraToolsTool-DupzA6Vm.js +0 -1
  232. package/dist/chunks/TeleportResumeWrapper-DnHTI39O.js +0 -1
  233. package/dist/chunks/agents-BYQO6DbG.js +0 -101
  234. package/dist/chunks/api-j0iE1mkR.js +0 -1
  235. package/dist/chunks/auth-C9FUZzpW.js +0 -1
  236. package/dist/chunks/auth-DwPrlTHv.js +0 -1
  237. package/dist/chunks/backgroundHousekeeping-BxcVB3By.js +0 -1
  238. package/dist/chunks/bridgeConfig-Bxs5dqjH.js +0 -1
  239. package/dist/chunks/bridgeStatusUtil-BQF0AJDO.js +0 -1
  240. package/dist/chunks/caches-C9--b9a7.js +0 -1
  241. package/dist/chunks/claudeDesktop-DPIJpc1V.js +0 -1
  242. package/dist/chunks/client-Dr9AYB-r.js +0 -1
  243. package/dist/chunks/commands-DTB0Qzd5.js +0 -1
  244. package/dist/chunks/config-B1kYcRIP.js +0 -1
  245. package/dist/chunks/context-noninteractive-Bno2Xsmp.js +0 -1
  246. package/dist/chunks/conversation-hNXWaswI.js +0 -1
  247. package/dist/chunks/createSession-BZx-2UIB.js +0 -1
  248. package/dist/chunks/doctor-aKE2bG5C.js +0 -1
  249. package/dist/chunks/extractMemories-WmPLOLUT.js +0 -1
  250. package/dist/chunks/fast-BVABmasw.js +0 -1
  251. package/dist/chunks/firstPartyEventLogger-CabA8fu0.js +0 -1
  252. package/dist/chunks/help-CELr6oJZ.js +0 -1
  253. package/dist/chunks/hooks-9rkDD2iw.js +0 -1
  254. package/dist/chunks/install-Dn3_M1Ui.js +0 -1
  255. package/dist/chunks/loadAgentsDir-D-a1uUb5.js +0 -1
  256. package/dist/chunks/localSearch-hOERAH9v.js +0 -1
  257. package/dist/chunks/managedEnv-AEhH_HUs.js +0 -1
  258. package/dist/chunks/model-BWR43D3c.js +0 -1
  259. package/dist/chunks/model-CmDF8O9G.js +0 -1
  260. package/dist/chunks/pluginStartupCheck-BGN6Je6d.js +0 -1
  261. package/dist/chunks/poorMode-XDBnxTiF.js +0 -1
  262. package/dist/chunks/prompt-B0gADAvI.js +0 -1
  263. package/dist/chunks/prompt-DqyEtC_I2.js +0 -1
  264. package/dist/chunks/ripgrep-DrpZ79Pp.js +0 -1
  265. package/dist/chunks/sandbox-adapter-DQ_fJSIo.js +0 -1
  266. package/dist/chunks/searchExtraTools-C7b2x2p_.js +0 -1
  267. package/dist/chunks/sessionFileAccessHooks-CQvGAbvL.js +0 -1
  268. package/dist/chunks/sessionObserver-BoQY7nOa.js +0 -1
  269. package/dist/chunks/sessionStorage-BeaEgnaa.js +0 -1
  270. package/dist/chunks/settings-Da6ax5aI.js +0 -1
  271. package/dist/chunks/sinks-B_ehGpvp.js +0 -1
  272. package/dist/chunks/status-DwyWiaVc.js +0 -1
  273. package/dist/chunks/switcher-DDUnWU_4.js +0 -1
  274. package/dist/chunks/trustedDevice-D_z7bAQh.js +0 -1
  275. package/dist/chunks/updateCCB-ts7Joyve.js +0 -5
  276. package/dist/chunks/useMainLoopModel-DkjG_ikT.js +0 -1
  277. package/dist/chunks/worktree-V7xiUAtl.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,i as p,l as m,o as h,p as g,r as _,s as v,u as y}from"./envUtils-DcaKZlRU.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,G as ve,Gr as ye,Gt as be,H as xe,Hr as Se,I as P,Kr as Ce,Lr as we,Lt as Te,Mr as Ee,P as F,Pr as De,Pt as Oe,Qr as ke,Rn as Ae,T as je,Tt as Me,Vr as Ne,Vt as Pe,Wt as Fe,Xn as Ie,Yt as Le,Zt as eee,_ as Re,ai as ze,bn as Be,cr as Ve,d as He,di as Ue,et as We,fi as Ge,fr as Ke,gr as qe,gt as tee,hn as Je,hr as nee,j as ree,l as iee,ln as aee,mi as oee,mr as see,mt as Ye,nt as cee,or as lee,ot as Xe,pi as uee,pr as dee,qr as Ze,rn as fee,sn as Qe,sr as pee,t as I,ui as mee,vn as hee,xr as gee,y as $e,yn as _ee,yr as vee,zr as yee}from"./src-DL3w8VPk2.js";import{i as bee,r as xee}from"./isSymbol-BO6cdPI7.js";import{t as et}from"./jsx-runtime-Bb4Xn-E0.js";import{A as L,B as See,C as R,D as tt,H as Cee,I as wee,M as nt,N as Tee,O as rt,R as Eee,T as it,U as Dee,a as at,b as ot,f as st,g as ct,h as Oee,j as lt,k as ut,l as dt,m as ft,p as z,s as kee,u as Aee,v as jee,w as B,x as pt}from"./external-CEp-aPkt.js";import{i as mt,n as ht,r as gt,t as _t}from"./lazySchema-B4D4qJVE.js";import{$t as vt,Ai as Mee,At as yt,B as bt,Bn as Nee,Br as xt,Bt as Pee,C as Fee,Cr as St,Ct as Iee,D as Lee,Dn as Ct,Dt as Ree,E as zee,En as wt,Et as Tt,Fr as Bee,Ft as Vee,G as Hee,Gr as Et,Gt as Dt,H as Ot,Hn as Uee,Hr as Wee,Ht as Gee,I as kt,It as Kee,Jt as qee,K as At,Kr as Jee,Kt as jt,L as Yee,Ln as Mt,Lt as Xee,Mi as Zee,Mr as Nt,Mt as Qee,Ni as $ee,Nr as Pt,Nt as ete,O as Ft,Oi as tte,On as It,Ot as Lt,Pr as nte,Q as Rt,R as zt,Rn as Bt,Rr as Vt,Rt as rte,S as ite,Sr as Ht,St as ate,T as ote,Ti as ste,Tt as cte,U as lte,Un as ute,Ur as dte,Ut as fte,V as pte,Vn as mte,Vr as hte,Wn as gte,Wr as Ut,Wt,Xt as _te,Y as vte,Yt as yte,_ as bte,_i as xte,_n as Gt,_r as Kt,_t as qt,a as Ste,ai as Cte,an as wte,at as Tte,bi as Jt,br as Ete,bt as Dte,c as Ote,ci as kte,cn as Ate,cr as jte,ct as Mte,d as Nte,dn as Pte,dr as Fte,dt as Yt,et as Xt,f as Ite,fi as Lte,g as Rte,gi as zte,gr as Zt,h as Qt,ht as $t,i as Bte,ii as Vte,it as en,j as Hte,ji as Ute,jt as tn,ki as Wte,kn as Gte,kt as nn,li as Kte,lr as rn,lt as an,m as qte,mn as Jte,mr as Yte,n as Xte,ni as Zte,nt as on,o as Qte,or as $te,ot as ene,p as tne,pi as nne,pt as sn,qr as rne,qt as cn,r as ine,ri as ln,rt as un,s as ane,st as one,t as sne,tr as cne,u as dn,un as lne,ur as fn,ut as pn,vt as une,w as dne,wi as fne,wt as pne,x as mne,xi as mn,xt as hn,yt as hne,z as gn,zr as _n,zt as gne}from"./state-BPFYBqm1.js";import{i as _ne,n as vn,r as vne,t as yn}from"./cwd-Besi3Os3.js";import{$ as yne,A as bn,B as xn,C as V,D as bne,E as Sn,F as Cn,I as xne,J as wn,L as Tn,M as En,N as Sne,O as Dn,P as H,Q as Cne,R as On,S as kn,T as An,U as jn,V as Mn,W as Nn,X as Pn,Y as Fn,Z as In,_ as Ln,a as Rn,c as U,d as zn,f as Bn,g as Vn,h as wne,i as W,j as Hn,k as Un,m as Wn,nt as Gn,p as Kn,q as Tne,rt as Ene,s as qn,t as Dne,tt as Jn,u as G,v as One,x as Yn,y as kne,z as Ane}from"./debug-BQj6h99Q.js";import{$ as Xn,$t as jne,A as Mne,An as Nne,Ar as Pne,At as Fne,B as Zn,Bn as Qn,Bt as $n,C as Ine,Cn as er,Cr as tr,Ct as nr,D as Lne,Dn as Rne,Dr as zne,Dt as rr,E as Bne,Er as ir,Et as Vne,F as ar,Ft as Hne,G as Une,H as or,Ht as sr,I as cr,In as lr,J as ur,Jn as dr,Jt as Wne,K as fr,Kt as pr,L as mr,Ln as hr,Mn as Gne,Mt as gr,N as Kne,Nn as qne,On as _r,Or as Jne,Ot as vr,P as yr,Pn as br,Q as xr,Qt as Sr,R as Yne,Rn as Cr,Rt as Xne,Sn as wr,Sr as Zne,St as Qne,T as $ne,Tn as ere,Tr,U as tre,V as Er,Vt as nre,W as rre,Wt as Dr,X as ire,Xn as Or,Xt as kr,Y as are,Yn as ore,Yt as Ar,Z as sre,Zt as jr,_n as Mr,_t as Nr,ar as Pr,at as Fr,bn as cre,br as lre,bt as ure,c as Ir,cr as Lr,ct as dre,dr as fre,dt as Rr,en as pre,f as zr,fn as mre,fr as hre,ft as Br,g as Vr,gn as gre,gr as _re,h as vre,hn as yre,hr as bre,ht as Hr,in as xre,ir as Sre,it as Ur,j as Cre,jt as Wr,kn as Gr,kr as wre,kt as Tre,l as Kr,ln as qr,lr as Ere,lt as Jr,m as Dre,mn as Yr,mr as Ore,mt as kre,n as Xr,nn as Zr,nr as Are,nt as jre,o as Mre,on as Nre,or as Qr,ot as $r,p as Pre,pn as Fre,pr as Ire,pt as Lre,q as ei,rn as Rre,rr as zre,rt as Bre,s as ti,sn as Vre,sr as ni,st as ri,t as Hre,tn as Ure,tr as Wre,u as Gre,un as ii,ur as ai,ut as oi,v as Kre,vn as qre,vt as si,w as Jre,wn as ci,wr as Yre,x as li,xn as ui,xr as Xre,yn as Zre,yr as Qre,yt as di,z as fi,zn as $re}from"./settings-aUygByiZ.js";import{A as pi,C as mi,F as eie,I as tie,L as nie,M as hi,N as gi,O as rie,P as _i,R as iie,S as vi,c as yi,d as aie,h as bi,j as oie,k as xi,l as sie,m as cie,n as lie,o as Si,u as Ci,v as wi,y as Ti,z as uie}from"./config-BkbL2e5Q.js";import{A as die,C as fie,D as pie,E as mie,O as Ei,S as Di,T as hie,_ as gie,a as Oi,b as _ie,c as vie,h as yie,i as ki,k as Ai,l as ji,m as Mi,n as Ni,o as bie,p as Pi,r as Fi,w as xie,x as Sie,y as Cie}from"./git-DplvjXEY.js";import{c as Ii,i as wie,l as Tie,n as Li,o as Ri,r as zi,t as Bi}from"./execFileNoThrow-DYm1GeGn.js";import{A as Eie,B as Vi,C as Die,F as Oie,G as kie,H as Aie,I as Hi,K as jie,L as Ui,N as Mie,P as Wi,R as Gi,T as Ki,U as qi,V as Ji,W as Nie,_ as Pie,c as K,d as Fie,f as Iie,j as Lie,k as Yi,l as Xi,m as Rie,n as Zi,o as Qi,q as $i,s as q,w as ea,z as ta}from"./log-BlJ7CcKG.js";import{i as na,n as zie,r as Bie,t as Vie}from"./hash-Tu-My5Vp.js";import{a as ra,i as ia,n as aa,t as oa}from"./memoize-_2f7NWDv.js";import{n as sa,t as ca}from"./which-BR8YVCCW.js";import{i as la,o as ua}from"./platform-DVeTi9mp.js";import{a as da,i as fa,s as pa,t as Hie}from"./windowsPaths-BmXyrasP.js";import{_ as Uie,a as ma,c as ha,d as Wie,f as Gie,g as Kie,h as qie,i as Jie,l as ga,m as _a,o as va,r as Yie,s as ya,t as ba,u as Xie}from"./sessionStoragePortable-x0Yn02-G.js";import{a as xa,c as Sa,n as Zie,r as Ca,s as wa,t as Ta,u as Ea}from"./types-BomO8WUz.js";import{n as Da,r as J}from"./analytics-DJobLaWP.js";import{a as Qie,n as Oa,o as ka,t as $ie}from"./intl-D2kgJmX7.js";import{C as Aa,a as ja,b as Ma,c as Na,f as Pa,g as Fa,h as Ia,i as eae,l as La,n as tae,o as nae,s as Ra,u as za,v as Ba,w as rae}from"./startupProfiler-2sjXZkIP.js";import{l as Va,o as iae,s as aae,u as Ha}from"./oauth-D38aRTUb.js";import{n as oae,r as sae,t as Ua}from"./bundledMode--fG1S62b.js";import{a as Wa,c as Ga,i as Ka,l as qa,n as cae,o as Ja,r as Ya,s as Xa,t as Za,u as Qa}from"./stringUtils-BjnclTLB.js";import{$ as lae,$r as $a,An as eo,B as to,Bt as no,C as ro,Cn as io,Cr as ao,D as uae,Dt as dae,F as oo,Fn as so,Ft as co,G as fae,Gr as lo,Gt as uo,Hn as pae,In as fo,It as po,Jr as mae,Jt as mo,Kn as ho,Kr as go,Ln as hae,M as gae,Mn as _ae,N as vae,Nn as yae,Nr as _o,Nt as bae,On as xae,Ot as vo,P as Sae,Pn as yo,Pr as bo,Q as Cae,Qn as xo,Qr as wae,Rn as Tae,S as So,Sn as Co,Sr as wo,St as To,T as Eo,Tn as Eae,Un as Do,V as Oo,Vn as ko,W as Ao,Wn as Dae,Xr as Oae,Yr as kae,Zn as jo,Zr as Mo,_ as No,_n as Po,_t as Aae,ai as Fo,ar as Io,c as jae,d as Mae,dr as Nae,dt as Pae,ei as Fae,er as Lo,et as Ro,fr as Iae,g as Lae,gn as Rae,gt as zae,h as zo,hn as Bae,hr as Bo,ii as Vo,ir as Ho,it as Vae,jn as Uo,jt as Hae,kn as Uae,l as Wo,lr as Wae,m as Go,mr as Gae,mt as Ko,ni as Kae,nn as qae,nr as Jae,nt as qo,oi as Jo,or as Yae,pr as Xae,qn as Zae,qr as Qae,r as Yo,rt as Xo,s as $ae,si as Zo,sr as eoe,ti as toe,tt as noe,u as Qo,ur as roe,vn as $o,vr as ioe,vt as aoe,wn as ooe,xt as soe,y as es,yr as coe,zn as loe}from"./model-CmDF8O9G.js";import{$ as ts,$t as uoe,A as doe,At as foe,B as poe,Bt as ns,Ct as moe,Dt as hoe,Et as rs,Ft as goe,G as _oe,Gt as is,H as voe,Ht as as,I as yoe,It as boe,J as xoe,Jt as os,K as Soe,Kt as ss,Lt as Coe,Mt as woe,N as Toe,Nt as cs,O as Eoe,Ot as ls,P as Doe,Pt as Ooe,Q as koe,Qt as Aoe,R as joe,Rt as us,S as Moe,St as ds,T as Noe,Tt as fs,U as Poe,Ut as ps,Vt as ms,W as Foe,Wt as hs,X as Ioe,Xt as gs,Y as Loe,Yt as Roe,Z as zoe,Zt as Boe,_ as Voe,_n as _s,_t as vs,a as ys,an as bs,at as xs,b as Hoe,bn as Ss,bt as Uoe,c as Cs,cn as Woe,d as Goe,dn as ws,dt as Koe,en as qoe,et as Joe,f as Ts,fn as Yoe,ft as Xoe,g as Es,gn as Ds,gt as Zoe,h as Qoe,hn as Os,ht as ks,i as As,in as js,jt as $oe,k as ese,kt as Ms,l as tse,ln as nse,lt as rse,m as ise,mn as Ns,mt as Ps,n as ase,nn as Fs,nt as Is,o as ose,on as sse,p as cse,pt as Ls,q as lse,qt as Rs,r as zs,rn as use,rt as dse,s as fse,sn as Bs,st as Vs,t as pse,tn as mse,tt as Hs,u as hse,ut as gse,vn as _se,vt as vse,w as yse,wt as Us,xn as Ws,xt as Gs,yn as Ks,yt as qs,z as bse,zt as Js}from"./prompt-DnPppVz8.js";import{a as Ys,c as xse,h as Sse,l as Xs,m as Cse,o as wse,s as Tse,u as Ese}from"./proxy-C0j74LqT.js";import{n as Dse,t as Ose}from"./userAgent-BggRZ-ZE.js";import{i as kse,m as Ase,o as jse,p as Mse}from"./terminalSetup-CpMNk6dc.js";import{B as Nse,C as Pse,N as Zs,O as Fse,P as Ise,Q as Qs,S as $s,T as ec,Y as Lse,Z as Rse,at as tc,b as nc,bt as zse,d as Bse,et as rc,h as Vse,k as Hse,m as Use,n as Wse,p as Gse,q as Kse,r as qse,st as ic,u as ac,ut as Jse,v as oc,vt as Yse,y as sc,yt as Xse,z as Zse}from"./sessionState-C2REgUrs.js";import{a as Qse,i as $se,n as ece,o as tce,t as nce}from"./break-cache-Cd1yQ-0h.js";import{a as rce,i as ice,l as cc,n as ace,o as lc,r as oce,s as sce,t as cce}from"./localSearch-C-stDP9C.js";import{a as uc,i as dc,n as fc,o as lce,r as pc,t as uce}from"./shellQuote-D3Ocv_U-.js";import{a as mc,c as hc,n as dce,s as gc}from"./ripgrep-X5m4gJ-3.js";import{a as fce,i as pce,n as mce,r as hce}from"./client-B7WkO81L.js";import{r as _c,t as gce}from"./store-Z8rTjDHe.js";import{a as _ce,n as vce,o as vc,s as yce,t as bce}from"./switcher-BUNSEJ-7.js";import{a as yc,i as bc,n as xce}from"./genericProcessUtils-Bbcbi11g.js";import{$ as Sce,J as Cce,Q as xc,X as wce,Y as Tce,at as Ece,ct as Sc,et as Cc,ft as Dce,lt as wc,nt as Tc,ot as Ec,rt as Dc,st as Oce,tt as kce,ut as Oc}from"./esm-CrJVXrKW.js";import{r as kc,t as Ac}from"./subprocessEnv-CNBOhlDV.js";import{n as Ace,t as jce}from"./sessionIdCompat-Dgp6PW_1.js";import{a as Mce,o as Nce,r as jc,s as Pce,t as Fce}from"./parser-a2S_eFyE.js";import{C as Mc,S as Ice,T as Nc,a as Lce,b as Rce,c as Pc,f as zce,g as Bce,h as Vce,i as Hce,m as Uce,n as Wce,o as Gce,p as Kce,s as Fc,t as qce,u as Jce,v as Yce,w as Ic,x as Xce,y as Zce}from"./sessionTracing-Bm7hQKHA.js";import{n as Qce,r as $ce,t as Lc}from"./poorMode-D4L_-yWS.js";import{a as ele,i as Rc,o as tle,r as zc}from"./detectRepository-Qy3zKoyn.js";import{a as Bc,i as nle,o as Vc,r as Hc}from"./api-C5I2xwgd.js";import{f as rle,n as ile,p as ale,s as ole}from"./firstPartyEventLogger-D4yuDP-n.js";import{n as sle,t as cle}from"./datadog-DcLf1QpG.js";import{i as lle,t as ule}from"./src-l6_O0K-a.js";import{n as dle,t as fle}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as ple,t as mle}from"./featureCheck-D6FjD-nt.js";import*as hle from"os";import{homedir as Uc,platform as gle,release as _le,tmpdir as Wc,type as vle,version as yle}from"os";import*as Gc from"path";import{basename as Kc,delimiter as ble,dirname as qc,extname as Jc,isAbsolute as Yc,join as Y,normalize as Xc,parse as Zc,posix as Qc,relative as $c,resolve as el,sep as tl,win32 as nl}from"path";import rl from"node:process";import*as il from"node:path";import al,{basename as xle,dirname as Sle,isAbsolute as Cle,join as ol,relative as sl,resolve as cl,sep as wle}from"node:path";import*as ll from"fs";import{accessSync as Tle,closeSync as Ele,constants as ul,createReadStream as Dle,existsSync as Ole,fstat as kle,fstatSync as Ale,mkdirSync as jle,openSync as Mle,readFileSync as dl,readSync as Nle,readdirSync as Ple,rm as Fle,rmSync as Ile,statSync as Lle,unlinkSync as Rle,watch as zle,writeFileSync as Ble,writeSync as fl}from"fs";import{execSync as Vle,spawn as Hle,spawnSync as Ule}from"node:child_process";import*as pl from"node:fs";import{closeSync as Wle,existsSync as ml,mkdirSync as Gle,openSync as Kle,readFileSync as qle,readSync as Jle,readdirSync as hl,renameSync as Yle,rmSync as Xle,stat as Zle,statSync as Qle,unlinkSync as $le,unwatchFile as eue,watch as tue,watchFile as nue,writeFileSync as rue}from"node:fs";import{EOL as gl,homedir as iue,tmpdir as _l,type as aue}from"node:os";import{createHash as oue,randomBytes as sue,randomUUID as cue}from"node:crypto";import{createHash as vl,randomBytes as yl,randomUUID as bl}from"crypto";import*as xl from"fs/promises";import{access as lue,appendFile as Sl,chmod as Cl,copyFile as wl,link as Tl,lstat as uue,mkdir as El,open as Dl,readFile as Ol,readdir as kl,readlink as due,realpath as Al,rename as jl,rm as Ml,rmdir as fue,stat as Nl,symlink as Pl,truncate as pue,unlink as Fl,utimes as mue,writeFile as Il}from"fs/promises";import{isDeepStrictEqual as hue}from"util";import{execFile as gue,execFileSync as Ll,spawn as Rl,spawnSync as zl}from"child_process";import{createServer as Bl}from"http";import{fileURLToPath as _ue,parse as vue,pathToFileURL as Vl}from"url";import yue,{createConnection as bue,isIP as xue}from"net";import{EventEmitter as Sue}from"node:events";import{setMaxListeners as Cue}from"events";import{PassThrough as wue,Readable as Tue}from"node:stream";import{lstat as Hl,mkdir as Eue,open as Due,readFile as Ul,readdir as Wl,realpath as Gl,rename as Oue,rm as kue,stat as Kl,writeFile as Aue}from"node:fs/promises";import{request as jue}from"node:https";import{Agent as Mue,createServer as Nue,request as ql}from"node:http";import{lookup as Pue}from"dns";import{URL as Jl,fileURLToPath as Fue}from"node:url";import{BlockList as Iue,connect as Yl,isIP as Xl}from"node:net";import{connect as Lue}from"node:tls";import{text as Rue}from"node:stream/consumers";import{join as Zl}from"path/posix";async function zue(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};i&&(i.aborted&&y(i.reason),i.addEventListener(`abort`,g,{once:!0}));let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==Ql&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===Ql&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var Ql,Bue=n((()=>{Ql=Symbol(`skip`)}));function Vue(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return Hue.has(t)}var Hue,Uue=n((()=>{Hue=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 Wue(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var Gue=n((()=>{}));function Kue(e,t){return e&&Tr(t,Et(t),e)}var que=n((()=>{ir(),Ut()}));function Jue(e,t){return e&&Tr(t,Yre(t),e)}var Yue=n((()=>{ir(),tr()}));function Xue(e,t){return Tr(e,Lte(e),t)}var Zue=n((()=>{ir(),nne()}));function Que(e,t){return Tr(e,iie(e),t)}var $ue=n((()=>{ir(),uie()}));function ede(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&tde.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var tde,nde=n((()=>{tde=Object.prototype.hasOwnProperty}));function rde(e,t){var n=t?bre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var ide=n((()=>{_re()}));function ade(e){var t=new e.constructor(e.source,ode.exec(e));return t.lastIndex=e.lastIndex,t}var ode,sde=n((()=>{ode=/\w*$/}));function cde(e){return eu?Object(eu.call(e)):{}}var $l,eu,lde=n((()=>{c(),$l=o?o.prototype:void 0,eu=$l?$l.valueOf:void 0}));function ude(e,t,n){var r=e.constructor;switch(t){case yde:return bre(e);case dde:case fde:return new r(+e);case bde:return rde(e,n);case xde:case Sde:case Cde:case wde:case Tde:case Ede:case Dde:case Ode:case kde:return Ire(e,n);case pde:return new r;case mde:case _de:return new r(e);case hde:return ade(e);case gde:return new r;case vde:return cde(e)}}var dde,fde,pde,mde,hde,gde,_de,vde,yde,bde,xde,Sde,Cde,wde,Tde,Ede,Dde,Ode,kde,Ade=n((()=>{_re(),ide(),sde(),lde(),Ore(),dde=`[object Boolean]`,fde=`[object Date]`,pde=`[object Map]`,mde=`[object Number]`,hde=`[object RegExp]`,gde=`[object Set]`,_de=`[object String]`,vde=`[object Symbol]`,yde=`[object ArrayBuffer]`,bde=`[object DataView]`,xde=`[object Float32Array]`,Sde=`[object Float64Array]`,Cde=`[object Int8Array]`,wde=`[object Int16Array]`,Tde=`[object Int32Array]`,Ede=`[object Uint8Array]`,Dde=`[object Uint8ClampedArray]`,Ode=`[object Uint16Array]`,kde=`[object Uint32Array]`}));function jde(e){return bee(e)&&Vt(e)==Mde}var Mde,Nde=n((()=>{_n(),xee(),Mde=`[object Map]`})),tu,Pde,Fde=n((()=>{Nde(),Cte(),Zte(),tu=ln&&ln.isMap,Pde=tu?Vte(tu):jde}));function Ide(e){return bee(e)&&Vt(e)==Lde}var Lde,Rde=n((()=>{_n(),xee(),Lde=`[object Set]`})),nu,zde,Bde=n((()=>{Rde(),Cte(),Zte(),nu=ln&&ln.isSet,zde=nu?Vte(nu):Ide}));function ru(e,t,n,r,i,a){var o,c=t&Vde,l=t&Hde,u=t&Ude;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=mn(e);if(d){if(o=ede(e),!c)return Qre(e,o)}else{var f=Vt(e),p=f==au||f==Jde;if(Kte(e))return Xre(e,c);if(f==ou||f==iu||p&&!i){if(o=l||p?{}:fre(e),!c)return l?Que(e,Jue(o,e)):Xue(e,Kue(o,e))}else{if(!su[f])return i?e:{};o=ude(e,f,c)}}a||(a=new Zee);var m=a.get(e);if(m)return m;a.set(e,o),zde(e)?e.forEach(function(r){o.add(ru(r,t,n,r,e,a))}):Pde(e)&&e.forEach(function(r,i){o.set(i,ru(r,t,n,i,e,a))});var h=d?void 0:(u?l?tie:Wee:l?Yre:Et)(e);return Wue(h||e,function(r,i){h&&(i=r,r=e[i]),zne(o,i,ru(r,t,n,i,e,a))}),o}var Vde,Hde,Ude,iu,Wde,Gde,Kde,qde,au,Jde,Yde,Xde,ou,Zde,Qde,$de,efe,tfe,nfe,rfe,ife,afe,ofe,sfe,cfe,lfe,ufe,dfe,ffe,su,cu=n((()=>{$ee(),Gue(),Jne(),que(),Yue(),Zne(),lre(),Zue(),$ue(),dte(),nie(),_n(),nde(),Ade(),hre(),Jt(),kte(),Fde(),l(),Bde(),Ut(),tr(),Vde=1,Hde=2,Ude=4,iu=`[object Arguments]`,Wde=`[object Array]`,Gde=`[object Boolean]`,Kde=`[object Date]`,qde=`[object Error]`,au=`[object Function]`,Jde=`[object GeneratorFunction]`,Yde=`[object Map]`,Xde=`[object Number]`,ou=`[object Object]`,Zde=`[object RegExp]`,Qde=`[object Set]`,$de=`[object String]`,efe=`[object Symbol]`,tfe=`[object WeakMap]`,nfe=`[object ArrayBuffer]`,rfe=`[object DataView]`,ife=`[object Float32Array]`,afe=`[object Float64Array]`,ofe=`[object Int8Array]`,sfe=`[object Int16Array]`,cfe=`[object Int32Array]`,lfe=`[object Uint8Array]`,ufe=`[object Uint8ClampedArray]`,dfe=`[object Uint16Array]`,ffe=`[object Uint32Array]`,su={},su[iu]=su[Wde]=su[nfe]=su[rfe]=su[Gde]=su[Kde]=su[ife]=su[afe]=su[ofe]=su[sfe]=su[cfe]=su[Yde]=su[Xde]=su[ou]=su[Zde]=su[Qde]=su[$de]=su[efe]=su[lfe]=su[ufe]=su[dfe]=su[ffe]=!0,su[qde]=su[au]=su[tfe]=!1}));function pfe(e){return ru(e,mfe|hfe)}var mfe,hfe,gfe=n((()=>{cu(),mfe=1,hfe=4}));function lu(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 _fe=n((()=>{})),uu=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})),du=a((e=>{var t=uu(),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})),vfe=a((e=>{var t=uu(),n=du(),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,i as p,l as m,o as h,p as g,r as _,s as v,u as y}from"./envUtils-DcaKZlRU.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,G as ve,Gr as ye,Gt as be,H as xe,Hr as Se,I as P,Kr as Ce,Lr as we,Lt as Te,Mr as Ee,P as F,Pr as De,Pt as Oe,Qr as ke,Rn as Ae,T as je,Tt as Me,Vr as Ne,Vt as Pe,Wt as Fe,Xn as Ie,Yt as Le,Zt as eee,_ as Re,ai as ze,bn as Be,cr as Ve,d as He,di as Ue,et as We,fi as Ge,fr as Ke,gr as qe,gt as tee,hn as Je,hr as nee,j as ree,l as iee,ln as aee,mi as oee,mr as see,mt as Ye,nt as cee,or as lee,ot as Xe,pi as uee,pr as dee,qr as Ze,rn as fee,sn as Qe,sr as pee,t as I,ui as mee,vn as hee,xr as gee,y as $e,yn as _ee,yr as vee,zr as yee}from"./src-DL3w8VPk2.js";import{i as bee,r as xee}from"./isSymbol-BO6cdPI7.js";import{t as et}from"./jsx-runtime-Bb4Xn-E0.js";import{A as L,B as See,C as R,D as tt,H as Cee,I as wee,M as nt,N as Tee,O as rt,R as Eee,T as it,U as Dee,a as at,b as ot,f as st,g as ct,h as Oee,j as lt,k as ut,l as dt,m as ft,p as z,s as kee,u as Aee,v as jee,w as B,x as pt}from"./external-CEp-aPkt.js";import{i as mt,n as ht,r as gt,t as _t}from"./lazySchema-B4D4qJVE.js";import{$t as vt,Ai as Mee,At as yt,B as bt,Bn as Nee,Br as xt,Bt as Pee,C as Fee,Cr as St,Ct as Iee,D as Lee,Dn as Ct,Dt as Ree,E as zee,En as wt,Et as Tt,Fr as Bee,Ft as Vee,G as Hee,Gr as Et,Gt as Dt,H as Ot,Hn as Uee,Hr as Wee,Ht as Gee,I as kt,It as Kee,Jt as qee,K as At,Kr as Jee,Kt as jt,L as Yee,Ln as Mt,Lt as Xee,Mi as Zee,Mr as Nt,Mt as Qee,Ni as $ee,Nr as Pt,Nt as ete,O as Ft,Oi as tte,On as It,Ot as Lt,Pr as nte,Q as Rt,R as zt,Rn as Bt,Rr as Vt,Rt as rte,S as ite,Sr as Ht,St as ate,T as ote,Ti as ste,Tt as cte,U as lte,Un as ute,Ur as dte,Ut as fte,V as pte,Vn as mte,Vr as hte,Wn as gte,Wr as Ut,Wt,Xt as _te,Y as vte,Yt as yte,_ as bte,_i as xte,_n as Gt,_r as Kt,_t as qt,a as Ste,ai as Cte,an as wte,at as Tte,bi as Jt,br as Ete,bt as Dte,c as Ote,ci as kte,cn as Ate,cr as jte,ct as Mte,d as Nte,dn as Pte,dr as Fte,dt as Yt,et as Xt,f as Ite,fi as Lte,g as Rte,gi as zte,gr as Zt,h as Qt,ht as $t,i as Bte,ii as Vte,it as en,j as Hte,ji as Ute,jt as tn,ki as Wte,kn as Gte,kt as nn,li as Kte,lr as rn,lt as an,m as qte,mn as Jte,mr as Yte,n as Xte,ni as Zte,nt as on,o as Qte,or as $te,ot as ene,p as tne,pi as nne,pt as sn,qr as rne,qt as cn,r as ine,ri as ln,rt as un,s as ane,st as one,t as sne,tr as cne,u as dn,un as lne,ur as fn,ut as pn,vt as une,w as dne,wi as fne,wt as pne,x as mne,xi as mn,xt as hn,yt as hne,z as gn,zr as _n,zt as gne}from"./state-BPFYBqm1.js";import{i as _ne,n as vn,r as vne,t as yn}from"./cwd-Besi3Os3.js";import{$ as yne,A as bn,B as xn,C as V,D as bne,E as Sn,F as Cn,I as xne,J as wn,L as Tn,M as En,N as Sne,O as Dn,P as H,Q as Cne,R as On,S as kn,T as An,U as jn,V as Mn,W as Nn,X as Pn,Y as Fn,Z as In,_ as Ln,a as Rn,c as U,d as zn,f as Bn,g as Vn,h as wne,i as W,j as Hn,k as Un,m as Wn,nt as Gn,p as Kn,q as Tne,rt as Ene,s as qn,t as Dne,tt as Jn,u as G,v as One,x as Yn,y as kne,z as Ane}from"./debug-BQj6h99Q.js";import{$ as Xn,$t as jne,A as Mne,An as Nne,Ar as Pne,At as Fne,B as Zn,Bn as Qn,Bt as $n,C as Ine,Cn as er,Cr as tr,Ct as nr,D as Lne,Dn as Rne,Dr as zne,Dt as rr,E as Bne,Er as ir,Et as Vne,F as ar,Ft as Hne,G as Une,H as or,Ht as sr,I as cr,In as lr,J as ur,Jn as dr,Jt as Wne,K as fr,Kt as pr,L as mr,Ln as hr,Mn as Gne,Mt as gr,N as Kne,Nn as qne,On as _r,Or as Jne,Ot as vr,P as yr,Pn as br,Q as xr,Qt as Sr,R as Yne,Rn as Cr,Rt as Xne,Sn as wr,Sr as Zne,St as Qne,T as $ne,Tn as ere,Tr,U as tre,V as Er,Vt as nre,W as rre,Wt as Dr,X as ire,Xn as Or,Xt as kr,Y as are,Yn as ore,Yt as Ar,Z as sre,Zt as jr,_n as Mr,_t as Nr,ar as Pr,at as Fr,bn as cre,br as lre,bt as ure,c as Ir,cr as Lr,ct as dre,dr as fre,dt as Rr,en as pre,f as zr,fn as mre,fr as hre,ft as Br,g as Vr,gn as gre,gr as _re,h as vre,hn as yre,hr as bre,ht as Hr,in as xre,ir as Sre,it as Ur,j as Cre,jt as Wr,kn as Gr,kr as wre,kt as Tre,l as Kr,ln as qr,lr as Ere,lt as Jr,m as Dre,mn as Yr,mr as Ore,mt as kre,n as Xr,nn as Zr,nr as Are,nt as jre,o as Mre,on as Nre,or as Qr,ot as $r,p as Pre,pn as Fre,pr as Ire,pt as Lre,q as ei,rn as Rre,rr as zre,rt as Bre,s as ti,sn as Vre,sr as ni,st as ri,t as Hre,tn as Ure,tr as Wre,u as Gre,un as ii,ur as ai,ut as oi,v as Kre,vn as qre,vt as si,w as Jre,wn as ci,wr as Yre,x as li,xn as ui,xr as Xre,yn as Zre,yr as Qre,yt as di,z as fi,zn as $re}from"./settings-CvhsRFaT.js";import{A as pi,C as mi,F as eie,I as tie,L as nie,M as hi,N as gi,O as rie,P as _i,R as iie,S as vi,c as yi,d as aie,h as bi,j as oie,k as xi,l as sie,m as cie,n as lie,o as Si,u as Ci,v as wi,y as Ti,z as uie}from"./config-BSkuQZNf.js";import{A as die,C as fie,D as pie,E as mie,O as Ei,S as Di,T as hie,_ as gie,a as Oi,b as _ie,c as vie,h as yie,i as ki,k as Ai,l as ji,m as Mi,n as Ni,o as bie,p as Pi,r as Fi,w as xie,x as Sie,y as Cie}from"./git-DplvjXEY.js";import{c as Ii,i as wie,l as Tie,n as Li,o as Ri,r as zi,t as Bi}from"./execFileNoThrow-DYm1GeGn.js";import{A as Eie,B as Vi,C as Die,F as Oie,G as kie,H as Aie,I as Hi,K as jie,L as Ui,N as Mie,P as Wi,R as Gi,T as Ki,U as qi,V as Ji,W as Nie,_ as Pie,c as K,d as Fie,f as Iie,j as Lie,k as Yi,l as Xi,m as Rie,n as Zi,o as Qi,q as $i,s as q,w as ea,z as ta}from"./log-BlJ7CcKG.js";import{i as na,n as zie,r as Bie,t as Vie}from"./hash-Tu-My5Vp.js";import{a as ra,i as ia,n as aa,t as oa}from"./memoize-_2f7NWDv.js";import{n as sa,t as ca}from"./which-BR8YVCCW.js";import{i as la,o as ua}from"./platform-DVeTi9mp.js";import{a as da,i as fa,s as pa,t as Hie}from"./windowsPaths-BmXyrasP.js";import{_ as Uie,a as ma,c as ha,d as Wie,f as Gie,g as Kie,h as qie,i as Jie,l as ga,m as _a,o as va,r as Yie,s as ya,t as ba,u as Xie}from"./sessionStoragePortable-x0Yn02-G.js";import{a as xa,c as Sa,n as Zie,r as Ca,s as wa,t as Ta,u as Ea}from"./types-BomO8WUz.js";import{n as Da,r as J}from"./analytics-DJobLaWP.js";import{a as Qie,n as Oa,o as ka,t as $ie}from"./intl-D2kgJmX7.js";import{C as Aa,a as ja,b as Ma,c as Na,f as Pa,g as Fa,h as Ia,i as eae,l as La,n as tae,o as nae,s as Ra,u as za,v as Ba,w as rae}from"./startupProfiler-2sjXZkIP.js";import{l as Va,o as iae,s as aae,u as Ha}from"./oauth-D38aRTUb.js";import{n as oae,r as sae,t as Ua}from"./bundledMode--fG1S62b.js";import{a as Wa,c as Ga,i as Ka,l as qa,n as cae,o as Ja,r as Ya,s as Xa,t as Za,u as Qa}from"./stringUtils-BjnclTLB.js";import{$ as lae,$r as $a,An as eo,B as to,Bt as no,C as ro,Cn as io,Cr as ao,D as uae,Dt as dae,F as oo,Fn as so,Ft as co,G as fae,Gr as lo,Gt as uo,Hn as pae,In as fo,It as po,Jr as mae,Jt as mo,Kn as ho,Kr as go,Ln as hae,M as gae,Mn as _ae,N as vae,Nn as yae,Nr as _o,Nt as bae,On as xae,Ot as vo,P as Sae,Pn as yo,Pr as bo,Q as Cae,Qn as xo,Qr as wae,Rn as Tae,S as So,Sn as Co,Sr as wo,St as To,T as Eo,Tn as Eae,Un as Do,V as Oo,Vn as ko,W as Ao,Wn as Dae,Xr as Oae,Yr as kae,Zn as jo,Zr as Mo,_ as No,_n as Po,_t as Aae,ai as Fo,ar as Io,c as jae,d as Mae,dr as Nae,dt as Pae,ei as Fae,er as Lo,et as Ro,fr as Iae,g as Lae,gn as Rae,gt as zae,h as zo,hn as Bae,hr as Bo,ii as Vo,ir as Ho,it as Vae,jn as Uo,jt as Hae,kn as Uae,l as Wo,lr as Wae,m as Go,mr as Gae,mt as Ko,ni as Kae,nn as qae,nr as Jae,nt as qo,oi as Jo,or as Yae,pr as Xae,qn as Zae,qr as Qae,r as Yo,rt as Xo,s as $ae,si as Zo,sr as eoe,ti as toe,tt as noe,u as Qo,ur as roe,vn as $o,vr as ioe,vt as aoe,wn as ooe,xt as soe,y as es,yr as coe,zn as loe}from"./model-CeG-iOKF.js";import{$ as ts,$t as uoe,A as doe,At as foe,B as poe,Bt as ns,Ct as moe,Dt as hoe,Et as rs,Ft as goe,G as _oe,Gt as is,H as voe,Ht as as,I as yoe,It as boe,J as xoe,Jt as os,K as Soe,Kt as ss,Lt as Coe,Mt as woe,N as Toe,Nt as cs,O as Eoe,Ot as ls,P as Doe,Pt as Ooe,Q as koe,Qt as Aoe,R as joe,Rt as us,S as Moe,St as ds,T as Noe,Tt as fs,U as Poe,Ut as ps,Vt as ms,W as Foe,Wt as hs,X as Ioe,Xt as gs,Y as Loe,Yt as Roe,Z as zoe,Zt as Boe,_ as Voe,_n as _s,_t as vs,a as ys,an as bs,at as xs,b as Hoe,bn as Ss,bt as Uoe,c as Cs,cn as Woe,d as Goe,dn as ws,dt as Koe,en as qoe,et as Joe,f as Ts,fn as Yoe,ft as Xoe,g as Es,gn as Ds,gt as Zoe,h as Qoe,hn as Os,ht as ks,i as As,in as js,jt as $oe,k as ese,kt as Ms,l as tse,ln as nse,lt as rse,m as ise,mn as Ns,mt as Ps,n as ase,nn as Fs,nt as Is,o as ose,on as sse,p as cse,pt as Ls,q as lse,qt as Rs,r as zs,rn as use,rt as dse,s as fse,sn as Bs,st as Vs,t as pse,tn as mse,tt as Hs,u as hse,ut as gse,vn as _se,vt as vse,w as yse,wt as Us,xn as Ws,xt as Gs,yn as Ks,yt as qs,z as bse,zt as Js}from"./prompt-Bm2EEG4F.js";import{a as Ys,c as xse,h as Sse,l as Xs,m as Cse,o as wse,s as Tse,u as Ese}from"./proxy-C0j74LqT.js";import{n as Dse,t as Ose}from"./userAgent-aoe_xVAb.js";import{i as kse,m as Ase,o as jse,p as Mse}from"./terminalSetup-JJiXmszo.js";import{B as Nse,C as Pse,N as Zs,O as Fse,P as Ise,Q as Qs,S as $s,T as ec,Y as Lse,Z as Rse,at as tc,b as nc,bt as zse,d as Bse,et as rc,h as Vse,k as Hse,m as Use,n as Wse,p as Gse,q as Kse,r as qse,st as ic,u as ac,ut as Jse,v as oc,vt as Yse,y as sc,yt as Xse,z as Zse}from"./sessionState-zhvcDpb2.js";import{a as Qse,i as $se,n as ece,o as tce,t as nce}from"./break-cache-Cd1yQ-0h.js";import{a as rce,i as ice,l as cc,n as ace,o as lc,r as oce,s as sce,t as cce}from"./localSearch-BEnlgSB7.js";import{a as uc,i as dc,n as fc,o as lce,r as pc,t as uce}from"./shellQuote-D3Ocv_U-.js";import{a as mc,c as hc,n as dce,s as gc}from"./ripgrep-DsLUmulz.js";import{a as fce,i as pce,n as mce,r as hce}from"./client-B7WkO81L.js";import{r as _c,t as gce}from"./store-Z8rTjDHe.js";import{a as _ce,n as vce,o as vc,s as yce,t as bce}from"./switcher-BkGOeIzI.js";import{a as yc,i as bc,n as xce}from"./genericProcessUtils-Bbcbi11g.js";import{$ as Sce,J as Cce,Q as xc,X as wce,Y as Tce,at as Ece,ct as Sc,et as Cc,ft as Dce,lt as wc,nt as Tc,ot as Ec,rt as Dc,st as Oce,tt as kce,ut as Oc}from"./esm-DtcV71xh.js";import{r as kc,t as Ac}from"./subprocessEnv-CNBOhlDV.js";import{n as Ace,t as jce}from"./sessionIdCompat-Dgp6PW_1.js";import{a as Mce,o as Nce,r as jc,s as Pce,t as Fce}from"./parser-a2S_eFyE.js";import{C as Mc,S as Ice,T as Nc,a as Lce,b as Rce,c as Pc,f as zce,g as Bce,h as Vce,i as Hce,m as Uce,n as Wce,o as Gce,p as Kce,s as Fc,t as qce,u as Jce,v as Yce,w as Ic,x as Xce,y as Zce}from"./sessionTracing-C4uqAdud.js";import{n as Qce,r as $ce,t as Lc}from"./poorMode-wm2WkPF0.js";import{a as ele,i as Rc,o as tle,r as zc}from"./detectRepository-Qy3zKoyn.js";import{a as Bc,i as nle,o as Vc,r as Hc}from"./api-ClAyS7cQ.js";import{f as rle,n as ile,p as ale,s as ole}from"./firstPartyEventLogger-7pAyUdbp.js";import{n as sle,t as cle}from"./datadog-C9uqPA6N.js";import{i as lle,t as ule}from"./src-l6_O0K-a.js";import{n as dle,t as fle}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as ple,t as mle}from"./featureCheck-D6FjD-nt.js";import*as hle from"os";import{homedir as Uc,platform as gle,release as _le,tmpdir as Wc,type as vle,version as yle}from"os";import*as Gc from"path";import{basename as Kc,delimiter as ble,dirname as qc,extname as Jc,isAbsolute as Yc,join as Y,normalize as Xc,parse as Zc,posix as Qc,relative as $c,resolve as el,sep as tl,win32 as nl}from"path";import rl from"node:process";import*as il from"node:path";import al,{basename as xle,dirname as Sle,isAbsolute as Cle,join as ol,relative as sl,resolve as cl,sep as wle}from"node:path";import*as ll from"fs";import{accessSync as Tle,closeSync as Ele,constants as ul,createReadStream as Dle,existsSync as Ole,fstat as kle,fstatSync as Ale,mkdirSync as jle,openSync as Mle,readFileSync as dl,readSync as Nle,readdirSync as Ple,rm as Fle,rmSync as Ile,statSync as Lle,unlinkSync as Rle,watch as zle,writeFileSync as Ble,writeSync as fl}from"fs";import{execSync as Vle,spawn as Hle,spawnSync as Ule}from"node:child_process";import*as pl from"node:fs";import{closeSync as Wle,existsSync as ml,mkdirSync as Gle,openSync as Kle,readFileSync as qle,readSync as Jle,readdirSync as hl,renameSync as Yle,rmSync as Xle,stat as Zle,statSync as Qle,unlinkSync as $le,unwatchFile as eue,watch as tue,watchFile as nue,writeFileSync as rue}from"node:fs";import{EOL as gl,homedir as iue,tmpdir as _l,type as aue}from"node:os";import{createHash as oue,randomBytes as sue,randomUUID as cue}from"node:crypto";import{createHash as vl,randomBytes as yl,randomUUID as bl}from"crypto";import*as xl from"fs/promises";import{access as lue,appendFile as Sl,chmod as Cl,copyFile as wl,link as Tl,lstat as uue,mkdir as El,open as Dl,readFile as Ol,readdir as kl,readlink as due,realpath as Al,rename as jl,rm as Ml,rmdir as fue,stat as Nl,symlink as Pl,truncate as pue,unlink as Fl,utimes as mue,writeFile as Il}from"fs/promises";import{isDeepStrictEqual as hue}from"util";import{execFile as gue,execFileSync as Ll,spawn as Rl,spawnSync as zl}from"child_process";import{createServer as Bl}from"http";import{fileURLToPath as _ue,parse as vue,pathToFileURL as Vl}from"url";import yue,{createConnection as bue,isIP as xue}from"net";import{EventEmitter as Sue}from"node:events";import{setMaxListeners as Cue}from"events";import{PassThrough as wue,Readable as Tue}from"node:stream";import{lstat as Hl,mkdir as Eue,open as Due,readFile as Ul,readdir as Wl,realpath as Gl,rename as Oue,rm as kue,stat as Kl,writeFile as Aue}from"node:fs/promises";import{request as jue}from"node:https";import{Agent as Mue,createServer as Nue,request as ql}from"node:http";import{lookup as Pue}from"dns";import{URL as Jl,fileURLToPath as Fue}from"node:url";import{BlockList as Iue,connect as Yl,isIP as Xl}from"node:net";import{connect as Lue}from"node:tls";import{text as Rue}from"node:stream/consumers";import{join as Zl}from"path/posix";async function zue(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};i&&(i.aborted&&y(i.reason),i.addEventListener(`abort`,g,{once:!0}));let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==Ql&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===Ql&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var Ql,Bue=n((()=>{Ql=Symbol(`skip`)}));function Vue(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return Hue.has(t)}var Hue,Uue=n((()=>{Hue=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 Wue(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var Gue=n((()=>{}));function Kue(e,t){return e&&Tr(t,Et(t),e)}var que=n((()=>{ir(),Ut()}));function Jue(e,t){return e&&Tr(t,Yre(t),e)}var Yue=n((()=>{ir(),tr()}));function Xue(e,t){return Tr(e,Lte(e),t)}var Zue=n((()=>{ir(),nne()}));function Que(e,t){return Tr(e,iie(e),t)}var $ue=n((()=>{ir(),uie()}));function ede(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&tde.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var tde,nde=n((()=>{tde=Object.prototype.hasOwnProperty}));function rde(e,t){var n=t?bre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var ide=n((()=>{_re()}));function ade(e){var t=new e.constructor(e.source,ode.exec(e));return t.lastIndex=e.lastIndex,t}var ode,sde=n((()=>{ode=/\w*$/}));function cde(e){return eu?Object(eu.call(e)):{}}var $l,eu,lde=n((()=>{c(),$l=o?o.prototype:void 0,eu=$l?$l.valueOf:void 0}));function ude(e,t,n){var r=e.constructor;switch(t){case yde:return bre(e);case dde:case fde:return new r(+e);case bde:return rde(e,n);case xde:case Sde:case Cde:case wde:case Tde:case Ede:case Dde:case Ode:case kde:return Ire(e,n);case pde:return new r;case mde:case _de:return new r(e);case hde:return ade(e);case gde:return new r;case vde:return cde(e)}}var dde,fde,pde,mde,hde,gde,_de,vde,yde,bde,xde,Sde,Cde,wde,Tde,Ede,Dde,Ode,kde,Ade=n((()=>{_re(),ide(),sde(),lde(),Ore(),dde=`[object Boolean]`,fde=`[object Date]`,pde=`[object Map]`,mde=`[object Number]`,hde=`[object RegExp]`,gde=`[object Set]`,_de=`[object String]`,vde=`[object Symbol]`,yde=`[object ArrayBuffer]`,bde=`[object DataView]`,xde=`[object Float32Array]`,Sde=`[object Float64Array]`,Cde=`[object Int8Array]`,wde=`[object Int16Array]`,Tde=`[object Int32Array]`,Ede=`[object Uint8Array]`,Dde=`[object Uint8ClampedArray]`,Ode=`[object Uint16Array]`,kde=`[object Uint32Array]`}));function jde(e){return bee(e)&&Vt(e)==Mde}var Mde,Nde=n((()=>{_n(),xee(),Mde=`[object Map]`})),tu,Pde,Fde=n((()=>{Nde(),Cte(),Zte(),tu=ln&&ln.isMap,Pde=tu?Vte(tu):jde}));function Ide(e){return bee(e)&&Vt(e)==Lde}var Lde,Rde=n((()=>{_n(),xee(),Lde=`[object Set]`})),nu,zde,Bde=n((()=>{Rde(),Cte(),Zte(),nu=ln&&ln.isSet,zde=nu?Vte(nu):Ide}));function ru(e,t,n,r,i,a){var o,c=t&Vde,l=t&Hde,u=t&Ude;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=mn(e);if(d){if(o=ede(e),!c)return Qre(e,o)}else{var f=Vt(e),p=f==au||f==Jde;if(Kte(e))return Xre(e,c);if(f==ou||f==iu||p&&!i){if(o=l||p?{}:fre(e),!c)return l?Que(e,Jue(o,e)):Xue(e,Kue(o,e))}else{if(!su[f])return i?e:{};o=ude(e,f,c)}}a||(a=new Zee);var m=a.get(e);if(m)return m;a.set(e,o),zde(e)?e.forEach(function(r){o.add(ru(r,t,n,r,e,a))}):Pde(e)&&e.forEach(function(r,i){o.set(i,ru(r,t,n,i,e,a))});var h=d?void 0:(u?l?tie:Wee:l?Yre:Et)(e);return Wue(h||e,function(r,i){h&&(i=r,r=e[i]),zne(o,i,ru(r,t,n,i,e,a))}),o}var Vde,Hde,Ude,iu,Wde,Gde,Kde,qde,au,Jde,Yde,Xde,ou,Zde,Qde,$de,efe,tfe,nfe,rfe,ife,afe,ofe,sfe,cfe,lfe,ufe,dfe,ffe,su,cu=n((()=>{$ee(),Gue(),Jne(),que(),Yue(),Zne(),lre(),Zue(),$ue(),dte(),nie(),_n(),nde(),Ade(),hre(),Jt(),kte(),Fde(),l(),Bde(),Ut(),tr(),Vde=1,Hde=2,Ude=4,iu=`[object Arguments]`,Wde=`[object Array]`,Gde=`[object Boolean]`,Kde=`[object Date]`,qde=`[object Error]`,au=`[object Function]`,Jde=`[object GeneratorFunction]`,Yde=`[object Map]`,Xde=`[object Number]`,ou=`[object Object]`,Zde=`[object RegExp]`,Qde=`[object Set]`,$de=`[object String]`,efe=`[object Symbol]`,tfe=`[object WeakMap]`,nfe=`[object ArrayBuffer]`,rfe=`[object DataView]`,ife=`[object Float32Array]`,afe=`[object Float64Array]`,ofe=`[object Int8Array]`,sfe=`[object Int16Array]`,cfe=`[object Int32Array]`,lfe=`[object Uint8Array]`,ufe=`[object Uint8ClampedArray]`,dfe=`[object Uint16Array]`,ffe=`[object Uint32Array]`,su={},su[iu]=su[Wde]=su[nfe]=su[rfe]=su[Gde]=su[Kde]=su[ife]=su[afe]=su[ofe]=su[sfe]=su[cfe]=su[Yde]=su[Xde]=su[ou]=su[Zde]=su[Qde]=su[$de]=su[efe]=su[lfe]=su[ufe]=su[dfe]=su[ffe]=!0,su[qde]=su[au]=su[tfe]=!1}));function pfe(e){return ru(e,mfe|hfe)}var mfe,hfe,gfe=n((()=>{cu(),mfe=1,hfe=4}));function lu(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 _fe=n((()=>{})),uu=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})),du=a((e=>{var t=uu(),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})),vfe=a((e=>{var t=uu(),n=du(),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})),fu=a((e=>{var t=uu(),n=du();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})),yfe=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})),pu=a((e=>{var t=uu();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})),mu=a((e=>{var t=yfe(),n=uu(),r=pu();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}}})),hu=a((e=>{var t=fu(),n=du(),r=uu(),i=mu(),a=pu(),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})),gu=a((e=>{var t=uu(),n=mu(),r=pu(),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})),_u=a((e=>{var t=hu(),n=uu(),r=gu(),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})),vu=a((e=>{var t=_u(),n=uu(),r=mu();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})),yu=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())}}}})),Vfe=a((e=>{var t=Qu(),n=Uu(),r=Wu(),i=Su(),a=uu(),o=td(),s=nd();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})),rd=a((e=>{var t=Qu(),n=Uu(),r=Hu(),i=Wu(),a=hu(),o=uu(),s=Tu(),c=gu(),l=Du(),u=ku(),d=$u(),f=ed(),p=td(),m=nd(),h=Vfe(),g=du();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 id(e){return typeof Bun<`u`?Bun.YAML.parse(e):rd().parse(e)}var ad=n((()=>{}));function Hfe(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(pd.test(i)){let e=i.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);n.push(`${r}: "${e}"`);continue}}n.push(e)}return n.join(`
117
- `)}function od(e,t){let n=e.match(md);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=id(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=id(Hfe(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){U(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function sd(e){if(Array.isArray(e))return e.flatMap(sd);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=>cd(e))}function cd(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=cd(n+e+i);o.push(...t)}return o}function ld(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function ud(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(U(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function dd(e){return e===!0||e===`true`}function fd(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(hd.includes(n))return n;U(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${hd.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var pd,md,hd,gd=n((()=>{W(),ad(),pd=/[{}[\]*&#!|>%@`]|: /,md=/^---\s*\n([\s\S]*?)---\s*\n?/,hd=[`bash`,`powershell`]}));function _d(e){return Vo()===`vertex`?yd:e?.isNonInteractive?e.hasAppendSystemPrompt?bd:xd:yd}function Ufe(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function vd(){if(!Ufe())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=toe(),n=`x-anthropic-billing-header: cc_version=0.0.14; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return U(`attribution header ${n}`),n}var yd,bd,xd,Sd,Cd,wd=n((()=>{W(),h(),Jo(),Kae(),yd=`You are Work Mate, a CLI for Claude.`,bd=`You are Work Mate, a CLI for Claude, running within the Claude Agent SDK.`,xd=`You are a Claude agent, built on the Claude Agent SDK.`,Sd=[yd,bd,xd],Cd=new Set(Sd)})),Td,Wfe=n((()=>{Td=e=>!1})),Gfe=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 Kfe(e){if(typeof e==`string`)return Ed.find(t=>t===e)}var Ed,Dd,Od,kd,Ad,jd,Md,Nd=n((()=>{Ed=[`user`,`feedback`,`project`,`reference`],Dd=[`## 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>`,``],Od=[`## 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.`],kd=`- 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.`,Ad=[`## 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.`,kd],jd=[`## 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."],Md=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${Ed.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function Pd(e){let t=e.trim(),n=t.split(`
117
+ `)}function od(e,t){let n=e.match(md);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=id(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=id(Hfe(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){U(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function sd(e){if(Array.isArray(e))return e.flatMap(sd);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=>cd(e))}function cd(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=cd(n+e+i);o.push(...t)}return o}function ld(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function ud(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(U(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function dd(e){return e===!0||e===`true`}function fd(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(hd.includes(n))return n;U(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${hd.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var pd,md,hd,gd=n((()=>{W(),ad(),pd=/[{}[\]*&#!|>%@`]|: /,md=/^---\s*\n([\s\S]*?)---\s*\n?/,hd=[`bash`,`powershell`]}));function _d(e){return Vo()===`vertex`?yd:e?.isNonInteractive?e.hasAppendSystemPrompt?bd:xd:yd}function Ufe(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function vd(){if(!Ufe())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=toe(),n=`x-anthropic-billing-header: cc_version=0.0.15; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return U(`attribution header ${n}`),n}var yd,bd,xd,Sd,Cd,wd=n((()=>{W(),h(),Jo(),Kae(),yd=`You are Work Mate, a CLI for Work Mate.`,bd=`You are Work Mate, a CLI for Work Mate, running within the Work Mate Agent SDK.`,xd=`You are a Work Mate agent, built on the Work Mate Agent SDK.`,Sd=[yd,bd,xd],Cd=new Set(Sd)})),Td,Wfe=n((()=>{Td=e=>!1})),Gfe=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 Kfe(e){if(typeof e==`string`)return Ed.find(t=>t===e)}var Ed,Dd,Od,kd,Ad,jd,Md,Nd=n((()=>{Ed=[`user`,`feedback`,`project`,`reference`],Dd=[`## 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>`,``],Od=[`## 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.`],kd=`- 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.`,Ad=[`## 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.`,kd],jd=[`## 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."],Md=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${Ed.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function Pd(e){let t=e.trim(),n=t.split(`
118
118
  `),r=n.length,i=t.length,a=r>200,o=i>Bd;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
  `,Bd);s=s.slice(0,e>0?e:Bd)}let c=o&&!a?`${za(i)} (limit: ${za(Bd)}) — index entries are too long`:a&&!o?`${r} lines (limit: 200)`:`${r} lines and ${za(i)}`;return{content:s+`\n\n> WARNING: ${zd} 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 Fd(e){let t=G();try{await t.mkdir(e)}catch(t){U(`ensureMemoryDirExists failed for ${e}: ${(t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:void 0)??String(t)}`,{level:`debug`})}}function Id(e,t){G().readdir(e).then(e=>{let n=0,r=0;for(let t of e)t.isFile()?n++:t.isDirectory()&&r++;J(`tengu_memdir_loaded`,{...t,total_file_count:n,total_subdir_count:r})},()=>{J(`tengu_memdir_loaded`,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:",``,...Md,``,`- 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:",``,...Md,``,`**Step 2** — add a pointer to that file in \`${zd}\`. \`${zd}\` 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 \`${zd}\`.`,``,`- \`${zd}\` 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}\`. ${Hd}`,``,`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.`,``,...Dd,...Od,``,...i,``,...Ad,``,...jd,``,`## 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 qfe(e){let{displayName:t,memoryDir:n,extraGuidelines:r}=e,i=G(),a=n+zd,o=``;try{o=i.readFileSync(a,{encoding:`utf-8`})}catch{}let s=Ld(t,n,r);if(o.trim()){let e=Pd(o),r=t===Vd?`auto`:`agent`;Id(n,{content_length:e.byteCount,line_count:e.lineCount,was_truncated:e.wasLineTruncated,was_byte_truncated:e.wasByteTruncated,memory_type:r}),s.push(`## ${zd}`,``,e.content)}else s.push(`## ${zd}`,``,`Your ${zd} is currently empty. When you save new memories, they will appear here.`);return s.join(`
121
121
  `)}async function Rd(){let e=_i(),t=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES,n=t&&t.trim().length>0?[t]:void 0;if(e){let e=xi();return await Fd(e),Id(e,{memory_type:`auto`}),Ld(`auto memory`,e,n,!1).join(`
122
- `)}return J(`tengu_memdir_disabled`,{disabled_by_env_var:m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&Xr().autoMemoryEnabled===!1}),null}var zd,Bd,Vd,Hd,Ud=n((()=>{Bn(),hi(),Da(),W(),h(),Ba(),Vr(),Nd(),zd=`MEMORY.md`,Bd=25e3,Vd=`auto memory`,Hd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Jfe(e){return e.replace(/:/g,`-`)}function Wd(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,_a(Ni(en())??en()),`agent-memory-local`,e)+tl:Y(yn(),`.workmate`,`agent-memory-local`,e)+tl}function Gd(e,t){let n=Jfe(e);switch(t){case`project`:return Y(yn(),`.workmate`,`agent-memory`,n)+tl;case`local`:return Wd(n);case`user`:return Y(pi(),`agent-memory`,n)+tl}}function Kd(e){let t=Xc(e),n=pi();if(t.startsWith(Y(n,`agent-memory`)+tl)||t.startsWith(Y(yn(),`.workmate`,`agent-memory`)+tl))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${tl}agent-memory-local${tl}`)&&t.startsWith(Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+tl))return!0}else if(t.startsWith(Y(yn(),`.workmate`,`agent-memory-local`)+tl))return!0;return!1}function Yfe(e){switch(e){case`user`:return`User (${Y(pi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${Wd(`...`)})`;default:return`None`}}function qd(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=Gd(e,t);Fd(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return qfe({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var Jd=n((()=>{Wt(),Ud(),hi(),vn(),Mi(),Lr()}));function Yd(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Xd=n((()=>{W()}));function Xfe(e){return yl(4).readUInt32BE(0)%e}function Zd(e){return e[Xfe(e.length)]}function Zfe(){return`${Zd(Qd)}-${Zd(ef)}-${Zd($d)}`}function Qfe(){return`${Zd(Qd)}-${Zd($d)}`}var Qd,$d,ef,tf=n((()=>{Qd=`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(`.`),$d=`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(`.`),ef=`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 nf(e){let t=e??sn(),n=on().get(t);if(!n){let e=df();for(let t=0;t<uf;t++){n=Zfe();let t=Y(e,`${n}.md`);if(!G().existsSync(t))break}mte(t,n)}return n}function rf(e,t){mte(e,t)}function $fe(){on().clear()}function af(e){let t=nf(sn());return e?Y(df(),`${t}-agent-${e}.md`):Y(df(),`${t}.md`)}function of(e){let t=af(e);try{return G().readFileSync(t,{encoding:`utf-8`})}catch(e){return xn(e)||q(e),null}}function sf(e){return e.messages.find(e=>e.slug)?.slug}async function cf(e,t){let n=sf(e);if(!n)return!1;rf(t??sn(),n);let r=Y(df(),`${n}.md`);try{return await G().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!xn(t))return q(t),!1;if(Yd()===null)return!1;U(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=npe(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,U(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=tpe(e),i&&U(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await Il(r,i,{encoding:`utf-8`}),!0}catch(e){return q(e),!1}return U(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function epe(e,t){let n=sf(e);if(!n)return!1;let r=df(),i=Y(r,`${n}.md`),a=Y(r,`${nf(t)}.md`);try{return await wl(i,a),!0}catch(e){return xn(e)||q(e),!1}}function tpe(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 npe(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 lf(){if(Yd()!==null)try{let e=[],t=of();if(t&&e.push({key:`plan`,path:af(),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:bl(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-BeaEgnaa.js`);await r([n])}catch(e){q(e)}}var uf,df,ff=n((()=>{d(),Wt(),os(),vn(),W(),h(),On(),Xd(),Bn(),Qi(),Vr(),tf(),uf=10,df=u(function(){let e=Xr().plansDirectory,t;if(e){let n=yn(),r=el(n,e);!r.startsWith(n+tl)&&r!==n?(q(Error(`plansDirectory must be within project root: ${e}`)),t=Y(p(),`plans`)):t=r}else t=Y(p(),`plans`);try{G().mkdirSync(t)}catch(e){q(e)}return t})})),pf,rpe=n((()=>{pf={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-CpWXReCi.js`)}})),mf,ipe=n((()=>{mf={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-B0UmiVKl.js`)}})),hf,ape=n((()=>{hf={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-CNzBoL7O.js`)}})),gf,ope=n((()=>{h(),gf={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!m(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-Bj8mdDYN.js`)}})),_f,spe=n((()=>{_f={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-B1kYcRIP.js`)}})),vf,yf,cpe=n((()=>{Wt(),vf={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!gn(),type:`local-jsx`,load:()=>import(`./context-DB1Ar85E.js`)},yf={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!gn()},isEnabled(){return gn()},load:()=>import(`./context-noninteractive-Bno2Xsmp.js`)}})),bf,lpe=n((()=>{bf={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-dfXWiuLA.js`)}})),xf,upe=n((()=>{h(),xf={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!m(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-aKE2bG5C.js`)}})),Sf,dpe=n((()=>{Sf={type:`local-jsx`,name:`memory`,description:`编辑 Claude 记忆文件`,load:()=>import(`./memory-DK8bOrUr.js`)}})),Cf,fpe=n((()=>{Cf={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-BhfhEpnW.js`)}})),wf,ppe=n((()=>{wf={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-CELr6oJZ.js`)}}));function mpe(e,t){let n=sl(e,t);return n===``||!n.startsWith(`..`)&&!Cle(n)}function hpe(e,t){let n=cl(e),r=cl(t);if(!mpe(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Sle(a);if(e===a)break;a=e}return i.reverse()}async function Tf(e,t){try{let n=(await G().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Ere(sl(t,e))||xle(e),content:n}:null}catch{return null}}function gpe(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
122
+ `)}return J(`tengu_memdir_disabled`,{disabled_by_env_var:m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&Xr().autoMemoryEnabled===!1}),null}var zd,Bd,Vd,Hd,Ud=n((()=>{Bn(),hi(),Da(),W(),h(),Ba(),Vr(),Nd(),zd=`MEMORY.md`,Bd=25e3,Vd=`auto memory`,Hd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Jfe(e){return e.replace(/:/g,`-`)}function Wd(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,_a(Ni(en())??en()),`agent-memory-local`,e)+tl:Y(yn(),`.workmate`,`agent-memory-local`,e)+tl}function Gd(e,t){let n=Jfe(e);switch(t){case`project`:return Y(yn(),`.workmate`,`agent-memory`,n)+tl;case`local`:return Wd(n);case`user`:return Y(pi(),`agent-memory`,n)+tl}}function Kd(e){let t=Xc(e),n=pi();if(t.startsWith(Y(n,`agent-memory`)+tl)||t.startsWith(Y(yn(),`.workmate`,`agent-memory`)+tl))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${tl}agent-memory-local${tl}`)&&t.startsWith(Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+tl))return!0}else if(t.startsWith(Y(yn(),`.workmate`,`agent-memory-local`)+tl))return!0;return!1}function Yfe(e){switch(e){case`user`:return`User (${Y(pi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${Wd(`...`)})`;default:return`None`}}function qd(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=Gd(e,t);Fd(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return qfe({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var Jd=n((()=>{Wt(),Ud(),hi(),vn(),Mi(),Lr()}));function Yd(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Xd=n((()=>{W()}));function Xfe(e){return yl(4).readUInt32BE(0)%e}function Zd(e){return e[Xfe(e.length)]}function Zfe(){return`${Zd(Qd)}-${Zd(ef)}-${Zd($d)}`}function Qfe(){return`${Zd(Qd)}-${Zd($d)}`}var Qd,$d,ef,tf=n((()=>{Qd=`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(`.`),$d=`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(`.`),ef=`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 nf(e){let t=e??sn(),n=on().get(t);if(!n){let e=df();for(let t=0;t<uf;t++){n=Zfe();let t=Y(e,`${n}.md`);if(!G().existsSync(t))break}mte(t,n)}return n}function rf(e,t){mte(e,t)}function $fe(){on().clear()}function af(e){let t=nf(sn());return e?Y(df(),`${t}-agent-${e}.md`):Y(df(),`${t}.md`)}function of(e){let t=af(e);try{return G().readFileSync(t,{encoding:`utf-8`})}catch(e){return xn(e)||q(e),null}}function sf(e){return e.messages.find(e=>e.slug)?.slug}async function cf(e,t){let n=sf(e);if(!n)return!1;rf(t??sn(),n);let r=Y(df(),`${n}.md`);try{return await G().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!xn(t))return q(t),!1;if(Yd()===null)return!1;U(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=npe(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,U(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=tpe(e),i&&U(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await Il(r,i,{encoding:`utf-8`}),!0}catch(e){return q(e),!1}return U(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function epe(e,t){let n=sf(e);if(!n)return!1;let r=df(),i=Y(r,`${n}.md`),a=Y(r,`${nf(t)}.md`);try{return await wl(i,a),!0}catch(e){return xn(e)||q(e),!1}}function tpe(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 npe(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 lf(){if(Yd()!==null)try{let e=[],t=of();if(t&&e.push({key:`plan`,path:af(),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:bl(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-LMY409Ji.js`);await r([n])}catch(e){q(e)}}var uf,df,ff=n((()=>{d(),Wt(),os(),vn(),W(),h(),On(),Xd(),Bn(),Qi(),Vr(),tf(),uf=10,df=u(function(){let e=Xr().plansDirectory,t;if(e){let n=yn(),r=el(n,e);!r.startsWith(n+tl)&&r!==n?(q(Error(`plansDirectory must be within project root: ${e}`)),t=Y(p(),`plans`)):t=r}else t=Y(p(),`plans`);try{G().mkdirSync(t)}catch(e){q(e)}return t})})),pf,rpe=n((()=>{pf={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-BQ-ljgk6.js`)}})),mf,ipe=n((()=>{mf={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-IGcgP-Qq.js`)}})),hf,ape=n((()=>{hf={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-CF-FZwpe.js`)}})),gf,ope=n((()=>{h(),gf={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!m(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-BrJGpEFZ.js`)}})),_f,spe=n((()=>{_f={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-BohF3_IV.js`)}})),vf,yf,cpe=n((()=>{Wt(),vf={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!gn(),type:`local-jsx`,load:()=>import(`./context-DADnwl4t.js`)},yf={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!gn()},isEnabled(){return gn()},load:()=>import(`./context-noninteractive-BAbzwNxu.js`)}})),bf,lpe=n((()=>{bf={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-CzChvQyK.js`)}})),xf,upe=n((()=>{h(),xf={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!m(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-DdvdGkNX.js`)}})),Sf,dpe=n((()=>{Sf={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-C2U7CCmM.js`)}})),Cf,fpe=n((()=>{Cf={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-ByV6NqmB.js`)}})),wf,ppe=n((()=>{wf={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-DJp61Job.js`)}}));function mpe(e,t){let n=sl(e,t);return n===``||!n.startsWith(`..`)&&!Cle(n)}function hpe(e,t){let n=cl(e),r=cl(t);if(!mpe(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Sle(a);if(e===a)break;a=e}return i.reverse()}async function Tf(e,t){try{let n=(await G().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Ere(sl(t,e))||xle(e),content:n}:null}catch{return null}}function gpe(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
123
123
 
124
124
  `)}function _pe(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 vpe(e){let t=[],n=_pe(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 ype(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 Ef(e,t){return`${e}::${t.name}::${t.interval}::${t.prompt}`}function bpe(e,t){let n=[];for(let r of e.heartbeatTasks){let i=ype(r.interval);if(i==null)continue;let a=Ef(e.rootDir,r),o=Pf.get(a);o!==void 0&&t-o<i||n.push(r)}return n}function xpe(e,t,n){for(let r of t)Pf.set(Ef(e.rootDir,r),n)}async function Spe(e={}){let t=cl(e.rootDir??en()),n=cl(e.currentDir??yn()),r=hpe(t,n),[i,a]=await Promise.all([Promise.all(r.map(async e=>Tf(ol(e,kf,jf),t))),Tf(ol(t,kf,Mf),t)]),o=i.filter(e=>e!==null);return{rootDir:t,currentDir:n,agentsFiles:o,agentsContent:gpe(o),heartbeatFile:a,heartbeatContent:a?.content??null,heartbeatTasks:a?vpe(a.content):[]}}async function Cpe(e){let t=await Df(e);return Of(t),t.prompt}async function Df(e){let t=await Spe({rootDir:e.rootDir,currentDir:e.currentDir}),n=e.nowMs??Date.now(),r=e.trigger===`proactive-tick`?bpe(t,n):[],i=r.filter(e=>e.steps.length===0),a=[];if(t.agentsContent&&a.push(`Workspace authority from ${jf}:\n${t.agentsContent}`),t.heartbeatContent&&a.push(`Workspace heartbeat guidance from ${Mf}:\n${t.heartbeatContent}`),i.length>0&&a.push([`Due ${Mf} tasks:`,...i.map(e=>`- ${e.name} (${e.interval}): ${e.prompt}`)].join(`
@@ -187,7 +187,7 @@ Analyze the project to detect what's in different subdirectories. The project ma
187
187
  - Check MCP configuration (.mcp.json) for browser automation tools:
188
188
  - Playwright MCP server
189
189
  - Chrome DevTools MCP server
190
- - Claude Chrome Extension MCP (browser-use via Claude's Chrome extension)
190
+ - Claude Chrome Extension MCP (browser-use via Work Mate's Chrome extension)
191
191
  - For Python projects, check for playwright, pytest-playwright
192
192
 
193
193
  ## Phase 2: Verification Tool Setup
@@ -295,7 +295,7 @@ Based on the areas detected in Phase 1, you may need to create multiple verifier
295
295
 
296
296
  ## Phase 4: Generate Verifier Skill
297
297
 
298
- **All verifier skills are created in the project root's \`.workmate/skills/\` directory.** This ensures they are automatically loaded when Claude runs in the project.
298
+ **All verifier skills are created in the project root's \`.workmate/skills/\` directory.** This ensures they are automatically loaded when Work Mate runs in the project.
299
299
 
300
300
  Write the skill file to \`.workmate/skills/<verifier-name>/SKILL.md\`.
301
301
 
@@ -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
- `}]}}}));function Epe(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=zf.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Uf.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Uf.join(`, `)}`);return t.root=e,new Xf(t)}var zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Dpe=n((()=>{b(),zf={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Bf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:zf.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(Bf),Vf=`READDIRP_RECURSIVE_ERROR`,Hf=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Vf]),Uf=[zf.DIR_TYPE,zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE,zf.FILE_TYPE],Wf=new Set([zf.DIR_TYPE,zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE]),Gf=new Set([zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE,zf.FILE_TYPE]),Kf=e=>Hf.has(e.code),qf=process.platform===`win32`,Jf=e=>!0,Yf=e=>{if(e===void 0)return Jf;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Jf},Xf=class extends Tue{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark}),x(this,`parents`,void 0),x(this,`reading`,void 0),x(this,`parent`,void 0),x(this,`_stat`,void 0),x(this,`_maxDepth`,void 0),x(this,`_wantsDir`,void 0),x(this,`_wantsFile`,void 0),x(this,`_wantsEverything`,void 0),x(this,`_root`,void 0),x(this,`_isDirent`,void 0),x(this,`_statsProp`,void 0),x(this,`_rdOptions`,void 0),x(this,`_fileFilter`,void 0),x(this,`_directoryFilter`,void 0);let t={...Bf,...e},{root:n,type:r}=t;this._fileFilter=Yf(t.fileFilter),this._directoryFilter=Yf(t.directoryFilter);let i=t.lstat?Hl:Kl;qf?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Bf.depth,this._wantsDir=r?Wf.has(r):!1,this._wantsFile=r?Gf.has(r):!1,this._wantsEverything=r===zf.EVERYTHING_TYPE,this._root=cl(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await Wl(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=cl(ol(t,r));n={path:sl(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){Kf(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await Gl(t),n=await Hl(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===wle){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Vf,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}}}));function Zf(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Cp(il.resolve(e,r),dp,il.join(e,r))};try{return tue(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Ope=n((()=>{b(),Qf=`data`,$f=`close`,ep=()=>{},tp=process.platform,np=tp===`win32`,rp=tp===`darwin`,ip=tp===`linux`,ap=tp===`freebsd`,op=aue()===`OS400`,sp={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},cp=sp,lp=`watch`,up={lstat:Hl,stat:Kl},dp=`listeners`,fp=`errHandlers`,pp=`rawEmitters`,mp=[dp,fp,pp],hp=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),gp=e=>hp.has(il.extname(e).slice(1).toLowerCase()),_p=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},vp=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},yp=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},bp=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},xp=e=>e instanceof Set?e.size===0:!e,Sp=new Map,Cp=(e,t,n,r,i)=>{let a=Sp.get(e);a&&_p(a[t],e=>{e(n,r,i)})},wp=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Sp.get(t),c;if(!n.persistent)return c=Zf(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)vp(s,dp,i),vp(s,fp,a),vp(s,pp,o);else{if(c=Zf(e,n,Cp.bind(null,t,dp),a,Cp.bind(null,t,pp)),!c)return;c.on(cp.ERROR,async n=>{let r=Cp.bind(null,t,fp);if(s&&(s.watcherUnusable=!0),np&&n.code===`EPERM`)try{await(await Due(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Sp.set(t,s)}return()=>{bp(s,dp,i),bp(s,fp,a),bp(s,pp,o),xp(s.listeners)&&(s.watcher.close(),Sp.delete(t),mp.forEach(yp(s)),s.watcher=void 0,Object.freeze(s))}},Tp=new Map,Ep=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Tp.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(eue(t),o=void 0),o?(vp(o,dp,i),vp(o,pp,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:nue(t,n,(n,r)=>{_p(o.rawEmitters,e=>{e(cp.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&_p(o.listeners,t=>t(e,n))})},Tp.set(t,o)),()=>{bp(o,dp,i),bp(o,pp,a),xp(o.listeners)&&(Tp.delete(t),eue(t),o.options=o.watcher=void 0,Object.freeze(o))}},Dp=class{constructor(e){x(this,`fsw`,void 0),x(this,`_boundHandleError`,void 0),this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=il.dirname(e),i=il.basename(e);this.fsw._getWatchedDir(r).add(i);let a=il.resolve(e),o={persistent:n.persistent};t||(t=ep);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&gp(i)?n.binaryInterval:n.interval,s=Ep(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=wp(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=il.dirname(e),i=il.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(lp,e,5)){if(!n||n.mtimeMs===0)try{let n=await Kl(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(cp.CHANGE,e,n),(rp||ip||ap)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(cp.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(cp.ADD,e,0))return;this.fsw._emit(cp.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await Gl(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(cp.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(cp.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=il.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(Qf,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=il.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,s))){if(this.fsw.closed){u=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),d=il.join(i,il.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(cp.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!u)return s();u.once(`end`,()=>{if(this.fsw.closed){u=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(il.dirname(e)),c=s.has(il.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(cp.ADD_DIR,e,t),s.add(il.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await up[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=il.resolve(e),l=s?await Gl(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await Gl(e):e;if(this.fsw.closed)return;let a=il.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(cp.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(il.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}}}));function Op(e){return Array.isArray(e)?e:[e]}function kpe(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=il.relative(e.path,t);return n?!n.startsWith(`..`)&&!il.isAbsolute(n):!1}return!1}:()=>!1}function Ape(e){if(typeof e!=`string`)throw Error(`string expected`);e=il.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(Ip,`/`),t&&(e=`/`+e),e}function kp(e,t,n){let r=Ape(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function jpe(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Op(e).map(e=>kpe(e));return t==null?(e,t)=>kp(n,e,t):kp(n,t)}function Mpe(e,t={}){let n=new Xp(t);return n.add(e),n}var Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp=n((()=>{Dpe(),Ope(),b(),Ap=`/`,jp=`//`,Mp=`.`,Np=`..`,Pp=`string`,Fp=/\\/g,Ip=/\/\//g,Lp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Rp=/^\.[/\\]/,zp=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),Bp=e=>{let t=Op(e).flat();if(!t.every(e=>typeof e===Pp))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Hp)},Vp=e=>{let t=e.replace(Fp,Ap),n=!1;return t.startsWith(jp)&&(n=!0),t=t.replace(Ip,Ap),n&&(t=Ap+t),t},Hp=e=>Vp(il.normalize(Vp(e))),Up=(e=``)=>t=>typeof t==`string`?Hp(il.isAbsolute(t)?t:il.join(e,t)):t,Wp=(e,t)=>il.isAbsolute(e)?e:il.join(t,e),Gp=Object.freeze(new Set),Kp=class{constructor(e,t){x(this,`path`,void 0),x(this,`_removeWatcher`,void 0),x(this,`items`,void 0),this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Mp&&e!==Np&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Wl(n)}catch{this._removeWatcher&&this._removeWatcher(il.dirname(n),il.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=ep,this.items=Gp,Object.freeze(this)}},qp=`stat`,Jp=`lstat`,Yp=class{constructor(e,t,n){x(this,`fsw`,void 0),x(this,`path`,void 0),x(this,`watchPath`,void 0),x(this,`fullWatchPath`,void 0),x(this,`dirParts`,void 0),x(this,`followSymlinks`,void 0),x(this,`statMethod`,void 0),this.fsw=n;let r=e;this.path=e=e.replace(Rp,``),this.watchPath=r,this.fullWatchPath=il.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?qp:Jp}entryPath(e){return il.join(this.watchPath,il.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Xp=class extends Sue{constructor(e={}){super(),x(this,`closed`,void 0),x(this,`options`,void 0),x(this,`_closers`,void 0),x(this,`_ignoredPaths`,void 0),x(this,`_throttled`,void 0),x(this,`_streams`,void 0),x(this,`_symlinkPaths`,void 0),x(this,`_watched`,void 0),x(this,`_pendingWrites`,void 0),x(this,`_pendingUnlinks`,void 0),x(this,`_readyCount`,void 0),x(this,`_emitReady`,void 0),x(this,`_closePromise`,void 0),x(this,`_userIgnored`,void 0),x(this,`_readyEmitted`,void 0),x(this,`_emitRaw`,void 0),x(this,`_boundRemove`,void 0),x(this,`_nodeFsHandler`,void 0),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Op(e.ignored):Op([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};op&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=ep,this._readyEmitted=!0,process.nextTick(()=>this.emit(sp.READY)))},this._emitRaw=(...e)=>this.emit(sp.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Dp(this),Object.freeze(r)}_addIgnoredPath(e){if(zp(e)){for(let t of this._ignoredPaths)if(zp(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)zp(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Bp(e);return r&&(i=i.map(e=>Wp(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(il.dirname(e),il.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Bp(e),{cwd:n}=this.options;return t.forEach(e=>{!il.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=il.join(n,e)),e=il.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?il.relative(this.options.cwd,n):n)||Mp;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==sp.ERROR&&this.emit(sp.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;np&&(t=il.normalize(t)),r.cwd&&(t=il.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===sp.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(sp.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===sp.ADD&&this._pendingUnlinks.has(t)&&(e=sp.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===sp.ADD||e===sp.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=sp.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===sp.CHANGE&&!this._throttle(sp.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===sp.ADD||e===sp.ADD_DIR||e===sp.CHANGE)){let e=r.cwd?il.join(r.cwd,t):t,n;try{n=await Kl(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(sp.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!il.isAbsolute(e)&&(s=il.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){Zle(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&Lp.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Up(e)),n=[...[...this._ignoredPaths].map(Up(e)),...t];this._userIgnored=jpe(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Yp(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=il.resolve(e);return this._watched.has(t)||this._watched.set(t,new Kp(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=il.join(e,t),i=il.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=il.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===sp.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?sp.UNLINK_DIR:sp.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=il.dirname(e);this._getWatchedDir(t).remove(il.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Epe(e,{type:sp.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once($f,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Zp={watch:Mpe,FSWatcher:Xp}})),$p,em,tm,nm=n((()=>{Yse(),Ua(),ua(),$p=la()===`windows`?`alt+v`:`ctrl+v`,em=la()!==`windows`||(sae()?zse(process.versions.bun,`>=1.2.23`):zse(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,tm=[{context:`Global`,bindings:{"ctrl+c":`app:interrupt`,"ctrl+d":`app:exit`,"ctrl+l":`app:redraw`,"ctrl+t":`app:toggleTodos`,"ctrl+o":`app:toggleTranscript`,"ctrl+shift+o":`app:toggleTeammatePreview`,"ctrl+r":`history:search`}},{context:`Chat`,bindings:{escape:`chat:cancel`,"ctrl+x ctrl+k":`chat:killAgents`,[em]:`chat:cycleMode`,"meta+p":`chat:modelPicker`,"meta+o":`chat:fastMode`,"meta+t":`chat:thinkingToggle`,enter:`chat:submit`,up:`history:previous`,down:`history:next`,"ctrl+_":`chat:undo`,"ctrl+shift+-":`chat:undo`,"ctrl+x ctrl+e":`chat:externalEditor`,"ctrl+g":`chat:externalEditor`,"ctrl+s":`chat:stash`,[$p]:`chat:imagePaste`}},{context:`Autocomplete`,bindings:{tab:`autocomplete:accept`,escape:`autocomplete:dismiss`,up:`autocomplete:previous`,down:`autocomplete:next`}},{context:`Settings`,bindings:{escape:`confirm:no`,up:`select:previous`,down:`select:next`,k:`select:previous`,j:`select:next`,"ctrl+p":`select:previous`,"ctrl+n":`select:next`,left:`select:previousValue`,right:`select:nextValue`,space:`select:accept`,enter:`settings:close`,"/":`settings:search`,r:`settings:retry`}},{context:`Confirmation`,bindings:{enter:`confirm:yes`,escape:`confirm:no`,up:`confirm:previous`,down:`confirm:next`,tab:`confirm:nextField`,space:`confirm:toggle`,"shift+tab":`confirm:cycleMode`,"ctrl+e":`confirm:toggleExplanation`,"ctrl+d":`permission:toggleDebug`}},{context:`FormField`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,up:`tabs:previous`,down:`tabs:next`}},{context:`Tabs`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,right:`tabs:next`,left:`tabs:previous`}},{context:`Transcript`,bindings:{"ctrl+e":`transcript:toggleShowAll`,"ctrl+c":`transcript:exit`,escape:`transcript:exit`,q:`transcript:exit`}},{context:`HistorySearch`,bindings:{"ctrl+r":`historySearch:next`,escape:`historySearch:accept`,tab:`historySearch:accept`,"ctrl+c":`historySearch:cancel`,enter:`historySearch:execute`}},{context:`Task`,bindings:{"ctrl+b":`task:background`}},{context:`ThemePicker`,bindings:{"ctrl+t":`theme:toggleSyntaxHighlighting`}},{context:`Scroll`,bindings:{pageup:`scroll:pageUp`,pagedown:`scroll:pageDown`,wheelup:`scroll:lineUp`,wheeldown:`scroll:lineDown`,"ctrl+home":`scroll:top`,"ctrl+end":`scroll:bottom`,"ctrl+shift+c":`selection:copy`,"cmd+c":`selection:copy`}},{context:`Help`,bindings:{escape:`help:dismiss`}},{context:`Attachments`,bindings:{right:`attachments:next`,left:`attachments:previous`,backspace:`attachments:remove`,delete:`attachments:remove`,down:`attachments:exit`,escape:`attachments:exit`}},{context:`Footer`,bindings:{up:`footer:up`,"ctrl+p":`footer:up`,down:`footer:down`,"ctrl+n":`footer:down`,right:`footer:next`,left:`footer:previous`,enter:`footer:openSelected`,escape:`footer:clearSelection`}},{context:`MessageSelector`,bindings:{up:`messageSelector:up`,down:`messageSelector:down`,k:`messageSelector:up`,j:`messageSelector:down`,"ctrl+p":`messageSelector:up`,"ctrl+n":`messageSelector:down`,"ctrl+up":`messageSelector:top`,"shift+up":`messageSelector:top`,"meta+up":`messageSelector:top`,"shift+k":`messageSelector:top`,"ctrl+down":`messageSelector:bottom`,"shift+down":`messageSelector:bottom`,"meta+down":`messageSelector:bottom`,"shift+j":`messageSelector:bottom`,enter:`messageSelector:select`}},{context:`DiffDialog`,bindings:{escape:`diff:dismiss`,left:`diff:previousSource`,right:`diff:nextSource`,up:`diff:previousFile`,down:`diff:nextFile`,enter:`diff:viewDetails`}},{context:`ModelPicker`,bindings:{space:`modelPicker:toggle1M`}},{context:`Select`,bindings:{up:`select:previous`,down:`select:next`,j:`select:next`,k:`select:previous`,"ctrl+n":`select:next`,"ctrl+p":`select:previous`,enter:`select:accept`,escape:`select:cancel`}},{context:`Plugin`,bindings:{space:`plugin:toggle`,i:`plugin:install`}}]})),rm=n((()=>{I()}));function Npe(){let e=la(),t=[...am,...om];return e===`macos`&&t.push(...sm),t}function im(e){return e.trim().split(/\s+/).map(Ppe).join(` `)}function Ppe(e){let t=e.split(`+`),n=[],r=``;for(let e of t){let t=e.trim().toLowerCase();[`ctrl`,`control`,`alt`,`opt`,`option`,`meta`,`cmd`,`command`,`shift`].includes(t)?t===`control`?n.push(`ctrl`):t===`option`||t===`opt`?n.push(`alt`):t===`command`||t===`cmd`?n.push(`cmd`):n.push(t):r=t}return n.sort(),[...n,r].join(`+`)}var am,om,sm,Fpe=n((()=>{ua(),am=[{key:`ctrl+c`,reason:`Cannot be rebound - used for interrupt/exit (hardcoded)`,severity:`error`},{key:`ctrl+d`,reason:`Cannot be rebound - used for exit (hardcoded)`,severity:`error`},{key:`ctrl+m`,reason:`Cannot be rebound - identical to Enter in terminals (both send CR)`,severity:`error`}],om=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],sm=[{key:`cmd+c`,reason:`macOS system copy`,severity:`error`},{key:`cmd+v`,reason:`macOS system paste`,severity:`error`},{key:`cmd+x`,reason:`macOS system cut`,severity:`error`},{key:`cmd+q`,reason:`macOS quit application`,severity:`error`},{key:`cmd+w`,reason:`macOS close window/tab`,severity:`error`},{key:`cmd+tab`,reason:`macOS app switcher`,severity:`error`},{key:`cmd+space`,reason:`macOS Spotlight`,severity:`error`}]}));function Ipe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Lpe(e){return Array.isArray(e)&&e.every(Ipe)}function Rpe(e){return cm.includes(e)}function zpe(e){let t=e.toLowerCase().split(`+`);for(let n of t)if(!n.trim())return{type:`parse_error`,severity:`error`,message:`Empty key part in "${e}"`,key:e,suggestion:`Remove extra "+" characters`};let n=aee(e);return!n.key&&!n.ctrl&&!n.alt&&!n.shift&&!n.meta?{type:`parse_error`,severity:`error`,message:`Could not parse keystroke "${e}"`,key:e}:null}function Bpe(e,t){let n=[];if(typeof e!=`object`||!e)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} is not an object`}),n;let r=e,i=r.context,a;if(typeof i==`string`?Rpe(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${cm.join(`, `)}`}):n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "context" field`}),typeof r.bindings!=`object`||r.bindings===null)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "bindings" field`}),n;let o=r.bindings;for(let[e,t]of Object.entries(o)){let r=zpe(e);r&&(r.context=a,n.push(r)),t!==null&&typeof t!=`string`?n.push({type:`invalid_action`,severity:`error`,message:`Invalid action for "${e}": must be a string or null`,key:e,context:a}):typeof t==`string`&&t.startsWith(`command:`)&&(/^command:[a-zA-Z0-9:\-_]+$/.test(t)||n.push({type:`invalid_action`,severity:`warning`,message:`Invalid command binding "${t}" for "${e}": command name may only contain alphanumeric characters, colons, hyphens, and underscores`,key:e,context:a,action:t}),a&&a!==`Chat`&&n.push({type:`invalid_action`,severity:`warning`,message:`Command binding "${t}" must be in "Chat" context, not "${a}"`,key:e,context:a,action:t,suggestion:`Move this binding to a block with "context": "Chat"`}))}return n}function Vpe(e){let t=[],n=/"bindings"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,r;for(;(r=n.exec(e))!==null;){let n=r[1];if(!n)continue;let i=e.slice(0,r.index).match(/"context"\s*:\s*"([^"]+)"[^{]*$/)?.[1]??`unknown`,a=/"([^"]+)"\s*:/g,o=new Map,s;for(;(s=a.exec(n))!==null;){let e=s[1];if(!e)continue;let n=(o.get(e)??0)+1;o.set(e,n),n===2&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate key "${e}" in ${i} bindings`,key:e,context:i,suggestion:`This key appears multiple times in the same context. JSON uses the last value, earlier values are ignored.`})}}return t}function Hpe(e){let t=[];if(!Array.isArray(e))return t.push({type:`parse_error`,severity:`error`,message:`keybindings.json must contain an array`,suggestion:`Wrap your bindings in [ ]`}),t;for(let n=0;n<e.length;n++)t.push(...Bpe(e[n],n));return t}function Upe(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.context)??new Map;n.set(r.context,e);for(let[n,i]of Object.entries(r.bindings)){let a=im(n),o=e.get(a);o&&o!==i&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate binding "${n}" in ${r.context} context`,key:n,context:r.context,action:i??`null (unbind)`,suggestion:`Previously bound to "${o}". Only the last binding will be used.`}),e.set(a,i??`null`)}}return t}function Wpe(e){let t=[],n=Npe();for(let r of e){let e=fee(r.chord),i=im(e);for(let a of n)im(a.key)===i&&t.push({type:`reserved`,severity:a.severity,message:`"${e}" may not work: ${a.reason}`,key:e,context:r.context,action:r.action??void 0})}return t}function Gpe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>aee(e));t.push({chord:i,action:r,context:n.context})}return t}function Kpe(e,t){let n=[];if(n.push(...Hpe(e)),Lpe(e)){n.push(...Upe(e));let t=Gpe(e);n.push(...Wpe(t))}let r=new Set;return n.filter(e=>{let t=`${e.type}:${e.key}:${e.context}`;return r.has(t)?!1:(r.add(t),!0)})}var cm,qpe=n((()=>{rm(),Fpe(),cm=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function lm(){return!1}function Jpe(e){let t=new Date().toISOString().slice(0,10);ym!==t&&(ym=t,J(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function Ype(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Xpe(e){return Array.isArray(e)&&e.every(Ype)}function um(){return Y(p(),`keybindings.json`)}function dm(){return Qe(tm)}async function Zpe(){let e=dm();if(!lm())return{bindings:e,warnings:[]};let t=um();try{let n=await Ol(t,`utf-8`),r=kn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!Xpe(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=Qe(i);U(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];Jpe(a.length);let s=[...Vpe(n),...Kpe(i,o)];return s.length>0&&U(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return xn(n)?{bindings:e,warnings:[]}:(U(`[keybindings] Error loading ${t}: ${H(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${H(n)}`}]})}}function Qpe(){return gm||fm().bindings}function fm(){if(gm)return{bindings:gm,warnings:_m};let e=dm();if(!lm())return gm=e,_m=[],{bindings:gm,warnings:_m};let t=um();try{let n=dl(t,`utf-8`),r=kn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return gm=e,_m=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:gm,warnings:_m};if(!Xpe(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return gm=e,_m=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:gm,warnings:_m}}let a=Qe(i);return U(`[keybindings] Loaded ${a.length} user bindings from ${t}`),gm=[...e,...a],Jpe(a.length),_m=[...Vpe(n),...Kpe(i,gm)],_m.length>0&&U(`[keybindings] Found ${_m.length} validation issue(s)`),{bindings:gm,warnings:_m}}catch{return gm=e,_m=[],{bindings:gm,warnings:_m}}}async function $pe(){if(mm||hm)return;if(!lm()){U(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=um(),t=qc(e);try{if(!(await Nl(t)).isDirectory()){U(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{U(`[keybindings] Not watching: ${t} does not exist`);return}mm=!0,U(`[keybindings] Watching for changes to ${e}`),pm=Zp.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:ime,pollInterval:ame},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),pm.on(`add`,tme),pm.on(`change`,tme),pm.on(`unlink`,nme),Gn(async()=>eme())}function eme(){hm=!0,pm&&(pm.close(),pm=null),vm.clear()}async function tme(e){U(`[keybindings] Detected change to ${e}`);try{let e=await Zpe();gm=e.bindings,_m=e.warnings,vm.emit(e)}catch(e){U(`[keybindings] Error reloading: ${H(e)}`)}}function nme(e){U(`[keybindings] Detected deletion of ${e}`);let t=dm();gm=t,_m=[],vm.emit({bindings:t,warnings:[]})}function rme(){return _m}var ime,ame,pm,mm,hm,gm,_m,vm,ym,ome,bm=n((()=>{Qp(),Da(),Jn(),W(),h(),On(),fn(),Yn(),nm(),rm(),qpe(),ime=500,ame=200,pm=null,mm=!1,hm=!1,gm=null,_m=[],vm=rn(),ym=null,ome=vm.subscribe})),xm,sme=n((()=>{bm(),xm={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>lm(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-B5kUoxvg.js`)}})),cme,lme=n((()=>{cme={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-_tBxhPV-.js`)}})),ume,dme=n((()=>{ume={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding--GCJWeeS.js`)).callOnboarding})}})),fme,pme=n((()=>{fme={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-BDo5qIK0.js`)}})),mme,hme=n((()=>{mme={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-Bbweh2hA.js`)}})),Sm,gme=n((()=>{Wt(),Sm={type:`local-jsx`,name:`session`,aliases:[`remote`],description:`显示远程会话的 URL 和二维码`,isEnabled:()=>bt(),get isHidden(){return!bt()},load:()=>import(`./session-CkuTMD_4.js`)}})),_me,vme=n((()=>{_me={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-BghnKnNo.js`)}})),yme,bme=n((()=>{yme={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-DwyWiaVc.js`)}})),xme,Sme=n((()=>{xme={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-BjFot03S.js`)}})),Cme,wme=n((()=>{Cme={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-CPucX8Xj.js`)).callLocalMemory})}})),Tme,Eme=n((()=>{Ar(),Tme={type:`local-jsx`,name:`terminal-setup`,description:pr.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:pr.terminal!==null&&pr.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-Ty8T8ePM.js`)}})),Cm,Dme=n((()=>{Cm={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-c6grxWNn.js`)}})),wm,Ome=n((()=>{wm={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-cFcxfuac.js`)}})),Tm,kme=n((()=>{Tm={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(tc(),e(Jse));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
+ `}]}}}));function Epe(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=zf.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Uf.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Uf.join(`, `)}`);return t.root=e,new Xf(t)}var zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Dpe=n((()=>{b(),zf={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Bf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:zf.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(Bf),Vf=`READDIRP_RECURSIVE_ERROR`,Hf=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Vf]),Uf=[zf.DIR_TYPE,zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE,zf.FILE_TYPE],Wf=new Set([zf.DIR_TYPE,zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE]),Gf=new Set([zf.EVERYTHING_TYPE,zf.FILE_DIR_TYPE,zf.FILE_TYPE]),Kf=e=>Hf.has(e.code),qf=process.platform===`win32`,Jf=e=>!0,Yf=e=>{if(e===void 0)return Jf;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Jf},Xf=class extends Tue{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark}),x(this,`parents`,void 0),x(this,`reading`,void 0),x(this,`parent`,void 0),x(this,`_stat`,void 0),x(this,`_maxDepth`,void 0),x(this,`_wantsDir`,void 0),x(this,`_wantsFile`,void 0),x(this,`_wantsEverything`,void 0),x(this,`_root`,void 0),x(this,`_isDirent`,void 0),x(this,`_statsProp`,void 0),x(this,`_rdOptions`,void 0),x(this,`_fileFilter`,void 0),x(this,`_directoryFilter`,void 0);let t={...Bf,...e},{root:n,type:r}=t;this._fileFilter=Yf(t.fileFilter),this._directoryFilter=Yf(t.directoryFilter);let i=t.lstat?Hl:Kl;qf?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Bf.depth,this._wantsDir=r?Wf.has(r):!1,this._wantsFile=r?Gf.has(r):!1,this._wantsEverything=r===zf.EVERYTHING_TYPE,this._root=cl(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await Wl(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=cl(ol(t,r));n={path:sl(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){Kf(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await Gl(t),n=await Hl(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===wle){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Vf,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}}}));function Zf(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Cp(il.resolve(e,r),dp,il.join(e,r))};try{return tue(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Ope=n((()=>{b(),Qf=`data`,$f=`close`,ep=()=>{},tp=process.platform,np=tp===`win32`,rp=tp===`darwin`,ip=tp===`linux`,ap=tp===`freebsd`,op=aue()===`OS400`,sp={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},cp=sp,lp=`watch`,up={lstat:Hl,stat:Kl},dp=`listeners`,fp=`errHandlers`,pp=`rawEmitters`,mp=[dp,fp,pp],hp=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),gp=e=>hp.has(il.extname(e).slice(1).toLowerCase()),_p=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},vp=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},yp=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},bp=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},xp=e=>e instanceof Set?e.size===0:!e,Sp=new Map,Cp=(e,t,n,r,i)=>{let a=Sp.get(e);a&&_p(a[t],e=>{e(n,r,i)})},wp=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Sp.get(t),c;if(!n.persistent)return c=Zf(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)vp(s,dp,i),vp(s,fp,a),vp(s,pp,o);else{if(c=Zf(e,n,Cp.bind(null,t,dp),a,Cp.bind(null,t,pp)),!c)return;c.on(cp.ERROR,async n=>{let r=Cp.bind(null,t,fp);if(s&&(s.watcherUnusable=!0),np&&n.code===`EPERM`)try{await(await Due(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Sp.set(t,s)}return()=>{bp(s,dp,i),bp(s,fp,a),bp(s,pp,o),xp(s.listeners)&&(s.watcher.close(),Sp.delete(t),mp.forEach(yp(s)),s.watcher=void 0,Object.freeze(s))}},Tp=new Map,Ep=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Tp.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(eue(t),o=void 0),o?(vp(o,dp,i),vp(o,pp,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:nue(t,n,(n,r)=>{_p(o.rawEmitters,e=>{e(cp.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&_p(o.listeners,t=>t(e,n))})},Tp.set(t,o)),()=>{bp(o,dp,i),bp(o,pp,a),xp(o.listeners)&&(Tp.delete(t),eue(t),o.options=o.watcher=void 0,Object.freeze(o))}},Dp=class{constructor(e){x(this,`fsw`,void 0),x(this,`_boundHandleError`,void 0),this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=il.dirname(e),i=il.basename(e);this.fsw._getWatchedDir(r).add(i);let a=il.resolve(e),o={persistent:n.persistent};t||(t=ep);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&gp(i)?n.binaryInterval:n.interval,s=Ep(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=wp(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=il.dirname(e),i=il.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(lp,e,5)){if(!n||n.mtimeMs===0)try{let n=await Kl(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(cp.CHANGE,e,n),(rp||ip||ap)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(cp.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(cp.ADD,e,0))return;this.fsw._emit(cp.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await Gl(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(cp.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(cp.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=il.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(Qf,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=il.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,s))){if(this.fsw.closed){u=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),d=il.join(i,il.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(cp.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!u)return s();u.once(`end`,()=>{if(this.fsw.closed){u=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(il.dirname(e)),c=s.has(il.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(cp.ADD_DIR,e,t),s.add(il.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await up[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=il.resolve(e),l=s?await Gl(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await Gl(e):e;if(this.fsw.closed)return;let a=il.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(cp.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(il.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}}}));function Op(e){return Array.isArray(e)?e:[e]}function kpe(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=il.relative(e.path,t);return n?!n.startsWith(`..`)&&!il.isAbsolute(n):!1}return!1}:()=>!1}function Ape(e){if(typeof e!=`string`)throw Error(`string expected`);e=il.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(Ip,`/`),t&&(e=`/`+e),e}function kp(e,t,n){let r=Ape(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function jpe(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Op(e).map(e=>kpe(e));return t==null?(e,t)=>kp(n,e,t):kp(n,t)}function Mpe(e,t={}){let n=new Xp(t);return n.add(e),n}var Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp=n((()=>{Dpe(),Ope(),b(),Ap=`/`,jp=`//`,Mp=`.`,Np=`..`,Pp=`string`,Fp=/\\/g,Ip=/\/\//g,Lp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Rp=/^\.[/\\]/,zp=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),Bp=e=>{let t=Op(e).flat();if(!t.every(e=>typeof e===Pp))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Hp)},Vp=e=>{let t=e.replace(Fp,Ap),n=!1;return t.startsWith(jp)&&(n=!0),t=t.replace(Ip,Ap),n&&(t=Ap+t),t},Hp=e=>Vp(il.normalize(Vp(e))),Up=(e=``)=>t=>typeof t==`string`?Hp(il.isAbsolute(t)?t:il.join(e,t)):t,Wp=(e,t)=>il.isAbsolute(e)?e:il.join(t,e),Gp=Object.freeze(new Set),Kp=class{constructor(e,t){x(this,`path`,void 0),x(this,`_removeWatcher`,void 0),x(this,`items`,void 0),this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Mp&&e!==Np&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Wl(n)}catch{this._removeWatcher&&this._removeWatcher(il.dirname(n),il.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=ep,this.items=Gp,Object.freeze(this)}},qp=`stat`,Jp=`lstat`,Yp=class{constructor(e,t,n){x(this,`fsw`,void 0),x(this,`path`,void 0),x(this,`watchPath`,void 0),x(this,`fullWatchPath`,void 0),x(this,`dirParts`,void 0),x(this,`followSymlinks`,void 0),x(this,`statMethod`,void 0),this.fsw=n;let r=e;this.path=e=e.replace(Rp,``),this.watchPath=r,this.fullWatchPath=il.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?qp:Jp}entryPath(e){return il.join(this.watchPath,il.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Xp=class extends Sue{constructor(e={}){super(),x(this,`closed`,void 0),x(this,`options`,void 0),x(this,`_closers`,void 0),x(this,`_ignoredPaths`,void 0),x(this,`_throttled`,void 0),x(this,`_streams`,void 0),x(this,`_symlinkPaths`,void 0),x(this,`_watched`,void 0),x(this,`_pendingWrites`,void 0),x(this,`_pendingUnlinks`,void 0),x(this,`_readyCount`,void 0),x(this,`_emitReady`,void 0),x(this,`_closePromise`,void 0),x(this,`_userIgnored`,void 0),x(this,`_readyEmitted`,void 0),x(this,`_emitRaw`,void 0),x(this,`_boundRemove`,void 0),x(this,`_nodeFsHandler`,void 0),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Op(e.ignored):Op([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};op&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=ep,this._readyEmitted=!0,process.nextTick(()=>this.emit(sp.READY)))},this._emitRaw=(...e)=>this.emit(sp.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Dp(this),Object.freeze(r)}_addIgnoredPath(e){if(zp(e)){for(let t of this._ignoredPaths)if(zp(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)zp(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Bp(e);return r&&(i=i.map(e=>Wp(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(il.dirname(e),il.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Bp(e),{cwd:n}=this.options;return t.forEach(e=>{!il.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=il.join(n,e)),e=il.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?il.relative(this.options.cwd,n):n)||Mp;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==sp.ERROR&&this.emit(sp.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;np&&(t=il.normalize(t)),r.cwd&&(t=il.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===sp.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(sp.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===sp.ADD&&this._pendingUnlinks.has(t)&&(e=sp.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===sp.ADD||e===sp.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=sp.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===sp.CHANGE&&!this._throttle(sp.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===sp.ADD||e===sp.ADD_DIR||e===sp.CHANGE)){let e=r.cwd?il.join(r.cwd,t):t,n;try{n=await Kl(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(sp.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!il.isAbsolute(e)&&(s=il.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){Zle(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&Lp.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Up(e)),n=[...[...this._ignoredPaths].map(Up(e)),...t];this._userIgnored=jpe(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Yp(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=il.resolve(e);return this._watched.has(t)||this._watched.set(t,new Kp(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=il.join(e,t),i=il.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=il.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===sp.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?sp.UNLINK_DIR:sp.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=il.dirname(e);this._getWatchedDir(t).remove(il.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Epe(e,{type:sp.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once($f,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Zp={watch:Mpe,FSWatcher:Xp}})),$p,em,tm,nm=n((()=>{Yse(),Ua(),ua(),$p=la()===`windows`?`alt+v`:`ctrl+v`,em=la()!==`windows`||(sae()?zse(process.versions.bun,`>=1.2.23`):zse(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,tm=[{context:`Global`,bindings:{"ctrl+c":`app:interrupt`,"ctrl+d":`app:exit`,"ctrl+l":`app:redraw`,"ctrl+t":`app:toggleTodos`,"ctrl+o":`app:toggleTranscript`,"ctrl+shift+o":`app:toggleTeammatePreview`,"ctrl+r":`history:search`}},{context:`Chat`,bindings:{escape:`chat:cancel`,"ctrl+x ctrl+k":`chat:killAgents`,[em]:`chat:cycleMode`,"meta+p":`chat:modelPicker`,"meta+o":`chat:fastMode`,"meta+t":`chat:thinkingToggle`,enter:`chat:submit`,up:`history:previous`,down:`history:next`,"ctrl+_":`chat:undo`,"ctrl+shift+-":`chat:undo`,"ctrl+x ctrl+e":`chat:externalEditor`,"ctrl+g":`chat:externalEditor`,"ctrl+s":`chat:stash`,[$p]:`chat:imagePaste`}},{context:`Autocomplete`,bindings:{tab:`autocomplete:accept`,escape:`autocomplete:dismiss`,up:`autocomplete:previous`,down:`autocomplete:next`}},{context:`Settings`,bindings:{escape:`confirm:no`,up:`select:previous`,down:`select:next`,k:`select:previous`,j:`select:next`,"ctrl+p":`select:previous`,"ctrl+n":`select:next`,left:`select:previousValue`,right:`select:nextValue`,space:`select:accept`,enter:`settings:close`,"/":`settings:search`,r:`settings:retry`}},{context:`Confirmation`,bindings:{enter:`confirm:yes`,escape:`confirm:no`,up:`confirm:previous`,down:`confirm:next`,tab:`confirm:nextField`,space:`confirm:toggle`,"shift+tab":`confirm:cycleMode`,"ctrl+e":`confirm:toggleExplanation`,"ctrl+d":`permission:toggleDebug`}},{context:`FormField`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,up:`tabs:previous`,down:`tabs:next`}},{context:`Tabs`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,right:`tabs:next`,left:`tabs:previous`}},{context:`Transcript`,bindings:{"ctrl+e":`transcript:toggleShowAll`,"ctrl+c":`transcript:exit`,escape:`transcript:exit`,q:`transcript:exit`}},{context:`HistorySearch`,bindings:{"ctrl+r":`historySearch:next`,escape:`historySearch:accept`,tab:`historySearch:accept`,"ctrl+c":`historySearch:cancel`,enter:`historySearch:execute`}},{context:`Task`,bindings:{"ctrl+b":`task:background`}},{context:`ThemePicker`,bindings:{"ctrl+t":`theme:toggleSyntaxHighlighting`}},{context:`Scroll`,bindings:{pageup:`scroll:pageUp`,pagedown:`scroll:pageDown`,wheelup:`scroll:lineUp`,wheeldown:`scroll:lineDown`,"ctrl+home":`scroll:top`,"ctrl+end":`scroll:bottom`,"ctrl+shift+c":`selection:copy`,"cmd+c":`selection:copy`}},{context:`Help`,bindings:{escape:`help:dismiss`}},{context:`Attachments`,bindings:{right:`attachments:next`,left:`attachments:previous`,backspace:`attachments:remove`,delete:`attachments:remove`,down:`attachments:exit`,escape:`attachments:exit`}},{context:`Footer`,bindings:{up:`footer:up`,"ctrl+p":`footer:up`,down:`footer:down`,"ctrl+n":`footer:down`,right:`footer:next`,left:`footer:previous`,enter:`footer:openSelected`,escape:`footer:clearSelection`}},{context:`MessageSelector`,bindings:{up:`messageSelector:up`,down:`messageSelector:down`,k:`messageSelector:up`,j:`messageSelector:down`,"ctrl+p":`messageSelector:up`,"ctrl+n":`messageSelector:down`,"ctrl+up":`messageSelector:top`,"shift+up":`messageSelector:top`,"meta+up":`messageSelector:top`,"shift+k":`messageSelector:top`,"ctrl+down":`messageSelector:bottom`,"shift+down":`messageSelector:bottom`,"meta+down":`messageSelector:bottom`,"shift+j":`messageSelector:bottom`,enter:`messageSelector:select`}},{context:`DiffDialog`,bindings:{escape:`diff:dismiss`,left:`diff:previousSource`,right:`diff:nextSource`,up:`diff:previousFile`,down:`diff:nextFile`,enter:`diff:viewDetails`}},{context:`ModelPicker`,bindings:{space:`modelPicker:toggle1M`}},{context:`Select`,bindings:{up:`select:previous`,down:`select:next`,j:`select:next`,k:`select:previous`,"ctrl+n":`select:next`,"ctrl+p":`select:previous`,enter:`select:accept`,escape:`select:cancel`}},{context:`Plugin`,bindings:{space:`plugin:toggle`,i:`plugin:install`}}]})),rm=n((()=>{I()}));function Npe(){let e=la(),t=[...am,...om];return e===`macos`&&t.push(...sm),t}function im(e){return e.trim().split(/\s+/).map(Ppe).join(` `)}function Ppe(e){let t=e.split(`+`),n=[],r=``;for(let e of t){let t=e.trim().toLowerCase();[`ctrl`,`control`,`alt`,`opt`,`option`,`meta`,`cmd`,`command`,`shift`].includes(t)?t===`control`?n.push(`ctrl`):t===`option`||t===`opt`?n.push(`alt`):t===`command`||t===`cmd`?n.push(`cmd`):n.push(t):r=t}return n.sort(),[...n,r].join(`+`)}var am,om,sm,Fpe=n((()=>{ua(),am=[{key:`ctrl+c`,reason:`Cannot be rebound - used for interrupt/exit (hardcoded)`,severity:`error`},{key:`ctrl+d`,reason:`Cannot be rebound - used for exit (hardcoded)`,severity:`error`},{key:`ctrl+m`,reason:`Cannot be rebound - identical to Enter in terminals (both send CR)`,severity:`error`}],om=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],sm=[{key:`cmd+c`,reason:`macOS system copy`,severity:`error`},{key:`cmd+v`,reason:`macOS system paste`,severity:`error`},{key:`cmd+x`,reason:`macOS system cut`,severity:`error`},{key:`cmd+q`,reason:`macOS quit application`,severity:`error`},{key:`cmd+w`,reason:`macOS close window/tab`,severity:`error`},{key:`cmd+tab`,reason:`macOS app switcher`,severity:`error`},{key:`cmd+space`,reason:`macOS Spotlight`,severity:`error`}]}));function Ipe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Lpe(e){return Array.isArray(e)&&e.every(Ipe)}function Rpe(e){return cm.includes(e)}function zpe(e){let t=e.toLowerCase().split(`+`);for(let n of t)if(!n.trim())return{type:`parse_error`,severity:`error`,message:`Empty key part in "${e}"`,key:e,suggestion:`Remove extra "+" characters`};let n=aee(e);return!n.key&&!n.ctrl&&!n.alt&&!n.shift&&!n.meta?{type:`parse_error`,severity:`error`,message:`Could not parse keystroke "${e}"`,key:e}:null}function Bpe(e,t){let n=[];if(typeof e!=`object`||!e)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} is not an object`}),n;let r=e,i=r.context,a;if(typeof i==`string`?Rpe(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${cm.join(`, `)}`}):n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "context" field`}),typeof r.bindings!=`object`||r.bindings===null)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "bindings" field`}),n;let o=r.bindings;for(let[e,t]of Object.entries(o)){let r=zpe(e);r&&(r.context=a,n.push(r)),t!==null&&typeof t!=`string`?n.push({type:`invalid_action`,severity:`error`,message:`Invalid action for "${e}": must be a string or null`,key:e,context:a}):typeof t==`string`&&t.startsWith(`command:`)&&(/^command:[a-zA-Z0-9:\-_]+$/.test(t)||n.push({type:`invalid_action`,severity:`warning`,message:`Invalid command binding "${t}" for "${e}": command name may only contain alphanumeric characters, colons, hyphens, and underscores`,key:e,context:a,action:t}),a&&a!==`Chat`&&n.push({type:`invalid_action`,severity:`warning`,message:`Command binding "${t}" must be in "Chat" context, not "${a}"`,key:e,context:a,action:t,suggestion:`Move this binding to a block with "context": "Chat"`}))}return n}function Vpe(e){let t=[],n=/"bindings"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,r;for(;(r=n.exec(e))!==null;){let n=r[1];if(!n)continue;let i=e.slice(0,r.index).match(/"context"\s*:\s*"([^"]+)"[^{]*$/)?.[1]??`unknown`,a=/"([^"]+)"\s*:/g,o=new Map,s;for(;(s=a.exec(n))!==null;){let e=s[1];if(!e)continue;let n=(o.get(e)??0)+1;o.set(e,n),n===2&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate key "${e}" in ${i} bindings`,key:e,context:i,suggestion:`This key appears multiple times in the same context. JSON uses the last value, earlier values are ignored.`})}}return t}function Hpe(e){let t=[];if(!Array.isArray(e))return t.push({type:`parse_error`,severity:`error`,message:`keybindings.json must contain an array`,suggestion:`Wrap your bindings in [ ]`}),t;for(let n=0;n<e.length;n++)t.push(...Bpe(e[n],n));return t}function Upe(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.context)??new Map;n.set(r.context,e);for(let[n,i]of Object.entries(r.bindings)){let a=im(n),o=e.get(a);o&&o!==i&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate binding "${n}" in ${r.context} context`,key:n,context:r.context,action:i??`null (unbind)`,suggestion:`Previously bound to "${o}". Only the last binding will be used.`}),e.set(a,i??`null`)}}return t}function Wpe(e){let t=[],n=Npe();for(let r of e){let e=fee(r.chord),i=im(e);for(let a of n)im(a.key)===i&&t.push({type:`reserved`,severity:a.severity,message:`"${e}" may not work: ${a.reason}`,key:e,context:r.context,action:r.action??void 0})}return t}function Gpe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>aee(e));t.push({chord:i,action:r,context:n.context})}return t}function Kpe(e,t){let n=[];if(n.push(...Hpe(e)),Lpe(e)){n.push(...Upe(e));let t=Gpe(e);n.push(...Wpe(t))}let r=new Set;return n.filter(e=>{let t=`${e.type}:${e.key}:${e.context}`;return r.has(t)?!1:(r.add(t),!0)})}var cm,qpe=n((()=>{rm(),Fpe(),cm=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function lm(){return!1}function Jpe(e){let t=new Date().toISOString().slice(0,10);ym!==t&&(ym=t,J(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function Ype(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Xpe(e){return Array.isArray(e)&&e.every(Ype)}function um(){return Y(p(),`keybindings.json`)}function dm(){return Qe(tm)}async function Zpe(){let e=dm();if(!lm())return{bindings:e,warnings:[]};let t=um();try{let n=await Ol(t,`utf-8`),r=kn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!Xpe(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=Qe(i);U(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];Jpe(a.length);let s=[...Vpe(n),...Kpe(i,o)];return s.length>0&&U(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return xn(n)?{bindings:e,warnings:[]}:(U(`[keybindings] Error loading ${t}: ${H(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${H(n)}`}]})}}function Qpe(){return gm||fm().bindings}function fm(){if(gm)return{bindings:gm,warnings:_m};let e=dm();if(!lm())return gm=e,_m=[],{bindings:gm,warnings:_m};let t=um();try{let n=dl(t,`utf-8`),r=kn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return gm=e,_m=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:gm,warnings:_m};if(!Xpe(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return gm=e,_m=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:gm,warnings:_m}}let a=Qe(i);return U(`[keybindings] Loaded ${a.length} user bindings from ${t}`),gm=[...e,...a],Jpe(a.length),_m=[...Vpe(n),...Kpe(i,gm)],_m.length>0&&U(`[keybindings] Found ${_m.length} validation issue(s)`),{bindings:gm,warnings:_m}}catch{return gm=e,_m=[],{bindings:gm,warnings:_m}}}async function $pe(){if(mm||hm)return;if(!lm()){U(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=um(),t=qc(e);try{if(!(await Nl(t)).isDirectory()){U(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{U(`[keybindings] Not watching: ${t} does not exist`);return}mm=!0,U(`[keybindings] Watching for changes to ${e}`),pm=Zp.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:ime,pollInterval:ame},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),pm.on(`add`,tme),pm.on(`change`,tme),pm.on(`unlink`,nme),Gn(async()=>eme())}function eme(){hm=!0,pm&&(pm.close(),pm=null),vm.clear()}async function tme(e){U(`[keybindings] Detected change to ${e}`);try{let e=await Zpe();gm=e.bindings,_m=e.warnings,vm.emit(e)}catch(e){U(`[keybindings] Error reloading: ${H(e)}`)}}function nme(e){U(`[keybindings] Detected deletion of ${e}`);let t=dm();gm=t,_m=[],vm.emit({bindings:t,warnings:[]})}function rme(){return _m}var ime,ame,pm,mm,hm,gm,_m,vm,ym,ome,bm=n((()=>{Qp(),Da(),Jn(),W(),h(),On(),fn(),Yn(),nm(),rm(),qpe(),ime=500,ame=200,pm=null,mm=!1,hm=!1,gm=null,_m=[],vm=rn(),ym=null,ome=vm.subscribe})),xm,sme=n((()=>{bm(),xm={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>lm(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-Ch5lzNB8.js`)}})),cme,lme=n((()=>{cme={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-BA8XQ6h1.js`)}})),ume,dme=n((()=>{ume={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-DHOylaqn.js`)).callOnboarding})}})),fme,pme=n((()=>{fme={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-mDtCTbnD.js`)}})),mme,hme=n((()=>{mme={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-DRvz4QFs.js`)}})),Sm,gme=n((()=>{Wt(),Sm={type:`local-jsx`,name:`session`,aliases:[`remote`],description:`显示远程会话的 URL 和二维码`,isEnabled:()=>bt(),get isHidden(){return!bt()},load:()=>import(`./session-COVyD8UU.js`)}})),_me,vme=n((()=>{_me={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-DZRBy7vT.js`)}})),yme,bme=n((()=>{yme={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-CZYD3NGb.js`)}})),xme,Sme=n((()=>{xme={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-CIUuwrX4.js`)}})),Cme,wme=n((()=>{Cme={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-DsaijVcO.js`)).callLocalMemory})}})),Tme,Eme=n((()=>{Ar(),Tme={type:`local-jsx`,name:`terminal-setup`,description:pr.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:pr.terminal!==null&&pr.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-DDvQ0K5e.js`)}})),Cm,Dme=n((()=>{Cm={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-Nwii7354.js`)}})),wm,Ome=n((()=>{wm={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-s-wmybpU.js`)}})),Tm,kme=n((()=>{Tm={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(tc(),e(Jse));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}})}})),Ame,jme=n((()=>{Ame={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-rW1mEYtm.js`)}})),Mme,Nme=n((()=>{Mme={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-B09SOyra.js`)}})),Pme,Fme=n((()=>{Pme={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions--iKUbWBw.js`)}})),Em,Ime=n((()=>{Em={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-DiHCGXhM.js`)}}));function Lme(){return!1}var Rme=n((()=>{})),zme,Bme=n((()=>{Ro(),Rme(),zme={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${fae} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>Xo(),get isHidden(){return!Xo()},argumentHint:`[on|off]`,get immediate(){return Lme()},load:()=>import(`./fast-BVABmasw.js`)}})),Vme,Hme=n((()=>{Vme={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-BI4NY5IC.js`)}})),Ume,Wme=n((()=>{Ume={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-BOWBZo5K.js`)}})),Gme,Kme=n((()=>{Gme={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-BYQO6DbG.js`)}})),qme,Jme=n((()=>{qme={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-BeC4D7XF.js`)}})),Yme,Xme=n((()=>{Yme={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-GdqFZblC.js`)}})),Zme,Qme=n((()=>{Zme={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),$me,ehe,the=n((()=>{$me=async()=>({type:`text`,value:`0.0.14 (built 2026-08-13T18:38:19.460Z)`}),ehe={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:$me})}})),nhe=i({isSkillSearchCompiledIn:()=>rhe,isSkillSearchEnabled:()=>Dm});function rhe(){return!1}function Dm(){return process.env.SKILL_SEARCH_ENABLED===`1`}var Om=n((()=>{})),ihe,ahe=n((()=>{Om(),ihe={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>rhe(),isHidden:!1,load:()=>import(`./skillSearchPanel-Cxr1QQn4.js`)}}));function X(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 km=n((()=>{}));function ohe(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 Jl(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{X(`Invalid parent proxy URL, ignoring: ${fhe(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:she(r)}}function she(e){let t={all:!1,suffixes:[],cidr:new Iue};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=Xl(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=Xl(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 Am(e,t){let n=Nm(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=Xl(n);if(r&&ghe.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 jm(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function che(e){let{destHost:t,destPort:n}=e,r=Nm(t);if(!Pm(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=Xl(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??Fm,()=>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}})}})),Ame,jme=n((()=>{Ame={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-BHhkQbvu.js`)}})),Mme,Nme=n((()=>{Mme={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-D4E2WQVn.js`)}})),Pme,Fme=n((()=>{Pme={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions-CJUBfBTr.js`)}})),Em,Ime=n((()=>{Em={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-eFur8bdH.js`)}}));function Lme(){return!1}var Rme=n((()=>{})),zme,Bme=n((()=>{Ro(),Rme(),zme={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${fae} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>Xo(),get isHidden(){return!Xo()},argumentHint:`[on|off]`,get immediate(){return Lme()},load:()=>import(`./fast-CuUjONVV.js`)}})),Vme,Hme=n((()=>{Vme={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-CJ17byYD.js`)}})),Ume,Wme=n((()=>{Ume={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-BWbCrXBJ.js`)}})),Gme,Kme=n((()=>{Gme={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-DMyQUXwl.js`)}})),qme,Jme=n((()=>{qme={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-fYLRLdOY.js`)}})),Yme,Xme=n((()=>{Yme={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-6xcH3dLg.js`)}})),Zme,Qme=n((()=>{Zme={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),$me,ehe,the=n((()=>{$me=async()=>({type:`text`,value:`0.0.15 (built 2026-08-14T02:22:06.766Z)`}),ehe={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:$me})}})),nhe=i({isSkillSearchCompiledIn:()=>rhe,isSkillSearchEnabled:()=>Dm});function rhe(){return!1}function Dm(){return process.env.SKILL_SEARCH_ENABLED===`1`}var Om=n((()=>{})),ihe,ahe=n((()=>{Om(),ihe={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>rhe(),isHidden:!1,load:()=>import(`./skillSearchPanel-CneXymsb.js`)}}));function X(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 km=n((()=>{}));function ohe(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 Jl(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{X(`Invalid parent proxy URL, ignoring: ${fhe(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:she(r)}}function she(e){let t={all:!1,suffixes:[],cidr:new Iue};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=Xl(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=Xl(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 Am(e,t){let n=Nm(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=Xl(n);if(r&&ghe.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 jm(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function che(e){let{destHost:t,destPort:n}=e,r=Nm(t);if(!Pm(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=Xl(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??Fm,()=>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
@@ -409,7 +409,7 @@ Connection blocked by network allowlist`);return}let c=e.getMitmSocketPath?.(o),
409
409
  `);return`${o} -c ${Ah.quote([i])}`}else{let e=[...s,`eval ${Ah.quote([n])}`].join(`
410
410
  `);return`${o} -c ${Ah.quote([e])}`}}async function c_e(e,t,n={command:`rg`},r=jh,i=!1,a){let o=[],s=[],c=[];if(t){o.push(`--ro-bind`,`/`,`/`);for(let e of t.allowOnly||[]){let t=vh(e);if(X(`[Sandbox Linux] Processing write path: ${e} -> ${t}`),t.startsWith(`/dev/`)){X(`[Sandbox Linux] Skipping /dev path: ${t}`);continue}if(!ll.existsSync(t)){X(`[Sandbox Linux] Skipping non-existent write path: ${t}`);continue}try{let n=ll.realpathSync(t);if(n!==t.replace(/\/+$/,``)&&_h(t,n)){X(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${e} -> ${n}`);continue}}catch{X(`[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 r_e(n,r,i,a)],l=new Set;for(let t of e){let e=vh(t);if(l.has(e)||(l.add(e),e.startsWith(`/dev/`)))continue;let n=e_e(e,s);if(n){c.push(`--ro-bind`,`/dev/null`,n),X(`[Sandbox Linux] Mounted /dev/null at symlink ${n} to prevent symlink replacement attack`);continue}if(!ll.existsSync(e)){if(t_e(e)){X(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${e}`);continue}let t=al.dirname(e);for(;t!==`/`&&!ll.existsSync(t);)t=al.dirname(t);if(s.some(n=>t.startsWith(n+`/`)||t===n||e.startsWith(n+`/`))){let t=n_e(e);if(t!==e){let n=ll.mkdtempSync(al.join(_l(),`claude-empty-`));c.push(`--ro-bind`,n,t),Nh.add(t),kh(),X(`[Sandbox Linux] Mounted empty dir at ${t} to block creation of ${e}`)}else c.push(`--ro-bind`,`/dev/null`,t),Nh.add(t),kh(),X(`[Sandbox Linux] Mounted /dev/null at ${t} to block creation of ${e}`)}else X(`[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):X(`[Sandbox Linux] Skipping deny path not within allowed paths: ${e}`)}}else o.push(`--bind`,`/`,`/`);let l=[],u=(e?.allowWithinDeny||[]).map(e=>vh(e)),d=new Set([`proc`,`dev`,`sys`]);for(let t of e?.denyOnly||[])if(vh(t)===`/`)for(let e of ll.readdirSync(`/`))d.has(e)||l.push(`/`+e);else l.push(t);ll.existsSync(`/etc/ssh/ssh_config.d`)&&l.push(`/etc/ssh/ssh_config.d`);for(let e of l){let t=vh(e);if(!ll.existsSync(t)){X(`[Sandbox Linux] Skipping non-existent read deny path: ${t}`);continue}let n=t===`/`?`/`:t+`/`;if(ll.statSync(t).isDirectory()){o.push(`--tmpfs`,t);for(let e of s)(e.startsWith(n)||e===t)&&(o.push(`--bind`,e,e),X(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${e}`));for(let e of u)if(e.startsWith(n)||e===t){if(!ll.existsSync(e)){X(`[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),X(`[Sandbox Linux] Re-allowed read access within denied region: ${e}`)}}else{if(u.some(e=>t===e||t.startsWith(e+`/`))){X(`[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 l_e(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=jh,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)X(`[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled`);else{b=Qge(h?.bpfPath)??void 0;let e=Th(h?.applyPath);!b||!e?(X(`[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/`)||(Mh.add(b),kh()),X(`[Sandbox Linux] Generated seccomp BPF filter for Unix socket blocking`))}if(n&&(y.push(`--unshare-net`),r&&i)){if(!ll.existsSync(r))throw Error(`Linux HTTP bridge socket does not exist: ${r}. The bridge process may have died. Try reinitializing the sandbox.`);if(!ll.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=Uge(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 c_e(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=zm(x);if(!S)throw Error(`Shell '${x}' not found in PATH`);if(y.push(`--`,S,`-c`),n&&r&&i){let e=s_e(r,i,t,b,S,h?.applyPath);y.push(e)}else if(b){let e=Th(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=Ah.quote([e,b,S,`-c`,t]);y.push(n)}else y.push(t);let C=Ah.quote([`bwrap`,...y]),w=[];return n&&w.push(`network`),(_||v)&&w.push(`filesystem`),b&&w.push(`seccomp(unix-block)`),X(`[Sandbox Linux] Wrapped command with bwrap (${w.join(`, `)} restrictions)`),C}catch(e){throw b&&!b.includes(`/vendor/seccomp/`)&&Mh.delete(b),e}}var Ah,jh,Mh,Nh,Ph,u_e=n((()=>{Ah=r(lce(),1),km(),Bm(),Bge(),Ch(),$ge(),jh=3,Mh=new Set,Nh=new Set,Ph=!1}));function d_e(e=!1){let t=process.cwd(),n=[];for(let e of Sh)n.push(Gc.resolve(t,e)),n.push(`**/${e}`);for(let e of Vge())n.push(Gc.resolve(t,e)),n.push(`**/${e}/**`);return n.push(Gc.resolve(t,`.git/hooks`)),n.push(`**/.git/hooks/**`),e||(n.push(Gc.resolve(t,`.git/config`)),n.push(`**/.git/config`)),[...new Set(n)]}function f_e(e){return`CMD64_${Wge(e)}_END_${Ih}`}function p_e(e){let t=[],n=Gc.dirname(e);for(;n!==`/`&&n!==`.`;){t.push(n);let e=Gc.dirname(n);if(e===n)break;n=e}return t}function m_e(e,t){let n=[];for(let r of e){let e=vh(r);if(hh(e)){let r=bh(e);n.push(`(deny file-write-unlink`,` (regex ${Fh(r)})`,` (with message "${t}"))`);let i=e.split(/[*?[\]]/)[0];if(i&&i!==`/`){let e=i.endsWith(`/`)?i.slice(0,-1):Gc.dirname(i);n.push(`(deny file-write-unlink`,` (literal ${Fh(e)})`,` (with message "${t}"))`);for(let r of p_e(e))n.push(`(deny file-write-unlink`,` (literal ${Fh(r)})`,` (with message "${t}"))`)}}else{n.push(`(deny file-write-unlink`,` (subpath ${Fh(e)})`,` (with message "${t}"))`);for(let r of p_e(e))n.push(`(deny file-write-unlink`,` (literal ${Fh(r)})`,` (with message "${t}"))`)}}return n}function h_e(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=vh(i);if(e===`/`&&(r=!0),hh(e)){let r=bh(e);n.push(`(deny file-read*`,` (regex ${Fh(r)})`,` (with message "${t}"))`)}else n.push(`(deny file-read*`,` (subpath ${Fh(e)})`,` (with message "${t}"))`)}r&&n.push(`(allow file-read* (literal "/"))`);for(let r of e.allowWithinDeny||[]){let e=vh(r);if(hh(e)){let r=bh(e);n.push(`(allow file-read*`,` (regex ${Fh(r)})`,` (with message "${t}"))`)}else n.push(`(allow file-read*`,` (subpath ${Fh(e)})`,` (with message "${t}"))`)}return e.denyOnly.length>0&&n.push(`(allow file-read-metadata`,` (vnode-type DIRECTORY))`),n.push(...m_e(e.denyOnly||[],t)),n}function g_e(e,t,n=!1){if(!e)return[`(allow file-write*)`];let r=[];for(let n of e.allowOnly||[]){let e=vh(n);if(hh(e)){let n=bh(e);r.push(`(allow file-write*`,` (regex ${Fh(n)})`,` (with message "${t}"))`)}else r.push(`(allow file-write*`,` (subpath ${Fh(e)})`,` (with message "${t}"))`)}let i=[...e.denyWithinAllow||[],...d_e(n)];for(let e of i){let n=vh(e);if(hh(n)){let e=bh(n);r.push(`(deny file-write*`,` (regex ${Fh(e)})`,` (with message "${t}"))`)}else r.push(`(deny file-write*`,` (subpath ${Fh(n)})`,` (with message "${t}"))`)}return r.push(...m_e(i,t)),r}function __e({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=vh(e);f.push(`(allow network-bind (local unix-socket (subpath ${Fh(t)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${Fh(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(...h_e(e,d)),f.push(``),f.push(`; File write`),f.push(...g_e(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(`
411
411
  `)}function Fh(e){return JSON.stringify(e)}function v_e(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=__e({readConfig:c,writeConfig:l,httpProxyPort:r,socksProxyPort:i,needsNetworkRestriction:n,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:u,allowGitConfig:d,enableWeakerNetworkIsolation:f,logTag:f_e(t)}),g=Uge(r,i),_=p||`bash`,v=zm(_);if(!v)throw Error(`Shell '${_}' not found in PATH`);let y=b_e.quote([`env`,...g,`sandbox-exec`,`-p`,h,v,`-c`,t]);return X(`[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 y_e(e,t){let n=/CMD64_(.+?)_END/,r=/Sandbox:\s+(.+)$/,i=t?.[`*`]||[],a=t?Object.entries(t).filter(([e])=>e!==`*`):[],o=Rl(`log`,[`stream`,`--predicate`,`(eventMessage ENDSWITH "${Ih}")`,`--style`,`compact`]);return o.stdout?.on(`data`,o=>{let s=o.toString().split(`
412
- `),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=Gge(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=>{X(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{X(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{X(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{X(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var b_e,Ih,x_e=n((()=>{b_e=r(lce(),1),km(),Bm(),Ch(),Ih=`_${Math.random().toString(36).slice(2,11)}_SBX`})),Lh,Rh=n((()=>{Ch(),Lh=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=Wge(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 S_e(){if(Kh)return;let e=()=>Bh().catch(e=>{X(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Kh=!0}function zh(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(Xl(Nm(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function C_e(e,t,n){if(!Vh)return X(`No config available, denying network request`),!1;if(!Pm(t))return X(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=phe(t)??t;for(let n of Vh.network.deniedDomains)if(zh(r,n))return X(`Denied by config rule: ${t}:${e}`),!1;for(let n of Vh.network.allowedDomains)if(zh(r,n))return X(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return X(`No matching config rule, denying: ${t}:${e}`),!1;X(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(X(`User allowed: ${t}:${e}`),!0):(X(`User denied: ${t}:${e}`),!1)}catch(e){return X(`Error in permission callback: ${e}`,{level:`error`}),!1}}function w_e(e){if(!Vh?.network.mitmProxy)return;let{socketPath:t,domains:n}=Vh.network.mitmProxy;for(let r of n)if(zh(e,r))return X(`Host ${e} matches MITM pattern ${r}`),t}async function T_e(e){return Hh=_he({filter:(t,n)=>C_e(t,n,e),getMitmSocketPath:w_e,parentProxy:Jh}),new Promise((e,t)=>{if(!Hh){t(Error(`HTTP proxy server undefined before listen`));return}let n=Hh;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),X(`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 E_e(e){return Uh=The({filter:(t,n)=>C_e(t,n,e),parentProxy:Jh}),new Promise((e,t)=>{if(!Uh){t(Error(`SOCKS proxy server undefined before listen`));return}Uh.listen(0,`127.0.0.1`).then(t=>{Uh?.unref(),e(t)}).catch(t)})}async function D_e(e,t,n=!1){if(Gh){await Gh;return}Vh=e,Jh=ohe(e.network.parentProxy),Jh&&X(`Parent proxy configured: http=${dhe(Jh.httpUrl)} https=${dhe(Jh.httpsUrl)}`);let r=A_e();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&ph()===`macos`&&(qh=y_e(Yh.addViolation.bind(Yh),Vh.ignoreViolations),X(`Started macOS sandbox log monitor`)),S_e(),Gh=(async()=>{try{let e;Vh.network.httpProxyPort===void 0?e=await T_e(t):(e=Vh.network.httpProxyPort,X(`Using external HTTP proxy on port ${e}`));let n;Vh.network.socksProxyPort===void 0?n=await E_e(t):(n=Vh.network.socksProxyPort,X(`Using external SOCKS proxy on port ${n}`));let r;ph()===`linux`&&(r=await o_e(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Wh=i,X(`Network infrastructure initialized`),i}catch(e){throw Gh=void 0,Wh=void 0,Bh().catch(e=>{X(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await Gh}function O_e(){let e=ph();return e===`linux`?Rge()!==`1`:e===`macos`}function k_e(){return Vh!==void 0}function A_e(e){if(!O_e())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??Vh?.ripgrep??{command:`rg`};if(zm(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),ph()===`linux`){let e=a_e(Vh?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function j_e(){if(!Vh)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of Vh.filesystem.denyRead){let n=gh(t);if(ph()===`linux`&&hh(n)){let n=xh(t);X(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of Vh.filesystem.allowRead??[]){let n=gh(e);if(ph()===`linux`&&hh(n)){let n=xh(e);X(`[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 M_e(){if(!Vh)return{allowOnly:yh(),denyWithinAllow:[]};let e=Vh.filesystem.allowWrite.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=Vh.filesystem.denyWrite.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...yh(),...e],denyWithinAllow:t}}function N_e(){if(!Vh)return{};let e=Vh.network.allowedDomains,t=Vh.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function P_e(){return Vh?.network?.allowUnixSockets}function F_e(){return Vh?.network?.allowAllUnixSockets}function I_e(){return Vh?.network?.allowLocalBinding}function L_e(){return Vh?.ignoreViolations}function R_e(){return Vh?.enableWeakerNestedSandbox}function z_e(){return Vh?.enableWeakerNetworkIsolation}function B_e(){return Vh?.ripgrep??{command:`rg`}}function V_e(){return Vh?.mandatoryDenySearchDepth??3}function H_e(){return Vh?.filesystem?.allowGitConfig??!1}function U_e(){return Vh?.seccomp}function W_e(){return Wh?.httpProxyPort}function G_e(){return Wh?.socksProxyPort}function K_e(){return Wh?.linuxBridge?.httpSocketPath}function q_e(){return Wh?.linuxBridge?.socksSocketPath}async function J_e(){if(!Vh)return!1;if(Gh)try{return await Gh,!0}catch{return!1}return Wh!==void 0}async function Y_e(e,t,n,r){let i=ph(),a=e=>e.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??Vh?.filesystem.allowWrite??[]),s={allowOnly:[...yh(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??Vh?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??Vh?.filesystem.denyRead??[],l=[];for(let e of c){let t=gh(e);ph()===`linux`&&hh(t)?l.push(...xh(e)):l.push(t)}let u=n?.filesystem?.allowRead??Vh?.filesystem.allowRead??[],d=[];for(let e of u){let t=gh(e);ph()===`linux`&&hh(t)?d.push(...xh(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||Vh?.network?.allowedDomains!==void 0,m=p,h=p;h&&await J_e();let g=n?.allowPty??Vh?.allowPty;switch(i){case`macos`:return v_e({command:e,needsNetworkRestriction:m,httpProxyPort:h?W_e():void 0,socksProxyPort:h?G_e():void 0,readConfig:f,writeConfig:s,allowUnixSockets:P_e(),allowAllUnixSockets:F_e(),allowLocalBinding:I_e(),ignoreViolations:L_e(),allowPty:g,allowGitConfig:H_e(),enableWeakerNetworkIsolation:z_e(),binShell:t});case`linux`:return l_e({command:e,needsNetworkRestriction:m,httpSocketPath:h?K_e():void 0,socksSocketPath:h?q_e():void 0,httpProxyPort:h?Wh?.httpProxyPort:void 0,socksProxyPort:h?Wh?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:R_e(),allowAllUnixSockets:F_e(),binShell:t,ripgrepConfig:B_e(),mandatoryDenySearchDepth:V_e(),allowGitConfig:H_e(),seccompConfig:U_e(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function X_e(){return Vh}function Z_e(e){Vh=pfe(e),Jh=ohe(e.network.parentProxy),X(`Sandbox configuration updated`)}function Q_e(){i_e()}async function Bh(){if(Q_e(),qh&&(qh(),qh=void 0),Wh?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Wh.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),X(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{X(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){X(`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`&&X(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),X(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{X(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){X(`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`&&X(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{ll.rmSync(e,{force:!0}),X(`Cleaned up HTTP socket`)}catch(e){X(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{ll.rmSync(t,{force:!0}),X(`Cleaned up SOCKS socket`)}catch(e){X(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Hh){let t=Hh,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&X(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(Uh){let t=Uh.close().catch(e=>{X(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Hh=void 0,Uh=void 0,Wh=void 0,Gh=void 0,Jh=void 0}function $_e(){return Yh}function eve(e,t){if(!Vh)return t;let n=Yh.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=gl+`<sandbox_violations>`+gl;for(let e of n)r+=e.line+gl;return r+=`</sandbox_violations>`,r}function tve(){if(ph()!==`linux`||!Vh)return[];let e=[],t=[...Vh.filesystem.allowWrite,...Vh.filesystem.denyWrite];for(let n of t)hh(gh(n))&&e.push(n);return e}var Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,nve=n((()=>{yhe(),Ehe(),km(),Bm(),fh(),mh(),u_e(),x_e(),Ch(),Rh(),Im(),Kh=!1,Yh=new Lh,Xh={initialize:D_e,isSupportedPlatform:O_e,isSandboxingEnabled:k_e,checkDependencies:A_e,getFsReadConfig:j_e,getFsWriteConfig:M_e,getNetworkRestrictionConfig:N_e,getAllowUnixSockets:P_e,getAllowLocalBinding:I_e,getIgnoreViolations:L_e,getEnableWeakerNestedSandbox:R_e,getProxyPort:W_e,getSocksProxyPort:G_e,getLinuxHttpSocketPath:K_e,getLinuxSocksSocketPath:q_e,waitForNetworkInitialization:J_e,wrapWithSandbox:Y_e,cleanupAfterCommand:Q_e,reset:Bh,getSandboxViolationStore:$_e,annotateStderrWithSandboxFailures:eve,getLinuxGlobPatternWarnings:tve,getConfig:X_e,updateConfig:Z_e}})),Zh,Qh,rve,ive,ave,ove,sve,cve,lve,uve=n((()=>{N(),Zh=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.`}),Qh=j().min(1,`Path cannot be empty`),rve=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(Zh).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),ive=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.`)}),ave=se({allowedDomains:M(Zh).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(Zh).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:rve.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:ive.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.`)}),ove=se({denyRead:M(Qh).describe(`Paths denied for reading`),allowRead:M(Qh).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(Qh).describe(`Paths allowed for writing`),denyWrite:M(Qh).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.`)}),sve=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),cve=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])`)}),lve=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:ave.describe(`Network restrictions configuration`),filesystem:ove.describe(`Filesystem restrictions configuration`),ignoreViolations:sve.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:cve.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:lve.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),dve=n((()=>{nve(),Rh(),uve(),Ch(),mh()}));async function fve(){if(bt()||ig||ag)return;ig=!0,yve(),Gn(pve);let{dirs:e,settingsFiles:t,dropInDir:n}=await mve();ag||e.length!==0&&(U(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),tg=Zp.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:cg?.stabilityThreshold??Sve,pollInterval:cg?.pollInterval??Cve},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(Gc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=Gc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+Gc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),tg.on(`change`,gve),tg.on(`unlink`,vve),tg.on(`add`,_ve))}function pve(){ag=!0,ng&&(clearInterval(ng),ng=null);for(let e of og.values())clearTimeout(e);og.clear(),rg=null,jne(),sg.clear();let e=tg;return tg=null,e?e.close():Promise.resolve()}async function mve(){let e=new Map,t=new Set;for(let n of Zr){if(n===`flagSettings`)continue;let r=ti(n);if(!r)continue;let i=Gc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await Nl(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=jr();try{(await Nl(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function hve(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 gve(e){let t=$h(e);if(!t)return;let n=og.get(e);n&&(clearTimeout(n),og.delete(e),U(`Cancelled pending deletion of ${e} — file was recreated`)),!pre(e,wve)&&(U(`Detected change to ${e}`),u7(hve(t),e).then(n=>{if(i7(n)){U(`ConfigChange hook blocked change to ${e}`);return}eg(t)}))}function _ve(e){if(!$h(e))return;let t=og.get(e);t&&(clearTimeout(t),og.delete(e),U(`Cancelled pending deletion of ${e} — file was re-added`)),gve(e)}function vve(e){let t=$h(e);if(!t||(U(`Detected deletion of ${e}`),og.has(e)))return;let n=setTimeout((e,t)=>{og.delete(e),u7(hve(t),e).then(n=>{if(i7(n)){U(`ConfigChange hook blocked deletion of ${e}`);return}eg(t)})},cg?.deletionGrace??Eve,e,t);og.set(e,n)}function $h(e){let t=Gc.normalize(e),n=jr();return t.startsWith(n+Gc.sep)?`policySettings`:Zr.find(e=>ti(e)===t)}function yve(){let e=Jre(),t=Ine();rg=V({mdm:e.settings,hkcu:t.settings}),ng=setInterval(()=>{ag||(async()=>{try{let{mdm:e,hkcu:t}=await Bne();if(ag)return;let n=V({mdm:e.settings,hkcu:t.settings});n!==rg&&(rg=n,Lne(e,t),U(`Detected MDM settings change via poll`),eg(`policySettings`))}catch(e){U(`MDM poll error: ${H(e)}`)}})()},cg?.mdmPollInterval??Tve),ng.unref()}function eg(e){Kt(),sg.emit(e)}function bve(e){U(`Programmatic settings change notification for ${e}`),eg(e)}function xve(e){ng&&(clearInterval(ng),ng=null);for(let e of og.values())clearTimeout(e);og.clear(),rg=null,ig=!1,ag=!1,cg=e??null;let t=tg;return tg=null,t?t.close():Promise.resolve()}var Sve,Cve,wve,Tve,Eve,tg,ng,rg,ig,ag,og,sg,cg,Dve,lg,ug=n((()=>{Qp(),Wt(),Jn(),W(),On(),_7(),fn(),Yn(),qr(),Ure(),Sr(),$ne(),Vr(),Zt(),Sve=1e3,Cve=500,wve=5e3,Tve=1800*1e3,Eve=1700,tg=null,ng=null,rg=null,ig=!1,ag=!1,og=new Map,sg=rn(),cg=null,Dve=sg.subscribe,lg={initialize:fve,dispose:pve,subscribe:Dve,notifyChange:bve,resetForTesting:xve}}));function dg(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 Ove(e){return e.match(/^(.+):\*$/)?.[1]??null}function fg(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?el(Kr(t),e.slice(1)):e}function pg(e,t){return e.startsWith(`//`)?e.slice(1):Qr(e,Kr(t))}function mg(){return Ir(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function kve(){return Ir(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function hg(e){let t=e.permissions||{},n=[],r=[];if(mg()){let e=Ir(`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=dg(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,I8()],a=[],o=[],s=[],c=Zr.map(e=>ti(e)).filter(e=>e!==void 0);a.push(...c),a.push(jr());let l=Ft(),u=Xt();l!==u&&(a.push(el(l,`.workmate`,`settings.json`)),a.push(el(l,`.workmate`,`settings.local.json`))),a.push(el(u,`.workmate`,`skills`)),l!==u&&a.push(el(l,`.workmate`,`skills`)),Sg.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=el(e,t);try{Lle(n),a.push(n)}catch{Sg.push(n)}}xg&&xg!==l&&i.push(xg);let f=new Set([...e.permissions?.additionalDirectories||[],...Qt()]);i.push(...f);for(let e of Zr){let t=Ir(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=dg(n);t.toolName===`Edit`&&t.ruleContent&&i.push(fg(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=dg(n);t.toolName===`Edit`&&t.ruleContent&&a.push(fg(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(fg(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(pg(t,e));for(let t of n.denyWrite||[])a.push(pg(t,e));for(let t of n.denyRead||[])o.push(pg(t,e));if(!kve()||e===`policySettings`)for(let t of n.allowRead||[])s.push(pg(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=hc(),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 Ave(){for(let e of Sg)try{Ile(e,{recursive:!0}),U(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function jve(e){let t=Y(e,`.git`);try{let n=(await Ol(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=el(e,n[1].trim()),i=`${tl}.git${tl}worktrees${tl}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function gg(){try{return zr()?.sandbox?.enabled??!1}catch(e){return U(`Failed to get settings for sandbox check: ${e}`),!1}}function Mve(){return zr()?.sandbox?.autoAllowBashIfSandboxed??!0}function Nve(){return zr()?.sandbox?.allowUnsandboxedCommands??!0}function Pve(){let e=zr();return gg()&&(e?.sandbox?.failIfUnavailable??!1)}function _g(){try{let e=Xr()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=la();return e.includes(t)}catch(e){return U(`Failed to check enabledPlatforms: ${e}`),!0}}function vg(){return!wg()||Cg().errors.length>0||!_g()?!1:gg()}function Fve(){if(!gg())return;if(!wg()){let e=la();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(!_g())return`sandbox.enabled is set but ${la()} is not in sandbox.enabledPlatforms`;let e=Cg();if(e.errors.length>0){let t=la()===`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 Ive(){let e=la();if(e!==`linux`&&e!==`wsl`)return[];try{let e=zr();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=dg(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return U(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Lve(){for(let e of[`flagSettings`,`policySettings`]){let t=Ir(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function Rve(e){li(`localSettings`,{sandbox:{...Ir(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function zve(){return zr()?.sandbox?.excludedCommands??[]}async function Bve(e,t,n,r){if(vg())if(yg)await yg;else throw Error(`Sandbox failed to initialize. `);return Xh.wrapWithSandbox(e,t,n,r)}async function Vve(e){if(yg)return yg;if(!vg())return;let t=e?async t=>mg()?(U(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return yg=(async()=>{try{xg===void 0&&(xg=await jve(Ft()));let e=hg(zr());await Xh.initialize(e,t),bg=lg.subscribe(()=>{let e=hg(zr());Xh.updateConfig(e),U(`Sandbox configuration updated from settings change`)})}catch(e){yg=void 0,U(`Failed to initialize sandbox: ${H(e)}`)}})(),yg}function Hve(){if(!vg())return;let e=hg(zr());Xh.updateConfig(e)}async function Uve(){return bg?.(),bg=void 0,xg=void 0,Sg.length=0,Cg.cache.clear?.(),wg.cache.clear?.(),yg=void 0,Xh.reset()}function Wve(e,t){let n=Ir(`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===js);t?.ruleContent&&(i=Ove(t.ruleContent)||t.ruleContent)}}return r.includes(i)||li(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var yg,bg,xg,Sg,Cg,wg,Tg,Eg=n((()=>{dve(),fh(),Wt(),W(),Lr(),ua(),ug(),qr(),Sr(),Vr(),bs(),Ns(),Fs(),On(),R8(),mc(),Sg=[],Cg=u(()=>{let{rgPath:e,rgArgs:t}=hc();return Xh.checkDependencies({command:e,args:t})}),wg=u(()=>Xh.isSupportedPlatform()),Tg={initialize:Vve,isSandboxingEnabled:vg,isSandboxEnabledInSettings:gg,isPlatformInEnabledList:_g,getSandboxUnavailableReason:Fve,isAutoAllowBashIfSandboxedEnabled:Mve,areUnsandboxedCommandsAllowed:Nve,isSandboxRequired:Pve,areSandboxSettingsLockedByPolicy:Lve,setSandboxSettings:Rve,getExcludedCommands:zve,wrapWithSandbox:Bve,refreshConfig:Hve,reset:Uve,checkDependencies:Cg,getFsReadConfig:Xh.getFsReadConfig,getFsWriteConfig:Xh.getFsWriteConfig,getNetworkRestrictionConfig:Xh.getNetworkRestrictionConfig,getIgnoreViolations:Xh.getIgnoreViolations,getLinuxGlobPatternWarnings:Ive,isSupportedPlatform:wg,getAllowUnixSockets:Xh.getAllowUnixSockets,getAllowLocalBinding:Xh.getAllowLocalBinding,getEnableWeakerNestedSandbox:Xh.getEnableWeakerNestedSandbox,getProxyPort:Xh.getProxyPort,getSocksProxyPort:Xh.getSocksProxyPort,getLinuxHttpSocketPath:Xh.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Xh.getLinuxSocksSocketPath,waitForNetworkInitialization:Xh.waitForNetworkInitialization,getSandboxViolationStore:Xh.getSandboxViolationStore,annotateStderrWithSandboxFailures:Xh.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Xh.cleanupAfterCommand(),Ave()}}})),Gve,Kve=n((()=>{ne(),Eg(),Gve={name:`sandbox`,get description(){let e=Tg.isSandboxingEnabled(),t=Tg.isAutoAllowBashIfSandboxedEnabled(),n=Tg.areUnsandboxedCommandsAllowed(),r=Tg.areSandboxSettingsLockedByPolicy(),i=Tg.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!Tg.isSupportedPlatform()||!Tg.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-DmNSThQK.js`)}}));function Dg(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function Og(){return{}}function kg(){return m(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!yo()?!1:Og().enabled??!1}function Ag(){return kg()&&(Og().canUserConfigure??!1)}function qve(){let e=Og();return kg()&&!Ag()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function jg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Mg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Jve(){if(kg())return Xr().advisorModel}function Yve(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Xve,Ng=n((()=>{Uo(),h(),Vr(),Xve=`# Advisor Tool
412
+ `),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=Gge(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=>{X(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{X(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{X(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{X(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var b_e,Ih,x_e=n((()=>{b_e=r(lce(),1),km(),Bm(),Ch(),Ih=`_${Math.random().toString(36).slice(2,11)}_SBX`})),Lh,Rh=n((()=>{Ch(),Lh=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=Wge(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 S_e(){if(Kh)return;let e=()=>Bh().catch(e=>{X(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Kh=!0}function zh(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(Xl(Nm(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function C_e(e,t,n){if(!Vh)return X(`No config available, denying network request`),!1;if(!Pm(t))return X(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=phe(t)??t;for(let n of Vh.network.deniedDomains)if(zh(r,n))return X(`Denied by config rule: ${t}:${e}`),!1;for(let n of Vh.network.allowedDomains)if(zh(r,n))return X(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return X(`No matching config rule, denying: ${t}:${e}`),!1;X(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(X(`User allowed: ${t}:${e}`),!0):(X(`User denied: ${t}:${e}`),!1)}catch(e){return X(`Error in permission callback: ${e}`,{level:`error`}),!1}}function w_e(e){if(!Vh?.network.mitmProxy)return;let{socketPath:t,domains:n}=Vh.network.mitmProxy;for(let r of n)if(zh(e,r))return X(`Host ${e} matches MITM pattern ${r}`),t}async function T_e(e){return Hh=_he({filter:(t,n)=>C_e(t,n,e),getMitmSocketPath:w_e,parentProxy:Jh}),new Promise((e,t)=>{if(!Hh){t(Error(`HTTP proxy server undefined before listen`));return}let n=Hh;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),X(`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 E_e(e){return Uh=The({filter:(t,n)=>C_e(t,n,e),parentProxy:Jh}),new Promise((e,t)=>{if(!Uh){t(Error(`SOCKS proxy server undefined before listen`));return}Uh.listen(0,`127.0.0.1`).then(t=>{Uh?.unref(),e(t)}).catch(t)})}async function D_e(e,t,n=!1){if(Gh){await Gh;return}Vh=e,Jh=ohe(e.network.parentProxy),Jh&&X(`Parent proxy configured: http=${dhe(Jh.httpUrl)} https=${dhe(Jh.httpsUrl)}`);let r=A_e();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&ph()===`macos`&&(qh=y_e(Yh.addViolation.bind(Yh),Vh.ignoreViolations),X(`Started macOS sandbox log monitor`)),S_e(),Gh=(async()=>{try{let e;Vh.network.httpProxyPort===void 0?e=await T_e(t):(e=Vh.network.httpProxyPort,X(`Using external HTTP proxy on port ${e}`));let n;Vh.network.socksProxyPort===void 0?n=await E_e(t):(n=Vh.network.socksProxyPort,X(`Using external SOCKS proxy on port ${n}`));let r;ph()===`linux`&&(r=await o_e(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Wh=i,X(`Network infrastructure initialized`),i}catch(e){throw Gh=void 0,Wh=void 0,Bh().catch(e=>{X(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await Gh}function O_e(){let e=ph();return e===`linux`?Rge()!==`1`:e===`macos`}function k_e(){return Vh!==void 0}function A_e(e){if(!O_e())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??Vh?.ripgrep??{command:`rg`};if(zm(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),ph()===`linux`){let e=a_e(Vh?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function j_e(){if(!Vh)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of Vh.filesystem.denyRead){let n=gh(t);if(ph()===`linux`&&hh(n)){let n=xh(t);X(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of Vh.filesystem.allowRead??[]){let n=gh(e);if(ph()===`linux`&&hh(n)){let n=xh(e);X(`[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 M_e(){if(!Vh)return{allowOnly:yh(),denyWithinAllow:[]};let e=Vh.filesystem.allowWrite.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=Vh.filesystem.denyWrite.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...yh(),...e],denyWithinAllow:t}}function N_e(){if(!Vh)return{};let e=Vh.network.allowedDomains,t=Vh.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function P_e(){return Vh?.network?.allowUnixSockets}function F_e(){return Vh?.network?.allowAllUnixSockets}function I_e(){return Vh?.network?.allowLocalBinding}function L_e(){return Vh?.ignoreViolations}function R_e(){return Vh?.enableWeakerNestedSandbox}function z_e(){return Vh?.enableWeakerNetworkIsolation}function B_e(){return Vh?.ripgrep??{command:`rg`}}function V_e(){return Vh?.mandatoryDenySearchDepth??3}function H_e(){return Vh?.filesystem?.allowGitConfig??!1}function U_e(){return Vh?.seccomp}function W_e(){return Wh?.httpProxyPort}function G_e(){return Wh?.socksProxyPort}function K_e(){return Wh?.linuxBridge?.httpSocketPath}function q_e(){return Wh?.linuxBridge?.socksSocketPath}async function J_e(){if(!Vh)return!1;if(Gh)try{return await Gh,!0}catch{return!1}return Wh!==void 0}async function Y_e(e,t,n,r){let i=ph(),a=e=>e.map(e=>gh(e)).filter(e=>ph()===`linux`&&hh(e)?(X(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??Vh?.filesystem.allowWrite??[]),s={allowOnly:[...yh(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??Vh?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??Vh?.filesystem.denyRead??[],l=[];for(let e of c){let t=gh(e);ph()===`linux`&&hh(t)?l.push(...xh(e)):l.push(t)}let u=n?.filesystem?.allowRead??Vh?.filesystem.allowRead??[],d=[];for(let e of u){let t=gh(e);ph()===`linux`&&hh(t)?d.push(...xh(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||Vh?.network?.allowedDomains!==void 0,m=p,h=p;h&&await J_e();let g=n?.allowPty??Vh?.allowPty;switch(i){case`macos`:return v_e({command:e,needsNetworkRestriction:m,httpProxyPort:h?W_e():void 0,socksProxyPort:h?G_e():void 0,readConfig:f,writeConfig:s,allowUnixSockets:P_e(),allowAllUnixSockets:F_e(),allowLocalBinding:I_e(),ignoreViolations:L_e(),allowPty:g,allowGitConfig:H_e(),enableWeakerNetworkIsolation:z_e(),binShell:t});case`linux`:return l_e({command:e,needsNetworkRestriction:m,httpSocketPath:h?K_e():void 0,socksSocketPath:h?q_e():void 0,httpProxyPort:h?Wh?.httpProxyPort:void 0,socksProxyPort:h?Wh?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:R_e(),allowAllUnixSockets:F_e(),binShell:t,ripgrepConfig:B_e(),mandatoryDenySearchDepth:V_e(),allowGitConfig:H_e(),seccompConfig:U_e(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function X_e(){return Vh}function Z_e(e){Vh=pfe(e),Jh=ohe(e.network.parentProxy),X(`Sandbox configuration updated`)}function Q_e(){i_e()}async function Bh(){if(Q_e(),qh&&(qh(),qh=void 0),Wh?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Wh.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),X(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{X(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){X(`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`&&X(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),X(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{X(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){X(`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`&&X(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{ll.rmSync(e,{force:!0}),X(`Cleaned up HTTP socket`)}catch(e){X(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{ll.rmSync(t,{force:!0}),X(`Cleaned up SOCKS socket`)}catch(e){X(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Hh){let t=Hh,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&X(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(Uh){let t=Uh.close().catch(e=>{X(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Hh=void 0,Uh=void 0,Wh=void 0,Gh=void 0,Jh=void 0}function $_e(){return Yh}function eve(e,t){if(!Vh)return t;let n=Yh.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=gl+`<sandbox_violations>`+gl;for(let e of n)r+=e.line+gl;return r+=`</sandbox_violations>`,r}function tve(){if(ph()!==`linux`||!Vh)return[];let e=[],t=[...Vh.filesystem.allowWrite,...Vh.filesystem.denyWrite];for(let n of t)hh(gh(n))&&e.push(n);return e}var Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,nve=n((()=>{yhe(),Ehe(),km(),Bm(),fh(),mh(),u_e(),x_e(),Ch(),Rh(),Im(),Kh=!1,Yh=new Lh,Xh={initialize:D_e,isSupportedPlatform:O_e,isSandboxingEnabled:k_e,checkDependencies:A_e,getFsReadConfig:j_e,getFsWriteConfig:M_e,getNetworkRestrictionConfig:N_e,getAllowUnixSockets:P_e,getAllowLocalBinding:I_e,getIgnoreViolations:L_e,getEnableWeakerNestedSandbox:R_e,getProxyPort:W_e,getSocksProxyPort:G_e,getLinuxHttpSocketPath:K_e,getLinuxSocksSocketPath:q_e,waitForNetworkInitialization:J_e,wrapWithSandbox:Y_e,cleanupAfterCommand:Q_e,reset:Bh,getSandboxViolationStore:$_e,annotateStderrWithSandboxFailures:eve,getLinuxGlobPatternWarnings:tve,getConfig:X_e,updateConfig:Z_e}})),Zh,Qh,rve,ive,ave,ove,sve,cve,lve,uve=n((()=>{N(),Zh=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.`}),Qh=j().min(1,`Path cannot be empty`),rve=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(Zh).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),ive=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.`)}),ave=se({allowedDomains:M(Zh).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(Zh).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:rve.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:ive.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.`)}),ove=se({denyRead:M(Qh).describe(`Paths denied for reading`),allowRead:M(Qh).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(Qh).describe(`Paths allowed for writing`),denyWrite:M(Qh).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.`)}),sve=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),cve=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])`)}),lve=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:ave.describe(`Network restrictions configuration`),filesystem:ove.describe(`Filesystem restrictions configuration`),ignoreViolations:sve.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:cve.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:lve.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),dve=n((()=>{nve(),Rh(),uve(),Ch(),mh()}));async function fve(){if(bt()||ig||ag)return;ig=!0,yve(),Gn(pve);let{dirs:e,settingsFiles:t,dropInDir:n}=await mve();ag||e.length!==0&&(U(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),tg=Zp.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:cg?.stabilityThreshold??Sve,pollInterval:cg?.pollInterval??Cve},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(Gc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=Gc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+Gc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),tg.on(`change`,gve),tg.on(`unlink`,vve),tg.on(`add`,_ve))}function pve(){ag=!0,ng&&(clearInterval(ng),ng=null);for(let e of og.values())clearTimeout(e);og.clear(),rg=null,jne(),sg.clear();let e=tg;return tg=null,e?e.close():Promise.resolve()}async function mve(){let e=new Map,t=new Set;for(let n of Zr){if(n===`flagSettings`)continue;let r=ti(n);if(!r)continue;let i=Gc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await Nl(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=jr();try{(await Nl(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function hve(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 gve(e){let t=$h(e);if(!t)return;let n=og.get(e);n&&(clearTimeout(n),og.delete(e),U(`Cancelled pending deletion of ${e} — file was recreated`)),!pre(e,wve)&&(U(`Detected change to ${e}`),u7(hve(t),e).then(n=>{if(i7(n)){U(`ConfigChange hook blocked change to ${e}`);return}eg(t)}))}function _ve(e){if(!$h(e))return;let t=og.get(e);t&&(clearTimeout(t),og.delete(e),U(`Cancelled pending deletion of ${e} — file was re-added`)),gve(e)}function vve(e){let t=$h(e);if(!t||(U(`Detected deletion of ${e}`),og.has(e)))return;let n=setTimeout((e,t)=>{og.delete(e),u7(hve(t),e).then(n=>{if(i7(n)){U(`ConfigChange hook blocked deletion of ${e}`);return}eg(t)})},cg?.deletionGrace??Eve,e,t);og.set(e,n)}function $h(e){let t=Gc.normalize(e),n=jr();return t.startsWith(n+Gc.sep)?`policySettings`:Zr.find(e=>ti(e)===t)}function yve(){let e=Jre(),t=Ine();rg=V({mdm:e.settings,hkcu:t.settings}),ng=setInterval(()=>{ag||(async()=>{try{let{mdm:e,hkcu:t}=await Bne();if(ag)return;let n=V({mdm:e.settings,hkcu:t.settings});n!==rg&&(rg=n,Lne(e,t),U(`Detected MDM settings change via poll`),eg(`policySettings`))}catch(e){U(`MDM poll error: ${H(e)}`)}})()},cg?.mdmPollInterval??Tve),ng.unref()}function eg(e){Kt(),sg.emit(e)}function bve(e){U(`Programmatic settings change notification for ${e}`),eg(e)}function xve(e){ng&&(clearInterval(ng),ng=null);for(let e of og.values())clearTimeout(e);og.clear(),rg=null,ig=!1,ag=!1,cg=e??null;let t=tg;return tg=null,t?t.close():Promise.resolve()}var Sve,Cve,wve,Tve,Eve,tg,ng,rg,ig,ag,og,sg,cg,Dve,lg,ug=n((()=>{Qp(),Wt(),Jn(),W(),On(),_7(),fn(),Yn(),qr(),Ure(),Sr(),$ne(),Vr(),Zt(),Sve=1e3,Cve=500,wve=5e3,Tve=1800*1e3,Eve=1700,tg=null,ng=null,rg=null,ig=!1,ag=!1,og=new Map,sg=rn(),cg=null,Dve=sg.subscribe,lg={initialize:fve,dispose:pve,subscribe:Dve,notifyChange:bve,resetForTesting:xve}}));function dg(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 Ove(e){return e.match(/^(.+):\*$/)?.[1]??null}function fg(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?el(Kr(t),e.slice(1)):e}function pg(e,t){return e.startsWith(`//`)?e.slice(1):Qr(e,Kr(t))}function mg(){return Ir(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function kve(){return Ir(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function hg(e){let t=e.permissions||{},n=[],r=[];if(mg()){let e=Ir(`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=dg(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,I8()],a=[],o=[],s=[],c=Zr.map(e=>ti(e)).filter(e=>e!==void 0);a.push(...c),a.push(jr());let l=Ft(),u=Xt();l!==u&&(a.push(el(l,`.workmate`,`settings.json`)),a.push(el(l,`.workmate`,`settings.local.json`))),a.push(el(u,`.workmate`,`skills`)),l!==u&&a.push(el(l,`.workmate`,`skills`)),Sg.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=el(e,t);try{Lle(n),a.push(n)}catch{Sg.push(n)}}xg&&xg!==l&&i.push(xg);let f=new Set([...e.permissions?.additionalDirectories||[],...Qt()]);i.push(...f);for(let e of Zr){let t=Ir(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=dg(n);t.toolName===`Edit`&&t.ruleContent&&i.push(fg(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=dg(n);t.toolName===`Edit`&&t.ruleContent&&a.push(fg(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(fg(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(pg(t,e));for(let t of n.denyWrite||[])a.push(pg(t,e));for(let t of n.denyRead||[])o.push(pg(t,e));if(!kve()||e===`policySettings`)for(let t of n.allowRead||[])s.push(pg(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=hc(),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 Ave(){for(let e of Sg)try{Ile(e,{recursive:!0}),U(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function jve(e){let t=Y(e,`.git`);try{let n=(await Ol(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=el(e,n[1].trim()),i=`${tl}.git${tl}worktrees${tl}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function gg(){try{return zr()?.sandbox?.enabled??!1}catch(e){return U(`Failed to get settings for sandbox check: ${e}`),!1}}function Mve(){return zr()?.sandbox?.autoAllowBashIfSandboxed??!0}function Nve(){return zr()?.sandbox?.allowUnsandboxedCommands??!0}function Pve(){let e=zr();return gg()&&(e?.sandbox?.failIfUnavailable??!1)}function _g(){try{let e=Xr()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=la();return e.includes(t)}catch(e){return U(`Failed to check enabledPlatforms: ${e}`),!0}}function vg(){return!wg()||Cg().errors.length>0||!_g()?!1:gg()}function Fve(){if(!gg())return;if(!wg()){let e=la();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(!_g())return`sandbox.enabled is set but ${la()} is not in sandbox.enabledPlatforms`;let e=Cg();if(e.errors.length>0){let t=la()===`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 Ive(){let e=la();if(e!==`linux`&&e!==`wsl`)return[];try{let e=zr();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=dg(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return U(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Lve(){for(let e of[`flagSettings`,`policySettings`]){let t=Ir(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function Rve(e){li(`localSettings`,{sandbox:{...Ir(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function zve(){return zr()?.sandbox?.excludedCommands??[]}async function Bve(e,t,n,r){if(vg())if(yg)await yg;else throw Error(`Sandbox failed to initialize. `);return Xh.wrapWithSandbox(e,t,n,r)}async function Vve(e){if(yg)return yg;if(!vg())return;let t=e?async t=>mg()?(U(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return yg=(async()=>{try{xg===void 0&&(xg=await jve(Ft()));let e=hg(zr());await Xh.initialize(e,t),bg=lg.subscribe(()=>{let e=hg(zr());Xh.updateConfig(e),U(`Sandbox configuration updated from settings change`)})}catch(e){yg=void 0,U(`Failed to initialize sandbox: ${H(e)}`)}})(),yg}function Hve(){if(!vg())return;let e=hg(zr());Xh.updateConfig(e)}async function Uve(){return bg?.(),bg=void 0,xg=void 0,Sg.length=0,Cg.cache.clear?.(),wg.cache.clear?.(),yg=void 0,Xh.reset()}function Wve(e,t){let n=Ir(`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===js);t?.ruleContent&&(i=Ove(t.ruleContent)||t.ruleContent)}}return r.includes(i)||li(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var yg,bg,xg,Sg,Cg,wg,Tg,Eg=n((()=>{dve(),fh(),Wt(),W(),Lr(),ua(),ug(),qr(),Sr(),Vr(),bs(),Ns(),Fs(),On(),R8(),mc(),Sg=[],Cg=u(()=>{let{rgPath:e,rgArgs:t}=hc();return Xh.checkDependencies({command:e,args:t})}),wg=u(()=>Xh.isSupportedPlatform()),Tg={initialize:Vve,isSandboxingEnabled:vg,isSandboxEnabledInSettings:gg,isPlatformInEnabledList:_g,getSandboxUnavailableReason:Fve,isAutoAllowBashIfSandboxedEnabled:Mve,areUnsandboxedCommandsAllowed:Nve,isSandboxRequired:Pve,areSandboxSettingsLockedByPolicy:Lve,setSandboxSettings:Rve,getExcludedCommands:zve,wrapWithSandbox:Bve,refreshConfig:Hve,reset:Uve,checkDependencies:Cg,getFsReadConfig:Xh.getFsReadConfig,getFsWriteConfig:Xh.getFsWriteConfig,getNetworkRestrictionConfig:Xh.getNetworkRestrictionConfig,getIgnoreViolations:Xh.getIgnoreViolations,getLinuxGlobPatternWarnings:Ive,isSupportedPlatform:wg,getAllowUnixSockets:Xh.getAllowUnixSockets,getAllowLocalBinding:Xh.getAllowLocalBinding,getEnableWeakerNestedSandbox:Xh.getEnableWeakerNestedSandbox,getProxyPort:Xh.getProxyPort,getSocksProxyPort:Xh.getSocksProxyPort,getLinuxHttpSocketPath:Xh.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Xh.getLinuxSocksSocketPath,waitForNetworkInitialization:Xh.waitForNetworkInitialization,getSandboxViolationStore:Xh.getSandboxViolationStore,annotateStderrWithSandboxFailures:Xh.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Xh.cleanupAfterCommand(),Ave()}}})),Gve,Kve=n((()=>{ne(),Eg(),Gve={name:`sandbox`,get description(){let e=Tg.isSandboxingEnabled(),t=Tg.isAutoAllowBashIfSandboxedEnabled(),n=Tg.areUnsandboxedCommandsAllowed(),r=Tg.areSandboxSettingsLockedByPolicy(),i=Tg.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!Tg.isSupportedPlatform()||!Tg.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-DKcw3SbO.js`)}}));function Dg(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function Og(){return{}}function kg(){return m(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!yo()?!1:Og().enabled??!1}function Ag(){return kg()&&(Og().canUserConfigure??!1)}function qve(){let e=Og();return kg()&&!Ag()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function jg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Mg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Jve(){if(kg())return Xr().advisorModel}function Yve(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Xve,Ng=n((()=>{Uo(),h(),Vr(),Xve=`# Advisor Tool
413
413
 
414
414
  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.
415
415
 
@@ -563,8 +563,8 @@ FIND_GREP_FUNC_END
563
563
  echo "Error: Snapshot file was not created at $SNAPSHOT_FILE" >&2
564
564
  exit 1
565
565
  fi
566
- `}var uy,dy,jxe,Mxe,Nxe=n((()=>{Ii(),Da(),Jn(),vn(),W(),sy(),h(),ci(),Bn(),Qi(),ua(),mc(),Ac(),pc(),uy=`\\`,dy=1e4,jxe=[`.git`,`.svn`,`.hg`,`.bzr`,`.jj`,`.sl`],Mxe=async e=>{let t=e.includes(`zsh`)?`zsh`:e.includes(`bash`)?`bash`:`sh`;return U(`Creating shell snapshot for ${t} (${e})`),new Promise(async n=>{try{let r=ly(e);U(`Looking for shell config file: ${r}`);let i=await Gr(r);i||U(`Shell config file not found: ${r}, creating snapshot with Work Mate defaults only`);let a=Date.now(),o=Math.random().toString(36).substring(2,8),s=Y(p(),`shell-snapshots`);U(`Snapshots directory: ${s}`);let c=Y(s,`snapshot-${t}-${a}-${o}.sh`);await El(s,{recursive:!0});let l=await Axe(e,c,i);U(`Creating snapshot at: ${c}`),U(`Execution timeout: ${dy}ms`),gue(e,[`-c`,`-l`,l],{env:{...process.env.CLAUDE_CODE_DONT_INHERIT_ENV?{}:kc(),SHELL:e,GIT_EDITOR:`true`,CLAUDECODE:`1`},timeout:dy,maxBuffer:1024*1024,encoding:`utf8`},async(t,r,a)=>{if(t){let o=t;U(`Shell snapshot creation failed: ${t.message}`),U(`Error details:`),U(` - Error code: ${o?.code}`),U(` - Error signal: ${o?.signal}`),U(` - Error killed: ${o?.killed}`),U(` - Shell path: ${e}`),U(` - Config file: ${ly(e)}`),U(` - Config file exists: ${i}`),U(` - Working directory: ${yn()}`),U(` - Claude home: ${p()}`),U(`Full snapshot script:\n${l}`),U(r?`stdout output (${r.length} chars):\n${r}`:`No stdout output captured`),U(a?`stderr output (${a.length} chars): ${a}`:`No stderr output captured`),q(Error(`Failed to create shell snapshot: ${t.message}`));let s=o?.signal?hle.constants.signals[o.signal]:void 0;J(`tengu_shell_snapshot_failed`,{stderr_length:a?.length||0,has_error_code:!!o?.code,error_signal_number:s,error_killed:o?.killed}),n(void 0)}else{let e;try{e=(await Nl(c)).size}catch{}if(e!==void 0)U(`Shell snapshot created successfully (${e} bytes)`),Gn(async()=>{try{await G().unlink(c),U(`Cleaned up session snapshot: ${c}`)}catch(e){U(`Error cleaning up session snapshot: ${e}`)}}),n(c);else{U(`Shell snapshot file not found after creation: ${c}`),U(`Checking if parent directory still exists: ${s}`);try{U(`Directory contains ${(await G().readdir(s)).length} files`)}catch{U(`Parent directory does not exist or is not accessible: ${s}`)}J(`tengu_shell_unknown_error`,{}),n(void 0)}}})}catch(e){U(`Unexpected error during snapshot creation: ${e}`),e instanceof Error&&U(`Error stack trace: ${e.stack}`),q(e),J(`tengu_shell_snapshot_error`,{}),n(void 0)}})}}));function Pxe(e,t){let n=e.lastIndexOf(` -`);if(n>0){let r=e.substring(0,n),i=e.substring(n+1);return`${dc([r])} ${i} ${dc([t])}`}else return`${dc([e])} ${dc([t])}`}var Fxe=n((()=>{pc()}));function fy(e){return/\d\s*<<\s*\d/.test(e)||/\[\[\s*\d+\s*<<\s*\d+\s*\]\]/.test(e)||/\$\(\(.*<<.*\)\)/.test(e)?!1:/<<-?\s*(?:(['"]?)(\w+)\1|\\(\w+))/.test(e)}function Ixe(e){return/'(?:[^'\\]|\\.)*\n(?:[^'\\]|\\.)*'/.test(e)||/"(?:[^"\\]|\\.)*\n(?:[^"\\]|\\.)*"/.test(e)}function Lxe(e,t=!0){if(fy(e)||Ixe(e)){let n=`'${e.replace(/'/g,`'"'"'`)}'`;return fy(e)?n:t?`${n} < /dev/null`:n}return dc(t?[e,`<`,`/dev/null`]:[e])}function Rxe(e){return/(?:^|[\s;&|])<(?![<(])\s*\S+/.test(e)}function zxe(e){return!(fy(e)||Rxe(e))}function Bxe(e){return e.replace(Vxe,`$1/dev/null`)}var Vxe,Hxe=n((()=>{pc(),Vxe=/(\d?&?>+\s*)[Nn][Uu][Ll](?=\s|$|[|&;)\n])/g}));function Uxe(){return py}function Wxe(){py.clear()}var py,my=n((()=>{py=new Map}));function Gxe(){return null}function Kxe(e){return process.env.CLAUDE_CODE_SHELL_PREFIX?`{ shopt -u extglob || setopt NO_EXTENDED_GLOB; } >/dev/null 2>&1 || true`:e.includes(`bash`)?`shopt -u extglob 2>/dev/null || true`:e.includes(`zsh`)?`setopt NO_EXTENDED_GLOB 2>/dev/null || true`:null}async function qxe(e,t){let n,r=t?.skipSnapshot?Promise.resolve(void 0):Mxe(e).catch(e=>{U(`Failed to create shell snapshot: ${e}`)}),i;return{type:`bash`,shellPath:e,detached:!0,async buildExecCommand(t,a){let o=await r;if(o)try{await lue(o)}catch{U(`Snapshot file missing, falling back to login shell: ${o}`),o=void 0}i=o,n=a.sandboxTmpDir;let s=Wc(),c=la()===`windows`?pa(s):s,l=a.useSandbox?Zl(a.sandboxTmpDir,`cwd-${a.id}`):Zl(c,`claude-${a.id}-cwd`),u=a.useSandbox?Zl(a.sandboxTmpDir,`cwd-${a.id}`):Y(s,`claude-${a.id}-cwd`),d=Bxe(t),f=zxe(d),p=Lxe(d,f);(t.includes(`<<`)||t.includes(`
567
- `))&&(U(`Shell: Command before quoting (first 500 chars):\n${t.slice(0,500)}`),U(`Shell: Quoted command (first 500 chars):\n${p.slice(0,500)}`)),d.includes(`|`)&&f&&(p=gxe(d));let m=[];if(o){let e=la()===`windows`?pa(o):o;m.push(`source ${dc([e])} 2>/dev/null || true`)}let h=await rxe();h&&m.push(h);let g=Kxe(e);g&&m.push(g),m.push(`eval ${p}`),m.push(`pwd -P >| ${dc([l])}`);let _=m.join(` && `);return process.env.CLAUDE_CODE_SHELL_PREFIX&&(_=Pxe(process.env.CLAUDE_CODE_SHELL_PREFIX,_)),{commandString:_,cwdFilePath:u}},getSpawnArgs(e){let t=i!==void 0;return t&&U(`Spawning shell without login (-l flag skipped)`),[`-c`,...t?[]:[`-l`],e]},async getEnvironmentOverrides(e){let t=Gxe(),r={};if(t&&(r.TMUX=t),n){let e=n;la()===`windows`&&(e=pa(e)),r.TMPDIR=e,r.CLAUDE_CODE_TMPDIR=e,r.TMPPREFIX=Zl(e,`zsh`)}for(let[e,t]of Uxe())r[e]=t;return r}}}var Jxe=n((()=>{wxe(),Nxe(),Fxe(),pc(),Hxe(),W(),ua(),zv(),my(),fa()}));async function Yxe(e){try{return(await Nl(e)).isFile()?e:null}catch{return null}}async function Xxe(){let e=await sa(`pwsh`);if(e){if(la()===`linux`){let t=await Al(e).catch(()=>e);if(e.startsWith(`/snap/`)||t.startsWith(`/snap/`)){let e=await Yxe(`/opt/microsoft/powershell/7/pwsh`)??await Yxe(`/usr/bin/pwsh`);if(e){let t=await Al(e).catch(()=>e);if(!e.startsWith(`/snap/`)&&!t.startsWith(`/snap/`))return e}}}return e}return await sa(`powershell`)||null}function hy(){return gy||(gy=Xxe()),gy}async function Zxe(){let e=await hy();return e?e.split(/[/\\]/).pop().toLowerCase().replace(/\.exe$/,``)===`pwsh`?`core`:`desktop`:null}var gy,_y=n((()=>{ua(),ca(),gy=null}));function Qxe(e){return[`-NoProfile`,`-NonInteractive`,`-Command`,e]}function $xe(e){return Buffer.from(e,`utf16le`).toString(`base64`)}function eSe(e){let t;return{type:`powershell`,shellPath:e,detached:!1,async buildExecCommand(n,r){t=r.useSandbox?r.sandboxTmpDir:void 0;let i=r.useSandbox&&r.sandboxTmpDir?Zl(r.sandboxTmpDir,`claude-pwd-ps-${r.id}`):Y(Wc(),`claude-pwd-ps-${r.id}`),a=n+`\n; $_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }\n; (Get-Location).Path | Out-File -FilePath '${i.replace(/'/g,`''`)}' -Encoding utf8 -NoNewline\n; exit $_ec`;return{commandString:r.useSandbox?[`'${e.replace(/'/g,`'\\''`)}'`,`-NoProfile`,`-NonInteractive`,`-EncodedCommand`,$xe(a)].join(` `):a,cwdFilePath:i}},getSpawnArgs(e){return Qxe(e)},async getEnvironmentOverrides(){let e={};for(let[t,n]of Uxe())e[t]=n;return t&&(e.TMPDIR=t,e.CLAUDE_CODE_TMPDIR=t),e}}}var tSe=n((()=>{my()}));function vy(e){try{return Tle(e,ul.X_OK),!0}catch{try{return Ll(e,[`--version`],{timeout:1e3,stdio:`ignore`}),!0}catch{return!1}}}async function nSe(){let e=process.env.CLAUDE_CODE_SHELL;if(e){if((e.includes(`bash`)||e.includes(`zsh`))&&vy(e))return U(`Using shell override: ${e}`),e;U(`CLAUDE_CODE_SHELL="${e}" is not a valid bash/zsh path, falling back to detection`)}let t=process.env.SHELL,n=t&&(t.includes(`bash`)||t.includes(`zsh`)),r=t?.includes(`bash`),[i,a]=await Promise.all([sa(`zsh`),sa(`bash`)]),o=[`/bin`,`/usr/bin`,`/usr/local/bin`,`/opt/homebrew/bin`],s=(r?[`bash`,`zsh`]:[`zsh`,`bash`]).flatMap(e=>o.map(t=>`${t}/${e}`));r?(a&&s.unshift(a),i&&s.push(i)):(i&&s.unshift(i),a&&s.push(a)),n&&vy(t)&&s.unshift(t);let c=s.find(e=>e&&vy(e));if(!c){let e=`No suitable shell found. Claude CLI requires a Posix shell environment. Please ensure you have a valid shell installed and the SHELL environment variable set.`;throw q(Error(e)),Error(e)}return c}async function rSe(){return{provider:await qxe(await nSe())}}async function yy(e,t,n,r){let{timeout:i,onProgress:a,preventCwdChanges:o,shouldUseSandbox:s,shouldAutoBackground:c,onStdout:l}=r??{},u=i||iSe,d=await sSe[n](),f=Math.floor(Math.random()*65536).toString(16).padStart(4,`0`),p=Zl(process.env.CLAUDE_CODE_TMPDIR||Wc(),Owt()),{commandString:m,cwdFilePath:h}=await d.buildExecCommand(e,{id:f,sandboxTmpDir:s?p:void 0,useSandbox:s??!1}),g=m,_=vne();try{await Al(_)}catch{let e=Xt();U(`Shell CWD "${_}" no longer exists, recovering to "${e}"`);try{await Al(e),Pte(e),_=e}catch{return fTt(`Working directory "${_}" no longer exists. Please restart Claude from an existing directory.`)}}if(t.aborted)return dTt();let v=d.shellPath,y=s&&n===`powershell`,b=y?`/bin/sh`:v;if(s){g=await Tg.wrapWithSandbox(g,b,void 0,t);try{await G().mkdir(p,{mode:448})}catch(e){U(`Failed to create ${p} directory: ${e}`)}}let x=y?`/bin/sh`:v,S=y?[`-c`,g]:d.getSpawnArgs(g),C=await d.getEnvironmentOverrides(e),w=!!l,T=new kv(s5(`local_bash`),a??null,!w);await El(z8(),{recursive:!0});let E;if(!w){let e=ul.O_NOFOLLOW??0;E=await Dl(T.path,process.platform===`win32`?`w`:ul.O_WRONLY|ul.O_CREAT|ul.O_APPEND|e)}try{let e=Rl(x,S,{env:{...kc(),SHELL:n===`bash`?v:void 0,GIT_EDITOR:`true`,CLAUDECODE:`1`,...C},cwd:_,stdio:w?[`pipe`,`pipe`,`pipe`]:[`pipe`,E?.fd,E?.fd],detached:d.detached,windowsHide:!0}),r=uTt(e,t,u,T,c);if(E!==void 0)try{await E.close()}catch{}e.stdout&&l&&e.stdout.on(`data`,e=>{l(typeof e==`string`?e:e.toString())});let i=la()===`windows`?da(h):h;return r.result.then(async e=>{if(s&&Tg.cleanupAfterCommand(),e&&!o&&!e.backgroundTaskId)try{let e=dl(i,{encoding:`utf8`}).trim();la()===`windows`&&(e=da(e)),e.normalize(`NFC`)!==_&&(by(e,_),Fv(),mxe(_,e))}catch{J(`tengu_shell_set_cwd`,{success:!1})}try{Rle(i)}catch{}}),r}catch(e){if(E!==void 0)try{await E.close()}catch{}return T.clear(),U(`Shell exec error: ${H(e)}`),dTt(void 0,{code:126,stderr:H(e)})}}function by(e,t){let n=Yc(e)?e:el(t||G().cwd(),e),r;try{r=G().realpathSync(n)}catch(e){throw xn(e)?Error(`Path "${n}" does not exist`):e}Pte(r);try{J(`tengu_shell_set_cwd`,{success:!0})}catch{}}var iSe,aSe,oSe,sSe,xy=n((()=>{d(),Da(),Wt(),l5(),vn(),W(),On(),Bn(),Qi(),_Tt(),o5(),Nv(),ca(),ry(),R8(),ua(),Eg(),zv(),Jxe(),_y(),tSe(),Ac(),fa(),iSe=1800*1e3,aSe=u(rSe),oSe=u(async()=>{let e=await hy();if(!e)throw Error(`PowerShell is not available`);return eSe(e)}),sSe={bash:async()=>(await aSe()).provider,powershell:oSe}}));function cSe(e){let t=e.split(`
566
+ `}var uy,dy,jxe,Mxe,Nxe=n((()=>{Ii(),Da(),Jn(),vn(),W(),sy(),h(),ci(),Bn(),Qi(),ua(),mc(),Ac(),pc(),uy=`\\`,dy=1e4,jxe=[`.git`,`.svn`,`.hg`,`.bzr`,`.jj`,`.sl`],Mxe=async e=>{let t=e.includes(`zsh`)?`zsh`:e.includes(`bash`)?`bash`:`sh`;return U(`Creating shell snapshot for ${t} (${e})`),new Promise(async n=>{try{let r=ly(e);U(`Looking for shell config file: ${r}`);let i=await Gr(r);i||U(`Shell config file not found: ${r}, creating snapshot with Work Mate defaults only`);let a=Date.now(),o=Math.random().toString(36).substring(2,8),s=Y(p(),`shell-snapshots`);U(`Snapshots directory: ${s}`);let c=Y(s,`snapshot-${t}-${a}-${o}.sh`);await El(s,{recursive:!0});let l=await Axe(e,c,i);U(`Creating snapshot at: ${c}`),U(`Execution timeout: ${dy}ms`),gue(e,[`-c`,`-l`,l],{env:{...process.env.CLAUDE_CODE_DONT_INHERIT_ENV?{}:kc(),SHELL:e,GIT_EDITOR:`true`,CLAUDECODE:`1`},timeout:dy,maxBuffer:1024*1024,encoding:`utf8`},async(t,r,a)=>{if(t){let o=t;U(`Shell snapshot creation failed: ${t.message}`),U(`Error details:`),U(` - Error code: ${o?.code}`),U(` - Error signal: ${o?.signal}`),U(` - Error killed: ${o?.killed}`),U(` - Shell path: ${e}`),U(` - Config file: ${ly(e)}`),U(` - Config file exists: ${i}`),U(` - Working directory: ${yn()}`),U(` - Work Mate home: ${p()}`),U(`Full snapshot script:\n${l}`),U(r?`stdout output (${r.length} chars):\n${r}`:`No stdout output captured`),U(a?`stderr output (${a.length} chars): ${a}`:`No stderr output captured`),q(Error(`Failed to create shell snapshot: ${t.message}`));let s=o?.signal?hle.constants.signals[o.signal]:void 0;J(`tengu_shell_snapshot_failed`,{stderr_length:a?.length||0,has_error_code:!!o?.code,error_signal_number:s,error_killed:o?.killed}),n(void 0)}else{let e;try{e=(await Nl(c)).size}catch{}if(e!==void 0)U(`Shell snapshot created successfully (${e} bytes)`),Gn(async()=>{try{await G().unlink(c),U(`Cleaned up session snapshot: ${c}`)}catch(e){U(`Error cleaning up session snapshot: ${e}`)}}),n(c);else{U(`Shell snapshot file not found after creation: ${c}`),U(`Checking if parent directory still exists: ${s}`);try{U(`Directory contains ${(await G().readdir(s)).length} files`)}catch{U(`Parent directory does not exist or is not accessible: ${s}`)}J(`tengu_shell_unknown_error`,{}),n(void 0)}}})}catch(e){U(`Unexpected error during snapshot creation: ${e}`),e instanceof Error&&U(`Error stack trace: ${e.stack}`),q(e),J(`tengu_shell_snapshot_error`,{}),n(void 0)}})}}));function Pxe(e,t){let n=e.lastIndexOf(` -`);if(n>0){let r=e.substring(0,n),i=e.substring(n+1);return`${dc([r])} ${i} ${dc([t])}`}else return`${dc([e])} ${dc([t])}`}var Fxe=n((()=>{pc()}));function fy(e){return/\d\s*<<\s*\d/.test(e)||/\[\[\s*\d+\s*<<\s*\d+\s*\]\]/.test(e)||/\$\(\(.*<<.*\)\)/.test(e)?!1:/<<-?\s*(?:(['"]?)(\w+)\1|\\(\w+))/.test(e)}function Ixe(e){return/'(?:[^'\\]|\\.)*\n(?:[^'\\]|\\.)*'/.test(e)||/"(?:[^"\\]|\\.)*\n(?:[^"\\]|\\.)*"/.test(e)}function Lxe(e,t=!0){if(fy(e)||Ixe(e)){let n=`'${e.replace(/'/g,`'"'"'`)}'`;return fy(e)?n:t?`${n} < /dev/null`:n}return dc(t?[e,`<`,`/dev/null`]:[e])}function Rxe(e){return/(?:^|[\s;&|])<(?![<(])\s*\S+/.test(e)}function zxe(e){return!(fy(e)||Rxe(e))}function Bxe(e){return e.replace(Vxe,`$1/dev/null`)}var Vxe,Hxe=n((()=>{pc(),Vxe=/(\d?&?>+\s*)[Nn][Uu][Ll](?=\s|$|[|&;)\n])/g}));function Uxe(){return py}function Wxe(){py.clear()}var py,my=n((()=>{py=new Map}));function Gxe(){return null}function Kxe(e){return process.env.CLAUDE_CODE_SHELL_PREFIX?`{ shopt -u extglob || setopt NO_EXTENDED_GLOB; } >/dev/null 2>&1 || true`:e.includes(`bash`)?`shopt -u extglob 2>/dev/null || true`:e.includes(`zsh`)?`setopt NO_EXTENDED_GLOB 2>/dev/null || true`:null}async function qxe(e,t){let n,r=t?.skipSnapshot?Promise.resolve(void 0):Mxe(e).catch(e=>{U(`Failed to create shell snapshot: ${e}`)}),i;return{type:`bash`,shellPath:e,detached:!0,async buildExecCommand(t,a){let o=await r;if(o)try{await lue(o)}catch{U(`Snapshot file missing, falling back to login shell: ${o}`),o=void 0}i=o,n=a.sandboxTmpDir;let s=Wc(),c=la()===`windows`?pa(s):s,l=a.useSandbox?Zl(a.sandboxTmpDir,`cwd-${a.id}`):Zl(c,`claude-${a.id}-cwd`),u=a.useSandbox?Zl(a.sandboxTmpDir,`cwd-${a.id}`):Y(s,`claude-${a.id}-cwd`),d=Bxe(t),f=zxe(d),p=Lxe(d,f);(t.includes(`<<`)||t.includes(`
567
+ `))&&(U(`Shell: Command before quoting (first 500 chars):\n${t.slice(0,500)}`),U(`Shell: Quoted command (first 500 chars):\n${p.slice(0,500)}`)),d.includes(`|`)&&f&&(p=gxe(d));let m=[];if(o){let e=la()===`windows`?pa(o):o;m.push(`source ${dc([e])} 2>/dev/null || true`)}let h=await rxe();h&&m.push(h);let g=Kxe(e);g&&m.push(g),m.push(`eval ${p}`),m.push(`pwd -P >| ${dc([l])}`);let _=m.join(` && `);return process.env.CLAUDE_CODE_SHELL_PREFIX&&(_=Pxe(process.env.CLAUDE_CODE_SHELL_PREFIX,_)),{commandString:_,cwdFilePath:u}},getSpawnArgs(e){let t=i!==void 0;return t&&U(`Spawning shell without login (-l flag skipped)`),[`-c`,...t?[]:[`-l`],e]},async getEnvironmentOverrides(e){let t=Gxe(),r={};if(t&&(r.TMUX=t),n){let e=n;la()===`windows`&&(e=pa(e)),r.TMPDIR=e,r.CLAUDE_CODE_TMPDIR=e,r.TMPPREFIX=Zl(e,`zsh`)}for(let[e,t]of Uxe())r[e]=t;return r}}}var Jxe=n((()=>{wxe(),Nxe(),Fxe(),pc(),Hxe(),W(),ua(),zv(),my(),fa()}));async function Yxe(e){try{return(await Nl(e)).isFile()?e:null}catch{return null}}async function Xxe(){let e=await sa(`pwsh`);if(e){if(la()===`linux`){let t=await Al(e).catch(()=>e);if(e.startsWith(`/snap/`)||t.startsWith(`/snap/`)){let e=await Yxe(`/opt/microsoft/powershell/7/pwsh`)??await Yxe(`/usr/bin/pwsh`);if(e){let t=await Al(e).catch(()=>e);if(!e.startsWith(`/snap/`)&&!t.startsWith(`/snap/`))return e}}}return e}return await sa(`powershell`)||null}function hy(){return gy||(gy=Xxe()),gy}async function Zxe(){let e=await hy();return e?e.split(/[/\\]/).pop().toLowerCase().replace(/\.exe$/,``)===`pwsh`?`core`:`desktop`:null}var gy,_y=n((()=>{ua(),ca(),gy=null}));function Qxe(e){return[`-NoProfile`,`-NonInteractive`,`-Command`,e]}function $xe(e){return Buffer.from(e,`utf16le`).toString(`base64`)}function eSe(e){let t;return{type:`powershell`,shellPath:e,detached:!1,async buildExecCommand(n,r){t=r.useSandbox?r.sandboxTmpDir:void 0;let i=r.useSandbox&&r.sandboxTmpDir?Zl(r.sandboxTmpDir,`claude-pwd-ps-${r.id}`):Y(Wc(),`claude-pwd-ps-${r.id}`),a=n+`\n; $_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }\n; (Get-Location).Path | Out-File -FilePath '${i.replace(/'/g,`''`)}' -Encoding utf8 -NoNewline\n; exit $_ec`;return{commandString:r.useSandbox?[`'${e.replace(/'/g,`'\\''`)}'`,`-NoProfile`,`-NonInteractive`,`-EncodedCommand`,$xe(a)].join(` `):a,cwdFilePath:i}},getSpawnArgs(e){return Qxe(e)},async getEnvironmentOverrides(){let e={};for(let[t,n]of Uxe())e[t]=n;return t&&(e.TMPDIR=t,e.CLAUDE_CODE_TMPDIR=t),e}}}var tSe=n((()=>{my()}));function vy(e){try{return Tle(e,ul.X_OK),!0}catch{try{return Ll(e,[`--version`],{timeout:1e3,stdio:`ignore`}),!0}catch{return!1}}}async function nSe(){let e=process.env.CLAUDE_CODE_SHELL;if(e){if((e.includes(`bash`)||e.includes(`zsh`))&&vy(e))return U(`Using shell override: ${e}`),e;U(`CLAUDE_CODE_SHELL="${e}" is not a valid bash/zsh path, falling back to detection`)}let t=process.env.SHELL,n=t&&(t.includes(`bash`)||t.includes(`zsh`)),r=t?.includes(`bash`),[i,a]=await Promise.all([sa(`zsh`),sa(`bash`)]),o=[`/bin`,`/usr/bin`,`/usr/local/bin`,`/opt/homebrew/bin`],s=(r?[`bash`,`zsh`]:[`zsh`,`bash`]).flatMap(e=>o.map(t=>`${t}/${e}`));r?(a&&s.unshift(a),i&&s.push(i)):(i&&s.unshift(i),a&&s.push(a)),n&&vy(t)&&s.unshift(t);let c=s.find(e=>e&&vy(e));if(!c){let e=`No suitable shell found. Work Mate CLI requires a Posix shell environment. Please ensure you have a valid shell installed and the SHELL environment variable set.`;throw q(Error(e)),Error(e)}return c}async function rSe(){return{provider:await qxe(await nSe())}}async function yy(e,t,n,r){let{timeout:i,onProgress:a,preventCwdChanges:o,shouldUseSandbox:s,shouldAutoBackground:c,onStdout:l}=r??{},u=i||iSe,d=await sSe[n](),f=Math.floor(Math.random()*65536).toString(16).padStart(4,`0`),p=Zl(process.env.CLAUDE_CODE_TMPDIR||Wc(),Owt()),{commandString:m,cwdFilePath:h}=await d.buildExecCommand(e,{id:f,sandboxTmpDir:s?p:void 0,useSandbox:s??!1}),g=m,_=vne();try{await Al(_)}catch{let e=Xt();U(`Shell CWD "${_}" no longer exists, recovering to "${e}"`);try{await Al(e),Pte(e),_=e}catch{return fTt(`Working directory "${_}" no longer exists. Please restart Work Mate from an existing directory.`)}}if(t.aborted)return dTt();let v=d.shellPath,y=s&&n===`powershell`,b=y?`/bin/sh`:v;if(s){g=await Tg.wrapWithSandbox(g,b,void 0,t);try{await G().mkdir(p,{mode:448})}catch(e){U(`Failed to create ${p} directory: ${e}`)}}let x=y?`/bin/sh`:v,S=y?[`-c`,g]:d.getSpawnArgs(g),C=await d.getEnvironmentOverrides(e),w=!!l,T=new kv(s5(`local_bash`),a??null,!w);await El(z8(),{recursive:!0});let E;if(!w){let e=ul.O_NOFOLLOW??0;E=await Dl(T.path,process.platform===`win32`?`w`:ul.O_WRONLY|ul.O_CREAT|ul.O_APPEND|e)}try{let e=Rl(x,S,{env:{...kc(),SHELL:n===`bash`?v:void 0,GIT_EDITOR:`true`,CLAUDECODE:`1`,...C},cwd:_,stdio:w?[`pipe`,`pipe`,`pipe`]:[`pipe`,E?.fd,E?.fd],detached:d.detached,windowsHide:!0}),r=uTt(e,t,u,T,c);if(E!==void 0)try{await E.close()}catch{}e.stdout&&l&&e.stdout.on(`data`,e=>{l(typeof e==`string`?e:e.toString())});let i=la()===`windows`?da(h):h;return r.result.then(async e=>{if(s&&Tg.cleanupAfterCommand(),e&&!o&&!e.backgroundTaskId)try{let e=dl(i,{encoding:`utf8`}).trim();la()===`windows`&&(e=da(e)),e.normalize(`NFC`)!==_&&(by(e,_),Fv(),mxe(_,e))}catch{J(`tengu_shell_set_cwd`,{success:!1})}try{Rle(i)}catch{}}),r}catch(e){if(E!==void 0)try{await E.close()}catch{}return T.clear(),U(`Shell exec error: ${H(e)}`),dTt(void 0,{code:126,stderr:H(e)})}}function by(e,t){let n=Yc(e)?e:el(t||G().cwd(),e),r;try{r=G().realpathSync(n)}catch(e){throw xn(e)?Error(`Path "${n}" does not exist`):e}Pte(r);try{J(`tengu_shell_set_cwd`,{success:!0})}catch{}}var iSe,aSe,oSe,sSe,xy=n((()=>{d(),Da(),Wt(),l5(),vn(),W(),On(),Bn(),Qi(),_Tt(),o5(),Nv(),ca(),ry(),R8(),ua(),Eg(),zv(),Jxe(),_y(),tSe(),Ac(),fa(),iSe=1800*1e3,aSe=u(rSe),oSe=u(async()=>{let e=await hy();if(!e)throw Error(`PowerShell is not available`);return eSe(e)}),sSe={bash:async()=>(await aSe()).provider,powershell:oSe}}));function cSe(e){let t=e.split(`
568
568
  `),n=0;for(;n<t.length&&t[n]?.trim()===``;)n++;let r=t.length-1;for(;r>=0&&t[r]?.trim()===``;)r--;return n>r?``:t.slice(n,r+1).join(`
569
569
  `)}function Sy(e){return/^data:image\/[a-z0-9.+_-]+;base64,/i.test(e)}function lSe(e){let t=e.trim().match(mSe);return!t?.[1]||!t[2]?null:{mediaType:t[1],data:t[2]}}function uSe(e,t){let n=lSe(e);return n?{tool_use_id:t,type:`tool_result`,content:[{type:`image`,source:{type:`base64`,media_type:n.mediaType,data:n.data}}]}:null}async function dSe(e,t,n){let r=e;if(t){if((n??(await Nl(t)).size)>hSe)return null;r=await Ol(t,`utf8`)}let i=lSe(r);if(!i)return null;let a=Buffer.from(i.data,`base64`),o=i.mediaType.split(`/`)[1]||`png`,s=await X_(a,a.length,o);return`data:image/${s.mediaType};base64,${s.buffer.toString(`base64`)}`}function fSe(e){let t=Sy(e);if(t)return{totalLines:1,truncatedContent:e,isImage:t};let n=mv();if(e.length<=n)return{totalLines:Ya(e,`
570
570
  `)+1,truncatedContent:e,isImage:t};let r=`${e.slice(0,n)}\n\n... [${Ya(e,`
@@ -665,8 +665,8 @@ Parameters:
665
665
  if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
666
666
  ...iss,
667
667
  path: iss.path ? [${TD(e)}, ...iss.path] : [${TD(e)}]
668
- })));`),t.write(`newResult[${TD(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=ED,o=!vD.jitless,s=o&&RD.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??(l=n.value);let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||(i=r(t.shape)),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?$O(e,u,t,f):QO(e,u,t))):i?$O(r,u,t,f):QO(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>QO(t,u,e))):QO(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}}),Vk=Q(`$ZodUnion`,(e,t)=>{ck.init(e,t),CD(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),CD(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),CD(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),CD(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>SD(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>ek(t,n,e,r)):ek(a,n,e,r)}}),Hk=Q(`$ZodIntersection`,(e,t)=>{ck.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>nk(e,t,n)):nk(e,i,a)}}),Uk=Q(`$ZodRecord`,(e,t)=>{ck.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!DD(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...MD(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...MD(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s=s??[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>PD(e,r,gD())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...MD(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...MD(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Wk=Q(`$ZodEnum`,(e,t)=>{ck.init(e,t);let n=tje(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>zD.has(typeof e)).map(e=>typeof e==`string`?OD(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),Gk=Q(`$ZodLiteral`,(e,t)=>{ck.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?OD(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),Kk=Q(`$ZodTransform`,(e,t)=>{ck.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new _D;return e.value=r,e}}),qk=Q(`$ZodOptional`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),CD(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${SD(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),Jk=Q(`$ZodNullable`,(e,t)=>{ck.init(e,t),CD(e._zod,`optin`,()=>t.innerType._zod.optin),CD(e._zod,`optout`,()=>t.innerType._zod.optout),CD(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${SD(e.source)}|null)$`):void 0}),CD(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Yk=Q(`$ZodDefault`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>rk(e,t)):rk(r,t)}}),Xk=Q(`$ZodPrefault`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Zk=Q(`$ZodNonOptional`,(e,t)=>{ck.init(e,t),CD(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ik(t,e)):ik(i,e)}}),Qk=Q(`$ZodCatch`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`optout`,()=>t.innerType._zod.optout),CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>PD(e,n,gD()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>PD(e,n,gD()))},input:e.value}),e.issues=[]),e)}}),$k=Q(`$ZodPipe`,(e,t)=>{ck.init(e,t),CD(e._zod,`values`,()=>t.in._zod.values),CD(e._zod,`optin`,()=>t.in._zod.optin),CD(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ak(e,t,n)):ak(r,t,n)}}),eA=Q(`$ZodReadonly`,(e,t)=>{ck.init(e,t),CD(e._zod,`propValues`,()=>t.innerType._zod.propValues),CD(e._zod,`values`,()=>t.innerType._zod.values),CD(e._zod,`optin`,()=>t.innerType._zod.optin),CD(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ok):ok(r)}}),tA=Q(`$ZodCustom`,(e,t)=>{OO.init(e,t),ck.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>sk(t,n,r,e));sk(i,n,r,e)}})}));function yje(){return new nA}var nA,rA,bje=n((()=>{nA=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}},rA=yje()}));function xje(e,t){return new e({type:`string`,...AD(t)})}function Sje(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...AD(t)})}function iA(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...AD(t)})}function Cje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...AD(t)})}function wje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...AD(t)})}function Tje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...AD(t)})}function Eje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...AD(t)})}function Dje(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...AD(t)})}function Oje(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...AD(t)})}function kje(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...AD(t)})}function Aje(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...AD(t)})}function jje(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...AD(t)})}function Mje(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...AD(t)})}function Nje(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...AD(t)})}function Pje(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...AD(t)})}function Fje(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...AD(t)})}function Ije(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...AD(t)})}function Lje(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...AD(t)})}function Rje(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...AD(t)})}function zje(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...AD(t)})}function Bje(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...AD(t)})}function Vje(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...AD(t)})}function Hje(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...AD(t)})}function Uje(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...AD(t)})}function Wje(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...AD(t)})}function Gje(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...AD(t)})}function Kje(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...AD(t)})}function qje(e,t){return new e({type:`number`,checks:[],...AD(t)})}function Jje(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...AD(t)})}function Yje(e,t){return new e({type:`boolean`,...AD(t)})}function Xje(e){return new e({type:`unknown`})}function Zje(e,t){return new e({type:`never`,...AD(t)})}function aA(e,t){return new AO({check:`less_than`,...AD(t),value:e,inclusive:!1})}function oA(e,t){return new AO({check:`less_than`,...AD(t),value:e,inclusive:!0})}function sA(e,t){return new jO({check:`greater_than`,...AD(t),value:e,inclusive:!1})}function cA(e,t){return new jO({check:`greater_than`,...AD(t),value:e,inclusive:!0})}function lA(e,t){return new MO({check:`multiple_of`,...AD(t),value:e})}function uA(e,t){return new PO({check:`max_length`,...AD(t),maximum:e})}function dA(e,t){return new FO({check:`min_length`,...AD(t),minimum:e})}function fA(e,t){return new IO({check:`length_equals`,...AD(t),length:e})}function Qje(e,t){return new RO({check:`string_format`,format:`regex`,...AD(t),pattern:e})}function $je(e){return new zO({check:`string_format`,format:`lowercase`,...AD(e)})}function eMe(e){return new BO({check:`string_format`,format:`uppercase`,...AD(e)})}function tMe(e,t){return new VO({check:`string_format`,format:`includes`,...AD(t),includes:e})}function nMe(e,t){return new HO({check:`string_format`,format:`starts_with`,...AD(t),prefix:e})}function rMe(e,t){return new UO({check:`string_format`,format:`ends_with`,...AD(t),suffix:e})}function pA(e){return new WO({check:`overwrite`,tx:e})}function iMe(e){return pA(t=>t.normalize(e))}function aMe(){return pA(e=>e.trim())}function oMe(){return pA(e=>e.toLowerCase())}function sMe(){return pA(e=>e.toUpperCase())}function cMe(e,t,n){return new e({type:`array`,element:t,...AD(n)})}function lMe(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...AD(n)})}var uMe=n((()=>{GO(),VD()})),dMe=n((()=>{})),fMe=n((()=>{})),mA=n((()=>{yD(),QD(),GD(),vje(),GO(),YO(),VD(),DO(),bje(),qO(),dMe(),uMe(),fMe()})),hA=n((()=>{mA()}));function pMe(e){return Uje(gA,e)}function mMe(e){return Wje(_A,e)}function hMe(e){return Gje(vA,e)}function gMe(e){return Kje(yA,e)}var gA,_A,vA,yA,bA=n((()=>{mA(),Nj(),gA=Q(`ZodISODateTime`,(e,t)=>{Sk.init(e,t),GA.init(e,t)}),_A=Q(`ZodISODate`,(e,t)=>{Ck.init(e,t),GA.init(e,t)}),vA=Q(`ZodISOTime`,(e,t)=>{wk.init(e,t),GA.init(e,t)}),yA=Q(`ZodISODuration`,(e,t)=>{Tk.init(e,t),GA.init(e,t)})})),xA,SA,CA=n((()=>{mA(),xA=(e,t)=>{UD.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>fje(e,t)},flatten:{value:t=>dje(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})},Q(`ZodError`,xA),SA=Q(`ZodError`,xA,{Parent:Error})})),wA,TA,EA,DA,OA=n((()=>{mA(),CA(),wA=KD(SA),TA=qD(SA),EA=JD(SA),DA=XD(SA)}));function kA(e){return xje(WA,e)}function _Me(e){return qje(dj,e)}function AA(e){return Jje(fj,e)}function jA(e){return Yje(pj,e)}function MA(){return Xje(mj)}function vMe(e){return Zje(hj,e)}function NA(e,t){return cMe(gj,e,t)}function PA(e,t){let n={type:`object`,get shape(){return wD(this,`shape`,{...e}),this.shape},...AD(t)};return new _j(n)}function FA(e,t){return new vj({type:`union`,options:e,...AD(t)})}function yMe(e,t){return new yj({type:`intersection`,left:e,right:t})}function IA(e,t,n){return new bj({type:`record`,keyType:e,valueType:t,...AD(n)})}function LA(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new xj({type:`enum`,entries:n,...AD(t)})}function RA(e,t){return new Sj({type:`literal`,values:Array.isArray(e)?e:[e],...AD(t)})}function bMe(e){return new Cj({type:`transform`,transform:e})}function zA(e){return new wj({type:`optional`,innerType:e})}function BA(e){return new Tj({type:`nullable`,innerType:e})}function xMe(e,t){return new Ej({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function SMe(e,t){return new Dj({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function CMe(e,t){return new Oj({type:`nonoptional`,innerType:e,...AD(t)})}function wMe(e,t){return new kj({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}function VA(e,t){return new Aj({type:`pipe`,in:e,out:t})}function TMe(e){return new jj({type:`readonly`,innerType:e})}function EMe(e){let t=new OO({check:`custom`});return t._zod.check=e,t}function DMe(e,t={}){return lMe(Mj,e,t)}function OMe(e){let t=EMe(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(ID(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code=`custom`),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(ID(r))}},e(n.value,n)));return t}var HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj,lj,uj,dj,fj,pj,mj,hj,gj,_j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj=n((()=>{mA(),hA(),bA(),OA(),HA=Q(`ZodType`,(e,t)=>(ck.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>kD(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>wA(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>EA(e,t,n),e.parseAsync=async(t,n)=>TA(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>DA(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(DMe(t,n)),e.superRefine=t=>e.check(OMe(t)),e.overwrite=t=>e.check(pA(t)),e.optional=()=>zA(e),e.nullable=()=>BA(e),e.nullish=()=>zA(BA(e)),e.nonoptional=t=>CMe(e,t),e.array=()=>NA(e),e.or=t=>FA([e,t]),e.and=t=>yMe(e,t),e.transform=t=>VA(e,bMe(t)),e.default=t=>xMe(e,t),e.prefault=t=>SMe(e,t),e.catch=t=>wMe(e,t),e.pipe=t=>VA(e,t),e.readonly=()=>TMe(e),e.describe=t=>{let n=e.clone();return rA.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return rA.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return rA.get(e);let n=e.clone();return rA.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),UA=Q(`_ZodString`,(e,t)=>{lk.init(e,t),HA.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Qje(...t)),e.includes=(...t)=>e.check(tMe(...t)),e.startsWith=(...t)=>e.check(nMe(...t)),e.endsWith=(...t)=>e.check(rMe(...t)),e.min=(...t)=>e.check(dA(...t)),e.max=(...t)=>e.check(uA(...t)),e.length=(...t)=>e.check(fA(...t)),e.nonempty=(...t)=>e.check(dA(1,...t)),e.lowercase=t=>e.check($je(t)),e.uppercase=t=>e.check(eMe(t)),e.trim=()=>e.check(aMe()),e.normalize=(...t)=>e.check(iMe(...t)),e.toLowerCase=()=>e.check(oMe()),e.toUpperCase=()=>e.check(sMe())}),WA=Q(`ZodString`,(e,t)=>{lk.init(e,t),UA.init(e,t),e.email=t=>e.check(Sje(KA,t)),e.url=t=>e.check(Dje(YA,t)),e.jwt=t=>e.check(Hje(uj,t)),e.emoji=t=>e.check(Oje(XA,t)),e.guid=t=>e.check(iA(qA,t)),e.uuid=t=>e.check(Cje(JA,t)),e.uuidv4=t=>e.check(wje(JA,t)),e.uuidv6=t=>e.check(Tje(JA,t)),e.uuidv7=t=>e.check(Eje(JA,t)),e.nanoid=t=>e.check(kje(ZA,t)),e.guid=t=>e.check(iA(qA,t)),e.cuid=t=>e.check(Aje(QA,t)),e.cuid2=t=>e.check(jje($A,t)),e.ulid=t=>e.check(Mje(ej,t)),e.base64=t=>e.check(zje(sj,t)),e.base64url=t=>e.check(Bje(cj,t)),e.xid=t=>e.check(Nje(tj,t)),e.ksuid=t=>e.check(Pje(nj,t)),e.ipv4=t=>e.check(Fje(rj,t)),e.ipv6=t=>e.check(Ije(ij,t)),e.cidrv4=t=>e.check(Lje(aj,t)),e.cidrv6=t=>e.check(Rje(oj,t)),e.e164=t=>e.check(Vje(lj,t)),e.datetime=t=>e.check(pMe(t)),e.date=t=>e.check(mMe(t)),e.time=t=>e.check(hMe(t)),e.duration=t=>e.check(gMe(t))}),GA=Q(`ZodStringFormat`,(e,t)=>{uk.init(e,t),UA.init(e,t)}),KA=Q(`ZodEmail`,(e,t)=>{pk.init(e,t),GA.init(e,t)}),qA=Q(`ZodGUID`,(e,t)=>{dk.init(e,t),GA.init(e,t)}),JA=Q(`ZodUUID`,(e,t)=>{fk.init(e,t),GA.init(e,t)}),YA=Q(`ZodURL`,(e,t)=>{mk.init(e,t),GA.init(e,t)}),XA=Q(`ZodEmoji`,(e,t)=>{hk.init(e,t),GA.init(e,t)}),ZA=Q(`ZodNanoID`,(e,t)=>{gk.init(e,t),GA.init(e,t)}),QA=Q(`ZodCUID`,(e,t)=>{_k.init(e,t),GA.init(e,t)}),$A=Q(`ZodCUID2`,(e,t)=>{vk.init(e,t),GA.init(e,t)}),ej=Q(`ZodULID`,(e,t)=>{yk.init(e,t),GA.init(e,t)}),tj=Q(`ZodXID`,(e,t)=>{bk.init(e,t),GA.init(e,t)}),nj=Q(`ZodKSUID`,(e,t)=>{xk.init(e,t),GA.init(e,t)}),rj=Q(`ZodIPv4`,(e,t)=>{Ek.init(e,t),GA.init(e,t)}),ij=Q(`ZodIPv6`,(e,t)=>{Dk.init(e,t),GA.init(e,t)}),aj=Q(`ZodCIDRv4`,(e,t)=>{Ok.init(e,t),GA.init(e,t)}),oj=Q(`ZodCIDRv6`,(e,t)=>{kk.init(e,t),GA.init(e,t)}),sj=Q(`ZodBase64`,(e,t)=>{Ak.init(e,t),GA.init(e,t)}),cj=Q(`ZodBase64URL`,(e,t)=>{jk.init(e,t),GA.init(e,t)}),lj=Q(`ZodE164`,(e,t)=>{Mk.init(e,t),GA.init(e,t)}),uj=Q(`ZodJWT`,(e,t)=>{Nk.init(e,t),GA.init(e,t)}),dj=Q(`ZodNumber`,(e,t)=>{Pk.init(e,t),HA.init(e,t),e.gt=(t,n)=>e.check(sA(t,n)),e.gte=(t,n)=>e.check(cA(t,n)),e.min=(t,n)=>e.check(cA(t,n)),e.lt=(t,n)=>e.check(aA(t,n)),e.lte=(t,n)=>e.check(oA(t,n)),e.max=(t,n)=>e.check(oA(t,n)),e.int=t=>e.check(AA(t)),e.safe=t=>e.check(AA(t)),e.positive=t=>e.check(sA(0,t)),e.nonnegative=t=>e.check(cA(0,t)),e.negative=t=>e.check(aA(0,t)),e.nonpositive=t=>e.check(oA(0,t)),e.multipleOf=(t,n)=>e.check(lA(t,n)),e.step=(t,n)=>e.check(lA(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),fj=Q(`ZodNumberFormat`,(e,t)=>{Fk.init(e,t),dj.init(e,t)}),pj=Q(`ZodBoolean`,(e,t)=>{Ik.init(e,t),HA.init(e,t)}),mj=Q(`ZodUnknown`,(e,t)=>{Lk.init(e,t),HA.init(e,t)}),hj=Q(`ZodNever`,(e,t)=>{Rk.init(e,t),HA.init(e,t)}),gj=Q(`ZodArray`,(e,t)=>{zk.init(e,t),HA.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(dA(t,n)),e.nonempty=t=>e.check(dA(1,t)),e.max=(t,n)=>e.check(uA(t,n)),e.length=(t,n)=>e.check(fA(t,n)),e.unwrap=()=>e.element}),_j=Q(`ZodObject`,(e,t)=>{Bk.init(e,t),HA.init(e,t),CD(e,`shape`,()=>t.shape),e.keyof=()=>LA(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:MA()}),e.loose=()=>e.clone({...e._zod.def,catchall:MA()}),e.strict=()=>e.clone({...e._zod.def,catchall:vMe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>sje(e,t),e.merge=t=>cje(e,t),e.pick=t=>aje(e,t),e.omit=t=>oje(e,t),e.partial=(...t)=>lje(wj,e,t[0]),e.required=(...t)=>uje(Oj,e,t[0])}),vj=Q(`ZodUnion`,(e,t)=>{Vk.init(e,t),HA.init(e,t),e.options=t.options}),yj=Q(`ZodIntersection`,(e,t)=>{Hk.init(e,t),HA.init(e,t)}),bj=Q(`ZodRecord`,(e,t)=>{Uk.init(e,t),HA.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),xj=Q(`ZodEnum`,(e,t)=>{Wk.init(e,t),HA.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xj({...t,checks:[],...AD(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xj({...t,checks:[],...AD(r),entries:i})}}),Sj=Q(`ZodLiteral`,(e,t)=>{Gk.init(e,t),HA.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),Cj=Q(`ZodTransform`,(e,t)=>{Kk.init(e,t),HA.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ID(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code=`custom`),t.input??(t.input=n.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),n.issues.push(ID(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}}),wj=Q(`ZodOptional`,(e,t)=>{qk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Tj=Q(`ZodNullable`,(e,t)=>{Jk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Ej=Q(`ZodDefault`,(e,t)=>{Yk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Dj=Q(`ZodPrefault`,(e,t)=>{Xk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Oj=Q(`ZodNonOptional`,(e,t)=>{Zk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),kj=Q(`ZodCatch`,(e,t)=>{Qk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Aj=Q(`ZodPipe`,(e,t)=>{$k.init(e,t),HA.init(e,t),e.in=t.in,e.out=t.out}),jj=Q(`ZodReadonly`,(e,t)=>{eA.init(e,t),HA.init(e,t)}),Mj=Q(`ZodCustom`,(e,t)=>{tA.init(e,t),HA.init(e,t)})})),kMe=n((()=>{mA()})),Pj=n((()=>{mA(),Nj(),hA(),CA(),OA(),kMe(),VD(),bA(),Nj()})),AMe=n((()=>{Pj(),Pj()})),jMe=n((()=>{AMe()})),Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,MMe=n((()=>{jMe(),LA([`local`,`user`,`project`,`dynamic`,`enterprise`,`claudeai`,`managed`]),LA([`stdio`,`sse`,`sse-ide`,`http`,`ws`,`sdk`,`claudeai-proxy`]),Fj=PA({type:RA(`stdio`).optional(),command:kA().min(1,`Command cannot be empty`),args:NA(kA()).default([]),env:IA(kA(),kA()).optional()}),Ij=PA({clientId:kA().optional(),callbackPort:_Me().int().positive().optional(),authServerMetadataUrl:kA().url().startsWith(`https://`,{message:`authServerMetadataUrl must use https://`}).optional(),xaa:jA().optional()}),Lj=PA({type:RA(`sse`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional(),oauth:Ij.optional()}),Rj=PA({type:RA(`sse-ide`),url:kA(),ideName:kA(),ideRunningInWindows:jA().optional()}),zj=PA({type:RA(`ws-ide`),url:kA(),ideName:kA(),authToken:kA().optional(),ideRunningInWindows:jA().optional()}),Bj=PA({type:RA(`http`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional(),oauth:Ij.optional()}),Vj=PA({type:RA(`ws`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional()}),Hj=PA({type:RA(`sdk`),name:kA()}),Uj=PA({type:RA(`claudeai-proxy`),url:kA(),id:kA()}),Wj=FA([Fj,Lj,Rj,zj,Bj,Vj,Hj,Uj]),PA({mcpServers:IA(kA(),Wj)})}));function Gj(e){if(typeof e==`string`)return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,``).replace(/\uFFFD/g,``).normalize(`NFC`);if(Array.isArray(e))return e.map(e=>Gj(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=Gj(r);return t}return e}var NMe=n((()=>{}));function PMe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}var Kj,FMe=n((()=>{hDe(),qS(),Kj=2048})),qj=n((()=>{qS()})),Jj=n((()=>{qS()})),IMe=n((()=>{qj(),Jj()})),LMe=n((()=>{MMe(),NMe(),FMe(),qj(),Jj(),IMe()}));function RMe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function zMe(e,t){let n=RMe(t);return{isSearch:Yj.has(n),isRead:Xj.has(n)}}var Yj,Xj,BMe=n((()=>{Yj=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(`.`)),Xj=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 VMe(e){return e.scope===`project`||e.scope===`local`}async function HMe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&VMe(t)&&!gn()&&!lie())return qn(`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 .`)),J(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{K(e,`Executing headersHelper to get dynamic headers`);let n=await Li(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,CLAUDE_CODE_MCP_SERVER_NAME:e,CLAUDE_CODE_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=kn(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 K(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Xi(e,`Error getting headers from headersHelper: ${H(t)}`),q(Error(`Error getting MCP headers from headersHelper for server '${e}': ${H(t)}`)),null}}async function Zj(e,t){let n=t.headers||{},r=await HMe(e,t)||{};return{...n,...r}}var UMe=n((()=>{Wt(),bi(),W(),On(),zi(),Qi(),Yn(),Da()})),Qj,WMe=n((()=>{b(),Qj=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 GMe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||EM}function $j(){return Y(p(),`mcp-needs-auth-cache.json`)}function eM(){return kM||(kM=Ol($j(),`utf-8`).then(e=>kn(e)).catch(()=>({}))),kM}async function KMe(e){let t=(await eM())[e];return t?Date.now()-t.timestamp<OM:!1}function qMe(e){AM=AM.then(async()=>{let t=await eM();t[e]={timestamp:Date.now()};let n=$j();await El(qc(n),{recursive:!0}),await Il(n,V(t)),kM=null}).catch(()=>{})}function tM(){kM=null,Fl($j()).catch(()=>{})}function nM(e){let t=JT(e);return t?{mcpServerBaseUrl:t}:{}}function rM(e,t,n){return J(`tengu_mcp_server_needs_auth`,{transportType:n,...nM(t)}),K(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),qMe(e),{name:e,type:`needs-auth`,config:t}}function JMe(e){return async(t,n)=>{let r=async()=>{await Ko();let r=vo();if(!r)throw Error(`No claude.ai OAuth token available`);let i=new Headers(n?.headers);return i.set(`Authorization`,`Bearer ${r.accessToken}`),{response:await e(t,{...n,headers:i}),sentToken:r.accessToken}},{response:i,sentToken:a}=await r();if(i.status!==401)return i;let o=await po(a).catch(()=>!1);if(J(`tengu_mcp_claudeai_proxy_401`,{tokenChanged:o}),!o){let e=vo()?.accessToken;if(!e||e===a)return i}try{return(await r()).response}catch{return i}}}async function iM(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function aM(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function oM(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`,NM);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),MM,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 sM(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function YMe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function cM(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function XMe(e){return!e.name.startsWith(`mcp__ide__`)||PM.includes(e.name)}function lM(e,t){return`${e}-${V(t)}`}async function uM(e,t){let n=lM(e,t);try{let n=await FM(e,t);n.type===`connected`&&await n.cleanup()}catch{}FM.cache.delete(n),LM.cache.delete(e),RM.cache.delete(e),zM.cache.delete(e)}async function dM(e){if(e.config.type===`sdk`)return e;let t=await FM(e.name,e.config);if(t.type!==`connected`)throw new Hn(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function ZMe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return V(r)===V(a)}function QMe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function fM(e,t,n){return(await xM({client:n,tool:e,args:t,signal:rD().signal})).content}async function pM(e,t){try{wo(),await uM(e,t);let n=await FM(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};t.type===`claudeai-proxy`&&lT(e);let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([LM(n),zM(n),Promise.resolve([]),r?RM(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([Aw,tD].some(e=>i.some(t=>Ws(t,e.name)))||l.push(Aw,tD)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return Xi(e,`Error during reconnection: ${H(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function mM(e,t,n){await zue(e,n,{concurrency:t})}async function hM(e,t){let n=!1,r=Object.entries(t??(await AT()).servers),i=[];for(let t of r)PT(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=hr(i,([e,t])=>t.type===`stdio`),s=hr(i,([e,t])=>t.type===`sse`),c=hr(i,([e,t])=>t.type===`http`),l=hr(i,([e,t])=>t.type===`sse-ide`),u=hr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>cM(t)),f=i.filter(([e,t])=>!cM(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(PT(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}if((r.type===`claudeai-proxy`||r.type===`http`||r.type===`sse`)&&(await KMe(t)||(r.type===`http`||r.type===`sse`)&&MAe(t,r))){K(t,`Skipping connection (cached needs-auth)`),e({client:{name:t,type:`needs-auth`,config:r},tools:[WE(t,r)],commands:[]});return}let i=await FM(t,r,p);if(i.type!==`connected`){e({client:i,tools:i.type===`needs-auth`?[WE(t,r)]:[],commands:[]});return}r.type===`claudeai-proxy`&&lT(t);let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([LM(i),zM(i),Promise.resolve([]),a?RM(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(Aw,tD)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){Xi(t,`Error fetching tools/commands/resources: ${H(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([mM(d,sM(),m),mM(f,YMe(),m)])}function gM(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=[];hM(e=>{if(i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n){let e=o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0);J(`tengu_mcp_tools_commands_loaded`,{tools_count:a.length,commands_count:o.length,commands_metadata_length:e}),t({clients:i,tools:a,commands:o})}},e).catch(e=>{Xi(`prefetchAllMcpResources`,`Failed to get MCP resources: ${H(e)}`),t({clients:[],tools:[],commands:[]})})})}async function _M(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 vM(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 X_(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(jM.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await X_(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 vM(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 vM(e,t,n,r){let i=await qE(e,t,`mcp-${ri(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:JE(i.filepath,t,i.size,r)}]}function yM(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${yM(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${yM(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function $Me(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:V(e.structuredContent),type:`structuredContent`,schema:yM(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>_M(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:yM(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Xi(n,i),new Hn(i,`MCP tool unexpected response format`)}function bM(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function eNe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await $Me(e,t,n,r);if(n===`ide`||i&&!bM(a)||!await WOe(a))return a;let c=Nw(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await KOe(a);if(!a)return a;if(bM(a))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await KOe(a);let l=Date.now(),u=`mcp-${ri(n)}-${ri(t)}-${l}`,d=nNe(a),p=typeof a==`string`?a:d??V(a,null,2),m=await My(p,u);if(Iy(m)){let e=p.length;return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`persist_failed`,sizeEstimateTokens:c}),`Error: result (${e.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${m.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`}J(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?KE(o,s):KE(`toolResult`);return BAe(m.filepath,m.originalSize,h)}function tNe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function nNe(e){if(!tNe()||!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 rNe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=xM,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 KS)||e.code!==zx.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 K(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;K(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 pD(s,e,a);if(r){if(K(s,`URL elicitation ${t} resolved by hook: ${V(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 mD(s,i,a,`url`,t);if(c.action!==`accept`)return K(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.`};K(s,`Elicitation ${t} completed, retrying tool call`)}}}async function xM({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{K(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;K(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=GMe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new Hn(`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},jS,{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 Xi(t,e),new wM(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;K(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`}`);let g=XAe(t);return g&&J(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await eNe(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`&&K(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 _w)throw K(t,`Tool call returned 401 Unauthorized - token may have expired`),J(`tengu_mcp_tool_call_auth_error`,{}),new SM(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=TM(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&(n.type===`http`||n.type===`claudeai-proxy`);if(r||i)throw K(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),J(`tengu_mcp_session_expired`,{}),await uM(t,n),new CM(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function iNe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function aNe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new Qj(e,t),i=new QS({name:`workmate`,title:`Work Mate`,version:`0.0.14`,description:`Agentic coding tool`,websiteUrl:Ew},{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 LM(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Xi(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 SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM,zM,BM=n((()=>{hDe(),uOe(),vOe(),SOe(),IC(),qS(),ah(),d(),Lge(),Bue(),Wt(),Ha(),Dw(),Ks(),jw(),oke(),zAe(),nD(),oD(),Cr(),no(),Jn(),lD(),W(),h(),On(),Jae(),CN(),rv(),Qi(),YE(),JOe(),ZAe(),oa(),Sse(),Xs(),Pse(),Ac(),zy(),Da(),hD(),Ur(),$r(),YT(),LMe(),b(),bw(),BMe(),ao(),Po(),UE(),pT(),zT(),UMe(),WMe(),Yn(),SM=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},CM=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},wM=class extends Hn{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},TM=PMe,EM=1e8,DM=Kj,OM=900*1e3,kM=null,AM=Promise.resolve(),jM=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),MM=6e4,NM=`application/json, text/event-stream`,PM=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],FM=u(async(e,t,n)=>{let r=Date.now();try{let i,a=$s();if(t.type===`sse`){let n=new HE(e,t),r=await Zj(e,t),a={authProvider:n,fetch:oM(NE(FC(),n)),requestInit:{headers:{"User-Agent":Lo(),...r}}};a.eventSourceInit={fetch:async(e,t)=>{let i={},a=await n.tokens();a&&(i.Authorization=`Bearer ${a.access_token}`);let o=Ys();return fetch(e,{...t,...o,headers:{"User-Agent":Lo(),...i,...t?.headers,...r,Accept:`text/event-stream`}})}},i=new xw(new URL(t.url),a),K(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){K(e,`Setting up SSE-IDE transport to ${t.url}`);let n=Ys(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":Lo(),...t?.headers}})}}:{};i=new xw(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=Cse(),n={"User-Agent":Lo(),...t.authToken&&{"X-Claude-Code-Ide-Authorization":t.authToken}},r;r=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:n,proxy:xse(t.url),tls:e||void 0}):await iM(t.url,{headers:n,agent:Tse(t.url),...e||{}}),i=new fD(r)}else if(t.type===`ws`){K(e,`Initializing WebSocket transport to ${t.url}`);let n=await Zj(e,t),r=Cse(),o={"User-Agent":Lo(),...a&&{Authorization:`Bearer ${a}`},...n},s=ih(o,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);K(e,`WebSocket transport options: ${V({url:t.url,headers:s,hasSessionAuth:!!a})}`);let c;c=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:o,proxy:xse(t.url),tls:r||void 0}):await iM(t.url,{headers:o,agent:Tse(t.url),...r||{}}),i=new fD(c)}else if(t.type===`http`){K(e,`Initializing HTTP transport to ${t.url}`),K(e,`Node version: ${process.version}, Platform: ${process.platform}`),K(e,`Environment: ${V({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=new HE(e,t),r=await Zj(e,t),o=!!await n.tokens(),s=Ys();K(e,`Proxy options: ${s.dispatcher?`custom dispatcher`:`default`}`);let c={authProvider:n,fetch:oM(NE(FC(),n)),requestInit:{...s,headers:{"User-Agent":Lo(),...a&&!o&&{Authorization:`Bearer ${a}`},...r}}},l=c.requestInit?.headers?ih(c.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;K(e,`HTTP transport options: ${V({url:t.url,headers:l,hasAuthProvider:!!n,timeoutMs:MM})}`),i=new ww(new URL(t.url),c),K(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`claudeai-proxy`){if(K(e,`Initializing claude.ai proxy transport for server ${t.id}`),!vo())throw Error(`No claude.ai OAuth token found`);let n=Va(),r=`${n.MCP_PROXY_URL}${n.MCP_PROXY_PATH.replace(`{server_id}`,t.id)}`;K(e,`Using claude.ai proxy at ${r}`);let a=JMe(globalThis.fetch),o=Ys(),s={fetch:oM(a),requestInit:{...o,headers:{"User-Agent":Lo(),"X-Mcp-Client-Session-Id":sn()}}};i=new ww(new URL(r),s),K(e,`claude.ai proxy transport created successfully`)}else if(t.type===`stdio`||!t.type){let e=t;i=new _Oe({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...kc(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let o,s=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(o=e=>{if(s.length<64*1024*1024)try{s+=e.toString()}catch{}},e.stderr.on(`data`,o))}let c=new QS({name:`workmate`,title:`Work Mate`,version:`0.0.14`,description:`Agentic coding tool`,websiteUrl:Ew},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&K(e,`Client created, setting up request handler`),c.setRequestHandler(WS,async()=>(K(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Xt()}`}]})),K(e,`Starting connection with timeout of ${aM()}ms`),t.type===`http`){K(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);K(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&K(e,`Using loopback address: ${n.hostname}`)}catch(t){K(e,`Failed to parse URL: ${t}`)}}let l=c.connect(i),u=new Promise((t,n)=>{let a=setTimeout(()=>{K(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${aM()}ms)`),i.close().catch(()=>{}),n(new Hn(`MCP server "${e}" connection timed out after ${aM()}ms`,`MCP connection timeout`))},aM());l.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([l,u]),s&&(Xi(e,`Server stderr: ${s}`),s=``);let n=Date.now()-r;K(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(K(e,`SSE Connection failed after ${a}ms: ${V({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Xi(e,n),n instanceof _w)return rM(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(K(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Xi(e,n),n instanceof _w)return rM(e,t,`http`)}else if(t.type===`claudeai-proxy`&&n instanceof Error){if(K(e,`claude.ai proxy connection failed after ${a}ms: ${n.message}`),Xi(e,n),n.code===401)return rM(e,t,`claudeai-proxy`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&J(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),s&&Xi(e,`Server stderr: ${s}`),n}let d=c.getServerCapabilities(),f=c.getServerVersion(),p=c.getInstructions(),m=p;if(p&&p.length>DM&&(m=`${p.slice(0,DM)}… [truncated]`,K(e,`Server instructions truncated from ${p.length} to ${DM} chars`)),K(e,`Connection established with capabilities: ${V({hasTools:!!d?.tools,hasPrompts:!!d?.prompts,hasResources:!!d?.resources,hasResourceSubscribe:!!d?.resources?.subscribe,serverVersion:f||`unknown`})}`),U(`[MCP] Server "${e}" connected with subscribe=${!!d?.resources?.subscribe}`),c.setRequestHandler(BS,async t=>(K(e,`Elicitation request received during initialization: ${V(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){J(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:f});try{bNe(c)}catch(t){Xi(e,`Failed to send ide_connected notification: ${t}`)}}let h=Date.now(),g=!1,_=c.onerror,v=c.onclose,y=0,b=!1,x=t=>{b||(b=!0,K(e,`Closing transport (${t})`),c.close().catch(t=>{K(e,`Error during close: ${H(t)}`)}))},S=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`);c.onerror=n=>{let r=Date.now()-h;g=!0;let i=t.type||`stdio`;if(K(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?K(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?K(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?K(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?K(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?K(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?K(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?K(e,`Failed to spawn process - check command and permissions`):K(e,`Connection error: ${n.message}`)),(i===`http`||i===`claudeai-proxy`)&&TM(n)){K(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),x(`session expired`),_&&_(n);return}if(i===`sse`||i===`http`||i===`claudeai-proxy`){if(n.message.includes(`Maximum reconnection attempts`)){x(`SSE reconnection exhausted`),_&&_(n);return}S(n.message)?(y++,K(e,`Terminal connection error ${y}/3`),y>=3&&(y=0,x(`max consecutive terminal errors`))):y=0}_&&_(n)},c.onclose=()=>{let n=Date.now()-h;K(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${g?`with errors`:`cleanly`})`);let r=lM(e,t);LM.cache.delete(e),RM.cache.delete(e),zM.cache.delete(e),FM.cache.delete(r),K(e,`Cleared connection cache for reconnection`),v&&v()};let C=async()=>{if(o&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,o),t.type===`stdio`)try{let t=i.pid;if(t){K(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){K(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),K(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),K(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await $o(100),!r){try{process.kill(t,0),K(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){K(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await $o(400),!r)try{process.kill(t,0),K(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){K(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){K(e,`Error terminating process: ${t}`)}try{await c.close()}catch(t){K(e,`Error closing client: ${t}`)}},w=Gn(C),T=async()=>{w?.(),await C()};return J(`tengu_mcp_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,transportType:t.type??`stdio`,totalServers:n?.totalServers,stdioCount:n?.stdioCount,sseCount:n?.sseCount,httpCount:n?.httpCount,sseIdeCount:n?.sseIdeCount,wsIdeCount:n?.wsIdeCount,...nM(t)}),{name:e,client:c,type:`connected`,capabilities:d??{},serverInfo:f,instructions:m,config:t,cleanup:T}}catch(i){let a=Date.now()-r;return J(`tengu_mcp_server_connection_failed`,{connectionDurationMs:a,totalServers:n?.totalServers||1,stdioCount:n?.stdioCount||+(t.type===`stdio`),sseCount:n?.sseCount||+(t.type===`sse`),httpCount:n?.httpCount||+(t.type===`http`),sseIdeCount:n?.sseIdeCount||+(t.type===`sse-ide`),wsIdeCount:n?.wsIdeCount||+(t.type===`ws-ide`),transportType:t.type??`stdio`,...nM(t)}),K(e,`Connection failed after ${a}ms: ${H(i)}`),Xi(e,`Connection failed: ${H(i)}`),{name:e,type:`failed`,config:t,error:H(i)}}},lM),IM=20,LM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=Gj((await e.client.request({method:`tools/list`},AS)).tools),n=e.config.type===`sdk`&&m(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Xn(e.name,t.name);return{...ake,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>DM?`${e.slice(0,DM)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return QMe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return zMe(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=iNe(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 rNe({client:await dM(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 CM&&i<1){K(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 Hn)){let e=n.constructor.name;if(e===`Error`)throw new Hn(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new Hn(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(XMe)}catch(t){return Xi(e.name,`Failed to fetch tools: ${H(t)}`),[]}},e=>e.name,IM),RM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},gS);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Xi(e.name,`Failed to fetch resources: ${H(t)}`),[]}},e=>e.name,IM),zM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},xS);return t.prompts?Gj(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${ri(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 dM(e),a=await r.client.getPrompt({name:t.name,arguments:Ige(n,i)});return(await Promise.all(a.messages.map(e=>_M(e.content,r.name)))).flat()}catch(n){throw Xi(e.name,`Error running command '${t.name}': ${H(n)}`),n}}}}):[]}catch(t){return Xi(e.name,`Failed to fetch commands: ${H(t)}`),[]}},e=>e.name,IM)}));function oNe(e){let t=Uc(),n=[],r=HM[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||Y(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||Y(t,`AppData`,`Local`);switch(gle()){case`darwin`:n.push(Y(t,`Library`,`Application Support`,`JetBrains`),Y(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(Y(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(Y(i,`JetBrains`),Y(a,`JetBrains`),Y(i)),e.toLowerCase()===`androidstudio`&&n.push(Y(a,`Google`));break;case`linux`:n.push(Y(t,`.config`,`JetBrains`),Y(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(Y(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(Y(t,`.config`,`Google`));break;default:break}return n}async function sNe(e){let t=[],n=G(),r=oNe(e),i=HM[e.toLowerCase()];if(!i)return t;let a=i.map(e=>RegExp(`^${e}`));for(let e of r)try{let r=await n.readdir(e);for(let i of a)for(let a of r){if(!i.test(a.name)||!a.isDirectory()&&!a.isSymbolicLink())continue;let r=Y(e,a.name);if(gle()===`linux`){t.push(r);continue}let o=Y(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function cNe(e){let t=await sNe(e);for(let e of t){let t=Y(e,VM);try{return await G().stat(t),!0}catch{}}return!1}async function lNe(e,t=!1){if(!t){let t=WM.get(e);if(t)return t}let n=cNe(e).then(t=>(UM.set(e,t),t));return WM.set(e,n),n}async function uNe(e,t=!1){return t&&(UM.delete(e),WM.delete(e)),lNe(e,t)}var VM,HM,UM,WM,dNe=n((()=>{Bn(),VM=`claude-code-jetbrains-plugin`,HM={pycharm:[`PyCharm`],intellij:[`IntelliJIdea`,`IdeaIC`],webstorm:[`WebStorm`],phpstorm:[`PhpStorm`],rubymine:[`RubyMine`],clion:[`CLion`],goland:[`GoLand`],rider:[`Rider`],datagrip:[`DataGrip`],appcode:[`AppCode`],dataspell:[`DataSpell`],aqua:[`Aqua`],gateway:[`Gateway`],fleet:[`Fleet`],androidstudio:[`AndroidStudio`]},UM=new Map,WM=new Map}));function fNe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var GM,KM=n((()=>{b(),GM=class{constructor(e){x(this,`wslDistroName`,void 0),this.wslDistroName=e}toLocalPath(e){if(!e)return e;if(this.wslDistroName){let t=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);if(t&&t[1]!==this.wslDistroName)return e}try{return Ll(`wslpath`,[`-u`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e.replace(/\\/g,`/`).replace(/^([A-Z]):/i,(e,t)=>`/mnt/${t.toLowerCase()}`)}}toIDEPath(e){if(!e)return e;try{return Ll(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function pNe({onDone:e,installationStatus:t}){hNe(),be({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??QM(),r=ZM(n),i=uN(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=pr.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,qM.jsxs)(qM.Fragment,{children:[(0,qM.jsx)($e,{title:(0,qM.jsxs)(qM.Fragment,{children:[(0,qM.jsx)(F,{color:`claude`,children:`✻ `}),(0,qM.jsxs)(F,{children:[`Welcome to Claude Code for `,i]})]}),subtitle:a?`installed ${o} v${a}`:void 0,color:`ide`,onCancel:e,hideInputGuide:!0,children:(0,qM.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,qM.jsxs)(F,{children:[`• Claude has context of `,(0,qM.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,qM.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,qM.jsxs)(F,{children:[`• Review Claude Code's changes `,(0,qM.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,qM.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,qM.jsxs)(F,{children:[`• Cmd+Esc`,(0,qM.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,qM.jsxs)(F,{children:[`• `,s,(0,qM.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,qM.jsx)(P,{paddingX:1,children:(0,qM.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function mNe(){let e=yi(),t=Oc.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function hNe(){if(mNe())return;let e=Oc.terminal||`unknown`;Ti(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var qM,JM=n((()=>{Dce(),I(),ub(),bi(),Ar(),CN(),qM=et()}));function YM(e){try{return process.kill(e,0),!0}catch{return!1}}function gNe(){let e=null;return()=>(e||(e=xce(process.ppid,10).then(e=>new Set(e))),e)}function XM(e){if(!e)return!1;let t=pN[e];return t&&t.ideKind===`vscode`}function ZM(e){if(!e)return!1;let t=pN[e];return t&&t.ideKind===`jetbrains`}function QM(){return gN()?pr.terminal:null}async function $M(){try{let e=await _Ne();return(await Promise.all(e.map(async e=>{try{let t=(await G().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=Y(e,t.name);try{return{path:n,mtime:(await G().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return Mn(e)||q(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return q(e),[]}}async function eN(e){try{let t=await G().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=kn(t);e.workspaceFolders&&(n=e.workspaceFolders),r=e.pid,i=e.ideName,a=e.transport===`ws`,o=e.runningInWindows===!0,s=e.authToken}catch{n=t.split(`
669
- `).map(e=>e.trim())}let c=e.split(tl).pop();if(!c)return null;let l=c.replace(`.lock`,``);return{workspaceFolders:n,port:parseInt(l,10),pid:r,ideName:i,useWebSocket:a,runningInWindows:o,authToken:s}}catch(e){return q(e),null}}async function tN(e,t,n=500){try{return new Promise(r=>{let i=bue({host:e,port:t,timeout:n});i.on(`connect`,()=>{i.destroy(),r(!0)}),i.on(`error`,()=>{r(!1)}),i.on(`timeout`,()=>{i.destroy(),r(!1)})})}catch{return!1}}async function _Ne(){let e=[Y(p(),`ide`)];if(la()!==`wsl`)return e;let t=await _N();if(t){let n=new GM(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(el(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await G().readdir(t);for(let r of n)!r.isDirectory()&&!r.isSymbolicLink()||r.name===`Public`||r.name===`Default`||r.name===`Default User`||r.name===`All Users`||e.push(Y(t,r.name,`.workmate`,`ide`))}catch(e){Mn(e)?U(`WSL IDE lockfile path detection failed (${e.code}): ${H(e)}`):q(e)}return e}async function vNe(){try{let e=await $M();for(let t of e){let e=await eN(t);if(!e){try{await G().unlink(t)}catch(e){q(e)}continue}let n=await SN(e.runningInWindows,e.port),r=!1;if(e.pid?YM(e.pid)||la()===`wsl`&&await tN(n,e.port)||(r=!0):await tN(n,e.port)||(r=!0),r)try{await G().unlink(t)}catch(e){q(e)}}}catch(e){q(e)}}async function yNe(e){try{let t=await SNe(e);return J(`tengu_ext_installed`,{}),yi().diffTool||Ti(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){J(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return q(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function nN(){vN&&vN.abort(),vN=rD();let e=vN.signal;await vNe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(pte()){await $o(1e3,e);continue}let t=await rN(!1);if(e.aborted)return null;if(t.length===1)return t[0];await $o(1e3,e)}return null}async function rN(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Xt().normalize(`NFC`),a=await $M(),o=await Promise.all(a.map(eN)),s=gNe(),c=la()!==`wsl`&&gN();for(let n of o){if(!n)continue;let a=!1;if(a=m(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(la()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!fNe(e,process.env.WSL_DISTRO_NAME))return!1;let n=el(t).normalize(`NFC`);if(i===n||i.startsWith(n+tl))return!0;t=new GM(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=el(t).normalize(`NFC`);if(la()===`windows`){let e=i.replace(/^[a-zA-Z]:/,e=>e.toUpperCase()),t=r.replace(/^[a-zA-Z]:/,e=>e.toUpperCase());return e===t||e.startsWith(t+tl)}return i===r||i.startsWith(r+tl)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!YM(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(gN()?uN(Oc.terminal):`IDE`),l=await SN(n.runningInWindows,n.port),u;u=n.useWebSocket?`ws://${l}:${n.port}`:`http://${l}:${n.port}/sse`,t.push({url:u,name:o,workspaceFolders:n.workspaceFolders,port:n.port,isValid:a,authToken:n.authToken,ideRunningInWindows:n.runningInWindows})}if(!e&&r){let e=t.filter(e=>e.isValid&&e.port===r);if(e.length===1)return e}}catch(e){q(e)}return t}async function bNe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function xNe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function iN(e){if(XM(e)){let t=await sN(e);if(t)try{if((await Li(t,[`--list-extensions`],{env:aN()})).stdout?.includes(yN))return!0}catch{}}else if(ZM(e))return await uNe(e);return!1}async function SNe(e){if(XM(e)){let t=await sN(e);if(t){let e=await CNe(t);if(!e||Xse(e,oN())){await $o(500);let n=await Li(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:aN()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=oN()}return e}}return null}function aN(){if(la()===`linux`)return{...process.env,DISPLAY:``}}function oN(){return`0.0.14`}async function CNe(e){let{stdout:t}=await Bi(e,[`--list-extensions`,`--show-versions`],{env:aN()}),n=t?.split(`
668
+ })));`),t.write(`newResult[${TD(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=ED,o=!vD.jitless,s=o&&RD.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??(l=n.value);let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||(i=r(t.shape)),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?$O(e,u,t,f):QO(e,u,t))):i?$O(r,u,t,f):QO(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>QO(t,u,e))):QO(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}}),Vk=Q(`$ZodUnion`,(e,t)=>{ck.init(e,t),CD(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),CD(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),CD(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),CD(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>SD(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>ek(t,n,e,r)):ek(a,n,e,r)}}),Hk=Q(`$ZodIntersection`,(e,t)=>{ck.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>nk(e,t,n)):nk(e,i,a)}}),Uk=Q(`$ZodRecord`,(e,t)=>{ck.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!DD(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...MD(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...MD(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s=s??[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>PD(e,r,gD())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...MD(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...MD(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Wk=Q(`$ZodEnum`,(e,t)=>{ck.init(e,t);let n=tje(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>zD.has(typeof e)).map(e=>typeof e==`string`?OD(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),Gk=Q(`$ZodLiteral`,(e,t)=>{ck.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?OD(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),Kk=Q(`$ZodTransform`,(e,t)=>{ck.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new _D;return e.value=r,e}}),qk=Q(`$ZodOptional`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),CD(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${SD(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),Jk=Q(`$ZodNullable`,(e,t)=>{ck.init(e,t),CD(e._zod,`optin`,()=>t.innerType._zod.optin),CD(e._zod,`optout`,()=>t.innerType._zod.optout),CD(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${SD(e.source)}|null)$`):void 0}),CD(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Yk=Q(`$ZodDefault`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>rk(e,t)):rk(r,t)}}),Xk=Q(`$ZodPrefault`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Zk=Q(`$ZodNonOptional`,(e,t)=>{ck.init(e,t),CD(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>ik(t,e)):ik(i,e)}}),Qk=Q(`$ZodCatch`,(e,t)=>{ck.init(e,t),e._zod.optin=`optional`,CD(e._zod,`optout`,()=>t.innerType._zod.optout),CD(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>PD(e,n,gD()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>PD(e,n,gD()))},input:e.value}),e.issues=[]),e)}}),$k=Q(`$ZodPipe`,(e,t)=>{ck.init(e,t),CD(e._zod,`values`,()=>t.in._zod.values),CD(e._zod,`optin`,()=>t.in._zod.optin),CD(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ak(e,t,n)):ak(r,t,n)}}),eA=Q(`$ZodReadonly`,(e,t)=>{ck.init(e,t),CD(e._zod,`propValues`,()=>t.innerType._zod.propValues),CD(e._zod,`values`,()=>t.innerType._zod.values),CD(e._zod,`optin`,()=>t.innerType._zod.optin),CD(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ok):ok(r)}}),tA=Q(`$ZodCustom`,(e,t)=>{OO.init(e,t),ck.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>sk(t,n,r,e));sk(i,n,r,e)}})}));function yje(){return new nA}var nA,rA,bje=n((()=>{nA=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}},rA=yje()}));function xje(e,t){return new e({type:`string`,...AD(t)})}function Sje(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...AD(t)})}function iA(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...AD(t)})}function Cje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...AD(t)})}function wje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...AD(t)})}function Tje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...AD(t)})}function Eje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...AD(t)})}function Dje(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...AD(t)})}function Oje(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...AD(t)})}function kje(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...AD(t)})}function Aje(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...AD(t)})}function jje(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...AD(t)})}function Mje(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...AD(t)})}function Nje(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...AD(t)})}function Pje(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...AD(t)})}function Fje(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...AD(t)})}function Ije(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...AD(t)})}function Lje(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...AD(t)})}function Rje(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...AD(t)})}function zje(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...AD(t)})}function Bje(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...AD(t)})}function Vje(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...AD(t)})}function Hje(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...AD(t)})}function Uje(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...AD(t)})}function Wje(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...AD(t)})}function Gje(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...AD(t)})}function Kje(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...AD(t)})}function qje(e,t){return new e({type:`number`,checks:[],...AD(t)})}function Jje(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...AD(t)})}function Yje(e,t){return new e({type:`boolean`,...AD(t)})}function Xje(e){return new e({type:`unknown`})}function Zje(e,t){return new e({type:`never`,...AD(t)})}function aA(e,t){return new AO({check:`less_than`,...AD(t),value:e,inclusive:!1})}function oA(e,t){return new AO({check:`less_than`,...AD(t),value:e,inclusive:!0})}function sA(e,t){return new jO({check:`greater_than`,...AD(t),value:e,inclusive:!1})}function cA(e,t){return new jO({check:`greater_than`,...AD(t),value:e,inclusive:!0})}function lA(e,t){return new MO({check:`multiple_of`,...AD(t),value:e})}function uA(e,t){return new PO({check:`max_length`,...AD(t),maximum:e})}function dA(e,t){return new FO({check:`min_length`,...AD(t),minimum:e})}function fA(e,t){return new IO({check:`length_equals`,...AD(t),length:e})}function Qje(e,t){return new RO({check:`string_format`,format:`regex`,...AD(t),pattern:e})}function $je(e){return new zO({check:`string_format`,format:`lowercase`,...AD(e)})}function eMe(e){return new BO({check:`string_format`,format:`uppercase`,...AD(e)})}function tMe(e,t){return new VO({check:`string_format`,format:`includes`,...AD(t),includes:e})}function nMe(e,t){return new HO({check:`string_format`,format:`starts_with`,...AD(t),prefix:e})}function rMe(e,t){return new UO({check:`string_format`,format:`ends_with`,...AD(t),suffix:e})}function pA(e){return new WO({check:`overwrite`,tx:e})}function iMe(e){return pA(t=>t.normalize(e))}function aMe(){return pA(e=>e.trim())}function oMe(){return pA(e=>e.toLowerCase())}function sMe(){return pA(e=>e.toUpperCase())}function cMe(e,t,n){return new e({type:`array`,element:t,...AD(n)})}function lMe(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...AD(n)})}var uMe=n((()=>{GO(),VD()})),dMe=n((()=>{})),fMe=n((()=>{})),mA=n((()=>{yD(),QD(),GD(),vje(),GO(),YO(),VD(),DO(),bje(),qO(),dMe(),uMe(),fMe()})),hA=n((()=>{mA()}));function pMe(e){return Uje(gA,e)}function mMe(e){return Wje(_A,e)}function hMe(e){return Gje(vA,e)}function gMe(e){return Kje(yA,e)}var gA,_A,vA,yA,bA=n((()=>{mA(),Nj(),gA=Q(`ZodISODateTime`,(e,t)=>{Sk.init(e,t),GA.init(e,t)}),_A=Q(`ZodISODate`,(e,t)=>{Ck.init(e,t),GA.init(e,t)}),vA=Q(`ZodISOTime`,(e,t)=>{wk.init(e,t),GA.init(e,t)}),yA=Q(`ZodISODuration`,(e,t)=>{Tk.init(e,t),GA.init(e,t)})})),xA,SA,CA=n((()=>{mA(),xA=(e,t)=>{UD.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>fje(e,t)},flatten:{value:t=>dje(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})},Q(`ZodError`,xA),SA=Q(`ZodError`,xA,{Parent:Error})})),wA,TA,EA,DA,OA=n((()=>{mA(),CA(),wA=KD(SA),TA=qD(SA),EA=JD(SA),DA=XD(SA)}));function kA(e){return xje(WA,e)}function _Me(e){return qje(dj,e)}function AA(e){return Jje(fj,e)}function jA(e){return Yje(pj,e)}function MA(){return Xje(mj)}function vMe(e){return Zje(hj,e)}function NA(e,t){return cMe(gj,e,t)}function PA(e,t){let n={type:`object`,get shape(){return wD(this,`shape`,{...e}),this.shape},...AD(t)};return new _j(n)}function FA(e,t){return new vj({type:`union`,options:e,...AD(t)})}function yMe(e,t){return new yj({type:`intersection`,left:e,right:t})}function IA(e,t,n){return new bj({type:`record`,keyType:e,valueType:t,...AD(n)})}function LA(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new xj({type:`enum`,entries:n,...AD(t)})}function RA(e,t){return new Sj({type:`literal`,values:Array.isArray(e)?e:[e],...AD(t)})}function bMe(e){return new Cj({type:`transform`,transform:e})}function zA(e){return new wj({type:`optional`,innerType:e})}function BA(e){return new Tj({type:`nullable`,innerType:e})}function xMe(e,t){return new Ej({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function SMe(e,t){return new Dj({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function CMe(e,t){return new Oj({type:`nonoptional`,innerType:e,...AD(t)})}function wMe(e,t){return new kj({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}function VA(e,t){return new Aj({type:`pipe`,in:e,out:t})}function TMe(e){return new jj({type:`readonly`,innerType:e})}function EMe(e){let t=new OO({check:`custom`});return t._zod.check=e,t}function DMe(e,t={}){return lMe(Mj,e,t)}function OMe(e){let t=EMe(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(ID(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code=`custom`),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(ID(r))}},e(n.value,n)));return t}var HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj,lj,uj,dj,fj,pj,mj,hj,gj,_j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj=n((()=>{mA(),hA(),bA(),OA(),HA=Q(`ZodType`,(e,t)=>(ck.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>kD(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>wA(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>EA(e,t,n),e.parseAsync=async(t,n)=>TA(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>DA(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(DMe(t,n)),e.superRefine=t=>e.check(OMe(t)),e.overwrite=t=>e.check(pA(t)),e.optional=()=>zA(e),e.nullable=()=>BA(e),e.nullish=()=>zA(BA(e)),e.nonoptional=t=>CMe(e,t),e.array=()=>NA(e),e.or=t=>FA([e,t]),e.and=t=>yMe(e,t),e.transform=t=>VA(e,bMe(t)),e.default=t=>xMe(e,t),e.prefault=t=>SMe(e,t),e.catch=t=>wMe(e,t),e.pipe=t=>VA(e,t),e.readonly=()=>TMe(e),e.describe=t=>{let n=e.clone();return rA.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return rA.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return rA.get(e);let n=e.clone();return rA.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),UA=Q(`_ZodString`,(e,t)=>{lk.init(e,t),HA.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Qje(...t)),e.includes=(...t)=>e.check(tMe(...t)),e.startsWith=(...t)=>e.check(nMe(...t)),e.endsWith=(...t)=>e.check(rMe(...t)),e.min=(...t)=>e.check(dA(...t)),e.max=(...t)=>e.check(uA(...t)),e.length=(...t)=>e.check(fA(...t)),e.nonempty=(...t)=>e.check(dA(1,...t)),e.lowercase=t=>e.check($je(t)),e.uppercase=t=>e.check(eMe(t)),e.trim=()=>e.check(aMe()),e.normalize=(...t)=>e.check(iMe(...t)),e.toLowerCase=()=>e.check(oMe()),e.toUpperCase=()=>e.check(sMe())}),WA=Q(`ZodString`,(e,t)=>{lk.init(e,t),UA.init(e,t),e.email=t=>e.check(Sje(KA,t)),e.url=t=>e.check(Dje(YA,t)),e.jwt=t=>e.check(Hje(uj,t)),e.emoji=t=>e.check(Oje(XA,t)),e.guid=t=>e.check(iA(qA,t)),e.uuid=t=>e.check(Cje(JA,t)),e.uuidv4=t=>e.check(wje(JA,t)),e.uuidv6=t=>e.check(Tje(JA,t)),e.uuidv7=t=>e.check(Eje(JA,t)),e.nanoid=t=>e.check(kje(ZA,t)),e.guid=t=>e.check(iA(qA,t)),e.cuid=t=>e.check(Aje(QA,t)),e.cuid2=t=>e.check(jje($A,t)),e.ulid=t=>e.check(Mje(ej,t)),e.base64=t=>e.check(zje(sj,t)),e.base64url=t=>e.check(Bje(cj,t)),e.xid=t=>e.check(Nje(tj,t)),e.ksuid=t=>e.check(Pje(nj,t)),e.ipv4=t=>e.check(Fje(rj,t)),e.ipv6=t=>e.check(Ije(ij,t)),e.cidrv4=t=>e.check(Lje(aj,t)),e.cidrv6=t=>e.check(Rje(oj,t)),e.e164=t=>e.check(Vje(lj,t)),e.datetime=t=>e.check(pMe(t)),e.date=t=>e.check(mMe(t)),e.time=t=>e.check(hMe(t)),e.duration=t=>e.check(gMe(t))}),GA=Q(`ZodStringFormat`,(e,t)=>{uk.init(e,t),UA.init(e,t)}),KA=Q(`ZodEmail`,(e,t)=>{pk.init(e,t),GA.init(e,t)}),qA=Q(`ZodGUID`,(e,t)=>{dk.init(e,t),GA.init(e,t)}),JA=Q(`ZodUUID`,(e,t)=>{fk.init(e,t),GA.init(e,t)}),YA=Q(`ZodURL`,(e,t)=>{mk.init(e,t),GA.init(e,t)}),XA=Q(`ZodEmoji`,(e,t)=>{hk.init(e,t),GA.init(e,t)}),ZA=Q(`ZodNanoID`,(e,t)=>{gk.init(e,t),GA.init(e,t)}),QA=Q(`ZodCUID`,(e,t)=>{_k.init(e,t),GA.init(e,t)}),$A=Q(`ZodCUID2`,(e,t)=>{vk.init(e,t),GA.init(e,t)}),ej=Q(`ZodULID`,(e,t)=>{yk.init(e,t),GA.init(e,t)}),tj=Q(`ZodXID`,(e,t)=>{bk.init(e,t),GA.init(e,t)}),nj=Q(`ZodKSUID`,(e,t)=>{xk.init(e,t),GA.init(e,t)}),rj=Q(`ZodIPv4`,(e,t)=>{Ek.init(e,t),GA.init(e,t)}),ij=Q(`ZodIPv6`,(e,t)=>{Dk.init(e,t),GA.init(e,t)}),aj=Q(`ZodCIDRv4`,(e,t)=>{Ok.init(e,t),GA.init(e,t)}),oj=Q(`ZodCIDRv6`,(e,t)=>{kk.init(e,t),GA.init(e,t)}),sj=Q(`ZodBase64`,(e,t)=>{Ak.init(e,t),GA.init(e,t)}),cj=Q(`ZodBase64URL`,(e,t)=>{jk.init(e,t),GA.init(e,t)}),lj=Q(`ZodE164`,(e,t)=>{Mk.init(e,t),GA.init(e,t)}),uj=Q(`ZodJWT`,(e,t)=>{Nk.init(e,t),GA.init(e,t)}),dj=Q(`ZodNumber`,(e,t)=>{Pk.init(e,t),HA.init(e,t),e.gt=(t,n)=>e.check(sA(t,n)),e.gte=(t,n)=>e.check(cA(t,n)),e.min=(t,n)=>e.check(cA(t,n)),e.lt=(t,n)=>e.check(aA(t,n)),e.lte=(t,n)=>e.check(oA(t,n)),e.max=(t,n)=>e.check(oA(t,n)),e.int=t=>e.check(AA(t)),e.safe=t=>e.check(AA(t)),e.positive=t=>e.check(sA(0,t)),e.nonnegative=t=>e.check(cA(0,t)),e.negative=t=>e.check(aA(0,t)),e.nonpositive=t=>e.check(oA(0,t)),e.multipleOf=(t,n)=>e.check(lA(t,n)),e.step=(t,n)=>e.check(lA(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),fj=Q(`ZodNumberFormat`,(e,t)=>{Fk.init(e,t),dj.init(e,t)}),pj=Q(`ZodBoolean`,(e,t)=>{Ik.init(e,t),HA.init(e,t)}),mj=Q(`ZodUnknown`,(e,t)=>{Lk.init(e,t),HA.init(e,t)}),hj=Q(`ZodNever`,(e,t)=>{Rk.init(e,t),HA.init(e,t)}),gj=Q(`ZodArray`,(e,t)=>{zk.init(e,t),HA.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(dA(t,n)),e.nonempty=t=>e.check(dA(1,t)),e.max=(t,n)=>e.check(uA(t,n)),e.length=(t,n)=>e.check(fA(t,n)),e.unwrap=()=>e.element}),_j=Q(`ZodObject`,(e,t)=>{Bk.init(e,t),HA.init(e,t),CD(e,`shape`,()=>t.shape),e.keyof=()=>LA(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:MA()}),e.loose=()=>e.clone({...e._zod.def,catchall:MA()}),e.strict=()=>e.clone({...e._zod.def,catchall:vMe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>sje(e,t),e.merge=t=>cje(e,t),e.pick=t=>aje(e,t),e.omit=t=>oje(e,t),e.partial=(...t)=>lje(wj,e,t[0]),e.required=(...t)=>uje(Oj,e,t[0])}),vj=Q(`ZodUnion`,(e,t)=>{Vk.init(e,t),HA.init(e,t),e.options=t.options}),yj=Q(`ZodIntersection`,(e,t)=>{Hk.init(e,t),HA.init(e,t)}),bj=Q(`ZodRecord`,(e,t)=>{Uk.init(e,t),HA.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),xj=Q(`ZodEnum`,(e,t)=>{Wk.init(e,t),HA.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xj({...t,checks:[],...AD(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xj({...t,checks:[],...AD(r),entries:i})}}),Sj=Q(`ZodLiteral`,(e,t)=>{Gk.init(e,t),HA.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),Cj=Q(`ZodTransform`,(e,t)=>{Kk.init(e,t),HA.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ID(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code=`custom`),t.input??(t.input=n.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),n.issues.push(ID(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}}),wj=Q(`ZodOptional`,(e,t)=>{qk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Tj=Q(`ZodNullable`,(e,t)=>{Jk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Ej=Q(`ZodDefault`,(e,t)=>{Yk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Dj=Q(`ZodPrefault`,(e,t)=>{Xk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Oj=Q(`ZodNonOptional`,(e,t)=>{Zk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),kj=Q(`ZodCatch`,(e,t)=>{Qk.init(e,t),HA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Aj=Q(`ZodPipe`,(e,t)=>{$k.init(e,t),HA.init(e,t),e.in=t.in,e.out=t.out}),jj=Q(`ZodReadonly`,(e,t)=>{eA.init(e,t),HA.init(e,t)}),Mj=Q(`ZodCustom`,(e,t)=>{tA.init(e,t),HA.init(e,t)})})),kMe=n((()=>{mA()})),Pj=n((()=>{mA(),Nj(),hA(),CA(),OA(),kMe(),VD(),bA(),Nj()})),AMe=n((()=>{Pj(),Pj()})),jMe=n((()=>{AMe()})),Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,MMe=n((()=>{jMe(),LA([`local`,`user`,`project`,`dynamic`,`enterprise`,`claudeai`,`managed`]),LA([`stdio`,`sse`,`sse-ide`,`http`,`ws`,`sdk`,`claudeai-proxy`]),Fj=PA({type:RA(`stdio`).optional(),command:kA().min(1,`Command cannot be empty`),args:NA(kA()).default([]),env:IA(kA(),kA()).optional()}),Ij=PA({clientId:kA().optional(),callbackPort:_Me().int().positive().optional(),authServerMetadataUrl:kA().url().startsWith(`https://`,{message:`authServerMetadataUrl must use https://`}).optional(),xaa:jA().optional()}),Lj=PA({type:RA(`sse`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional(),oauth:Ij.optional()}),Rj=PA({type:RA(`sse-ide`),url:kA(),ideName:kA(),ideRunningInWindows:jA().optional()}),zj=PA({type:RA(`ws-ide`),url:kA(),ideName:kA(),authToken:kA().optional(),ideRunningInWindows:jA().optional()}),Bj=PA({type:RA(`http`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional(),oauth:Ij.optional()}),Vj=PA({type:RA(`ws`),url:kA(),headers:IA(kA(),kA()).optional(),headersHelper:kA().optional()}),Hj=PA({type:RA(`sdk`),name:kA()}),Uj=PA({type:RA(`claudeai-proxy`),url:kA(),id:kA()}),Wj=FA([Fj,Lj,Rj,zj,Bj,Vj,Hj,Uj]),PA({mcpServers:IA(kA(),Wj)})}));function Gj(e){if(typeof e==`string`)return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,``).replace(/\uFFFD/g,``).normalize(`NFC`);if(Array.isArray(e))return e.map(e=>Gj(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=Gj(r);return t}return e}var NMe=n((()=>{}));function PMe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}var Kj,FMe=n((()=>{hDe(),qS(),Kj=2048})),qj=n((()=>{qS()})),Jj=n((()=>{qS()})),IMe=n((()=>{qj(),Jj()})),LMe=n((()=>{MMe(),NMe(),FMe(),qj(),Jj(),IMe()}));function RMe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function zMe(e,t){let n=RMe(t);return{isSearch:Yj.has(n),isRead:Xj.has(n)}}var Yj,Xj,BMe=n((()=>{Yj=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(`.`)),Xj=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 VMe(e){return e.scope===`project`||e.scope===`local`}async function HMe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&VMe(t)&&!gn()&&!lie())return qn(`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 .`)),J(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{K(e,`Executing headersHelper to get dynamic headers`);let n=await Li(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,CLAUDE_CODE_MCP_SERVER_NAME:e,CLAUDE_CODE_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=kn(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 K(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Xi(e,`Error getting headers from headersHelper: ${H(t)}`),q(Error(`Error getting MCP headers from headersHelper for server '${e}': ${H(t)}`)),null}}async function Zj(e,t){let n=t.headers||{},r=await HMe(e,t)||{};return{...n,...r}}var UMe=n((()=>{Wt(),bi(),W(),On(),zi(),Qi(),Yn(),Da()})),Qj,WMe=n((()=>{b(),Qj=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 GMe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||EM}function $j(){return Y(p(),`mcp-needs-auth-cache.json`)}function eM(){return kM||(kM=Ol($j(),`utf-8`).then(e=>kn(e)).catch(()=>({}))),kM}async function KMe(e){let t=(await eM())[e];return t?Date.now()-t.timestamp<OM:!1}function qMe(e){AM=AM.then(async()=>{let t=await eM();t[e]={timestamp:Date.now()};let n=$j();await El(qc(n),{recursive:!0}),await Il(n,V(t)),kM=null}).catch(()=>{})}function tM(){kM=null,Fl($j()).catch(()=>{})}function nM(e){let t=JT(e);return t?{mcpServerBaseUrl:t}:{}}function rM(e,t,n){return J(`tengu_mcp_server_needs_auth`,{transportType:n,...nM(t)}),K(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),qMe(e),{name:e,type:`needs-auth`,config:t}}function JMe(e){return async(t,n)=>{let r=async()=>{await Ko();let r=vo();if(!r)throw Error(`No claude.ai OAuth token available`);let i=new Headers(n?.headers);return i.set(`Authorization`,`Bearer ${r.accessToken}`),{response:await e(t,{...n,headers:i}),sentToken:r.accessToken}},{response:i,sentToken:a}=await r();if(i.status!==401)return i;let o=await po(a).catch(()=>!1);if(J(`tengu_mcp_claudeai_proxy_401`,{tokenChanged:o}),!o){let e=vo()?.accessToken;if(!e||e===a)return i}try{return(await r()).response}catch{return i}}}async function iM(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function aM(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function oM(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`,NM);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),MM,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 sM(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function YMe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function cM(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function XMe(e){return!e.name.startsWith(`mcp__ide__`)||PM.includes(e.name)}function lM(e,t){return`${e}-${V(t)}`}async function uM(e,t){let n=lM(e,t);try{let n=await FM(e,t);n.type===`connected`&&await n.cleanup()}catch{}FM.cache.delete(n),LM.cache.delete(e),RM.cache.delete(e),zM.cache.delete(e)}async function dM(e){if(e.config.type===`sdk`)return e;let t=await FM(e.name,e.config);if(t.type!==`connected`)throw new Hn(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function ZMe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return V(r)===V(a)}function QMe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function fM(e,t,n){return(await xM({client:n,tool:e,args:t,signal:rD().signal})).content}async function pM(e,t){try{wo(),await uM(e,t);let n=await FM(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};t.type===`claudeai-proxy`&&lT(e);let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([LM(n),zM(n),Promise.resolve([]),r?RM(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([Aw,tD].some(e=>i.some(t=>Ws(t,e.name)))||l.push(Aw,tD)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return Xi(e,`Error during reconnection: ${H(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function mM(e,t,n){await zue(e,n,{concurrency:t})}async function hM(e,t){let n=!1,r=Object.entries(t??(await AT()).servers),i=[];for(let t of r)PT(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=hr(i,([e,t])=>t.type===`stdio`),s=hr(i,([e,t])=>t.type===`sse`),c=hr(i,([e,t])=>t.type===`http`),l=hr(i,([e,t])=>t.type===`sse-ide`),u=hr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>cM(t)),f=i.filter(([e,t])=>!cM(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(PT(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}if((r.type===`claudeai-proxy`||r.type===`http`||r.type===`sse`)&&(await KMe(t)||(r.type===`http`||r.type===`sse`)&&MAe(t,r))){K(t,`Skipping connection (cached needs-auth)`),e({client:{name:t,type:`needs-auth`,config:r},tools:[WE(t,r)],commands:[]});return}let i=await FM(t,r,p);if(i.type!==`connected`){e({client:i,tools:i.type===`needs-auth`?[WE(t,r)]:[],commands:[]});return}r.type===`claudeai-proxy`&&lT(t);let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([LM(i),zM(i),Promise.resolve([]),a?RM(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(Aw,tD)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){Xi(t,`Error fetching tools/commands/resources: ${H(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([mM(d,sM(),m),mM(f,YMe(),m)])}function gM(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=[];hM(e=>{if(i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n){let e=o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0);J(`tengu_mcp_tools_commands_loaded`,{tools_count:a.length,commands_count:o.length,commands_metadata_length:e}),t({clients:i,tools:a,commands:o})}},e).catch(e=>{Xi(`prefetchAllMcpResources`,`Failed to get MCP resources: ${H(e)}`),t({clients:[],tools:[],commands:[]})})})}async function _M(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 vM(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 X_(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(jM.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await X_(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 vM(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 vM(e,t,n,r){let i=await qE(e,t,`mcp-${ri(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:JE(i.filepath,t,i.size,r)}]}function yM(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${yM(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${yM(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function $Me(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:V(e.structuredContent),type:`structuredContent`,schema:yM(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>_M(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:yM(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Xi(n,i),new Hn(i,`MCP tool unexpected response format`)}function bM(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function eNe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await $Me(e,t,n,r);if(n===`ide`||i&&!bM(a)||!await WOe(a))return a;let c=Nw(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await KOe(a);if(!a)return a;if(bM(a))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await KOe(a);let l=Date.now(),u=`mcp-${ri(n)}-${ri(t)}-${l}`,d=nNe(a),p=typeof a==`string`?a:d??V(a,null,2),m=await My(p,u);if(Iy(m)){let e=p.length;return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`persist_failed`,sizeEstimateTokens:c}),`Error: result (${e.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${m.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`}J(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?KE(o,s):KE(`toolResult`);return BAe(m.filepath,m.originalSize,h)}function tNe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function nNe(e){if(!tNe()||!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 rNe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=xM,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 KS)||e.code!==zx.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 K(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;K(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 pD(s,e,a);if(r){if(K(s,`URL elicitation ${t} resolved by hook: ${V(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 mD(s,i,a,`url`,t);if(c.action!==`accept`)return K(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.`};K(s,`Elicitation ${t} completed, retrying tool call`)}}}async function xM({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{K(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;K(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=GMe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new Hn(`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},jS,{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 Xi(t,e),new wM(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;K(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`}`);let g=XAe(t);return g&&J(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await eNe(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`&&K(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 _w)throw K(t,`Tool call returned 401 Unauthorized - token may have expired`),J(`tengu_mcp_tool_call_auth_error`,{}),new SM(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=TM(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&(n.type===`http`||n.type===`claudeai-proxy`);if(r||i)throw K(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),J(`tengu_mcp_session_expired`,{}),await uM(t,n),new CM(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function iNe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function aNe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new Qj(e,t),i=new QS({name:`workmate`,title:`Work Mate`,version:`0.0.15`,description:`Agentic coding tool`,websiteUrl:Ew},{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 LM(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Xi(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 SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM,zM,BM=n((()=>{hDe(),uOe(),vOe(),SOe(),IC(),qS(),ah(),d(),Lge(),Bue(),Wt(),Ha(),Dw(),Ks(),jw(),oke(),zAe(),nD(),oD(),Cr(),no(),Jn(),lD(),W(),h(),On(),Jae(),CN(),rv(),Qi(),YE(),JOe(),ZAe(),oa(),Sse(),Xs(),Pse(),Ac(),zy(),Da(),hD(),Ur(),$r(),YT(),LMe(),b(),bw(),BMe(),ao(),Po(),UE(),pT(),zT(),UMe(),WMe(),Yn(),SM=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},CM=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},wM=class extends Hn{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},TM=PMe,EM=1e8,DM=Kj,OM=900*1e3,kM=null,AM=Promise.resolve(),jM=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),MM=6e4,NM=`application/json, text/event-stream`,PM=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],FM=u(async(e,t,n)=>{let r=Date.now();try{let i,a=$s();if(t.type===`sse`){let n=new HE(e,t),r=await Zj(e,t),a={authProvider:n,fetch:oM(NE(FC(),n)),requestInit:{headers:{"User-Agent":Lo(),...r}}};a.eventSourceInit={fetch:async(e,t)=>{let i={},a=await n.tokens();a&&(i.Authorization=`Bearer ${a.access_token}`);let o=Ys();return fetch(e,{...t,...o,headers:{"User-Agent":Lo(),...i,...t?.headers,...r,Accept:`text/event-stream`}})}},i=new xw(new URL(t.url),a),K(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){K(e,`Setting up SSE-IDE transport to ${t.url}`);let n=Ys(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":Lo(),...t?.headers}})}}:{};i=new xw(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=Cse(),n={"User-Agent":Lo(),...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:xse(t.url),tls:e||void 0}):await iM(t.url,{headers:n,agent:Tse(t.url),...e||{}}),i=new fD(r)}else if(t.type===`ws`){K(e,`Initializing WebSocket transport to ${t.url}`);let n=await Zj(e,t),r=Cse(),o={"User-Agent":Lo(),...a&&{Authorization:`Bearer ${a}`},...n},s=ih(o,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);K(e,`WebSocket transport options: ${V({url:t.url,headers:s,hasSessionAuth:!!a})}`);let c;c=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:o,proxy:xse(t.url),tls:r||void 0}):await iM(t.url,{headers:o,agent:Tse(t.url),...r||{}}),i=new fD(c)}else if(t.type===`http`){K(e,`Initializing HTTP transport to ${t.url}`),K(e,`Node version: ${process.version}, Platform: ${process.platform}`),K(e,`Environment: ${V({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=new HE(e,t),r=await Zj(e,t),o=!!await n.tokens(),s=Ys();K(e,`Proxy options: ${s.dispatcher?`custom dispatcher`:`default`}`);let c={authProvider:n,fetch:oM(NE(FC(),n)),requestInit:{...s,headers:{"User-Agent":Lo(),...a&&!o&&{Authorization:`Bearer ${a}`},...r}}},l=c.requestInit?.headers?ih(c.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;K(e,`HTTP transport options: ${V({url:t.url,headers:l,hasAuthProvider:!!n,timeoutMs:MM})}`),i=new ww(new URL(t.url),c),K(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`claudeai-proxy`){if(K(e,`Initializing claude.ai proxy transport for server ${t.id}`),!vo())throw Error(`No claude.ai OAuth token found`);let n=Va(),r=`${n.MCP_PROXY_URL}${n.MCP_PROXY_PATH.replace(`{server_id}`,t.id)}`;K(e,`Using claude.ai proxy at ${r}`);let a=JMe(globalThis.fetch),o=Ys(),s={fetch:oM(a),requestInit:{...o,headers:{"User-Agent":Lo(),"X-Mcp-Client-Session-Id":sn()}}};i=new ww(new URL(r),s),K(e,`claude.ai proxy transport created successfully`)}else if(t.type===`stdio`||!t.type){let e=t;i=new _Oe({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...kc(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let o,s=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(o=e=>{if(s.length<64*1024*1024)try{s+=e.toString()}catch{}},e.stderr.on(`data`,o))}let c=new QS({name:`workmate`,title:`Work Mate`,version:`0.0.15`,description:`Agentic coding tool`,websiteUrl:Ew},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&K(e,`Client created, setting up request handler`),c.setRequestHandler(WS,async()=>(K(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Xt()}`}]})),K(e,`Starting connection with timeout of ${aM()}ms`),t.type===`http`){K(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);K(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&K(e,`Using loopback address: ${n.hostname}`)}catch(t){K(e,`Failed to parse URL: ${t}`)}}let l=c.connect(i),u=new Promise((t,n)=>{let a=setTimeout(()=>{K(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${aM()}ms)`),i.close().catch(()=>{}),n(new Hn(`MCP server "${e}" connection timed out after ${aM()}ms`,`MCP connection timeout`))},aM());l.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([l,u]),s&&(Xi(e,`Server stderr: ${s}`),s=``);let n=Date.now()-r;K(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(K(e,`SSE Connection failed after ${a}ms: ${V({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Xi(e,n),n instanceof _w)return rM(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(K(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Xi(e,n),n instanceof _w)return rM(e,t,`http`)}else if(t.type===`claudeai-proxy`&&n instanceof Error){if(K(e,`claude.ai proxy connection failed after ${a}ms: ${n.message}`),Xi(e,n),n.code===401)return rM(e,t,`claudeai-proxy`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&J(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),s&&Xi(e,`Server stderr: ${s}`),n}let d=c.getServerCapabilities(),f=c.getServerVersion(),p=c.getInstructions(),m=p;if(p&&p.length>DM&&(m=`${p.slice(0,DM)}… [truncated]`,K(e,`Server instructions truncated from ${p.length} to ${DM} chars`)),K(e,`Connection established with capabilities: ${V({hasTools:!!d?.tools,hasPrompts:!!d?.prompts,hasResources:!!d?.resources,hasResourceSubscribe:!!d?.resources?.subscribe,serverVersion:f||`unknown`})}`),U(`[MCP] Server "${e}" connected with subscribe=${!!d?.resources?.subscribe}`),c.setRequestHandler(BS,async t=>(K(e,`Elicitation request received during initialization: ${V(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){J(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:f});try{bNe(c)}catch(t){Xi(e,`Failed to send ide_connected notification: ${t}`)}}let h=Date.now(),g=!1,_=c.onerror,v=c.onclose,y=0,b=!1,x=t=>{b||(b=!0,K(e,`Closing transport (${t})`),c.close().catch(t=>{K(e,`Error during close: ${H(t)}`)}))},S=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`);c.onerror=n=>{let r=Date.now()-h;g=!0;let i=t.type||`stdio`;if(K(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?K(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?K(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?K(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?K(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?K(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?K(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?K(e,`Failed to spawn process - check command and permissions`):K(e,`Connection error: ${n.message}`)),(i===`http`||i===`claudeai-proxy`)&&TM(n)){K(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),x(`session expired`),_&&_(n);return}if(i===`sse`||i===`http`||i===`claudeai-proxy`){if(n.message.includes(`Maximum reconnection attempts`)){x(`SSE reconnection exhausted`),_&&_(n);return}S(n.message)?(y++,K(e,`Terminal connection error ${y}/3`),y>=3&&(y=0,x(`max consecutive terminal errors`))):y=0}_&&_(n)},c.onclose=()=>{let n=Date.now()-h;K(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${g?`with errors`:`cleanly`})`);let r=lM(e,t);LM.cache.delete(e),RM.cache.delete(e),zM.cache.delete(e),FM.cache.delete(r),K(e,`Cleared connection cache for reconnection`),v&&v()};let C=async()=>{if(o&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,o),t.type===`stdio`)try{let t=i.pid;if(t){K(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){K(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),K(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),K(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await $o(100),!r){try{process.kill(t,0),K(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){K(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await $o(400),!r)try{process.kill(t,0),K(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){K(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){K(e,`Error terminating process: ${t}`)}try{await c.close()}catch(t){K(e,`Error closing client: ${t}`)}},w=Gn(C),T=async()=>{w?.(),await C()};return J(`tengu_mcp_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,transportType:t.type??`stdio`,totalServers:n?.totalServers,stdioCount:n?.stdioCount,sseCount:n?.sseCount,httpCount:n?.httpCount,sseIdeCount:n?.sseIdeCount,wsIdeCount:n?.wsIdeCount,...nM(t)}),{name:e,client:c,type:`connected`,capabilities:d??{},serverInfo:f,instructions:m,config:t,cleanup:T}}catch(i){let a=Date.now()-r;return J(`tengu_mcp_server_connection_failed`,{connectionDurationMs:a,totalServers:n?.totalServers||1,stdioCount:n?.stdioCount||+(t.type===`stdio`),sseCount:n?.sseCount||+(t.type===`sse`),httpCount:n?.httpCount||+(t.type===`http`),sseIdeCount:n?.sseIdeCount||+(t.type===`sse-ide`),wsIdeCount:n?.wsIdeCount||+(t.type===`ws-ide`),transportType:t.type??`stdio`,...nM(t)}),K(e,`Connection failed after ${a}ms: ${H(i)}`),Xi(e,`Connection failed: ${H(i)}`),{name:e,type:`failed`,config:t,error:H(i)}}},lM),IM=20,LM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=Gj((await e.client.request({method:`tools/list`},AS)).tools),n=e.config.type===`sdk`&&m(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Xn(e.name,t.name);return{...ake,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>DM?`${e.slice(0,DM)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return QMe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return zMe(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=iNe(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 rNe({client:await dM(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 CM&&i<1){K(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 Hn)){let e=n.constructor.name;if(e===`Error`)throw new Hn(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new Hn(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(XMe)}catch(t){return Xi(e.name,`Failed to fetch tools: ${H(t)}`),[]}},e=>e.name,IM),RM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},gS);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Xi(e.name,`Failed to fetch resources: ${H(t)}`),[]}},e=>e.name,IM),zM=aa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},xS);return t.prompts?Gj(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${ri(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 dM(e),a=await r.client.getPrompt({name:t.name,arguments:Ige(n,i)});return(await Promise.all(a.messages.map(e=>_M(e.content,r.name)))).flat()}catch(n){throw Xi(e.name,`Error running command '${t.name}': ${H(n)}`),n}}}}):[]}catch(t){return Xi(e.name,`Failed to fetch commands: ${H(t)}`),[]}},e=>e.name,IM)}));function oNe(e){let t=Uc(),n=[],r=HM[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||Y(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||Y(t,`AppData`,`Local`);switch(gle()){case`darwin`:n.push(Y(t,`Library`,`Application Support`,`JetBrains`),Y(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(Y(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(Y(i,`JetBrains`),Y(a,`JetBrains`),Y(i)),e.toLowerCase()===`androidstudio`&&n.push(Y(a,`Google`));break;case`linux`:n.push(Y(t,`.config`,`JetBrains`),Y(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(Y(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(Y(t,`.config`,`Google`));break;default:break}return n}async function sNe(e){let t=[],n=G(),r=oNe(e),i=HM[e.toLowerCase()];if(!i)return t;let a=i.map(e=>RegExp(`^${e}`));for(let e of r)try{let r=await n.readdir(e);for(let i of a)for(let a of r){if(!i.test(a.name)||!a.isDirectory()&&!a.isSymbolicLink())continue;let r=Y(e,a.name);if(gle()===`linux`){t.push(r);continue}let o=Y(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function cNe(e){let t=await sNe(e);for(let e of t){let t=Y(e,VM);try{return await G().stat(t),!0}catch{}}return!1}async function lNe(e,t=!1){if(!t){let t=WM.get(e);if(t)return t}let n=cNe(e).then(t=>(UM.set(e,t),t));return WM.set(e,n),n}async function uNe(e,t=!1){return t&&(UM.delete(e),WM.delete(e)),lNe(e,t)}var VM,HM,UM,WM,dNe=n((()=>{Bn(),VM=`claude-code-jetbrains-plugin`,HM={pycharm:[`PyCharm`],intellij:[`IntelliJIdea`,`IdeaIC`],webstorm:[`WebStorm`],phpstorm:[`PhpStorm`],rubymine:[`RubyMine`],clion:[`CLion`],goland:[`GoLand`],rider:[`Rider`],datagrip:[`DataGrip`],appcode:[`AppCode`],dataspell:[`DataSpell`],aqua:[`Aqua`],gateway:[`Gateway`],fleet:[`Fleet`],androidstudio:[`AndroidStudio`]},UM=new Map,WM=new Map}));function fNe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var GM,KM=n((()=>{b(),GM=class{constructor(e){x(this,`wslDistroName`,void 0),this.wslDistroName=e}toLocalPath(e){if(!e)return e;if(this.wslDistroName){let t=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);if(t&&t[1]!==this.wslDistroName)return e}try{return Ll(`wslpath`,[`-u`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e.replace(/\\/g,`/`).replace(/^([A-Z]):/i,(e,t)=>`/mnt/${t.toLowerCase()}`)}}toIDEPath(e){if(!e)return e;try{return Ll(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function pNe({onDone:e,installationStatus:t}){hNe(),be({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??QM(),r=ZM(n),i=uN(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=pr.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,qM.jsxs)(qM.Fragment,{children:[(0,qM.jsx)($e,{title:(0,qM.jsxs)(qM.Fragment,{children:[(0,qM.jsx)(F,{color:`claude`,children:`✻ `}),(0,qM.jsxs)(F,{children:[`Welcome to Work Mate for `,i]})]}),subtitle:a?`installed ${o} v${a}`:void 0,color:`ide`,onCancel:e,hideInputGuide:!0,children:(0,qM.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,qM.jsxs)(F,{children:[`• Work Mate has context of `,(0,qM.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,qM.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,qM.jsxs)(F,{children:[`• Review Work Mate's changes `,(0,qM.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,qM.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,qM.jsxs)(F,{children:[`• Cmd+Esc`,(0,qM.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,qM.jsxs)(F,{children:[`• `,s,(0,qM.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,qM.jsx)(P,{paddingX:1,children:(0,qM.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function mNe(){let e=yi(),t=Oc.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function hNe(){if(mNe())return;let e=Oc.terminal||`unknown`;Ti(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var qM,JM=n((()=>{Dce(),I(),ub(),bi(),Ar(),CN(),qM=et()}));function YM(e){try{return process.kill(e,0),!0}catch{return!1}}function gNe(){let e=null;return()=>(e||(e=xce(process.ppid,10).then(e=>new Set(e))),e)}function XM(e){if(!e)return!1;let t=pN[e];return t&&t.ideKind===`vscode`}function ZM(e){if(!e)return!1;let t=pN[e];return t&&t.ideKind===`jetbrains`}function QM(){return gN()?pr.terminal:null}async function $M(){try{let e=await _Ne();return(await Promise.all(e.map(async e=>{try{let t=(await G().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=Y(e,t.name);try{return{path:n,mtime:(await G().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return Mn(e)||q(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return q(e),[]}}async function eN(e){try{let t=await G().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=kn(t);e.workspaceFolders&&(n=e.workspaceFolders),r=e.pid,i=e.ideName,a=e.transport===`ws`,o=e.runningInWindows===!0,s=e.authToken}catch{n=t.split(`
669
+ `).map(e=>e.trim())}let c=e.split(tl).pop();if(!c)return null;let l=c.replace(`.lock`,``);return{workspaceFolders:n,port:parseInt(l,10),pid:r,ideName:i,useWebSocket:a,runningInWindows:o,authToken:s}}catch(e){return q(e),null}}async function tN(e,t,n=500){try{return new Promise(r=>{let i=bue({host:e,port:t,timeout:n});i.on(`connect`,()=>{i.destroy(),r(!0)}),i.on(`error`,()=>{r(!1)}),i.on(`timeout`,()=>{i.destroy(),r(!1)})})}catch{return!1}}async function _Ne(){let e=[Y(p(),`ide`)];if(la()!==`wsl`)return e;let t=await _N();if(t){let n=new GM(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(el(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await G().readdir(t);for(let r of n)!r.isDirectory()&&!r.isSymbolicLink()||r.name===`Public`||r.name===`Default`||r.name===`Default User`||r.name===`All Users`||e.push(Y(t,r.name,`.workmate`,`ide`))}catch(e){Mn(e)?U(`WSL IDE lockfile path detection failed (${e.code}): ${H(e)}`):q(e)}return e}async function vNe(){try{let e=await $M();for(let t of e){let e=await eN(t);if(!e){try{await G().unlink(t)}catch(e){q(e)}continue}let n=await SN(e.runningInWindows,e.port),r=!1;if(e.pid?YM(e.pid)||la()===`wsl`&&await tN(n,e.port)||(r=!0):await tN(n,e.port)||(r=!0),r)try{await G().unlink(t)}catch(e){q(e)}}}catch(e){q(e)}}async function yNe(e){try{let t=await SNe(e);return J(`tengu_ext_installed`,{}),yi().diffTool||Ti(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){J(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return q(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function nN(){vN&&vN.abort(),vN=rD();let e=vN.signal;await vNe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(pte()){await $o(1e3,e);continue}let t=await rN(!1);if(e.aborted)return null;if(t.length===1)return t[0];await $o(1e3,e)}return null}async function rN(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Xt().normalize(`NFC`),a=await $M(),o=await Promise.all(a.map(eN)),s=gNe(),c=la()!==`wsl`&&gN();for(let n of o){if(!n)continue;let a=!1;if(a=m(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(la()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!fNe(e,process.env.WSL_DISTRO_NAME))return!1;let n=el(t).normalize(`NFC`);if(i===n||i.startsWith(n+tl))return!0;t=new GM(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=el(t).normalize(`NFC`);if(la()===`windows`){let e=i.replace(/^[a-zA-Z]:/,e=>e.toUpperCase()),t=r.replace(/^[a-zA-Z]:/,e=>e.toUpperCase());return e===t||e.startsWith(t+tl)}return i===r||i.startsWith(r+tl)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!YM(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(gN()?uN(Oc.terminal):`IDE`),l=await SN(n.runningInWindows,n.port),u;u=n.useWebSocket?`ws://${l}:${n.port}`:`http://${l}:${n.port}/sse`,t.push({url:u,name:o,workspaceFolders:n.workspaceFolders,port:n.port,isValid:a,authToken:n.authToken,ideRunningInWindows:n.runningInWindows})}if(!e&&r){let e=t.filter(e=>e.isValid&&e.port===r);if(e.length===1)return e}}catch(e){q(e)}return t}async function bNe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function xNe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function iN(e){if(XM(e)){let t=await sN(e);if(t)try{if((await Li(t,[`--list-extensions`],{env:aN()})).stdout?.includes(yN))return!0}catch{}}else if(ZM(e))return await uNe(e);return!1}async function SNe(e){if(XM(e)){let t=await sN(e);if(t){let e=await CNe(t);if(!e||Xse(e,oN())){await $o(500);let n=await Li(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:aN()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=oN()}return e}}return null}function aN(){if(la()===`linux`)return{...process.env,DISPLAY:``}}function oN(){return`0.0.15`}async function CNe(e){let{stdout:t}=await Bi(e,[`--list-extensions`,`--show-versions`],{env:aN()}),n=t?.split(`
670
670
  `)||[];for(let e of n){let[t,n]=e.split(`@`);if(t===`anthropic.claude-code`&&n)return n}return null}function wNe(){try{if(la()!==`macos`)return null;let e=process.ppid;for(let t=0;t<10&&!(!e||e===0||e===1);t++){let t=wie(`ps -o command= -p ${e}`)?.trim();if(t)for(let[e,n]of Object.entries({"Visual Studio Code.app":`code`,"Cursor.app":`cursor`,"Windsurf.app":`windsurf`,"Visual Studio Code - Insiders.app":`code`,"VSCodium.app":`codium`})){let r=t.indexOf(e+`/Contents/MacOS/Electron`);if(r!==-1){let i=r+e.length;return t.substring(0,i)+`/Contents/Resources/app/bin/`+n}}let n=wie(`ps -o ppid= -p ${e}`)?.trim();if(!n)break;e=parseInt(n.trim(),10)}return null}catch{return null}}async function sN(e){let t=wNe();if(t)try{return await G().stat(t),t}catch{}let n=la()===`windows`?`.cmd`:``;switch(e){case`vscode`:return`code${n}`;case`cursor`:return`cursor${n}`;case`windsurf`:return`windsurf${n}`;default:break}return null}async function TNe(){return(await Bi(`cursor`,[`--version`])).code===0}async function ENe(){return(await Bi(`windsurf`,[`--version`])).code===0}async function DNe(){let e=await Bi(`code`,[`--help`]);return e.code===0&&!!e.stdout?.includes(`Visual Studio Code`)}async function ONe(){let e=[];try{let t=la();if(t===`macos`){let t=(await Ri(`ps aux | grep -E "Visual Studio Code|Code Helper|Cursor Helper|Windsurf Helper|IntelliJ IDEA|PyCharm|WebStorm|PhpStorm|RubyMine|CLion|GoLand|Rider|DataGrip|AppCode|DataSpell|Aqua|Gateway|Fleet|Android Studio" | grep -v grep`,{shell:!0,reject:!1})).stdout??``;for(let[n,r]of Object.entries(pN))for(let i of r.processKeywordsMac)if(t.includes(i)){e.push(n);break}}else if(t===`windows`){let t=((await Ri(`tasklist | findstr /I "Code.exe Cursor.exe Windsurf.exe idea64.exe pycharm64.exe webstorm64.exe phpstorm64.exe rubymine64.exe clion64.exe goland64.exe rider64.exe datagrip64.exe appcode.exe dataspell64.exe aqua64.exe gateway64.exe fleet.exe studio64.exe"`,{shell:!0,reject:!1})).stdout??``).toLowerCase();for(let[n,r]of Object.entries(pN))for(let i of r.processKeywordsWindows)if(t.includes(i.toLowerCase())){e.push(n);break}}else if(t===`linux`){let t=((await Ri(`ps aux | grep -E "code|cursor|windsurf|idea|pycharm|webstorm|phpstorm|rubymine|clion|goland|rider|datagrip|dataspell|aqua|gateway|fleet|android-studio" | grep -v grep`,{shell:!0,reject:!1})).stdout??``).toLowerCase();for(let[n,r]of Object.entries(pN))for(let i of r.processKeywordsLinux)if(t.includes(i)){if(n!==`vscode`){e.push(n);break}else if(!t.includes(`cursor`)&&!t.includes(`appcode`)){e.push(n);break}}}}catch(e){q(e)}return e}async function kNe(){let e=await ONe();return bN=e,e}async function ANe(){return bN===null?kNe():bN}function cN(e){return lN(e.find(e=>e.type===`connected`&&e.name===`ide`))}function lN(e){let t=e?.config;return t?.type===`sse-ide`||t?.type===`ws-ide`?t.ideName:gN()?uN(Oc.terminal):null}function uN(e){if(!e)return`IDE`;let t=pN[e];if(t)return t.displayName;let n=xN[e.toLowerCase().trim()];if(n)return n;let r=e.split(` `)[0],i=r?Kc(r).toLowerCase():null;return i?xN[i]||Zm(i):Zm(e)}function dN(e){if(!e)return;let t=e.find(e=>e.type===`connected`&&e.name===`ide`);return t?.type===`connected`?t:void 0}async function jNe(e){try{await fM(`closeAllDiffTabs`,{},e)}catch{}}async function MNe(e,t,n,r){nN().then(e);let i=yi().autoInstallIdeExtension??!0;if(!m(process.env.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL)&&i){let i=t??QM();i&&(XM(i)?iN(i).then(async t=>{yNe(i).catch(e=>({installed:!1,error:e.message||`Installation failed`,installedVersion:null,ideType:i})).then(i=>{r(i),i?.installed&&nN().then(e),!t&&i?.installed===!0&&!fN().hasIdeOnboardingDialogBeenShown()&&n()})}):ZM(i)&&iN(i).then(async e=>{e&&!fN().hasIdeOnboardingDialogBeenShown()&&n()}))}}var fN,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN=n((()=>{Ii(),Qm(),d(),Da(),Wt(),BM(),bi(),Ar(),h(),zi(),Bn(),bc(),dNe(),Qi(),ua(),Yse(),oD(),W(),Dce(),On(),KM(),Po(),Yn(),fN=()=>JM(),pN={cursor:{ideKind:`vscode`,displayName:`Cursor`,processKeywordsMac:[`Cursor Helper`,`Cursor.app`],processKeywordsWindows:[`cursor.exe`],processKeywordsLinux:[`cursor`]},windsurf:{ideKind:`vscode`,displayName:`Windsurf`,processKeywordsMac:[`Windsurf Helper`,`Windsurf.app`],processKeywordsWindows:[`windsurf.exe`],processKeywordsLinux:[`windsurf`]},vscode:{ideKind:`vscode`,displayName:`VS Code`,processKeywordsMac:[`Visual Studio Code`,`Code Helper`],processKeywordsWindows:[`code.exe`],processKeywordsLinux:[`code`]},intellij:{ideKind:`jetbrains`,displayName:`IntelliJ IDEA`,processKeywordsMac:[`IntelliJ IDEA`],processKeywordsWindows:[`idea64.exe`],processKeywordsLinux:[`idea`,`intellij`]},pycharm:{ideKind:`jetbrains`,displayName:`PyCharm`,processKeywordsMac:[`PyCharm`],processKeywordsWindows:[`pycharm64.exe`],processKeywordsLinux:[`pycharm`]},webstorm:{ideKind:`jetbrains`,displayName:`WebStorm`,processKeywordsMac:[`WebStorm`],processKeywordsWindows:[`webstorm64.exe`],processKeywordsLinux:[`webstorm`]},phpstorm:{ideKind:`jetbrains`,displayName:`PhpStorm`,processKeywordsMac:[`PhpStorm`],processKeywordsWindows:[`phpstorm64.exe`],processKeywordsLinux:[`phpstorm`]},rubymine:{ideKind:`jetbrains`,displayName:`RubyMine`,processKeywordsMac:[`RubyMine`],processKeywordsWindows:[`rubymine64.exe`],processKeywordsLinux:[`rubymine`]},clion:{ideKind:`jetbrains`,displayName:`CLion`,processKeywordsMac:[`CLion`],processKeywordsWindows:[`clion64.exe`],processKeywordsLinux:[`clion`]},goland:{ideKind:`jetbrains`,displayName:`GoLand`,processKeywordsMac:[`GoLand`],processKeywordsWindows:[`goland64.exe`],processKeywordsLinux:[`goland`]},rider:{ideKind:`jetbrains`,displayName:`Rider`,processKeywordsMac:[`Rider`],processKeywordsWindows:[`rider64.exe`],processKeywordsLinux:[`rider`]},datagrip:{ideKind:`jetbrains`,displayName:`DataGrip`,processKeywordsMac:[`DataGrip`],processKeywordsWindows:[`datagrip64.exe`],processKeywordsLinux:[`datagrip`]},appcode:{ideKind:`jetbrains`,displayName:`AppCode`,processKeywordsMac:[`AppCode`],processKeywordsWindows:[`appcode.exe`],processKeywordsLinux:[`appcode`]},dataspell:{ideKind:`jetbrains`,displayName:`DataSpell`,processKeywordsMac:[`DataSpell`],processKeywordsWindows:[`dataspell64.exe`],processKeywordsLinux:[`dataspell`]},aqua:{ideKind:`jetbrains`,displayName:`Aqua`,processKeywordsMac:[],processKeywordsWindows:[`aqua64.exe`],processKeywordsLinux:[]},gateway:{ideKind:`jetbrains`,displayName:`Gateway`,processKeywordsMac:[],processKeywordsWindows:[`gateway64.exe`],processKeywordsLinux:[]},fleet:{ideKind:`jetbrains`,displayName:`Fleet`,processKeywordsMac:[],processKeywordsWindows:[`fleet.exe`],processKeywordsLinux:[]},androidstudio:{ideKind:`jetbrains`,displayName:`Android Studio`,processKeywordsMac:[`Android Studio`],processKeywordsWindows:[`studio64.exe`],processKeywordsLinux:[`android-studio`]}},mN=u(()=>XM(pr.terminal)),hN=u(()=>ZM(Oc.terminal)),gN=u(()=>mN()||hN()||!!process.env.FORCE_CODE_TERMINAL),_N=u(async()=>{if(process.env.USERPROFILE)return process.env.USERPROFILE;let{stdout:e,code:t}=await Bi(`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`$env:USERPROFILE`]);if(t===0&&e.trim())return e.trim();U(`Unable to get Windows USERPROFILE via PowerShell - IDE detection may be incomplete`)}),vN=null,yN=`anthropic.claude-code`,bN=null,xN={code:`VS Code`,cursor:`Cursor`,windsurf:`Windsurf`,antigravity:`Antigravity`,vi:`Vim`,vim:`Vim`,nano:`nano`,notepad:`Notepad`,"start /wait notepad":`Notepad`,emacs:`Emacs`,subl:`Sublime Text`,atom:`Atom`},SN=u(async(e,t)=>{if(process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE)return process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE;if(la()!==`wsl`||!e)return`127.0.0.1`;try{let e=await Ri(`ip route show | grep -i default`,{shell:!0,reject:!1});if(e.exitCode===0&&e.stdout){let n=e.stdout.match(/default via (\d+\.\d+\.\d+\.\d+)/);if(n){let e=n[1];if(await tN(e,t))return e}}}catch{}return`127.0.0.1`},(e,t)=>`${e}:${t}`)}));function wN(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function TN(e){PN=e}function EN(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(LN.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}function DN(e,t){if(t){if(LN.escapeTest.test(e))return e.replace(LN.escapeReplace,WP)}else if(LN.escapeTestNoEncode.test(e))return e.replace(LN.escapeReplaceNoEncode,WP);return e}function ON(e){try{e=encodeURI(e).replace(LN.percentDecode,`%`)}catch{return null}return e}function kN(e,t){let n=e.replace(LN.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(LN.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(LN.slashPipe,`|`);return n}function AN(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function NNe(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function PNe(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function jN(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function FNe(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
671
671
  `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
672
672
  `)}function MN(e,t){return QP.parse(e,t)}var NN,PN,FN,IN,LN,RN,zN,BN,VN,HN,UN,WN,GN,KN,qN,JN,YN,XN,ZN,QN,$N,eP,tP,nP,rP,iP,aP,oP,sP,cP,lP,uP,dP,fP,pP,mP,hP,gP,_P,vP,yP,bP,xP,SP,CP,wP,TP,EP,DP,OP,kP,AP,jP,MP,NP,PP,FP,IP,LP,RP,zP,BP,VP,HP,UP,WP,GP,KP,qP,JP,YP,XP,ZP,QP,$P=n((()=>{b(),PN=wN(),FN={exec:()=>null},IN=(()=>{try{return!0}catch{return!1}})(),LN={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},RN=/^(?:[ \t]*(?:\n|$))+/,zN=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,BN=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,VN=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,HN=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,UN=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,WN=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,GN=EN(WN).replace(/bull/g,UN).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),KN=EN(WN).replace(/bull/g,UN).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),qN=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,JN=/^[^\n]+/,YN=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,XN=EN(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,YN).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ZN=EN(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,UN).getRegex(),QN=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,$N=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,eP=EN(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,$N).replace(`tag`,QN).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),tP=EN(qN).replace(`hr`,VN).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,QN).getRegex(),nP={blockquote:EN(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,tP).getRegex(),code:zN,def:XN,fences:BN,heading:HN,hr:VN,html:eP,lheading:GN,list:ZN,newline:RN,paragraph:tP,table:FN,text:JN},rP=EN(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,VN).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,QN).getRegex(),iP={...nP,lheading:KN,table:rP,paragraph:EN(qN).replace(`hr`,VN).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,rP).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,QN).getRegex()},aP={...nP,html:EN(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,$N).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:FN,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:EN(qN).replace(`hr`,VN).replace(`heading`,` *#{1,6} *[^
@@ -775,7 +775,7 @@ Examples:
775
775
  - "重构这个模块的代码" -> refactor code modularize
776
776
  - "帮我写个 Go 单元测试" -> write test golang unit
777
777
 
778
- Output ONLY keywords. Nothing else.`,VI=6e3,RPe=500,zPe=120,BPe=200,VPe=150,HI=new Map})),UPe=i({collectSkillDiscoveryPrefetch:()=>XPe,extractQueryFromMessages:()=>WI,getTurnZeroSkillDiscovery:()=>ZPe,startSkillDiscoveryPrefetch:()=>YPe});function UI(e,t){if(e.add(t),e.size>QPe){let t=e.size-$Pe,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function WI(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 WPe(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function GPe(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=tFe||i.score<eFe){r.push(e);continue}let a=await KPe(i);if(!a){r.push(e);continue}n++,await qPe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function KPe(e){if(!e.skillRoot)return null;let t=[ol(e.skillRoot,`SKILL.md`),ol(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:od(await Ul(e,`utf8`)).content.slice(0,nFe)}}catch{}return null}async function qPe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-CsdHk8n-.js`);i(e,t,n,r.agentId??null)}catch{}}async function JPe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!KI.has(i)){UI(KI,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-CCNeSjIb.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){U(`[skill-search] skill gap learning error: ${e}`);return}}}async function YPe(e,t,n){if(!Dm())return[];let r=Date.now(),i=WI(e,t);if(!i.trim())return[];try{let e=await rce(n.cwd??process.cwd()),t=sce(i,e).filter(e=>!GI.has(e.name));if(t.length===0)return[];for(let e of t)UI(GI,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return U(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[WPe(await GPe(t,n),a)]}catch(e){return U(`[skill-search] prefetch error: ${e}`),[]}}async function XPe(e){try{return await e}catch{return[]}}async function ZPe(e,t,n){if(!Dm()||!e.trim())return null;let r=Date.now();try{let t=await rce(n.cwd??process.cwd()),i=sce(await MPe(e),t),a=await GPe(i,n),o=a.some(e=>e.autoLoaded)?void 0:await JPe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)UI(GI,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return U(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),WPe(a,s,o)}catch(e){return U(`[skill-search] turn-zero error: ${e}`),null}}var QPe,$Pe,GI,KI,eFe,tFe,nFe,qI=n((()=>{Om(),lc(),HPe(),W(),gd(),QPe=1e3,$Pe=750,GI=new Set,KI=new Set,eFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),tFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),nFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function rFe(e){return cFe.test(e)}function iFe(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 aFe(e){let t=e.filter(e=>As(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}=iFe(r.name),o=r.searchHint??``,s=cc(i.join(` `)),c=cc(o),l=cc(t),u=[...new Set([...s,...c,...l])],d=oce([{tokens:s,weight:XI.name},{tokens:c,weight:XI.searchHint},{tokens:l,weight:XI.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=ace(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return U(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function JI(e,t,n=5){if(t.length===0||!e.trim())return[];let r=cc(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=ace(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>rFe(e[0]??``)),u=r.filter(e=>!rFe(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=ice(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<sFe&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=oFe&&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 YI(e){let t=e.map(e=>e.name).sort().join(`,`);return ZI&&QI===t?ZI:(ZI=await aFe(e),QI=t,ZI)}var XI,oFe,sFe,cFe,ZI,QI,lFe=n((()=>{W(),lc(),zs(),XI={name:3,searchHint:2.5,description:1},oFe=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),sFe=2,cFe=/[\u4e00-\u9fff\u3400-\u4dbf]/,ZI=null,QI=null})),uFe=i({buildToolDiscoveryAttachment:()=>_Fe,clearSearchExtraToolsPrefetchResults:()=>mFe,collectSearchExtraToolsPrefetch:()=>bFe,getSearchExtraToolsPrefetchSnapshot:()=>pFe,getTurnZeroSearchExtraToolsPrefetch:()=>yFe,startSearchExtraToolsPrefetch:()=>vFe,subscribeToSearchExtraToolsPrefetch:()=>fFe});function dFe(){for(let e of tL)e()}function fFe(e){return tL.add(e),()=>{tL.delete(e)}}function pFe(){return eL}function mFe(){eL=[],dFe()}function hFe(e,t){if(e.add(t),e.size>xFe){let t=e.size-SFe,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function gFe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function _Fe(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function vFe(e,t){let n=Date.now(),r=WI(null,t);if(!r.trim())return[];try{let t=await YI(e),i=JI(r,t,3).filter(e=>!$I.has(e.name));if(i.length===0)return[];for(let e of i)hFe($I,e.name);let a=Date.now()-n;U(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(gFe);return eL=o,dFe(),[_Fe(o,`assistant_turn`,r,a,t.length)]}catch(e){return U(`[search-extra-tools] prefetch error: ${e}`),[]}}async function yFe(e,t){return null}async function bFe(e){try{return await e}catch{return[]}}var xFe,SFe,$I,eL,tL,nL=n((()=>{lFe(),W(),qI(),xFe=500,SFe=400,$I=new Set,eL=[],tL=new Set}));function rL(e){aL=e}function iL(){return aL}function CFe(e){oL=e}function wFe(){return oL}function TFe(e){sL=e}function EFe(){return sL}var aL,oL,sL,cL=n((()=>{aL=!1,oL=!1,sL=!1}));function lL(){return!1}function DFe(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 OFe(e,t){let n={...t,uuid:bl(),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?(U(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[$({content:[{type:`text`,text:kFe(e)}]})]):[n,$({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:jFe}]})),{type:`text`,text:kFe(e)}]})]}function kFe(e){return`<${Yi}>
778
+ Output ONLY keywords. Nothing else.`,VI=6e3,RPe=500,zPe=120,BPe=200,VPe=150,HI=new Map})),UPe=i({collectSkillDiscoveryPrefetch:()=>XPe,extractQueryFromMessages:()=>WI,getTurnZeroSkillDiscovery:()=>ZPe,startSkillDiscoveryPrefetch:()=>YPe});function UI(e,t){if(e.add(t),e.size>QPe){let t=e.size-$Pe,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function WI(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 WPe(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function GPe(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=tFe||i.score<eFe){r.push(e);continue}let a=await KPe(i);if(!a){r.push(e);continue}n++,await qPe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function KPe(e){if(!e.skillRoot)return null;let t=[ol(e.skillRoot,`SKILL.md`),ol(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:od(await Ul(e,`utf8`)).content.slice(0,nFe)}}catch{}return null}async function qPe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-CsdHk8n-.js`);i(e,t,n,r.agentId??null)}catch{}}async function JPe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!KI.has(i)){UI(KI,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-CJjt3IW7.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){U(`[skill-search] skill gap learning error: ${e}`);return}}}async function YPe(e,t,n){if(!Dm())return[];let r=Date.now(),i=WI(e,t);if(!i.trim())return[];try{let e=await rce(n.cwd??process.cwd()),t=sce(i,e).filter(e=>!GI.has(e.name));if(t.length===0)return[];for(let e of t)UI(GI,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return U(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[WPe(await GPe(t,n),a)]}catch(e){return U(`[skill-search] prefetch error: ${e}`),[]}}async function XPe(e){try{return await e}catch{return[]}}async function ZPe(e,t,n){if(!Dm()||!e.trim())return null;let r=Date.now();try{let t=await rce(n.cwd??process.cwd()),i=sce(await MPe(e),t),a=await GPe(i,n),o=a.some(e=>e.autoLoaded)?void 0:await JPe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)UI(GI,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return U(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),WPe(a,s,o)}catch(e){return U(`[skill-search] turn-zero error: ${e}`),null}}var QPe,$Pe,GI,KI,eFe,tFe,nFe,qI=n((()=>{Om(),lc(),HPe(),W(),gd(),QPe=1e3,$Pe=750,GI=new Set,KI=new Set,eFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),tFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),nFe=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function rFe(e){return cFe.test(e)}function iFe(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 aFe(e){let t=e.filter(e=>As(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}=iFe(r.name),o=r.searchHint??``,s=cc(i.join(` `)),c=cc(o),l=cc(t),u=[...new Set([...s,...c,...l])],d=oce([{tokens:s,weight:XI.name},{tokens:c,weight:XI.searchHint},{tokens:l,weight:XI.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=ace(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return U(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function JI(e,t,n=5){if(t.length===0||!e.trim())return[];let r=cc(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=ace(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>rFe(e[0]??``)),u=r.filter(e=>!rFe(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=ice(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<sFe&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=oFe&&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 YI(e){let t=e.map(e=>e.name).sort().join(`,`);return ZI&&QI===t?ZI:(ZI=await aFe(e),QI=t,ZI)}var XI,oFe,sFe,cFe,ZI,QI,lFe=n((()=>{W(),lc(),zs(),XI={name:3,searchHint:2.5,description:1},oFe=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),sFe=2,cFe=/[\u4e00-\u9fff\u3400-\u4dbf]/,ZI=null,QI=null})),uFe=i({buildToolDiscoveryAttachment:()=>_Fe,clearSearchExtraToolsPrefetchResults:()=>mFe,collectSearchExtraToolsPrefetch:()=>bFe,getSearchExtraToolsPrefetchSnapshot:()=>pFe,getTurnZeroSearchExtraToolsPrefetch:()=>yFe,startSearchExtraToolsPrefetch:()=>vFe,subscribeToSearchExtraToolsPrefetch:()=>fFe});function dFe(){for(let e of tL)e()}function fFe(e){return tL.add(e),()=>{tL.delete(e)}}function pFe(){return eL}function mFe(){eL=[],dFe()}function hFe(e,t){if(e.add(t),e.size>xFe){let t=e.size-SFe,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function gFe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function _Fe(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function vFe(e,t){let n=Date.now(),r=WI(null,t);if(!r.trim())return[];try{let t=await YI(e),i=JI(r,t,3).filter(e=>!$I.has(e.name));if(i.length===0)return[];for(let e of i)hFe($I,e.name);let a=Date.now()-n;U(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(gFe);return eL=o,dFe(),[_Fe(o,`assistant_turn`,r,a,t.length)]}catch(e){return U(`[search-extra-tools] prefetch error: ${e}`),[]}}async function yFe(e,t){return null}async function bFe(e){try{return await e}catch{return[]}}var xFe,SFe,$I,eL,tL,nL=n((()=>{lFe(),W(),qI(),xFe=500,SFe=400,$I=new Set,eL=[],tL=new Set}));function rL(e){aL=e}function iL(){return aL}function CFe(e){oL=e}function wFe(){return oL}function TFe(e){sL=e}function EFe(){return sL}var aL,oL,sL,cL=n((()=>{aL=!1,oL=!1,sL=!1}));function lL(){return!1}function DFe(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 OFe(e,t){let n={...t,uuid:bl(),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?(U(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[$({content:[{type:`text`,text:kFe(e)}]})]):[n,$({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:jFe}]})),{type:`text`,text:kFe(e)}]})]}function kFe(e){return`<${Yi}>
779
779
  STOP. READ THIS FIRST.
780
780
 
781
781
  You are a forked worker process. You are NOT the main agent.
@@ -853,7 +853,7 @@ Usage notes:
853
853
  - If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple ${ur} tool use content blocks. For example, if you need to launch both a build-validator agent and a test-runner agent in parallel, send a single message with both tool calls.${a}${o}`}var IFe=n((()=>{no(),sy(),h(),Fs(),fs(),xr(),fL()}));function LFe(e,t){let n=Object.create(null),r=0;for(let i of e){let e=t(i,r++);n[e]===void 0&&(n[e]=[]),n[e].push(i)}return n}var RFe=n((()=>{})),zFe=i({clearCommandQueue:()=>YFe,dequeue:()=>GFe,dequeueAll:()=>KFe,dequeueAllMatching:()=>_L,enqueue:()=>hL,enqueuePendingNotification:()=>gL,getCommandQueue:()=>VFe,getCommandQueueLength:()=>HFe,getCommandQueueSnapshot:()=>BFe,getCommandsByMaxPriority:()=>bL,hasCommandsInQueue:()=>UFe,isPromptInputModeEditable:()=>ZFe,isQueuedCommandEditable:()=>yL,isQueuedCommandVisible:()=>QFe,isSlashCommand:()=>nIe,peek:()=>qFe,popAllEditable:()=>tIe,recheckCommandQueue:()=>WFe,remove:()=>vL,removeByFilter:()=>JFe,resetCommandQueue:()=>XFe,subscribeToCommandQueue:()=>wL});function pL(e,t){let n=sn();y6({type:`queue-operation`,operation:e,timestamp:new Date().toISOString(),sessionId:n,...t!==void 0&&{content:t}})}function mL(){SL=Object.freeze([...xL]),CL.emit()}function BFe(){return SL}function VFe(){return[...xL]}function HFe(){return xL.length}function UFe(){return xL.length>0}function WFe(){xL.length>0&&mL()}function hL(e){xL.push({...e,priority:e.priority??`next`}),mL(),pL(`enqueue`,typeof e.value==`string`?e.value:void 0)}function gL(e){xL.push({...e,priority:e.priority??`later`}),mL(),pL(`enqueue`,typeof e.value==`string`?e.value:void 0)}function GFe(e){if(xL.length===0)return;let t=-1,n=1/0;for(let r=0;r<xL.length;r++){let i=xL[r];if(e&&!e(i))continue;let a=TL[i.priority??`next`];a<n&&(t=r,n=a)}if(t===-1)return;let[r]=xL.splice(t,1);return mL(),pL(`dequeue`),r}function KFe(){if(xL.length===0)return[];let e=[...xL];xL.length=0,mL();for(let t of e)pL(`dequeue`);return e}function qFe(e){if(xL.length===0)return;let t=-1,n=1/0;for(let r=0;r<xL.length;r++){let i=xL[r];if(e&&!e(i))continue;let a=TL[i.priority??`next`];a<n&&(t=r,n=a)}if(t!==-1)return xL[t]}function _L(e){let t=[],n=[];for(let r of xL)e(r)?t.push(r):n.push(r);if(t.length===0)return[];xL.length=0,xL.push(...n),mL();for(let e of t)pL(`dequeue`);return t}function vL(e){if(e.length===0)return;let t=xL.length;for(let t=xL.length-1;t>=0;t--)e.includes(xL[t])&&xL.splice(t,1);xL.length!==t&&mL();for(let t of e)pL(`remove`)}function JFe(e){let t=[];for(let n=xL.length-1;n>=0;n--)e(xL[n])&&t.unshift(xL.splice(n,1)[0]);if(t.length>0){mL();for(let e of t)pL(`remove`)}return t}function YFe(){xL.length!==0&&(xL.length=0,mL())}function XFe(){xL.length=0,SL=Object.freeze([])}function ZFe(e){return!rIe.has(e)}function yL(e){return ZFe(e.mode)&&!e.isMeta}function QFe(e){return yL(e)}function $Fe(e){return typeof e==`string`?e:q4(e,`
854
854
  `)}function eIe(e,t){if(typeof e==`string`)return[];let n=[],r=0;for(let i of e)i.type===`image`&&i.source.type===`base64`&&(n.push({id:t+r,type:`image`,content:i.source.data,mediaType:i.source.media_type,filename:`image${r+1}`}),r++);return n}function tIe(e,t){if(xL.length===0)return;let{editable:n=[],nonEditable:r=[]}=LFe([...xL],e=>yL(e)?`editable`:`nonEditable`);if(n.length===0)return;let i=n.map(e=>$Fe(e.value)),a=[...i,e].filter(Boolean).join(`
855
855
  `),o=i.join(`
856
- `).length+1+t,s=[],c=Date.now();for(let e of n){if(e.pastedContents)for(let t of Object.values(e.pastedContents))t.type===`image`&&s.push(t);let t=eIe(e.value,c);s.push(...t),c+=t.length}for(let e of n)pL(`popAll`,typeof e.value==`string`?e.value:void 0);return xL.length=0,xL.push(...r),mL(),{text:a,cursorOffset:o,images:s}}function bL(e){let t=TL[e];return xL.filter(e=>TL[e.priority??`next`]<=t)}function nIe(e){return typeof e.value==`string`&&e.value.trim().startsWith(`/`)&&(!e.skipSlashCommands||e.bridgeOrigin===!0)}var xL,SL,CL,wL,TL,rIe,EL=n((()=>{Wt(),m3(),RFe(),h8(),fn(),xL=[],SL=Object.freeze([]),CL=rn(),wL=CL.subscribe,TL={now:0,next:1,later:2},rIe=new Set([`task-notification`])}));function DL(e,t,n){t(t=>{let r=t.tasks?.[e];if(!r)return t;let i=n(r);return i===r?t:{...t,tasks:{...t.tasks,[e]:i}}})}function OL(e,t){let n=!1;t(t=>{let r=t.tasks[e.id];n=r!==void 0;let i=r&&`retain`in r?{...e,retain:r.retain,startTime:r.startTime,messages:r.messages,diskLoaded:r.diskLoaded,pendingMessages:r.pendingMessages}:e;return{...t,tasks:{...t.tasks,[e.id]:i}}}),!n&&sc({type:`system`,subtype:`task_started`,task_id:e.id,tool_use_id:e.toolUseId,description:e.description,task_type:e.type,workflow_name:`workflowName`in e?e.workflowName:void 0,prompt:`prompt`in e?e.prompt:void 0})}function iIe(e){let t=e.tasks??{};return Object.values(t).filter(e=>e.status===`running`)}async function aIe(e){let t=[],n={},r=[],i=e.tasks??{};for(let e of Object.values(i)){if(e.notified)switch(e.status){case`completed`:case`failed`:case`killed`:r.push(e.id);continue;case`pending`:continue;case`running`:break}if(e.status===`running`){let t=await qwt(e.id,e.outputOffset);t.content&&(n[e.id]=t.newOffset)}}return{attachments:t,updatedTaskOffsets:n,evictedTaskIds:r}}function oIe(e,t,n){let r=Object.keys(t);r.length===0&&n.length===0||e(e=>{let i=!1,a={...e.tasks};for(let e of r){let n=a[e];n?.status===`running`&&(a[e]={...n,outputOffset:t[e]},i=!0)}for(let e of n){let t=a[e];!t||!Xwt(t.status)||!t.notified||`retain`in t&&(t.evictAfter??1/0)>Date.now()||(delete a[e],i=!0)}return i?{...e,tasks:a}:e})}var kL,AL=n((()=>{l5(),EL(),nc(),o5(),kL=3e4}));function sIe(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.type!==`image`||typeof t.source!=`object`||t.source===null)return!1;let n=t.source;return n.type===`base64`&&typeof n.data==`string`}function cIe(e){let t=[],n=0;for(let r of e){if(typeof r!=`object`||!r)continue;let e=r;if(e.type!==`user`)continue;let i=e.message;if(!i)continue;let a=i.content;if(!(typeof a==`string`||!Array.isArray(a))){for(let e of a)if(sIe(e)){n++;let r=e.source.data.length;r>5242880&&(J(`tengu_image_api_validation_failed`,{base64_size_bytes:r,max_bytes:H_}),t.push({index:n,size:r}))}}}if(t.length>0)throw new jL(t,H_)}var jL,ML=n((()=>{G_(),Da(),Ba(),jL=class extends Error{constructor(e,t){let n,r=e[0];n=e.length===1&&r?`Image base64 size (${za(r.size)}) exceeds API limit (${za(t)}). Please resize the image before sending.`:`${e.length} images exceed the API limit (${za(t)}): `+e.map(e=>`Image ${e.index}: ${za(e.size)}`).join(`, `)+`. Please resize these images before sending.`,super(n),this.name=`ImageSizeError`}}})),NL,lIe=n((()=>{NL={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 uIe(){if(m(process.env.DISABLE_COST_WARNINGS)||uo())return!1;let e=dae(),t=soe()!==null;if(!e.hasToken&&!t)return!1;let n=yi(),r=n.oauthAccount?.organizationRole,i=n.oauthAccount?.workspaceRole;return!r||!i?!1:[`admin`,`billing`].includes(r)||[`workspace_admin`,`workspace_billing`].includes(i)}function PL(){if(!uo())return!1;let e=co();if(e===`max`||e===`pro`)return!0;let t=yi().oauthAccount?.organizationRole;return!!t&&[`admin`,`billing`,`owner`,`primary_owner`].includes(t)}var FL=n((()=>{no(),bi(),h()}));function dIe(e){return yIe.some(t=>e.startsWith(t))}function fIe(e,t){if(e.isUsingOverage)return e.overageStatus===`allowed_warning`?{message:`You're close to your extra usage spending limit`,severity:`warning`}:null;if(e.status===`rejected`)return{message:hIe(e,t),severity:`error`};if(e.status===`allowed_warning`){if(e.utilization!==void 0&&e.utilization<.7)return null;let t=co(),n=t===`team`||t===`enterprise`,r=Hae()?.hasExtraUsageEnabled===!0;if(n&&r&&!PL())return null;let i=gIe(e);if(i)return{message:i,severity:`warning`}}return null}function pIe(e,t){let n=fIe(e,t);return n&&n.severity===`error`?n.message:null}function mIe(e,t){let n=fIe(e,t);return n&&n.severity===`warning`?n.message:null}function hIe(e,t){let n=e.resetsAt,r=n?Ia(n,!0):void 0,i=e.overageResetsAt?Ia(e.overageResetsAt,!0):void 0,a=r?` · resets ${r}`:``;if(e.overageStatus===`rejected`){let a=``;return n&&e.overageResetsAt?a=n<e.overageResetsAt?` · resets ${r}`:` · resets ${i}`:r?a=` · resets ${r}`:i&&(a=` · resets ${i}`),e.overageDisabledReason===`out_of_credits`?`You're out of extra usage${a}`:IL(`limit`,a,t)}if(e.rateLimitType===`seven_day_sonnet`){let e=co();return IL(e===`pro`||e===`enterprise`?`weekly limit`:`Sonnet limit`,a,t)}return e.rateLimitType===`seven_day_opus`?IL(`Opus limit`,a,t):e.rateLimitType===`seven_day`?IL(`weekly limit`,a,t):e.rateLimitType===`five_hour`?IL(`session limit`,a,t):IL(`usage limit`,a,t)}function gIe(e){let t=null;switch(e.rateLimitType){case`seven_day`:t=`weekly limit`;break;case`five_hour`:t=`session limit`;break;case`seven_day_opus`:t=`Opus limit`;break;case`seven_day_sonnet`:t=`Sonnet limit`;break;case`overage`:t=`extra usage`;break;case void 0:return null}let n=e.utilization?Math.floor(e.utilization*100):void 0,r=e.resetsAt?Ia(e.resetsAt,!0):void 0,i=_Ie(e.rateLimitType);if(n&&r){let e=`You've used ${n}% of your ${t} · resets ${r}`;return i?`${e} · ${i}`:e}if(n){let e=`You've used ${n}% of your ${t}`;return i?`${e} · ${i}`:e}if(e.rateLimitType===`overage`&&(t+=` limit`),r){let e=`Approaching ${t} · resets ${r}`;return i?`${e} · ${i}`:e}let a=`Approaching ${t}`;return i?`${a} · ${i}`:a}function _Ie(e){return co(),null}function vIe(e){let t=e.resetsAt?Ia(e.resetsAt,!0):``,n=``;if(e.rateLimitType===`five_hour`)n=`session limit`;else if(e.rateLimitType===`seven_day`)n=`weekly limit`;else if(e.rateLimitType===`seven_day_opus`)n=`Opus limit`;else if(e.rateLimitType===`seven_day_sonnet`){let e=co();n=e===`pro`||e===`enterprise`?`weekly limit`:`Sonnet limit`}return n?`You're now using extra usage${t?` · Your ${n} resets ${t}`:``}`:`Now using extra usage`}function IL(e,t,n){return`You've hit your ${e}${t}`}var yIe,LL=n((()=>{no(),FL(),Ba(),yIe=[`You've hit your`,`You've used`,`You're now using extra usage`,`You're close to`,`You're out of extra usage`]}));function bIe(e,t){let n=Date.now()/1e3-(e-t);return Math.max(0,Math.min(1,n/t))}function xIe(){return VL}function SIe(e){let t={};for(let[n,r]of[[`five_hour`,`5h`],[`seven_day`,`7d`]]){let i=e.get(`anthropic-ratelimit-unified-${r}-utilization`),a=e.get(`anthropic-ratelimit-unified-${r}-reset`);i!==null&&a!==null&&(t[n]={utilization:Number(i),resets_at:Number(a)})}return t}function RL(e){BL=e,HL.forEach(t=>t(e));let t=Math.round((e.resetsAt?e.resetsAt-Date.now()/1e3:0)/3600);J(`tengu_claudeai_limits_status_changed`,{status:e.status,unifiedRateLimitFallbackAvailable:e.unifiedRateLimitFallbackAvailable,hoursTillReset:t})}async function CIe(){let e=zo(),t=await jo({maxRetries:0,model:e,source:`quota_check`}),n=[{role:`user`,content:`quota`}],r=eo(e);return t.beta.messages.create({model:e,max_tokens:1,messages:n,metadata:X7(),...r.length>0?{betas:r}:{}}).asResponse()}async function wIe(){if(!Iie()&&uo()&&!gn())try{AIe((await CIe()).headers)}catch(e){e instanceof Pn&&zL(e)}}function TIe(e,t){for(let[n,r]of Object.entries(MIe)){let i=e.get(`anthropic-ratelimit-unified-${n}-surpassed-threshold`);if(i!==null){let a=e.get(`anthropic-ratelimit-unified-${n}-utilization`),o=e.get(`anthropic-ratelimit-unified-${n}-reset`),s=a?Number(a):void 0;return{status:`allowed_warning`,resetsAt:o?Number(o):void 0,rateLimitType:r,utilization:s,unifiedRateLimitFallbackAvailable:t,isUsingOverage:!1,surpassedThreshold:Number(i)}}}return null}function EIe(e,t,n){let{rateLimitType:r,claimAbbrev:i,windowSeconds:a,thresholds:o}=t,s=e.get(`anthropic-ratelimit-unified-${i}-utilization`),c=e.get(`anthropic-ratelimit-unified-${i}-reset`);if(s===null||c===null)return null;let l=Number(s),u=Number(c),d=bIe(u,a);return o.some(e=>l>=e.utilization&&d<=e.timePct)?{status:`allowed_warning`,resetsAt:u,rateLimitType:r,utilization:l,unifiedRateLimitFallbackAvailable:n,isUsingOverage:!1}:null}function DIe(e,t){let n=TIe(e,t);if(n)return n;for(let n of jIe){let r=EIe(e,n,t);if(r)return r}return null}function OIe(e){let t=e.get(`anthropic-ratelimit-unified-status`)||`allowed`,n=e.get(`anthropic-ratelimit-unified-reset`),r=n?Number(n):void 0,i=e.get(`anthropic-ratelimit-unified-fallback`)===`available`,a=e.get(`anthropic-ratelimit-unified-representative-claim`),o=e.get(`anthropic-ratelimit-unified-overage-status`),s=e.get(`anthropic-ratelimit-unified-overage-reset`),c=s?Number(s):void 0,l=e.get(`anthropic-ratelimit-unified-overage-disabled-reason`),u=t===`rejected`&&(o===`allowed`||o===`allowed_warning`),d=t;if(t===`allowed`||t===`allowed_warning`){let t=DIe(e,i);if(t)return t;d=`allowed`}return{status:d,resetsAt:r,unifiedRateLimitFallbackAvailable:i,...a&&{rateLimitType:a},...o&&{overageStatus:o},...c&&{overageResetsAt:c},...l&&{overageDisabledReason:l},isUsingOverage:u}}function kIe(e){let t=e.get(`anthropic-ratelimit-unified-overage-disabled-reason`)??null;yi().cachedExtraUsageDisabledReason!==t&&Ti(e=>({...e,cachedExtraUsageDisabledReason:t}))}function AIe(e){if(!uo()){VL={},_c(`anthropic`,[]),(BL.status!==`allowed`||BL.resetsAt)&&RL({status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1});return}VL=SIe(e),_c(`anthropic`,NL.parseHeaders(e));let t=OIe(e);kIe(e),Io(BL,t)||RL(t)}function zL(e){if(!(!uo()||e.status!==429))try{let t={...BL};e.headers&&(VL=SIe(e.headers),_c(`anthropic`,NL.parseHeaders(e.headers)),t=OIe(e.headers),kIe(e.headers)),t.status=`rejected`,Io(BL,t)||RL(t)}catch(e){q(e)}}var jIe,MIe,BL,VL,HL,UL=n((()=>{Nn(),Ho(),Wt(),no(),Uo(),bi(),Qi(),No(),Fie(),Da(),r9(),xo(),lIe(),gce(),LL(),jIe=[{rateLimitType:`five_hour`,claimAbbrev:`5h`,windowSeconds:300*60,thresholds:[{utilization:.9,timePct:.72}]},{rateLimitType:`seven_day`,claimAbbrev:`7d`,windowSeconds:10080*60,thresholds:[{utilization:.75,timePct:.6},{utilization:.5,timePct:.35},{utilization:.25,timePct:.15}]}],MIe={"5h":`five_hour`,"7d":`seven_day`,overage:`overage`},BL={status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},VL={},HL=new Set})),WL=n((()=>{ec()}));function GL(e){return e.startsWith(JL)}function NIe(e){if(!e.isApiErrorMessage)return!1;let t=e.message.content;return Array.isArray(t)?t.some(e=>e.type===`text`&&e.text.startsWith(`Prompt is too long`)):!1}function PIe(e){let t=e.match(/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/i);return{actualTokens:t?parseInt(t[1],10):void 0,limitTokens:t?parseInt(t[2],10):void 0}}function FIe(e){if(!NIe(e)||!e.errorDetails)return;let{actualTokens:t,limitTokens:n}=PIe(e.errorDetails);if(t===void 0||n===void 0)return;let r=t-n;return r>0?r:void 0}function IIe(){let e=`max 100 pages, ${za(W_)}`;return gn()?`PDF too large (${e}). Try reading the file a different way (e.g., extract text with pdftotext).`:`PDF too large (${e}). Double press esc to go back and try again, or use pdftotext to convert to text first.`}function LIe(){return gn()?`PDF is password protected. Try using a CLI tool to extract or convert the PDF.`:`PDF is password protected. Please double press esc to edit your message and try again.`}function RIe(){return gn()?`The PDF file was not valid. Try converting it to text first (e.g., pdftotext).`:`The PDF file was not valid. Double press esc to go back and try again with a different file.`}function KL(){return gn()?`Image was too large. Try resizing the image or using a different approach.`:`Image was too large. Double press esc to go back and try again with a smaller image.`}function zIe(){let e=`max ${za(W_)}`;return gn()?`Request too large (${e}). Try with a smaller file.`:`Request too large (${e}). Double press esc to go back and try with a smaller file.`}function BIe(){return gn()?`Your account does not have access to Claude. Please contact your administrator.`:tR}function VIe(){return gn()?`Your organization does not have access to Claude. Please contact your administrator.`:YIe}function HIe(){return m(process.env.CLAUDE_CODE_REMOTE)}function UIe(e,t,n){try{let r=-1;for(let t=0;t<n.length;t++){let i=n[t];if(!i)continue;let a=i.message.content;if(Array.isArray(a)){for(let n of a)if(n.type===`tool_use`&&`id`in n&&n.id===e){r=t;break}}if(r!==-1)break}let i=-1;for(let n=0;n<t.length;n++){let r=t[n];if(r){if(r.type===`assistant`&&`message`in r){let t=r.message.content;if(Array.isArray(t)){for(let r of t)if(r.type===`tool_use`&&`id`in r&&r.id===e){i=n;break}}}if(i!==-1)break}}let a=[];for(let e=r+1;e<n.length;e++){let t=n[e];if(!t)continue;let r=t.message.content;if(Array.isArray(r))for(let e of r){let n=t.message.role;e.type===`tool_use`&&`id`in e?a.push(`${n}:tool_use:${e.id}`):e.type===`tool_result`&&`tool_use_id`in e?a.push(`${n}:tool_result:${e.tool_use_id}`):e.type===`text`?a.push(`${n}:text`):e.type===`thinking`?a.push(`${n}:thinking`):e.type===`image`?a.push(`${n}:image`):a.push(`${n}:${e.type}`)}else typeof r==`string`&&a.push(`${t.message.role}:string_content`)}let o=[];for(let e=i+1;e<t.length;e++){let n=t[e];if(n)switch(n.type){case`user`:case`assistant`:if(`message`in n){let e=n.message.content;if(Array.isArray(e))for(let t of e){let e=n.message.role;t.type===`tool_use`&&`id`in t?o.push(`${e}:tool_use:${t.id}`):t.type===`tool_result`&&`tool_use_id`in t?o.push(`${e}:tool_result:${t.tool_use_id}`):t.type===`text`?o.push(`${e}:text`):t.type===`thinking`?o.push(`${e}:thinking`):t.type===`image`?o.push(`${e}:image`):o.push(`${e}:${t.type}`)}else typeof e==`string`&&o.push(`${n.message.role}:string_content`)}break;case`attachment`:`attachment`in n&&o.push(`attachment:${n.attachment.type}`);break;case`system`:`subtype`in n&&o.push(`system:${n.subtype}`);break;case`progress`:`progress`in n&&n.progress&&typeof n.progress==`object`&&`type`in n.progress?o.push(`progress:${n.progress.type??`unknown`}`):o.push(`progress:unknown`);break}}J(`tengu_tool_use_tool_result_mismatch_error`,{toolUseId:e,normalizedSequence:a.join(`, `),preNormalizedSequence:o.join(`, `),normalizedMessageCount:n.length,originalMessageCount:t.length,normalizedToolUseIndex:r,originalToolUseIndex:i})}catch{}}function qL(e,t,n){if(e instanceof Fn||e instanceof wn&&e.message.toLowerCase().includes(`timeout`))return A4({content:iR,error:`unknown`});if(e instanceof jL||e instanceof nv)return A4({content:KL()});if(e instanceof Error&&e.message.includes(`Opus is experiencing high load, please use /model to switch to Sonnet`))return A4({content:rR,error:`rate_limit`});if(e instanceof Pn&&e.status===429&&uo()){let n=e.headers?.get?.(`anthropic-ratelimit-unified-representative-claim`),r=e.headers?.get?.(`anthropic-ratelimit-unified-overage-status`);if(n||r){let i={status:`rejected`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},a=e.headers?.get?.(`anthropic-ratelimit-unified-reset`);a&&(i.resetsAt=Number(a)),n&&(i.rateLimitType=n),r&&(i.overageStatus=r);let o=e.headers?.get?.(`anthropic-ratelimit-unified-overage-reset`);o&&(i.overageResetsAt=Number(o));let s=e.headers?.get?.(`anthropic-ratelimit-unified-overage-disabled-reason`);s&&(i.overageDisabledReason=s);let c=pIe(i,t);return A4(c?{content:c,error:`rate_limit`}:{content:l3,error:`rate_limit`})}if(e.message.includes(`Extra usage is required for long context`)){let e=gn()?`enable extra usage at claude.ai/settings/usage, or use --model to switch to standard context`:`enable extra usage at claude.ai/settings/usage, or use /model to switch to standard context`;return A4({content:`${JL}: Extra usage is required for 1M context · ${e}`,error:`rate_limit`})}let i=e.message.replace(/^429\s+/,``),a=i.match(/"message"\s*:\s*"([^"]*)"/)?.[1]||i;return A4({content:`${JL}: Request rejected (429) · ${a||`this may be a temporary capacity issue — check status.anthropic.com`}`,error:`rate_limit`})}if(e instanceof Error&&e.message.toLowerCase().includes(`prompt is too long`))return A4({content:YL,error:`invalid_request`,errorDetails:e.message});if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return A4({content:IIe(),error:`invalid_request`,errorDetails:e.message});if(e instanceof Error&&e.message.includes(`The PDF specified is password protected`))return A4({content:LIe(),error:`invalid_request`});if(e instanceof Error&&e.message.includes(`The PDF specified was not valid`))return A4({content:RIe(),error:`invalid_request`});if(e instanceof Pn&&e.status===400&&e.message.includes(`image exceeds`)&&e.message.includes(`maximum`))return A4({content:KL(),errorDetails:e.message});if(e instanceof Pn&&e.status===400&&e.message.includes(`image dimensions exceed`)&&e.message.includes(`many-image`))return A4({content:gn()?`An image in the conversation exceeds the dimension limit for many-image requests (2000px). Start a new session with fewer images.`:`An image in the conversation exceeds the dimension limit for many-image requests (2000px). Run /compact to remove old images from context, or start a new session.`,error:`invalid_request`,errorDetails:e.message});if(e instanceof Pn&&e.status===413)return A4({content:zIe(),error:`invalid_request`});if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after")){if(n?.messages&&n?.messagesForAPI){let t=e.message.match(/toolu_[a-zA-Z0-9]+/),r=t?t[0]:null;r&&UIe(r,n.messages,n.messagesForAPI)}return A4({content:`API Error: 400 due to tool use concurrency issues.`+(gn()?``:` Run /rewind to recover the conversation.`),error:`invalid_request`})}if(e instanceof Pn&&e.status===400&&e.message.includes("unexpected `tool_use_id` found in `tool_result`")&&J(`tengu_unexpected_tool_result`,{}),e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids must be unique"))return J(`tengu_duplicate_tool_use_id`,{}),A4({content:`API Error: 400 duplicate tool_use ID in conversation history.${gn()?``:` Run /rewind to recover the conversation.`}`,error:`invalid_request`,errorDetails:e.message});if(uo()&&e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`invalid model name`)&&(es(t)||t===`opus`))return A4({content:`Claude Opus is not available with the Claude Pro plan.`,error:`invalid_request`});if(e instanceof Error&&e.message.includes(`Your credit balance is too low`))return A4({content:XL,error:`billing_error`});if(e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`organization has been disabled`)){let{source:e}=To();if(e===`ANTHROPIC_API_KEY`&&process.env.ANTHROPIC_API_KEY&&!uo())return A4({error:`invalid_request`,content:vo()?.accessToken==null?eR:$L})}if(e instanceof Error&&e.message.toLowerCase().includes(`x-api-key`)){if(HIe())return A4({error:`authentication_failed`,content:nR});let{source:e}=To();return A4({error:`authentication_failed`,content:e===`ANTHROPIC_API_KEY`||e===`apiKeyHelper`?QL:ZL})}if(e instanceof Pn&&e.status===403&&e.message.includes(`OAuth token has been revoked`))return A4({error:`authentication_failed`,content:BIe()});if(e instanceof Pn&&(e.status===401||e.status===403)&&e.message.includes(`OAuth authentication is currently not allowed for this organization`))return A4({error:`authentication_failed`,content:VIe()});if(e instanceof Pn&&(e.status===401||e.status===403))return HIe()?A4({error:`authentication_failed`,content:nR}):A4({error:`authentication_failed`,content:`Failed to authenticate. ${JL}: ${e.message}`});if(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&e instanceof Error&&e.message.toLowerCase().includes(`model id`)){let n=gn()?`--model`:`/model`,r=WIe(t);return A4({content:r?`${JL} (${t}): ${e.message}. Try ${n} to switch to ${r}.`:`${JL} (${t}): ${e.message}. Run ${n} to pick a different model.`,error:`invalid_request`})}if(e instanceof Pn&&e.status===404){let e=gn()?`--model`:`/model`,n=WIe(t);return A4({content:n?`The model ${t} is not available on your ${Vo()} deployment. Try ${e} to switch to ${n}, or ask your admin to enable this model.`:`There's an issue with the selected model (${t}). It may not exist or you may not have access to it. Run ${e} to pick a different model.`,error:`invalid_request`})}return e instanceof wn?A4({content:`${JL}: ${Ise(e)}`,error:`unknown`}):e instanceof Error?A4({content:`${JL}: ${e.message}`,error:`unknown`}):A4({content:JL,error:`unknown`})}function WIe(e){if(Vo()===`firstParty`)return;let t=e.toLowerCase();if(t.includes(`opus-4-7`)||t.includes(`opus_4_7`))return lo().opus46;if(t.includes(`opus-4-6`)||t.includes(`opus_4_6`))return lo().opus41;if(t.includes(`sonnet-4-6`)||t.includes(`sonnet_4_6`))return lo().sonnet45;if(t.includes(`sonnet-4-5`)||t.includes(`sonnet_4_5`))return lo().sonnet40}function GIe(e){if(e instanceof Error&&e.message===`Request was aborted.`)return`aborted`;if(e instanceof Fn||e instanceof wn&&e.message.toLowerCase().includes(`timeout`))return`api_timeout`;if(e instanceof Error&&e.message.includes(`Repeated 529 Overloaded errors`))return`repeated_529`;if(e instanceof Error&&e.message.includes(`Opus is experiencing high load, please use /model to switch to Sonnet`))return`capacity_off_switch`;if(e instanceof Pn&&e.status===429)return`rate_limit`;if(e instanceof Pn&&(e.status===529||e.message?.includes(`"type":"overloaded_error"`)))return`server_overload`;if(e instanceof Error&&e.message.toLowerCase().includes(`prompt is too long`))return`prompt_too_long`;if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return`pdf_too_large`;if(e instanceof Error&&e.message.includes(`The PDF specified is password protected`))return`pdf_password_protected`;if(e instanceof Pn&&e.status===400&&e.message.includes(`image exceeds`)&&e.message.includes(`maximum`)||e instanceof Pn&&e.status===400&&e.message.includes(`image dimensions exceed`)&&e.message.includes(`many-image`))return`image_too_large`;if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after"))return`tool_use_mismatch`;if(e instanceof Pn&&e.status===400&&e.message.includes("unexpected `tool_use_id` found in `tool_result`"))return`unexpected_tool_result`;if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids must be unique"))return`duplicate_tool_use_id`;if(e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`invalid model name`))return`invalid_model`;if(e instanceof Error&&e.message.toLowerCase().includes(`credit balance is too low`))return`credit_balance_low`;if(e instanceof Error&&e.message.toLowerCase().includes(`x-api-key`))return`invalid_api_key`;if(e instanceof Pn&&e.status===403&&e.message.includes(`OAuth token has been revoked`))return`token_revoked`;if(e instanceof Pn&&(e.status===401||e.status===403)&&e.message.includes(`OAuth authentication is currently not allowed for this organization`))return`oauth_org_not_allowed`;if(e instanceof Pn&&(e.status===401||e.status===403))return`auth_error`;if(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&e instanceof Error&&e.message.toLowerCase().includes(`model id`))return`bedrock_model_access`;if(e instanceof Pn){let t=e.status;if(t>=500)return`server_error`;if(t>=400)return`client_error`}return e instanceof wn?Zs(e)?.isSSLError?`ssl_cert_error`:`connection_error`:`unknown`}function KIe(e){return e.status===529||e.message?.includes(`"type":"overloaded_error"`)||e.status===429?`rate_limit`:e.status===401||e.status===403?`authentication_failed`:e.status!==void 0&&e.status>=408?`server_error`:`unknown`}function qIe(e,t){if(e===`refusal`)return J(`tengu_refusal_api_response`,{}),A4({content:(gn()?`${JL}: Work Mate is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Try rephrasing the request or attempting a different approach.`:`${JL}: Work Mate is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Please double press esc to edit your last message or start a new session for Work Mate to assist with a different task.`)+(t===`claude-sonnet-4-20250514`?``:` If you are seeing this refusal repeatedly, try running /model claude-sonnet-4-20250514 to switch models.`),error:`invalid_request`})}var JL,YL,XL,ZL,QL,$L,eR,tR,nR,JIe,rR,iR,YIe,aR=n((()=>{Nn(),Bo(),no(),m3(),No(),go(),Jo(),Wt(),G_(),h(),Ba(),rv(),ML(),Da(),UL(),WL(),JL=`API Error`,YL=`Prompt is too long`,XL=`Credit balance is too low`,ZL=`Not logged in`,QL=`Invalid API key · Fix external API key`,$L=`Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your subscription instead`,eR=`Your ANTHROPIC_API_KEY belongs to a disabled organization · Update or unset the environment variable`,tR=`OAuth token revoked`,nR=`Authentication error · This may be a temporary network issue, please try again`,JIe=`Repeated 529 Overloaded errors`,rR=`Opus is experiencing high load, please use /model to switch to Sonnet`,iR=`Request timed out`,YIe=`Your account does not have access to Work Mate.`}));function XIe(e){return e===void 0||pLe.has(e)}function oR(){return!1}function ZIe(e){return lR(e)||e instanceof Pn&&e.status===429}function QIe(e){if(!(e instanceof wn))return!1;let t=Zs(e);return t?.code===`ECONNRESET`||t?.code===`EPIPE`}async function*sR(e,t,n){let r=cLe(n),i={model:n.model,thinkingConfig:n.thinkingConfig,...Xo()&&{fastMode:n.fastMode}},a=null,o=n.initialConsecutive529Errors??0,s,c=0;for(let l=1;l<=r+1;l++){if(n.signal?.aborted)throw new In;let u=Xo()?i.fastMode&&!qo():!1;try{let n=QIe(s);if(a===null||s instanceof Pn&&s.status===401||uR(s)||nLe(s)||aLe(s)||n){if(s instanceof Pn&&s.status===401||uR(s)){let e=vo()?.accessToken;e&&await po(e)}a=await e()}return await t(a,l,i)}catch(e){if(s=e,U(`API error (attempt ${l}/${r+1}): ${e instanceof Pn?`${e.status} ${e.message}`:H(e)}`,{level:`error`}),u&&!oR()&&e instanceof Pn&&(e.status===429||lR(e))){let t=e.headers?.get(`anthropic-ratelimit-unified-overage-disabled-reason`);if(t!=null){Cae(t),i.fastMode=!1;continue}let r=lLe(e);if(r!==null&&r<gLe){await $o(r,n.signal,{abortError:fR});continue}let a=Math.max(r??hLe,_Le),o=lR(e)?`overloaded`:`rate_limit`;Pae(Date.now()+a,o),Xo()&&(i.fastMode=!1);continue}if(u&&tLe(e)){lae(),i.fastMode=!1;continue}if(lR(e)&&!XIe(n.querySource))throw J(`tengu_api_529_background_dropped`,{query_source:n.querySource}),new gR(e,i);if(lR(e)&&(process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS||!uo()&&es(n.model))&&(o++,o>=fLe)){if(n.fallbackModel)throw J(`tengu_api_opus_fallback_triggered`,{original_model:n.model,fallback_model:n.fallbackModel,provider:Fo()}),new _R(n.model,n.fallbackModel);if(!process.env.IS_SANDBOX&&!oR())throw J(`tengu_api_custom_529_overloaded_error`,{}),new gR(Error(JIe),i)}let t=oR()&&ZIe(e);if(l>r&&!t||!(rLe(e)||oLe(e))&&(!(e instanceof Pn)||!sLe(e)))throw new gR(e,i);if(e instanceof Pn){let t=eLe(e);if(t){let{inputTokens:n,contextLimit:r}=t,a=Math.max(0,r-n-1e3);if(a<pR)throw q(Error(`availableContext ${a} is less than FLOOR_OUTPUT_TOKENS ${pR}`)),e;let o=(i.thinkingConfig.type===`enabled`?i.thinkingConfig.budgetTokens:0)+1,s=Math.max(pR,a,o);i.maxTokensOverride=s,J(`tengu_max_tokens_context_overflow_adjustment`,{inputTokens:n,contextLimit:r,adjustedMaxTokens:s,attempt:l});continue}}let a=$Ie(e),d;t&&e instanceof Pn&&e.status===429?(c++,d=uLe(e)??Math.min(cR(c,a,mR),hR)):t?(c++,d=Math.min(cR(c,a,mR),hR)):d=cR(l,a);let f=t?c:l;if(J(`tengu_api_retry`,{attempt:f,delayMs:d,error:e.message,status:e.status,provider:Fo()}),t){d>6e4&&J(`tengu_api_persistent_retry_wait`,{status:e.status,delayMs:d,attempt:f,provider:Fo()});let t=d;for(;t>0;){if(n.signal?.aborted)throw new In;e instanceof Pn&&(yield cxt(e,t,f,r));let i=Math.min(t,mLe);await $o(i,n.signal,{abortError:fR}),t-=i}l>=r&&(l=r)}else e instanceof Pn&&(yield cxt(e,d,l,r)),await $o(d,n.signal,{abortError:fR})}}throw new gR(s,i)}function $Ie(e){return(e.headers?.[`retry-after`]||e.headers?.get?.(`retry-after`))??null}function cR(e,t,n=32e3){if(t){let e=parseInt(t,10);if(!isNaN(e))return e*1e3}let r=Math.min(500*2**(e-1),n);return r+Math.random()*.25*r}function eLe(e){if(e.status!==400||!e.message||!e.message.includes("input length and `max_tokens` exceed context limit"))return;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(t?.length!==4)return;if(!t[1]||!t[2]||!t[3]){q(Error(`Unable to parse max_tokens from max_tokens exceed context limit error message`));return}let n=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!(isNaN(n)||isNaN(r)||isNaN(i)))return{inputTokens:n,maxTokens:r,contextLimit:i}}function tLe(e){return e instanceof Pn&&e.status===400&&(e.message?.includes(`Fast mode is not enabled`)??!1)}function lR(e){return e instanceof Pn?e.status===529||(e.message?.includes(`"type":"overloaded_error"`)??!1):!1}function uR(e){return e instanceof Pn&&e.status===403&&(e.message?.includes(`OAuth token has been revoked`)??!1)}function nLe(e){return!!(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&(coe(e)||e instanceof Pn&&e.status===403))}function rLe(e){return nLe(e)?(Aae(),!0):!1}function iLe(e){if(!(e instanceof Error))return!1;let t=e.message;return t.includes(`Could not load the default credentials`)||t.includes(`Could not refresh access token`)||t.includes(`invalid_grant`)}function aLe(e){return!!(m(process.env.CLAUDE_CODE_USE_VERTEX)&&(iLe(e)||e instanceof Pn&&e.status===401))}function oLe(e){return aLe(e)?(aoe(),!0):!1}function sLe(e){if(oR()&&ZIe(e)||m(process.env.CLAUDE_CODE_REMOTE)&&(e.status===401||e.status===403)||e.message?.includes(`"type":"overloaded_error"`)||eLe(e))return!0;let t=e.headers?.get(`x-should-retry`);return t===`true`&&(!uo()||mo())?!0:t===`false`?!1:e instanceof wn?!0:e.status?e.status===408||e.status===409?!0:e.status===429?!uo()||mo():e.status===401?(zae(),!0):!!(uR(e)||e.status&&e.status>=500):!1}function dR(){return process.env.CLAUDE_CODE_MAX_RETRIES?parseInt(process.env.CLAUDE_CODE_MAX_RETRIES,10):dLe}function cLe(e){return e.maxRetries??dR()}function lLe(e){let t=$Ie(e);if(t){let e=parseInt(t,10);if(!isNaN(e))return e*1e3}return null}function uLe(e){let t=e.headers?.get?.(`anthropic-ratelimit-unified-reset`);if(!t)return null;let n=Number(t);if(!Number.isFinite(n))return null;let r=n*1e3-Date.now();return r<=0?null:Math.min(r,hR)}var fR,dLe,pR,fLe,pLe,mR,hR,mLe,gR,_R,hLe,gLe,_Le,vR=n((()=>{Nn(),ioe(),W(),Qi(),m3(),Jo(),no(),h(),On(),Ro(),No(),Xs(),Po(),Da(),aR(),WL(),b(),fR=()=>new In,dLe=10,pR=3e3,fLe=3,pLe=new Set([`repl_main_thread`,`repl_main_thread:outputStyle:custom`,`repl_main_thread:outputStyle:Explanatory`,`repl_main_thread:outputStyle:Learning`,`sdk`,`agent:custom`,`agent:default`,`agent:builtin`,`compact`,`hook_agent`,`hook_prompt`,`verification_agent`,`side_question`,`auto_mode`]),mR=300*1e3,hR=360*60*1e3,mLe=3e4,gR=class extends Error{constructor(e,t){let n=H(e);super(n),x(this,`originalError`,void 0),x(this,`retryContext`,void 0),this.originalError=e,this.retryContext=t,this.name=`RetryError`,e instanceof Error&&e.stack&&(this.stack=e.stack)}},_R=class extends Error{constructor(e,t){super(`Model fallback triggered: ${e} -> ${t}`),x(this,`originalModel`,void 0),x(this,`fallbackModel`,void 0),this.originalModel=e,this.fallbackModel=t,this.name=`FallbackTriggeredError`}},hLe=1800*1e3,gLe=20*1e3,_Le=600*1e3}));function yR(e){if(e?.type===`assistant`&&e.message&&`usage`in e.message&&!(Array.isArray(e.message.content)&&e.message.content[0]?.type===`text`&&u3.has(e.message.content[0].text))&&e.message.model!==`<synthetic>`)return e.message.usage}function vLe(e){if(e?.type===`assistant`&&`id`in e.message&&e.message.model!==`<synthetic>`)return e.message.id}function bR(e){return e?(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)+(e.output_tokens??0):0}function xR(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(r)return bR(r);t--}return 0}function yLe(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(r){let e=r.iterations;if(e&&e.length>0){let t=e.at(-1);return t.input_tokens+t.output_tokens}return r.input_tokens+r.output_tokens}t--}return 0}function bLe(e){for(let t=e.length-1;t>=0;t--){let n=e[t],r=n?yR(n):void 0;if(r){if((r.input_tokens??0)+(r.cache_creation_input_tokens??0)+(r.cache_read_input_tokens??0)===0&&(r.output_tokens??0)===0)continue;return{input_tokens:r.input_tokens??0,output_tokens:r.output_tokens??0,cache_creation_input_tokens:r.cache_creation_input_tokens??0,cache_read_input_tokens:r.cache_read_input_tokens??0}}}return null}function xLe(e){let t=e.findLast(e=>e.type===`assistant`);if(!t)return!1;let n=yR(t);return n?bR(n)>2e5:!1}function SLe(e){let t=0,n=e.message?.content;if(!Array.isArray(n))return t;for(let e of n)e.type===`text`?t+=e.text.length:e.type===`thinking`?t+=e.thinking.length:e.type===`redacted_thinking`?t+=e.data.length:e.type===`tool_use`&&(t+=V(e.input).length);return t}function SR(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(n&&r){let i=vLe(n);if(i){let n=t-1;for(;n>=0;){let r=e[n],a=r?vLe(r):void 0;if(a===i)t=n;else if(a!==void 0)break;n--}}return bR(r)+b3(e.slice(t+1))}t--}return b3(e)}var CR=n((()=>{w3(),m3(),Yn()}));function CLe(){let e=``;for(let t=0;t<4;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return Y(I8(),`cache-break-${e}.diff`)}function wLe(e){return e.includes(`haiku`)}function wR(e,t){if(e===`compact`)return`repl_main_thread`;for(let n of ILe)if(e.startsWith(n))return t||e;return null}function TLe(e){return e.map(e=>{if(!(`cache_control`in e))return e;let{cache_control:t,...n}=e;return n})}function TR(e){let t=V(e);if(typeof Bun<`u`){let e=Bun.hash(t);return typeof e==`bigint`?Number(e&4294967295n):e}return Vie(t)}function ER(e){return e.startsWith(`mcp__`)?`mcp`:e}function ELe(e,t){let n={};for(let r=0;r<e.length;r++)n[t[r]??`__idx_${r}`]=TR(e[r]);return n}function DLe(e){let t=0;for(let n of e)t+=n.text.length;return t}function OLe(e,t,n){let r=e.map(e=>e.text).join(`
856
+ `).length+1+t,s=[],c=Date.now();for(let e of n){if(e.pastedContents)for(let t of Object.values(e.pastedContents))t.type===`image`&&s.push(t);let t=eIe(e.value,c);s.push(...t),c+=t.length}for(let e of n)pL(`popAll`,typeof e.value==`string`?e.value:void 0);return xL.length=0,xL.push(...r),mL(),{text:a,cursorOffset:o,images:s}}function bL(e){let t=TL[e];return xL.filter(e=>TL[e.priority??`next`]<=t)}function nIe(e){return typeof e.value==`string`&&e.value.trim().startsWith(`/`)&&(!e.skipSlashCommands||e.bridgeOrigin===!0)}var xL,SL,CL,wL,TL,rIe,EL=n((()=>{Wt(),m3(),RFe(),h8(),fn(),xL=[],SL=Object.freeze([]),CL=rn(),wL=CL.subscribe,TL={now:0,next:1,later:2},rIe=new Set([`task-notification`])}));function DL(e,t,n){t(t=>{let r=t.tasks?.[e];if(!r)return t;let i=n(r);return i===r?t:{...t,tasks:{...t.tasks,[e]:i}}})}function OL(e,t){let n=!1;t(t=>{let r=t.tasks[e.id];n=r!==void 0;let i=r&&`retain`in r?{...e,retain:r.retain,startTime:r.startTime,messages:r.messages,diskLoaded:r.diskLoaded,pendingMessages:r.pendingMessages}:e;return{...t,tasks:{...t.tasks,[e.id]:i}}}),!n&&sc({type:`system`,subtype:`task_started`,task_id:e.id,tool_use_id:e.toolUseId,description:e.description,task_type:e.type,workflow_name:`workflowName`in e?e.workflowName:void 0,prompt:`prompt`in e?e.prompt:void 0})}function iIe(e){let t=e.tasks??{};return Object.values(t).filter(e=>e.status===`running`)}async function aIe(e){let t=[],n={},r=[],i=e.tasks??{};for(let e of Object.values(i)){if(e.notified)switch(e.status){case`completed`:case`failed`:case`killed`:r.push(e.id);continue;case`pending`:continue;case`running`:break}if(e.status===`running`){let t=await qwt(e.id,e.outputOffset);t.content&&(n[e.id]=t.newOffset)}}return{attachments:t,updatedTaskOffsets:n,evictedTaskIds:r}}function oIe(e,t,n){let r=Object.keys(t);r.length===0&&n.length===0||e(e=>{let i=!1,a={...e.tasks};for(let e of r){let n=a[e];n?.status===`running`&&(a[e]={...n,outputOffset:t[e]},i=!0)}for(let e of n){let t=a[e];!t||!Xwt(t.status)||!t.notified||`retain`in t&&(t.evictAfter??1/0)>Date.now()||(delete a[e],i=!0)}return i?{...e,tasks:a}:e})}var kL,AL=n((()=>{l5(),EL(),nc(),o5(),kL=3e4}));function sIe(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.type!==`image`||typeof t.source!=`object`||t.source===null)return!1;let n=t.source;return n.type===`base64`&&typeof n.data==`string`}function cIe(e){let t=[],n=0;for(let r of e){if(typeof r!=`object`||!r)continue;let e=r;if(e.type!==`user`)continue;let i=e.message;if(!i)continue;let a=i.content;if(!(typeof a==`string`||!Array.isArray(a))){for(let e of a)if(sIe(e)){n++;let r=e.source.data.length;r>5242880&&(J(`tengu_image_api_validation_failed`,{base64_size_bytes:r,max_bytes:H_}),t.push({index:n,size:r}))}}}if(t.length>0)throw new jL(t,H_)}var jL,ML=n((()=>{G_(),Da(),Ba(),jL=class extends Error{constructor(e,t){let n,r=e[0];n=e.length===1&&r?`Image base64 size (${za(r.size)}) exceeds API limit (${za(t)}). Please resize the image before sending.`:`${e.length} images exceed the API limit (${za(t)}): `+e.map(e=>`Image ${e.index}: ${za(e.size)}`).join(`, `)+`. Please resize these images before sending.`,super(n),this.name=`ImageSizeError`}}})),NL,lIe=n((()=>{NL={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 uIe(){if(m(process.env.DISABLE_COST_WARNINGS)||uo())return!1;let e=dae(),t=soe()!==null;if(!e.hasToken&&!t)return!1;let n=yi(),r=n.oauthAccount?.organizationRole,i=n.oauthAccount?.workspaceRole;return!r||!i?!1:[`admin`,`billing`].includes(r)||[`workspace_admin`,`workspace_billing`].includes(i)}function PL(){if(!uo())return!1;let e=co();if(e===`max`||e===`pro`)return!0;let t=yi().oauthAccount?.organizationRole;return!!t&&[`admin`,`billing`,`owner`,`primary_owner`].includes(t)}var FL=n((()=>{no(),bi(),h()}));function dIe(e){return yIe.some(t=>e.startsWith(t))}function fIe(e,t){if(e.isUsingOverage)return e.overageStatus===`allowed_warning`?{message:`You're close to your extra usage spending limit`,severity:`warning`}:null;if(e.status===`rejected`)return{message:hIe(e,t),severity:`error`};if(e.status===`allowed_warning`){if(e.utilization!==void 0&&e.utilization<.7)return null;let t=co(),n=t===`team`||t===`enterprise`,r=Hae()?.hasExtraUsageEnabled===!0;if(n&&r&&!PL())return null;let i=gIe(e);if(i)return{message:i,severity:`warning`}}return null}function pIe(e,t){let n=fIe(e,t);return n&&n.severity===`error`?n.message:null}function mIe(e,t){let n=fIe(e,t);return n&&n.severity===`warning`?n.message:null}function hIe(e,t){let n=e.resetsAt,r=n?Ia(n,!0):void 0,i=e.overageResetsAt?Ia(e.overageResetsAt,!0):void 0,a=r?` · resets ${r}`:``;if(e.overageStatus===`rejected`){let a=``;return n&&e.overageResetsAt?a=n<e.overageResetsAt?` · resets ${r}`:` · resets ${i}`:r?a=` · resets ${r}`:i&&(a=` · resets ${i}`),e.overageDisabledReason===`out_of_credits`?`You're out of extra usage${a}`:IL(`limit`,a,t)}if(e.rateLimitType===`seven_day_sonnet`){let e=co();return IL(e===`pro`||e===`enterprise`?`weekly limit`:`Sonnet limit`,a,t)}return e.rateLimitType===`seven_day_opus`?IL(`Opus limit`,a,t):e.rateLimitType===`seven_day`?IL(`weekly limit`,a,t):e.rateLimitType===`five_hour`?IL(`session limit`,a,t):IL(`usage limit`,a,t)}function gIe(e){let t=null;switch(e.rateLimitType){case`seven_day`:t=`weekly limit`;break;case`five_hour`:t=`session limit`;break;case`seven_day_opus`:t=`Opus limit`;break;case`seven_day_sonnet`:t=`Sonnet limit`;break;case`overage`:t=`extra usage`;break;case void 0:return null}let n=e.utilization?Math.floor(e.utilization*100):void 0,r=e.resetsAt?Ia(e.resetsAt,!0):void 0,i=_Ie(e.rateLimitType);if(n&&r){let e=`You've used ${n}% of your ${t} · resets ${r}`;return i?`${e} · ${i}`:e}if(n){let e=`You've used ${n}% of your ${t}`;return i?`${e} · ${i}`:e}if(e.rateLimitType===`overage`&&(t+=` limit`),r){let e=`Approaching ${t} · resets ${r}`;return i?`${e} · ${i}`:e}let a=`Approaching ${t}`;return i?`${a} · ${i}`:a}function _Ie(e){return co(),null}function vIe(e){let t=e.resetsAt?Ia(e.resetsAt,!0):``,n=``;if(e.rateLimitType===`five_hour`)n=`session limit`;else if(e.rateLimitType===`seven_day`)n=`weekly limit`;else if(e.rateLimitType===`seven_day_opus`)n=`Opus limit`;else if(e.rateLimitType===`seven_day_sonnet`){let e=co();n=e===`pro`||e===`enterprise`?`weekly limit`:`Sonnet limit`}return n?`You're now using extra usage${t?` · Your ${n} resets ${t}`:``}`:`Now using extra usage`}function IL(e,t,n){return`You've hit your ${e}${t}`}var yIe,LL=n((()=>{no(),FL(),Ba(),yIe=[`You've hit your`,`You've used`,`You're now using extra usage`,`You're close to`,`You're out of extra usage`]}));function bIe(e,t){let n=Date.now()/1e3-(e-t);return Math.max(0,Math.min(1,n/t))}function xIe(){return VL}function SIe(e){let t={};for(let[n,r]of[[`five_hour`,`5h`],[`seven_day`,`7d`]]){let i=e.get(`anthropic-ratelimit-unified-${r}-utilization`),a=e.get(`anthropic-ratelimit-unified-${r}-reset`);i!==null&&a!==null&&(t[n]={utilization:Number(i),resets_at:Number(a)})}return t}function RL(e){BL=e,HL.forEach(t=>t(e));let t=Math.round((e.resetsAt?e.resetsAt-Date.now()/1e3:0)/3600);J(`tengu_claudeai_limits_status_changed`,{status:e.status,unifiedRateLimitFallbackAvailable:e.unifiedRateLimitFallbackAvailable,hoursTillReset:t})}async function CIe(){let e=zo(),t=await jo({maxRetries:0,model:e,source:`quota_check`}),n=[{role:`user`,content:`quota`}],r=eo(e);return t.beta.messages.create({model:e,max_tokens:1,messages:n,metadata:X7(),...r.length>0?{betas:r}:{}}).asResponse()}async function wIe(){if(!Iie()&&uo()&&!gn())try{AIe((await CIe()).headers)}catch(e){e instanceof Pn&&zL(e)}}function TIe(e,t){for(let[n,r]of Object.entries(MIe)){let i=e.get(`anthropic-ratelimit-unified-${n}-surpassed-threshold`);if(i!==null){let a=e.get(`anthropic-ratelimit-unified-${n}-utilization`),o=e.get(`anthropic-ratelimit-unified-${n}-reset`),s=a?Number(a):void 0;return{status:`allowed_warning`,resetsAt:o?Number(o):void 0,rateLimitType:r,utilization:s,unifiedRateLimitFallbackAvailable:t,isUsingOverage:!1,surpassedThreshold:Number(i)}}}return null}function EIe(e,t,n){let{rateLimitType:r,claimAbbrev:i,windowSeconds:a,thresholds:o}=t,s=e.get(`anthropic-ratelimit-unified-${i}-utilization`),c=e.get(`anthropic-ratelimit-unified-${i}-reset`);if(s===null||c===null)return null;let l=Number(s),u=Number(c),d=bIe(u,a);return o.some(e=>l>=e.utilization&&d<=e.timePct)?{status:`allowed_warning`,resetsAt:u,rateLimitType:r,utilization:l,unifiedRateLimitFallbackAvailable:n,isUsingOverage:!1}:null}function DIe(e,t){let n=TIe(e,t);if(n)return n;for(let n of jIe){let r=EIe(e,n,t);if(r)return r}return null}function OIe(e){let t=e.get(`anthropic-ratelimit-unified-status`)||`allowed`,n=e.get(`anthropic-ratelimit-unified-reset`),r=n?Number(n):void 0,i=e.get(`anthropic-ratelimit-unified-fallback`)===`available`,a=e.get(`anthropic-ratelimit-unified-representative-claim`),o=e.get(`anthropic-ratelimit-unified-overage-status`),s=e.get(`anthropic-ratelimit-unified-overage-reset`),c=s?Number(s):void 0,l=e.get(`anthropic-ratelimit-unified-overage-disabled-reason`),u=t===`rejected`&&(o===`allowed`||o===`allowed_warning`),d=t;if(t===`allowed`||t===`allowed_warning`){let t=DIe(e,i);if(t)return t;d=`allowed`}return{status:d,resetsAt:r,unifiedRateLimitFallbackAvailable:i,...a&&{rateLimitType:a},...o&&{overageStatus:o},...c&&{overageResetsAt:c},...l&&{overageDisabledReason:l},isUsingOverage:u}}function kIe(e){let t=e.get(`anthropic-ratelimit-unified-overage-disabled-reason`)??null;yi().cachedExtraUsageDisabledReason!==t&&Ti(e=>({...e,cachedExtraUsageDisabledReason:t}))}function AIe(e){if(!uo()){VL={},_c(`anthropic`,[]),(BL.status!==`allowed`||BL.resetsAt)&&RL({status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1});return}VL=SIe(e),_c(`anthropic`,NL.parseHeaders(e));let t=OIe(e);kIe(e),Io(BL,t)||RL(t)}function zL(e){if(!(!uo()||e.status!==429))try{let t={...BL};e.headers&&(VL=SIe(e.headers),_c(`anthropic`,NL.parseHeaders(e.headers)),t=OIe(e.headers),kIe(e.headers)),t.status=`rejected`,Io(BL,t)||RL(t)}catch(e){q(e)}}var jIe,MIe,BL,VL,HL,UL=n((()=>{Nn(),Ho(),Wt(),no(),Uo(),bi(),Qi(),No(),Fie(),Da(),r9(),xo(),lIe(),gce(),LL(),jIe=[{rateLimitType:`five_hour`,claimAbbrev:`5h`,windowSeconds:300*60,thresholds:[{utilization:.9,timePct:.72}]},{rateLimitType:`seven_day`,claimAbbrev:`7d`,windowSeconds:10080*60,thresholds:[{utilization:.75,timePct:.6},{utilization:.5,timePct:.35},{utilization:.25,timePct:.15}]}],MIe={"5h":`five_hour`,"7d":`seven_day`,overage:`overage`},BL={status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},VL={},HL=new Set})),WL=n((()=>{ec()}));function GL(e){return e.startsWith(JL)}function NIe(e){if(!e.isApiErrorMessage)return!1;let t=e.message.content;return Array.isArray(t)?t.some(e=>e.type===`text`&&e.text.startsWith(`Prompt is too long`)):!1}function PIe(e){let t=e.match(/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/i);return{actualTokens:t?parseInt(t[1],10):void 0,limitTokens:t?parseInt(t[2],10):void 0}}function FIe(e){if(!NIe(e)||!e.errorDetails)return;let{actualTokens:t,limitTokens:n}=PIe(e.errorDetails);if(t===void 0||n===void 0)return;let r=t-n;return r>0?r:void 0}function IIe(){let e=`max 100 pages, ${za(W_)}`;return gn()?`PDF too large (${e}). Try reading the file a different way (e.g., extract text with pdftotext).`:`PDF too large (${e}). Double press esc to go back and try again, or use pdftotext to convert to text first.`}function LIe(){return gn()?`PDF is password protected. Try using a CLI tool to extract or convert the PDF.`:`PDF is password protected. Please double press esc to edit your message and try again.`}function RIe(){return gn()?`The PDF file was not valid. Try converting it to text first (e.g., pdftotext).`:`The PDF file was not valid. Double press esc to go back and try again with a different file.`}function KL(){return gn()?`Image was too large. Try resizing the image or using a different approach.`:`Image was too large. Double press esc to go back and try again with a smaller image.`}function zIe(){let e=`max ${za(W_)}`;return gn()?`Request too large (${e}). Try with a smaller file.`:`Request too large (${e}). Double press esc to go back and try with a smaller file.`}function BIe(){return gn()?`Your account does not have access to Work Mate. Please contact your administrator.`:tR}function VIe(){return gn()?`Your organization does not have access to Work Mate. Please contact your administrator.`:YIe}function HIe(){return m(process.env.CLAUDE_CODE_REMOTE)}function UIe(e,t,n){try{let r=-1;for(let t=0;t<n.length;t++){let i=n[t];if(!i)continue;let a=i.message.content;if(Array.isArray(a)){for(let n of a)if(n.type===`tool_use`&&`id`in n&&n.id===e){r=t;break}}if(r!==-1)break}let i=-1;for(let n=0;n<t.length;n++){let r=t[n];if(r){if(r.type===`assistant`&&`message`in r){let t=r.message.content;if(Array.isArray(t)){for(let r of t)if(r.type===`tool_use`&&`id`in r&&r.id===e){i=n;break}}}if(i!==-1)break}}let a=[];for(let e=r+1;e<n.length;e++){let t=n[e];if(!t)continue;let r=t.message.content;if(Array.isArray(r))for(let e of r){let n=t.message.role;e.type===`tool_use`&&`id`in e?a.push(`${n}:tool_use:${e.id}`):e.type===`tool_result`&&`tool_use_id`in e?a.push(`${n}:tool_result:${e.tool_use_id}`):e.type===`text`?a.push(`${n}:text`):e.type===`thinking`?a.push(`${n}:thinking`):e.type===`image`?a.push(`${n}:image`):a.push(`${n}:${e.type}`)}else typeof r==`string`&&a.push(`${t.message.role}:string_content`)}let o=[];for(let e=i+1;e<t.length;e++){let n=t[e];if(n)switch(n.type){case`user`:case`assistant`:if(`message`in n){let e=n.message.content;if(Array.isArray(e))for(let t of e){let e=n.message.role;t.type===`tool_use`&&`id`in t?o.push(`${e}:tool_use:${t.id}`):t.type===`tool_result`&&`tool_use_id`in t?o.push(`${e}:tool_result:${t.tool_use_id}`):t.type===`text`?o.push(`${e}:text`):t.type===`thinking`?o.push(`${e}:thinking`):t.type===`image`?o.push(`${e}:image`):o.push(`${e}:${t.type}`)}else typeof e==`string`&&o.push(`${n.message.role}:string_content`)}break;case`attachment`:`attachment`in n&&o.push(`attachment:${n.attachment.type}`);break;case`system`:`subtype`in n&&o.push(`system:${n.subtype}`);break;case`progress`:`progress`in n&&n.progress&&typeof n.progress==`object`&&`type`in n.progress?o.push(`progress:${n.progress.type??`unknown`}`):o.push(`progress:unknown`);break}}J(`tengu_tool_use_tool_result_mismatch_error`,{toolUseId:e,normalizedSequence:a.join(`, `),preNormalizedSequence:o.join(`, `),normalizedMessageCount:n.length,originalMessageCount:t.length,normalizedToolUseIndex:r,originalToolUseIndex:i})}catch{}}function qL(e,t,n){if(e instanceof Fn||e instanceof wn&&e.message.toLowerCase().includes(`timeout`))return A4({content:iR,error:`unknown`});if(e instanceof jL||e instanceof nv)return A4({content:KL()});if(e instanceof Error&&e.message.includes(`Opus is experiencing high load, please use /model to switch to Sonnet`))return A4({content:rR,error:`rate_limit`});if(e instanceof Pn&&e.status===429&&uo()){let n=e.headers?.get?.(`anthropic-ratelimit-unified-representative-claim`),r=e.headers?.get?.(`anthropic-ratelimit-unified-overage-status`);if(n||r){let i={status:`rejected`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},a=e.headers?.get?.(`anthropic-ratelimit-unified-reset`);a&&(i.resetsAt=Number(a)),n&&(i.rateLimitType=n),r&&(i.overageStatus=r);let o=e.headers?.get?.(`anthropic-ratelimit-unified-overage-reset`);o&&(i.overageResetsAt=Number(o));let s=e.headers?.get?.(`anthropic-ratelimit-unified-overage-disabled-reason`);s&&(i.overageDisabledReason=s);let c=pIe(i,t);return A4(c?{content:c,error:`rate_limit`}:{content:l3,error:`rate_limit`})}if(e.message.includes(`Extra usage is required for long context`)){let e=gn()?`enable extra usage at claude.ai/settings/usage, or use --model to switch to standard context`:`enable extra usage at claude.ai/settings/usage, or use /model to switch to standard context`;return A4({content:`${JL}: Extra usage is required for 1M context · ${e}`,error:`rate_limit`})}let i=e.message.replace(/^429\s+/,``),a=i.match(/"message"\s*:\s*"([^"]*)"/)?.[1]||i;return A4({content:`${JL}: Request rejected (429) · ${a||`this may be a temporary capacity issue — check status.anthropic.com`}`,error:`rate_limit`})}if(e instanceof Error&&e.message.toLowerCase().includes(`prompt is too long`))return A4({content:YL,error:`invalid_request`,errorDetails:e.message});if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return A4({content:IIe(),error:`invalid_request`,errorDetails:e.message});if(e instanceof Error&&e.message.includes(`The PDF specified is password protected`))return A4({content:LIe(),error:`invalid_request`});if(e instanceof Error&&e.message.includes(`The PDF specified was not valid`))return A4({content:RIe(),error:`invalid_request`});if(e instanceof Pn&&e.status===400&&e.message.includes(`image exceeds`)&&e.message.includes(`maximum`))return A4({content:KL(),errorDetails:e.message});if(e instanceof Pn&&e.status===400&&e.message.includes(`image dimensions exceed`)&&e.message.includes(`many-image`))return A4({content:gn()?`An image in the conversation exceeds the dimension limit for many-image requests (2000px). Start a new session with fewer images.`:`An image in the conversation exceeds the dimension limit for many-image requests (2000px). Run /compact to remove old images from context, or start a new session.`,error:`invalid_request`,errorDetails:e.message});if(e instanceof Pn&&e.status===413)return A4({content:zIe(),error:`invalid_request`});if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after")){if(n?.messages&&n?.messagesForAPI){let t=e.message.match(/toolu_[a-zA-Z0-9]+/),r=t?t[0]:null;r&&UIe(r,n.messages,n.messagesForAPI)}return A4({content:`API Error: 400 due to tool use concurrency issues.`+(gn()?``:` Run /rewind to recover the conversation.`),error:`invalid_request`})}if(e instanceof Pn&&e.status===400&&e.message.includes("unexpected `tool_use_id` found in `tool_result`")&&J(`tengu_unexpected_tool_result`,{}),e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids must be unique"))return J(`tengu_duplicate_tool_use_id`,{}),A4({content:`API Error: 400 duplicate tool_use ID in conversation history.${gn()?``:` Run /rewind to recover the conversation.`}`,error:`invalid_request`,errorDetails:e.message});if(uo()&&e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`invalid model name`)&&(es(t)||t===`opus`))return A4({content:`Claude Opus is not available with the Claude Pro plan.`,error:`invalid_request`});if(e instanceof Error&&e.message.includes(`Your credit balance is too low`))return A4({content:XL,error:`billing_error`});if(e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`organization has been disabled`)){let{source:e}=To();if(e===`ANTHROPIC_API_KEY`&&process.env.ANTHROPIC_API_KEY&&!uo())return A4({error:`invalid_request`,content:vo()?.accessToken==null?eR:$L})}if(e instanceof Error&&e.message.toLowerCase().includes(`x-api-key`)){if(HIe())return A4({error:`authentication_failed`,content:nR});let{source:e}=To();return A4({error:`authentication_failed`,content:e===`ANTHROPIC_API_KEY`||e===`apiKeyHelper`?QL:ZL})}if(e instanceof Pn&&e.status===403&&e.message.includes(`OAuth token has been revoked`))return A4({error:`authentication_failed`,content:BIe()});if(e instanceof Pn&&(e.status===401||e.status===403)&&e.message.includes(`OAuth authentication is currently not allowed for this organization`))return A4({error:`authentication_failed`,content:VIe()});if(e instanceof Pn&&(e.status===401||e.status===403))return HIe()?A4({error:`authentication_failed`,content:nR}):A4({error:`authentication_failed`,content:`Failed to authenticate. ${JL}: ${e.message}`});if(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&e instanceof Error&&e.message.toLowerCase().includes(`model id`)){let n=gn()?`--model`:`/model`,r=WIe(t);return A4({content:r?`${JL} (${t}): ${e.message}. Try ${n} to switch to ${r}.`:`${JL} (${t}): ${e.message}. Run ${n} to pick a different model.`,error:`invalid_request`})}if(e instanceof Pn&&e.status===404){let e=gn()?`--model`:`/model`,n=WIe(t);return A4({content:n?`The model ${t} is not available on your ${Vo()} deployment. Try ${e} to switch to ${n}, or ask your admin to enable this model.`:`There's an issue with the selected model (${t}). It may not exist or you may not have access to it. Run ${e} to pick a different model.`,error:`invalid_request`})}return e instanceof wn?A4({content:`${JL}: ${Ise(e)}`,error:`unknown`}):e instanceof Error?A4({content:`${JL}: ${e.message}`,error:`unknown`}):A4({content:JL,error:`unknown`})}function WIe(e){if(Vo()===`firstParty`)return;let t=e.toLowerCase();if(t.includes(`opus-4-7`)||t.includes(`opus_4_7`))return lo().opus46;if(t.includes(`opus-4-6`)||t.includes(`opus_4_6`))return lo().opus41;if(t.includes(`sonnet-4-6`)||t.includes(`sonnet_4_6`))return lo().sonnet45;if(t.includes(`sonnet-4-5`)||t.includes(`sonnet_4_5`))return lo().sonnet40}function GIe(e){if(e instanceof Error&&e.message===`Request was aborted.`)return`aborted`;if(e instanceof Fn||e instanceof wn&&e.message.toLowerCase().includes(`timeout`))return`api_timeout`;if(e instanceof Error&&e.message.includes(`Repeated 529 Overloaded errors`))return`repeated_529`;if(e instanceof Error&&e.message.includes(`Opus is experiencing high load, please use /model to switch to Sonnet`))return`capacity_off_switch`;if(e instanceof Pn&&e.status===429)return`rate_limit`;if(e instanceof Pn&&(e.status===529||e.message?.includes(`"type":"overloaded_error"`)))return`server_overload`;if(e instanceof Error&&e.message.toLowerCase().includes(`prompt is too long`))return`prompt_too_long`;if(e instanceof Error&&/maximum of \d+ PDF pages/.test(e.message))return`pdf_too_large`;if(e instanceof Error&&e.message.includes(`The PDF specified is password protected`))return`pdf_password_protected`;if(e instanceof Pn&&e.status===400&&e.message.includes(`image exceeds`)&&e.message.includes(`maximum`)||e instanceof Pn&&e.status===400&&e.message.includes(`image dimensions exceed`)&&e.message.includes(`many-image`))return`image_too_large`;if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids were found without `tool_result` blocks immediately after"))return`tool_use_mismatch`;if(e instanceof Pn&&e.status===400&&e.message.includes("unexpected `tool_use_id` found in `tool_result`"))return`unexpected_tool_result`;if(e instanceof Pn&&e.status===400&&e.message.includes("`tool_use` ids must be unique"))return`duplicate_tool_use_id`;if(e instanceof Pn&&e.status===400&&e.message.toLowerCase().includes(`invalid model name`))return`invalid_model`;if(e instanceof Error&&e.message.toLowerCase().includes(`credit balance is too low`))return`credit_balance_low`;if(e instanceof Error&&e.message.toLowerCase().includes(`x-api-key`))return`invalid_api_key`;if(e instanceof Pn&&e.status===403&&e.message.includes(`OAuth token has been revoked`))return`token_revoked`;if(e instanceof Pn&&(e.status===401||e.status===403)&&e.message.includes(`OAuth authentication is currently not allowed for this organization`))return`oauth_org_not_allowed`;if(e instanceof Pn&&(e.status===401||e.status===403))return`auth_error`;if(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&e instanceof Error&&e.message.toLowerCase().includes(`model id`))return`bedrock_model_access`;if(e instanceof Pn){let t=e.status;if(t>=500)return`server_error`;if(t>=400)return`client_error`}return e instanceof wn?Zs(e)?.isSSLError?`ssl_cert_error`:`connection_error`:`unknown`}function KIe(e){return e.status===529||e.message?.includes(`"type":"overloaded_error"`)||e.status===429?`rate_limit`:e.status===401||e.status===403?`authentication_failed`:e.status!==void 0&&e.status>=408?`server_error`:`unknown`}function qIe(e,t){if(e===`refusal`)return J(`tengu_refusal_api_response`,{}),A4({content:(gn()?`${JL}: Work Mate is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Try rephrasing the request or attempting a different approach.`:`${JL}: Work Mate is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup). Please double press esc to edit your last message or start a new session for Work Mate to assist with a different task.`)+(t===`claude-sonnet-4-20250514`?``:` If you are seeing this refusal repeatedly, try running /model claude-sonnet-4-20250514 to switch models.`),error:`invalid_request`})}var JL,YL,XL,ZL,QL,$L,eR,tR,nR,JIe,rR,iR,YIe,aR=n((()=>{Nn(),Bo(),no(),m3(),No(),go(),Jo(),Wt(),G_(),h(),Ba(),rv(),ML(),Da(),UL(),WL(),JL=`API Error`,YL=`Prompt is too long`,XL=`Credit balance is too low`,ZL=`Not logged in`,QL=`Invalid API key · Fix external API key`,$L=`Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your subscription instead`,eR=`Your ANTHROPIC_API_KEY belongs to a disabled organization · Update or unset the environment variable`,tR=`OAuth token revoked`,nR=`Authentication error · This may be a temporary network issue, please try again`,JIe=`Repeated 529 Overloaded errors`,rR=`Opus is experiencing high load, please use /model to switch to Sonnet`,iR=`Request timed out`,YIe=`Your account does not have access to Work Mate.`}));function XIe(e){return e===void 0||pLe.has(e)}function oR(){return!1}function ZIe(e){return lR(e)||e instanceof Pn&&e.status===429}function QIe(e){if(!(e instanceof wn))return!1;let t=Zs(e);return t?.code===`ECONNRESET`||t?.code===`EPIPE`}async function*sR(e,t,n){let r=cLe(n),i={model:n.model,thinkingConfig:n.thinkingConfig,...Xo()&&{fastMode:n.fastMode}},a=null,o=n.initialConsecutive529Errors??0,s,c=0;for(let l=1;l<=r+1;l++){if(n.signal?.aborted)throw new In;let u=Xo()?i.fastMode&&!qo():!1;try{let n=QIe(s);if(a===null||s instanceof Pn&&s.status===401||uR(s)||nLe(s)||aLe(s)||n){if(s instanceof Pn&&s.status===401||uR(s)){let e=vo()?.accessToken;e&&await po(e)}a=await e()}return await t(a,l,i)}catch(e){if(s=e,U(`API error (attempt ${l}/${r+1}): ${e instanceof Pn?`${e.status} ${e.message}`:H(e)}`,{level:`error`}),u&&!oR()&&e instanceof Pn&&(e.status===429||lR(e))){let t=e.headers?.get(`anthropic-ratelimit-unified-overage-disabled-reason`);if(t!=null){Cae(t),i.fastMode=!1;continue}let r=lLe(e);if(r!==null&&r<gLe){await $o(r,n.signal,{abortError:fR});continue}let a=Math.max(r??hLe,_Le),o=lR(e)?`overloaded`:`rate_limit`;Pae(Date.now()+a,o),Xo()&&(i.fastMode=!1);continue}if(u&&tLe(e)){lae(),i.fastMode=!1;continue}if(lR(e)&&!XIe(n.querySource))throw J(`tengu_api_529_background_dropped`,{query_source:n.querySource}),new gR(e,i);if(lR(e)&&(process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS||!uo()&&es(n.model))&&(o++,o>=fLe)){if(n.fallbackModel)throw J(`tengu_api_opus_fallback_triggered`,{original_model:n.model,fallback_model:n.fallbackModel,provider:Fo()}),new _R(n.model,n.fallbackModel);if(!process.env.IS_SANDBOX&&!oR())throw J(`tengu_api_custom_529_overloaded_error`,{}),new gR(Error(JIe),i)}let t=oR()&&ZIe(e);if(l>r&&!t||!(rLe(e)||oLe(e))&&(!(e instanceof Pn)||!sLe(e)))throw new gR(e,i);if(e instanceof Pn){let t=eLe(e);if(t){let{inputTokens:n,contextLimit:r}=t,a=Math.max(0,r-n-1e3);if(a<pR)throw q(Error(`availableContext ${a} is less than FLOOR_OUTPUT_TOKENS ${pR}`)),e;let o=(i.thinkingConfig.type===`enabled`?i.thinkingConfig.budgetTokens:0)+1,s=Math.max(pR,a,o);i.maxTokensOverride=s,J(`tengu_max_tokens_context_overflow_adjustment`,{inputTokens:n,contextLimit:r,adjustedMaxTokens:s,attempt:l});continue}}let a=$Ie(e),d;t&&e instanceof Pn&&e.status===429?(c++,d=uLe(e)??Math.min(cR(c,a,mR),hR)):t?(c++,d=Math.min(cR(c,a,mR),hR)):d=cR(l,a);let f=t?c:l;if(J(`tengu_api_retry`,{attempt:f,delayMs:d,error:e.message,status:e.status,provider:Fo()}),t){d>6e4&&J(`tengu_api_persistent_retry_wait`,{status:e.status,delayMs:d,attempt:f,provider:Fo()});let t=d;for(;t>0;){if(n.signal?.aborted)throw new In;e instanceof Pn&&(yield cxt(e,t,f,r));let i=Math.min(t,mLe);await $o(i,n.signal,{abortError:fR}),t-=i}l>=r&&(l=r)}else e instanceof Pn&&(yield cxt(e,d,l,r)),await $o(d,n.signal,{abortError:fR})}}throw new gR(s,i)}function $Ie(e){return(e.headers?.[`retry-after`]||e.headers?.get?.(`retry-after`))??null}function cR(e,t,n=32e3){if(t){let e=parseInt(t,10);if(!isNaN(e))return e*1e3}let r=Math.min(500*2**(e-1),n);return r+Math.random()*.25*r}function eLe(e){if(e.status!==400||!e.message||!e.message.includes("input length and `max_tokens` exceed context limit"))return;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(t?.length!==4)return;if(!t[1]||!t[2]||!t[3]){q(Error(`Unable to parse max_tokens from max_tokens exceed context limit error message`));return}let n=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!(isNaN(n)||isNaN(r)||isNaN(i)))return{inputTokens:n,maxTokens:r,contextLimit:i}}function tLe(e){return e instanceof Pn&&e.status===400&&(e.message?.includes(`Fast mode is not enabled`)??!1)}function lR(e){return e instanceof Pn?e.status===529||(e.message?.includes(`"type":"overloaded_error"`)??!1):!1}function uR(e){return e instanceof Pn&&e.status===403&&(e.message?.includes(`OAuth token has been revoked`)??!1)}function nLe(e){return!!(m(process.env.CLAUDE_CODE_USE_BEDROCK)&&(coe(e)||e instanceof Pn&&e.status===403))}function rLe(e){return nLe(e)?(Aae(),!0):!1}function iLe(e){if(!(e instanceof Error))return!1;let t=e.message;return t.includes(`Could not load the default credentials`)||t.includes(`Could not refresh access token`)||t.includes(`invalid_grant`)}function aLe(e){return!!(m(process.env.CLAUDE_CODE_USE_VERTEX)&&(iLe(e)||e instanceof Pn&&e.status===401))}function oLe(e){return aLe(e)?(aoe(),!0):!1}function sLe(e){if(oR()&&ZIe(e)||m(process.env.CLAUDE_CODE_REMOTE)&&(e.status===401||e.status===403)||e.message?.includes(`"type":"overloaded_error"`)||eLe(e))return!0;let t=e.headers?.get(`x-should-retry`);return t===`true`&&(!uo()||mo())?!0:t===`false`?!1:e instanceof wn?!0:e.status?e.status===408||e.status===409?!0:e.status===429?!uo()||mo():e.status===401?(zae(),!0):!!(uR(e)||e.status&&e.status>=500):!1}function dR(){return process.env.CLAUDE_CODE_MAX_RETRIES?parseInt(process.env.CLAUDE_CODE_MAX_RETRIES,10):dLe}function cLe(e){return e.maxRetries??dR()}function lLe(e){let t=$Ie(e);if(t){let e=parseInt(t,10);if(!isNaN(e))return e*1e3}return null}function uLe(e){let t=e.headers?.get?.(`anthropic-ratelimit-unified-reset`);if(!t)return null;let n=Number(t);if(!Number.isFinite(n))return null;let r=n*1e3-Date.now();return r<=0?null:Math.min(r,hR)}var fR,dLe,pR,fLe,pLe,mR,hR,mLe,gR,_R,hLe,gLe,_Le,vR=n((()=>{Nn(),ioe(),W(),Qi(),m3(),Jo(),no(),h(),On(),Ro(),No(),Xs(),Po(),Da(),aR(),WL(),b(),fR=()=>new In,dLe=10,pR=3e3,fLe=3,pLe=new Set([`repl_main_thread`,`repl_main_thread:outputStyle:custom`,`repl_main_thread:outputStyle:Explanatory`,`repl_main_thread:outputStyle:Learning`,`sdk`,`agent:custom`,`agent:default`,`agent:builtin`,`compact`,`hook_agent`,`hook_prompt`,`verification_agent`,`side_question`,`auto_mode`]),mR=300*1e3,hR=360*60*1e3,mLe=3e4,gR=class extends Error{constructor(e,t){let n=H(e);super(n),x(this,`originalError`,void 0),x(this,`retryContext`,void 0),this.originalError=e,this.retryContext=t,this.name=`RetryError`,e instanceof Error&&e.stack&&(this.stack=e.stack)}},_R=class extends Error{constructor(e,t){super(`Model fallback triggered: ${e} -> ${t}`),x(this,`originalModel`,void 0),x(this,`fallbackModel`,void 0),this.originalModel=e,this.fallbackModel=t,this.name=`FallbackTriggeredError`}},hLe=1800*1e3,gLe=20*1e3,_Le=600*1e3}));function yR(e){if(e?.type===`assistant`&&e.message&&`usage`in e.message&&!(Array.isArray(e.message.content)&&e.message.content[0]?.type===`text`&&u3.has(e.message.content[0].text))&&e.message.model!==`<synthetic>`)return e.message.usage}function vLe(e){if(e?.type===`assistant`&&`id`in e.message&&e.message.model!==`<synthetic>`)return e.message.id}function bR(e){return e?(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)+(e.output_tokens??0):0}function xR(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(r)return bR(r);t--}return 0}function yLe(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(r){let e=r.iterations;if(e&&e.length>0){let t=e.at(-1);return t.input_tokens+t.output_tokens}return r.input_tokens+r.output_tokens}t--}return 0}function bLe(e){for(let t=e.length-1;t>=0;t--){let n=e[t],r=n?yR(n):void 0;if(r){if((r.input_tokens??0)+(r.cache_creation_input_tokens??0)+(r.cache_read_input_tokens??0)===0&&(r.output_tokens??0)===0)continue;return{input_tokens:r.input_tokens??0,output_tokens:r.output_tokens??0,cache_creation_input_tokens:r.cache_creation_input_tokens??0,cache_read_input_tokens:r.cache_read_input_tokens??0}}}return null}function xLe(e){let t=e.findLast(e=>e.type===`assistant`);if(!t)return!1;let n=yR(t);return n?bR(n)>2e5:!1}function SLe(e){let t=0,n=e.message?.content;if(!Array.isArray(n))return t;for(let e of n)e.type===`text`?t+=e.text.length:e.type===`thinking`?t+=e.thinking.length:e.type===`redacted_thinking`?t+=e.data.length:e.type===`tool_use`&&(t+=V(e.input).length);return t}function SR(e){let t=e.length-1;for(;t>=0;){let n=e[t],r=n?yR(n):void 0;if(n&&r){let i=vLe(n);if(i){let n=t-1;for(;n>=0;){let r=e[n],a=r?vLe(r):void 0;if(a===i)t=n;else if(a!==void 0)break;n--}}return bR(r)+b3(e.slice(t+1))}t--}return b3(e)}var CR=n((()=>{w3(),m3(),Yn()}));function CLe(){let e=``;for(let t=0;t<4;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`[Math.floor(Math.random()*36)];return Y(I8(),`cache-break-${e}.diff`)}function wLe(e){return e.includes(`haiku`)}function wR(e,t){if(e===`compact`)return`repl_main_thread`;for(let n of ILe)if(e.startsWith(n))return t||e;return null}function TLe(e){return e.map(e=>{if(!(`cache_control`in e))return e;let{cache_control:t,...n}=e;return n})}function TR(e){let t=V(e);if(typeof Bun<`u`){let e=Bun.hash(t);return typeof e==`bigint`?Number(e&4294967295n):e}return Vie(t)}function ER(e){return e.startsWith(`mcp__`)?`mcp`:e}function ELe(e,t){let n={};for(let r=0;r<e.length;r++)n[t[r]??`__idx_${r}`]=TR(e[r]);return n}function DLe(e){let t=0;for(let n of e)t+=n.text.length;return t}function OLe(e,t,n){let r=e.map(e=>e.text).join(`
857
857
 
858
858
  `),i=t.map(e=>{if(!(`name`in e))return`unknown`;let t=`description`in e?e.description:``,n=`input_schema`in e?V(e.input_schema):``;return`${e.name}\n description: ${t}\n input_schema: ${n}`}).sort().join(`
859
859
 
@@ -861,7 +861,7 @@ Usage notes:
861
861
  ... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)`:i;return Ai(`info`,`git_status_completed`,{duration_ms:Date.now()-e,truncated:i.length>qR}),[`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(`
862
862
 
863
863
  `)}catch(t){return Ai(`error`,`git_status_failed`,{duration_ms:Date.now()-e}),q(t),null}}),YR=u(async()=>{let e=Date.now();Ai(`info`,`system_context_started`);let t=m(process.env.CLAUDE_CODE_REMOTE)||!hRe()?null:await JR();return Ai(`info`,`system_context_completed`,{duration_ms:Date.now()-e,has_git_status:t!==null,has_injection:!1}),{...t&&{gitStatus:t}}}),XR=u(async()=>{let e=Date.now();Ai(`info`,`user_context_started`);let t=m(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS)||v()&&Qt().length===0,n=t?null:AF(gF(await DF()));return Ate(n||null),Ai(`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 ${WR()}.`}})}));function yRe(){return ic()}function QR({mainThreadAgentDefinition:e,toolUseContext:t,customSystemPrompt:n,defaultSystemPrompt:r,appendSystemPrompt:i,overrideSystemPrompt:a}){if(a)return Qs([a]);let o=e?q9(e)?e.getSystemPrompt({toolUseContext:{options:t.options}}):e.getSystemPrompt():void 0;return e?.memory&&J(`tengu_agent_memory_loaded`,{scope:e.memory,source:`main-thread`}),o&&yRe()?Qs([...r,`\n# Custom Agent Instructions\n${o}`,...i?[i]:[]]):Qs([...o?[o]:n?[n]:r,...i?[i]:[]])}var $R=n((()=>{Da(),$9(),BI(),tc()})),bRe=i({_resetCacheWarningStateForTest:()=>ERe,calculateCacheHitRate:()=>CRe,createCacheWarningMessage:()=>TRe,getCacheThreshold:()=>xRe,isCacheWarningEnabled:()=>SRe,shouldShowCacheWarning:()=>wRe});function xRe(){return Xr().cacheThreshold??ORe}function SRe(){return Xr().cacheWarningEnabled??!0}function CRe(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 wRe(e,t,n){let r=CRe(e);if(r===null)return null;let i=ez.get(t);if(!i){if(i={lastHitRate:null,lastTimestamp:null},ez.size>=DRe){let e=ez.keys().next().value;e!==void 0&&ez.delete(e)}ez.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 TRe(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:bl(),isMeta:!1}}function ERe(){ez.clear()}var ez,DRe,ORe,kRe=n((()=>{Vr(),ez=new Map,DRe=50,ORe=80}));async function tz(e,t){try{let n=await v3(e,t);if(n!==null)return n;U(`countTokensWithFallback: API returned null, trying haiku fallback (${t.length} tools)`)}catch(e){U(`countTokensWithFallback: API failed: ${H(e)}`),q(e)}try{let n=await Xxt(e,t);return n===null&&U(`countTokensWithFallback: haiku fallback also returned null (${t.length} tools)`),n}catch(e){return U(`countTokensWithFallback: haiku fallback failed: ${H(e)}`),q(e),null}}async function nz(e,t,n,r){let i=await tz([],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(`, `);U(`countToolDefinitionTokens returned ${i} for ${e.length} tools: ${t.slice(0,100)}${t.length>100?`...`:``}`)}return i??0}function ARe(e){let t=e.match(/^#+\s+(.+)$/m);if(t)return t[1].trim();let n=e.split(`
864
- `).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function jRe(e){let t=await YR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:ARe(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})=>tz([{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 MRe(){if(m(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=gF(await DF()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await tz([{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 NRe(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-C7b2x2p_.js`),{isDeferredTool:c}=await import(`./prompt-B0gADAvI.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 nz(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=>nz([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 nz(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function PRe(e){return _s(e,us)}async function FRe(e,t,n){let r=await cbe(yn()),i=PRe(e);return i?{slashCommandTokens:await nz([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function IRe(e,t,n){try{let r=await lbe(yn()),i=PRe(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await nz([i],t,n),o=r.map(e=>({name:H3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:aSt(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return q(jn(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function LRe(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await nz(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>y3(V({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-C7b2x2p_.js`),{isDeferredTool:p}=await import(`./prompt-B0gADAvI.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 RRe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>tz([{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 zRe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=y3(V(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 BRe(e,t,n){if(typeof e.message.content==`string`){let n=y3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=y3(V(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 VRe(e,t){let n=y3(V(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function HRe(e){let t=await VR(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`?zRe(e,n):e.type===`user`?BRe(e,n,r):e.type===`attachment`&&VRe(e,n);return n.totalTokens=await tz(R4(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function URe(t,n,r,i,a,o,s,c,l){let u=Go({permissionMode:(await r()).mode,mainLoopModel:n}),d=ko(u,Yt()),f=await I7(i,u),p=QR({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([jRe(p),MRe(),NRe(i,r,a,u,t),LRe(i,r,a,u,t),RRe(a),FRe(i,r,a),HRe(t)]),A=(await IRe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=nG(),re=ne?$W(n)-iG: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:rz,tokens:oe,color:`inactive`})):ne||(oe=aG,ie.push({name:iz,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=bLe(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===rz||e.name===iz),_e=pe.filter(e=>e.name!==rz&&e.name!==iz&&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 xe=[];for(let e=0;e<de;e++)xe.push(he.slice(e*ue,(e+1)*ue));let Se=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,resultTokens:t})}let P=Array.from(Se.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:P,attachmentsByType:Ce};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:xe,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}=(kRe(),e(bRe)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var rz,iz,WRe=n((()=>{V7(),UR(),Wt(),e6(),ZR(),sG(),w3(),R3(),Ks(),Js(),V_(),W7(),jF(),ho(),vn(),W(),h(),On(),Qi(),m3(),No(),Yn(),$R(),CR(),rz=`Autocompact buffer`,iz=`Compact buffer`}));function az(e){let t=oz.get(e);if(t)return t;let n=See(e);return oz.set(e,n),n}var oz,sz=n((()=>{gt(),oz=new WeakMap}));function GRe(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(U(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function KRe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function cz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return gz;let t=GRe(e);return t===null?gz:t}function qRe(e){let t=ko(e,Uae(e)),n=cz()/100;return Math.floor(t*n)}function JRe(e){return Math.floor(qRe(e)*nze)}function lz(){if(m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?GRe(e):null;return t===0?`tst`:t===100?`standard`:KRe(e)?`tst-auto`:m(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function uz(){let e=lz();return e===`standard`?(_z||(_z=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(_z||(_z=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function dz(e){return e.some(e=>Ws(e,Vs))}async function YRe(e,t,n){let r=e.filter(e=>As(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?V(r.inputJSONSchema):r.inputSchema?V(az(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function fz(e,t,n,r,i){let a=hr(t,e=>e.isMcp);function o(t,n,r,i){J(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!dz(t))return U(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=lz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await tze(t,n,r,e);return a?(U(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(U(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),o(!1,s,`auto_below_threshold`,l),!1)}case`standard`:return o(!1,s,`standard_mode`),!1}}function pz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function XRe(e){return pz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function ZRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function QRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function $Re(e){let t=ize.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function mz(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(ZRe(n))for(let e of n.content)XRe(e)&&t.add(e.tool_name);if(QRe(n)){let e=$Re(n.content);for(let n of e)t.add(n)}}}return t.size>0&&U(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function hz(){return!1}function eze(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(As),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:(J(`tengu_deferred_tools_pool_change`,{addedCount:u.length,removedCount:d.length,priorAnnouncedCount:r.size,messagesLength:t.length,attachmentCount:i,dtdCount:a,callSite:n?.callSite??`unknown`,querySource:n?.querySource??`unknown`,attachmentTypesSeen:[...o].sort().join(`,`)}),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(pse).sort(),removedNames:d.sort()})}async function tze(e,t,n,r){let i=await rze(e,t,n,r);if(i!==null){let e=qRe(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${cz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await YRe(e,t,n),o=JRe(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${cz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var gz,nze,rze,_z,ize,vz=n((()=>{d(),Da(),Ks(),zs(),WRe(),Cr(),Uo(),ho(),W(),h(),Yn(),sz(),gz=10,nze=2.5,rze=u(async(e,t,n,r)=>{let i=e.filter(e=>As(e));if(i.length===0)return 0;try{let e=await nz(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>As(e)).map(e=>e.name).join(`,`)),_z=!1,ize=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function aze(e){return e.map(e=>e.name).sort().join(`,`)}function oze(e){let t=aze(e);Sz!==t&&(U(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Cz.cache.clear?.(),Sz=t)}function sze(){Cz.cache.clear?.(),Sz=null}function yz(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 cze(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 lze(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Ka(n)}\\b`));return t}async function uze(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=lze(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=cze(e.name),r=(await Cz(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=cze(e.name),r=(await Cz(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 dze,fze,bz,xz,Sz,Cz,wz,Tz=n((()=>{d(),gt(),Da(),Ks(),W(),_t(),Ja(),vz(),zs(),lFe(),dze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),fze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),bz=ht(()=>B({query:L().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:R().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),xz=ht(()=>B({matches:z(L()),query:L(),total_deferred_tools:R(),pending_mcp_servers:z(L()).optional(),already_loaded:z(L()).optional()})),Sz=null,Cz=u(async(e,t)=>{let n=_s(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),wz=Os({isEnabled(){return uz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Vs,maxResultSizeChars:1e5,async description(){return ase()},async prompt(){return ase()},get inputSchema(){return bz()},get outputSchema(){return xz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(As);oze(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){J(`tengu_search_extra_tools_outcome`,{query:r,queryType:t,matchCount:e.length,totalDeferredTools:a.length,maxResults:i,hasMatches:e.length>0})}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=_s(a,r),o=e??_s(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){U(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return yz([],r,a.length,e)}return l.length>0?U(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):U(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),yz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=JI(l[1].trim(),await YI(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(`
864
+ `).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function jRe(e){let t=await YR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:ARe(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})=>tz([{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 MRe(){if(m(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=gF(await DF()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await tz([{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 NRe(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-DIgC0CFB.js`),{isDeferredTool:c}=await import(`./prompt-CX_v9F3s.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 nz(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=>nz([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 nz(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function PRe(e){return _s(e,us)}async function FRe(e,t,n){let r=await cbe(yn()),i=PRe(e);return i?{slashCommandTokens:await nz([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function IRe(e,t,n){try{let r=await lbe(yn()),i=PRe(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await nz([i],t,n),o=r.map(e=>({name:H3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:aSt(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return q(jn(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function LRe(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await nz(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>y3(V({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-DIgC0CFB.js`),{isDeferredTool:p}=await import(`./prompt-CX_v9F3s.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 RRe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>tz([{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 zRe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=y3(V(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 BRe(e,t,n){if(typeof e.message.content==`string`){let n=y3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=y3(V(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 VRe(e,t){let n=y3(V(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function HRe(e){let t=await VR(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`?zRe(e,n):e.type===`user`?BRe(e,n,r):e.type===`attachment`&&VRe(e,n);return n.totalTokens=await tz(R4(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function URe(t,n,r,i,a,o,s,c,l){let u=Go({permissionMode:(await r()).mode,mainLoopModel:n}),d=ko(u,Yt()),f=await I7(i,u),p=QR({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([jRe(p),MRe(),NRe(i,r,a,u,t),LRe(i,r,a,u,t),RRe(a),FRe(i,r,a),HRe(t)]),A=(await IRe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=nG(),re=ne?$W(n)-iG: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:rz,tokens:oe,color:`inactive`})):ne||(oe=aG,ie.push({name:iz,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=bLe(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===rz||e.name===iz),_e=pe.filter(e=>e.name!==rz&&e.name!==iz&&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 xe=[];for(let e=0;e<de;e++)xe.push(he.slice(e*ue,(e+1)*ue));let Se=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,resultTokens:t})}let P=Array.from(Se.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:P,attachmentsByType:Ce};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:xe,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}=(kRe(),e(bRe)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var rz,iz,WRe=n((()=>{V7(),UR(),Wt(),e6(),ZR(),sG(),w3(),R3(),Ks(),Js(),V_(),W7(),jF(),ho(),vn(),W(),h(),On(),Qi(),m3(),No(),Yn(),$R(),CR(),rz=`Autocompact buffer`,iz=`Compact buffer`}));function az(e){let t=oz.get(e);if(t)return t;let n=See(e);return oz.set(e,n),n}var oz,sz=n((()=>{gt(),oz=new WeakMap}));function GRe(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(U(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function KRe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function cz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return gz;let t=GRe(e);return t===null?gz:t}function qRe(e){let t=ko(e,Uae(e)),n=cz()/100;return Math.floor(t*n)}function JRe(e){return Math.floor(qRe(e)*nze)}function lz(){if(m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?GRe(e):null;return t===0?`tst`:t===100?`standard`:KRe(e)?`tst-auto`:m(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function uz(){let e=lz();return e===`standard`?(_z||(_z=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(_z||(_z=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function dz(e){return e.some(e=>Ws(e,Vs))}async function YRe(e,t,n){let r=e.filter(e=>As(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?V(r.inputJSONSchema):r.inputSchema?V(az(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function fz(e,t,n,r,i){let a=hr(t,e=>e.isMcp);function o(t,n,r,i){J(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!dz(t))return U(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=lz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await tze(t,n,r,e);return a?(U(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(U(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),o(!1,s,`auto_below_threshold`,l),!1)}case`standard`:return o(!1,s,`standard_mode`),!1}}function pz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function XRe(e){return pz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function ZRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function QRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function $Re(e){let t=ize.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function mz(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(ZRe(n))for(let e of n.content)XRe(e)&&t.add(e.tool_name);if(QRe(n)){let e=$Re(n.content);for(let n of e)t.add(n)}}}return t.size>0&&U(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function hz(){return!1}function eze(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(As),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:(J(`tengu_deferred_tools_pool_change`,{addedCount:u.length,removedCount:d.length,priorAnnouncedCount:r.size,messagesLength:t.length,attachmentCount:i,dtdCount:a,callSite:n?.callSite??`unknown`,querySource:n?.querySource??`unknown`,attachmentTypesSeen:[...o].sort().join(`,`)}),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(pse).sort(),removedNames:d.sort()})}async function tze(e,t,n,r){let i=await rze(e,t,n,r);if(i!==null){let e=qRe(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${cz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await YRe(e,t,n),o=JRe(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${cz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var gz,nze,rze,_z,ize,vz=n((()=>{d(),Da(),Ks(),zs(),WRe(),Cr(),Uo(),ho(),W(),h(),Yn(),sz(),gz=10,nze=2.5,rze=u(async(e,t,n,r)=>{let i=e.filter(e=>As(e));if(i.length===0)return 0;try{let e=await nz(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>As(e)).map(e=>e.name).join(`,`)),_z=!1,ize=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function aze(e){return e.map(e=>e.name).sort().join(`,`)}function oze(e){let t=aze(e);Sz!==t&&(U(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Cz.cache.clear?.(),Sz=t)}function sze(){Cz.cache.clear?.(),Sz=null}function yz(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 cze(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 lze(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Ka(n)}\\b`));return t}async function uze(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=lze(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=cze(e.name),r=(await Cz(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=cze(e.name),r=(await Cz(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 dze,fze,bz,xz,Sz,Cz,wz,Tz=n((()=>{d(),gt(),Da(),Ks(),W(),_t(),Ja(),vz(),zs(),lFe(),dze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),fze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),bz=ht(()=>B({query:L().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:R().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),xz=ht(()=>B({matches:z(L()),query:L(),total_deferred_tools:R(),pending_mcp_servers:z(L()).optional(),already_loaded:z(L()).optional()})),Sz=null,Cz=u(async(e,t)=>{let n=_s(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),wz=Os({isEnabled(){return uz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Vs,maxResultSizeChars:1e5,async description(){return ase()},async prompt(){return ase()},get inputSchema(){return bz()},get outputSchema(){return xz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(As);oze(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){J(`tengu_search_extra_tools_outcome`,{query:r,queryType:t,matchCount:e.length,totalDeferredTools:a.length,maxResults:i,hasMatches:e.length>0})}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=_s(a,r),o=e??_s(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){U(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return yz([],r,a.length,e)}return l.length>0?U(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):U(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),yz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=JI(l[1].trim(),await YI(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(`
865
865
 
866
866
  `)}`,s(e.map(e=>e.name),`keyword`),yz(e.map(e=>e.name),r,a.length)}let u=new Set(a.map(e=>e.name)),[d,f]=await Promise.all([uze(r,a,t,i),YI(a)]),p=JI(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*dze)}),p.forEach(e=>{m.set(e.name,(m.get(e.name)??0)+e.score*fze)});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(U(`SearchExtraToolsTool: keyword search for "${r}", found ${h.length} matches`),s(h,`keyword`),h.length===0){let e=o();return yz(h,r,a.length,e)}return yz(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(`
867
867
  `)}}})}));function pze(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)}}),R4(e).forEach(e=>{let{content:a}=e.message;if(typeof a==`string`){let n=y3(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=>mze(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 mze(e,t,n,r,i,a){let o=y3(V(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(hze(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(hze(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 hze(e,t,n){e.set(t,(e.get(t)||0)+n)}function gze(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 _ze=n((()=>{w3(),m3(),Yn()})),vze,yze=n((()=>{vze=[`User`,`Project`,`Local`,`Managed`,`AutoMem`]}));function bze(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 Ez(){Az.cache?.clear?.()}async function xze(){if(!an())return;let{enabled:e}=await u4(),t=new Set(e.map(e=>e.path)),n=an();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)}Nte(),vt(r)}function Dz(){let e=zr(),t=Ir(`policySettings`),n=e=>e?Object.fromEntries(Object.entries(e).sort()):{};return V({enabledPlugins:n(e.enabledPlugins),extraKnownMarketplaces:n(e.extraKnownMarketplaces),strictKnownMarketplaces:t?.strictKnownMarketplaces??[],blockedMarketplaces:t?.blockedMarketplaces??[]})}function Sze(){Oz||(Oz=!0,kz=Dz(),lg.subscribe(e=>{if(e===`policySettings`){let e=Dz();if(e===kz){U(`Plugin hooks: skipping reload, plugin-affecting settings unchanged`);return}kz=e,U(`Plugin hooks: reloading due to plugin-affecting settings change`),c4(`loadPluginHooks: plugin-affecting settings changed`),Ez(),Az()}}))}var Oz,kz,Az,jz=n((()=>{d(),Wt(),W(),ug(),Vr(),Yn(),d4(),Oz=!1,Az=u(async()=>{let{enabled:e}=await u4(),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;U(`Loading hooks from plugin: ${n.name}`);let e=bze(n);for(let n of Object.keys(e))t[n].push(...e[n])}Nte(),vt(t),U(`Registered ${Object.values(t).reduce((e,t)=>e+t.reduce((e,t)=>e+t.hooks.length,0),0)} hooks from ${e.length} plugins`)})}));function Cze(){let e=Nz;return Nz=void 0,e}async function Mz(e,{sessionId:t,agentType:n,model:r,forceSyncExecution:i}={}){if(v())return[];let a=[],o=[],s=[];if(Uv())U(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await die(`load_plugin_hooks`,()=>Az())}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),q(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.`,U(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${r}. ${i}`,{level:`warn`})}let c=n??vte();for await(let n of _Et(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&&(Nz=n.initialUserMessage),n.watchPaths&&n.watchPaths.length>0&&s.push(...n.watchPaths);if(s.length>0&&fxe(s),o.length>0){let e=j0({type:`hook_additional_context`,content:o,hookName:`SessionStart`,toolUseID:`SessionStart`,hookEvent:`SessionStart`});a.push(e)}return a}async function wze(e,{forceSyncExecution:t}={}){if(v())return[];let n=[],r=[];if(Uv())U(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await Az()}catch(e){U(`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 vEt(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=j0({type:`hook_additional_context`,content:r,hookName:`Setup`,toolUseID:`Setup`,hookEvent:`Setup`});n.push(e)}return n}var Nz,Pz=n((()=>{Wt(),H0(),W(),Ei(),h(),ry(),Jv(),_7(),Qi(),jz()}));async function Tze(e,t){}var Eze=n((()=>{}));function Dze(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 Oze=n((()=>{}));function kze(e,t=`from`){let n=Iz+(t===`up_to`?Fze:Pze);return e&&e.trim()!==``&&(n+=`\n\nAdditional Instructions:\n${e}`),n+=Rz,n}function Aze(e){let t=Iz+Nze;return e&&e.trim()!==``&&(t+=`\n\nAdditional Instructions:\n${e}`),t+=Rz,t}function jze(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,`
@@ -1160,7 +1160,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
1160
1160
  `),`utf8`)),p=Oqe(s,a,f),m=a.length),p!==-1)return await Aqe(e,s,c-u+p,m,n,l+dH(s,0,p));c+=d;let h=Math.min(o,f);l+=dH(s,0,f-h),u=h,s.copyWithin(0,f-u,f)}return{content:``,lineOffset:1,truncated:c>=pH}}async function Dqe(e){let t=Buffer.allocUnsafe(fH),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 kqe(t,n)}function Oqe(e,t,n){let r=e.indexOf(t);return r===-1||r+t.length>n?-1:r}function dH(e,t,n){let r=0;for(let i=t;i<n;i++)e[i]===mH&&r++;return r}function kqe(e,t){let n=e.toString(`utf8`,0,t);return n.includes(`\r`)?n.replaceAll(`\r
1161
1161
  `,`
1162
1162
  `):n}async function Aqe(e,t,n,r,i,a){let o=Math.min(n,fH),{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]===mH&&(l++,l>i));e--)c--;let u=a-dH(t,s-(n-c),s)+1,d=n+r,{bytesRead:f}=await e.read(t,0,fH,d),p=d;l=0;for(let e=0;e<f&&(p++,!(t[e]===mH&&(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:kqe(h,g),lineOffset:u,truncated:!1}}var fH,pH,mH,hH=n((()=>{On(),fH=8*1024,pH=10*1024*1024,mH=10}));function jqe(e){return e?e.file_path?.startsWith(df())?`Updated plan`:e.edits==null&&e.old_string===``?`Create`:`Update`:`Update`}function Mqe(e){return e?.file_path?ui(e.file_path):null}function Nqe({file_path:e},{verbose:t}){return e?e.startsWith(df())?``:(0,_H.jsx)(qb,{filePath:e,children:t?e:ui(e)}):null}function Pqe({filePath:e,structuredPatch:t,originalFile:n},r,{style:i,verbose:a}){let o=e.startsWith(df());return(0,_H.jsx)(Cqe,{filePath:e,structuredPatch:t,firstLine:n.split(`
1163
- `)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function Fqe(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,_H.jsx)(oH,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,_H.jsx)(oH,{file_path:i,operation:`write`,content:o,firstLine:Wa(o),verbose:r}):(0,_H.jsx)(Lqe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function Iqe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&M4(e,`tool_use_error`)?M4(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,_H.jsx)(Z,{children:(0,_H.jsx)(F,{color:`error`,children:`File not found`})}):(0,_H.jsx)(Z,{children:(0,_H.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,_H.jsx)(Ub,{result:e,verbose:n})}function Lqe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,gH.useState)(()=>zqe(e,t,n,r));return(0,_H.jsx)(gH.Suspense,{fallback:(0,_H.jsx)(oH,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,_H.jsx)(Rqe,{promise:o,filePath:e,style:i,verbose:a})})}function Rqe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,gH.use)(e);return(0,_H.jsx)(oH,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function zqe(e,t,n,r){try{let i=await Tqe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=II({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=FI(i.content,t)||t,{patch:o}=II({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:wI(o,i.lineOffset-1),firstLine:i.lineOffset===1?Wa(i.content):null,fileContent:i.content}}catch(e){return q(e),{patch:[],firstLine:null,fileContent:void 0}}}var gH,_H,Bqe=n((()=>{gH=r(ze(),1),Sqe(),Rb(),m3(),Kb(),wqe(),I(),Jb(),NI(),ci(),Qi(),ff(),hH(),Ja(),zI(),_H=et()}));function vH(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Vqe(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 Hqe(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Vqe(t[0]):null}function Uqe(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Wqe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Gqe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function Kqe(e,t){let n=e.split(vH(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function qqe(e,t){let n={},r=Yqe.test(e);if(yH.test(e)||r){let i=Uqe(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(bH.test(e)){let e=Wqe(t);e&&(n.push={branch:e})}if(Xqe.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=Kqe(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(Zqe.test(e)&&/Successfully rebased/.test(t)){let t=Kqe(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=xH.find(t=>t.re.test(e))?.action;if(i){let e=Hqe(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Gqe(t);e&&(n.pr={number:e,action:i})}}return n}function Jqe(e,t,n){if(t!==0)return;yH.test(e)&&(J(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&J(`tengu_git_operation`,{operation:`commit_amend`}),ote()?.add(1)),bH.test(e)&&J(`tengu_git_operation`,{operation:`push`});let r=xH.find(t=>t.re.test(e));if(r&&J(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(un()?.add(1),n)){let e=Hqe(n);e&&import(`./sessionStorage-BeaEgnaa.js`).then(({linkSessionToPR:t})=>{import(`./state-CsdHk8n-.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(J(`tengu_git_operation`,{operation:`pr_create`}),un()?.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&&(J(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1))}var yH,bH,Yqe,Xqe,Zqe,xH,SH=n((()=>{Wt(),Da(),yH=vH(`commit`),bH=vH(`push`),Yqe=vH(`cherry-pick`),Xqe=vH(`merge`,`(?!-)`),Zqe=vH(`rebase`),xH=[{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 Qqe(e){let t=eJe(e),n=rJe.get(t);return n===void 0?nJe:n}function $qe(e){return e.trim().split(/\s+/)[0]||``}function eJe(e){let t=a9(e);return $qe(t[t.length-1]||e)}function tJe(e,t,n,r){let i=Qqe(e)(t,n,r);return{isError:i.isError,message:i.message}}var nJe,rJe,iJe=n((()=>{g9(),nJe=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),rJe=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})]])}));function aJe(){return Fi(yn())??Xt()}function oJe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function sJe(){return{fileStates:new Map,sessionBaselines:new Map,surface:oJe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function cJe(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(cJe(n,bl())),n}var uJe,CH,wH=n((()=>{Wt(),vn(),W(),zi(),Bn(),Di(),Mi(),Qi(),No(),$a(),uJe=`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(`,`),CH=null,Fae(async()=>{if(CH!==null)return CH===`internal`;let e=await Sie(aJe());if(!e)return CH=`none`,!1;let t=uJe.some(t=>e.includes(t));return CH=t?`internal`:`external`,t})}));function dJe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of fJe)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var fJe,pJe=n((()=>{fJe=[{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 mJe(e){switch(Vo()){case`openai`:return Rse(e);case`gemini`:return Kse(e);case`grok`:return Lse(e);default:return e}}function hJe(){return mJe(Qo())}var gJe=n((()=>{ec(),No(),Jo()})),TH,EH,DH,_Je,OH=n((()=>{gt(),_t(),nV(),TH=ht(()=>ut({file_path:L().describe(`The absolute path to the file to modify`),old_string:L().describe(`The text to replace`),new_string:L().describe(`The text to replace it with (must be different from old_string)`),replace_all:tV(ft().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),EH=ht(()=>B({oldStart:R(),oldLines:R(),newStart:R(),newLines:R(),lines:z(L())})),DH=ht(()=>B({filename:L(),status:dt([`modified`,`added`]),additions:R(),deletions:R(),changes:R(),patch:L(),repository:L().nullable().optional().describe(`GitHub owner/repo when available`)})),_Je=ht(()=>B({filePath:L().describe(`The file path that was edited`),oldString:L().describe(`The original string that was replaced`),newString:L().describe(`The new string that replaced it`),originalFile:L().describe(`The original file contents before editing`),structuredPatch:z(EH()).describe(`Diff patch showing the changes`),userModified:ft().describe(`Whether the user modified the proposed changes`),replaceAll:ft().describe(`Whether all occurrences were replaced`),gitDiff:DH().optional()}))}));function vJe({serverName:e,files:t}){let n=bl();U(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),jH.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function yJe(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function bJe(e){return V({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function xJe(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=MH.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=bJe(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=jn(e),a=t.message?.substring(0,100)||`<no message>`;q(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 SJe(){U(`LSP Diagnostics: Checking registry - ${jH.size} pending`);let e=[],t=new Set,n=[];for(let r of jH.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=xJe(e)}catch(t){let n=jn(t);q(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of jH)t.attachmentSent&&jH.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&&U(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>yJe(e.severity)-yJe(t.severity)),e.diagnostics.length>kH&&(s+=e.diagnostics.length-kH,e.diagnostics=e.diagnostics.slice(0,kH));let t=AH-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&&U(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${kH}/file, ${AH} total)`);for(let e of r){MH.has(e.uri)||MH.set(e.uri,new Set);let t=MH.get(e.uri);for(let n of e.diagnostics)try{t.add(bJe(n))}catch(t){let r=jn(t),i=n.message?.substring(0,100)||`<no message>`;q(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?(U(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(U(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function CJe(){U(`LSP Diagnostics: Clearing ${jH.size} pending diagnostic(s)`),jH.clear()}function wJe(){U(`LSP Diagnostics: Resetting all state (${jH.size} pending, ${MH.size} files tracked)`),jH.clear(),MH.clear()}function TJe(e){MH.has(e)&&(U(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),MH.delete(e))}var kH,AH,EJe,jH,MH,NH=n((()=>{ra(),W(),On(),Qi(),Yn(),kH=10,AH=30,EJe=500,jH=new Map,MH=new ia({max:EJe})}));function DJe(e,t){let n=el(e),r=el(e,t),i=$c(n,r);return i.startsWith(`..`)||el(i)===i?null:r}async function OJe(e,t=[]){let n={},r=Y(e.path,`.lsp.json`);try{let i=kn(await Ol(r,`utf-8`)),a=rt(L(),Br()).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}`;q(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){xn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,q(jn(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 kJe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function kJe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=DJe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;q(Error(t)),U(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=kn(await Ol(a,`utf-8`)),o=rt(L(),Br()).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}`;q(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}`,q(jn(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=Br().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}`;q(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 AJe(e,t,n,r){let i=[],a=e=>{let r=rT(e,t);n&&(r=iT(r,n));let{expanded:a,missingVars:o}=Hw(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:F_(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(`, `)}`;q(Error(e)),U(e,{level:`warn`})}return o}function jJe(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 MJe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await OJe(e,t);if(!n)return;let r=e.manifest.userConfig?aT(tT(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=AJe(o,e,r,t);return jJe(i,e.name)}var NJe=n((()=>{gt(),Uw(),W(),On(),Qi(),Yn(),I_(),oT(),si()}));async function PJe(){let e={};try{let{enabled:t}=await u4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await MJe(e,t),errors:t}}catch(n){return U(`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),U(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&U(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}U(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){q(jn(e)),U(`Error loading LSP servers: ${H(e)}`)}return{servers:e}}var FJe=n((()=>{W(),On(),Qi(),NJe(),d4()})),PH=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})),IJe=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=PH(),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={}))})),LJe=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))}}})),RJe=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={}))})),FH=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})),IH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=FH(),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(){}})),LH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=FH(),n=PH(),r=IH(),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}}})),zJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=LH(),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)}}})),BJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=FH();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()}}}})),VJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=FH(),n=PH(),r=IH(),i=BJe(),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))}}})),HJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=FH(),n=PH(),r=BJe(),i=IH(),a=`Content-Length: `,o=`\r
1163
+ `)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function Fqe(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,_H.jsx)(oH,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,_H.jsx)(oH,{file_path:i,operation:`write`,content:o,firstLine:Wa(o),verbose:r}):(0,_H.jsx)(Lqe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function Iqe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&M4(e,`tool_use_error`)?M4(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,_H.jsx)(Z,{children:(0,_H.jsx)(F,{color:`error`,children:`File not found`})}):(0,_H.jsx)(Z,{children:(0,_H.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,_H.jsx)(Ub,{result:e,verbose:n})}function Lqe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,gH.useState)(()=>zqe(e,t,n,r));return(0,_H.jsx)(gH.Suspense,{fallback:(0,_H.jsx)(oH,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,_H.jsx)(Rqe,{promise:o,filePath:e,style:i,verbose:a})})}function Rqe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,gH.use)(e);return(0,_H.jsx)(oH,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function zqe(e,t,n,r){try{let i=await Tqe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=II({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=FI(i.content,t)||t,{patch:o}=II({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:wI(o,i.lineOffset-1),firstLine:i.lineOffset===1?Wa(i.content):null,fileContent:i.content}}catch(e){return q(e),{patch:[],firstLine:null,fileContent:void 0}}}var gH,_H,Bqe=n((()=>{gH=r(ze(),1),Sqe(),Rb(),m3(),Kb(),wqe(),I(),Jb(),NI(),ci(),Qi(),ff(),hH(),Ja(),zI(),_H=et()}));function vH(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Vqe(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 Hqe(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Vqe(t[0]):null}function Uqe(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Wqe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Gqe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function Kqe(e,t){let n=e.split(vH(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function qqe(e,t){let n={},r=Yqe.test(e);if(yH.test(e)||r){let i=Uqe(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(bH.test(e)){let e=Wqe(t);e&&(n.push={branch:e})}if(Xqe.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=Kqe(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(Zqe.test(e)&&/Successfully rebased/.test(t)){let t=Kqe(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=xH.find(t=>t.re.test(e))?.action;if(i){let e=Hqe(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Gqe(t);e&&(n.pr={number:e,action:i})}}return n}function Jqe(e,t,n){if(t!==0)return;yH.test(e)&&(J(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&J(`tengu_git_operation`,{operation:`commit_amend`}),ote()?.add(1)),bH.test(e)&&J(`tengu_git_operation`,{operation:`push`});let r=xH.find(t=>t.re.test(e));if(r&&J(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(un()?.add(1),n)){let e=Hqe(n);e&&import(`./sessionStorage-LMY409Ji.js`).then(({linkSessionToPR:t})=>{import(`./state-CsdHk8n-.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(J(`tengu_git_operation`,{operation:`pr_create`}),un()?.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&&(J(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1))}var yH,bH,Yqe,Xqe,Zqe,xH,SH=n((()=>{Wt(),Da(),yH=vH(`commit`),bH=vH(`push`),Yqe=vH(`cherry-pick`),Xqe=vH(`merge`,`(?!-)`),Zqe=vH(`rebase`),xH=[{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 Qqe(e){let t=eJe(e),n=rJe.get(t);return n===void 0?nJe:n}function $qe(e){return e.trim().split(/\s+/)[0]||``}function eJe(e){let t=a9(e);return $qe(t[t.length-1]||e)}function tJe(e,t,n,r){let i=Qqe(e)(t,n,r);return{isError:i.isError,message:i.message}}var nJe,rJe,iJe=n((()=>{g9(),nJe=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),rJe=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})]])}));function aJe(){return Fi(yn())??Xt()}function oJe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function sJe(){return{fileStates:new Map,sessionBaselines:new Map,surface:oJe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function cJe(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(cJe(n,bl())),n}var uJe,CH,wH=n((()=>{Wt(),vn(),W(),zi(),Bn(),Di(),Mi(),Qi(),No(),$a(),uJe=`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(`,`),CH=null,Fae(async()=>{if(CH!==null)return CH===`internal`;let e=await Sie(aJe());if(!e)return CH=`none`,!1;let t=uJe.some(t=>e.includes(t));return CH=t?`internal`:`external`,t})}));function dJe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of fJe)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var fJe,pJe=n((()=>{fJe=[{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 mJe(e){switch(Vo()){case`openai`:return Rse(e);case`gemini`:return Kse(e);case`grok`:return Lse(e);default:return e}}function hJe(){return mJe(Qo())}var gJe=n((()=>{ec(),No(),Jo()})),TH,EH,DH,_Je,OH=n((()=>{gt(),_t(),nV(),TH=ht(()=>ut({file_path:L().describe(`The absolute path to the file to modify`),old_string:L().describe(`The text to replace`),new_string:L().describe(`The text to replace it with (must be different from old_string)`),replace_all:tV(ft().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),EH=ht(()=>B({oldStart:R(),oldLines:R(),newStart:R(),newLines:R(),lines:z(L())})),DH=ht(()=>B({filename:L(),status:dt([`modified`,`added`]),additions:R(),deletions:R(),changes:R(),patch:L(),repository:L().nullable().optional().describe(`GitHub owner/repo when available`)})),_Je=ht(()=>B({filePath:L().describe(`The file path that was edited`),oldString:L().describe(`The original string that was replaced`),newString:L().describe(`The new string that replaced it`),originalFile:L().describe(`The original file contents before editing`),structuredPatch:z(EH()).describe(`Diff patch showing the changes`),userModified:ft().describe(`Whether the user modified the proposed changes`),replaceAll:ft().describe(`Whether all occurrences were replaced`),gitDiff:DH().optional()}))}));function vJe({serverName:e,files:t}){let n=bl();U(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),jH.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function yJe(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function bJe(e){return V({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function xJe(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=MH.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=bJe(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=jn(e),a=t.message?.substring(0,100)||`<no message>`;q(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 SJe(){U(`LSP Diagnostics: Checking registry - ${jH.size} pending`);let e=[],t=new Set,n=[];for(let r of jH.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=xJe(e)}catch(t){let n=jn(t);q(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of jH)t.attachmentSent&&jH.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&&U(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>yJe(e.severity)-yJe(t.severity)),e.diagnostics.length>kH&&(s+=e.diagnostics.length-kH,e.diagnostics=e.diagnostics.slice(0,kH));let t=AH-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&&U(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${kH}/file, ${AH} total)`);for(let e of r){MH.has(e.uri)||MH.set(e.uri,new Set);let t=MH.get(e.uri);for(let n of e.diagnostics)try{t.add(bJe(n))}catch(t){let r=jn(t),i=n.message?.substring(0,100)||`<no message>`;q(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?(U(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(U(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function CJe(){U(`LSP Diagnostics: Clearing ${jH.size} pending diagnostic(s)`),jH.clear()}function wJe(){U(`LSP Diagnostics: Resetting all state (${jH.size} pending, ${MH.size} files tracked)`),jH.clear(),MH.clear()}function TJe(e){MH.has(e)&&(U(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),MH.delete(e))}var kH,AH,EJe,jH,MH,NH=n((()=>{ra(),W(),On(),Qi(),Yn(),kH=10,AH=30,EJe=500,jH=new Map,MH=new ia({max:EJe})}));function DJe(e,t){let n=el(e),r=el(e,t),i=$c(n,r);return i.startsWith(`..`)||el(i)===i?null:r}async function OJe(e,t=[]){let n={},r=Y(e.path,`.lsp.json`);try{let i=kn(await Ol(r,`utf-8`)),a=rt(L(),Br()).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}`;q(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){xn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,q(jn(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 kJe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function kJe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=DJe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;q(Error(t)),U(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=kn(await Ol(a,`utf-8`)),o=rt(L(),Br()).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}`;q(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}`,q(jn(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=Br().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}`;q(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 AJe(e,t,n,r){let i=[],a=e=>{let r=rT(e,t);n&&(r=iT(r,n));let{expanded:a,missingVars:o}=Hw(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:F_(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(`, `)}`;q(Error(e)),U(e,{level:`warn`})}return o}function jJe(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 MJe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await OJe(e,t);if(!n)return;let r=e.manifest.userConfig?aT(tT(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=AJe(o,e,r,t);return jJe(i,e.name)}var NJe=n((()=>{gt(),Uw(),W(),On(),Qi(),Yn(),I_(),oT(),si()}));async function PJe(){let e={};try{let{enabled:t}=await u4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await MJe(e,t),errors:t}}catch(n){return U(`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),U(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&U(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}U(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){q(jn(e)),U(`Error loading LSP servers: ${H(e)}`)}return{servers:e}}var FJe=n((()=>{W(),On(),Qi(),NJe(),d4()})),PH=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})),IJe=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=PH(),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={}))})),LJe=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))}}})),RJe=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={}))})),FH=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})),IH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=FH(),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(){}})),LH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=FH(),n=PH(),r=IH(),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}}})),zJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=LH(),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)}}})),BJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=FH();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()}}}})),VJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=FH(),n=PH(),r=IH(),i=BJe(),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))}}})),HJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=FH(),n=PH(),r=BJe(),i=IH(),a=`Content-Length: `,o=`\r
1164
1164
  `,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()}}})),UJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractMessageBuffer=void 0;var t=13,n=10,r=`\r
1165
1165
  `;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}}})),WJe=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=FH(),n=PH(),r=IJe(),i=LJe(),a=IH(),o=LH(),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 xe(){return N===E.Closed}function Se(){return N===E.Disposed}function P(){(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(P),f.onError(Ce),v.onClose(P),v.onError(we);function Te(){re||ie.size===0||(re=(0,t.default)().timer.setImmediate(()=>{re=void 0,F()}))}function Ee(e){r.Message.isRequest(e)?Oe(e):r.Message.isNotification(e)?Ae(e):r.Message.isResponse(e)?ke(e):je(e)}function F(){if(ie.size===0)return;let e=ie.shift();try{let t=x?.messageStrategy;w.is(t)?t.handleMessage(e,Ee):Ee(e)}finally{Te()}}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{Te()}};function Oe(e){if(Se())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(!Se())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(eee(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(Se())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 Re(`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.
1166
1166
 
@@ -1578,7 +1578,7 @@ Good: "Adding retry logic to fetchUser"
1578
1578
  Bad (past tense): "Analyzed the branch diff"
1579
1579
  Bad (too vague): "Investigating the issue"
1580
1580
  Bad (too long): "Reviewing full branch diff and AgentTool.tsx integration"
1581
- Bad (branch name): "Analyzed adam/background-summary branch diff"`}function t2e(e){return{type:`user`,message:{role:`user`,content:e},uuid:cue(),timestamp:new Date().toISOString()}}var n2e=n((()=>{}));function HG(e,t,n,r,i={}){let{forkContextMessages:a,...o}=n,s=null,c=null,l=!1,u=null,d=null,f=i.clearTimeout??clearTimeout,p=i.getAgentTranscript??X6,m=i.isPoorModeActive??Qce,h=i.logError??q,g=i.logForDebugging??U,_=i.runForkedAgent??I1,v=i.setTimeout??setTimeout,y=i.updateAgentSummary??Mht;async function b(){if(!l){if(m()){g(`[AgentSummary] Skipping summary — poor mode active`),x();return}g(`[AgentSummary] Timer fired for agent ${t}`);try{let n=await p(t);if(!n||n.messages.length<3){g(`[AgentSummary] Skipping summary for ${e}: not enough messages (${n?.messages.length??0})`);return}let i=Z0e(n.messages,d);if(i.skipReason===`unchanged`){g(`[AgentSummary] Skipping summary for ${e}: transcript unchanged`);return}if(i.skipReason===`too_small`){g(`[AgentSummary] Skipping summary for ${e}: no bounded context available`);return}let a={...o,forkContextMessages:i.messages};g(`[AgentSummary] Forking for summary, ${i.messages.length} messages in context`),s=new AbortController;let c=await _({promptMessages:[t2e(e2e(u))],cacheSafeParams:a,canUseTool:async()=>({behavior:`deny`,message:`No tools needed for summary`,decisionReason:{type:`other`,reason:`summary only`}}),querySource:`agent_summary`,forkLabel:`agent_summary`,overrides:{abortController:s},skipTranscript:!0});if(l)return;for(let t of c.messages){if(t.type!==`assistant`)continue;if(t.isApiErrorMessage){U(`[AgentSummary] Skipping API error message for ${e}`);continue}let n=(Array.isArray(t.message.content)?t.message.content:[]).find(e=>e.type===`text`);if(n?.type===`text`&&n.text.trim()){let t=n.text.trim();g(`[AgentSummary] Summary result for ${e}: ${t}`),d=i.fingerprint,u=t,y(e,t,r);break}}}catch(e){!l&&e instanceof Error&&h(e)}finally{s=null,l||x()}}}function x(){l||(c=v(b,r2e))}function S(){g(`[AgentSummary] Stopping summarization for ${e}`),l=!0,c&&(f(c),c=null),s&&(s.abort(),s=null)}return x(),{stop:S}}var r2e,i2e=n((()=>{Lc(),p0(),W(),R1(),Qi(),h8(),$0e(),n2e(),r2e=3e4}));function a2e(){}var UG=n((()=>{Wt(),h()}));function o2e(e){return e.filter(e=>!ys.has(e.name))}var s2e=n((()=>{Cs()}));function c2e(){return`inherit`}function l2e(e,t,n,r){if(process.env.CLAUDE_CODE_SUBAGENT_MODEL)return ro(process.env.CLAUDE_CODE_SUBAGENT_MODEL);let i=kae(t),a=(e,t)=>i&&Vo()===`bedrock`?kae(t)?e:Qae(e,i):e;if(n)return u2e(n,t)?t:a(ro(n),n);let o=e??c2e();return o===`inherit`?Go({permissionMode:r??`default`,mainLoopModel:t,exceeds200kTokens:!1}):u2e(o,t)?t:a(ro(o),o)}function u2e(e,t){let n=Yo(t);switch(e.toLowerCase()){case`opus`:return n.includes(`opus`);case`sonnet`:return n.includes(`sonnet`);case`haiku`:return n.includes(`haiku`);default:return!1}}function d2e(e){return e?e===`inherit`?`Inherit from parent`:cae(e):`Inherit from parent (default)`}function f2e(){return[{value:`sonnet`,label:`Sonnet`,description:`Balanced performance - best for most agents`},{value:`opus`,label:`Opus`,description:`Most capable for complex reasoning tasks`},{value:`haiku`,label:`Haiku`,description:`Fast and efficient for simple tasks`},{value:`inherit`,label:`Inherit from parent`,description:`Use the same model as the main conversation`}]}var WG=n((()=>{Ja(),oo(),Mo(),No(),Jo(),[...Sae]}));function p2e(e){return typeof e==`string`&&m2e.test(e)?e:null}function GG(e){let t=yl(8).toString(`hex`);return e?`a${e}-${t}`:`a${t}`}var m2e,KG=n((()=>{m2e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i}));function qG(e){if(e===`general-purpose`)return;let t=bte().get(e);if(t&&YG.includes(t))return XG[t]}function JG(e,t){let n=bte();if(!t){n.delete(e);return}YG.includes(t)&&n.set(e,t)}var YG,XG,ZG=n((()=>{Wt(),YG=[`red`,`blue`,`green`,`yellow`,`purple`,`orange`,`pink`,`cyan`],XG={red:`red_FOR_SUBAGENTS_ONLY`,blue:`blue_FOR_SUBAGENTS_ONLY`,green:`green_FOR_SUBAGENTS_ONLY`,yellow:`yellow_FOR_SUBAGENTS_ONLY`,purple:`purple_FOR_SUBAGENTS_ONLY`,orange:`orange_FOR_SUBAGENTS_ONLY`,pink:`pink_FOR_SUBAGENTS_ONLY`,cyan:`cyan_FOR_SUBAGENTS_ONLY`}}));function h2e(e,t){let n=e.find(e=>e.type===`tool_use`&&e.name===t);return n?.type===`tool_use`?n:null}function g2e(e,t){let n=t.safeParse(e.input);return n.success?n.data:null}var _2e=n((()=>{})),v2e=i({default:()=>y2e}),y2e,b2e=n((()=>{y2e=`/assets/auto_mode_system_prompt-BOUkwTgh.txt`})),x2e=i({default:()=>S2e}),S2e,C2e=n((()=>{S2e=`data:text/plain;base64,IyMgQWxsb3cgUnVsZXMKClRoZSBmb2xsb3dpbmcgdHlwZXMgb2YgYWN0aW9ucyBzaG91bGQgYmUgYXV0by1hcHByb3ZlZDoKCjx1c2VyX2FsbG93X3J1bGVzX3RvX3JlcGxhY2U+Ci0gUnVubmluZyByZWFkLW9ubHkgc2hlbGwgY29tbWFuZHMgKGxzLCBjYXQsIGhlYWQsIHRhaWwsIHdjLCBlY2hvLCBlbnYsIHdoaWNoLCB3aGVyZWlzLCB1bmFtZSwgZGF0ZSwgd2hvYW1pLCBwd2QsIHN0YXQsIGZpbGUsIGR1LCBkZiwgZnJlZSwgdG9wIC1iIC1uIDEsIHBzKQotIFJ1bm5pbmcgdmVyc2lvbiBhbmQgaGVscCBjb21tYW5kcyAobm9kZSAtLXZlcnNpb24sIHB5dGhvbiAtLXZlcnNpb24sIHJ1YnkgLS12ZXJzaW9uLCBnbyB2ZXJzaW9uLCBydXN0YyAtLXZlcnNpb24sIGNhcmdvIC0tdmVyc2lvbiwgbnBtIC0tdmVyc2lvbiwgYnVuIC0tdmVyc2lvbiwgZ2l0IC0tdmVyc2lvbiwgLS1oZWxwIGZsYWdzKQotIFJ1bm5pbmcgZ2l0IHJlYWQtb25seSBjb21tYW5kcyAoZ2l0IHN0YXR1cywgZ2l0IGxvZywgZ2l0IGRpZmYsIGdpdCBzaG93LCBnaXQgYnJhbmNoLCBnaXQgdGFnLCBnaXQgcmVtb3RlLCBnaXQgc3Rhc2ggbGlzdCwgZ2l0IGNvbmZpZyAtLWxpc3QgLS1sb2NhbCkKLSBSdW5uaW5nIHRlc3RzLCBsaW50ZXJzLCBmb3JtYXR0ZXJzLCBhbmQgYnVpbGQgY29tbWFuZHMgd2l0aGluIHRoZSBwcm9qZWN0IChucG0gdGVzdCwgbnBtIHJ1biBsaW50LCBucG0gcnVuIGJ1aWxkLCBidW4gdGVzdCwgY2FyZ28gdGVzdCwgZ28gdGVzdCwgcHl0ZXN0LCBqZXN0LCB2aXRlc3QsIGVzbGludCwgcHJldHRpZXIsIGJpb21lLCB0c2MpCi0gUnVubmluZyBwYWNrYWdlIGluc3RhbGwgY29tbWFuZHMgd2l0aGluIHRoZSBwcm9qZWN0IChucG0gaW5zdGFsbCwgeWFybiwgcG5wbSBpbnN0YWxsLCBidW4gaW5zdGFsbCwgcGlwIGluc3RhbGwgd2l0aGluIGEgdmlydHVhbCBlbnZpcm9ubWVudCwgY2FyZ28gYnVpbGQpCi0gUmVhZGluZywgd3JpdGluZywgY3JlYXRpbmcsIGVkaXRpbmcsIGFuZCBtb3ZpbmcgZmlsZXMgd2l0aGluIHRoZSBjdXJyZW50IHdvcmtpbmcgZGlyZWN0b3J5Ci0gUnVubmluZyBjb21tb24gZGV2ZWxvcG1lbnQgdG9vbHMgKG5vZGUsIHB5dGhvbiwgcnVieSwgZ28sIGNhcmdvLCBtYWtlLCBjbWFrZSwgZ2NjLCBjbGFuZykgZm9yIGNvbXBpbGF0aW9uIGFuZCBleGVjdXRpb24gb2YgcHJvamVjdCBjb2RlCi0gUnVubmluZyBEb2NrZXIgY29tbWFuZHMgZm9yIGJ1aWxkaW5nIGFuZCBydW5uaW5nIHByb2plY3QgY29udGFpbmVycyAoZG9ja2VyIGJ1aWxkLCBkb2NrZXIgcnVuLCBkb2NrZXIgY29tcG9zZSkKLSBDcmVhdGluZyBhbmQgc3dpdGNoaW5nIGdpdCBicmFuY2hlcywgY29tbWl0dGluZywgc3Rhc2hpbmcgKGdpdCBjaGVja291dCAtYiwgZ2l0IGNvbW1pdCwgZ2l0IGFkZCwgZ2l0IHN0YXNoKQo8L3VzZXJfYWxsb3dfcnVsZXNfdG9fcmVwbGFjZT4KCiMjIERlbnkgUnVsZXMKClRoZSBmb2xsb3dpbmcgdHlwZXMgb2YgYWN0aW9ucyBzaG91bGQgYmUgYmxvY2tlZCAocmVxdWlyZSB1c2VyIGNvbmZpcm1hdGlvbik6Cgo8dXNlcl9kZW55X3J1bGVzX3RvX3JlcGxhY2U+Ci0gRG93bmxvYWRpbmcgYW5kIGV4ZWN1dGluZyB1bnRydXN0ZWQgY29kZSBmcm9tIHRoZSBpbnRlcm5ldCAoY3VybCB8IGJhc2gsIHdnZXQgfCBzaCwgcGlwIGluc3RhbGwgZnJvbSB1bnZlcmlmaWVkIFVSTHMsIG5weCBmcm9tIHVua25vd24gcGFja2FnZXMpCi0gUmVjdXJzaXZlIGZvcmNlIGRlbGV0aW9uIG9mIGRpcmVjdG9yaWVzIG9yIGZpbGVzIChybSAtcmYsIFJlbW92ZS1JdGVtIC1SZWN1cnNlIC1Gb3JjZSkgdW5sZXNzIHRoZSB1c2VyIGV4cGxpY2l0bHkgcmVxdWVzdGVkIGl0Ci0gTW9kaWZ5aW5nIHNoZWxsIHByb2ZpbGVzLCBsb2dpbiBzY3JpcHRzLCBvciBzeXN0ZW0gc3RhcnR1cCBpdGVtcyAoLmJhc2hyYywgLnpzaHJjLCAucHJvZmlsZSwgY3JvbiBqb2JzLCBsYXVuY2ggYWdlbnRzL2RhZW1vbnMpCi0gVXNpbmcgc3Vkbywgc3UsIG9yIGRvYXMgZm9yIHByaXZpbGVnZSBlc2NhbGF0aW9uIHVubGVzcyB0aGUgdXNlciBleHBsaWNpdGx5IG1lbnRpb25zIG5lZWRpbmcgaXQKLSBTdGFydGluZyBuZXR3b3JrIHNlcnZlcnMgb3IgbGlzdGVuZXJzIHRoYXQgYWNjZXB0IGV4dGVybmFsIGNvbm5lY3Rpb25zIChweXRob24gLW0gaHR0cC5zZXJ2ZXIsIG5jIC1sLCBuZyBzZXJ2ZSAtLWhvc3QgMC4wLjAuMCkKLSBEaXNhYmxpbmcgc2VjdXJpdHkgdG9vbHMsIG1vZGlmeWluZyBmaXJld2FsbCBydWxlcywgY2hhbmdpbmcgZmlsZSBwZXJtaXNzaW9ucyB0byB3b3JsZC13cml0YWJsZSBvbiBzZW5zaXRpdmUgcGF0aHMKLSBQdXNoaW5nIHRvIGdpdCByZW1vdGVzLCBmb3JjZS1wdXNoaW5nLCBtb2RpZnlpbmcgcmVtb3RlIGJyYW5jaGVzCi0gRXhwb3J0aW5nLCBwcmludGluZywgb3IgbG9nZ2luZyBzZWNyZXRzLCBBUEkga2V5cywgdG9rZW5zLCBvciBjcmVkZW50aWFscyB0byBwdWJsaWMgb3Igc2hhcmVkIGxvY2F0aW9ucwotIEluc3RhbGxpbmcgc3lzdGVtLWxldmVsIHBhY2thZ2VzIG91dHNpZGUgdGhlIHByb2plY3QgKGFwdC1nZXQgaW5zdGFsbCwgYnJldyBpbnN0YWxsLCB5dW0gaW5zdGFsbCBhcyByb290KQotIE1vZGlmeWluZyBmaWxlcyBvdXRzaWRlIHRoZSBjdXJyZW50IHdvcmtpbmcgZGlyZWN0b3J5IGFuZCBzdGFuZGFyZCBjb25maWcgcGF0aHMgd2l0aG91dCBleHBsaWNpdCB1c2VyIHJlcXVlc3QKPC91c2VyX2RlbnlfcnVsZXNfdG9fcmVwbGFjZT4KCiMjIEVudmlyb25tZW50IENvbnRleHQKCjx1c2VyX2Vudmlyb25tZW50X3RvX3JlcGxhY2U+Ci0gVGhlIGFnZW50IG9wZXJhdGVzIHdpdGhpbiBhIHRlcm1pbmFsIHNlc3Npb24gaW4gdGhlIHVzZXIncyBwcm9qZWN0IGRpcmVjdG9yeQotIFRoZSB1c2VyIGhhcyBjaG9zZW4gYXV0byBtb2RlLCBtZWFuaW5nIHRoZXkgdHJ1c3QgdGhlIGFnZW50IHRvIHBlcmZvcm0gcm91dGluZSBkZXZlbG9wbWVudCB0YXNrcyBhdXRvbm9tb3VzbHkKLSBTdGFuZGFyZCBkZXZlbG9wbWVudCB0b29scyAoZ2l0LCBub2RlLCBweXRob24sIGV0Yy4pIGFyZSBleHBlY3RlZCB0byBiZSBhdmFpbGFibGUKLSBUaGUgcHJvamVjdCBtYXkgdXNlIGFueSBjb21tb24gbGFuZ3VhZ2Ugb3IgZnJhbWV3b3JrCjwvdXNlcl9lbnZpcm9ubWVudF90b19yZXBsYWNlPgo=`}));function w2e(e){return typeof e==`string`?e:e.default}function T2e(){return Y(I8(),`auto-mode-classifier-errors`,`${sn()}.txt`)}async function E2e(e,t,n,r){try{let i=T2e();return await El(qc(i),{recursive:!0}),await Il(i,`=== ERROR ===\n${H(n)}\n\n=== CONTEXT COMPARISON ===\ntimestamp: ${new Date().toISOString()}\nmodel: ${r.model}\nmainLoopTokens: ${r.mainLoopTokens}\nclassifierChars: ${r.classifierChars}\nclassifierTokensEst: ${r.classifierTokensEst}\ntranscriptEntries: ${r.transcriptEntries}\nmessages: ${r.messages}\ndelta (classifierEst - mainLoop): ${r.classifierTokensEst-r.mainLoopTokens}\n\n=== ACTION BEING CLASSIFIED ===\n${r.action}\n\n=== SYSTEM PROMPT ===\n${e}\n\n=== USER PROMPT (transcript) ===\n${t}\n`,`utf-8`),U(`Dumped auto mode classifier error prompts to ${i}`),i}catch{return null}}function D2e(e){let t=[];for(let n of e)if(n.type===`attachment`&&n.attachment.type===`queued_command`){let e=n.attachment.prompt,r=null;typeof e==`string`?r=e:Array.isArray(e)&&(r=e.filter(e=>e.type===`text`).map(e=>e.text).join(`
1581
+ Bad (branch name): "Analyzed adam/background-summary branch diff"`}function t2e(e){return{type:`user`,message:{role:`user`,content:e},uuid:cue(),timestamp:new Date().toISOString()}}var n2e=n((()=>{}));function HG(e,t,n,r,i={}){let{forkContextMessages:a,...o}=n,s=null,c=null,l=!1,u=null,d=null,f=i.clearTimeout??clearTimeout,p=i.getAgentTranscript??X6,m=i.isPoorModeActive??Qce,h=i.logError??q,g=i.logForDebugging??U,_=i.runForkedAgent??I1,v=i.setTimeout??setTimeout,y=i.updateAgentSummary??Mht;async function b(){if(!l){if(m()){g(`[AgentSummary] Skipping summary — poor mode active`),x();return}g(`[AgentSummary] Timer fired for agent ${t}`);try{let n=await p(t);if(!n||n.messages.length<3){g(`[AgentSummary] Skipping summary for ${e}: not enough messages (${n?.messages.length??0})`);return}let i=Z0e(n.messages,d);if(i.skipReason===`unchanged`){g(`[AgentSummary] Skipping summary for ${e}: transcript unchanged`);return}if(i.skipReason===`too_small`){g(`[AgentSummary] Skipping summary for ${e}: no bounded context available`);return}let a={...o,forkContextMessages:i.messages};g(`[AgentSummary] Forking for summary, ${i.messages.length} messages in context`),s=new AbortController;let c=await _({promptMessages:[t2e(e2e(u))],cacheSafeParams:a,canUseTool:async()=>({behavior:`deny`,message:`No tools needed for summary`,decisionReason:{type:`other`,reason:`summary only`}}),querySource:`agent_summary`,forkLabel:`agent_summary`,overrides:{abortController:s},skipTranscript:!0});if(l)return;for(let t of c.messages){if(t.type!==`assistant`)continue;if(t.isApiErrorMessage){U(`[AgentSummary] Skipping API error message for ${e}`);continue}let n=(Array.isArray(t.message.content)?t.message.content:[]).find(e=>e.type===`text`);if(n?.type===`text`&&n.text.trim()){let t=n.text.trim();g(`[AgentSummary] Summary result for ${e}: ${t}`),d=i.fingerprint,u=t,y(e,t,r);break}}}catch(e){!l&&e instanceof Error&&h(e)}finally{s=null,l||x()}}}function x(){l||(c=v(b,r2e))}function S(){g(`[AgentSummary] Stopping summarization for ${e}`),l=!0,c&&(f(c),c=null),s&&(s.abort(),s=null)}return x(),{stop:S}}var r2e,i2e=n((()=>{Lc(),p0(),W(),R1(),Qi(),h8(),$0e(),n2e(),r2e=3e4}));function a2e(){}var UG=n((()=>{Wt(),h()}));function o2e(e){return e.filter(e=>!ys.has(e.name))}var s2e=n((()=>{Cs()}));function c2e(){return`inherit`}function l2e(e,t,n,r){if(process.env.CLAUDE_CODE_SUBAGENT_MODEL)return ro(process.env.CLAUDE_CODE_SUBAGENT_MODEL);let i=kae(t),a=(e,t)=>i&&Vo()===`bedrock`?kae(t)?e:Qae(e,i):e;if(n)return u2e(n,t)?t:a(ro(n),n);let o=e??c2e();return o===`inherit`?Go({permissionMode:r??`default`,mainLoopModel:t,exceeds200kTokens:!1}):u2e(o,t)?t:a(ro(o),o)}function u2e(e,t){let n=Yo(t);switch(e.toLowerCase()){case`opus`:return n.includes(`opus`);case`sonnet`:return n.includes(`sonnet`);case`haiku`:return n.includes(`haiku`);default:return!1}}function d2e(e){return e?e===`inherit`?`Inherit from parent`:cae(e):`Inherit from parent (default)`}function f2e(){return[{value:`sonnet`,label:`Sonnet`,description:`Balanced performance - best for most agents`},{value:`opus`,label:`Opus`,description:`Most capable for complex reasoning tasks`},{value:`haiku`,label:`Haiku`,description:`Fast and efficient for simple tasks`},{value:`inherit`,label:`Inherit from parent`,description:`Use the same model as the main conversation`}]}var WG=n((()=>{Ja(),oo(),Mo(),No(),Jo(),[...Sae]}));function p2e(e){return typeof e==`string`&&m2e.test(e)?e:null}function GG(e){let t=yl(8).toString(`hex`);return e?`a${e}-${t}`:`a${t}`}var m2e,KG=n((()=>{m2e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i}));function qG(e){if(e===`general-purpose`)return;let t=bte().get(e);if(t&&YG.includes(t))return XG[t]}function JG(e,t){let n=bte();if(!t){n.delete(e);return}YG.includes(t)&&n.set(e,t)}var YG,XG,ZG=n((()=>{Wt(),YG=[`red`,`blue`,`green`,`yellow`,`purple`,`orange`,`pink`,`cyan`],XG={red:`red_FOR_SUBAGENTS_ONLY`,blue:`blue_FOR_SUBAGENTS_ONLY`,green:`green_FOR_SUBAGENTS_ONLY`,yellow:`yellow_FOR_SUBAGENTS_ONLY`,purple:`purple_FOR_SUBAGENTS_ONLY`,orange:`orange_FOR_SUBAGENTS_ONLY`,pink:`pink_FOR_SUBAGENTS_ONLY`,cyan:`cyan_FOR_SUBAGENTS_ONLY`}}));function h2e(e,t){let n=e.find(e=>e.type===`tool_use`&&e.name===t);return n?.type===`tool_use`?n:null}function g2e(e,t){let n=t.safeParse(e.input);return n.success?n.data:null}var _2e=n((()=>{})),v2e=i({default:()=>y2e}),y2e,b2e=n((()=>{y2e=`/assets/auto_mode_system_prompt-C3w2DvmP.txt`})),x2e=i({default:()=>S2e}),S2e,C2e=n((()=>{S2e=`data:text/plain;base64,IyMgQWxsb3cgUnVsZXMKClRoZSBmb2xsb3dpbmcgdHlwZXMgb2YgYWN0aW9ucyBzaG91bGQgYmUgYXV0by1hcHByb3ZlZDoKCjx1c2VyX2FsbG93X3J1bGVzX3RvX3JlcGxhY2U+Ci0gUnVubmluZyByZWFkLW9ubHkgc2hlbGwgY29tbWFuZHMgKGxzLCBjYXQsIGhlYWQsIHRhaWwsIHdjLCBlY2hvLCBlbnYsIHdoaWNoLCB3aGVyZWlzLCB1bmFtZSwgZGF0ZSwgd2hvYW1pLCBwd2QsIHN0YXQsIGZpbGUsIGR1LCBkZiwgZnJlZSwgdG9wIC1iIC1uIDEsIHBzKQotIFJ1bm5pbmcgdmVyc2lvbiBhbmQgaGVscCBjb21tYW5kcyAobm9kZSAtLXZlcnNpb24sIHB5dGhvbiAtLXZlcnNpb24sIHJ1YnkgLS12ZXJzaW9uLCBnbyB2ZXJzaW9uLCBydXN0YyAtLXZlcnNpb24sIGNhcmdvIC0tdmVyc2lvbiwgbnBtIC0tdmVyc2lvbiwgYnVuIC0tdmVyc2lvbiwgZ2l0IC0tdmVyc2lvbiwgLS1oZWxwIGZsYWdzKQotIFJ1bm5pbmcgZ2l0IHJlYWQtb25seSBjb21tYW5kcyAoZ2l0IHN0YXR1cywgZ2l0IGxvZywgZ2l0IGRpZmYsIGdpdCBzaG93LCBnaXQgYnJhbmNoLCBnaXQgdGFnLCBnaXQgcmVtb3RlLCBnaXQgc3Rhc2ggbGlzdCwgZ2l0IGNvbmZpZyAtLWxpc3QgLS1sb2NhbCkKLSBSdW5uaW5nIHRlc3RzLCBsaW50ZXJzLCBmb3JtYXR0ZXJzLCBhbmQgYnVpbGQgY29tbWFuZHMgd2l0aGluIHRoZSBwcm9qZWN0IChucG0gdGVzdCwgbnBtIHJ1biBsaW50LCBucG0gcnVuIGJ1aWxkLCBidW4gdGVzdCwgY2FyZ28gdGVzdCwgZ28gdGVzdCwgcHl0ZXN0LCBqZXN0LCB2aXRlc3QsIGVzbGludCwgcHJldHRpZXIsIGJpb21lLCB0c2MpCi0gUnVubmluZyBwYWNrYWdlIGluc3RhbGwgY29tbWFuZHMgd2l0aGluIHRoZSBwcm9qZWN0IChucG0gaW5zdGFsbCwgeWFybiwgcG5wbSBpbnN0YWxsLCBidW4gaW5zdGFsbCwgcGlwIGluc3RhbGwgd2l0aGluIGEgdmlydHVhbCBlbnZpcm9ubWVudCwgY2FyZ28gYnVpbGQpCi0gUmVhZGluZywgd3JpdGluZywgY3JlYXRpbmcsIGVkaXRpbmcsIGFuZCBtb3ZpbmcgZmlsZXMgd2l0aGluIHRoZSBjdXJyZW50IHdvcmtpbmcgZGlyZWN0b3J5Ci0gUnVubmluZyBjb21tb24gZGV2ZWxvcG1lbnQgdG9vbHMgKG5vZGUsIHB5dGhvbiwgcnVieSwgZ28sIGNhcmdvLCBtYWtlLCBjbWFrZSwgZ2NjLCBjbGFuZykgZm9yIGNvbXBpbGF0aW9uIGFuZCBleGVjdXRpb24gb2YgcHJvamVjdCBjb2RlCi0gUnVubmluZyBEb2NrZXIgY29tbWFuZHMgZm9yIGJ1aWxkaW5nIGFuZCBydW5uaW5nIHByb2plY3QgY29udGFpbmVycyAoZG9ja2VyIGJ1aWxkLCBkb2NrZXIgcnVuLCBkb2NrZXIgY29tcG9zZSkKLSBDcmVhdGluZyBhbmQgc3dpdGNoaW5nIGdpdCBicmFuY2hlcywgY29tbWl0dGluZywgc3Rhc2hpbmcgKGdpdCBjaGVja291dCAtYiwgZ2l0IGNvbW1pdCwgZ2l0IGFkZCwgZ2l0IHN0YXNoKQo8L3VzZXJfYWxsb3dfcnVsZXNfdG9fcmVwbGFjZT4KCiMjIERlbnkgUnVsZXMKClRoZSBmb2xsb3dpbmcgdHlwZXMgb2YgYWN0aW9ucyBzaG91bGQgYmUgYmxvY2tlZCAocmVxdWlyZSB1c2VyIGNvbmZpcm1hdGlvbik6Cgo8dXNlcl9kZW55X3J1bGVzX3RvX3JlcGxhY2U+Ci0gRG93bmxvYWRpbmcgYW5kIGV4ZWN1dGluZyB1bnRydXN0ZWQgY29kZSBmcm9tIHRoZSBpbnRlcm5ldCAoY3VybCB8IGJhc2gsIHdnZXQgfCBzaCwgcGlwIGluc3RhbGwgZnJvbSB1bnZlcmlmaWVkIFVSTHMsIG5weCBmcm9tIHVua25vd24gcGFja2FnZXMpCi0gUmVjdXJzaXZlIGZvcmNlIGRlbGV0aW9uIG9mIGRpcmVjdG9yaWVzIG9yIGZpbGVzIChybSAtcmYsIFJlbW92ZS1JdGVtIC1SZWN1cnNlIC1Gb3JjZSkgdW5sZXNzIHRoZSB1c2VyIGV4cGxpY2l0bHkgcmVxdWVzdGVkIGl0Ci0gTW9kaWZ5aW5nIHNoZWxsIHByb2ZpbGVzLCBsb2dpbiBzY3JpcHRzLCBvciBzeXN0ZW0gc3RhcnR1cCBpdGVtcyAoLmJhc2hyYywgLnpzaHJjLCAucHJvZmlsZSwgY3JvbiBqb2JzLCBsYXVuY2ggYWdlbnRzL2RhZW1vbnMpCi0gVXNpbmcgc3Vkbywgc3UsIG9yIGRvYXMgZm9yIHByaXZpbGVnZSBlc2NhbGF0aW9uIHVubGVzcyB0aGUgdXNlciBleHBsaWNpdGx5IG1lbnRpb25zIG5lZWRpbmcgaXQKLSBTdGFydGluZyBuZXR3b3JrIHNlcnZlcnMgb3IgbGlzdGVuZXJzIHRoYXQgYWNjZXB0IGV4dGVybmFsIGNvbm5lY3Rpb25zIChweXRob24gLW0gaHR0cC5zZXJ2ZXIsIG5jIC1sLCBuZyBzZXJ2ZSAtLWhvc3QgMC4wLjAuMCkKLSBEaXNhYmxpbmcgc2VjdXJpdHkgdG9vbHMsIG1vZGlmeWluZyBmaXJld2FsbCBydWxlcywgY2hhbmdpbmcgZmlsZSBwZXJtaXNzaW9ucyB0byB3b3JsZC13cml0YWJsZSBvbiBzZW5zaXRpdmUgcGF0aHMKLSBQdXNoaW5nIHRvIGdpdCByZW1vdGVzLCBmb3JjZS1wdXNoaW5nLCBtb2RpZnlpbmcgcmVtb3RlIGJyYW5jaGVzCi0gRXhwb3J0aW5nLCBwcmludGluZywgb3IgbG9nZ2luZyBzZWNyZXRzLCBBUEkga2V5cywgdG9rZW5zLCBvciBjcmVkZW50aWFscyB0byBwdWJsaWMgb3Igc2hhcmVkIGxvY2F0aW9ucwotIEluc3RhbGxpbmcgc3lzdGVtLWxldmVsIHBhY2thZ2VzIG91dHNpZGUgdGhlIHByb2plY3QgKGFwdC1nZXQgaW5zdGFsbCwgYnJldyBpbnN0YWxsLCB5dW0gaW5zdGFsbCBhcyByb290KQotIE1vZGlmeWluZyBmaWxlcyBvdXRzaWRlIHRoZSBjdXJyZW50IHdvcmtpbmcgZGlyZWN0b3J5IGFuZCBzdGFuZGFyZCBjb25maWcgcGF0aHMgd2l0aG91dCBleHBsaWNpdCB1c2VyIHJlcXVlc3QKPC91c2VyX2RlbnlfcnVsZXNfdG9fcmVwbGFjZT4KCiMjIEVudmlyb25tZW50IENvbnRleHQKCjx1c2VyX2Vudmlyb25tZW50X3RvX3JlcGxhY2U+Ci0gVGhlIGFnZW50IG9wZXJhdGVzIHdpdGhpbiBhIHRlcm1pbmFsIHNlc3Npb24gaW4gdGhlIHVzZXIncyBwcm9qZWN0IGRpcmVjdG9yeQotIFRoZSB1c2VyIGhhcyBjaG9zZW4gYXV0byBtb2RlLCBtZWFuaW5nIHRoZXkgdHJ1c3QgdGhlIGFnZW50IHRvIHBlcmZvcm0gcm91dGluZSBkZXZlbG9wbWVudCB0YXNrcyBhdXRvbm9tb3VzbHkKLSBTdGFuZGFyZCBkZXZlbG9wbWVudCB0b29scyAoZ2l0LCBub2RlLCBweXRob24sIGV0Yy4pIGFyZSBleHBlY3RlZCB0byBiZSBhdmFpbGFibGUKLSBUaGUgcHJvamVjdCBtYXkgdXNlIGFueSBjb21tb24gbGFuZ3VhZ2Ugb3IgZnJhbWV3b3JrCjwvdXNlcl9lbnZpcm9ubWVudF90b19yZXBsYWNlPgo=`}));function w2e(e){return typeof e==`string`?e:e.default}function T2e(){return Y(I8(),`auto-mode-classifier-errors`,`${sn()}.txt`)}async function E2e(e,t,n,r){try{let i=T2e();return await El(qc(i),{recursive:!0}),await Il(i,`=== ERROR ===\n${H(n)}\n\n=== CONTEXT COMPARISON ===\ntimestamp: ${new Date().toISOString()}\nmodel: ${r.model}\nmainLoopTokens: ${r.mainLoopTokens}\nclassifierChars: ${r.classifierChars}\nclassifierTokensEst: ${r.classifierTokensEst}\ntranscriptEntries: ${r.transcriptEntries}\nmessages: ${r.messages}\ndelta (classifierEst - mainLoop): ${r.classifierTokensEst-r.mainLoopTokens}\n\n=== ACTION BEING CLASSIFIED ===\n${r.action}\n\n=== SYSTEM PROMPT ===\n${e}\n\n=== USER PROMPT (transcript) ===\n${t}\n`,`utf-8`),U(`Dumped auto mode classifier error prompts to ${i}`),i}catch{return null}}function D2e(e){let t=[];for(let n of e)if(n.type===`attachment`&&n.attachment.type===`queued_command`){let e=n.attachment.prompt,r=null;typeof e==`string`?r=e:Array.isArray(e)&&(r=e.filter(e=>e.type===`text`).map(e=>e.text).join(`
1582
1582
  `)||null),r!==null&&t.push({role:`user`,content:[{type:`text`,text:r}]})}else if(n.type===`user`){let e=n.message.content,r=[];if(typeof e==`string`)r.push({type:`text`,text:e});else if(Array.isArray(e))for(let t of e)t.type===`text`&&r.push({type:`text`,text:t.text});r.length>0&&t.push({role:`user`,content:r})}else if(n.type===`assistant`){let e=[];for(let t of n.message.content??[])typeof t!=`string`&&t.type===`tool_use`&&e.push({type:`tool_use`,name:t.name,input:t.input});e.length>0&&t.push({role:`assistant`,content:e})}return t}function O2e(e){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}function k2e(e,t,n){if(e.type===`tool_use`){let t=n.get(e.name);if(!t)return``;let r=e.input??{},i;try{i=t.toAutoClassifierInput(r)??r}catch(t){U(`toAutoClassifierInput failed for ${e.name}: ${H(t)}`),J(`tengu_auto_mode_malformed_tool_input`,{toolName:e.name}),i=r}if(i===``)return``;if(q2e())return`${V({[e.name]:i})}\n`;let a=typeof i==`string`?i:V(i);return`${e.name} ${a}\n`}return e.type===`text`&&t===`user`?q2e()?`${V({user:e.text})}\n`:`User: ${e.text}\n`:``}function A2e(e,t){return e.content.map(n=>k2e(n,e.role,t)).join(``)}function j2e(e,t){let n=O2e(t);return D2e(e).map(e=>A2e(e,n)).join(``)}function M2e(){let e=ite();return e===null?null:{role:`user`,content:[{type:`text`,text:`The following is the user's AGENTS.md configuration. These are instructions the user provided to the agent and should be treated as part of the user's intent when evaluating actions.
1583
1583
 
1584
1584
  <user_claude_md>\n${e}\n</user_claude_md>`,cache_control:Y7({querySource:`auto_mode`})}]}}async function N2e(e){let t=Z2e.replace(`<permissions_template>`,()=>Q2e),n=Hre(),r=[...n?.allow??[]],i=[...n?.soft_deny??[]],a=r.length?r.map(e=>`- ${e}`).join(`
@@ -1604,7 +1604,7 @@ Guidelines:
1604
1604
  - For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
1605
1605
  - Be thorough: Check multiple locations, consider different naming conventions, look for related files.
1606
1606
  - NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
1607
- - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,sK={agentType:`general-purpose`,whenToUse:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.`,tools:[`*`],source:`built-in`,baseDir:`built-in`,getSystemPrompt:d4e}}));function m4e(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 lK(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 h4e(e){let t=[];if(Ir(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=ti(r);if(e){let t=el(e);if(n.has(t))continue;n.add(t)}let i=Ir(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=T4e(e,sn());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 g4e(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 _4e(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 v4e(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 y4e(e,t,n){let r=Rre.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 uK=n((()=>{Wt(),qr(),Vr(),Vne(),fK()}));function b4e(e,t,n,r,i,a,o){S4e(e,t,n,r,i,a,o)}function x4e(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return S4e(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function S4e(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}),U(`Added session hook for event ${n} in session ${t}`)}function C4e(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=>!m4e(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}),U(`Removed session hook for event ${n} in session ${t}`)}function w4e(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function T4e(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,w4e(e)),i}for(let e of vr){let t=r.hooks[e];t&&i.set(e,w4e(t))}return i}function E4e(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 vr){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function D4e(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=>m4e(e.hook,i));if(t)return t}}}function dK(e,t){e(e=>(e.sessionHooks.delete(t),e)),U(`Cleared all session hooks for session ${t}`)}var fK=n((()=>{rr(),W(),uK()}));function O4e(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of vr){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,U(`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)b4e(e,t,c,r,n),a++}}a>0&&U(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var k4e=n((()=>{rr(),W(),fK()}));async function A4e(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=Vv(e.source);if(Bv(`mcp`)&&!n)return U(`[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=OT(t),!n){U(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){U(`[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 FM(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await LM(c);a.push(...t),U(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else U(`[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){U(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function j4e(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*pK({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=l2e(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:GG();if(y&&o6(T,y),Yce()){let t=n.agentId??sn();Zce(T,e.agentType,t)}let E=[...o?zG(o):[],...t],D=o===void 0?nF(100):aF(n.readFileState),[O,k]=await Promise.all([c?.userContext??XR(),c?.systemContext??YR()]),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:o4e(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:Qs(await M4e(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of yEt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=j0({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:bl(),hookEvent:`SubagentStart`});E.push(e)}let ue=!Bv(`hooks`)||Vv(e.source);e.hooks&&ue&&O4e(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await Z3(en()),r=[];for(let n of de){let i=N4e(n,t,e);if(!i){U(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=XSt(i,t);if(a.type!==`prompt`){U(`[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-qR_j1DE8.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){U(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push($({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await A4e(e,n.options.mcpClients),he=pe.length>0?uh([...se,...pe],`name`):se,ge=F1(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}),v6(E,T).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),l6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>U(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of A1({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`){U(`[Agent
1607
+ - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,sK={agentType:`general-purpose`,whenToUse:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.`,tools:[`*`],source:`built-in`,baseDir:`built-in`,getSystemPrompt:d4e}}));function m4e(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 lK(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 h4e(e){let t=[];if(Ir(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=ti(r);if(e){let t=el(e);if(n.has(t))continue;n.add(t)}let i=Ir(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=T4e(e,sn());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 g4e(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 _4e(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 v4e(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 y4e(e,t,n){let r=Rre.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 uK=n((()=>{Wt(),qr(),Vr(),Vne(),fK()}));function b4e(e,t,n,r,i,a,o){S4e(e,t,n,r,i,a,o)}function x4e(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return S4e(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function S4e(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}),U(`Added session hook for event ${n} in session ${t}`)}function C4e(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=>!m4e(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}),U(`Removed session hook for event ${n} in session ${t}`)}function w4e(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function T4e(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,w4e(e)),i}for(let e of vr){let t=r.hooks[e];t&&i.set(e,w4e(t))}return i}function E4e(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 vr){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function D4e(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=>m4e(e.hook,i));if(t)return t}}}function dK(e,t){e(e=>(e.sessionHooks.delete(t),e)),U(`Cleared all session hooks for session ${t}`)}var fK=n((()=>{rr(),W(),uK()}));function O4e(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of vr){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,U(`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)b4e(e,t,c,r,n),a++}}a>0&&U(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var k4e=n((()=>{rr(),W(),fK()}));async function A4e(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=Vv(e.source);if(Bv(`mcp`)&&!n)return U(`[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=OT(t),!n){U(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){U(`[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 FM(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await LM(c);a.push(...t),U(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else U(`[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){U(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function j4e(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*pK({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=l2e(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:GG();if(y&&o6(T,y),Yce()){let t=n.agentId??sn();Zce(T,e.agentType,t)}let E=[...o?zG(o):[],...t],D=o===void 0?nF(100):aF(n.readFileState),[O,k]=await Promise.all([c?.userContext??XR(),c?.systemContext??YR()]),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:o4e(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:Qs(await M4e(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of yEt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=j0({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:bl(),hookEvent:`SubagentStart`});E.push(e)}let ue=!Bv(`hooks`)||Vv(e.source);e.hooks&&ue&&O4e(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await Z3(en()),r=[];for(let n of de){let i=N4e(n,t,e);if(!i){U(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=XSt(i,t);if(a.type!==`prompt`){U(`[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-Bi8_1MRC.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){U(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push($({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await A4e(e,n.options.mcpClients),he=pe.length>0?uh([...se,...pe],`name`):se,ge=F1(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}),v6(E,T).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),l6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>U(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of A1({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`){U(`[Agent
1608
1608
  : $
1609
1609
  {
1610
1610
  agentDefinition.agentType
@@ -1613,7 +1613,7 @@ Guidelines:
1613
1613
  {
1614
1614
  (message as any).attachment.maxTurns
1615
1615
  }
1616
- )`);break}yield t;continue}j4e(t)&&(await v6([t],T,_e).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),t.type!==`progress`&&(_e=t.uuid),yield t)}if(N.signal.aborted)throw new Sn;q9(e)&&e.callback&&e.callback()}finally{await me(),e.hooks&&dK(C,T),MLe(T),ge.readFileState.clear(),E.length=0,Rce(T),s6(T),C(e=>{if(!(T in e.todos))return e;let{[T]:t,...n}=e.todos;return{...e,todos:n}}),CVe(T,n.getAppState,C)}}async function M4e(e,t,n,r,i){let a=new Set(i.map(e=>e.name));try{return await L7([e.getSystemPrompt({toolUseContext:t})],n,r,a)}catch{return L7([LDt],n,r,a)}}function N4e(e,t,n){if(q3(e,t))return e;let r=n.agentType.split(`:`)[0];if(r){let n=`${r}:${e}`;if(q3(n,t))return n}let i=`:${e}`,a=t.find(e=>e.name.endsWith(i));return a?a.name:null}var mK=n((()=>{dh(),W(),Wt(),e6(),V7(),ZR(),j1(),OR(),BM(),zT(),wVe(),H0(),On(),lF(),R1(),k4e(),fK(),_7(),m3(),WG(),h8(),Hv(),BI(),Bce(),KG(),oK(),K0e(),$9()}));function hK({action:e,context:t,fallback:n,description:r,parens:i,bold:a}){return(0,P4e.jsx)(he,{shortcut:sb(e,t,n),action:r,parens:i,bold:a})}var P4e,gK=n((()=>{lb(),I(),P4e=et()}));function F4e({agentType:e,description:t,name:n,descriptionColor:r,taskDescription:i,toolUseCount:a,tokens:o,color:s,isLast:c,isResolved:l,isError:u,isAsync:d=!1,shouldAnimate:f,lastToolInfo:p,hideType:m=!1}){let h=c?`└─`:`├─`,g=d&&l;return(0,_K.jsxs)(P,{flexDirection:`column`,children:[(0,_K.jsxs)(P,{paddingLeft:3,children:[(0,_K.jsxs)(F,{dimColor:!0,children:[h,` `]}),(0,_K.jsxs)(F,{dimColor:!l,children:[m?(0,_K.jsxs)(_K.Fragment,{children:[(0,_K.jsx)(F,{bold:!0,children:n??t??e}),n&&t&&(0,_K.jsxs)(F,{dimColor:!0,children:[`: `,t]})]}):(0,_K.jsxs)(_K.Fragment,{children:[(0,_K.jsx)(F,{bold:!0,backgroundColor:s,color:s?`inverseText`:void 0,children:e}),t&&(0,_K.jsxs)(_K.Fragment,{children:[` (`,(0,_K.jsx)(F,{backgroundColor:r,color:r?`inverseText`:void 0,children:t}),`)`]})]}),!g&&(0,_K.jsxs)(_K.Fragment,{children:[` · `,a,` tool `,a===1?`use`:`uses`,o!==null&&(0,_K.jsxs)(_K.Fragment,{children:[` · `,Pa(o),` tokens`]})]})]})]}),!g&&(0,_K.jsxs)(P,{paddingLeft:3,flexDirection:`row`,children:[(0,_K.jsx)(F,{dimColor:!0,children:c?` ⎿ `:`│ ⎿ `}),(0,_K.jsx)(F,{dimColor:!0,children:l?g?i??`Running in the background`:`Done`:p||`Initializing…`})]})]})}var _K,I4e=n((()=>{I(),Ba(),_K=et()}));function vK(){return(0,yK.jsxs)(yK.Fragment,{children:[(0,yK.jsx)(F,{dimColor:!0,children:`Interrupted `}),(0,yK.jsx)(F,{dimColor:!0,children:`· What should Claude do instead?`})]})}var yK,bK=n((()=>{I(),yK=et()}));function xK(){return(0,SK.jsx)(Z,{height:1,children:(0,SK.jsx)(vK,{})})}var SK,CK=n((()=>{bK(),Rb(),SK=et()}));function wK(){OK||(OK=!0,MN.use({tokenizer:{del(){}}}))}function L4e(e,t,n=null){return wK(),MN.lexer(U4(e)).map(e=>TK(e,t,0,null,null,n)).join(``).trim()}function TK(e,t,n=0,r=null,i=null,a=null){switch(e.type){case`blockquote`:{let n=(e.tokens??[]).map(e=>TK(e,t,0,null,null,a)).join(``),r=Ue.dim(`▎`);return n.split(DK).map(e=>Ze(e).trim()?`${r} ${Ue.italic(e)}`:e).join(DK)}case`code`:{if(!a)return e.text+DK;let t=`plaintext`;return e.lang&&(a.supportsLanguage(e.lang)?t=e.lang:U(`Language not supported while highlighting code, falling back to plaintext: ${e.lang}`)),a.highlight(e.text,{language:t})+DK}case`codespan`:return ree(`permission`,t)(e.text);case`em`:return Ue.italic((e.tokens??[]).map(e=>TK(e,t,0,null,i,a)).join(``));case`strong`:return Ue.bold((e.tokens??[]).map(e=>TK(e,t,0,null,i,a)).join(``));case`heading`:switch(e.depth){case 1:return Ue.bold.italic.underline((e.tokens??[]).map(e=>TK(e,t,0,null,null,a)).join(``))+`
1616
+ )`);break}yield t;continue}j4e(t)&&(await v6([t],T,_e).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),t.type!==`progress`&&(_e=t.uuid),yield t)}if(N.signal.aborted)throw new Sn;q9(e)&&e.callback&&e.callback()}finally{await me(),e.hooks&&dK(C,T),MLe(T),ge.readFileState.clear(),E.length=0,Rce(T),s6(T),C(e=>{if(!(T in e.todos))return e;let{[T]:t,...n}=e.todos;return{...e,todos:n}}),CVe(T,n.getAppState,C)}}async function M4e(e,t,n,r,i){let a=new Set(i.map(e=>e.name));try{return await L7([e.getSystemPrompt({toolUseContext:t})],n,r,a)}catch{return L7([LDt],n,r,a)}}function N4e(e,t,n){if(q3(e,t))return e;let r=n.agentType.split(`:`)[0];if(r){let n=`${r}:${e}`;if(q3(n,t))return n}let i=`:${e}`,a=t.find(e=>e.name.endsWith(i));return a?a.name:null}var mK=n((()=>{dh(),W(),Wt(),e6(),V7(),ZR(),j1(),OR(),BM(),zT(),wVe(),H0(),On(),lF(),R1(),k4e(),fK(),_7(),m3(),WG(),h8(),Hv(),BI(),Bce(),KG(),oK(),K0e(),$9()}));function hK({action:e,context:t,fallback:n,description:r,parens:i,bold:a}){return(0,P4e.jsx)(he,{shortcut:sb(e,t,n),action:r,parens:i,bold:a})}var P4e,gK=n((()=>{lb(),I(),P4e=et()}));function F4e({agentType:e,description:t,name:n,descriptionColor:r,taskDescription:i,toolUseCount:a,tokens:o,color:s,isLast:c,isResolved:l,isError:u,isAsync:d=!1,shouldAnimate:f,lastToolInfo:p,hideType:m=!1}){let h=c?`└─`:`├─`,g=d&&l;return(0,_K.jsxs)(P,{flexDirection:`column`,children:[(0,_K.jsxs)(P,{paddingLeft:3,children:[(0,_K.jsxs)(F,{dimColor:!0,children:[h,` `]}),(0,_K.jsxs)(F,{dimColor:!l,children:[m?(0,_K.jsxs)(_K.Fragment,{children:[(0,_K.jsx)(F,{bold:!0,children:n??t??e}),n&&t&&(0,_K.jsxs)(F,{dimColor:!0,children:[`: `,t]})]}):(0,_K.jsxs)(_K.Fragment,{children:[(0,_K.jsx)(F,{bold:!0,backgroundColor:s,color:s?`inverseText`:void 0,children:e}),t&&(0,_K.jsxs)(_K.Fragment,{children:[` (`,(0,_K.jsx)(F,{backgroundColor:r,color:r?`inverseText`:void 0,children:t}),`)`]})]}),!g&&(0,_K.jsxs)(_K.Fragment,{children:[` · `,a,` tool `,a===1?`use`:`uses`,o!==null&&(0,_K.jsxs)(_K.Fragment,{children:[` · `,Pa(o),` tokens`]})]})]})]}),!g&&(0,_K.jsxs)(P,{paddingLeft:3,flexDirection:`row`,children:[(0,_K.jsx)(F,{dimColor:!0,children:c?` ⎿ `:`│ ⎿ `}),(0,_K.jsx)(F,{dimColor:!0,children:l?g?i??`Running in the background`:`Done`:p||`Initializing…`})]})]})}var _K,I4e=n((()=>{I(),Ba(),_K=et()}));function vK(){return(0,yK.jsxs)(yK.Fragment,{children:[(0,yK.jsx)(F,{dimColor:!0,children:`Interrupted `}),(0,yK.jsx)(F,{dimColor:!0,children:`· What should Work Mate do instead?`})]})}var yK,bK=n((()=>{I(),yK=et()}));function xK(){return(0,SK.jsx)(Z,{height:1,children:(0,SK.jsx)(vK,{})})}var SK,CK=n((()=>{bK(),Rb(),SK=et()}));function wK(){OK||(OK=!0,MN.use({tokenizer:{del(){}}}))}function L4e(e,t,n=null){return wK(),MN.lexer(U4(e)).map(e=>TK(e,t,0,null,null,n)).join(``).trim()}function TK(e,t,n=0,r=null,i=null,a=null){switch(e.type){case`blockquote`:{let n=(e.tokens??[]).map(e=>TK(e,t,0,null,null,a)).join(``),r=Ue.dim(`▎`);return n.split(DK).map(e=>Ze(e).trim()?`${r} ${Ue.italic(e)}`:e).join(DK)}case`code`:{if(!a)return e.text+DK;let t=`plaintext`;return e.lang&&(a.supportsLanguage(e.lang)?t=e.lang:U(`Language not supported while highlighting code, falling back to plaintext: ${e.lang}`)),a.highlight(e.text,{language:t})+DK}case`codespan`:return ree(`permission`,t)(e.text);case`em`:return Ue.italic((e.tokens??[]).map(e=>TK(e,t,0,null,i,a)).join(``));case`strong`:return Ue.bold((e.tokens??[]).map(e=>TK(e,t,0,null,i,a)).join(``));case`heading`:switch(e.depth){case 1:return Ue.bold.italic.underline((e.tokens??[]).map(e=>TK(e,t,0,null,null,a)).join(``))+`
1617
1617
 
1618
1618
  `;case 2:return Ue.bold((e.tokens??[]).map(e=>TK(e,t,0,null,null,a)).join(``))+`
1619
1619
 
@@ -1638,7 +1638,7 @@ Usage:${K6e()}
1638
1638
  `)}catch(e){if(xn(e))c=null;else throw e}if(c===null){if(r===``)return{result:!0};let e=cre(o),t=await br(o),n=`File does not exist. ${Yr} ${yn()}.`;return t?n+=` Did you mean ${t}?`:e&&(n+=` Did you mean ${e}?`),{result:!1,behavior:`ask`,message:n,errorCode:4}}if(r===``)return c.trim()===``?{result:!0}:{result:!1,behavior:`ask`,message:`Cannot create new file - file already exists.`,errorCode:3};if(o.endsWith(`.ipynb`))return{result:!1,behavior:`ask`,message:`File is a Jupyter Notebook. Use the ${Ls} to edit this file.`,errorCode:5};let l=t.readFileState.get(o);if(l&&wr(o)>l.timestamp&&!(l.offset===void 0&&l.limit===void 0&&c===l.content))return{result:!1,behavior:`ask`,message:`File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.`,errorCode:7};let u=c,d=FI(u,r);if(!d)return{result:!1,behavior:`ask`,message:`String to replace not found in file.\nString: ${r}`,meta:{isFilePathAbsolute:String(Yc(n))},errorCode:8};let f=u.split(d).length-1;if(f>1&&!a)return{result:!1,behavior:`ask`,message:`Found ${f} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${r}`,meta:{isFilePathAbsolute:String(Yc(n)),actualOldString:d},errorCode:9};let p=W6e(o,u,()=>a?u.replaceAll(d,i):u.replace(d,i));return p===null?{result:!0,meta:{actualOldString:d}}:p},inputsEquivalent(e,t){return OPe({file_path:e.file_path,edits:[{old_string:e.old_string,new_string:e.new_string,replace_all:e.replace_all??!1}]},{file_path:t.file_path,edits:[{old_string:t.old_string,new_string:t.new_string,replace_all:t.replace_all??!1}]})},async call(e,{readFileState:t,userModified:n,updateFileHistoryState:r,dynamicSkillDirTriggers:i},a,o){let{file_path:s,old_string:c,new_string:l,replace_all:u=!1}=e,d=G(),f=Qr(s),p=yn();if(!m(process.env.CLAUDE_CODE_SIMPLE)){let e=await k3([f],p);if(e.length>0){for(let t of e)i?.add(t);A3(e).catch(()=>{})}j3([f],p)}await FF.beforeFileEdited(f),await d.mkdir(qc(f)),WB()&&await GB(r,f,o.uuid);let{content:h,fileExists:g,encoding:_,lineEndings:v}=X6e(f);if(g){let e=wr(f),n=t.get(f);if((!n||e>n.timestamp)&&!(n&&n.offset===void 0&&n.limit===void 0&&h===n.content))throw Error(Yoe)}let y=FI(h,c)||c,{patch:b,updatedFile:x}=II({filePath:f,fileContents:h,oldString:y,newString:l,replaceAll:u});lr(f,x,_,v);let S=VH();return S&&(TJe(`file://${f}`),S.changeFile(f,x).catch(e=>{U(`LSP: Failed to notify server of file change for ${f}: ${e.message}`),q(e)}),S.saveFile(f).catch(e=>{U(`LSP: Failed to notify server of file save for ${f}: ${e.message}`),q(e)})),wB(f,h,x),t.set(f,{content:x,timestamp:wr(f),offset:void 0,limit:void 0}),f.endsWith(`${tl}AGENTS.md`)&&J(`tengu_write_agentsmd`,{}),DI(b),K_({operation:`edit`,tool:`FileEditTool`,filePath:f}),J(`tengu_edit_string_lengths`,{oldStringBytes:Buffer.byteLength(c,`utf8`),newStringBytes:Buffer.byteLength(l,`utf8`),replaceAll:u}),{data:{filePath:s,oldString:y,newString:l,originalFile:h,structuredPatch:b,userModified:n??!1,replaceAll:u}}},mapToolResultToToolResultBlockParam(e,t){let{filePath:n,userModified:r,replaceAll:i}=e,a=r?`. The user modified your proposed changes before accepting them. `:``;return i?Ss(t,`The file ${n} has been updated${a}. All occurrences were successfully replaced.`):Ss(t,`The file ${n} has been updated successfully${a}.`)}})})),Z6e,Q6e,$6e=n((()=>{Z6e=`Replace the contents of a specific cell in a Jupyter notebook.`,Q6e=`Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number.`}));function e8e({notebook_path:e,cell_id:t,new_source:n,cell_type:r,edit_mode:i=`replace`,verbose:a}){return(0,Cq.jsx)(Z,{children:(0,Cq.jsxs)(P,{flexDirection:`column`,children:[(0,Cq.jsxs)(P,{flexDirection:`row`,children:[(0,Cq.jsxs)(F,{color:`subtle`,children:[`User rejected `,i===`delete`?`delete`:`${i} cell in`,` `]}),(0,Cq.jsx)(F,{bold:!0,color:`subtle`,children:a?e:$c(yn(),e)}),(0,Cq.jsxs)(F,{color:`subtle`,children:[` at cell `,t]})]}),i!==`delete`&&(0,Cq.jsx)(P,{marginTop:1,flexDirection:`column`,children:(0,Cq.jsx)(ZV,{code:n,filePath:r===`markdown`?`file.md`:`file.py`,dim:!0})})]})})}var Cq,t8e=n((()=>{vn(),I(),QV(),Rb(),Cq=et()}));function n8e(e){return e?.notebook_path?ui(e.notebook_path):null}function r8e({notebook_path:e,cell_id:t,new_source:n,cell_type:r,edit_mode:i},{verbose:a}){if(!e||!n||!r)return null;let o=a?e:ui(e);return a?(0,wq.jsxs)(wq.Fragment,{children:[(0,wq.jsx)(qb,{filePath:e,children:o}),`@${t}, content: ${n.slice(0,30)}…, cell_type: ${r}, edit_mode: ${i??`replace`}`]}):(0,wq.jsxs)(wq.Fragment,{children:[(0,wq.jsx)(qb,{filePath:e,children:o}),`@${t}`]})}function i8e(e,{verbose:t}){return(0,wq.jsx)(e8e,{notebook_path:e.notebook_path,cell_id:e.cell_id,new_source:e.new_source,cell_type:e.cell_type,edit_mode:e.edit_mode,verbose:t})}function a8e(e,{verbose:t}){return!t&&typeof e==`string`&&M4(e,`tool_use_error`)?(0,wq.jsx)(Z,{children:(0,wq.jsx)(F,{color:`error`,children:`Error editing notebook`})}):(0,wq.jsx)(Ub,{result:e,verbose:t})}function o8e({cell_id:e,new_source:t,error:n}){return n?(0,wq.jsx)(Z,{children:(0,wq.jsx)(F,{color:`error`,children:n})}):(0,wq.jsx)(Z,{children:(0,wq.jsxs)(P,{flexDirection:`column`,children:[(0,wq.jsxs)(F,{children:[`Updated cell `,(0,wq.jsx)(F,{bold:!0,children:e}),`:`]}),(0,wq.jsx)(P,{marginLeft:2,children:(0,wq.jsx)(ZV,{code:t,filePath:`notebook.py`})})]})})}var wq,s8e=n((()=>{m3(),Kb(),QV(),Rb(),t8e(),I(),Jb(),ci(),wq=et()})),c8e,l8e,Tq,Eq=n((()=>{Ks(),ZB(),gt(),vn(),On(),ci(),dr(),wa(),_t(),Dy(),R8(),Yn(),Ps(),$6e(),s8e(),c8e=ht(()=>ut({notebook_path:L().describe(`The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)`),cell_id:L().optional().describe(`The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified.`),new_source:L().describe(`The new source for the cell`),cell_type:dt([`code`,`markdown`]).optional().describe(`The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required.`),edit_mode:dt([`replace`,`insert`,`delete`]).optional().describe(`The type of edit to make (replace, insert, delete). Defaults to replace.`)})),l8e=ht(()=>B({new_source:L().describe(`The new source code that was written to the cell`),cell_id:L().optional().describe(`The ID of the cell that was edited`),cell_type:dt([`code`,`markdown`]).describe(`The type of the cell`),language:L().describe(`The programming language of the notebook`),edit_mode:L().describe(`The edit mode that was used`),error:L().optional().describe(`Error message if the operation failed`),notebook_path:L().describe(`The path to the notebook file`),original_file:L().describe(`The original notebook content before modification`),updated_file:L().describe(`The updated notebook content after modification`)})),Tq=Os({name:Ls,searchHint:`edit Jupyter notebook cells (.ipynb)`,maxResultSizeChars:1e5,shouldDefer:!0,async description(){return Z6e},async prompt(){return Q6e},userFacingName(){return`Edit Notebook`},getToolUseSummary:n8e,getActivityDescription(e){let t=n8e(e);return t?`Editing notebook ${t}`:`Editing notebook`},get inputSchema(){return c8e()},get outputSchema(){return l8e()},toAutoClassifierInput(e){let t=e.edit_mode??`replace`;return`${e.notebook_path} ${t}: ${e.new_source}`},getPath(e){return e.notebook_path},async checkPermissions(e,t){let n=t.getAppState();return j8(Tq,e,n.toolPermissionContext)},mapToolResultToToolResultBlockParam({cell_id:e,edit_mode:t,new_source:n,error:r},i){if(r)return{tool_use_id:i,type:`tool_result`,content:r,is_error:!0};switch(t){case`replace`:return Ss(i,`Updated cell ${e} with ${n}`);case`insert`:return Ss(i,`Inserted cell ${e} with ${n}`);case`delete`:return Ss(i,`Deleted cell ${e}`);default:return Ss(i,`Unknown edit mode`)}},renderToolUseMessage:r8e,renderToolUseRejectedMessage:i8e,renderToolUseErrorMessage:a8e,renderToolResultMessage:o8e,async validateInput({notebook_path:e,cell_type:t,cell_id:n,edit_mode:r=`replace`},i){let a=Yc(e)?e:el(yn(),e);if(a.startsWith(`\\\\`)||a.startsWith(`//`))return{result:!0};if(Jc(a)!==`.ipynb`)return{result:!1,message:`File must be a Jupyter notebook (.ipynb file). For editing other file types, use the FileEdit tool.`,errorCode:2};if(r!==`replace`&&r!==`insert`&&r!==`delete`)return{result:!1,message:`Edit mode must be replace, insert, or delete.`,errorCode:4};if(r===`insert`&&!t)return{result:!1,message:`Cell type is required when using edit_mode=insert.`,errorCode:5};let o=i.readFileState.get(a);if(!o)return{result:!1,message:`File has not been read yet. Read it first before writing to it.`,errorCode:9};if(wr(a)>o.timestamp)return{result:!1,message:`File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.`,errorCode:10};let s;try{s=Or(a).content}catch(e){if(xn(e))return{result:!1,message:`Notebook file does not exist.`,errorCode:1};throw e}let c=Ea(s);if(!c)return{result:!1,message:`Notebook is not valid JSON.`,errorCode:6};if(!n){if(r!==`insert`)return{result:!1,message:`Cell ID must be specified when not inserting a new cell.`,errorCode:7}}else if(c.cells.findIndex(e=>e.id===n)===-1){let e=Ey(n);if(e!==void 0){if(!c.cells[e])return{result:!1,message:`Cell with index ${e} does not exist in notebook.`,errorCode:7}}else return{result:!1,message:`Cell with ID "${n}" not found in notebook.`,errorCode:8}}return{result:!0}},async call({notebook_path:e,new_source:t,cell_id:n,cell_type:r,edit_mode:i},{readFileState:a,updateFileHistoryState:o},s,c){let l=Yc(e)?e:el(yn(),e);WB()&&await GB(o,l,c.uuid);try{let{content:e,encoding:o,lineEndings:s}=Or(l),c;try{c=kn(e)}catch{return{data:{new_source:t,cell_type:r??`code`,language:`python`,edit_mode:`replace`,error:`Notebook is not valid JSON.`,cell_id:n,notebook_path:l,original_file:``,updated_file:``}}}let u;if(!n)u=0;else{if(u=c.cells.findIndex(e=>e.id===n),u===-1){let e=Ey(n);e!==void 0&&(u=e)}i===`insert`&&(u+=1)}let d=i;d===`replace`&&u===c.cells.length&&(d=`insert`,r||(r=`code`));let f=c.metadata.language_info?.name??`python`,p;if(((c.nbformat??4)>4||(c.nbformat??4)===4&&(c.nbformat_minor??0)>=5)&&(d===`insert`?p=Math.random().toString(36).substring(2,15):n!==null&&(p=n)),d===`delete`)c.cells.splice(u,1);else if(d===`insert`){let e;e=r===`markdown`?{cell_type:`markdown`,id:p,source:t,metadata:{}}:{cell_type:`code`,id:p,source:t,metadata:{},execution_count:null,outputs:[]},c.cells.splice(u,0,e)}else{let e=c.cells[u];e.source=t,e.cell_type===`code`&&(e.execution_count=null,e.outputs=[]),r&&r!==e.cell_type&&(e.cell_type=r)}let m=V(c,null,1);return lr(l,m,o,s),a.set(l,{content:m,timestamp:wr(l),offset:void 0,limit:void 0}),{data:{new_source:t,cell_type:r??`code`,language:f,edit_mode:d??`replace`,cell_id:p||void 0,error:``,notebook_path:l,original_file:e,updated_file:m}}}catch(e){return e instanceof Error?{data:{new_source:t,cell_type:r??`code`,language:`python`,edit_mode:`replace`,error:e.message,cell_id:n,notebook_path:l,original_file:``,updated_file:``}}:{data:{new_source:t,cell_type:r??`code`,language:`python`,edit_mode:`replace`,error:`Unknown error occurred while editing notebook`,cell_id:n,notebook_path:l,original_file:``,updated_file:``}}}}})}));function u8e(){return d8e??(d8e=[ex,QH,xq,fU,lU,SW,Tq,dJ])}var d8e,f8e=n((()=>{fJ(),CW(),Sq(),nx(),$H(),pU(),uU(),Eq()}));function p8e(){return!f(process.env.CLAUDE_CODE_REPL)&&!!m(process.env.CLAUDE_REPL_MODE)}var m8e,Dq=n((()=>{h(),xr(),bs(),Ns(),Fs(),vs(),fs(),ls(),Ps(),m8e=new Set([gs,ks,ws,Us,rs,js,Ls,ur])}));function Oq(e){if(!(!e||typeof e==`string`))return e[0]}function h8e(e){return!e||typeof e==`string`?[]:e}function g8e(e){let t=e;return t?.file_path??t?.path}function _8e(e){let t=e;return t?!!(t.path&&(cv(t.path)||Ube(t.path))||t.glob&&Gbe(t.glob)||t.command&&Wbe(t.command)):!1}function v8e(e,t){if(e!==`Write`&&e!==`Edit`)return!1;let n=g8e(t);return n!==void 0&&cv(n)}function kq(e){let t=`$ `+e.split(`
1639
1639
  `).map(e=>e.replace(/\s+/g,` `).trim()).filter(e=>e!==``).join(`
1640
1640
  `);return t.length>Iq?`${t.slice(0,Iq-1)}…`:t}function Aq(e,t,n){if(e===`REPL`)return{isCollapsible:!0,isSearch:!1,isRead:!1,isList:!1,isREPL:!0,isMemoryWrite:!1,isAbsorbedSilently:!0};if(v8e(e,t))return{isCollapsible:!0,isSearch:!1,isRead:!1,isList:!1,isREPL:!1,isMemoryWrite:!0,isAbsorbedSilently:!1};if(_V()&&e===`SearchExtraTools`)return{isCollapsible:!0,isSearch:!1,isRead:!1,isList:!1,isREPL:!1,isMemoryWrite:!1,isAbsorbedSilently:!0};let r=_s(n,e)??_s(u8e(),e);if(!r?.isSearchOrReadCommand)return{isCollapsible:!1,isSearch:!1,isRead:!1,isList:!1,isREPL:!1,isMemoryWrite:!1,isAbsorbedSilently:!1};let i=r.isSearchOrReadCommand(t),a=i.isList??!1,o=i.isSearch||i.isRead||a;return{isCollapsible:o||(_V()?e===`Bash`:!1),isSearch:i.isSearch,isRead:i.isRead,isList:a,isREPL:!1,isMemoryWrite:!1,isAbsorbedSilently:!1,...r.isMcp&&{mcpServerName:r.mcpInfo?.serverName},isBash:_V()?!o&&e===`Bash`:void 0}}function jq(e,t){if(e?.type===`tool_use`&&e.name){let n=Aq(e.name,e.input,t);if(n.isCollapsible||n.isREPL)return{isSearch:n.isSearch,isRead:n.isRead,isList:n.isList,isREPL:n.isREPL,isMemoryWrite:n.isMemoryWrite,isAbsorbedSilently:n.isAbsorbedSilently,mcpServerName:n.mcpServerName,isBash:n.isBash}}return null}function Mq(e,t,n){return Aq(e,t,n).isCollapsible}function y8e(e,t){if(e.type===`assistant`){let n=Oq(e.message?.content);if(!n)return null;let r=jq(n,t);if(r&&n.type===`tool_use`){let e=n;return{name:e.name,input:e.input,...r}}}if(e.type===`grouped_tool_use`){let n=Oq(e.messages[0]?.message?.content),r=n,i=jq(r?{type:`tool_use`,name:e.toolName,input:r.input}:void 0,t);if(i&&n&&n.type===`tool_use`)return{name:e.toolName,input:r?.input,...i}}return null}function b8e(e){if(e.type===`assistant`){let t=Oq(e.message?.content);if(t&&t.type===`text`&&t.text.trim().length>0)return!0}return!1}function x8e(e,t){if(e.type===`assistant`){let n=Oq(e.message?.content);if(n&&n.type===`tool_use`&&!Mq(n.name,n.input,t))return!0}if(e.type===`grouped_tool_use`){let n=Oq(e.messages[0]?.message?.content);if(n&&n.type===`tool_use`&&!Mq(e.toolName,n.input,t))return!0}return!1}function S8e(e){return e.type===`system`&&e.subtype===`stop_hook_summary`&&e.hookLabel===`PreToolUse`}function C8e(e){if(e.type===`assistant`){let t=Oq(e.message?.content);if(t&&(t.type===`thinking`||t.type===`redacted_thinking`))return!0}return e.type===`attachment`||e.type===`system`}function w8e(e,t){if(e.type===`assistant`){let n=Oq(e.message?.content);return n!==void 0&&n.type===`tool_use`&&Mq(n.name,n.input,t)}if(e.type===`grouped_tool_use`){let n=Oq(e.messages[0]?.message?.content);return n!==void 0&&n.type===`tool_use`&&Mq(e.toolName,n.input,t)}return!1}function T8e(e,t){if(e.type===`user`){let n=h8e(e.message?.content).filter(e=>e.type===`tool_result`);return n.length>0&&n.every(e=>t.has(e.tool_use_id))}return!1}function Nq(e){if(e.type===`assistant`){let t=Oq(e.message?.content);if(t&&t.type===`tool_use`)return[t.id]}return e.type===`grouped_tool_use`?e.messages.map(e=>{let t=Oq(e.message?.content);return t&&t.type===`tool_use`?t.id:``}).filter(Boolean):[]}function Pq(e){let t=[];for(let n of e.messages)t.push(...Nq(n));return t}function E8e(e,t){return Pq(e).some(e=>t.has(e))}function D8e(e){let t=e.displayMessage;return t.type===`grouped_tool_use`?t.displayMessage:t}function Fq(e){return e.type===`grouped_tool_use`?e.messages.length:1}function O8e(e){let t=[];if(e.type===`assistant`){let n=Oq(e.message?.content);if(n&&n.type===`tool_use`){let e=n.input;e?.file_path&&t.push(e.file_path)}}else if(e.type===`grouped_tool_use`)for(let n of e.messages){let e=Oq(n.message?.content);if(e&&e.type===`tool_use`){let n=e.input;n?.file_path&&t.push(n.file_path)}}return t}function k8e(e,t){if(e.type!==`user`)return;let n=e.toolUseResult;if(!n?.stdout&&!n?.stderr)return;let r=`${n.stdout??``}\n${n.stderr??``}`;for(let n of h8e(e.message?.content)){if(n.type!==`tool_result`)continue;let e=n,i=t.bashCommands?.get(e.tool_use_id);if(!i)continue;let{commit:a,push:o,branch:s,pr:c}=qqe(i,r);a&&t.commits?.push(a),o&&t.pushes?.push(o),s&&t.branches?.push(s),c&&t.prs?.push(c),(a||o||s||c)&&(t.gitOpBashCount=(t.gitOpBashCount??0)+1)}}function A8e(){let e={messages:[],searchCount:0,readFilePaths:new Set,readOperationCount:0,listCount:0,toolUseIds:new Set,memorySearchCount:0,memoryReadFilePaths:new Set,memoryWriteCount:0,nonMemSearchArgs:[],latestDisplayHint:void 0,hookTotalMs:0,hookCount:0,hookInfos:[]};return e.mcpCallCount=0,e.mcpServerNames=new Set,_V()&&(e.bashCount=0,e.bashCommands=new Map,e.commits=[],e.pushes=[],e.branches=[],e.prs=[],e.gitOpBashCount=0),e}function j8e(e){let t=e.messages[0],n=e.readFilePaths.size>0?e.readFilePaths.size:e.readOperationCount,r=e.memoryReadFilePaths.size,i=r+(e.relevantMemories?.length??0),a=[...e.readFilePaths].filter(t=>!e.memoryReadFilePaths.has(t)),o={type:`collapsed_read_search`,searchCount:Math.max(0,e.searchCount-e.memorySearchCount),readCount:Math.max(0,n-r),listCount:e.listCount,replCount:0,memorySearchCount:e.memorySearchCount,memoryReadCount:i,memoryWriteCount:e.memoryWriteCount,readFilePaths:a,searchArgs:e.nonMemSearchArgs,latestDisplayHint:e.latestDisplayHint,messages:e.messages,displayMessage:t,uuid:`collapsed-${t.uuid}`,timestamp:t.timestamp};return(e.mcpCallCount??0)>0&&(o.mcpCallCount=e.mcpCallCount,o.mcpServerNames=[...e.mcpServerNames??[]]),_V()&&((e.bashCount??0)>0&&(o.bashCount=e.bashCount,o.gitOpBashCount=e.gitOpBashCount),(e.commits?.length??0)>0&&(o.commits=e.commits),(e.pushes?.length??0)>0&&(o.pushes=e.pushes),(e.branches?.length??0)>0&&(o.branches=e.branches),(e.prs?.length??0)>0&&(o.prs=e.prs)),e.hookCount>0&&(o.hookTotalMs=e.hookTotalMs,o.hookCount=e.hookCount,o.hookInfos=e.hookInfos),e.relevantMemories&&e.relevantMemories.length>0&&(o.relevantMemories=e.relevantMemories),o}function M8e(e,t){let n=[],r=A8e(),i=[];function a(){if(r.messages.length!==0){n.push(j8e(r));for(let e of i)n.push(e);i=[],r=A8e()}}for(let s of e)if(w8e(s,t)){let e=y8e(s,t);if(e.isMemoryWrite)r.memoryWriteCount+=Fq(s);else if(!e.isAbsorbedSilently)if(e.mcpServerName){let t=Fq(s);r.mcpCallCount=(r.mcpCallCount??0)+t,r.mcpServerNames?.add(e.mcpServerName);let n=e.input;n?.query&&(r.latestDisplayHint=`"${n.query}"`)}else if(_V()&&e.isBash){let t=Fq(s);r.bashCount=(r.bashCount??0)+t;let n=e.input;if(n?.command){r.latestDisplayHint=kQe(n.command)??kq(n.command);for(let e of Nq(s))r.bashCommands?.set(e,n.command)}}else if(e.isList){r.listCount+=Fq(s);let t=e.input;t?.command&&(r.latestDisplayHint=kq(t.command))}else if(e.isSearch){let t=Fq(s);if(r.searchCount+=t,_8e(e.input))r.memorySearchCount+=t;else{let t=e.input;t?.pattern&&(r.nonMemSearchArgs.push(t.pattern),r.latestDisplayHint=`"${t.pattern}"`)}}else{let t=O8e(s);for(let e of t)r.readFilePaths.add(e),cv(e)?r.memoryReadFilePaths.add(e):r.latestDisplayHint=ui(e);if(t.length===0){r.readOperationCount+=Fq(s);let t=e.input;t?.command&&(r.latestDisplayHint=kq(t.command))}}for(let e of Nq(s))r.toolUseIds.add(e);r.messages.push(s)}else if(T8e(s,r.toolUseIds))r.messages.push(s),_V()&&r.bashCommands?.size&&k8e(s,r);else if(r.messages.length>0&&S8e(s))r.hookCount+=s.hookCount,r.hookTotalMs+=s.totalDurationMs??s.hookInfos.reduce((e,t)=>e+(t.durationMs??0),0),r.hookInfos.push(...s.hookInfos);else if(r.messages.length>0&&s.type===`attachment`&&s.attachment.type===`relevant_memories`){var o;(o=r).relevantMemories??(o.relevantMemories=[]),r.relevantMemories.push(...s.attachment.memories??[])}else C8e(s)?r.messages.length>0&&!(s.type===`attachment`&&s.attachment.type===`nested_memory`)?i.push(s):n.push(s):(b8e(s)||x8e(s,t),a(),n.push(s));return a(),n}function N8e(e,t,n,r=0,i,a=0){let o=[];if(i){let{memorySearchCount:e,memoryReadCount:t,memoryWriteCount:r}=i;if(t>0){let e=n?o.length===0?`Recalling`:`recalling`:o.length===0?`Recalled`:`recalled`;o.push(`${e} ${t} ${t===1?`memory`:`memories`}`)}if(e>0){let e=n?o.length===0?`Searching`:`searching`:o.length===0?`Searched`:`searched`;o.push(`${e} memories`)}if(r>0){let e=n?o.length===0?`Writing`:`writing`:o.length===0?`Wrote`:`wrote`;o.push(`${e} ${r} ${r===1?`memory`:`memories`}`)}}if(e>0){let t=n?o.length===0?`Searching for`:`searching for`:o.length===0?`Searched for`:`searched for`;o.push(`${t} ${e} ${e===1?`pattern`:`patterns`}`)}if(t>0){let e=n?o.length===0?`Reading`:`reading`:o.length===0?`Read`:`read`;o.push(`${e} ${t} ${t===1?`file`:`files`}`)}if(a>0){let e=n?o.length===0?`Listing`:`listing`:o.length===0?`Listed`:`listed`;o.push(`${e} ${a} ${a===1?`directory`:`directories`}`)}if(r>0){let e=n?`REPL'ing`:`REPL'd`;o.push(`${e} ${r} ${r===1?`time`:`times`}`)}let s=o.join(`, `);return n?`${s}…`:s}var Iq,Lq=n((()=>{Ks(),AQe(),bs(),Ns(),vs(),Dq(),f8e(),SH(),zs(),ci(),xV(),uv(),Iq=300}));function P8e({number:e,url:t,reviewState:n,bold:r}){let i=F8e(n);return(0,Rq.jsxs)(F,{children:[(0,Rq.jsx)(F,{dimColor:!r,children:`PR`}),` `,(0,Rq.jsx)(Te,{url:t,fallback:(0,Rq.jsxs)(F,{color:i,dimColor:!i&&!r,bold:r,children:[`#`,e]}),children:(0,Rq.jsxs)(F,{color:i,dimColor:!i&&!r,underline:!0,bold:r,children:[`#`,e]})})]})}function F8e(e){switch(e){case`approved`:return`success`;case`changes_requested`:return`error`;case`pending`:return`warning`;case`merged`:return`merged`;default:return}}var Rq,I8e=n((()=>{I(),Rq=et()}));function L8e({content:e,tools:t,lookups:n,inProgressToolUseIDs:r,shouldAnimate:i,theme:a}){let o=pb(),s=_s(t,e.name)??_s(u8e(),e.name);if(!s)return null;let c=n.resolvedToolUseIDs.has(e.id),l=n.erroredToolUseIDs.has(e.id),u=r.has(e.id),d=n.toolResultByToolUseID.get(e.id),f=d?.type===`user`?d.toolUseResult:void 0,p=s.outputSchema?.safeParse(f),m=p?.success?p.data:void 0,h=s.inputSchema.safeParse(e.input),g=h.success?h.data:void 0,_=s.userFacingName(g),v=g?s.renderToolUseMessage(g,{theme:a,verbose:!0}):null;return(0,Bq.jsxs)(P,{flexDirection:`column`,marginTop:1,backgroundColor:o,children:[(0,Bq.jsxs)(P,{flexDirection:`row`,children:[(0,Bq.jsx)(VK,{shouldAnimate:i&&u,isUnresolved:!c,isError:l}),(0,Bq.jsxs)(F,{children:[(0,Bq.jsx)(F,{bold:!0,children:_}),v&&(0,Bq.jsxs)(F,{children:[`(`,v,`)`]})]}),g&&s.renderToolUseTag?.(g)]}),c&&!l&&m!==void 0&&(0,Bq.jsx)(P,{children:s.renderToolResultMessage?.(m,[],{verbose:!0,tools:t,theme:a})})]},e.id)}function R8e({message:e,inProgressToolUseIDs:t,shouldAnimate:n,verbose:r,tools:i,lookups:a,isActiveGroup:o}){let s=pb(),{searchCount:c,readCount:l,listCount:u,replCount:d,memorySearchCount:f,memoryReadCount:p,memoryWriteCount:m,messages:h}=e,[g]=xe(),_=Pq(e),v=_.some(e=>a.erroredToolUseIDs.has(e)),y=f>0||p>0||m>0,b=(0,zq.useRef)(0),x=(0,zq.useRef)(0),S=(0,zq.useRef)(0),C=(0,zq.useRef)(0),w=(0,zq.useRef)(0);b.current=Math.max(b.current,l),x.current=Math.max(x.current,c),S.current=Math.max(S.current,u),C.current=Math.max(C.current,e.mcpCallCount??0),w.current=Math.max(w.current,e.bashCount??0);let T=b.current,E=x.current,D=S.current,O=C.current,k=e.gitOpBashCount??0,A=_V()?Math.max(0,w.current-k):0,ee=E>0||T>0||D>0||d>0||O>0||A>0||k>0,te=e.readFilePaths,ne=e.searchArgs,re=e.latestDisplayHint;if(re===void 0){let e=ne?.at(-1),t=e===void 0?void 0:`"${e}"`,n=te?.at(-1);re=n===void 0?t:ui(n)}if(o)for(let e of _){if(!t.has(e))continue;let n=a.progressMessagesByToolUseID.get(e)?.at(-1)?.data;if(n?.type===`repl_tool_call`&&n.phase===`start`){let e=n.toolInput;re=e.file_path??(e.pattern?`"${e.pattern}"`:void 0)??e.command??n.toolName}}let ie=cee(re,z8e);if(r){let r=[];for(let e of h)e.type===`assistant`?r.push(e):e.type===`grouped_tool_use`&&r.push(...e.messages);return(0,Bq.jsxs)(P,{flexDirection:`column`,children:[r.map(e=>{let r=e.message.content[0];return r?.type===`tool_use`?(0,Bq.jsx)(L8e,{content:r,tools:i,lookups:a,inProgressToolUseIDs:t,shouldAnimate:n,theme:g},r.id):null}),e.hookInfos&&e.hookInfos.length>0&&(0,Bq.jsxs)(Bq.Fragment,{children:[(0,Bq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Ran `,e.hookCount,` PreToolUse `,e.hookCount===1?`hook`:`hooks`,` (`,Fa(e.hookTotalMs??0),`)`]}),e.hookInfos.map((e,t)=>(0,Bq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,e.command,` (`,Fa(e.durationMs??0),`)`]},`hook-${t}`))]}),e.relevantMemories?.map(e=>(0,Bq.jsxs)(P,{flexDirection:`column`,marginTop:1,children:[(0,Bq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Recalled `,Kc(e.path)]}),(0,Bq.jsx)(P,{paddingLeft:5,children:(0,Bq.jsx)(F,{children:(0,Bq.jsx)(_e,{children:e.content})})})]},e.path))]})}if(!y&&!ee)return null;let ae=``;if(_V()&&o){let e,n=0;for(let r of _){if(!t.has(r))continue;let i=a.progressMessagesByToolUseID.get(r)?.at(-1)?.data;if(i?.type!==`bash_progress`&&i?.type!==`powershell_progress`)continue;let o=i.elapsedTimeSeconds,s=i.totalLines;(e===void 0||(o??0)>e)&&(e=o,n=s??0)}if(e!==void 0&&e>=2){let t=La(e*1e3);ae=n>0?` (${t} · ${n} ${n===1?`line`:`lines`})`:` (${t})`}}let j=[];function oe(e,t,n){let r=j.length===0;r||j.push((0,Bq.jsx)(F,{children:`, `},`comma-${e}`)),j.push((0,Bq.jsxs)(F,{children:[r?t[0].toUpperCase()+t.slice(1):t,` `,n]},e))}if(_V()&&e.commits?.length){let t={committed:`committed`,amended:`amended commit`,"cherry-picked":`cherry-picked`};for(let n of[`committed`,`amended`,`cherry-picked`]){let r=e.commits.filter(e=>e.kind===n).map(e=>e.sha);r.length&&oe(n,t[n],(0,Bq.jsx)(F,{bold:!0,children:r.join(`, `)}))}}if(_V()&&e.pushes?.length&&oe(`push`,`pushed to`,(0,Bq.jsx)(F,{bold:!0,children:Qn(e.pushes.map(e=>e.branch)).join(`, `)})),_V()&&e.branches?.length){let t={merged:`merged`,rebased:`rebased onto`};for(let n of e.branches)oe(`br-${n.action}-${n.ref}`,t[n.action],(0,Bq.jsx)(F,{bold:!0,children:n.ref}))}if(_V()&&e.prs?.length){let t={created:`created`,edited:`edited`,merged:`merged`,commented:`commented on`,closed:`closed`,ready:`marked ready`};for(let n of e.prs)oe(`pr-${n.action}-${n.number}`,t[n.action],n.url?(0,Bq.jsx)(P8e,{number:n.number,url:n.url,bold:!0}):(0,Bq.jsxs)(F,{bold:!0,children:[`PR #`,n.number]}))}if(E>0){let e=j.length===0,t=o?e?`Searching for`:`searching for`:e?`Searched for`:`searched for`;e||j.push((0,Bq.jsx)(F,{children:`, `},`comma-s`)),j.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:E}),` `,E===1?`pattern`:`patterns`]},`search`))}if(T>0){let e=j.length===0,t=o?e?`Reading`:`reading`:e?`Read`:`read`;e||j.push((0,Bq.jsx)(F,{children:`, `},`comma-r`)),j.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:T}),` `,T===1?`file`:`files`]},`read`))}if(D>0){let e=j.length===0,t=o?e?`Listing`:`listing`:e?`Listed`:`listed`;e||j.push((0,Bq.jsx)(F,{children:`, `},`comma-l`)),j.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:D}),` `,D===1?`directory`:`directories`]},`list`))}if(d>0){let e=o?`REPL'ing`:`REPL'd`;j.length>0&&j.push((0,Bq.jsx)(F,{children:`, `},`comma-repl`)),j.push((0,Bq.jsxs)(F,{children:[e,` `,(0,Bq.jsx)(F,{bold:!0,children:d}),` `,d===1?`time`:`times`]},`repl`))}if(O>0){let t=e.mcpServerNames?.map(e=>e.replace(/^claude\.ai /,``)).join(`, `)||`MCP`,n=j.length===0,r=o?n?`Querying`:`querying`:n?`Queried`:`queried`;n||j.push((0,Bq.jsx)(F,{children:`, `},`comma-mcp`)),j.push((0,Bq.jsxs)(F,{children:[r,` `,t,O>1&&(0,Bq.jsxs)(Bq.Fragment,{children:[` `,(0,Bq.jsx)(F,{bold:!0,children:O}),` times`]})]},`mcp`))}if(_V()&&A>0){let e=j.length===0,t=o?e?`Running`:`running`:e?`Ran`:`ran`;e||j.push((0,Bq.jsx)(F,{children:`, `},`comma-bash`)),j.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:A}),` bash `,A===1?`command`:`commands`]},`bash`))}let se=j.length>0,ce=[];if(p>0){let e=!se&&ce.length===0,t=o?e?`Recalling`:`recalling`:e?`Recalled`:`recalled`;e||ce.push((0,Bq.jsx)(F,{children:`, `},`comma-mr`)),ce.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:p}),` `,p===1?`memory`:`memories`]},`mem-read`))}if(f>0){let e=!se&&ce.length===0,t=o?e?`Searching`:`searching`:e?`Searched`:`searched`;e||ce.push((0,Bq.jsx)(F,{children:`, `},`comma-ms`)),ce.push((0,Bq.jsx)(F,{children:`${t} memories`},`mem-search`))}if(m>0){let e=!se&&ce.length===0,t=o?e?`Writing`:`writing`:e?`Wrote`:`wrote`;e||ce.push((0,Bq.jsx)(F,{children:`, `},`comma-mw`)),ce.push((0,Bq.jsxs)(F,{children:[t,` `,(0,Bq.jsx)(F,{bold:!0,children:m}),` `,m===1?`memory`:`memories`]},`mem-write`))}return(0,Bq.jsxs)(P,{flexDirection:`column`,marginTop:1,backgroundColor:s,children:[(0,Bq.jsxs)(P,{flexDirection:`row`,children:[o?(0,Bq.jsx)(VK,{shouldAnimate:!0,isUnresolved:!0,isError:v}):(0,Bq.jsx)(P,{minWidth:2}),(0,Bq.jsxs)(F,{dimColor:!o,children:[j,ce,o&&(0,Bq.jsx)(F,{children:`…`},`ellipsis`),` `,(0,Bq.jsx)(Eb,{})]})]}),o&&ie!==void 0&&(0,Bq.jsxs)(P,{flexDirection:`row`,children:[(0,Bq.jsx)(P,{width:5,flexShrink:0,children:(0,Bq.jsx)(F,{dimColor:!0,children:` ⎿ `})}),(0,Bq.jsx)(P,{flexDirection:`column`,flexGrow:1,children:ie.split(`
1641
- `).map((e,t,n)=>(0,Bq.jsxs)(F,{dimColor:!0,children:[e,t===n.length-1&&ae]},`hint-${t}`))})]}),e.hookTotalMs!==void 0&&e.hookTotalMs>0&&(0,Bq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Ran `,e.hookCount,` PreToolUse `,e.hookCount===1?`hook`:`hooks`,` (`,Fa(e.hookTotalMs),`)`]})]})}var zq,Bq,z8e,B8e=n((()=>{zq=r(ze(),1),U6e(),I(),Ks(),f8e(),Cr(),Lq(),ci(),Ba(),xV(),Ab(),wb(),I8e(),UK(),Bq=et(),z8e=700}));function V8e(){return(0,Vq.jsx)(P,{marginY:1,children:(0,Vq.jsxs)(F,{dimColor:!0,children:[`✻ Conversation compacted (`,sb(`app:toggleTranscript`,`Global`,`ctrl+o`),` for history)`]})})}var Vq,H8e=n((()=>{I(),lb(),Vq=et()}));function U8e({message:e,tools:t,lookups:n,inProgressToolUseIDs:r,shouldAnimate:i}){let a=_s(t,e.toolName);if(!a?.renderGroupedToolUse)return null;let o=new Map;for(let t of e.results)for(let e of t.message?.content??[]){let n=e;n.type===`tool_result`&&o.set(n.tool_use_id,{param:n,output:t.toolUseResult})}let s=e.messages.map(e=>{let t=(e.message?.content??[])[0],i=t.id,a=o.get(i);return{param:t,isResolved:n.resolvedToolUseIDs.has(i),isError:n.erroredToolUseIDs.has(i),isInProgress:r.has(i),progressMessages:Ds(n.progressMessagesByToolUseID.get(i)??[]),result:a}}),c=s.some(e=>e.isInProgress);return a.renderGroupedToolUse(s,{shouldAnimate:i&&c,tools:t})}var W8e=n((()=>{Ks()})),G8e,K8e=n((()=>{G8e=[`Baked`,`Brewed`,`Churned`,`Cogitated`,`Cooked`,`Crunched`,`Sautéed`,`Worked`]}));function q8e({message:{retryAttempt:e,error:t,retryInMs:n,maxRetries:r},verbose:i}){let a=e,o=n,s=r,c=t,l=a<4,[u,d]=(0,J8e.useState)(0);if(Be(()=>d(e=>e+1e3),l||u>=o?null:1e3),l)return null;let f=Math.max(0,Math.round((o-u)/1e3)),p=Ise(c),m=!i&&p.length>Uq;return(0,Hq.jsx)(Z,{children:(0,Hq.jsxs)(P,{flexDirection:`column`,children:[(0,Hq.jsx)(F,{color:`error`,children:m?`${p.slice(0,Uq)}…`:p}),m&&(0,Hq.jsx)(Eb,{}),(0,Hq.jsxs)(F,{dimColor:!0,children:[`Retrying in `,f,` `,f===1?`second`:`seconds`,`… (attempt `,a,`/`,s,`)`,process.env.API_TIMEOUT_MS?` · API_TIMEOUT_MS=${process.env.API_TIMEOUT_MS}ms, try increasing it`:``]})]})})}var J8e,Hq,Uq,Y8e=n((()=>{J8e=r(ze(),1),I(),ec(),hee(),Ab(),Rb(),Hq=et(),Uq=1e3})),X8e=n((()=>{I()}));function Z8e(e){return!(e.status!==`running`&&e.status!==`pending`||`isBackgrounded`in e&&e.isBackgrounded===!1)}var Q8e=n((()=>{}));function $8e(e){let t=e.length;if(e.every(t=>t.type===e[0].type))switch(e[0].type){case`local_bash`:return t===1?`1 shell`:`${t} shells`;case`local_agent`:return t===1?`1 local agent`:`${t} local agents`;case`remote_agent`:return e[0],t===1?`◇ 1 cloud session`:`◇ ${t} cloud sessions`;case`local_workflow`:return t===1?`1 background workflow`:`${t} background workflows`;case`dream`:return`dreaming`}return`${t} background ${t===1?`task`:`tasks`}`}function e5e(e){return!1}var t5e=n((()=>{Dr()}));function n5e({message:e,addMargin:t,verbose:n,isTranscriptMode:r}){let i=pb();if(e.subtype===`turn_duration`)return(0,Gq.jsx)(a5e,{message:e,addMargin:t});if(e.subtype===`memory_saved`)return(0,Gq.jsx)(o5e,{message:e,addMargin:t});if(e.subtype===`away_summary`)return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:`※`})}),(0,Gq.jsx)(F,{dimColor:!0,children:String(e.content??``)})]});if(e.subtype===`agents_killed`)return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{color:`error`,children:sr})}),(0,Gq.jsx)(F,{dimColor:!0,children:`All background agents stopped`})]});if(e.subtype===`thinking`)return null;if(e.subtype===`bridge_status`)return(0,Gq.jsx)(c5e,{message:e,addMargin:t});if(e.subtype===`permission_retry`)return(0,Gq.jsxs)(P,{marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsxs)(F,{dimColor:!0,children:[`✻`,` `]}),(0,Gq.jsx)(F,{children:`Allowed `}),(0,Gq.jsx)(F,{bold:!0,children:e.commands.join(`, `)})]});if(e.subtype!==`stop_hook_summary`&&!n&&e.level===`info`)return null;if(e.subtype===`api_error`)return(0,Gq.jsx)(q8e,{message:e,verbose:n});if(e.subtype===`stop_hook_summary`)return(0,Gq.jsx)(r5e,{message:e,addMargin:t,verbose:n,isTranscriptMode:r});let a=e.content;return typeof a==`string`?(0,Gq.jsx)(P,{flexDirection:`row`,width:`100%`,children:(0,Gq.jsx)(i5e,{content:a,addMargin:t,dot:e.level!==`info`,color:e.level===`warning`?`warning`:void 0,dimColor:e.level===`info`})}):null}function r5e({message:e,addMargin:t,verbose:n,isTranscriptMode:r}){let i=pb(),{hookCount:a,hookInfos:o}=e,s=e.hookErrors??[],c=e.preventedContinuation,l=e.stopReason,{columns:u}=Xe();return s.length===0&&!c&&!e.hookLabel?null:e.hookLabel?(0,Gq.jsxs)(P,{flexDirection:`column`,width:`100%`,children:[(0,Gq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Ran `,a,` `,e.hookLabel,` `,a===1?`hook`:`hooks`]}),r&&o.map((e,t)=>(0,Gq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,e.command===`prompt`?`prompt: ${e.promptText||``}`:e.command]},`cmd-${t}`))]}):(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{children:sr})}),(0,Gq.jsxs)(P,{flexDirection:`column`,width:u-10,children:[(0,Gq.jsxs)(F,{children:[`Ran `,(0,Gq.jsx)(F,{bold:!0,children:a}),` `,e.hookLabel??`stop`,` `,a===1?`hook`:`hooks`,!n&&o.length>0&&(0,Gq.jsxs)(Gq.Fragment,{children:[` `,(0,Gq.jsx)(Eb,{})]})]}),n&&o.length>0&&o.map((e,t)=>(0,Gq.jsxs)(F,{dimColor:!0,children:[`⎿ \xA0`,e.command===`prompt`?`prompt: ${e.promptText||``}`:e.command]},`cmd-${t}`)),c&&l&&(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{dimColor:!0,children:`⎿ \xA0`}),l]}),s.length>0&&s.map((t,n)=>(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{dimColor:!0,children:`⎿ \xA0`}),e.hookLabel??`Stop`,` hook error: `,t]},n))]})]})}function i5e({content:e,addMargin:t,dot:n,color:r,dimColor:i}){let{columns:a}=Xe(),o=pb();return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:o,width:`100%`,children:[n&&(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{color:r,dimColor:i,children:sr})}),(0,Gq.jsx)(P,{flexDirection:`column`,width:a-10,children:(0,Gq.jsx)(F,{color:r,dimColor:i,wrap:`wrap`,children:e.trim()})})]})}function a5e({message:e,addMargin:t}){let n=pb(),[r]=(0,Wq.useState)(()=>ch(G8e)??`Worked`),i=lV(),[a]=(0,Wq.useState)(()=>{let e=i.getState().tasks,t=Object.values(e??{}).filter(Z8e);return t.length>0?$8e(t):null}),o=yi().showTurnDuration??!0,s=La(e.durationMs),c=e.budgetLimit!==void 0,l=(()=>{if(!c)return``;let t=e.budgetTokens,n=e.budgetLimit,r=t>=n?`${Pa(t)} used (${Pa(n)} min ${ie.tick})`:`${Pa(t)} / ${Pa(n)} (${Math.round(t/n*100)}%)`,i=e.budgetNudges>0?` \u00B7 ${e.budgetNudges} ${e.budgetNudges===1?`nudge`:`nudges`}`:``;return`${o?` · `:``}${r}${i}`})();return!o&&!c?null:(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:n,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:`✻`})}),(0,Gq.jsxs)(F,{dimColor:!0,children:[o&&`${r} for ${s}`,l,a&&` \u00B7 ${a} still running`]})]})}function o5e({message:e,addMargin:t}){let n=pb(),r=e.writtenPaths??[],i=r.length,a=[i>0?`${i} ${i===1?`memory`:`memories`}`:null].filter(Boolean);return(0,Gq.jsxs)(P,{flexDirection:`column`,marginTop:+!!t,backgroundColor:n,children:[(0,Gq.jsxs)(P,{flexDirection:`row`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:sr})}),(0,Gq.jsxs)(F,{children:[e.verb??`Saved`,` `,a.join(` · `)]})]}),r.map(e=>(0,Gq.jsx)(s5e,{path:e},e))]})}function s5e({path:e}){let[t,n]=(0,Wq.useState)(!1);return(0,Gq.jsx)(Z,{children:(0,Gq.jsx)(P,{onClick:()=>void gke(e),onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:(0,Gq.jsx)(F,{dimColor:!t,underline:t,children:(0,Gq.jsx)(qb,{filePath:e,children:Kc(e)})})})})}function c5e({message:e,addMargin:t}){let n=pb(),r=e.url,i=e.upgradeNudge;return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:n,width:999,children:[(0,Gq.jsx)(P,{minWidth:2}),(0,Gq.jsxs)(P,{flexDirection:`column`,children:[(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{color:`suggestion`,children:`/remote-control`}),` is active. Code in CLI or at`]}),(0,Gq.jsx)(Te,{url:r,children:r}),i&&(0,Gq.jsxs)(F,{dimColor:!0,children:[`⎿ `,i]})]})]})}var Wq,Gq,l5e=n((()=>{I(),Jb(),Wq=r(ze(),1),lh(),Dr(),ne(),Rb(),zw(),K8e(),eb(),Y8e(),Ba(),bi(),X8e(),Ab(),mV(),Q8e(),t5e(),wb(),Gq=et()}));function u5e(){return(0,Kq.jsx)(Z,{height:1,children:(0,Kq.jsx)(vK,{})})}var Kq,d5e=n((()=>{bK(),Rb(),Kq=et()}));function f5e({plan:e}){return(0,qq.jsx)(Z,{children:(0,qq.jsxs)(P,{flexDirection:`column`,children:[(0,qq.jsx)(F,{color:`subtle`,children:`User rejected Claude's plan:`}),(0,qq.jsx)(P,{borderStyle:`round`,borderColor:`planMode`,paddingX:1,overflow:`hidden`,children:(0,qq.jsx)(PK,{children:e})})]})})}var qq,p5e=n((()=>{zK(),Rb(),I(),qq=et()}));function m5e(){return(0,Jq.jsx)(Z,{height:1,children:(0,Jq.jsx)(F,{dimColor:!0,children:`Tool use rejected`})})}var Jq,h5e=n((()=>{I(),Rb(),Jq=et()}));function g5e({progressMessagesForMessage:e,tool:t,tools:n,param:r,verbose:i,isTranscriptMode:a}){return typeof r.content==`string`&&r.content.includes(`[Request interrupted by user for tool use]`)?(0,Yq.jsx)(Z,{height:1,children:(0,Yq.jsx)(vK,{})}):typeof r.content==`string`&&r.content.startsWith(`The agent proposed a plan that was rejected by the user. The user chose to stay in plan mode rather than proceed with implementation.
1641
+ `).map((e,t,n)=>(0,Bq.jsxs)(F,{dimColor:!0,children:[e,t===n.length-1&&ae]},`hint-${t}`))})]}),e.hookTotalMs!==void 0&&e.hookTotalMs>0&&(0,Bq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Ran `,e.hookCount,` PreToolUse `,e.hookCount===1?`hook`:`hooks`,` (`,Fa(e.hookTotalMs),`)`]})]})}var zq,Bq,z8e,B8e=n((()=>{zq=r(ze(),1),U6e(),I(),Ks(),f8e(),Cr(),Lq(),ci(),Ba(),xV(),Ab(),wb(),I8e(),UK(),Bq=et(),z8e=700}));function V8e(){return(0,Vq.jsx)(P,{marginY:1,children:(0,Vq.jsxs)(F,{dimColor:!0,children:[`✻ Conversation compacted (`,sb(`app:toggleTranscript`,`Global`,`ctrl+o`),` for history)`]})})}var Vq,H8e=n((()=>{I(),lb(),Vq=et()}));function U8e({message:e,tools:t,lookups:n,inProgressToolUseIDs:r,shouldAnimate:i}){let a=_s(t,e.toolName);if(!a?.renderGroupedToolUse)return null;let o=new Map;for(let t of e.results)for(let e of t.message?.content??[]){let n=e;n.type===`tool_result`&&o.set(n.tool_use_id,{param:n,output:t.toolUseResult})}let s=e.messages.map(e=>{let t=(e.message?.content??[])[0],i=t.id,a=o.get(i);return{param:t,isResolved:n.resolvedToolUseIDs.has(i),isError:n.erroredToolUseIDs.has(i),isInProgress:r.has(i),progressMessages:Ds(n.progressMessagesByToolUseID.get(i)??[]),result:a}}),c=s.some(e=>e.isInProgress);return a.renderGroupedToolUse(s,{shouldAnimate:i&&c,tools:t})}var W8e=n((()=>{Ks()})),G8e,K8e=n((()=>{G8e=[`Baked`,`Brewed`,`Churned`,`Cogitated`,`Cooked`,`Crunched`,`Sautéed`,`Worked`]}));function q8e({message:{retryAttempt:e,error:t,retryInMs:n,maxRetries:r},verbose:i}){let a=e,o=n,s=r,c=t,l=a<4,[u,d]=(0,J8e.useState)(0);if(Be(()=>d(e=>e+1e3),l||u>=o?null:1e3),l)return null;let f=Math.max(0,Math.round((o-u)/1e3)),p=Ise(c),m=!i&&p.length>Uq;return(0,Hq.jsx)(Z,{children:(0,Hq.jsxs)(P,{flexDirection:`column`,children:[(0,Hq.jsx)(F,{color:`error`,children:m?`${p.slice(0,Uq)}…`:p}),m&&(0,Hq.jsx)(Eb,{}),(0,Hq.jsxs)(F,{dimColor:!0,children:[`Retrying in `,f,` `,f===1?`second`:`seconds`,`… (attempt `,a,`/`,s,`)`,process.env.API_TIMEOUT_MS?` · API_TIMEOUT_MS=${process.env.API_TIMEOUT_MS}ms, try increasing it`:``]})]})})}var J8e,Hq,Uq,Y8e=n((()=>{J8e=r(ze(),1),I(),ec(),hee(),Ab(),Rb(),Hq=et(),Uq=1e3})),X8e=n((()=>{I()}));function Z8e(e){return!(e.status!==`running`&&e.status!==`pending`||`isBackgrounded`in e&&e.isBackgrounded===!1)}var Q8e=n((()=>{}));function $8e(e){let t=e.length;if(e.every(t=>t.type===e[0].type))switch(e[0].type){case`local_bash`:return t===1?`1 shell`:`${t} shells`;case`local_agent`:return t===1?`1 local agent`:`${t} local agents`;case`remote_agent`:return e[0],t===1?`◇ 1 cloud session`:`◇ ${t} cloud sessions`;case`local_workflow`:return t===1?`1 background workflow`:`${t} background workflows`;case`dream`:return`dreaming`}return`${t} background ${t===1?`task`:`tasks`}`}function e5e(e){return!1}var t5e=n((()=>{Dr()}));function n5e({message:e,addMargin:t,verbose:n,isTranscriptMode:r}){let i=pb();if(e.subtype===`turn_duration`)return(0,Gq.jsx)(a5e,{message:e,addMargin:t});if(e.subtype===`memory_saved`)return(0,Gq.jsx)(o5e,{message:e,addMargin:t});if(e.subtype===`away_summary`)return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:`※`})}),(0,Gq.jsx)(F,{dimColor:!0,children:String(e.content??``)})]});if(e.subtype===`agents_killed`)return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{color:`error`,children:sr})}),(0,Gq.jsx)(F,{dimColor:!0,children:`All background agents stopped`})]});if(e.subtype===`thinking`)return null;if(e.subtype===`bridge_status`)return(0,Gq.jsx)(c5e,{message:e,addMargin:t});if(e.subtype===`permission_retry`)return(0,Gq.jsxs)(P,{marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsxs)(F,{dimColor:!0,children:[`✻`,` `]}),(0,Gq.jsx)(F,{children:`Allowed `}),(0,Gq.jsx)(F,{bold:!0,children:e.commands.join(`, `)})]});if(e.subtype!==`stop_hook_summary`&&!n&&e.level===`info`)return null;if(e.subtype===`api_error`)return(0,Gq.jsx)(q8e,{message:e,verbose:n});if(e.subtype===`stop_hook_summary`)return(0,Gq.jsx)(r5e,{message:e,addMargin:t,verbose:n,isTranscriptMode:r});let a=e.content;return typeof a==`string`?(0,Gq.jsx)(P,{flexDirection:`row`,width:`100%`,children:(0,Gq.jsx)(i5e,{content:a,addMargin:t,dot:e.level!==`info`,color:e.level===`warning`?`warning`:void 0,dimColor:e.level===`info`})}):null}function r5e({message:e,addMargin:t,verbose:n,isTranscriptMode:r}){let i=pb(),{hookCount:a,hookInfos:o}=e,s=e.hookErrors??[],c=e.preventedContinuation,l=e.stopReason,{columns:u}=Xe();return s.length===0&&!c&&!e.hookLabel?null:e.hookLabel?(0,Gq.jsxs)(P,{flexDirection:`column`,width:`100%`,children:[(0,Gq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,`Ran `,a,` `,e.hookLabel,` `,a===1?`hook`:`hooks`]}),r&&o.map((e,t)=>(0,Gq.jsxs)(F,{dimColor:!0,children:[` ⎿ `,e.command===`prompt`?`prompt: ${e.promptText||``}`:e.command]},`cmd-${t}`))]}):(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:i,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{children:sr})}),(0,Gq.jsxs)(P,{flexDirection:`column`,width:u-10,children:[(0,Gq.jsxs)(F,{children:[`Ran `,(0,Gq.jsx)(F,{bold:!0,children:a}),` `,e.hookLabel??`stop`,` `,a===1?`hook`:`hooks`,!n&&o.length>0&&(0,Gq.jsxs)(Gq.Fragment,{children:[` `,(0,Gq.jsx)(Eb,{})]})]}),n&&o.length>0&&o.map((e,t)=>(0,Gq.jsxs)(F,{dimColor:!0,children:[`⎿ \xA0`,e.command===`prompt`?`prompt: ${e.promptText||``}`:e.command]},`cmd-${t}`)),c&&l&&(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{dimColor:!0,children:`⎿ \xA0`}),l]}),s.length>0&&s.map((t,n)=>(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{dimColor:!0,children:`⎿ \xA0`}),e.hookLabel??`Stop`,` hook error: `,t]},n))]})]})}function i5e({content:e,addMargin:t,dot:n,color:r,dimColor:i}){let{columns:a}=Xe(),o=pb();return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:o,width:`100%`,children:[n&&(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{color:r,dimColor:i,children:sr})}),(0,Gq.jsx)(P,{flexDirection:`column`,width:a-10,children:(0,Gq.jsx)(F,{color:r,dimColor:i,wrap:`wrap`,children:e.trim()})})]})}function a5e({message:e,addMargin:t}){let n=pb(),[r]=(0,Wq.useState)(()=>ch(G8e)??`Worked`),i=lV(),[a]=(0,Wq.useState)(()=>{let e=i.getState().tasks,t=Object.values(e??{}).filter(Z8e);return t.length>0?$8e(t):null}),o=yi().showTurnDuration??!0,s=La(e.durationMs),c=e.budgetLimit!==void 0,l=(()=>{if(!c)return``;let t=e.budgetTokens,n=e.budgetLimit,r=t>=n?`${Pa(t)} used (${Pa(n)} min ${ie.tick})`:`${Pa(t)} / ${Pa(n)} (${Math.round(t/n*100)}%)`,i=e.budgetNudges>0?` \u00B7 ${e.budgetNudges} ${e.budgetNudges===1?`nudge`:`nudges`}`:``;return`${o?` · `:``}${r}${i}`})();return!o&&!c?null:(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:n,width:`100%`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:`✻`})}),(0,Gq.jsxs)(F,{dimColor:!0,children:[o&&`${r} for ${s}`,l,a&&` \u00B7 ${a} still running`]})]})}function o5e({message:e,addMargin:t}){let n=pb(),r=e.writtenPaths??[],i=r.length,a=[i>0?`${i} ${i===1?`memory`:`memories`}`:null].filter(Boolean);return(0,Gq.jsxs)(P,{flexDirection:`column`,marginTop:+!!t,backgroundColor:n,children:[(0,Gq.jsxs)(P,{flexDirection:`row`,children:[(0,Gq.jsx)(P,{minWidth:2,children:(0,Gq.jsx)(F,{dimColor:!0,children:sr})}),(0,Gq.jsxs)(F,{children:[e.verb??`Saved`,` `,a.join(` · `)]})]}),r.map(e=>(0,Gq.jsx)(s5e,{path:e},e))]})}function s5e({path:e}){let[t,n]=(0,Wq.useState)(!1);return(0,Gq.jsx)(Z,{children:(0,Gq.jsx)(P,{onClick:()=>void gke(e),onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:(0,Gq.jsx)(F,{dimColor:!t,underline:t,children:(0,Gq.jsx)(qb,{filePath:e,children:Kc(e)})})})})}function c5e({message:e,addMargin:t}){let n=pb(),r=e.url,i=e.upgradeNudge;return(0,Gq.jsxs)(P,{flexDirection:`row`,marginTop:+!!t,backgroundColor:n,width:999,children:[(0,Gq.jsx)(P,{minWidth:2}),(0,Gq.jsxs)(P,{flexDirection:`column`,children:[(0,Gq.jsxs)(F,{children:[(0,Gq.jsx)(F,{color:`suggestion`,children:`/remote-control`}),` is active. Code in CLI or at`]}),(0,Gq.jsx)(Te,{url:r,children:r}),i&&(0,Gq.jsxs)(F,{dimColor:!0,children:[`⎿ `,i]})]})]})}var Wq,Gq,l5e=n((()=>{I(),Jb(),Wq=r(ze(),1),lh(),Dr(),ne(),Rb(),zw(),K8e(),eb(),Y8e(),Ba(),bi(),X8e(),Ab(),mV(),Q8e(),t5e(),wb(),Gq=et()}));function u5e(){return(0,Kq.jsx)(Z,{height:1,children:(0,Kq.jsx)(vK,{})})}var Kq,d5e=n((()=>{bK(),Rb(),Kq=et()}));function f5e({plan:e}){return(0,qq.jsx)(Z,{children:(0,qq.jsxs)(P,{flexDirection:`column`,children:[(0,qq.jsx)(F,{color:`subtle`,children:`User rejected Work Mate's plan:`}),(0,qq.jsx)(P,{borderStyle:`round`,borderColor:`planMode`,paddingX:1,overflow:`hidden`,children:(0,qq.jsx)(PK,{children:e})})]})})}var qq,p5e=n((()=>{zK(),Rb(),I(),qq=et()}));function m5e(){return(0,Jq.jsx)(Z,{height:1,children:(0,Jq.jsx)(F,{dimColor:!0,children:`Tool use rejected`})})}var Jq,h5e=n((()=>{I(),Rb(),Jq=et()}));function g5e({progressMessagesForMessage:e,tool:t,tools:n,param:r,verbose:i,isTranscriptMode:a}){return typeof r.content==`string`&&r.content.includes(`[Request interrupted by user for tool use]`)?(0,Yq.jsx)(Z,{height:1,children:(0,Yq.jsx)(vK,{})}):typeof r.content==`string`&&r.content.startsWith(`The agent proposed a plan that was rejected by the user. The user chose to stay in plan mode rather than proceed with implementation.
1642
1642
 
1643
1643
  Rejected plan:
1644
1644
  `)?(0,Yq.jsx)(f5e,{plan:r.content.substring(Dxt.length)}):typeof r.content==`string`&&r.content.startsWith(`The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). To tell you how to proceed, the user said:
@@ -1646,9 +1646,9 @@ Rejected plan:
1646
1646
  `);{let e=s.getAppState(),t=await aK({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();c0({taskId:o,description:n,status:`completed`,setAppState:h,finalMessage:l,usage:{totalTokens:r0(t),toolUses:c.totalToolUseCount,durationMs:c.totalDurationMs},toolUseId:s.toolUseId,...u})}catch(e){if(e instanceof Sn){l0(o,h),J(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!0,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_background`});let e=await re(),t=c4e(i);c0({taskId:o,description:n,status:`killed`,setAppState:h,toolUseId:s.toolUseId,finalMessage:t,...e});return}let t=H(e);Pht(o,t,h);let r=await re();c0({taskId:o,description:n,status:`failed`,error:t,setAppState:h,toolUseId:s.toolUseId,...r})}finally{e?.(),dn(t)}});let c=s.options.tools.some(e=>Ws(e,`Read`)||Ws(e,`Bash`));return{data:{isAsync:!0,status:`async_launched`,agentId:o,description:n,prompt:e,outputFile:V8(o),canReadOutputFile:c}}}}if(S.type!==`message`)continue;let{result:C}=S;if(C.done)break;let w=C.value;if(i.push(w),i0(o,w,c,s.options.tools),f){let e=rK(w);e&&(iK(o,f,s.toolUseId,n,a,e),pn()&&u0(f,a0(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=SLe(w);e>0&&s.setResponseLength(t=>t+e)}let E=F4([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 Sn)throw C=!0,J(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!1,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_sync`}),e;U(`Sync agent error: ${H(e)}`,{level:`error`}),S=jn(e)}finally{if(s.setToolJSX&&s.setToolJSX(null),y?.(),f&&(Rht(f,h),!_)){let e=a0(o);sc({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}})}dn(t),m?.(),_||(E=await re())}let D=i.findLast(e=>e.type!==`system`&&e.type!==`progress`);if(D&&ubt(D))throw J(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!1,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_sync`}),new Sn;if(S){if(!i.some(e=>e.type===`assistant`))throw S;U(`Sync agent recovering from error with ${i.length} messages`)}let O=nK(i,t,T);{let e=s.getAppState(),t=await aK({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:W5e,userFacingNameBackgroundColor:G5e,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 ${gs} or ${js} 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&&ire.has(e.agentType)&&!r?Ss(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}
1647
1647
  <usage>total_tokens: ${e.totalTokens}
1648
1648
  tool_uses: ${e.totalToolUseCount}
1649
- duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:L5e,renderToolUseMessage:R5e,renderToolUseTag:z5e,renderToolUseProgressMessage:aJ,renderToolUseRejectedMessage:B5e,renderToolUseErrorMessage:V5e,renderGroupedToolUse:U5e})}));function r7e(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return vl(`sha256`).update(n+u7e).digest(`hex`).slice(0,16)}function i7e(e,t,n){return t===l7e?`default-bundle`:Qg(t)?`official`:n?.has(e)?`org`:`user-local`}function a7e(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(tl)?t:t+tl))?`seed-mount`:`user-install`}function pJ(e,t,n=null){let r=i7e(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:r7e(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 mJ(e,t=null){let{marketplace:n}=Zg(e.repository);return pJ(e.pluginManifest.name,n,t)}function o7e(e,t,n){for(let r of e){let{marketplace:e}=Zg(r.repository);J(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...pJ(r.name,e,t),enabled_via:a7e(r,t,n),skill_path_count:+!!r.skillsPath+(r.skillsPaths?.length??0),command_path_count:+!!r.commandsPath+(r.commandsPaths?.length??0),has_mcp:r.manifest.mcpServers!==void 0,has_hooks:r.hooksConfig!==void 0,...r.manifest.version&&{version:r.manifest.version}})}}function s7e(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 c7e(e,t){for(let n of e){let{name:e,marketplace:r}=Zg(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;J(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...pJ(i,r,t)})}}var l7e,u7e,hJ=n((()=>{Da(),$g(),l7e=`builtin`,u7e=`claude-plugin-telemetry-v1`}));function d7e(e){let t=Date.now(),n=gJ.get(e);n!==void 0&&t-n<p7e||(gJ.set(e,t),Ti(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function f7e(e){let t=yi().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 p7e,gJ,m7e=n((()=>{bi(),p7e=6e4,gJ=new Map}));function h7e(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function g7e(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 _7e=n((()=>{}));function v7e(e){if(`status`in e&&e.status===`forked`)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{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} ${qa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{children:t})})})}function y7e({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function _J(e,{tools:t,verbose:n}){if(!e.length)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{dimColor:!0,children:S7e})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=L4(e.map(e=>e.data));return(0,vJ.jsx)(Z,{children:(0,vJ.jsxs)(P,{flexDirection:`column`,children:[(0,vJ.jsx)(Tb,{children:r.map(e=>(0,vJ.jsx)(P,{height:1,overflow:`hidden`,children:(0,vJ.jsx)(tJ,{message:e.data.message,lookups:d3,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,vJ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,qa(i,`use`)]})]})})}function b7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(xK,{})]})}function x7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(Ub,{result:e,verbose:r})]})}var vJ,S7e,C7e=n((()=>{Ab(),Kb(),CK(),I(),nJ(),Rb(),m3(),Ja(),vJ=et(),S7e=`Initializing…`})),w7e=i({getDiscoveredRemoteSkill:()=>E7e,stripCanonicalPrefix:()=>T7e});function T7e(e){return null}function E7e(e){}var D7e=n((()=>{})),O7e=i({loadRemoteSkill:()=>k7e});function k7e(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var A7e=n((()=>{})),j7e=i({logRemoteSkillLoaded:()=>M7e});function M7e(e){}var N7e=n((()=>{}));async function yJ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?G3(en()):uh([...await G3(en()),...t],`name`)}async function P7e(e,t,n,r,i,a,o){let s=Date.now(),c=GG(),l=Y3().has(t),u=I7e(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=bJ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Zg(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=Ec()?.agentId;J(`tengu_skill_tool_invocation`,{command_name:f,_PROTO_skill_name:t,execution_context:`fork`,invocation_trigger:h>0?`nested-skill`:`claude-proactive`,query_depth:h,...g&&{parent_agent_id:g},...p,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...m&&{_PROTO_marketplace_name:m},plugin_name:u?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:u?e.pluginInfo.repository:`third-party`,...mJ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await Bmt(e,n||``,r),x=[];U(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of pK({agentDefinition:v,promptMessages:y,toolUseContext:{...r,getAppState:_},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(x.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=F4([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:b,agentId:c}})}}let n=Vmt(x,`Skill execution completed`);return x.length=0,U(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{dn(c)}}function F7e(e){for(let t of Object.keys(e)){if(z7e.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 I7e(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Qg(Zg(e.pluginInfo.repository).marketplace)}var bJ,L7e,R7e,xJ,z7e,B7e=n((()=>{dh(),Wt(),e6(),Ks(),W(),j9(),$g(),hJ(),gt(),$i(),Da(),Sc(),R1(),_t(),m3(),No(),m7e(),KG(),mK(),_7e(),Js(),V_(),C7e(),D7e(),A7e(),N7e(),Om(),bJ={...w7e,...O7e,...j7e,...nhe},L7e=ht(()=>B({skill:L().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:L().optional().describe(`Optional arguments for the skill`)})),R7e=ht(()=>lt([B({success:ft().describe(`Whether the skill is valid`),commandName:L().describe(`The name of the skill`),allowedTools:z(L()).optional().describe(`Tools allowed by this skill`),model:L().optional().describe(`Model override if specified`),status:ot(`inline`).optional().describe(`Execution status`)}),B({success:ft().describe(`Whether the skill completed successfully`),commandName:L().describe(`The name of the skill`),status:ot(`forked`).describe(`Execution status`),agentId:L().describe(`The ID of the sub-agent that executed the skill`),result:L().describe(`The result from the forked skill execution`)})])),xJ=Os({name:us,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return L7e()},get outputSchema(){return R7e()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>B_(en()),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(`/`);r&&J(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=K3(i,await yJ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${us} tool due to disable-model-invocation`,errorCode:4}:a.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${i} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${i}`,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=K3(i,await yJ(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,xJ,`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,xJ,`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`&&F7e(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:us,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:us,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 yJ(n),l=K3(s,c);if(d7e(s),l?.type===`prompt`&&l.context===`fork`)return P7e(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-qR_j1DE8.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model,m=Y3().has(s),h=l?.type===`prompt`&&l.source===`bundled`,g=l?.type===`prompt`&&I7e(l),_=m||h||g?s:`custom`,v=bJ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Zg(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=Ec()?.agentId;J(`tengu_skill_tool_invocation`,{command_name:_,_PROTO_skill_name:s,execution_context:`inline`,invocation_trigger:b>0?`nested-skill`:`claude-proactive`,query_depth:b,...x&&{parent_agent_id:x},...v,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...y&&{_PROTO_marketplace_name:y},plugin_name:g?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:g?l.pluginInfo.repository:`third-party`,...mJ(l.pluginInfo)}});let S=g7e(i,us),C=h7e(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}),S);return U(`SkillTool returning ${C.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:C,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:uae(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:v7e,renderToolUseMessage:y7e,renderToolUseProgressMessage:_J,renderToolUseRejectedMessage:b7e,renderToolUseErrorMessage:x7e}),z7e=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 V7e(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
1649
+ duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:L5e,renderToolUseMessage:R5e,renderToolUseTag:z5e,renderToolUseProgressMessage:aJ,renderToolUseRejectedMessage:B5e,renderToolUseErrorMessage:V5e,renderGroupedToolUse:U5e})}));function r7e(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return vl(`sha256`).update(n+u7e).digest(`hex`).slice(0,16)}function i7e(e,t,n){return t===l7e?`default-bundle`:Qg(t)?`official`:n?.has(e)?`org`:`user-local`}function a7e(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(tl)?t:t+tl))?`seed-mount`:`user-install`}function pJ(e,t,n=null){let r=i7e(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:r7e(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 mJ(e,t=null){let{marketplace:n}=Zg(e.repository);return pJ(e.pluginManifest.name,n,t)}function o7e(e,t,n){for(let r of e){let{marketplace:e}=Zg(r.repository);J(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...pJ(r.name,e,t),enabled_via:a7e(r,t,n),skill_path_count:+!!r.skillsPath+(r.skillsPaths?.length??0),command_path_count:+!!r.commandsPath+(r.commandsPaths?.length??0),has_mcp:r.manifest.mcpServers!==void 0,has_hooks:r.hooksConfig!==void 0,...r.manifest.version&&{version:r.manifest.version}})}}function s7e(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 c7e(e,t){for(let n of e){let{name:e,marketplace:r}=Zg(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;J(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...pJ(i,r,t)})}}var l7e,u7e,hJ=n((()=>{Da(),$g(),l7e=`builtin`,u7e=`claude-plugin-telemetry-v1`}));function d7e(e){let t=Date.now(),n=gJ.get(e);n!==void 0&&t-n<p7e||(gJ.set(e,t),Ti(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function f7e(e){let t=yi().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 p7e,gJ,m7e=n((()=>{bi(),p7e=6e4,gJ=new Map}));function h7e(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function g7e(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 _7e=n((()=>{}));function v7e(e){if(`status`in e&&e.status===`forked`)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{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} ${qa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{children:t})})})}function y7e({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function _J(e,{tools:t,verbose:n}){if(!e.length)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{dimColor:!0,children:S7e})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=L4(e.map(e=>e.data));return(0,vJ.jsx)(Z,{children:(0,vJ.jsxs)(P,{flexDirection:`column`,children:[(0,vJ.jsx)(Tb,{children:r.map(e=>(0,vJ.jsx)(P,{height:1,overflow:`hidden`,children:(0,vJ.jsx)(tJ,{message:e.data.message,lookups:d3,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,vJ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,qa(i,`use`)]})]})})}function b7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(xK,{})]})}function x7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(Ub,{result:e,verbose:r})]})}var vJ,S7e,C7e=n((()=>{Ab(),Kb(),CK(),I(),nJ(),Rb(),m3(),Ja(),vJ=et(),S7e=`Initializing…`})),w7e=i({getDiscoveredRemoteSkill:()=>E7e,stripCanonicalPrefix:()=>T7e});function T7e(e){return null}function E7e(e){}var D7e=n((()=>{})),O7e=i({loadRemoteSkill:()=>k7e});function k7e(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var A7e=n((()=>{})),j7e=i({logRemoteSkillLoaded:()=>M7e});function M7e(e){}var N7e=n((()=>{}));async function yJ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?G3(en()):uh([...await G3(en()),...t],`name`)}async function P7e(e,t,n,r,i,a,o){let s=Date.now(),c=GG(),l=Y3().has(t),u=I7e(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=bJ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Zg(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=Ec()?.agentId;J(`tengu_skill_tool_invocation`,{command_name:f,_PROTO_skill_name:t,execution_context:`fork`,invocation_trigger:h>0?`nested-skill`:`claude-proactive`,query_depth:h,...g&&{parent_agent_id:g},...p,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...m&&{_PROTO_marketplace_name:m},plugin_name:u?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:u?e.pluginInfo.repository:`third-party`,...mJ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await Bmt(e,n||``,r),x=[];U(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of pK({agentDefinition:v,promptMessages:y,toolUseContext:{...r,getAppState:_},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(x.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=F4([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:b,agentId:c}})}}let n=Vmt(x,`Skill execution completed`);return x.length=0,U(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{dn(c)}}function F7e(e){for(let t of Object.keys(e)){if(z7e.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 I7e(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Qg(Zg(e.pluginInfo.repository).marketplace)}var bJ,L7e,R7e,xJ,z7e,B7e=n((()=>{dh(),Wt(),e6(),Ks(),W(),j9(),$g(),hJ(),gt(),$i(),Da(),Sc(),R1(),_t(),m3(),No(),m7e(),KG(),mK(),_7e(),Js(),V_(),C7e(),D7e(),A7e(),N7e(),Om(),bJ={...w7e,...O7e,...j7e,...nhe},L7e=ht(()=>B({skill:L().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:L().optional().describe(`Optional arguments for the skill`)})),R7e=ht(()=>lt([B({success:ft().describe(`Whether the skill is valid`),commandName:L().describe(`The name of the skill`),allowedTools:z(L()).optional().describe(`Tools allowed by this skill`),model:L().optional().describe(`Model override if specified`),status:ot(`inline`).optional().describe(`Execution status`)}),B({success:ft().describe(`Whether the skill completed successfully`),commandName:L().describe(`The name of the skill`),status:ot(`forked`).describe(`Execution status`),agentId:L().describe(`The ID of the sub-agent that executed the skill`),result:L().describe(`The result from the forked skill execution`)})])),xJ=Os({name:us,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return L7e()},get outputSchema(){return R7e()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>B_(en()),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(`/`);r&&J(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=K3(i,await yJ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${us} tool due to disable-model-invocation`,errorCode:4}:a.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${i} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${i}`,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=K3(i,await yJ(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,xJ,`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,xJ,`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`&&F7e(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:us,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:us,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 yJ(n),l=K3(s,c);if(d7e(s),l?.type===`prompt`&&l.context===`fork`)return P7e(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-Bi8_1MRC.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model,m=Y3().has(s),h=l?.type===`prompt`&&l.source===`bundled`,g=l?.type===`prompt`&&I7e(l),_=m||h||g?s:`custom`,v=bJ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Zg(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=Ec()?.agentId;J(`tengu_skill_tool_invocation`,{command_name:_,_PROTO_skill_name:s,execution_context:`inline`,invocation_trigger:b>0?`nested-skill`:`claude-proactive`,query_depth:b,...x&&{parent_agent_id:x},...v,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...y&&{_PROTO_marketplace_name:y},plugin_name:g?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:g?l.pluginInfo.repository:`third-party`,...mJ(l.pluginInfo)}});let S=g7e(i,us),C=h7e(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}),S);return U(`SkillTool returning ${C.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:C,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:uae(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:v7e,renderToolUseMessage:y7e,renderToolUseProgressMessage:_J,renderToolUseRejectedMessage:b7e,renderToolUseErrorMessage:x7e}),z7e=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 V7e(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
1650
1650
  `),c=s>=0?r.slice(0,s):r;if(c.includes(`"isSidechain":true`)||c.includes(`"isSidechain": true`))return null;let l=va(i,`customTitle`)||va(r,`customTitle`)||va(i,`aiTitle`)||va(r,`aiTitle`)||void 0,u=Jie(r)||void 0,d=ma(r,`timestamp`),f;if(d){let e=Date.parse(d);Number.isNaN(e)||(f=e)}let p=l||va(i,`lastPrompt`)||va(i,`summary`)||u;if(!p)return null;let m=va(i,`gitBranch`)||ma(r,`gitBranch`)||void 0,h=ma(r,`cwd`)||n||void 0,g=i.split(`
1651
- `).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&&va(g,`tag`)||void 0,createdAt:f}}async function SJ(e,t,n){let r;try{r=await kl(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=qie(r.slice(0,-6));if(!i)return null;let a=Y(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await Nl(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function H7e(e){let t=await Wie(e.filePath);if(!t)return null;let n=V7e(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function U7e(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function W7e(e,t,n){e.sort(U7e);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+Y7e,e.length),c=e.slice(t,s),l=await Promise.all(c.map(H7e));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 G7e(e){let t=await Promise.all(e.map(H7e)),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 K7e(e,t,n){let r=await Yie(e),i;if(t)try{i=await Kie(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await ya(r);return e?SJ(e,n,r):[]}let a=ha(),o=process.platform===`win32`,s=i.map(e=>{let t=_a(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await kl(a,{withFileTypes:!0})}catch{let e=await ya(r);return e?SJ(e,n,r):[]}let l=[],u=new Set,d=await ya(r);if(d){let e=Kc(d);u.add(o?e.toLowerCase():e),l.push(...await SJ(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 SJ(Y(a,e.name),n,r));break}}}return l}async function q7e(e){let t=ha(),n;try{n=await kl(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>SJ(Y(t,n.name),e)))).flat()}async function J7e(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 K7e(t,i??!0,o):await q7e(o);return o?W7e(s,n,a):G7e(s)}var Y7e,X7e=n((()=>{Uie(),ga(),Y7e=32}));function CJ(){return Y(xi(),n9e)}async function Z7e(){try{return(await Nl(CJ())).mtimeMs}catch{return 0}}async function Q7e(){let e=CJ(),t,n;try{let[r,i]=await Promise.all([Nl(e),Ol(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<r9e&&n!==void 0&&yc(n))return U(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await El(xi(),{recursive:!0}),await Il(e,String(process.pid));let r;try{r=await Ol(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function $7e(e){let t=CJ();try{if(e===0){await Fl(t);return}await Il(t,``);let n=e/1e3;await mue(t,n,n)}catch(e){U(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function e9e(e){return(await SJ(s8(Xt()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function t9e(){try{await El(xi(),{recursive:!0}),await Il(CJ(),String(process.pid))}catch(e){U(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var n9e,r9e,wJ=n((()=>{Wt(),hi(),W(),bc(),X7e(),h8(),n9e=`.consolidate-lock`,r9e=3600*1e3}));function i9e(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function a9e(e,t){let n=s5(`dream`);return OL({...c5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function o9e(e,t,n,r){DL(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 s9e(e,t){DL(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function c9e(e,t){DL(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var TJ,EJ=n((()=>{wJ(),l5(),AL(),TJ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;DL(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 $7e(n)}}})),DJ,l9e=n((()=>{gt(),_t(),DJ=ht(()=>B({restrictions:rt(L(),B({allowed:ft()}))}))}));function u9e(e){return e instanceof Error}function d9e(){FJ||AJ()&&(FJ=new Promise(e=>{IJ=e,setTimeout(()=>{IJ&&(U(`Policy limits: Loading promise timed out, resolving anyway`),IJ(),IJ=null)},j9e)}))}function OJ(){return Y(p(),O9e)}function f9e(){return`${Va().BASE_API_URL}/api/claude_code/policy_limits`}function kJ(e){if(Array.isArray(e))return e.map(kJ);if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e).sort(([e],[t])=>e.localeCompare(t)))t[n]=kJ(r);return t}return e}function p9e(e){let t=V(kJ(e));return`sha256:${vl(`sha256`).update(t).digest(`hex`)}`}function AJ(){if(Vo()!==`firstParty`||!Zo())return!1;try{let{key:e}=To({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return!0}catch{}let e=vo();return!(!e?.accessToken||!e.scopes?.includes(`user:inference`)||e.subscriptionType!==`enterprise`&&e.subscriptionType!==`team`)}async function m9e(){FJ&&await FJ}function h9e(){try{let{key:e}=To({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return{headers:{"x-api-key":e}}}catch{}let e=vo();return e?.accessToken?{headers:{Authorization:`Bearer ${e.accessToken}`,"anthropic-beta":aae}}:{headers:{},error:`No authentication available`}}async function g9e(e){let t=null;for(let n=1;n<=6;n++){if(t=await _9e(e),t.success||t.skipRetry||n>MJ)return t;let r=cR(n);U(`Policy limits: Retry ${n}/${MJ} after ${r}ms`),await $o(r)}return t}async function _9e(e){try{await Ko();let t=h9e();if(t.error)return{success:!1,error:`Authentication required for policy limits`,skipRetry:!0};let n=f9e(),r={...t.headers,"User-Agent":Ose()};e&&(r[`If-None-Match`]=`"${e}"`);let i=await ue.get(n,{headers:r,timeout:k9e,validateStatus:e=>e===200||e===304||e===404});if(i.status===304)return U(`Policy limits: Using cached restrictions (304)`),{success:!0,restrictions:null,etag:e};if(i.status===404)return U(`Policy limits: No restrictions found (404)`),{success:!0,restrictions:{},etag:void 0};let a=DJ().safeParse(i.data);return a.success?(U(`Policy limits: Fetched successfully`),{success:!0,restrictions:a.data.restrictions}):(U(`Policy limits: Invalid response format - ${a.error.message}`),{success:!1,error:`Invalid policy limits format`})}catch(e){let{kind:t,message:n}=Sne(e);switch(t){case`auth`:return{success:!1,error:`Not authorized for policy limits`,skipRetry:!0};case`timeout`:return{success:!1,error:`Policy limits request timeout`};case`network`:return{success:!1,error:`Cannot connect to server`};default:return{success:!1,error:n}}}}function v9e(){try{let e=Ea(dl(OJ(),`utf-8`),!1),t=DJ().safeParse(e);return t.success?t.data.restrictions:null}catch{return null}}async function y9e(e){try{let t=OJ();await Il(t,V({restrictions:e},null,2),{encoding:`utf-8`,mode:384}),U(`Policy limits: Saved to ${t}`)}catch(e){U(`Policy limits: Failed to save - ${e instanceof Error?e.message:`unknown error`}`)}}async function jJ(){if(!AJ())return null;let e=v9e(),t=e?p9e(e):void 0;try{let n=await g9e(t);if(!n.success)return e?(U(`Policy limits: Using stale cache after fetch failure`),LJ=e,e):null;if(n.restrictions===null&&e)return U(`Policy limits: Cache still valid (304 Not Modified)`),LJ=e,e;let r=n.restrictions||{};if(Object.keys(r).length>0)return LJ=r,await y9e(r),U(`Policy limits: Applied new restrictions successfully`),r;LJ=r;try{await Fl(OJ()),U(`Policy limits: Deleted cached file (404 response)`)}catch(e){u9e(e)&&e.code!==`ENOENT`&&U(`Policy limits: Failed to delete cached file - ${e.message}`)}return r}catch{return e?(U(`Policy limits: Using stale cache after error`),LJ=e,e):null}}function b9e(e){let t=x9e();if(!t)return!(Iie()&&M9e.has(e));let n=t[e];return!n||n.allowed}function x9e(){if(!AJ())return null;if(LJ)return LJ;let e=v9e();return e?(LJ=e,e):null}async function S9e(){AJ()&&!FJ&&(FJ=new Promise(e=>{IJ=e}));try{await jJ(),AJ()&&E9e()}finally{IJ&&(IJ(),IJ=null)}}async function C9e(){await w9e(),AJ()&&(await jJ(),U(`Policy limits: Refreshed after auth change`))}async function w9e(){D9e(),LJ=null,FJ=null,IJ=null;try{await Fl(OJ())}catch{}}async function T9e(){if(!AJ())return;let e=LJ?V(LJ):null;try{await jJ(),(LJ?V(LJ):null)!==e&&U(`Policy limits: Changed during background poll`)}catch{}}function E9e(){NJ===null&&AJ()&&(NJ=setInterval(()=>{T9e()},A9e),NJ.unref(),PJ||(PJ=!0,Gn(async()=>D9e())))}function D9e(){NJ!==null&&(clearInterval(NJ),NJ=null)}var O9e,k9e,MJ,A9e,NJ,PJ,FJ,IJ,j9e,LJ,M9e,RJ=n((()=>{de(),Ha(),no(),Jn(),W(),h(),On(),wa(),Jo(),Fie(),Po(),Yn(),Dse(),vR(),l9e(),O9e=`policy-limits.json`,k9e=1e4,MJ=5,A9e=3600*1e3,NJ=null,PJ=!1,FJ=null,IJ=null,j9e=3e4,LJ=null,M9e=new Set([`allow_product_feedback`])}));async function N9e(){let e=vo()?.accessToken;if(!e)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await _o();if(!t)throw Error(`Unable to get organization UUID`);let n=`${Va().BASE_API_URL}/v1/environment_providers`;try{let r={...Bc(e),"x-organization-uuid":t},i=await ue.get(n,{headers:r,timeout:15e3});if(i.status!==200)throw Error(`Failed to fetch environments: ${i.status} ${i.statusText}`);return i.data.environments}catch(e){let t=jn(e);throw q(t),Error(`Failed to fetch environments: ${t.message}`)}}var P9e=n((()=>{de(),Ha(),bo(),no(),On(),Qi(),Vc()}));async function F9e(){return uo()?Ko():!1}async function I9e(){return await vie({ignoreUntracked:!0})}async function L9e(e,t,n){try{let r=vo()?.accessToken;if(!r)return U(`checkGithubAppInstalled: No access token found, assuming app not installed`),!1;let i=await _o();if(!i)return U(`checkGithubAppInstalled: No org UUID found, assuming app not installed`),!1;let a=`${Va().BASE_API_URL}/api/oauth/organizations/${i}/code/repos/${e}/${t}`,o={...Bc(r),"x-organization-uuid":i};U(`Checking GitHub app installation for ${e}/${t}`);let s=await ue.get(a,{headers:o,timeout:15e3,signal:n});if(s.status===200){if(s.data.status){let n=s.data.status.app_installed;return U(`GitHub app ${n?`is`:`is not`} installed on ${e}/${t}`),n}return U(`GitHub app is not installed on ${e}/${t} (status is null)`),!1}return U(`checkGithubAppInstalled: Unexpected response status ${s.status}`),!1}catch(n){if(ue.isAxiosError(n)){let r=n.response?.status;if(r&&r>=400&&r<500)return U(`checkGithubAppInstalled: Got ${r} error, app likely not installed on ${e}/${t}`),!1}return U(`checkGithubAppInstalled error: ${H(n)}`),!1}}var zJ=n((()=>{de(),Ha(),bo(),no(),vn(),W(),Rc(),On(),Mi(),Vc(),P9e()})),R9e=n((()=>{RJ(),Rc(),h(),zJ()}));function BJ(){if(process.stdout.isTTY)try{fl(1,qe);let e=Ae.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{fl(1,vee)}e?.drainStdin(),e?.detachForShutdown(),fl(1,fe),fl(1,ke),fl(1,nee),fl(1,see),fl(1,gee),fl(1,lee),Ke()&&fl(1,dee(pee)),m(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:fl(1,Ve))}catch{}}function VJ(){if(!GJ&&process.stdout.isTTY&&zt()&&!Dt())try{let e=sn();if(!p6(e))return;let t=I6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,fl(1,Ue.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),GJ=!0}catch{}}function HJ(e){qJ!==void 0&&(clearTimeout(qJ),qJ=void 0);try{Ae.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function UJ(e=0,t=`other`,n){process.exitCode=e,V9e=WJ(e,t,n).catch(t=>{U(`Graceful shutdown failed: ${t}`,{level:`error`}),BJ(),VJ(),HJ(e)}).catch(()=>{})}function z9e(){return KJ}async function WJ(e=0,t=`other`,n){if(KJ)return;KJ=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-9rkDD2iw.js`),a=i();qJ=setTimeout(e=>{BJ(),VJ(),HJ(e)},Math.max(5e3,a+3500),e),qJ.unref(),process.exitCode=e,BJ(),VJ();let o;try{let e=(async()=>{try{await Ene()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new H9e),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{eae()}catch{}let s=Hee();s&&J(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([ole(),sle()]),$o(500)])}catch{}if(n?.finalMessage)try{fl(2,`${n.finalMessage}\n`)}catch{}HJ(e)}var GJ,B9e,KJ,qJ,JJ,V9e,H9e,YJ=n((()=>{Ge(),d(),re(),Wt(),I(),cle(),ile(),Da(),Jn(),W(),Ei(),h(),h8(),Po(),tae(),GJ=!1,B9e=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Ai(`info`,`shutdown_signal`,{signal:`SIGINT`}),WJ(0))}),process.on(`SIGTERM`,()=>{Ai(`info`,`shutdown_signal`,{signal:`SIGTERM`}),WJ(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Ai(`info`,`shutdown_signal`,{signal:`SIGHUP`}),WJ(129)}),process.stdin.isTTY&&(JJ=setInterval(()=>{pte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(JJ),Ai(`info`,`shutdown_signal`,{signal:`orphan_detected`}),WJ(129))},3e4),JJ.unref())),process.on(`uncaughtException`,e=>{Ai(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),J(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;Ai(`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)}),J(`tengu_unhandled_rejection`,{error_name:t})})}),KJ=!1,H9e=class extends Error{constructor(){super(`Cleanup timeout`)}}}));function XJ(){let e=lV(),t=cV(),n=(0,ZJ.useCallback)(()=>{t(e=>{let r=U9e(e.notifications.queue);return e.notifications.current!==null||!r?e:($J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},r.timeoutMs??QJ,t,r.key,n),{...e,notifications:{queue:e.notifications.queue.filter(e=>e!==r),current:r}})})},[t]),r=(0,ZJ.useCallback)(e=>{if(e.priority===`immediate`){$J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t.key?{...e,notifications:{queue:e.notifications.queue.filter(e=>!t.invalidates?.includes(e.key)),current:null}}:e),n()},e.timeoutMs??QJ,t,e,n),t(t=>({...t,notifications:{current:e,queue:[...t.notifications.current?[t.notifications.current]:[],...t.notifications.queue].filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key))}}));return}t(r=>{if(e.fold){if(r.notifications.current?.key===e.key){let i=e.fold(r.notifications.current,e);return $J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},i.timeoutMs??QJ,t,i.key,n),{...r,notifications:{current:i,queue:r.notifications.queue}}}let i=r.notifications.queue.findIndex(t=>t.key===e.key);if(i!==-1){let t=e.fold(r.notifications.queue[i],e),n=[...r.notifications.queue];return n[i]=t,{...r,notifications:{current:r.notifications.current,queue:n}}}}if(!(!new Set(r.notifications.queue.map(e=>e.key)).has(e.key)&&r.notifications.current?.key!==e.key))return r;let i=r.notifications.current!==null&&e.invalidates?.includes(r.notifications.current.key);return i&&$J&&(clearTimeout($J),$J=null),{...r,notifications:{current:i?null:r.notifications.current,queue:[...r.notifications.queue.filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key)),e]}}}),n()},[t,n]),i=(0,ZJ.useCallback)(e=>{t(t=>{let n=t.notifications.current?.key===e,r=t.notifications.queue.some(t=>t.key===e);return!n&&!r?t:(n&&$J&&(clearTimeout($J),$J=null),{...t,notifications:{current:n?null:t.notifications.current,queue:t.notifications.queue.filter(t=>t.key!==e)}})}),n()},[t,n]);return(0,ZJ.useEffect)(()=>{e.getState().notifications.queue.length>0&&n()},[]),{addNotification:r,removeNotification:i}}function U9e(e){if(e.length!==0)return e.reduce((e,t)=>eY[t.priority]<eY[e.priority]?t:e)}var ZJ,QJ,$J,eY,tY=n((()=>{ZJ=r(ze(),1),mV(),QJ=8e3,$J=null,eY={immediate:0,high:1,medium:2,low:3}}));function W9e(){let e=process.platform,t=process.env.CLAUDE_CODE_TMPDIR||(e===`win32`?process.env.TEMP||`C:\\Temp`:Wc()),n=`claude_cli_latest_screenshot.png`,r={darwin:Y(t,n),linux:Y(t,n),win32:Y(t,n)},i=r[e]||r.linux,a={darwin:{checkImage:`osascript -e 'the clipboard as «class PNGf»'`,saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${i}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:`osascript -e 'get POSIX path of (the clipboard as «class furl»)'`,deleteFile:`rm -f "${i}"`},linux:{checkImage:`xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"`,saveImage:`xclip -selection clipboard -t image/png -o > "${i}" 2>/dev/null || wl-paste --type image/png > "${i}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${i}" 2>/dev/null || wl-paste --type image/bmp > "${i}"`,getPath:`xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null`,deleteFile:`rm -f "${i}"`},win32:{checkImage:`powershell -NoProfile -Command "(Get-Clipboard -Format Image) -ne $null"`,saveImage:`powershell -NoProfile -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${i.replace(/\\/g,`\\\\`)}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:`powershell -NoProfile -Command "Get-Clipboard"`,deleteFile:`del /f "${i}"`}};return{commands:a[e]||a.linux,screenshotPath:i}}async function G9e(){return process.platform===`darwin`&&(await Li(`osascript`,[`-e`,`the clipboard as «class PNGf»`])).code===0}async function nY(){let{commands:e,screenshotPath:t}=W9e();try{if((await Ri(e.checkImage,{shell:!0,reject:!1})).exitCode!==0||(await Ri(e.saveImage,{shell:!0,reject:!1})).exitCode!==0)return null;let n=G().readFileBytesSync(t);n.length>=2&&n[0]===66&&n[1]===77&&(n=await(await J_())(n).png().toBuffer());let r=await X_(n,n.length,`png`),i=r.buffer.toString(`base64`),a=$_(i);return Ri(e.deleteFile,{shell:!0,reject:!1}),{base64:i,mediaType:a,dimensions:r.dimensions}}catch{return null}}async function K9e(){let{commands:e}=W9e();try{let t=await Ri(e.getPath,{shell:!0,reject:!1});return t.exitCode!==0||!t.stdout?null:t.stdout.trim()}catch(e){return q(e),null}}function q9e(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function J9e(e){if(process.platform===`win32`)return e;let t=`__DOUBLE_BACKSLASH_${yl(8).toString(`hex`)}__`;return e.replace(/\\\\/g,t).replace(/\\(.)/g,`$1`).replace(new RegExp(t,`g`),`\\`)}function rY(e){let t=J9e(q9e(e.trim()));return iY.test(t)}function Y9e(e){let t=J9e(q9e(e.trim()));return iY.test(t)?t:null}async function X9e(e){let t=Y9e(e);if(!t)return null;let n=t,r;try{if(Yc(n))r=G().readFileBytesSync(n);else{let e=await K9e();e&&n===Kc(e)&&(r=G().readFileBytesSync(e))}}catch(e){return q(e),null}if(!r)return null;if(r.length===0)return U(`Image file is empty: ${n}`,{level:`warn`}),null;r.length>=2&&r[0]===66&&r[1]===77&&(r=await(await J_())(r).png().toBuffer());let i=Jc(n).slice(1).toLowerCase()||`png`,a=await X_(r,r.length,i),o=a.buffer.toString(`base64`);return{path:n,base64:o,mediaType:$_(o),dimensions:a.dimensions}}var iY,aY=n((()=>{Ii(),G_(),Sbe(),W(),zi(),Bn(),rv(),Qi(),iY=/\.(png|jpe?g|gif|webp)$/i}));function Z9e(e,t){let{addNotification:n}=XJ(),r=(0,oY.useRef)(e),i=(0,oY.useRef)(0),a=(0,oY.useRef)(null);(0,oY.useEffect)(()=>{let o=r.current;if(r.current=e,!(!t||!e||o))return a.current&&clearTimeout(a.current),a.current=setTimeout(async(e,t,n)=>{e.current=null;let r=Date.now();r-t.current<eet||await G9e()&&(t.current=r,n({key:Q9e,text:`Image in clipboard · ${ib(`chat:imagePaste`,`Chat`,`ctrl+v`)} to paste`,priority:`immediate`,timeoutMs:8e3}))},$9e,a,i,n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n])}var oY,Q9e,$9e,eet,tet=n((()=>{oY=r(ze(),1),tY(),ob(),aY(),Q9e=`clipboard-image-hint`,$9e=1e3,eet=3e4}));function net(e,t){switch(t){case`bash`:return`!${e}`;default:return e}}function ret(e){return e.startsWith(`!`)?`bash`:`prompt`}function iet(e){return ret(e)===`prompt`?e:e.slice(1)}function aet(e){return e===`!`}var oet=n((()=>{}));function sY(){return Y(p(),pet)}function set(e){return vl(`sha256`).update(e).digest(`hex`).slice(0,16)}function cet(e){return Y(sY(),`${e}.txt`)}async function uet(e,t){try{await El(sY(),{recursive:!0});let n=cet(e);await Il(n,t,{encoding:`utf8`,mode:384}),U(`Stored paste ${e} to ${n}`)}catch(e){U(`Failed to store paste: ${e}`)}}async function det(e){try{return await Ol(cet(e),{encoding:`utf8`})}catch(t){return xn(t)||U(`Failed to retrieve paste ${e}: ${t}`),null}}async function fet(e){let t=sY(),n;try{n=await kl(t)}catch{return}let r=e.getTime();for(let e of n){if(!e.endsWith(`.txt`))continue;let n=Y(t,e);try{(await Nl(n)).mtimeMs<r&&(await Fl(n),U(`Cleaned up old paste: ${n}`))}catch{}}}var pet,met=n((()=>{W(),h(),On(),pet=`paste-cache`}));function het(e){return(e.match(/\r\n|\r|\n/g)||[]).length}function get(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}function _et(e){return`[Image #${e}]`}function vet(e){return[...e.matchAll(/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.)*\]/g)].map(e=>({id:parseInt(e[2]||`0`,10),match:e[0],index:e.index})).filter(e=>e.id>0)}function yet(e,t){let n=vet(e),r=e;for(let e=n.length-1;e>=0;e--){let i=n[e],a=t[i.id];a?.type===`text`&&(r=r.slice(0,i.index)+a.content+r.slice(i.index+i.match.length))}return r}function bet(e){return kn(e)}async function*xet(){let e=sn();for(let e=uY.length-1;e>=0;e--)yield uY[e];let t=Y(p(),`history.jsonl`);try{for await(let n of wne(t))try{let t=bet(n);if(t.sessionId===e&&hY.has(t.timestamp))continue;yield t}catch(e){U(`Failed to parse history line: ${e}`)}}catch(e){if(Cn(e)===`ENOENT`)return;throw e}}async function*Cet(){for await(let e of xet())yield await cY(e)}async function*wet(){let e=en(),t=sn(),n=[],r=0;for await(let i of xet())if(!(!i||typeof i.project!=`string`)&&i.project===e&&(i.sessionId===t?(yield await cY(i),r++):n.push(i),r+n.length>=lY))break;for(let e of n){if(r>=lY)return;yield await cY(e),r++}}async function Tet(e){if(e.content)return{id:e.id,type:e.type,content:e.content,mediaType:e.mediaType,filename:e.filename};if(e.contentHash){let t=await det(e.contentHash);if(t)return{id:e.id,type:e.type,content:t,mediaType:e.mediaType,filename:e.filename}}return null}async function cY(e){let t={};for(let[n,r]of Object.entries(e.pastedContents||{})){let e=await Tet(r);e&&(t[Number(n)]=e)}return{display:e.display,pastedContents:t}}async function Eet(){if(uY.length===0)return;let e;try{let t=Y(p(),`history.jsonl`);await Il(t,``,{encoding:`utf8`,mode:384,flag:`a`}),e=await mi(t,{stale:1e4,retries:{retries:3,minTimeout:50}});let n=uY.map(e=>`${V(e)}\n`);uY=[],await Sl(t,n.join(``),{mode:384})}catch(e){U(`Failed to write prompt history: ${e}`)}finally{e&&await e()}}async function Det(e){if(!(dY||uY.length===0)&&!(e>5)){dY=!0;try{await Eet()}finally{dY=!1,uY.length>0&&(await $o(500),Det(e+1))}}}async function Oet(e){let t=typeof e==`string`?{display:e,pastedContents:{}}:e,n={};if(t.pastedContents){for(let[e,r]of Object.entries(t.pastedContents))if(r.type!==`image`)if(r.content.length<=jet)n[Number(e)]={id:r.id,type:r.type,content:r.content,mediaType:r.mediaType,filename:r.filename};else{let t=set(r.content);n[Number(e)]={id:r.id,type:r.type,contentHash:t,mediaType:r.mediaType,filename:r.filename},uet(t,r.content)}}let r={...t,pastedContents:n,timestamp:Date.now(),project:en(),sessionId:sn()};uY.push(r),mY=r,fY=Det(0)}function ket(e){m(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)||(pY||(pY=!0,Gn(async()=>{fY&&await fY,uY.length>0&&await Eet()})),Oet(e))}function Aet(){if(!mY)return;let e=mY;mY=null;let t=uY.lastIndexOf(e);t===-1?hY.add(e.timestamp):uY.splice(t,1)}var lY,jet,uY,dY,fY,pY,mY,hY,Met=n((()=>{Wt(),Jn(),W(),h(),On(),Bn(),vi(),met(),Po(),Yn(),lY=100,jet=1024,uY=[],dY=!1,fY=null,pY=!1,mY=null,hY=new Set}));function gY(e,t=`append`){e.length>0&&(xY&&yY.length>0?t===`prepend`?yY[0]=e+yY[0]:yY[0]+=e:(yY.unshift(e),yY.length>Let&&yY.pop()),xY=!0,wY=!1)}function Net(){return yY[0]??``}function _Y(){xY=!1}function Pet(e,t){SY=e,CY=t,wY=!0,bY=0}function Fet(){return!wY||yY.length<=1?null:(bY=(bY+1)%yY.length,{text:yY[bY]??``,start:SY,length:CY})}function Iet(e){CY=e}function vY(){wY=!1}var Let,yY,bY,xY,SY,CY,wY,Ret,TY,EY,DY,OY,kY,AY,zet,Bet=n((()=>{I(),ka(),b(),Let=10,yY=[],bY=0,xY=!1,SY=0,CY=0,wY=!1,Ret=/^[\p{L}\p{N}\p{M}_]$/u,TY=/\s/,EY=e=>Ret.test(e),DY=e=>TY.test(e),OY=e=>e.length>0&&!DY(e)&&!EY(e),kY=class e{constructor(e,t=0,n=0){x(this,`measuredText`,void 0),x(this,`selection`,void 0),x(this,`offset`,void 0),this.measuredText=e,this.selection=n,this.offset=Math.max(0,Math.min(this.text.length,t))}static fromText(t,n,r=0,i=0){return new e(new zet(t,n-1),r,i)}getViewportStartLine(e){if(e===void 0||e<=0)return 0;let{line:t}=this.getPosition(),n=this.measuredText.getWrappedText();if(n.length<=e)return 0;let r=Math.floor(e/2),i=Math.max(0,t-r),a=Math.min(n.length,i+e);return a-i<e&&(i=Math.max(0,a-e)),i}getViewportCharOffset(e){let t=this.getViewportStartLine(e);return t===0?0:this.measuredText.getWrappedLines()[t]?.startOffset??0}getViewportCharEnd(e){let t=this.getViewportStartLine(e),n=this.measuredText.getWrappedLines();if(e===void 0||e<=0)return this.text.length;let r=Math.min(n.length,t+e);return r>=n.length?this.text.length:n[r]?.startOffset??this.text.length}render(e,t,n,r,i){let{line:a,column:o}=this.getPosition(),s=this.measuredText.getWrappedText(),c=this.getViewportStartLine(i),l=i!==void 0&&i>0?Math.min(s.length,c+i):s.length;return s.slice(c,l).map((i,l)=>{let u=l+c,d=i;if(t){let e=Array.from(Oa().segment(i));if(u===s.length-1){let n=Math.min(6,e.length),r=e.length-n,a=e.length>n?e[r].index:0;d=t.repeat(r)+i.slice(a)}else d=t.repeat(e.length)}if(a!==u)return d.trimEnd();let f=``,p=e,m=``,h=0,g=!1;for(let{segment:e}of Oa().segment(d)){if(g){m+=e;continue}let t=h+ye(e);t>o?(p=e,g=!0):(h=t,f+=e)}let _,v=``;if(r&&u===s.length-1&&this.isAtEnd()&&r.text.length>0){let t=$ie(r.text)||r.text[0];_=e?n(t):t;let i=r.text.slice(t.length);i.length>0&&(v=r.dim(i))}else _=e?n(p):p;return f+_+v+m.trimEnd()}).join(`
1651
+ `).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&&va(g,`tag`)||void 0,createdAt:f}}async function SJ(e,t,n){let r;try{r=await kl(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=qie(r.slice(0,-6));if(!i)return null;let a=Y(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await Nl(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function H7e(e){let t=await Wie(e.filePath);if(!t)return null;let n=V7e(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function U7e(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function W7e(e,t,n){e.sort(U7e);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+Y7e,e.length),c=e.slice(t,s),l=await Promise.all(c.map(H7e));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 G7e(e){let t=await Promise.all(e.map(H7e)),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 K7e(e,t,n){let r=await Yie(e),i;if(t)try{i=await Kie(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await ya(r);return e?SJ(e,n,r):[]}let a=ha(),o=process.platform===`win32`,s=i.map(e=>{let t=_a(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await kl(a,{withFileTypes:!0})}catch{let e=await ya(r);return e?SJ(e,n,r):[]}let l=[],u=new Set,d=await ya(r);if(d){let e=Kc(d);u.add(o?e.toLowerCase():e),l.push(...await SJ(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 SJ(Y(a,e.name),n,r));break}}}return l}async function q7e(e){let t=ha(),n;try{n=await kl(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>SJ(Y(t,n.name),e)))).flat()}async function J7e(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 K7e(t,i??!0,o):await q7e(o);return o?W7e(s,n,a):G7e(s)}var Y7e,X7e=n((()=>{Uie(),ga(),Y7e=32}));function CJ(){return Y(xi(),n9e)}async function Z7e(){try{return(await Nl(CJ())).mtimeMs}catch{return 0}}async function Q7e(){let e=CJ(),t,n;try{let[r,i]=await Promise.all([Nl(e),Ol(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<r9e&&n!==void 0&&yc(n))return U(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await El(xi(),{recursive:!0}),await Il(e,String(process.pid));let r;try{r=await Ol(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function $7e(e){let t=CJ();try{if(e===0){await Fl(t);return}await Il(t,``);let n=e/1e3;await mue(t,n,n)}catch(e){U(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function e9e(e){return(await SJ(s8(Xt()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function t9e(){try{await El(xi(),{recursive:!0}),await Il(CJ(),String(process.pid))}catch(e){U(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var n9e,r9e,wJ=n((()=>{Wt(),hi(),W(),bc(),X7e(),h8(),n9e=`.consolidate-lock`,r9e=3600*1e3}));function i9e(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function a9e(e,t){let n=s5(`dream`);return OL({...c5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function o9e(e,t,n,r){DL(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 s9e(e,t){DL(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function c9e(e,t){DL(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var TJ,EJ=n((()=>{wJ(),l5(),AL(),TJ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;DL(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 $7e(n)}}})),DJ,l9e=n((()=>{gt(),_t(),DJ=ht(()=>B({restrictions:rt(L(),B({allowed:ft()}))}))}));function u9e(e){return e instanceof Error}function d9e(){FJ||AJ()&&(FJ=new Promise(e=>{IJ=e,setTimeout(()=>{IJ&&(U(`Policy limits: Loading promise timed out, resolving anyway`),IJ(),IJ=null)},j9e)}))}function OJ(){return Y(p(),O9e)}function f9e(){return`${Va().BASE_API_URL}/api/claude_code/policy_limits`}function kJ(e){if(Array.isArray(e))return e.map(kJ);if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e).sort(([e],[t])=>e.localeCompare(t)))t[n]=kJ(r);return t}return e}function p9e(e){let t=V(kJ(e));return`sha256:${vl(`sha256`).update(t).digest(`hex`)}`}function AJ(){if(Vo()!==`firstParty`||!Zo())return!1;try{let{key:e}=To({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return!0}catch{}let e=vo();return!(!e?.accessToken||!e.scopes?.includes(`user:inference`)||e.subscriptionType!==`enterprise`&&e.subscriptionType!==`team`)}async function m9e(){FJ&&await FJ}function h9e(){try{let{key:e}=To({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return{headers:{"x-api-key":e}}}catch{}let e=vo();return e?.accessToken?{headers:{Authorization:`Bearer ${e.accessToken}`,"anthropic-beta":aae}}:{headers:{},error:`No authentication available`}}async function g9e(e){let t=null;for(let n=1;n<=6;n++){if(t=await _9e(e),t.success||t.skipRetry||n>MJ)return t;let r=cR(n);U(`Policy limits: Retry ${n}/${MJ} after ${r}ms`),await $o(r)}return t}async function _9e(e){try{await Ko();let t=h9e();if(t.error)return{success:!1,error:`Authentication required for policy limits`,skipRetry:!0};let n=f9e(),r={...t.headers,"User-Agent":Ose()};e&&(r[`If-None-Match`]=`"${e}"`);let i=await ue.get(n,{headers:r,timeout:k9e,validateStatus:e=>e===200||e===304||e===404});if(i.status===304)return U(`Policy limits: Using cached restrictions (304)`),{success:!0,restrictions:null,etag:e};if(i.status===404)return U(`Policy limits: No restrictions found (404)`),{success:!0,restrictions:{},etag:void 0};let a=DJ().safeParse(i.data);return a.success?(U(`Policy limits: Fetched successfully`),{success:!0,restrictions:a.data.restrictions}):(U(`Policy limits: Invalid response format - ${a.error.message}`),{success:!1,error:`Invalid policy limits format`})}catch(e){let{kind:t,message:n}=Sne(e);switch(t){case`auth`:return{success:!1,error:`Not authorized for policy limits`,skipRetry:!0};case`timeout`:return{success:!1,error:`Policy limits request timeout`};case`network`:return{success:!1,error:`Cannot connect to server`};default:return{success:!1,error:n}}}}function v9e(){try{let e=Ea(dl(OJ(),`utf-8`),!1),t=DJ().safeParse(e);return t.success?t.data.restrictions:null}catch{return null}}async function y9e(e){try{let t=OJ();await Il(t,V({restrictions:e},null,2),{encoding:`utf-8`,mode:384}),U(`Policy limits: Saved to ${t}`)}catch(e){U(`Policy limits: Failed to save - ${e instanceof Error?e.message:`unknown error`}`)}}async function jJ(){if(!AJ())return null;let e=v9e(),t=e?p9e(e):void 0;try{let n=await g9e(t);if(!n.success)return e?(U(`Policy limits: Using stale cache after fetch failure`),LJ=e,e):null;if(n.restrictions===null&&e)return U(`Policy limits: Cache still valid (304 Not Modified)`),LJ=e,e;let r=n.restrictions||{};if(Object.keys(r).length>0)return LJ=r,await y9e(r),U(`Policy limits: Applied new restrictions successfully`),r;LJ=r;try{await Fl(OJ()),U(`Policy limits: Deleted cached file (404 response)`)}catch(e){u9e(e)&&e.code!==`ENOENT`&&U(`Policy limits: Failed to delete cached file - ${e.message}`)}return r}catch{return e?(U(`Policy limits: Using stale cache after error`),LJ=e,e):null}}function b9e(e){let t=x9e();if(!t)return!(Iie()&&M9e.has(e));let n=t[e];return!n||n.allowed}function x9e(){if(!AJ())return null;if(LJ)return LJ;let e=v9e();return e?(LJ=e,e):null}async function S9e(){AJ()&&!FJ&&(FJ=new Promise(e=>{IJ=e}));try{await jJ(),AJ()&&E9e()}finally{IJ&&(IJ(),IJ=null)}}async function C9e(){await w9e(),AJ()&&(await jJ(),U(`Policy limits: Refreshed after auth change`))}async function w9e(){D9e(),LJ=null,FJ=null,IJ=null;try{await Fl(OJ())}catch{}}async function T9e(){if(!AJ())return;let e=LJ?V(LJ):null;try{await jJ(),(LJ?V(LJ):null)!==e&&U(`Policy limits: Changed during background poll`)}catch{}}function E9e(){NJ===null&&AJ()&&(NJ=setInterval(()=>{T9e()},A9e),NJ.unref(),PJ||(PJ=!0,Gn(async()=>D9e())))}function D9e(){NJ!==null&&(clearInterval(NJ),NJ=null)}var O9e,k9e,MJ,A9e,NJ,PJ,FJ,IJ,j9e,LJ,M9e,RJ=n((()=>{de(),Ha(),no(),Jn(),W(),h(),On(),wa(),Jo(),Fie(),Po(),Yn(),Dse(),vR(),l9e(),O9e=`policy-limits.json`,k9e=1e4,MJ=5,A9e=3600*1e3,NJ=null,PJ=!1,FJ=null,IJ=null,j9e=3e4,LJ=null,M9e=new Set([`allow_product_feedback`])}));async function N9e(){let e=vo()?.accessToken;if(!e)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await _o();if(!t)throw Error(`Unable to get organization UUID`);let n=`${Va().BASE_API_URL}/v1/environment_providers`;try{let r={...Bc(e),"x-organization-uuid":t},i=await ue.get(n,{headers:r,timeout:15e3});if(i.status!==200)throw Error(`Failed to fetch environments: ${i.status} ${i.statusText}`);return i.data.environments}catch(e){let t=jn(e);throw q(t),Error(`Failed to fetch environments: ${t.message}`)}}var P9e=n((()=>{de(),Ha(),bo(),no(),On(),Qi(),Vc()}));async function F9e(){return uo()?Ko():!1}async function I9e(){return await vie({ignoreUntracked:!0})}async function L9e(e,t,n){try{let r=vo()?.accessToken;if(!r)return U(`checkGithubAppInstalled: No access token found, assuming app not installed`),!1;let i=await _o();if(!i)return U(`checkGithubAppInstalled: No org UUID found, assuming app not installed`),!1;let a=`${Va().BASE_API_URL}/api/oauth/organizations/${i}/code/repos/${e}/${t}`,o={...Bc(r),"x-organization-uuid":i};U(`Checking GitHub app installation for ${e}/${t}`);let s=await ue.get(a,{headers:o,timeout:15e3,signal:n});if(s.status===200){if(s.data.status){let n=s.data.status.app_installed;return U(`GitHub app ${n?`is`:`is not`} installed on ${e}/${t}`),n}return U(`GitHub app is not installed on ${e}/${t} (status is null)`),!1}return U(`checkGithubAppInstalled: Unexpected response status ${s.status}`),!1}catch(n){if(ue.isAxiosError(n)){let r=n.response?.status;if(r&&r>=400&&r<500)return U(`checkGithubAppInstalled: Got ${r} error, app likely not installed on ${e}/${t}`),!1}return U(`checkGithubAppInstalled error: ${H(n)}`),!1}}var zJ=n((()=>{de(),Ha(),bo(),no(),vn(),W(),Rc(),On(),Mi(),Vc(),P9e()})),R9e=n((()=>{RJ(),Rc(),h(),zJ()}));function BJ(){if(process.stdout.isTTY)try{fl(1,qe);let e=Ae.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{fl(1,vee)}e?.drainStdin(),e?.detachForShutdown(),fl(1,fe),fl(1,ke),fl(1,nee),fl(1,see),fl(1,gee),fl(1,lee),Ke()&&fl(1,dee(pee)),m(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:fl(1,Ve))}catch{}}function VJ(){if(!GJ&&process.stdout.isTTY&&zt()&&!Dt())try{let e=sn();if(!p6(e))return;let t=I6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,fl(1,Ue.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),GJ=!0}catch{}}function HJ(e){qJ!==void 0&&(clearTimeout(qJ),qJ=void 0);try{Ae.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function UJ(e=0,t=`other`,n){process.exitCode=e,V9e=WJ(e,t,n).catch(t=>{U(`Graceful shutdown failed: ${t}`,{level:`error`}),BJ(),VJ(),HJ(e)}).catch(()=>{})}function z9e(){return KJ}async function WJ(e=0,t=`other`,n){if(KJ)return;KJ=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-CjR3Eq0Z.js`),a=i();qJ=setTimeout(e=>{BJ(),VJ(),HJ(e)},Math.max(5e3,a+3500),e),qJ.unref(),process.exitCode=e,BJ(),VJ();let o;try{let e=(async()=>{try{await Ene()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new H9e),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{eae()}catch{}let s=Hee();s&&J(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([ole(),sle()]),$o(500)])}catch{}if(n?.finalMessage)try{fl(2,`${n.finalMessage}\n`)}catch{}HJ(e)}var GJ,B9e,KJ,qJ,JJ,V9e,H9e,YJ=n((()=>{Ge(),d(),re(),Wt(),I(),cle(),ile(),Da(),Jn(),W(),Ei(),h(),h8(),Po(),tae(),GJ=!1,B9e=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Ai(`info`,`shutdown_signal`,{signal:`SIGINT`}),WJ(0))}),process.on(`SIGTERM`,()=>{Ai(`info`,`shutdown_signal`,{signal:`SIGTERM`}),WJ(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Ai(`info`,`shutdown_signal`,{signal:`SIGHUP`}),WJ(129)}),process.stdin.isTTY&&(JJ=setInterval(()=>{pte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(JJ),Ai(`info`,`shutdown_signal`,{signal:`orphan_detected`}),WJ(129))},3e4),JJ.unref())),process.on(`uncaughtException`,e=>{Ai(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),J(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;Ai(`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)}),J(`tengu_unhandled_rejection`,{error_name:t})})}),KJ=!1,H9e=class extends Error{constructor(){super(`Cleanup timeout`)}}}));function XJ(){let e=lV(),t=cV(),n=(0,ZJ.useCallback)(()=>{t(e=>{let r=U9e(e.notifications.queue);return e.notifications.current!==null||!r?e:($J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},r.timeoutMs??QJ,t,r.key,n),{...e,notifications:{queue:e.notifications.queue.filter(e=>e!==r),current:r}})})},[t]),r=(0,ZJ.useCallback)(e=>{if(e.priority===`immediate`){$J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t.key?{...e,notifications:{queue:e.notifications.queue.filter(e=>!t.invalidates?.includes(e.key)),current:null}}:e),n()},e.timeoutMs??QJ,t,e,n),t(t=>({...t,notifications:{current:e,queue:[...t.notifications.current?[t.notifications.current]:[],...t.notifications.queue].filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key))}}));return}t(r=>{if(e.fold){if(r.notifications.current?.key===e.key){let i=e.fold(r.notifications.current,e);return $J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},i.timeoutMs??QJ,t,i.key,n),{...r,notifications:{current:i,queue:r.notifications.queue}}}let i=r.notifications.queue.findIndex(t=>t.key===e.key);if(i!==-1){let t=e.fold(r.notifications.queue[i],e),n=[...r.notifications.queue];return n[i]=t,{...r,notifications:{current:r.notifications.current,queue:n}}}}if(!(!new Set(r.notifications.queue.map(e=>e.key)).has(e.key)&&r.notifications.current?.key!==e.key))return r;let i=r.notifications.current!==null&&e.invalidates?.includes(r.notifications.current.key);return i&&$J&&(clearTimeout($J),$J=null),{...r,notifications:{current:i?null:r.notifications.current,queue:[...r.notifications.queue.filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key)),e]}}}),n()},[t,n]),i=(0,ZJ.useCallback)(e=>{t(t=>{let n=t.notifications.current?.key===e,r=t.notifications.queue.some(t=>t.key===e);return!n&&!r?t:(n&&$J&&(clearTimeout($J),$J=null),{...t,notifications:{current:n?null:t.notifications.current,queue:t.notifications.queue.filter(t=>t.key!==e)}})}),n()},[t,n]);return(0,ZJ.useEffect)(()=>{e.getState().notifications.queue.length>0&&n()},[]),{addNotification:r,removeNotification:i}}function U9e(e){if(e.length!==0)return e.reduce((e,t)=>eY[t.priority]<eY[e.priority]?t:e)}var ZJ,QJ,$J,eY,tY=n((()=>{ZJ=r(ze(),1),mV(),QJ=8e3,$J=null,eY={immediate:0,high:1,medium:2,low:3}}));function W9e(){let e=process.platform,t=process.env.CLAUDE_CODE_TMPDIR||(e===`win32`?process.env.TEMP||`C:\\Temp`:Wc()),n=`claude_cli_latest_screenshot.png`,r={darwin:Y(t,n),linux:Y(t,n),win32:Y(t,n)},i=r[e]||r.linux,a={darwin:{checkImage:`osascript -e 'the clipboard as «class PNGf»'`,saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${i}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:`osascript -e 'get POSIX path of (the clipboard as «class furl»)'`,deleteFile:`rm -f "${i}"`},linux:{checkImage:`xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"`,saveImage:`xclip -selection clipboard -t image/png -o > "${i}" 2>/dev/null || wl-paste --type image/png > "${i}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${i}" 2>/dev/null || wl-paste --type image/bmp > "${i}"`,getPath:`xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null`,deleteFile:`rm -f "${i}"`},win32:{checkImage:`powershell -NoProfile -Command "(Get-Clipboard -Format Image) -ne $null"`,saveImage:`powershell -NoProfile -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${i.replace(/\\/g,`\\\\`)}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:`powershell -NoProfile -Command "Get-Clipboard"`,deleteFile:`del /f "${i}"`}};return{commands:a[e]||a.linux,screenshotPath:i}}async function G9e(){return process.platform===`darwin`&&(await Li(`osascript`,[`-e`,`the clipboard as «class PNGf»`])).code===0}async function nY(){let{commands:e,screenshotPath:t}=W9e();try{if((await Ri(e.checkImage,{shell:!0,reject:!1})).exitCode!==0||(await Ri(e.saveImage,{shell:!0,reject:!1})).exitCode!==0)return null;let n=G().readFileBytesSync(t);n.length>=2&&n[0]===66&&n[1]===77&&(n=await(await J_())(n).png().toBuffer());let r=await X_(n,n.length,`png`),i=r.buffer.toString(`base64`),a=$_(i);return Ri(e.deleteFile,{shell:!0,reject:!1}),{base64:i,mediaType:a,dimensions:r.dimensions}}catch{return null}}async function K9e(){let{commands:e}=W9e();try{let t=await Ri(e.getPath,{shell:!0,reject:!1});return t.exitCode!==0||!t.stdout?null:t.stdout.trim()}catch(e){return q(e),null}}function q9e(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function J9e(e){if(process.platform===`win32`)return e;let t=`__DOUBLE_BACKSLASH_${yl(8).toString(`hex`)}__`;return e.replace(/\\\\/g,t).replace(/\\(.)/g,`$1`).replace(new RegExp(t,`g`),`\\`)}function rY(e){let t=J9e(q9e(e.trim()));return iY.test(t)}function Y9e(e){let t=J9e(q9e(e.trim()));return iY.test(t)?t:null}async function X9e(e){let t=Y9e(e);if(!t)return null;let n=t,r;try{if(Yc(n))r=G().readFileBytesSync(n);else{let e=await K9e();e&&n===Kc(e)&&(r=G().readFileBytesSync(e))}}catch(e){return q(e),null}if(!r)return null;if(r.length===0)return U(`Image file is empty: ${n}`,{level:`warn`}),null;r.length>=2&&r[0]===66&&r[1]===77&&(r=await(await J_())(r).png().toBuffer());let i=Jc(n).slice(1).toLowerCase()||`png`,a=await X_(r,r.length,i),o=a.buffer.toString(`base64`);return{path:n,base64:o,mediaType:$_(o),dimensions:a.dimensions}}var iY,aY=n((()=>{Ii(),G_(),Sbe(),W(),zi(),Bn(),rv(),Qi(),iY=/\.(png|jpe?g|gif|webp)$/i}));function Z9e(e,t){let{addNotification:n}=XJ(),r=(0,oY.useRef)(e),i=(0,oY.useRef)(0),a=(0,oY.useRef)(null);(0,oY.useEffect)(()=>{let o=r.current;if(r.current=e,!(!t||!e||o))return a.current&&clearTimeout(a.current),a.current=setTimeout(async(e,t,n)=>{e.current=null;let r=Date.now();r-t.current<eet||await G9e()&&(t.current=r,n({key:Q9e,text:`Image in clipboard · ${ib(`chat:imagePaste`,`Chat`,`ctrl+v`)} to paste`,priority:`immediate`,timeoutMs:8e3}))},$9e,a,i,n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n])}var oY,Q9e,$9e,eet,tet=n((()=>{oY=r(ze(),1),tY(),ob(),aY(),Q9e=`clipboard-image-hint`,$9e=1e3,eet=3e4}));function net(e,t){switch(t){case`bash`:return`!${e}`;default:return e}}function ret(e){return e.startsWith(`!`)?`bash`:`prompt`}function iet(e){return ret(e)===`prompt`?e:e.slice(1)}function aet(e){return e===`!`}var oet=n((()=>{}));function sY(){return Y(p(),pet)}function set(e){return vl(`sha256`).update(e).digest(`hex`).slice(0,16)}function cet(e){return Y(sY(),`${e}.txt`)}async function uet(e,t){try{await El(sY(),{recursive:!0});let n=cet(e);await Il(n,t,{encoding:`utf8`,mode:384}),U(`Stored paste ${e} to ${n}`)}catch(e){U(`Failed to store paste: ${e}`)}}async function det(e){try{return await Ol(cet(e),{encoding:`utf8`})}catch(t){return xn(t)||U(`Failed to retrieve paste ${e}: ${t}`),null}}async function fet(e){let t=sY(),n;try{n=await kl(t)}catch{return}let r=e.getTime();for(let e of n){if(!e.endsWith(`.txt`))continue;let n=Y(t,e);try{(await Nl(n)).mtimeMs<r&&(await Fl(n),U(`Cleaned up old paste: ${n}`))}catch{}}}var pet,met=n((()=>{W(),h(),On(),pet=`paste-cache`}));function het(e){return(e.match(/\r\n|\r|\n/g)||[]).length}function get(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}function _et(e){return`[Image #${e}]`}function vet(e){return[...e.matchAll(/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.)*\]/g)].map(e=>({id:parseInt(e[2]||`0`,10),match:e[0],index:e.index})).filter(e=>e.id>0)}function yet(e,t){let n=vet(e),r=e;for(let e=n.length-1;e>=0;e--){let i=n[e],a=t[i.id];a?.type===`text`&&(r=r.slice(0,i.index)+a.content+r.slice(i.index+i.match.length))}return r}function bet(e){return kn(e)}async function*xet(){let e=sn();for(let e=uY.length-1;e>=0;e--)yield uY[e];let t=Y(p(),`history.jsonl`);try{for await(let n of wne(t))try{let t=bet(n);if(t.sessionId===e&&hY.has(t.timestamp))continue;yield t}catch(e){U(`Failed to parse history line: ${e}`)}}catch(e){if(Cn(e)===`ENOENT`)return;throw e}}async function*Cet(){for await(let e of xet())yield await cY(e)}async function*wet(){let e=en(),t=sn(),n=[],r=0;for await(let i of xet())if(!(!i||typeof i.project!=`string`)&&i.project===e&&(i.sessionId===t?(yield await cY(i),r++):n.push(i),r+n.length>=lY))break;for(let e of n){if(r>=lY)return;yield await cY(e),r++}}async function Tet(e){if(e.content)return{id:e.id,type:e.type,content:e.content,mediaType:e.mediaType,filename:e.filename};if(e.contentHash){let t=await det(e.contentHash);if(t)return{id:e.id,type:e.type,content:t,mediaType:e.mediaType,filename:e.filename}}return null}async function cY(e){let t={};for(let[n,r]of Object.entries(e.pastedContents||{})){let e=await Tet(r);e&&(t[Number(n)]=e)}return{display:e.display,pastedContents:t}}async function Eet(){if(uY.length===0)return;let e;try{let t=Y(p(),`history.jsonl`);await Il(t,``,{encoding:`utf8`,mode:384,flag:`a`}),e=await mi(t,{stale:1e4,retries:{retries:3,minTimeout:50}});let n=uY.map(e=>`${V(e)}\n`);uY=[],await Sl(t,n.join(``),{mode:384})}catch(e){U(`Failed to write prompt history: ${e}`)}finally{e&&await e()}}async function Det(e){if(!(dY||uY.length===0)&&!(e>5)){dY=!0;try{await Eet()}finally{dY=!1,uY.length>0&&(await $o(500),Det(e+1))}}}async function Oet(e){let t=typeof e==`string`?{display:e,pastedContents:{}}:e,n={};if(t.pastedContents){for(let[e,r]of Object.entries(t.pastedContents))if(r.type!==`image`)if(r.content.length<=jet)n[Number(e)]={id:r.id,type:r.type,content:r.content,mediaType:r.mediaType,filename:r.filename};else{let t=set(r.content);n[Number(e)]={id:r.id,type:r.type,contentHash:t,mediaType:r.mediaType,filename:r.filename},uet(t,r.content)}}let r={...t,pastedContents:n,timestamp:Date.now(),project:en(),sessionId:sn()};uY.push(r),mY=r,fY=Det(0)}function ket(e){m(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)||(pY||(pY=!0,Gn(async()=>{fY&&await fY,uY.length>0&&await Eet()})),Oet(e))}function Aet(){if(!mY)return;let e=mY;mY=null;let t=uY.lastIndexOf(e);t===-1?hY.add(e.timestamp):uY.splice(t,1)}var lY,jet,uY,dY,fY,pY,mY,hY,Met=n((()=>{Wt(),Jn(),W(),h(),On(),Bn(),vi(),met(),Po(),Yn(),lY=100,jet=1024,uY=[],dY=!1,fY=null,pY=!1,mY=null,hY=new Set}));function gY(e,t=`append`){e.length>0&&(xY&&yY.length>0?t===`prepend`?yY[0]=e+yY[0]:yY[0]+=e:(yY.unshift(e),yY.length>Let&&yY.pop()),xY=!0,wY=!1)}function Net(){return yY[0]??``}function _Y(){xY=!1}function Pet(e,t){SY=e,CY=t,wY=!0,bY=0}function Fet(){return!wY||yY.length<=1?null:(bY=(bY+1)%yY.length,{text:yY[bY]??``,start:SY,length:CY})}function Iet(e){CY=e}function vY(){wY=!1}var Let,yY,bY,xY,SY,CY,wY,Ret,TY,EY,DY,OY,kY,AY,zet,Bet=n((()=>{I(),ka(),b(),Let=10,yY=[],bY=0,xY=!1,SY=0,CY=0,wY=!1,Ret=/^[\p{L}\p{N}\p{M}_]$/u,TY=/\s/,EY=e=>Ret.test(e),DY=e=>TY.test(e),OY=e=>e.length>0&&!DY(e)&&!EY(e),kY=class e{constructor(e,t=0,n=0){x(this,`measuredText`,void 0),x(this,`selection`,void 0),x(this,`offset`,void 0),this.measuredText=e,this.selection=n,this.offset=Math.max(0,Math.min(this.text.length,t))}static fromText(t,n,r=0,i=0){return new e(new zet(t,n-1),r,i)}getViewportStartLine(e){if(e===void 0||e<=0)return 0;let{line:t}=this.getPosition(),n=this.measuredText.getWrappedText();if(n.length<=e)return 0;let r=Math.floor(e/2),i=Math.max(0,t-r),a=Math.min(n.length,i+e);return a-i<e&&(i=Math.max(0,a-e)),i}getViewportCharOffset(e){let t=this.getViewportStartLine(e);return t===0?0:this.measuredText.getWrappedLines()[t]?.startOffset??0}getViewportCharEnd(e){let t=this.getViewportStartLine(e),n=this.measuredText.getWrappedLines();if(e===void 0||e<=0)return this.text.length;let r=Math.min(n.length,t+e);return r>=n.length?this.text.length:n[r]?.startOffset??this.text.length}render(e,t,n,r,i){let{line:a,column:o}=this.getPosition(),s=this.measuredText.getWrappedText(),c=this.getViewportStartLine(i),l=i!==void 0&&i>0?Math.min(s.length,c+i):s.length;return s.slice(c,l).map((i,l)=>{let u=l+c,d=i;if(t){let e=Array.from(Oa().segment(i));if(u===s.length-1){let n=Math.min(6,e.length),r=e.length-n,a=e.length>n?e[r].index:0;d=t.repeat(r)+i.slice(a)}else d=t.repeat(e.length)}if(a!==u)return d.trimEnd();let f=``,p=e,m=``,h=0,g=!1;for(let{segment:e}of Oa().segment(d)){if(g){m+=e;continue}let t=h+ye(e);t>o?(p=e,g=!0):(h=t,f+=e)}let _,v=``;if(r&&u===s.length-1&&this.isAtEnd()&&r.text.length>0){let t=$ie(r.text)||r.text[0];_=e?n(t):t;let i=r.text.slice(t.length);i.length>0&&(v=r.dim(i))}else _=e?n(p):p;return f+_+v+m.trimEnd()}).join(`
1652
1652
  `)}left(){if(this.offset===0)return this;let t=this.imageRefEndingAt(this.offset);if(t)return new e(this.measuredText,t.start);let n=this.measuredText.prevOffset(this.offset);return new e(this.measuredText,n)}right(){if(this.offset>=this.text.length)return this;let t=this.imageRefStartingAt(this.offset);if(t)return new e(this.measuredText,t.end);let n=this.measuredText.nextOffset(this.offset);return new e(this.measuredText,Math.min(n,this.text.length))}imageRefEndingAt(e){let t=this.text.slice(0,e).match(/\[Image #\d+\]$/);return t?{start:e-t[0].length,end:e}:null}imageRefStartingAt(e){let t=this.text.slice(e).match(/^\[Image #\d+\]/);return t?{start:e,end:e+t[0].length}:null}snapOutOfImageRef(e,t){let n=/\[Image #\d+\]/g,r;for(;(r=n.exec(this.text))!==null;){let n=r.index,i=n+r[0].length;if(e>n&&e<i)return t===`start`?n:i}return e}up(){let{line:t,column:n}=this.getPosition();if(t===0)return this;let r=this.measuredText.getWrappedText()[t-1];if(r===void 0)return this;let i=ye(r);if(n>i){let n=this.getOffset({line:t-1,column:i});return new e(this.measuredText,n,0)}let a=this.getOffset({line:t-1,column:n});return new e(this.measuredText,a,0)}down(){let{line:t,column:n}=this.getPosition();if(t>=this.measuredText.lineCount-1)return this;let r=this.measuredText.getWrappedText()[t+1];if(r===void 0)return this;let i=ye(r);if(n>i){let n=this.getOffset({line:t+1,column:i});return new e(this.measuredText,n,0)}let a=this.getOffset({line:t+1,column:n});return new e(this.measuredText,a,0)}startOfCurrentLine(){let{line:t}=this.getPosition();return new e(this.measuredText,this.getOffset({line:t,column:0}),0)}startOfLine(){let{line:t,column:n}=this.getPosition();return n===0&&t>0?new e(this.measuredText,this.getOffset({line:t-1,column:0}),0):this.startOfCurrentLine()}firstNonBlankInLine(){let{line:t}=this.getPosition(),n=(this.measuredText.getWrappedText()[t]||``).match(/^\s*\S/),r=n?.index?n.index+n[0].length-1:0,i=this.getOffset({line:t,column:r});return new e(this.measuredText,i,0)}endOfLine(){let{line:t}=this.getPosition(),n=this.measuredText.getLineLength(t),r=this.getOffset({line:t,column:n});return new e(this.measuredText,r,0)}findLogicalLineStart(e=this.offset){let t=this.text.lastIndexOf(`
1653
1653
  `,e-1);return t===-1?0:t+1}findLogicalLineEnd(e=this.offset){let t=this.text.indexOf(`
1654
1654
  `,e);return t===-1?this.text.length:t}getLogicalLineBounds(){return{start:this.findLogicalLineStart(),end:this.findLogicalLineEnd()}}createCursorWithColumn(t,n,r){let i=n-t,a=t+Math.min(r,i),o=this.measuredText.snapToGraphemeBoundary(a);return new e(this.measuredText,o,0)}endOfLogicalLine(){return new e(this.measuredText,this.findLogicalLineEnd(),0)}startOfLogicalLine(){return new e(this.measuredText,this.findLogicalLineStart(),0)}firstNonBlankInLogicalLine(){let{start:t,end:n}=this.getLogicalLineBounds(),r=t+(this.text.slice(t,n).match(/\S/)?.index??0);return new e(this.measuredText,r,0)}upLogicalLine(){let{start:t}=this.getLogicalLineBounds();if(t===0)return new e(this.measuredText,0,0);let n=this.offset-t,r=t-1,i=this.findLogicalLineStart(r);return this.createCursorWithColumn(i,r,n)}downLogicalLine(){let{start:t,end:n}=this.getLogicalLineBounds();if(n>=this.text.length)return new e(this.measuredText,this.text.length,0);let r=this.offset-t,i=n+1,a=this.findLogicalLineEnd(i);return this.createCursorWithColumn(i,a,r)}nextWord(){if(this.isAtEnd())return this;let t=this.measuredText.getWordBoundaries();for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.start);return new e(this.measuredText,this.text.length)}endOfWord(){if(this.isAtEnd())return this;let t=this.measuredText.getWordBoundaries();for(let n of t)if(n.isWordLike){if(this.offset>=n.start&&this.offset<n.end-1)return new e(this.measuredText,n.end-1);if(this.offset===n.end-1){for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.end-1);return this}}for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.end-1);return this}prevWord(){if(this.isAtStart())return this;let t=this.measuredText.getWordBoundaries(),n=null;for(let r of t)if(r.isWordLike&&r.start<this.offset){if(this.offset>r.start&&this.offset<=r.end)return new e(this.measuredText,r.start);n=r.start}return n===null?new e(this.measuredText,0):new e(this.measuredText,n)}nextVimWord(){if(this.isAtEnd())return this;let t=this.offset,n=e=>this.measuredText.nextOffset(e),r=this.graphemeAt(t);if(!r)return this;if(EY(r))for(;t<this.text.length&&EY(this.graphemeAt(t));)t=n(t);else if(OY(r))for(;t<this.text.length&&OY(this.graphemeAt(t));)t=n(t);for(;t<this.text.length&&TY.test(this.graphemeAt(t));)t=n(t);return new e(this.measuredText,t)}endOfVimWord(){if(this.isAtEnd())return this;let t=this.text,n=this.offset,r=e=>this.measuredText.nextOffset(e);if(this.graphemeAt(n)===``)return this;for(n=r(n);n<t.length&&TY.test(this.graphemeAt(n));)n=r(n);if(n>=t.length)return new e(this.measuredText,t.length);let i=this.graphemeAt(n);if(EY(i))for(;n<t.length;){let e=r(n);if(e>=t.length||!EY(this.graphemeAt(e)))break;n=e}else if(OY(i))for(;n<t.length;){let e=r(n);if(e>=t.length||!OY(this.graphemeAt(e)))break;n=e}return new e(this.measuredText,n)}prevVimWord(){if(this.isAtStart())return this;let t=this.offset,n=e=>this.measuredText.prevOffset(e);for(t=n(t);t>0&&TY.test(this.graphemeAt(t));)t=n(t);if(t===0&&TY.test(this.graphemeAt(0)))return new e(this.measuredText,0);let r=this.graphemeAt(t);if(EY(r))for(;t>0;){let e=n(t);if(!EY(this.graphemeAt(e)))break;t=e}else if(OY(r))for(;t>0;){let e=n(t);if(!OY(this.graphemeAt(e)))break;t=e}return new e(this.measuredText,t)}nextWORD(){let e=this;for(;!e.isOverWhitespace()&&!e.isAtEnd();)e=e.right();for(;e.isOverWhitespace()&&!e.isAtEnd();)e=e.right();return e}endOfWORD(){if(this.isAtEnd())return this;let e=this;if(!e.isOverWhitespace()&&(e.right().isOverWhitespace()||e.right().isAtEnd()))return e=e.right(),e.endOfWORD();for(e.isOverWhitespace()&&(e=e.nextWORD());!e.right().isOverWhitespace()&&!e.isAtEnd();)e=e.right();return e}prevWORD(){let e=this;for(e.left().isOverWhitespace()&&(e=e.left());e.isOverWhitespace()&&!e.isAtStart();)e=e.left();if(!e.isOverWhitespace())for(;!e.left().isOverWhitespace()&&!e.isAtStart();)e=e.left();return e}modifyText(t,n=``){let r=this.offset,i=t.offset,a=this.text.slice(0,r)+n+this.text.slice(i);return e.fromText(a,this.columns,r+n.normalize(`NFC`).length)}insert(e){return this.modifyText(this,e)}del(){return this.isAtEnd()?this:this.modifyText(this.right())}backspace(){return this.isAtStart()?this:this.left().modifyText(this)}deleteToLineStart(){if(this.offset>0&&this.text[this.offset-1]===`
@@ -1669,7 +1669,7 @@ duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool
1669
1669
  `)).filter(e=>e.trim()),c=s.filter(e=>rY(e));if(t&&c.length>0){let e=/\/TemporaryItems\/.*screencaptureui.*\/Screenshot/i.test(o);return Promise.all(c.map(e=>X9e(e))).then(c=>{let l=c.filter(e=>e!==null);if(l.length>0){for(let e of l){let n=Kc(e.path);t(e.base64,e.mediaType,n,e.dimensions,e.path)}let e=s.filter(e=>!rY(e));e.length>0&&n&&n(e.join(`
1670
1670
  `)),r(!1)}else e&&a?i():(n&&n(o),r(!1))}),{chunks:[],timeoutId:null}}return a&&t&&o.length===0?(i(),{chunks:[],timeoutId:null}):(n&&n(o),r(!1),{chunks:[],timeoutId:null})})},Qet,i,n,e,o,u,l,c)),[u,l,n,e]);return{wrappedOnInput:(r,a,s)=>{let f=s.keypress.isPasted;f&&o(!0);let p=r.split(/ (?=\/|[A-Za-z]:\\)/).flatMap(e=>e.split(`
1671
1671
  `)).some(e=>rY(e.trim()));if(f&&r.length===0&&l&&n){u(),o(!1);return}if(e&&(r.length>800||c.current||p||f||r.length>=3&&!a.return&&!a.tab&&!a.escape&&!a.upArrow&&!a.downArrow&&!a.leftArrow&&!a.rightArrow)){c.current=!0,i(({chunks:e,timeoutId:t})=>({chunks:[...e,r],timeoutId:d(t)}));return}t(r,a),r.length>10&&o(!1)},pasteState:r,isPasting:a}}var NY,Zet,Qet,$et=n((()=>{NY=r(ze(),1),Qi(),hee(),aY(),ua(),Zet=50,Qet=100}));function ett(e,t){if(t.length===0)return[{text:e,start:0}];let n=[...t].sort((e,t)=>e.start===t.start?t.priority-e.priority:e.start-t.start),r=[],i=[];for(let e of n)e.start!==e.end&&(i.some(t=>e.start>=t.start&&e.start<t.end||e.end>t.start&&e.end<=t.end||e.start<=t.start&&e.end>=t.end)||(r.push(e),i.push({start:e.start,end:e.end})));return new ntt(e).segment(r)}function ttt(e){return Ne(e).filter(e=>e.code!==e.endCode)}var ntt,rtt=n((()=>{ge(),b(),ntt=class{constructor(e){x(this,`text`,void 0),x(this,`tokens`,void 0),x(this,`visiblePos`,0),x(this,`stringPos`,0),x(this,`tokenIdx`,0),x(this,`charIdx`,0),x(this,`codes`,[]),this.text=e,this.tokens=we(e)}segment(e){let t=[];for(let n of e){let e=this.segmentTo(n.start);e&&t.push(e);let r=this.segmentTo(n.end);r&&(r.highlight=n,t.push(r))}let n=this.segmentTo(1/0);return n&&t.push(n),t}segmentTo(e){if(this.tokenIdx>=this.tokens.length||e<=this.visiblePos)return null;let t=this.visiblePos;for(;this.tokenIdx<this.tokens.length;){let e=this.tokens[this.tokenIdx];if(e.type!==`ansi`)break;this.codes.push(e),this.stringPos+=e.code.length,this.tokenIdx++}let n=this.stringPos,r=[...this.codes];for(;this.visiblePos<e&&this.tokenIdx<this.tokens.length;){let t=this.tokens[this.tokenIdx];if(t.type===`ansi`)this.codes.push(t),this.stringPos+=t.code.length,this.tokenIdx++;else{let n=e-this.visiblePos,r=t.value.length-this.charIdx,i=Math.min(n,r);this.stringPos+=i,this.visiblePos+=i,this.charIdx+=i,this.charIdx>=t.value.length&&(this.tokenIdx++,this.charIdx=0)}}if(this.stringPos===n)return null;let i=ttt(r),a=ttt(this.codes);this.codes=a;let o=Se(i),s=Se(yee(a));return{text:o+this.text.substring(n,this.stringPos)+s,start:t}}}}));function itt({char:e,index:t,glimmerIndex:n,messageColor:r,shimmerColor:i}){let a=t===n,o=Math.abs(t-n)===1;return(0,att.jsx)(F,{color:a||o?i:r,children:e})}var att,PY=n((()=>{I(),att=et()}));function ott({text:e,highlights:t}){let{lines:n,hasShimmer:r,sweepStart:i,cycleLength:a}=stt.useMemo(()=>{let n=ett(e,t),r=[[]],i=0;for(let e of n){let t=e.text.split(`
1672
- `);for(let n=0;n<t.length;n++){n>0&&(r.push([]),i+=1);let a=t[n];a.length>0&&r[r.length-1].push({text:a,highlight:e.highlight,start:i}),i+=a.length}}let a=t.some(e=>e.shimmerColor),o=0,s=1;if(a){let e=1/0,n=-1/0;for(let r of t)r.shimmerColor&&(e=Math.min(e,r.start),n=Math.max(n,r.end));o=e-10,s=n-e+20}return{lines:r,hasShimmer:a,sweepStart:o,cycleLength:s}},[e,t]),[o,s]=Ye(r?50:null),c=r?i+Math.floor(s/50)%a:-100;return(0,FY.jsx)(P,{ref:o,flexDirection:`column`,children:n.map((e,t)=>(0,FY.jsx)(P,{children:e.length===0?(0,FY.jsx)(F,{children:` `}):e.map((e,t)=>e.highlight?.shimmerColor&&e.highlight.color?(0,FY.jsx)(F,{children:e.text.split(``).map((t,n)=>(0,FY.jsx)(itt,{char:t,index:e.start+n,glimmerIndex:c,messageColor:e.highlight.color,shimmerColor:e.highlight.shimmerColor},n))},t):(0,FY.jsx)(F,{color:e.highlight?.color,dimColor:e.highlight?.dimColor,inverse:e.highlight?.inverse,children:(0,FY.jsx)(_e,{children:e.text})},t))},t))})}var stt,FY,ctt=n((()=>{stt=r(ze(),1),I(),rtt(),PY(),FY=et()}));function ltt({inputState:e,children:t,terminalFocus:n,invert:r,hidePlaceholderText:i,...a}){let{onInput:o,renderedValue:s,cursorLine:c,cursorColumn:l}=e,u=ve({line:c,column:l,active:!!(a.focus&&a.showCursor&&n)}),{wrappedOnInput:d,isPasting:f}=Xet({onPaste:a.onPaste,onInput:(e,t)=>{f&&t.return||o(e,t)},onImagePaste:a.onImagePaste}),{onIsPastingChange:p}=a;utt.useEffect(()=>{p&&p(f)},[f,p]);let{showPlaceholder:m,renderedPlaceholder:h}=Jet({placeholder:a.placeholder,value:a.value,showCursor:a.showCursor,focus:a.focus,terminalFocus:n,invert:r,hidePlaceholderText:i});Je(d,{isActive:a.focus});let g=a.value&&a.value.trim().indexOf(` `)===-1||a.value?.endsWith(` `),_=!!(a.argumentHint&&a.value&&g&&a.value.startsWith(`/`)),v=a.showCursor&&a.highlights?a.highlights.filter(e=>e.dimColor||a.cursorOffset<e.start||a.cursorOffset>=e.end):a.highlights,{viewportCharOffset:y,viewportCharEnd:b}=e,x=v&&y>0?v.filter(e=>e.end>y&&e.start<b).map(e=>({...e,start:Math.max(0,e.start-y),end:e.end-y})):v;return x&&x.length>0?(0,IY.jsxs)(P,{ref:u,children:[(0,IY.jsx)(ott,{text:s,highlights:x}),_&&(0,IY.jsxs)(F,{dimColor:!0,children:[a.value?.endsWith(` `)?``:` `,a.argumentHint]}),t]}):(0,IY.jsx)(P,{ref:u,children:(0,IY.jsxs)(F,{wrap:`truncate-end`,dimColor:a.dimColor,children:[m&&a.placeholderElement?a.placeholderElement:m&&h?(0,IY.jsx)(_e,{children:h}):(0,IY.jsx)(_e,{children:s}),_&&(0,IY.jsxs)(F,{dimColor:!0,children:[a.value?.endsWith(` `)?``:` `,a.argumentHint]}),t]})})}var utt,IY,dtt=n((()=>{utt=r(ze(),1),Yet(),$et(),I(),ctt(),IY=et()}));function LY(e){let[t]=xe(),n=Ie(),r=(0,ftt.useMemo)(()=>m(process.env.CLAUDE_CODE_ACCESSIBILITY),[]);hV().prefersReducedMotion,Z9e(n,!!e.onImagePaste);let i=n&&!r?Ue.inverse:e=>e;return(0,RY.jsx)(P,{children:(0,RY.jsx)(ltt,{inputState:Ket({value:e.value,onChange:e.onChange,onSubmit:e.onSubmit,onExit:e.onExit,onExitMessage:e.onExitMessage,onHistoryReset:e.onHistoryReset,onHistoryUp:e.onHistoryUp,onHistoryDown:e.onHistoryDown,onClearInput:e.onClearInput,focus:e.focus,mask:e.mask,multiline:e.multiline,cursorChar:e.showCursor?` `:``,highlightPastedText:e.highlightPastedText,invert:i,themeText:ree(`text`,t),columns:e.columns,maxVisibleLines:e.maxVisibleLines,onImagePaste:e.onImagePaste,disableCursorMovementForUpDownKeys:e.disableCursorMovementForUpDownKeys,disableEscapeDoublePress:e.disableEscapeDoublePress,externalOffset:e.cursorOffset,onOffsetChange:e.onChangeCursorOffset,inputFilter:e.inputFilter,inlineGhostText:e.inlineGhostText,dim:Ue.dim}),terminalFocus:n,highlights:e.highlights,invert:i,...e})})}var ftt,RY,zY=n((()=>{Ge(),ftt=r(ze(),1),tet(),gV(),qet(),I(),h(),dtt(),RY=et()}));function ptt({onDone:e}){let[t,n]=(0,BY.useState)({state:`custom_platform`,baseUrl:process.env.ANTHROPIC_BASE_URL??``,apiKey:process.env.ANTHROPIC_AUTH_TOKEN??``,haikuModel:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL??``,sonnetModel:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL??``,opusModel:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL??``,activeField:`base_url`});return(0,BY.useEffect)(()=>{if(t.state===`about_to_retry`){let e=setTimeout(n,1e3,t.nextState);return()=>clearTimeout(e)}},[t]),Fe(`confirm:yes`,()=>{J(`tengu_oauth_success`,{}),e()},{context:`Confirmation`,isActive:t.state===`success`}),Fe(`confirm:yes`,()=>{t.state===`error`&&t.toRetry&&n({state:`about_to_retry`,nextState:t.toRetry})},{context:`Confirmation`,isActive:t.state===`error`&&!!t.toRetry}),(0,VY.jsx)(P,{flexDirection:`column`,gap:1,children:(0,VY.jsx)(P,{paddingLeft:1,flexDirection:`column`,gap:1,children:(0,VY.jsx)(mtt,{oauthStatus:t,setOAuthStatus:n,onDone:e})})})}function mtt({oauthStatus:e,setOAuthStatus:t,onDone:n}){switch(e.state){case`custom_platform`:{let r=[`base_url`,`api_key`,`haiku_model`,`sonnet_model`,`opus_model`],{activeField:i,baseUrl:a,apiKey:o,haikuModel:s,sonnetModel:c,opusModel:l}=e,u={base_url:a,api_key:o,haiku_model:s,sonnet_model:c,opus_model:l},[d,f]=(0,BY.useState)(()=>u[i]),[p,m]=(0,BY.useState)(()=>u[i].length),h=(0,BY.useCallback)((e,t,n)=>{let r={state:`custom_platform`,activeField:n??i,baseUrl:a,apiKey:o,haikuModel:s,sonnetModel:c,opusModel:l};switch(e){case`base_url`:return{...r,baseUrl:t};case`api_key`:return{...r,apiKey:t};case`haiku_model`:return{...r,haikuModel:t};case`sonnet_model`:return{...r,sonnetModel:t};case`opus_model`:return{...r,opusModel:t}}},[i,a,o,s,c,l]),g=(0,BY.useCallback)(()=>{let e={...u,[i]:d},r={};if(e.base_url){try{new URL(e.base_url)}catch{t({state:`error`,message:`Invalid base URL: please enter a full URL including protocol (e.g., https://api.example.com)`,toRetry:{state:`custom_platform`,baseUrl:``,apiKey:``,haikuModel:``,sonnetModel:``,opusModel:``,activeField:`base_url`}});return}r.ANTHROPIC_BASE_URL=e.base_url}e.api_key&&(r.ANTHROPIC_AUTH_TOKEN=e.api_key),e.haiku_model&&(r.ANTHROPIC_DEFAULT_HAIKU_MODEL=e.haiku_model),e.sonnet_model&&(r.ANTHROPIC_DEFAULT_SONNET_MODEL=e.sonnet_model),e.opus_model&&(r.ANTHROPIC_DEFAULT_OPUS_MODEL=e.opus_model);let{error:a}=li(`userSettings`,{modelType:`anthropic`,env:r});if(a)t({state:`error`,message:`Failed to save settings. Please try again.`,toRetry:{state:`custom_platform`,baseUrl:e.base_url??``,apiKey:e.api_key??``,haikuModel:e.haiku_model??``,sonnetModel:e.sonnet_model??``,opusModel:e.opus_model??``,activeField:`base_url`}});else{for(let[e,t]of Object.entries(r))process.env[e]=t;t({state:`success`}),n()}},[i,d,u,t,n]),_=(0,BY.useCallback)(()=>{let e=r.indexOf(i);if(e===r.length-1)t(h(i,d)),g();else{let n=r[e+1];t(h(i,d,n)),f(u[n]??``),m((u[n]??``).length)}},[i,d,h,g,u,t]);Fe(`tabs:next`,()=>{let e=r.indexOf(i);e<r.length-1&&(t(h(i,d,r[e+1])),f(u[r[e+1]]??``),m((u[r[e+1]]??``).length))},{context:`FormField`}),Fe(`tabs:previous`,()=>{let e=r.indexOf(i);e>0&&(t(h(i,d,r[e-1])),f(u[r[e-1]]??``),m((u[r[e-1]]??``).length))},{context:`FormField`}),Fe(`confirm:no`,()=>{n()},{context:`Confirmation`});let v=Xe().columns-20,y=(e,t,n)=>{let r=i===e,a=u[e];return(0,VY.jsxs)(P,{children:[(0,VY.jsx)(F,{backgroundColor:r?`suggestion`:void 0,color:r?`inverseText`:void 0,children:` ${t} `}),(0,VY.jsx)(F,{children:` `}),r?(0,VY.jsx)(LY,{value:d,onChange:f,onSubmit:_,cursorOffset:p,onChangeCursorOffset:m,columns:v,mask:n?.mask?`*`:void 0,focus:!0}):a?(0,VY.jsx)(F,{color:`success`,children:n?.mask?a.slice(0,8)+`·`.repeat(Math.max(0,a.length-8)):a}):null]})};return(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,VY.jsx)(F,{bold:!0,children:`Compatible API Setup`}),(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[y(`base_url`,`Base URL `),y(`api_key`,`API Key `,{mask:!0}),y(`haiku_model`,`Haiku `),y(`sonnet_model`,`Sonnet `),y(`opus_model`,`Opus `)]}),(0,VY.jsx)(F,{dimColor:!0,children:`↑↓/Tab to switch · Enter on last field to save · Esc to go back`})]})}case`about_to_retry`:return(0,VY.jsx)(P,{flexDirection:`column`,gap:1,children:(0,VY.jsx)(F,{color:`permission`,children:`Retrying…`})});case`success`:return(0,VY.jsx)(P,{flexDirection:`column`,children:(0,VY.jsxs)(F,{color:`success`,children:[`Login successful. Press `,(0,VY.jsx)(F,{bold:!0,children:`Enter`}),` to continue…`]})});case`error`:return(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,VY.jsxs)(F,{color:`error`,children:[`OAuth error: `,e.message]}),e.toRetry&&(0,VY.jsx)(P,{marginTop:1,children:(0,VY.jsxs)(F,{color:`permission`,children:[`Press `,(0,VY.jsx)(F,{bold:!0,children:`Enter`}),` to retry.`]})})]});default:return null}}var BY,VY,htt=n((()=>{BY=r(ze(),1),Da(),eb(),I(),ub(),Vr(),zY(),VY=et()}));function gtt({imageId:e,backgroundColor:t,isSelected:n=!1}){let r=M6e(e),i=`[Image #${e}]`;if(r&&pe()){let e=Vl(r).href;return(0,HY.jsx)(Te,{url:e,fallback:(0,HY.jsx)(F,{backgroundColor:t,inverse:n,children:i}),children:(0,HY.jsx)(F,{backgroundColor:t,inverse:n,bold:n,children:i})})}return(0,HY.jsx)(F,{backgroundColor:t,inverse:n,children:i})}var HY,_tt=n((()=>{I(),gq(),HY=et()}));function UY({isFocused:e,isSelected:t,children:n,description:r,shouldShowDownArrow:i,shouldShowUpArrow:a,declareCursor:o}){return(0,vtt.jsx)(Re,{isFocused:e,isSelected:t,description:r,showScrollDown:i,showScrollUp:a,styled:!1,declareCursor:o,children:n})}var vtt,WY=n((()=>{I(),vtt=et()}));function GY({option:e,isFocused:t,isSelected:n,shouldShowDownArrow:r,shouldShowUpArrow:i,maxIndexWidth:a,index:o,inputValue:s,onInputChange:c,onSubmit:l,onExit:u,layout:d,children:f,showLabel:p=!1,onOpenEditor:m,resetCursorOnUpdate:h=!1,onImagePaste:g,pastedContents:_,onRemoveImage:v,imagesSelected:y,selectedImageIndex:b=0,onImagesSelectedChange:x,onSelectedImageIndexChange:S}){let C=_?Object.values(_).filter(e=>e.type===`image`):[],w=p||e.showLabelWithValue===!0,[T,E]=(0,KY.useState)(s.length),D=(0,KY.useRef)(!1);(0,KY.useEffect)(()=>{h&&t&&(D.current?D.current=!1:E(s.length))},[h,t,s]),Fe(`chat:externalEditor`,()=>{m?.(s,c)},{context:`Chat`,isActive:t&&!!m}),Fe(`chat:imagePaste`,()=>{g&&nY().then(e=>{e&&g(e.base64,e.mediaType,void 0,e.dimensions)})},{context:`Chat`,isActive:t&&!!g}),Fe(`attachments:remove`,()=>{C.length>0&&v&&v(C.at(-1).id)},{context:`Attachments`,isActive:t&&!y&&s===``&&C.length>0&&!!v}),be({"attachments:next":()=>{C.length>1&&S?.((b+1)%C.length)},"attachments:previous":()=>{C.length>1&&S?.((b-1+C.length)%C.length)},"attachments:remove":()=>{let e=C[b];e&&v&&(v(e.id),C.length<=1?x?.(!1):S?.(Math.min(b,C.length-2)))},"attachments:exit":()=>{x?.(!1)}},{context:`Attachments`,isActive:t&&!!y}),Je((e,t)=>{t.upArrow&&x?.(!1)},{isActive:t&&!!y}),(0,KY.useEffect)(()=>{!t&&y&&x?.(!1)},[t,y,x]);let O=d===`expanded`?a+3:a+4;return(0,qY.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,qY.jsx)(UY,{isFocused:t,isSelected:n,shouldShowDownArrow:r,shouldShowUpArrow:i,declareCursor:!1,children:(0,qY.jsxs)(P,{flexDirection:`row`,flexShrink:d===`compact`?0:void 0,children:[(0,qY.jsx)(F,{dimColor:!0,children:`${o}.`.padEnd(a+2)}),f,w?(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(F,{color:t?`suggestion`:void 0,children:e.label}),t?(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(F,{color:`suggestion`,children:e.labelValueSeparator??`, `}),(0,qY.jsx)(LY,{value:s,onChange:t=>{D.current=!0,c(t),e.onChange(t)},onSubmit:l,onExit:u,placeholder:e.placeholder,focus:!y,showCursor:!0,multiline:!0,cursorOffset:T,onChangeCursorOffset:E,columns:80,onImagePaste:g,onPaste:t=>{D.current=!0;let n=s.slice(0,T),r=s.slice(T),i=n+t+r;c(i),e.onChange(i),E(n.length+t.length)}})]}):s&&(0,qY.jsxs)(F,{children:[e.labelValueSeparator??`, `,s]})]}):t?(0,qY.jsx)(LY,{value:s,onChange:t=>{D.current=!0,c(t),e.onChange(t)},onSubmit:l,onExit:u,placeholder:e.placeholder||(typeof e.label==`string`?e.label:void 0),focus:!y,showCursor:!0,multiline:!0,cursorOffset:T,onChangeCursorOffset:E,columns:80,onImagePaste:g,onPaste:t=>{D.current=!0;let n=s.slice(0,T),r=s.slice(T),i=n+t+r;c(i),e.onChange(i),E(n.length+t.length)}}):(0,qY.jsx)(F,{color:s?void 0:`inactive`,children:s||e.placeholder||e.label})]})}),e.description&&(0,qY.jsx)(P,{paddingLeft:O,children:(0,qY.jsx)(F,{dimColor:e.dimDescription!==!1,color:n?`success`:t?`suggestion`:void 0,children:e.description})}),C.length>0&&(0,qY.jsxs)(P,{flexDirection:`row`,gap:1,paddingLeft:O,children:[C.map((e,t)=>(0,qY.jsx)(gtt,{imageId:e.id,isSelected:!!y&&t===b},e.id)),(0,qY.jsx)(P,{flexGrow:1,justifyContent:`flex-start`,flexDirection:`row`,children:(0,qY.jsx)(F,{dimColor:!0,children:y?(0,qY.jsxs)(je,{children:[C.length>1&&(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(hK,{action:`attachments:next`,context:`Attachments`,fallback:`→`,description:`next`}),(0,qY.jsx)(hK,{action:`attachments:previous`,context:`Attachments`,fallback:`←`,description:`prev`})]}),(0,qY.jsx)(hK,{action:`attachments:remove`,context:`Attachments`,fallback:`backspace`,description:`remove`}),(0,qY.jsx)(hK,{action:`attachments:exit`,context:`Attachments`,fallback:`esc`,description:`cancel`})]}):t?`(↓ to select)`:null})})]}),d===`expanded`&&(0,qY.jsx)(F,{children:` `})]})}var KY,qY,ytt=n((()=>{KY=r(ze(),1),I(),ub(),aY(),_tt(),gK(),zY(),WY(),qY=et()}));function JY(e,t=!0){let n=(0,YY.useContext)(fV)?.setState;(0,YY.useEffect)(()=>{if(!(!t||!n))return n(t=>{if(t.activeOverlays.has(e))return t;let n=new Set(t.activeOverlays);return n.add(e),{...t,activeOverlays:n}}),()=>{n(t=>{if(!t.activeOverlays.has(e))return t;let n=new Set(t.activeOverlays);return n.delete(e),{...t,activeOverlays:n}})}},[e,t,n]),(0,YY.useLayoutEffect)(()=>{if(t)return()=>Ae.get(process.stdout)?.invalidatePrevFrame()},[t])}function btt(){return sV(e=>e.activeOverlays.size>0)}function xtt(){return sV(e=>{for(let t of e.activeOverlays)if(!Stt.has(t))return!0;return!1})}var YY,Stt,XY=n((()=>{YY=r(ze(),1),I(),mV(),Stt=new Set([`autocomplete`])})),Ctt,wtt=n((()=>{b(),Ctt=class extends Map{constructor(e){let t=[],n,r,i,a=0;for(let o of e){let e={label:o.label,value:o.value,description:o.description,previous:i,next:void 0,index:a};i&&(i.next=e),n||(n=e),r=e,t.push([o.value,e]),a++,i=e}super(t),x(this,`first`,void 0),x(this,`last`,void 0),this.first=n,this.last=r}}}));function Ttt({visibleOptionCount:e=5,options:t,initialFocusValue:n,onFocus:r,focusValue:i}){let[a,o]=(0,ZY.useReducer)(Ett,{visibleOptionCount:e,options:t,initialFocusValue:i||n},QY),s=(0,ZY.useRef)(r);s.current=r;let[c,l]=(0,ZY.useState)(t);t!==c&&!hue(t,c)&&(o({type:`reset`,state:QY({visibleOptionCount:e,options:t,initialFocusValue:i??a.focusedValue??n,currentViewport:{visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex}})}),l(t));let u=(0,ZY.useCallback)(()=>{o({type:`focus-next-option`})},[]),d=(0,ZY.useCallback)(()=>{o({type:`focus-previous-option`})},[]),f=(0,ZY.useCallback)(()=>{o({type:`focus-next-page`})},[]),p=(0,ZY.useCallback)(()=>{o({type:`focus-previous-page`})},[]),m=(0,ZY.useCallback)(e=>{e!==void 0&&o({type:`set-focus`,value:e})},[]),h=(0,ZY.useMemo)(()=>t.map((e,t)=>({...e,index:t})).slice(a.visibleFromIndex,a.visibleToIndex),[t,a.visibleFromIndex,a.visibleToIndex]),g=(0,ZY.useMemo)(()=>{if(a.focusedValue!==void 0)return t.some(e=>e.value===a.focusedValue)?a.focusedValue:t[0]?.value},[a.focusedValue,t]),_=(0,ZY.useMemo)(()=>t.find(e=>e.value===g)?.type===`input`,[g,t]);return(0,ZY.useEffect)(()=>{g!==void 0&&s.current?.(g)},[g]),(0,ZY.useEffect)(()=>{i!==void 0&&o({type:`set-focus`,value:i})},[i]),{focusedValue:g,focusedIndex:(0,ZY.useMemo)(()=>{if(g===void 0)return 0;let e=t.findIndex(e=>e.value===g);return e>=0?e+1:0},[g,t]),visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex,visibleOptions:h,isInInput:_??!1,focusNextOption:u,focusPreviousOption:d,focusNextPage:f,focusPreviousPage:p,focusOption:m,options:t}}var ZY,Ett,QY,Dtt=n((()=>{ZY=r(ze(),1),wtt(),Ett=(e,t)=>{switch(t.type){case`focus-next-option`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=t.next||e.optionMap.first;if(!n)return e;if(!t.next&&n===e.optionMap.first)return{...e,focusedValue:n.value,visibleFromIndex:0,visibleToIndex:e.visibleOptionCount};if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let r=Math.min(e.optionMap.size,e.visibleToIndex+1),i=r-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:i,visibleToIndex:r}}case`focus-previous-option`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=t.previous||e.optionMap.last;if(!n)return e;if(!t.previous&&n===e.optionMap.last){let t=e.optionMap.size,r=Math.max(0,t-e.visibleOptionCount);return{...e,focusedValue:n.value,visibleFromIndex:r,visibleToIndex:t}}if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let r=Math.max(0,e.visibleFromIndex-1),i=r+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:r,visibleToIndex:i}}case`focus-next-page`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=Math.min(e.optionMap.size-1,t.index+e.visibleOptionCount),r=e.optionMap.first;for(;r&&r.index<n&&r.next;)r=r.next;if(!r)return e;let i=Math.min(e.optionMap.size,r.index+1),a=Math.max(0,i-e.visibleOptionCount);return{...e,focusedValue:r.value,visibleFromIndex:a,visibleToIndex:i}}case`focus-previous-page`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=Math.max(0,t.index-e.visibleOptionCount),r=e.optionMap.first;for(;r&&r.index<n&&r.next;)r=r.next;if(!r)return e;let i=Math.max(0,r.index),a=Math.min(e.optionMap.size,i+e.visibleOptionCount);return{...e,focusedValue:r.value,visibleFromIndex:i,visibleToIndex:a}}case`reset`:return t.state;case`set-focus`:{if(e.focusedValue===t.value)return e;let n=e.optionMap.get(t.value);if(!n)return e;if(n.index>=e.visibleFromIndex&&n.index<e.visibleToIndex)return{...e,focusedValue:t.value};let r,i;return n.index<e.visibleFromIndex?(r=n.index,i=Math.min(e.optionMap.size,r+e.visibleOptionCount)):(i=Math.min(e.optionMap.size,n.index+1),r=Math.max(0,i-e.visibleOptionCount)),{...e,focusedValue:t.value,visibleFromIndex:r,visibleToIndex:i}}}},QY=({visibleOptionCount:e,options:t,initialFocusValue:n,currentViewport:r})=>{let i=typeof e==`number`?Math.min(e,t.length):t.length,a=new Ctt(t),o=n!==void 0&&a.get(n),s=o?n:a.first?.value,c=0,l=i;if(o){let e=o.index;r?e>=r.visibleFromIndex&&e<r.visibleToIndex?(c=r.visibleFromIndex,l=Math.min(a.size,r.visibleToIndex)):e<r.visibleFromIndex?(c=e,l=Math.min(a.size,c+i)):(l=Math.min(a.size,e+1),c=Math.max(0,l-i)):e>=i&&(l=Math.min(a.size,e+1),c=Math.max(0,l-i)),c=Math.max(0,Math.min(c,a.size-1)),l=Math.min(a.size,Math.max(i,l))}return{optionMap:a,visibleOptionCount:i,focusedValue:s,visibleFromIndex:c,visibleToIndex:l}}}));function Ott({isDisabled:e=!1,visibleOptionCount:t=5,options:n,defaultValue:r=[],onChange:i,onCancel:a,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,hideIndexes:p=!1}){let[m,h]=(0,$Y.useState)(r),[g,_]=(0,$Y.useState)(!1),[v,y]=(0,$Y.useState)(n);n!==v&&!hue(n,v)&&(h(r),y(n));let[b,x]=(0,$Y.useState)(()=>{let e=new Map;return n.forEach(t=>{t.type===`input`&&t.initialValue&&e.set(t.value,t.initialValue)}),e}),S=(0,$Y.useCallback)(e=>{let t=typeof e==`function`?e(m):e;h(t),i?.(t)},[m,i]),C=Ttt({visibleOptionCount:t,options:n,initialFocusValue:f?n[n.length-1]?.value:void 0,onFocus:o,focusValue:s});JY(`multi-select`,void 0);let w=(0,$Y.useCallback)((e,t)=>{x(n=>{let r=new Map(n);return r.set(e,t),r});let r=n.find(t=>t.value===e);r&&r.type===`input`&&r.onChange(t),S(n=>t?n.includes(e)?n:[...n,e]:n.filter(t=>t!==e))},[n,S]);return Je((e,t,r)=>{let i=Xa(e),o=n.find(e=>e.value===C.focusedValue)?.type===`input`;if(o&&!(t.upArrow||t.downArrow||t.escape||t.tab||t.return||t.ctrl&&(e===`n`||e===`p`||t.return)))return;let s=n[n.length-1]?.value;if(t.tab&&!t.shift){c&&l&&C.focusedValue===s&&!g?_(!0):g||C.focusNextOption();return}if(t.tab&&t.shift){c&&l&&g?(_(!1),C.focusOption(s)):C.focusPreviousOption();return}if(t.downArrow||t.ctrl&&e===`n`||!t.ctrl&&!t.shift&&e===`j`){g&&u?u():c&&l&&C.focusedValue===s&&!g?_(!0):!c&&u&&C.focusedValue===s?u():g||C.focusNextOption();return}if(t.upArrow||t.ctrl&&e===`p`||!t.ctrl&&!t.shift&&e===`k`){c&&l&&g?(_(!1),C.focusOption(s)):d&&C.focusedValue===n[0]?.value?d():C.focusPreviousOption();return}if(t.pageDown){C.focusNextPage();return}if(t.pageUp){C.focusPreviousPage();return}if(t.return||Ga(e)===` `){if(t.ctrl&&t.return&&o&&l){l(m);return}if(g&&l){l(m);return}if(t.return&&!c&&l){l(m);return}if(C.focusedValue!==void 0){let e=m.includes(C.focusedValue)?m.filter(e=>e!==C.focusedValue):[...m,C.focusedValue];S(e)}return}if(!p&&/^[0-9]+$/.test(i)){let e=parseInt(i,10)-1;if(e>=0&&e<n.length){let t=n[e].value,r=m.includes(t)?m.filter(e=>e!==t):[...m,t];S(r)}return}t.escape&&(a(),r.stopImmediatePropagation())},{isActive:!e}),{...C,selectedValues:m,inputValues:b,isSubmitFocused:g,updateInputValue:w,onCancel:a}}var $Y,ktt=n((()=>{$Y=r(ze(),1),XY(),I(),Ja(),Dtt()}));function Att({isDisabled:e=!1,visibleOptionCount:t=5,options:n,defaultValue:r=[],onCancel:i,onChange:a,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,onOpenEditor:p,hideIndexes:m=!1,onImagePaste:h,pastedContents:g,onRemoveImage:_}){let v=Ott({isDisabled:e,visibleOptionCount:t,options:n,defaultValue:r,onChange:a,onCancel:i,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,hideIndexes:m}),y=n.length.toString().length;return(0,eX.jsxs)(P,{flexDirection:`column`,children:[(0,eX.jsx)(P,{flexDirection:`column`,children:v.visibleOptions.map((t,r)=>{let a=!e&&v.focusedValue===t.value&&!v.isSubmitFocused,o=v.selectedValues.includes(t.value),s=t.index===v.visibleFromIndex,c=t.index===v.visibleToIndex-1,l=v.visibleToIndex<n.length,u=v.visibleFromIndex>0,d=v.visibleFromIndex+r+1;if(t.type===`input`){let e=v.inputValues.get(t.value)||``;return(0,eX.jsx)(P,{gap:1,children:(0,eX.jsx)(GY,{option:t,isFocused:a,isSelected:!1,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&s,maxIndexWidth:y,index:d,inputValue:e,onInputChange:e=>{v.updateInputValue(t.value,e)},onSubmit:()=>{},onExit:()=>{i()},layout:`compact`,onOpenEditor:p,onImagePaste:h,pastedContents:g,onRemoveImage:_,children:(0,eX.jsxs)(F,{color:o?`success`:void 0,children:[`[`,o?ie.tick:` `,`] `]})})},String(t.value))}return(0,eX.jsx)(P,{gap:1,children:(0,eX.jsxs)(UY,{isFocused:a,isSelected:!1,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&s,description:t.description,children:[!m&&(0,eX.jsx)(F,{dimColor:!0,children:`${d}.`.padEnd(y)}),(0,eX.jsxs)(F,{color:o?`success`:void 0,children:[`[`,o?ie.tick:` `,`]`]}),(0,eX.jsx)(F,{color:a?`suggestion`:void 0,children:t.label})]})},String(t.value))})}),c&&l&&(0,eX.jsxs)(P,{marginTop:0,gap:1,children:[v.isSubmitFocused?(0,eX.jsx)(F,{color:`suggestion`,children:ie.pointer}):(0,eX.jsx)(F,{children:` `}),(0,eX.jsx)(P,{marginLeft:3,children:(0,eX.jsx)(F,{color:v.isSubmitFocused?`suggestion`:void 0,bold:!0,children:c})})]})]})}var eX,jtt=n((()=>{ne(),I(),ytt(),WY(),ktt(),eX=et()})),tX,Mtt,Ntt=n((()=>{tX=r(ze(),1),XY(),I(),ub(),Ja(),Mtt=({isDisabled:e=!1,disableSelection:t=!1,state:n,options:r,isMultiSelect:i=!1,onUpFromFirstItem:a,onDownFromLastItem:o,onInputModeToggle:s,inputValues:c,imagesSelected:l=!1,onEnterImageSelection:u})=>{JY(`select`,!!n.onCancel);let d=(0,tX.useMemo)(()=>r.find(e=>e.value===n.focusedValue)?.type===`input`,[r,n.focusedValue]);be((0,tX.useMemo)(()=>{let e={};return d||(e[`select:next`]=()=>{if(o){let e=r[r.length-1];if(e&&n.focusedValue===e.value){o();return}}n.focusNextOption()},e[`select:previous`]=()=>{if(a&&n.visibleFromIndex===0){let e=r[0];if(e&&n.focusedValue===e.value){a();return}}n.focusPreviousOption()},e[`select:accept`]=()=>{t!==!0&&n.focusedValue!==void 0&&r.find(e=>e.value===n.focusedValue)?.disabled!==!0&&(n.selectFocusedOption?.(),n.onChange?.(n.focusedValue))}),n.onCancel&&(e[`select:cancel`]=()=>{n.onCancel()}),e},[r,n,o,a,d,t]),{context:`Select`,isActive:!e}),Je((e,d,f)=>{let p=Xa(e),m=r.find(e=>e.value===n.focusedValue),h=m?.type===`input`;if(d.tab&&s&&n.focusedValue!==void 0){s(n.focusedValue);return}if(h){if(l)return;if(d.downArrow&&u?.()){f.stopImmediatePropagation();return}if(d.downArrow||d.ctrl&&e===`n`){if(o){let e=r[r.length-1];if(e&&n.focusedValue===e.value){o(),f.stopImmediatePropagation();return}}n.focusNextOption(),f.stopImmediatePropagation();return}if(d.upArrow||d.ctrl&&e===`p`){if(a&&n.visibleFromIndex===0){let e=r[0];if(e&&n.focusedValue===e.value){a(),f.stopImmediatePropagation();return}}n.focusPreviousOption(),f.stopImmediatePropagation();return}return}if(d.pageDown&&n.focusNextPage(),d.pageUp&&n.focusPreviousPage(),t!==!0&&(i&&Ga(e)===` `&&n.focusedValue!==void 0&&m?.disabled!==!0&&(n.selectFocusedOption?.(),n.onChange?.(n.focusedValue)),t!==`numeric`&&/^[0-9]+$/.test(p))){let e=parseInt(p,10)-1;if(e>=0&&e<n.options.length){let t=n.options[e];if(t.disabled===!0)return;if(t.type===`input`){if((c?.get(t.value)??``).trim()){n.onChange?.(t.value);return}if(t.allowEmptySubmitToCancel){n.onChange?.(t.value);return}n.focusOption(t.value);return}n.onChange?.(t.value);return}}},{isActive:!e})}}));function Ptt({visibleOptionCount:e=5,options:t,defaultValue:n,onChange:r,onCancel:i,onFocus:a,focusValue:o}){let[s,c]=(0,nX.useState)(n),l=Ttt({visibleOptionCount:e,options:t,initialFocusValue:void 0,onFocus:a,focusValue:o}),u=(0,nX.useCallback)(()=>{c(l.focusedValue)},[l.focusedValue]);return{...l,value:s,selectFocusedOption:u,onChange:r,onCancel:i}}var nX,Ftt=n((()=>{nX=r(ze(),1),Dtt()}));function rX(e){return typeof e==`string`?e:typeof e==`number`?String(e):e?Array.isArray(e)?e.map(rX).join(``):aX.isValidElement(e)?rX(e.props.children):``:``}function iX({isDisabled:e=!1,hideIndexes:t=!1,visibleOptionCount:n=5,highlightText:r,options:i,defaultValue:a,onCancel:o,onChange:s,onFocus:c,defaultFocusValue:l,layout:u=`compact`,disableSelection:d=!1,inlineDescriptions:f=!1,onUpFromFirstItem:p,onDownFromLastItem:m,onInputModeToggle:h,onOpenEditor:g,onImagePaste:_,pastedContents:v,onRemoveImage:y}){let[b,x]=(0,aX.useState)(!1),[S,C]=(0,aX.useState)(0),[w,T]=(0,aX.useState)(()=>{let e=new Map;return i.forEach(t=>{t.type===`input`&&t.initialValue&&e.set(t.value,t.initialValue)}),e}),E=(0,aX.useRef)(new Map);(0,aX.useEffect)(()=>{for(let e of i)if(e.type===`input`&&e.initialValue!==void 0){let t=E.current.get(e.value)??``,n=w.get(e.value)??``,r=e.initialValue;r!==t&&n===t&&T(t=>{let n=new Map(t);return n.set(e.value,r),n}),E.current.set(e.value,r)}},[i,w]);let D=Ptt({visibleOptionCount:n,options:i,defaultValue:a,onChange:s,onCancel:o,onFocus:c,focusValue:l});Mtt({isDisabled:e,disableSelection:d||(t?`numeric`:!1),state:D,options:i,isMultiSelect:!1,onUpFromFirstItem:p,onDownFromLastItem:m,onInputModeToggle:h,inputValues:w,imagesSelected:b,onEnterImageSelection:()=>{if(v&&Object.values(v).some(e=>e.type===`image`)){let e=hr(Object.values(v),e=>e.type===`image`);return x(!0),C(e-1),!0}return!1}});let O={container:()=>({flexDirection:`column`}),highlightedText:()=>({bold:!0})};if(u===`expanded`){let t=D.options.length.toString().length;return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((n,a)=>{let c=n.index===D.visibleFromIndex,l=n.index===D.visibleToIndex-1,u=D.visibleToIndex<i.length,d=D.visibleFromIndex>0,p=D.visibleFromIndex+a+1,m=!e&&D.focusedValue===n.value,h=D.value===n.value;if(n.type===`input`){let e=w.has(n.value)?w.get(n.value):n.initialValue||``;return(0,oX.jsx)(GY,{option:n,isFocused:m,isSelected:h,shouldShowDownArrow:u&&l,shouldShowUpArrow:d&&c,maxIndexWidth:t,index:p,inputValue:e,onInputChange:e=>{T(t=>{let r=new Map(t);return r.set(n.value,e),r})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||n.allowEmptySubmitToCancel?s?.(n.value):o?.()},onExit:o,layout:`expanded`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:n.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(n.value))}let E=n.label;if(typeof n.label==`string`&&r&&n.label.includes(r)){let e=n.label,t=e.indexOf(r);E=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let k=n.disabled===!0,A=k?void 0:h?`success`:m?`suggestion`:void 0;return(0,oX.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,oX.jsx)(UY,{isFocused:m,isSelected:h,shouldShowDownArrow:u&&l,shouldShowUpArrow:d&&c,children:(0,oX.jsx)(F,{dimColor:k,color:A,children:E})}),n.description&&(0,oX.jsx)(P,{paddingLeft:2,children:(0,oX.jsx)(F,{dimColor:k||n.dimDescription!==!1,color:A,children:(0,oX.jsx)(_e,{children:n.description})})}),(0,oX.jsx)(F,{children:` `})]},String(n.value))})})}if(u===`compact-vertical`){let n=t?0:D.options.length.toString().length;return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((a,c)=>{let l=a.index===D.visibleFromIndex,u=a.index===D.visibleToIndex-1,d=D.visibleToIndex<i.length,p=D.visibleFromIndex>0,m=D.visibleFromIndex+c+1,h=!e&&D.focusedValue===a.value,E=D.value===a.value;if(a.type===`input`){let e=w.has(a.value)?w.get(a.value):a.initialValue||``;return(0,oX.jsx)(GY,{option:a,isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,maxIndexWidth:n,index:m,inputValue:e,onInputChange:e=>{T(t=>{let n=new Map(t);return n.set(a.value,e),n})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||a.allowEmptySubmitToCancel?s?.(a.value):o?.()},onExit:o,layout:`compact`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:a.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(a.value))}let k=a.label;if(typeof a.label==`string`&&r&&a.label.includes(r)){let e=a.label,t=e.indexOf(r);k=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let A=a.disabled===!0;return(0,oX.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,oX.jsxs)(UY,{isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${m}.`.padEnd(n+1)}),(0,oX.jsx)(F,{dimColor:A,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:k})]}),a.description&&(0,oX.jsx)(P,{paddingLeft:t?4:n+4,children:(0,oX.jsx)(F,{dimColor:A||a.dimDescription!==!1,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:a.description})})})]},String(a.value))})})}let k=t?0:D.options.length.toString().length,A=D.visibleOptions.some(e=>e.type===`input`),ee=!f&&!A&&D.visibleOptions.some(e=>e.description),te=D.visibleOptions.map((t,n)=>{let a=t.index===D.visibleFromIndex,o=t.index===D.visibleToIndex-1,s=D.visibleToIndex<i.length,c=D.visibleFromIndex>0,l=D.visibleFromIndex+n+1,u=!e&&D.focusedValue===t.value,d=D.value===t.value,f=t.disabled===!0,p=t.label;if(typeof t.label==`string`&&r&&t.label.includes(r)){let e=t.label,n=e.indexOf(r);p=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,n),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(n+r.length)]})}return{option:t,index:l,label:p,isFocused:u,isSelected:d,isOptionDisabled:f,shouldShowDownArrow:s&&o,shouldShowUpArrow:c&&a}});if(ee){let e=Math.max(...te.map(e=>{if(e.option.type===`input`)return 0;let n=rX(e.option.label),r=t?0:k+2,i=e.isSelected?2:0;return 2+r+ye(n)+i}));return(0,oX.jsx)(P,{...O.container(),children:te.map(n=>{if(n.option.type===`input`)return null;let r=rX(n.option.label),i=t?0:k+2,a=n.isSelected?2:0,o=2+i+ye(r)+a,s=e-o;return(0,oX.jsxs)(Itt,{isFocused:n.isFocused,children:[(0,oX.jsxs)(P,{flexDirection:`row`,flexShrink:0,children:[n.isFocused?(0,oX.jsx)(F,{color:`suggestion`,children:ie.pointer}):n.shouldShowDownArrow?(0,oX.jsx)(F,{dimColor:!0,children:ie.arrowDown}):n.shouldShowUpArrow?(0,oX.jsx)(F,{dimColor:!0,children:ie.arrowUp}):(0,oX.jsx)(F,{children:` `}),(0,oX.jsx)(F,{children:` `}),(0,oX.jsxs)(F,{dimColor:n.isOptionDisabled,color:n.isOptionDisabled?void 0:n.isSelected?`success`:n.isFocused?`suggestion`:void 0,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${n.index}.`.padEnd(k+2)}),n.label]}),n.isSelected&&(0,oX.jsxs)(F,{color:`success`,children:[` `,ie.tick]}),s>0&&(0,oX.jsx)(F,{children:` `.repeat(s)})]}),(0,oX.jsx)(P,{flexGrow:1,marginLeft:2,children:(0,oX.jsx)(F,{wrap:`wrap`,dimColor:n.isOptionDisabled||n.option.dimDescription!==!1,color:n.isOptionDisabled?void 0:n.isSelected?`success`:n.isFocused?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:n.option.description||` `})})})]},String(n.option.value))})})}return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((n,a)=>{if(n.type===`input`){let t=w.has(n.value)?w.get(n.value):n.initialValue||``,r=n.index===D.visibleFromIndex,c=n.index===D.visibleToIndex-1,l=D.visibleToIndex<i.length,u=D.visibleFromIndex>0,d=D.visibleFromIndex+a+1;return(0,oX.jsx)(GY,{option:n,isFocused:!e&&D.focusedValue===n.value,isSelected:D.value===n.value,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&r,maxIndexWidth:k,index:d,inputValue:t,onInputChange:e=>{T(t=>{let r=new Map(t);return r.set(n.value,e),r})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||n.allowEmptySubmitToCancel?s?.(n.value):o?.()},onExit:o,layout:`compact`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:n.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(n.value))}let c=n.label;if(typeof n.label==`string`&&r&&n.label.includes(r)){let e=n.label,t=e.indexOf(r);c=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let l=n.index===D.visibleFromIndex,u=n.index===D.visibleToIndex-1,d=D.visibleToIndex<i.length,p=D.visibleFromIndex>0,m=D.visibleFromIndex+a+1,h=!e&&D.focusedValue===n.value,E=D.value===n.value,A=n.disabled===!0;return(0,oX.jsxs)(UY,{isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,children:[(0,oX.jsxs)(P,{flexDirection:`row`,flexShrink:0,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${m}.`.padEnd(k+2)}),(0,oX.jsxs)(F,{dimColor:A,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:[c,f&&n.description&&(0,oX.jsxs)(F,{dimColor:A||n.dimDescription!==!1,children:[` `,n.description]})]})]}),!f&&n.description&&(0,oX.jsx)(P,{flexShrink:99,marginLeft:2,children:(0,oX.jsx)(F,{wrap:`wrap-trim`,dimColor:A||n.dimDescription!==!1,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:n.description})})})]},String(n.value))})})}function Itt({isFocused:e,children:t}){return(0,oX.jsx)(P,{ref:ve({line:0,column:0,active:e}),flexDirection:`row`,children:t})}var aX,oX,Ltt=n((()=>{ne(),aX=r(ze(),1),I(),Cr(),ytt(),WY(),Ntt(),Ftt(),oX=et()})),sX=n((()=>{jtt(),Ltt()})),cX,lX,Rtt=n((()=>{Wt(),b(),cX=class e{constructor(e){x(this,`activeOperations`,new Set),x(this,`lastUserActivityTime`,0),x(this,`lastCLIRecordedTime`,void 0),x(this,`isCLIActive`,!1),x(this,`USER_ACTIVITY_TIMEOUT_MS`,5e3),x(this,`getNow`,void 0),x(this,`getActiveTimeCounter`,void 0),this.getNow=e?.getNow??(()=>Date.now()),this.getActiveTimeCounter=e?.getActiveTimeCounter??qte,this.lastCLIRecordedTime=this.getNow()}static getInstance(){return e.instance||(e.instance=new e),e.instance}static resetInstance(){e.instance=null}static createInstance(t){return e.instance=new e(t),e.instance}recordUserActivity(){if(!this.isCLIActive&&this.lastUserActivityTime!==0){let e=(this.getNow()-this.lastUserActivityTime)/1e3;if(e>0){let t=this.getActiveTimeCounter();t&&e<this.USER_ACTIVITY_TIMEOUT_MS/1e3&&t.add(e,{type:`user`})}}this.lastUserActivityTime=this.getNow()}startCLIActivity(e){this.activeOperations.has(e)&&this.endCLIActivity(e);let t=this.activeOperations.size===0;this.activeOperations.add(e),t&&(this.isCLIActive=!0,this.lastCLIRecordedTime=this.getNow())}endCLIActivity(e){if(this.activeOperations.delete(e),this.activeOperations.size===0){let e=this.getNow(),t=(e-this.lastCLIRecordedTime)/1e3;if(t>0){let e=this.getActiveTimeCounter();e&&e.add(t,{type:`cli`})}this.lastCLIRecordedTime=e,this.isCLIActive=!1}}async trackOperation(e,t){this.startCLIActivity(e);try{return await t()}finally{this.endCLIActivity(e)}}getActivityStates(){return{isUserActive:(this.getNow()-this.lastUserActivityTime)/1e3<this.USER_ACTIVITY_TIMEOUT_MS/1e3,isCLIActive:this.isCLIActive,activeOperationCount:this.activeOperations.size}}},x(cX,`instance`,null),lX=cX.getInstance()}));function ztt(){let e=Xr().spinnerVerbs;return e?e.mode===`replace`?e.verbs.length>0?e.verbs:uX:[...uX,...e.verbs]:uX}var uX,Btt=n((()=>{Vr(),uX=`Accomplishing.Actioning.Actualizing.Architecting.Baking.Beaming.Beboppin'.Befuddling.Billowing.Blanching.Bloviating.Boogieing.Boondoggling.Booping.Bootstrapping.Brewing.Bunning.Burrowing.Calculating.Canoodling.Caramelizing.Cascading.Catapulting.Cerebrating.Channeling.Channelling.Choreographing.Churning.Clauding.Coalescing.Cogitating.Combobulating.Composing.Computing.Concocting.Considering.Contemplating.Cooking.Crafting.Creating.Crunching.Crystallizing.Cultivating.Deciphering.Deliberating.Determining.Dilly-dallying.Discombobulating.Doing.Doodling.Drizzling.Ebbing.Effecting.Elucidating.Embellishing.Enchanting.Envisioning.Evaporating.Fermenting.Fiddle-faddling.Finagling.Flambéing.Flibbertigibbeting.Flowing.Flummoxing.Fluttering.Forging.Forming.Frolicking.Frosting.Gallivanting.Galloping.Garnishing.Generating.Gesticulating.Germinating.Gitifying.Grooving.Gusting.Harmonizing.Hashing.Hatching.Herding.Honking.Hullaballooing.Hyperspacing.Ideating.Imagining.Improvising.Incubating.Inferring.Infusing.Ionizing.Jitterbugging.Julienning.Kneading.Leavening.Levitating.Lollygagging.Manifesting.Marinating.Meandering.Metamorphosing.Misting.Moonwalking.Moseying.Mulling.Mustering.Musing.Nebulizing.Nesting.Newspapering.Noodling.Nucleating.Orbiting.Orchestrating.Osmosing.Perambulating.Percolating.Perusing.Philosophising.Photosynthesizing.Pollinating.Pondering.Pontificating.Pouncing.Precipitating.Prestidigitating.Processing.Proofing.Propagating.Puttering.Puzzling.Quantumizing.Razzle-dazzling.Razzmatazzing.Recombobulating.Reticulating.Roosting.Ruminating.Sautéing.Scampering.Schlepping.Scurrying.Seasoning.Shenaniganing.Shimmying.Simmering.Skedaddling.Sketching.Slithering.Smooshing.Sock-hopping.Spelunking.Spinning.Sprouting.Stewing.Sublimating.Swirling.Swooping.Symbioting.Synthesizing.Tempering.Thinking.Thundering.Tinkering.Tomfoolering.Topsy-turvying.Transfiguring.Transmuting.Twisting.Undulating.Unfurling.Unravelling.Vibing.Waddling.Wandering.Warping.Whatchamacalliting.Whirlpooling.Whirring.Whisking.Wibbling.Working.Wrangling.Zesting.Zigzagging`.split(`.`)}));function dX(e,t){let n=parseInt(e.id,10),r=parseInt(t.id,10);return!isNaN(n)&&!isNaN(r)?n-r:e.id.localeCompare(t.id)}function Vtt({tasks:e,isStandalone:t=!1}){let[,n]=fX.useState(0),{rows:r,columns:i}=Xe(),a=fX.useRef(new Map),o=fX.useRef(null);o.current===null&&(o.current=new Set(e.filter(e=>e.status===`completed`).map(e=>e.id)));let s=r<=10?0:Math.min(10,Math.max(3,r-14)),c=new Set(e.filter(e=>e.status===`completed`).map(e=>e.id)),l=Date.now();for(let e of c)o.current.has(e)||a.current.set(e,l);for(let e of a.current.keys())c.has(e)||a.current.delete(e);if(o.current=c,fX.useEffect(()=>{if(a.current.size===0)return;let e=Date.now(),t=1/0;for(let n of a.current.values()){let r=n+mX;r>e&&r<t&&(t=r)}if(t===1/0)return;let r=setTimeout(e=>e(e=>e+1),t-e,n);return()=>clearTimeout(r)},[e]),!ax()||e.length===0)return null;let u=hr(e,e=>e.status===`completed`),d=hr(e,e=>e.status===`pending`),f=e.length-u-d,p=new Set(e.filter(e=>e.status!==`completed`).map(e=>e.id)),m=e.length>s,h,g;if(m){let t=[],n=[];for(let r of e.filter(e=>e.status===`completed`)){let e=a.current.get(r.id);e&&l-e<mX?t.push(r):n.push(r)}t.sort(dX),n.sort(dX);let r=e.filter(e=>e.status===`in_progress`).sort(dX),i=e.filter(e=>e.status===`pending`).sort((e,t)=>{let n=e.blockedBy.some(e=>p.has(e));return n===t.blockedBy.some(e=>p.has(e))?dX(e,t):n?1:-1}),o=[...t,...r,...i,...n];h=o.slice(0,s),g=o.slice(s)}else h=[...e].sort(dX),g=[];let _=``;if(g.length>0){let e=[],t=hr(g,e=>e.status===`pending`),n=hr(g,e=>e.status===`in_progress`),r=hr(g,e=>e.status===`completed`);n>0&&e.push(`${n} in progress`),t>0&&e.push(`${t} pending`),r>0&&e.push(`${r} completed`),_=` … +${e.join(`, `)}`}let v=(0,pX.jsxs)(pX.Fragment,{children:[h.map(e=>(0,pX.jsx)(Utt,{task:e,openBlockers:e.blockedBy.filter(e=>p.has(e)),columns:i},e.id)),s>0&&_&&(0,pX.jsx)(F,{dimColor:!0,children:_})]});return t?(0,pX.jsxs)(P,{flexDirection:`column`,marginTop:1,marginLeft:2,children:[(0,pX.jsx)(P,{children:(0,pX.jsxs)(F,{dimColor:!0,children:[(0,pX.jsx)(F,{bold:!0,children:e.length}),` tasks (`,(0,pX.jsx)(F,{bold:!0,children:u}),` done, `,f>0&&(0,pX.jsxs)(pX.Fragment,{children:[(0,pX.jsx)(F,{bold:!0,children:f}),` in progress, `]}),(0,pX.jsx)(F,{bold:!0,children:d}),` open)`]})}),v]}):(0,pX.jsx)(P,{flexDirection:`column`,children:v})}function Htt(e){switch(e){case`completed`:return{icon:ie.tick,color:`success`};case`in_progress`:return{icon:ie.squareSmallFilled,color:`claude`};case`pending`:return{icon:ie.squareSmall,color:void 0}}}function Utt({task:e,openBlockers:t,columns:n}){let r=e.status===`completed`,i=e.status===`in_progress`,a=t.length>0,{icon:o,color:s}=Htt(e.status),c=Math.max(15,n-15),l=Aa(e.subject,c);return(0,pX.jsx)(P,{flexDirection:`column`,children:(0,pX.jsxs)(P,{children:[(0,pX.jsxs)(F,{color:s,children:[o,` `]}),(0,pX.jsx)(F,{bold:i,strikethrough:r,dimColor:r||a,children:l}),a&&(0,pX.jsxs)(F,{dimColor:!0,children:[` `,ie.pointerSmall,` blocked by`,` `,[...t].sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>`#${e}`).join(`, `)]})]})})}var fX,pX,mX,Wtt=n((()=>{ne(),fX=r(ze(),1),eb(),I(),Cr(),Ba(),hx(),pX=et(),mX=3e4}));function Gtt(){D(TX,this).emit()}function Ktt(e){if(!(e===D(bX,this)&&D(yX,this)!==null)){D(yX,this)?.close(),k(yX,this,null),k(bX,this,e);try{k(yX,this,zle(e,D(kX,this))),D(yX,this).unref()}catch{}}}function qtt(e){k(xX,this,null);let t=ox();t===e&&dx(t).then(async e=>{e.length>0&&e.every(e=>e.status===`completed`)&&(await bwe(t),k(_X,this,[]),k(vX,this,!0)),S(OX,this,Gtt).call(this)})}function Jtt(){D(xX,this)&&(clearTimeout(D(xX,this)),k(xX,this,null))}function Ytt(){D(yX,this)?.close(),k(yX,this,null),k(bX,this,null),D(wX,this)?.call(this),k(wX,this,null),S(OX,this,Jtt).call(this),D(SX,this)&&clearTimeout(D(SX,this)),D(CX,this)&&clearTimeout(D(CX,this)),k(SX,this,null),k(CX,this,null),k(DX,this,!1)}function Xtt(){return jX??(jX=new tnt)}function hX(){let e=ax()?Xtt():null;return(0,gX.useSyncExternalStore)(e?e.subscribe:rnt,e?e.getSnapshot:int)}function Ztt(){let e=hX(),t=cV(),n=e===void 0;return(0,gX.useEffect)(()=>{n&&t(e=>e.expandedView===`tasks`?{...e,expandedView:`none`}:e)},[n,t]),e}var gX,Qtt,$tt,ent,_X,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX,kX,AX,tnt,jX,nnt,rnt,int,ant=n((()=>{gX=r(ze(),1),mV(),fn(),hx(),A(),C(),b(),w(),T(),E(),Qtt=5e3,$tt=50,ent=5e3,_X=new WeakMap,vX=new WeakMap,yX=new WeakMap,bX=new WeakMap,xX=new WeakMap,SX=new WeakMap,CX=new WeakMap,wX=new WeakMap,TX=new WeakMap,EX=new WeakMap,DX=new WeakMap,OX=new WeakSet,kX=new WeakMap,AX=new WeakMap,tnt=class{constructor(){ee(this,OX),O(this,_X,void 0),O(this,vX,!1),O(this,yX,null),O(this,bX,null),O(this,xX,null),O(this,SX,null),O(this,CX,null),O(this,wX,null),O(this,TX,rn()),O(this,EX,0),O(this,DX,!1),x(this,`getSnapshot`,()=>D(vX,this)?void 0:D(_X,this)),x(this,`subscribe`,e=>{var t;let n=D(TX,this).subscribe(e);k(EX,this,(t=D(EX,this),t++,t)),D(DX,this)||(k(DX,this,!0),k(wX,this,jwe(D(kX,this))),D(AX,this).call(this));let r=!1;return()=>{var e;r||(r=!0,n(),k(EX,this,(e=D(EX,this),e--,e)),D(EX,this)===0&&S(OX,this,Ytt).call(this))}}),O(this,kX,()=>{D(SX,this)&&clearTimeout(D(SX,this)),k(SX,this,setTimeout(()=>void D(AX,this).call(this),$tt)),D(SX,this).unref()}),O(this,AX,async()=>{let e=ox();S(OX,this,Ktt).call(this,sx(e));let t=(await dx(e)).filter(e=>!e.metadata?._internal);k(_X,this,t);let n=t.some(e=>e.status!==`completed`);n||t.length===0?(k(vX,this,t.length===0),S(OX,this,Jtt).call(this)):D(xX,this)===null&&!D(vX,this)&&(k(xX,this,setTimeout(S(OX,this,qtt).bind(this,e),Qtt)),D(xX,this).unref()),S(OX,this,Gtt).call(this),D(CX,this)&&(clearTimeout(D(CX,this)),k(CX,this,null)),n&&(k(CX,this,setTimeout(D(kX,this),ent)),D(CX,this).unref())})}},jX=null,nnt=()=>{},rnt=()=>nnt,int=()=>void 0}));function MX(e){switch(e){case`light`:return snt;case`light-ansi`:return cnt;case`dark-ansi`:return lnt;case`light-daltonized`:return unt;case`dark-daltonized`:return fnt;default:return dnt}}var ont,snt,cnt,lnt,unt,dnt,fnt,NX=n((()=>{Ge(),Ar(),ont=[`dark`,`light`,`light-daltonized`,`dark-daltonized`,`light-ansi`,`dark-ansi`],[...ont],snt={autoAccept:`rgb(135,0,255)`,bashBorder:`rgb(255,0,135)`,claude:`rgb(215,119,87)`,claudeShimmer:`rgb(245,149,117)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(87,105,247)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(117,135,255)`,permission:`rgb(87,105,247)`,permissionShimmer:`rgb(137,155,255)`,planMode:`rgb(0,102,102)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(153,153,153)`,promptBorderShimmer:`rgb(183,183,183)`,text:`rgb(0,0,0)`,inverseText:`rgb(255,255,255)`,inactive:`rgb(102,102,102)`,inactiveShimmer:`rgb(142,142,142)`,subtle:`rgb(175,175,175)`,suggestion:`rgb(87,105,247)`,remember:`rgb(0,0,255)`,background:`rgb(0,153,153)`,success:`rgb(44,122,57)`,error:`rgb(171,43,63)`,warning:`rgb(150,108,30)`,merged:`rgb(135,0,255)`,warningShimmer:`rgb(200,158,80)`,diffAdded:`rgb(105,219,124)`,diffRemoved:`rgb(255,168,180)`,diffAddedDimmed:`rgb(199,225,203)`,diffRemovedDimmed:`rgb(253,210,216)`,diffAddedWord:`rgb(47,157,68)`,diffRemovedWord:`rgb(209,69,75)`,red_FOR_SUBAGENTS_ONLY:`rgb(220,38,38)`,blue_FOR_SUBAGENTS_ONLY:`rgb(37,99,235)`,green_FOR_SUBAGENTS_ONLY:`rgb(22,163,74)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(202,138,4)`,purple_FOR_SUBAGENTS_ONLY:`rgb(147,51,234)`,orange_FOR_SUBAGENTS_ONLY:`rgb(234,88,12)`,pink_FOR_SUBAGENTS_ONLY:`rgb(219,39,119)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(8,145,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(240, 240, 240)`,userMessageBackgroundHover:`rgb(252, 252, 252)`,messageActionsBackground:`rgb(232, 236, 244)`,selectionBg:`rgb(180, 213, 255)`,bashMessageBackgroundColor:`rgb(250, 245, 250)`,memoryBackgroundColor:`rgb(230, 245, 250)`,rate_limit_fill:`rgb(87,105,247)`,rate_limit_empty:`rgb(39,47,111)`,fastMode:`rgb(255,106,0)`,fastModeShimmer:`rgb(255,150,50)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},cnt={autoAccept:`ansi:magenta`,bashBorder:`ansi:magenta`,claude:`ansi:redBright`,claudeShimmer:`ansi:yellowBright`,claudeBlue_FOR_SYSTEM_SPINNER:`ansi:blue`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`ansi:blueBright`,permission:`ansi:blue`,permissionShimmer:`ansi:blueBright`,planMode:`ansi:cyan`,ide:`ansi:blueBright`,promptBorder:`ansi:white`,promptBorderShimmer:`ansi:whiteBright`,text:`ansi:black`,inverseText:`ansi:white`,inactive:`ansi:blackBright`,inactiveShimmer:`ansi:white`,subtle:`ansi:blackBright`,suggestion:`ansi:blue`,remember:`ansi:blue`,background:`ansi:cyan`,success:`ansi:green`,error:`ansi:red`,warning:`ansi:yellow`,merged:`ansi:magenta`,warningShimmer:`ansi:yellowBright`,diffAdded:`ansi:green`,diffRemoved:`ansi:red`,diffAddedDimmed:`ansi:green`,diffRemovedDimmed:`ansi:red`,diffAddedWord:`ansi:greenBright`,diffRemovedWord:`ansi:redBright`,red_FOR_SUBAGENTS_ONLY:`ansi:red`,blue_FOR_SUBAGENTS_ONLY:`ansi:blue`,green_FOR_SUBAGENTS_ONLY:`ansi:green`,yellow_FOR_SUBAGENTS_ONLY:`ansi:yellow`,purple_FOR_SUBAGENTS_ONLY:`ansi:magenta`,orange_FOR_SUBAGENTS_ONLY:`ansi:redBright`,pink_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,cyan_FOR_SUBAGENTS_ONLY:`ansi:cyan`,professionalBlue:`ansi:blueBright`,chromeYellow:`ansi:yellow`,clawd_body:`ansi:redBright`,clawd_background:`ansi:black`,userMessageBackground:`ansi:white`,userMessageBackgroundHover:`ansi:whiteBright`,messageActionsBackground:`ansi:white`,selectionBg:`ansi:cyan`,bashMessageBackgroundColor:`ansi:whiteBright`,memoryBackgroundColor:`ansi:white`,rate_limit_fill:`ansi:yellow`,rate_limit_empty:`ansi:black`,fastMode:`ansi:red`,fastModeShimmer:`ansi:redBright`,rainbow_red:`ansi:red`,rainbow_orange:`ansi:redBright`,rainbow_yellow:`ansi:yellow`,rainbow_green:`ansi:green`,rainbow_blue:`ansi:cyan`,rainbow_indigo:`ansi:blue`,rainbow_violet:`ansi:magenta`,rainbow_red_shimmer:`ansi:redBright`,rainbow_orange_shimmer:`ansi:yellow`,rainbow_yellow_shimmer:`ansi:yellowBright`,rainbow_green_shimmer:`ansi:greenBright`,rainbow_blue_shimmer:`ansi:cyanBright`,rainbow_indigo_shimmer:`ansi:blueBright`,rainbow_violet_shimmer:`ansi:magentaBright`},lnt={autoAccept:`ansi:magentaBright`,bashBorder:`ansi:magentaBright`,claude:`ansi:redBright`,claudeShimmer:`ansi:yellowBright`,claudeBlue_FOR_SYSTEM_SPINNER:`ansi:blueBright`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`ansi:blueBright`,permission:`ansi:blueBright`,permissionShimmer:`ansi:blueBright`,planMode:`ansi:cyanBright`,ide:`ansi:blue`,promptBorder:`ansi:white`,promptBorderShimmer:`ansi:whiteBright`,text:`ansi:whiteBright`,inverseText:`ansi:black`,inactive:`ansi:white`,inactiveShimmer:`ansi:whiteBright`,subtle:`ansi:white`,suggestion:`ansi:blueBright`,remember:`ansi:blueBright`,background:`ansi:cyanBright`,success:`ansi:greenBright`,error:`ansi:redBright`,warning:`ansi:yellowBright`,merged:`ansi:magentaBright`,warningShimmer:`ansi:yellowBright`,diffAdded:`ansi:green`,diffRemoved:`ansi:red`,diffAddedDimmed:`ansi:green`,diffRemovedDimmed:`ansi:red`,diffAddedWord:`ansi:greenBright`,diffRemovedWord:`ansi:redBright`,red_FOR_SUBAGENTS_ONLY:`ansi:redBright`,blue_FOR_SUBAGENTS_ONLY:`ansi:blueBright`,green_FOR_SUBAGENTS_ONLY:`ansi:greenBright`,yellow_FOR_SUBAGENTS_ONLY:`ansi:yellowBright`,purple_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,orange_FOR_SUBAGENTS_ONLY:`ansi:redBright`,pink_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,cyan_FOR_SUBAGENTS_ONLY:`ansi:cyanBright`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`ansi:yellowBright`,clawd_body:`ansi:redBright`,clawd_background:`ansi:black`,userMessageBackground:`ansi:blackBright`,userMessageBackgroundHover:`ansi:white`,messageActionsBackground:`ansi:blackBright`,selectionBg:`ansi:blue`,bashMessageBackgroundColor:`ansi:black`,memoryBackgroundColor:`ansi:blackBright`,rate_limit_fill:`ansi:yellow`,rate_limit_empty:`ansi:white`,fastMode:`ansi:redBright`,fastModeShimmer:`ansi:redBright`,rainbow_red:`ansi:red`,rainbow_orange:`ansi:redBright`,rainbow_yellow:`ansi:yellow`,rainbow_green:`ansi:green`,rainbow_blue:`ansi:cyan`,rainbow_indigo:`ansi:blue`,rainbow_violet:`ansi:magenta`,rainbow_red_shimmer:`ansi:redBright`,rainbow_orange_shimmer:`ansi:yellow`,rainbow_yellow_shimmer:`ansi:yellowBright`,rainbow_green_shimmer:`ansi:greenBright`,rainbow_blue_shimmer:`ansi:cyanBright`,rainbow_indigo_shimmer:`ansi:blueBright`,rainbow_violet_shimmer:`ansi:magentaBright`},unt={autoAccept:`rgb(135,0,255)`,bashBorder:`rgb(0,102,204)`,claude:`rgb(255,153,51)`,claudeShimmer:`rgb(255,183,101)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(51,102,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(101,152,255)`,permission:`rgb(51,102,255)`,permissionShimmer:`rgb(101,152,255)`,planMode:`rgb(51,102,102)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(153,153,153)`,promptBorderShimmer:`rgb(183,183,183)`,text:`rgb(0,0,0)`,inverseText:`rgb(255,255,255)`,inactive:`rgb(102,102,102)`,inactiveShimmer:`rgb(142,142,142)`,subtle:`rgb(175,175,175)`,suggestion:`rgb(51,102,255)`,remember:`rgb(51,102,255)`,background:`rgb(0,153,153)`,success:`rgb(0,102,153)`,error:`rgb(204,0,0)`,warning:`rgb(255,153,0)`,merged:`rgb(135,0,255)`,warningShimmer:`rgb(255,183,50)`,diffAdded:`rgb(153,204,255)`,diffRemoved:`rgb(255,204,204)`,diffAddedDimmed:`rgb(209,231,253)`,diffRemovedDimmed:`rgb(255,233,233)`,diffAddedWord:`rgb(51,102,204)`,diffRemovedWord:`rgb(153,51,51)`,red_FOR_SUBAGENTS_ONLY:`rgb(204,0,0)`,blue_FOR_SUBAGENTS_ONLY:`rgb(0,102,204)`,green_FOR_SUBAGENTS_ONLY:`rgb(0,204,0)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(255,204,0)`,purple_FOR_SUBAGENTS_ONLY:`rgb(128,0,128)`,orange_FOR_SUBAGENTS_ONLY:`rgb(255,128,0)`,pink_FOR_SUBAGENTS_ONLY:`rgb(255,102,178)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(0,178,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(220, 220, 220)`,userMessageBackgroundHover:`rgb(232, 232, 232)`,messageActionsBackground:`rgb(210, 216, 226)`,selectionBg:`rgb(180, 213, 255)`,bashMessageBackgroundColor:`rgb(250, 245, 250)`,memoryBackgroundColor:`rgb(230, 245, 250)`,rate_limit_fill:`rgb(51,102,255)`,rate_limit_empty:`rgb(23,46,114)`,fastMode:`rgb(255,106,0)`,fastModeShimmer:`rgb(255,150,50)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},dnt={autoAccept:`rgb(175,135,255)`,bashBorder:`rgb(253,93,177)`,claude:`rgb(215,119,87)`,claudeShimmer:`rgb(235,159,127)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(147,165,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(177,195,255)`,permission:`rgb(177,185,249)`,permissionShimmer:`rgb(207,215,255)`,planMode:`rgb(72,150,140)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(136,136,136)`,promptBorderShimmer:`rgb(166,166,166)`,text:`rgb(255,255,255)`,inverseText:`rgb(0,0,0)`,inactive:`rgb(153,153,153)`,inactiveShimmer:`rgb(193,193,193)`,subtle:`rgb(80,80,80)`,suggestion:`rgb(177,185,249)`,remember:`rgb(177,185,249)`,background:`rgb(0,204,204)`,success:`rgb(78,186,101)`,error:`rgb(255,107,128)`,warning:`rgb(255,193,7)`,merged:`rgb(175,135,255)`,warningShimmer:`rgb(255,223,57)`,diffAdded:`rgb(34,92,43)`,diffRemoved:`rgb(122,41,54)`,diffAddedDimmed:`rgb(71,88,74)`,diffRemovedDimmed:`rgb(105,72,77)`,diffAddedWord:`rgb(56,166,96)`,diffRemovedWord:`rgb(179,89,107)`,red_FOR_SUBAGENTS_ONLY:`rgb(220,38,38)`,blue_FOR_SUBAGENTS_ONLY:`rgb(37,99,235)`,green_FOR_SUBAGENTS_ONLY:`rgb(22,163,74)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(202,138,4)`,purple_FOR_SUBAGENTS_ONLY:`rgb(147,51,234)`,orange_FOR_SUBAGENTS_ONLY:`rgb(234,88,12)`,pink_FOR_SUBAGENTS_ONLY:`rgb(219,39,119)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(8,145,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(55, 55, 55)`,userMessageBackgroundHover:`rgb(70, 70, 70)`,messageActionsBackground:`rgb(44, 50, 62)`,selectionBg:`rgb(38, 79, 120)`,bashMessageBackgroundColor:`rgb(65, 60, 65)`,memoryBackgroundColor:`rgb(55, 65, 70)`,rate_limit_fill:`rgb(177,185,249)`,rate_limit_empty:`rgb(80,83,112)`,fastMode:`rgb(255,120,20)`,fastModeShimmer:`rgb(255,165,70)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},fnt={autoAccept:`rgb(175,135,255)`,bashBorder:`rgb(51,153,255)`,claude:`rgb(255,153,51)`,claudeShimmer:`rgb(255,183,101)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(153,204,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(183,224,255)`,permission:`rgb(153,204,255)`,permissionShimmer:`rgb(183,224,255)`,planMode:`rgb(102,153,153)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(136,136,136)`,promptBorderShimmer:`rgb(166,166,166)`,text:`rgb(255,255,255)`,inverseText:`rgb(0,0,0)`,inactive:`rgb(153,153,153)`,inactiveShimmer:`rgb(193,193,193)`,subtle:`rgb(80,80,80)`,suggestion:`rgb(153,204,255)`,remember:`rgb(153,204,255)`,background:`rgb(0,204,204)`,success:`rgb(51,153,255)`,error:`rgb(255,102,102)`,warning:`rgb(255,204,0)`,merged:`rgb(175,135,255)`,warningShimmer:`rgb(255,234,50)`,diffAdded:`rgb(0,68,102)`,diffRemoved:`rgb(102,0,0)`,diffAddedDimmed:`rgb(62,81,91)`,diffRemovedDimmed:`rgb(62,44,44)`,diffAddedWord:`rgb(0,119,179)`,diffRemovedWord:`rgb(179,0,0)`,red_FOR_SUBAGENTS_ONLY:`rgb(255,102,102)`,blue_FOR_SUBAGENTS_ONLY:`rgb(102,178,255)`,green_FOR_SUBAGENTS_ONLY:`rgb(102,255,102)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(255,255,102)`,purple_FOR_SUBAGENTS_ONLY:`rgb(178,102,255)`,orange_FOR_SUBAGENTS_ONLY:`rgb(255,178,102)`,pink_FOR_SUBAGENTS_ONLY:`rgb(255,153,204)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(102,204,204)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(55, 55, 55)`,userMessageBackgroundHover:`rgb(70, 70, 70)`,messageActionsBackground:`rgb(44, 50, 62)`,selectionBg:`rgb(38, 79, 120)`,bashMessageBackgroundColor:`rgb(65, 60, 65)`,memoryBackgroundColor:`rgb(55, 65, 70)`,rate_limit_fill:`rgb(153,204,255)`,rate_limit_empty:`rgb(69,92,115)`,fastMode:`rgb(255,120,20)`,fastModeShimmer:`rgb(255,165,70)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},pr.terminal===`Apple_Terminal`&&new mee({level:2})}));function pnt(){return process.env.TERM===`xterm-ghostty`?[`·`,`✢`,`✱`,`✶`,`✻`,`*`]:(process.platform,[`·`,`✢`,`✱`,`✶`,`✻`,`✽`])}function PX(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n)}}function FX(e){return`rgb(${e.r},${e.g},${e.b})`}function mnt(e){let t=(e%360+360)%360,n=.8*.7,r=n*(1-Math.abs(t/60%2-1)),i=.6-n/2,a=0,o=0,s=0;return t<60?(a=n,o=r):t<120?(a=r,o=n):t<180?(o=n,s=r):t<240?(o=r,s=n):t<300?(a=r,s=n):(a=n,s=r),{r:Math.round((a+i)*255),g:Math.round((o+i)*255),b:Math.round((s+i)*255)}}function IX(e){let t=LX.get(e);if(t!==void 0)return t;let n=e.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/),r=n?{r:parseInt(n[1],10),g:parseInt(n[2],10),b:parseInt(n[3],10)}:null;return LX.set(e,r),r}var LX,RX=n((()=>{LX=new Map})),hnt=n((()=>{I(),NX(),et()}));function gnt({message:e,mode:t,messageColor:n,glimmerIndex:r,flashOpacity:i,shimmerColor:a,stalledIntensity:o=0}){let[s]=xe(),c=MX(s),{segments:l,messageWidth:u}=_nt.useMemo(()=>{let t=[];for(let{segment:n}of Oa().segment(e))t.push({segment:n,width:ye(n)});return{segments:t,messageWidth:ye(e)}},[e]);if(!e)return null;if(o>0){let t=c[n],r=t?IX(t):null;if(r){let t=FX(PX(r,vnt,o));return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:t,children:e}),(0,zX.jsx)(F,{color:t,children:` `})]})}let i=o>.5?`error`:n;return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:i,children:e}),(0,zX.jsx)(F,{color:i,children:` `})]})}if(t===`tool-use`){let t=c[n],r=c[a],o=t?IX(t):null,s=r?IX(r):null;return o&&s?(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:FX(PX(o,s,i)),children:e}),(0,zX.jsx)(F,{color:n,children:` `})]}):(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:i>.5?a:n,children:e}),(0,zX.jsx)(F,{color:n,children:` `})]})}let d=r-1,f=r+1;if(d>=u||f<0)return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:n,children:e}),(0,zX.jsx)(F,{color:n,children:` `})]});let p=Math.max(0,d),m=0,h=``,g=``,_=``;for(let{segment:e,width:t}of l)m+t<=p?h+=e:m>f?_+=e:g+=e,m+=t;return(0,zX.jsxs)(zX.Fragment,{children:[h&&(0,zX.jsx)(F,{color:n,children:h}),(0,zX.jsx)(F,{color:a,children:g}),_&&(0,zX.jsx)(F,{color:n,children:_}),(0,zX.jsx)(F,{color:n,children:` `})]})}var _nt,zX,vnt,ynt=n((()=>{_nt=r(ze(),1),I(),ka(),NX(),RX(),zX=et(),vnt={r:171,g:43,b:63}}));function bnt({frame:e,messageColor:t,stalledIntensity:n=0,reducedMotion:r=!1,time:i=0}){let[a]=xe(),o=MX(a);if(r)return(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:t,dimColor:Math.floor(i/(Snt/2))%2==1,children:xnt})});let s=HX[e%HX.length];if(n>0){let e=o[t],r=e?IX(e):null;return r?(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:FX(PX(r,Cnt,n)),children:s})}):(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:n>.5?`error`:t,children:s})})}return(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:t,children:s})})}var BX,VX,HX,xnt,Snt,Cnt,UX=n((()=>{I(),NX(),RX(),BX=et(),VX=pnt(),HX=[...VX,...[...VX].reverse()],xnt=`●`,Snt=2e3,Cnt={r:171,g:43,b:63}}));function wnt(e,t,n){let r=e===`requesting`?50:200,[i,a]=Ye(n?null:r),o=(0,Tnt.useMemo)(()=>ye(t),[t]);if(n)return[i,-100];let s=Math.floor(a/r),c=o+20;return e===`requesting`?[i,s%c-10]:[i,o+10-s%c]}var Tnt,Ent=n((()=>{Tnt=r(ze(),1),I()}));function Dnt(e,t,n=!1,r=!1){let i=(0,WX.useRef)(e),a=(0,WX.useRef)(t),o=(0,WX.useRef)(e),s=(0,WX.useRef)(0),c=(0,WX.useRef)(e);t>a.current&&(i.current=e,a.current=t,s.current=0,c.current=e);let l;n?(l=0,i.current=e):l=t>0?e-i.current:e-o.current;let u=l>3e3&&!n,d=u?Math.min((l-3e3)/2e3,1):0;if(!r&&(d>0||s.current>0)){let t=e-c.current;if(t>=50){let n=Math.floor(t/50),r=s.current;for(let e=0;e<n;e++){let e=d-r;if(Math.abs(e)<.01){r=d;break}r+=e*.1}s.current=r,c.current=e}}else s.current=d,c.current=e;return{isStalled:u,stalledIntensity:r?d:s.current}}var WX,Ont=n((()=>{WX=r(ze(),1)})),knt=n((()=>{hnt(),ynt(),PY(),UX(),Ent(),Ont(),RX()}));function Ant({mode:e,reducedMotion:t,hasActiveTools:n,responseLengthRef:r,message:i,messageColor:a,shimmerColor:o,overrideColor:s,loadingStartTimeRef:c,totalPausedMsRef:l,pauseStartTimeRef:u,spinnerSuffix:d,verbose:f,columns:p,agentTokens:m,leaderIsIdle:h=!1,thinkingStatus:g}){let[_,v]=Ye(t?null:50),y=Date.now(),b=u.current===null?y-c.current-l.current:u.current-c.current-l.current,x=r.current,{isStalled:S,stalledIntensity:C}=Dnt(v,x,n||h,t),w=t?0:Math.floor(v/120),T=e===`requesting`?50:200,E=(0,GX.useMemo)(()=>ye(i),[i]),D=E+20,O=Math.floor(v/T),k=t||S?-100:e===`requesting`?O%D-10:E+10-O%D,A=t?0:e===`tool-use`?(Math.sin(v/1e3*Math.PI)+1)/2:0,ee=(0,GX.useRef)(x);if(t)ee.current=x;else{let e=x-ee.current;if(e>0){let t;t=e<70?3:e<200?Math.max(8,Math.ceil(e*.15)):50,ee.current=Math.min(ee.current+t,x)}}let te=ee.current,ne=Math.round(te/4),re=La(b),ae=ye(re),j=ne+m,oe=Pa(j),se=ye(`${ie.arrowDown} ${oe} tokens`),ce=g===`thinking`?`thinking`:typeof g==`number`?`thought for ${Math.max(1,Math.round(g/1e3))}s`:null,M=ce?ye(ce):0,N=E+2,le=Mnt,ue=g!==null,de=f||b>Nnt,fe=p-N-5,pe=ue&&fe>M;!pe&&ue&&g===`thinking`&&fe>qX&&(ce=`thinking`,M=qX,pe=!0);let me=pe?M+le:0,he=de&&fe>me+ae,ge=me+(he?ae+le:0),_e=de&&j>0&&fe>ge+se,ve=pe&&g===`thinking`&&!d&&!he&&!_e&&!0,be=(v-JX)/1e3,xe=v<JX?0:(Math.sin(be*Math.PI*2/Int)+1)/2,Se=FX(PX(Pnt,Fnt,xe)),Ce=[...d?[(0,KX.jsx)(F,{dimColor:!0,children:d},`suffix`)]:[],...he?[(0,KX.jsx)(F,{dimColor:!0,children:re},`elapsedTime`)]:[],..._e?[(0,KX.jsxs)(P,{flexDirection:`row`,children:[(0,KX.jsx)(jnt,{mode:e}),(0,KX.jsxs)(F,{dimColor:!0,children:[oe,` tokens`]})]},`tokens`)]:[],...pe&&ce?[g===`thinking`&&!t?(0,KX.jsx)(F,{color:Se,children:ve?`(${ce})`:ce},`thinking`):(0,KX.jsx)(F,{dimColor:!0,children:ce},`thinking`)]:[]],we=Ce.length>0?ve?(0,KX.jsx)(je,{children:Ce}):(0,KX.jsxs)(KX.Fragment,{children:[(0,KX.jsx)(F,{dimColor:!0,children:`(`}),(0,KX.jsx)(je,{children:Ce}),(0,KX.jsx)(F,{dimColor:!0,children:`)`})]}):null;return(0,KX.jsxs)(P,{ref:_,flexDirection:`row`,flexWrap:`wrap`,marginTop:1,width:`100%`,children:[(0,KX.jsx)(bnt,{frame:w,messageColor:a,stalledIntensity:s?0:C,reducedMotion:t,time:v}),(0,KX.jsx)(gnt,{message:i,mode:e,messageColor:a,glimmerIndex:k,flashOpacity:A,shimmerColor:o,stalledIntensity:s?0:C}),we]})}function jnt({mode:e}){switch(e){case`tool-input`:case`tool-use`:case`responding`:case`thinking`:return(0,KX.jsx)(P,{width:2,children:(0,KX.jsx)(F,{dimColor:!0,children:ie.arrowDown})});case`requesting`:return(0,KX.jsx)(P,{width:2,children:(0,KX.jsx)(F,{dimColor:!0,children:ie.arrowUp})})}}var GX,KX,Mnt,qX,Nnt,Pnt,Fnt,JX,Int,Lnt=n((()=>{ne(),GX=r(ze(),1),I(),Ba(),ynt(),UX(),Ont(),RX(),KX=et(),Mnt=ye(` · `),qX=ye(`thinking`),Nnt=3e4,Pnt={r:153,g:153,b:153},Fnt={r:185,g:185,b:185},JX=3e3,Int=2}));function Rnt(e){return(0,ZX.jsx)(znt,{...e})}function znt({mode:e,loadingStartTimeRef:t,totalPausedMsRef:n,pauseStartTimeRef:r,spinnerTip:i,responseLengthRef:a,overrideColor:o,overrideShimmerColor:s,overrideMessage:c,spinnerSuffix:l,verbose:u,hasActiveTools:d=!1,leaderIsIdle:f=!1}){let p=hV(),m=p.prefersReducedMotion??!1,h=sV(e=>e.tasks),g=sV(e=>e.expandedView)===`tasks`,{columns:_}=Xe(),v=hX(),[y,b]=(0,XX.useState)(null),x=(0,XX.useRef)(null);(0,XX.useEffect)(()=>{let t=null,n=null;if(e===`thinking`)x.current===null&&(x.current=Date.now(),b(`thinking`));else if(x.current!==null){let e=Date.now()-x.current,r=Date.now()-x.current,i=Math.max(0,2e3-r);x.current=null;let a=()=>{b(e),n=setTimeout(b,2e3,null)};i>0?t=setTimeout(a,i):a()}return()=>{t&&clearTimeout(t),n&&clearTimeout(n)}},[e]);let S=v?.find(e=>e.status!==`pending`&&e.status!==`completed`),C=Bnt(v),[w]=(0,XX.useState)(()=>ch(ztt())),T=`${c??S?.activeForm??S?.subject??w}…`;(0,XX.useEffect)(()=>{let t=`spinner-${e}`;return lX.startCLIActivity(t),()=>{lX.endCLIActivity(t)}},[e]);let E=0;for(let e of Object.values(h))e.status===`running`&&s0(e)&&e.progress?.tokenCount&&(E+=e.progress.tokenCount);let D=r.current===null?Date.now()-t.current-n.current:r.current-t.current-n.current,O=o??`claude`,k=s??`claudeShimmer`,A=p.spinnerTipsEnabled!==!1,ee=A&&D>18e5,te=A&&D>3e4&&!yi().btwUseCount,ne=ee&&!C?`Use /clear to start fresh when switching topics and free up context`:te&&!C?`Use /btw to ask a quick side question without interrupting Claude's current work`:i;return(0,ZX.jsxs)(P,{flexDirection:`column`,width:`100%`,alignItems:`flex-start`,children:[(0,ZX.jsx)(Ant,{mode:e,reducedMotion:m,hasActiveTools:d,responseLengthRef:a,message:T,messageColor:O,shimmerColor:k,overrideColor:o,loadingStartTimeRef:t,totalPausedMsRef:n,pauseStartTimeRef:r,spinnerSuffix:l,verbose:u,columns:_,agentTokens:E,leaderIsIdle:f,thinkingStatus:y}),g&&v&&v.length>0?(0,ZX.jsx)(P,{width:`100%`,flexDirection:`column`,children:(0,ZX.jsx)(Z,{children:(0,ZX.jsx)(Vtt,{tasks:v})})}):C||ne?(0,ZX.jsxs)(P,{width:`100%`,flexDirection:`column`,children:[null,(C||ne)&&(0,ZX.jsx)(Z,{children:(0,ZX.jsx)(F,{dimColor:!0,children:C?`Next: ${C.subject}`:`Tip: ${ne}`})})]}):null]})}function YX(){let e=hV().prefersReducedMotion??!1,[t,n]=Ye(e?null:120);if(e)return(0,ZX.jsx)(P,{ref:t,flexWrap:`wrap`,height:1,width:2,children:(0,ZX.jsx)(F,{color:`text`,children:`●`})});let r=Math.floor(n/120)%$X.length;return(0,ZX.jsx)(P,{ref:t,flexWrap:`wrap`,height:1,width:2,children:(0,ZX.jsx)(F,{color:`text`,children:$X[r]})})}function Bnt(e){if(!e)return;let t=e.filter(e=>e.status===`pending`);if(t.length===0)return;let n=new Set(e.filter(e=>e.status!==`completed`).map(e=>e.id));return t.find(e=>!e.blockedBy.some(e=>n.has(e)))??t[0]}var XX,ZX,QX,$X,Vnt=n((()=>{I(),XX=r(ze(),1),lh(),Ba(),Rtt(),Btt(),Rb(),Wtt(),ant(),mV(),eb(),knt(),Lnt(),gV(),p0(),Wt(),bi(),ZX=et(),QX=pnt(),$X=[...QX,...[...QX].reverse()]}));function Hnt({onStashAndContinue:e,onCancel:t}){let[n,r]=(0,eZ.useState)(null),i=n===null?[]:[...n.tracked,...n.untracked],[a,o]=(0,eZ.useState)(!0),[s,c]=(0,eZ.useState)(!1),[l,u]=(0,eZ.useState)(null);(0,eZ.useEffect)(()=>{(async()=>{try{let e=await bie();r(e)}catch(e){U(`Error getting changed files: ${e instanceof Error?e.message:String(e)}`,{level:`error`}),u(`Failed to get changed files`)}finally{o(!1)}})()},[]);let d=async()=>{c(!0);try{U(`Stashing changes before teleport...`),await gie(`Teleport auto-stash`)?(U(`Successfully stashed changes`),e()):u(`Failed to stash changes`)}catch(e){U(`Error stashing changes: ${e instanceof Error?e.message:String(e)}`,{level:`error`}),u(`Failed to stash changes`)}finally{c(!1)}},f=e=>{e===`stash`?d():t()};if(a)return(0,tZ.jsx)(P,{flexDirection:`column`,padding:1,children:(0,tZ.jsxs)(P,{marginBottom:1,children:[(0,tZ.jsx)(YX,{}),(0,tZ.jsxs)(F,{children:[` Checking git status`,ie.ellipsis]})]})});if(l)return(0,tZ.jsxs)(P,{flexDirection:`column`,padding:1,children:[(0,tZ.jsxs)(F,{bold:!0,color:`error`,children:[`Error: `,l]}),(0,tZ.jsxs)(P,{marginTop:1,children:[(0,tZ.jsx)(F,{dimColor:!0,children:`Press `}),(0,tZ.jsx)(F,{bold:!0,children:`Escape`}),(0,tZ.jsx)(F,{dimColor:!0,children:` to cancel`})]})]});let p=i.length>8;return(0,tZ.jsxs)($e,{title:`Working Directory Has Changes`,onCancel:t,children:[(0,tZ.jsx)(F,{children:`Teleport will switch git branches. The following changes were found:`}),(0,tZ.jsx)(P,{flexDirection:`column`,paddingLeft:2,children:i.length>0?p?(0,tZ.jsxs)(F,{children:[i.length,` files changed`]}):i.map((e,t)=>(0,tZ.jsx)(F,{children:e},t)):(0,tZ.jsx)(F,{dimColor:!0,children:`No changes detected`})}),(0,tZ.jsx)(F,{children:`Would you like to stash these changes and continue with teleport?`}),s?(0,tZ.jsxs)(P,{children:[(0,tZ.jsx)(YX,{}),(0,tZ.jsx)(F,{children:` Stashing changes...`})]}):(0,tZ.jsx)(iX,{options:[{label:`Stash changes and continue`,value:`stash`},{label:`Exit`,value:`exit`}],onChange:f})]})}var eZ,tZ,Unt=n((()=>{ne(),eZ=r(ze(),1),I(),W(),Mi(),sX(),Vnt(),tZ=et()}));function Wnt({onComplete:e,errorsToIgnore:t=Knt}){let[n,r]=(0,nZ.useState)(null),[i,a]=(0,nZ.useState)(!1),o=(0,nZ.useCallback)(async()=>{let n=await Gnt(),i=new Set(Array.from(n).filter(e=>!t.has(e)));if(i.size===0){e();return}i.has(`needsLogin`)?r(`needsLogin`):i.has(`needsGitStash`)&&r(`needsGitStash`)},[e,t]);(0,nZ.useEffect)(()=>{o()},[o]);let s=(0,nZ.useCallback)(()=>{UJ(0)},[]),c=(0,nZ.useCallback)(()=>{a(!1),o()},[o]),l=(0,nZ.useCallback)(()=>{a(!0)},[a]),u=(0,nZ.useCallback)(e=>{e===`login`?l():s()},[l,s]),d=(0,nZ.useCallback)(()=>{o()},[o]);if(!n)return null;switch(n){case`needsGitStash`:return(0,rZ.jsx)(Hnt,{onStashAndContinue:d,onCancel:s});case`needsLogin`:return i?(0,rZ.jsx)(ptt,{onDone:c}):(0,rZ.jsxs)($e,{title:`Log in to Claude`,onCancel:s,children:[(0,rZ.jsxs)(P,{flexDirection:`column`,children:[(0,rZ.jsx)(F,{dimColor:!0,children:`Teleport requires a Claude.ai account.`}),(0,rZ.jsx)(F,{dimColor:!0,children:`Your Claude Pro/Max subscription will be used by Claude Code.`})]}),(0,rZ.jsx)(iX,{options:[{label:`Login with Claude account`,value:`login`},{label:`Exit`,value:`exit`}],onChange:u})]})}}async function Gnt(){let e=new Set,[t,n]=await Promise.all([F9e(),I9e()]);return t&&e.add(`needsLogin`),n||e.add(`needsGitStash`),e}var nZ,rZ,Knt,qnt=n((()=>{nZ=r(ze(),1),zJ(),YJ(),I(),htt(),sX(),Unt(),rZ=et(),Knt=new Set}));function Jnt({children:e}){let{addNotification:t,removeNotification:n}=XJ();return(0,Xnt.jsx)(Pe,{loadBindings:fm,subscribeToChanges:ome,initWatcher:$pe,onWarnings:(0,Ynt.useCallback)((e,r)=>{let i=`keybinding-config-warning`;if(e.length===0){n(i);return}let a=hr(e,e=>e.severity===`error`),o=hr(e,e=>e.severity===`warning`),s;s=a>0&&o>0?`Found ${a} keybinding ${qa(a,`error`)} and ${o} ${qa(o,`warning`)}`:a>0?`Found ${a} keybinding ${qa(a,`error`)}`:`Found ${o} keybinding ${qa(o,`warning`)}`,s+=` · /doctor for details`,t({key:i,text:s,color:a>0?`error`:`warning`,priority:a>0?`immediate`:`high`,timeoutMs:6e4})},[t,n]),onDebugLog:U,children:e})}var Ynt,Xnt,Znt=n((()=>{Ynt=r(ze(),1),tY(),Cr(),W(),Ja(),I(),bm(),Xnt=et()}));function Qnt(e){let t=sZ.get(e);return t||(t=Fae(async(t,n,r)=>await $nt(e,t,n,r)),sZ.set(e,t)),t}async function $nt(e,t,n,r){for(let i=1;i<=oZ;i++){try{let a=aZ.get(e),o={...r};a&&(o[`Last-Uuid`]=a);let s=await ue.put(n,t,{headers:o,validateStatus:e=>e<500});if(s.status===200||s.status===201)return aZ.set(e,t.uuid),U(`Successfully persisted session log entry for session ${e}`),!0;if(s.status===409){let i=s.headers[`x-last-uuid`];if(i===t.uuid)return aZ.set(e,t.uuid),U(`Session entry ${t.uuid} already present on server, recovering from stale state`),Ai(`info`,`session_persist_recovered_from_409`),!0;if(i)aZ.set(e,i),U(`Session 409: adopting server lastUuid=${i} from header, retrying entry ${t.uuid}`);else{let i=await iZ(e,n,r),a=irt(i);if(a)aZ.set(e,a),U(`Session 409: re-fetched ${i.length} entries, adopting lastUuid=${a}, retrying entry ${t.uuid}`);else{let n=s.data.error?.message||`Concurrent modification detected`;return q(Error(`Session persistence conflict: UUID mismatch for session ${e}, entry ${t.uuid}. ${n}`)),Ai(`error`,`session_persist_fail_concurrent_modification`),!1}}Ai(`info`,`session_persist_409_adopt_server_uuid`);continue}if(s.status===401)return U(`Session token expired or invalid`),Ai(`error`,`session_persist_fail_bad_token`),!1;U(`Failed to persist session log: ${s.status} ${s.statusText}`),Ai(`error`,`session_persist_fail_status`,{status:s.status,attempt:i})}catch(e){let t=e;q(Error(`Error persisting session log: ${t.message}`)),Ai(`error`,`session_persist_fail_status`,{status:t.status,attempt:i})}if(i===oZ)return U(`Remote persistence failed after ${oZ} attempts`),Ai(`error`,`session_persist_error_retries_exhausted`,{attempt:i}),!1;let a=Math.min(ort*2**(i-1),8e3);U(`Remote persistence attempt ${i}/${oZ} failed, retrying in ${a}ms…`),await $o(a)}return!1}async function ert(e,t,n){let r=$s();if(!r)return U(`No session token available for session persistence`),Ai(`error`,`session_persist_fail_jwt_no_token`),!1;let i={Authorization:`Bearer ${r}`,"Content-Type":`application/json`};return Qnt(e)(t,n,i)}async function trt(e,t){let n=$s();if(!n)return U(`No session token available for fetching session logs`),Ai(`error`,`session_get_fail_no_token`),null;let r=await iZ(e,t,{Authorization:`Bearer ${n}`});if(r&&r.length>0){let t=r.at(-1);t&&`uuid`in t&&t.uuid&&aZ.set(e,t.uuid)}return r}async function nrt(e,t,n){let r=`${Va().BASE_API_URL}/v1/session_ingress/session/${e}`;return U(`[session-ingress] Fetching session logs from: ${r}`),await iZ(e,r,{...Bc(t),"x-organization-uuid":n})}async function rrt(e,t,n){let r=`${Va().BASE_API_URL}/v1/code/sessions/${e}/teleport-events`,i={...Bc(t),"x-organization-uuid":n};U(`[teleport] Fetching events from: ${r}`);let a=[],o,s=0;for(;s<100;){let t={limit:1e3};o!==void 0&&(t.cursor=o);let n;try{n=await ue.get(r,{headers:i,params:t,timeout:2e4,validateStatus:e=>e<500})}catch(e){return q(Error(`Teleport events fetch failed: ${e.message}`)),Ai(`error`,`teleport_events_fetch_fail`),null}if(n.status===404)return U(`[teleport] Session ${e} not found (page ${s})`),Ai(`warn`,`teleport_events_not_found`),s===0?null:a;if(n.status===401)throw Ai(`error`,`teleport_events_bad_token`),Error(`Your session has expired.`);if(n.status!==200)return q(Error(`Teleport events returned ${n.status}: ${V(n.data)}`)),Ai(`error`,`teleport_events_bad_status`),null;let{data:c,next_cursor:l}=n.data;if(!Array.isArray(c))return q(Error(`Teleport events invalid response shape: ${V(n.data)}`)),Ai(`error`,`teleport_events_invalid_shape`),null;for(let e of c)e.payload!==null&&a.push(e.payload);if(s++,l==null)break;o=l}return s>=100&&(q(Error(`Teleport events hit page cap (100) for ${e}`)),Ai(`warn`,`teleport_events_page_cap`)),U(`[teleport] Fetched ${a.length} events over ${s} page(s) for ${e}`),a}async function iZ(e,t,n){try{let r=await ue.get(t,{headers:n,timeout:2e4,validateStatus:e=>e<500,params:m(process.env.CLAUDE_AFTER_LAST_COMPACT)?{after_last_compact:!0}:void 0});if(r.status===200){let t=r.data;if(!t||typeof t!=`object`||!Array.isArray(t.loglines))return q(Error(`Invalid session logs response format: ${V(t)}`)),Ai(`error`,`session_get_fail_invalid_response`),null;let n=t.loglines;return U(`Fetched ${n.length} session logs for session ${e}`),n}if(r.status===404)return U(`No existing logs for session ${e}`),Ai(`warn`,`session_get_no_logs_for_session`),[];if(r.status===401)throw U(`Auth token expired or invalid`),Ai(`error`,`session_get_fail_bad_token`),Error(`Your session has expired.`);return U(`Failed to fetch session logs: ${r.status} ${r.statusText}`),Ai(`error`,`session_get_fail_status`,{status:r.status}),null}catch(e){let t=e;return q(Error(`Error fetching session logs: ${t.message}`)),Ai(`error`,`session_get_fail_status`,{status:t.status}),null}}function irt(e){if(!e)return;let t=e.findLast(e=>`uuid`in e&&e.uuid);return t&&`uuid`in t?t.uuid:void 0}function art(){aZ.clear(),sZ.clear()}var aZ,oZ,ort,sZ,cZ=n((()=>{de(),Ha(),W(),Ei(),h(),Qi(),$a(),Pse(),Po(),Yn(),Vc(),aZ=new Map,oZ=10,ort=500,sZ=new Map}));function srt(e){if(e.type!==`attachment`)return e;let t=e.attachment;if(t.type===`new_file`)return{...e,attachment:{...t,type:`file`,displayPath:$c(yn(),t.filename)}};if(t.type===`new_directory`)return{...e,attachment:{...t,type:`directory`,displayPath:$c(yn(),t.path)}};if(!(`displayPath`in t)){let n=`filename`in t?t.filename:`path`in t?t.path:`skillDir`in t?t.skillDir:void 0;if(n)return{...e,attachment:{...t,displayPath:$c(yn(),n)}}}return e}function crt(e){return lrt(e).messages}function lrt(e){try{let t=e.map(srt),n=new Set($n);for(let e of t)e.type===`user`&&e.permissionMode!==void 0&&!n.has(e.permissionMode)&&(e.permissionMode=void 0);let r=_xt(yxt(Hbt(t))),i=urt(r),a;if(i.kind===`interrupted_turn`){let[e]=F4([$({content:`Continue from where you left off.`,isMeta:!0})]);r.push(e),a={kind:`interrupted_prompt`,message:e}}else a=i;let o=r.findLastIndex(e=>e.type!==`system`&&e.type!==`progress`);return o!==-1&&r[o].type===`user`&&r.splice(o+1,0,k4({content:l3})),{messages:r,turnInterruptionState:a}}catch(e){throw q(e),e}}function urt(e){if(e.length===0)return{kind:`none`};let t=e.findLastIndex(e=>e.type!==`system`&&e.type!==`progress`&&!(e.type===`assistant`&&e.isApiErrorMessage)),n=t===-1?void 0:e[t];return!n||n.type===`assistant`?{kind:`none`}:n.type===`user`?n.isMeta||n.isCompactSummary?{kind:`none`}:bbt(n)?{kind:`interrupted_turn`}:{kind:`interrupted_prompt`,message:n}:n.type===`attachment`?{kind:`interrupted_turn`}:{kind:`none`}}function drt(e){for(let t of e)if(t.type===`attachment`){if(t.attachment.type===`invoked_skills`){let e=t.attachment.skills;for(let t of e)t.name&&t.path&&t.content&&sne(t.name,t.path,t.content,null)}t.attachment.type===`skill_listing`&&Bgt()}Bgt(),Vgt()}async function frt(e){let{messages:t,leafUuids:n}=await H6(e),r=null,i=0;for(let e of t.values()){if(e.isSidechain||!n.has(e.uuid))continue;let t=new Date(e.timestamp).getTime();t>i&&(i=t,r=e)}return r?{messages:w6(E6(t,r)),sessionId:r.sessionId}:{messages:[],sessionId:void 0}}async function prt(e,t){try{let n=null,r=null,i;if(e===void 0){let e=q6(),t=new Set;try{let{listAllLiveSessions:e}=await import(`./udsClient-DSvRPCvR.js`),n=await e();t=new Set(n.flatMap(e=>e.kind&&e.kind!==`interactive`&&e.sessionId?[e.sessionId]:[]))}catch{}n=(await e).find(e=>{let n=z6(e);return!n||!t.has(n)})??null}else if(t){let e=await frt(t);r=e.messages,i=e.sessionId}else typeof e==`string`?(n=await K6(e),i=e):n=e;if(!n&&!r)return null;n&&(B6(n)&&(n=await V6(n)),i||(i=z6(n)),i&&await cf(n,OB(i)),uHe(n),r=n.messages,D6(r)),drt(r);let a=lrt(r);r=a.messages;let o=await Mz(`resume`,{sessionId:i});return r.push(...o),{messages:r,turnInterruptionState:a.turnInterruptionState,fileHistorySnapshots:n?.fileHistorySnapshots,attributionSnapshots:n?.attributionSnapshots,contentReplacements:n?.contentReplacements,contextCollapseCommits:n?.contextCollapseCommits,contextCollapseSnapshot:n?.contextCollapseSnapshot,sessionId:i,agentName:n?.agentName,agentColor:n?.agentColor,agentSetting:n?.agentSetting,customTitle:n?.customTitle,tag:n?.tag,mode:n?.mode,worktreeSession:n?.worktreeSession,prNumber:n?.prNumber,prUrl:n?.prUrl,prRepository:n?.prRepository,fullPath:n?.fullPath,goal:n?.goal}}catch(e){throw q(e),e}}var mrt=n((()=>{vn(),Wt(),AB(),nre(),H0(),ZB(),Qi(),m3(),ff(),Pz(),h8()}));function hrt(){return process.env.ANTHROPIC_BASE_URL||process.env.CLAUDE_CODE_API_BASE_URL||`https://api.anthropic.com`}function lZ(e){U(`[files-api] ${e}`,{level:`error`})}function uZ(e){U(`[files-api] ${e}`)}async function grt(e,t){let n=``;for(let r=1;r<=pZ;r++){let i=await t(r);if(i.done)return i.value;if(n=i.error||`${e} failed`,uZ(`${e} attempt ${r}/${pZ} failed: ${n}`),r<pZ){let t=wrt*2**(r-1);uZ(`Retrying ${e} in ${t}ms...`),await $o(t)}}throw Error(`${n} after ${pZ} attempts`)}async function _rt(e,t){let n=`${t.baseUrl||hrt()}/v1/files/${e}/content`,r={Authorization:`Bearer ${t.oauthToken}`,"anthropic-version":fZ,"anthropic-beta":dZ};return uZ(`Downloading file ${e} from ${n}`),grt(`Download file ${e}`,async()=>{try{let t=await ue.get(n,{headers:r,responseType:`arraybuffer`,timeout:6e4,validateStatus:e=>e<500});if(t.status===200)return uZ(`Downloaded file ${e} (${t.data.length} bytes)`),{done:!0,value:Buffer.from(t.data)};if(t.status===404)throw Error(`File not found: ${e}`);if(t.status===401)throw Error(`Authentication failed: invalid or missing API key`);if(t.status===403)throw Error(`Access denied to file: ${e}`);return{done:!1,error:`status ${t.status}`}}catch(e){if(!ue.isAxiosError(e))throw e;return{done:!1,error:e.message}}})}function vrt(e,t,n){let r=Gc.normalize(n);if(r.startsWith(`..`))return lZ(`Invalid file path: ${n}. Path must not traverse above workspace`),null;let i=Gc.join(e,t,`uploads`),a=[Gc.join(e,t,`uploads`)+Gc.sep,`${Gc.sep}uploads${Gc.sep}`].find(e=>r.startsWith(e)),o=a?r.slice(a.length):r;return Gc.join(i,o)}async function yrt(e,t){let{fileId:n,relativePath:r}=e,i=vrt(yn(),t.sessionId,r);if(!i)return{fileId:n,path:``,success:!1,error:`Invalid file path: ${r}`};try{let e=await _rt(n,t),r=Gc.dirname(i);return await xl.mkdir(r,{recursive:!0}),await xl.writeFile(i,e),uZ(`Saved file ${n} to ${i} (${e.length} bytes)`),{fileId:n,path:i,success:!0,bytesWritten:e.length}}catch(e){return lZ(`Failed to download file ${n}: ${H(e)}`),e instanceof Error&&q(e),{fileId:n,path:i,success:!1,error:H(e)}}}async function brt(e,t,n){let r=Array(e.length),i=0;async function a(){for(;i<e.length;){let n=i++,a=e[n];a!==void 0&&(r[n]=await t(a,n))}}let o=[],s=Math.min(n,e.length);for(let e=0;e<s;e++)o.push(a());return await Promise.all(o),r}async function xrt(e,t,n=Trt){if(e.length===0)return[];uZ(`Downloading ${e.length} file(s) for session ${t.sessionId}`);let r=Date.now(),i=await brt(e,e=>yrt(e,t),n),a=Date.now()-r;return uZ(`Downloaded ${hr(i,e=>e.success)}/${e.length} file(s) in ${a}ms`),i}async function Srt(e,t,n,r){let i=`${n.baseUrl||hrt()}/v1/files`,a={Authorization:`Bearer ${n.oauthToken}`,"anthropic-version":fZ,"anthropic-beta":dZ};uZ(`Uploading file ${e} as ${t}`);let o;try{o=await xl.readFile(e)}catch(e){return J(`tengu_file_upload_failed`,{error_type:`file_read`}),{path:t,error:H(e),success:!1}}let s=o.length;if(s>mZ)return J(`tengu_file_upload_failed`,{error_type:`file_too_large`}),{path:t,error:`File exceeds maximum size of ${mZ} bytes (actual: ${s})`,success:!1};let c=`----FormBoundary${bl()}`,l=Gc.basename(t),u=[];u.push(Buffer.from(`--${c}\r\nContent-Disposition: form-data; name="file"; filename="${l}"\r\nContent-Type: application/octet-stream\r\n\r\n`)),u.push(o),u.push(Buffer.from(`\r
1672
+ `);for(let n=0;n<t.length;n++){n>0&&(r.push([]),i+=1);let a=t[n];a.length>0&&r[r.length-1].push({text:a,highlight:e.highlight,start:i}),i+=a.length}}let a=t.some(e=>e.shimmerColor),o=0,s=1;if(a){let e=1/0,n=-1/0;for(let r of t)r.shimmerColor&&(e=Math.min(e,r.start),n=Math.max(n,r.end));o=e-10,s=n-e+20}return{lines:r,hasShimmer:a,sweepStart:o,cycleLength:s}},[e,t]),[o,s]=Ye(r?50:null),c=r?i+Math.floor(s/50)%a:-100;return(0,FY.jsx)(P,{ref:o,flexDirection:`column`,children:n.map((e,t)=>(0,FY.jsx)(P,{children:e.length===0?(0,FY.jsx)(F,{children:` `}):e.map((e,t)=>e.highlight?.shimmerColor&&e.highlight.color?(0,FY.jsx)(F,{children:e.text.split(``).map((t,n)=>(0,FY.jsx)(itt,{char:t,index:e.start+n,glimmerIndex:c,messageColor:e.highlight.color,shimmerColor:e.highlight.shimmerColor},n))},t):(0,FY.jsx)(F,{color:e.highlight?.color,dimColor:e.highlight?.dimColor,inverse:e.highlight?.inverse,children:(0,FY.jsx)(_e,{children:e.text})},t))},t))})}var stt,FY,ctt=n((()=>{stt=r(ze(),1),I(),rtt(),PY(),FY=et()}));function ltt({inputState:e,children:t,terminalFocus:n,invert:r,hidePlaceholderText:i,...a}){let{onInput:o,renderedValue:s,cursorLine:c,cursorColumn:l}=e,u=ve({line:c,column:l,active:!!(a.focus&&a.showCursor&&n)}),{wrappedOnInput:d,isPasting:f}=Xet({onPaste:a.onPaste,onInput:(e,t)=>{f&&t.return||o(e,t)},onImagePaste:a.onImagePaste}),{onIsPastingChange:p}=a;utt.useEffect(()=>{p&&p(f)},[f,p]);let{showPlaceholder:m,renderedPlaceholder:h}=Jet({placeholder:a.placeholder,value:a.value,showCursor:a.showCursor,focus:a.focus,terminalFocus:n,invert:r,hidePlaceholderText:i});Je(d,{isActive:a.focus});let g=a.value&&a.value.trim().indexOf(` `)===-1||a.value?.endsWith(` `),_=!!(a.argumentHint&&a.value&&g&&a.value.startsWith(`/`)),v=a.showCursor&&a.highlights?a.highlights.filter(e=>e.dimColor||a.cursorOffset<e.start||a.cursorOffset>=e.end):a.highlights,{viewportCharOffset:y,viewportCharEnd:b}=e,x=v&&y>0?v.filter(e=>e.end>y&&e.start<b).map(e=>({...e,start:Math.max(0,e.start-y),end:e.end-y})):v;return x&&x.length>0?(0,IY.jsxs)(P,{ref:u,children:[(0,IY.jsx)(ott,{text:s,highlights:x}),_&&(0,IY.jsxs)(F,{dimColor:!0,children:[a.value?.endsWith(` `)?``:` `,a.argumentHint]}),t]}):(0,IY.jsx)(P,{ref:u,children:(0,IY.jsxs)(F,{wrap:`truncate-end`,dimColor:a.dimColor,children:[m&&a.placeholderElement?a.placeholderElement:m&&h?(0,IY.jsx)(_e,{children:h}):(0,IY.jsx)(_e,{children:s}),_&&(0,IY.jsxs)(F,{dimColor:!0,children:[a.value?.endsWith(` `)?``:` `,a.argumentHint]}),t]})})}var utt,IY,dtt=n((()=>{utt=r(ze(),1),Yet(),$et(),I(),ctt(),IY=et()}));function LY(e){let[t]=xe(),n=Ie(),r=(0,ftt.useMemo)(()=>m(process.env.CLAUDE_CODE_ACCESSIBILITY),[]);hV().prefersReducedMotion,Z9e(n,!!e.onImagePaste);let i=n&&!r?Ue.inverse:e=>e;return(0,RY.jsx)(P,{children:(0,RY.jsx)(ltt,{inputState:Ket({value:e.value,onChange:e.onChange,onSubmit:e.onSubmit,onExit:e.onExit,onExitMessage:e.onExitMessage,onHistoryReset:e.onHistoryReset,onHistoryUp:e.onHistoryUp,onHistoryDown:e.onHistoryDown,onClearInput:e.onClearInput,focus:e.focus,mask:e.mask,multiline:e.multiline,cursorChar:e.showCursor?` `:``,highlightPastedText:e.highlightPastedText,invert:i,themeText:ree(`text`,t),columns:e.columns,maxVisibleLines:e.maxVisibleLines,onImagePaste:e.onImagePaste,disableCursorMovementForUpDownKeys:e.disableCursorMovementForUpDownKeys,disableEscapeDoublePress:e.disableEscapeDoublePress,externalOffset:e.cursorOffset,onOffsetChange:e.onChangeCursorOffset,inputFilter:e.inputFilter,inlineGhostText:e.inlineGhostText,dim:Ue.dim}),terminalFocus:n,highlights:e.highlights,invert:i,...e})})}var ftt,RY,zY=n((()=>{Ge(),ftt=r(ze(),1),tet(),gV(),qet(),I(),h(),dtt(),RY=et()}));function ptt({onDone:e}){let[t,n]=(0,BY.useState)({state:`custom_platform`,baseUrl:process.env.ANTHROPIC_BASE_URL??``,apiKey:process.env.ANTHROPIC_AUTH_TOKEN??``,haikuModel:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL??``,sonnetModel:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL??``,opusModel:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL??``,activeField:`base_url`});return(0,BY.useEffect)(()=>{if(t.state===`about_to_retry`){let e=setTimeout(n,1e3,t.nextState);return()=>clearTimeout(e)}},[t]),Fe(`confirm:yes`,()=>{J(`tengu_oauth_success`,{}),e()},{context:`Confirmation`,isActive:t.state===`success`}),Fe(`confirm:yes`,()=>{t.state===`error`&&t.toRetry&&n({state:`about_to_retry`,nextState:t.toRetry})},{context:`Confirmation`,isActive:t.state===`error`&&!!t.toRetry}),(0,VY.jsx)(P,{flexDirection:`column`,gap:1,children:(0,VY.jsx)(P,{paddingLeft:1,flexDirection:`column`,gap:1,children:(0,VY.jsx)(mtt,{oauthStatus:t,setOAuthStatus:n,onDone:e})})})}function mtt({oauthStatus:e,setOAuthStatus:t,onDone:n}){switch(e.state){case`custom_platform`:{let r=[`base_url`,`api_key`,`haiku_model`,`sonnet_model`,`opus_model`],{activeField:i,baseUrl:a,apiKey:o,haikuModel:s,sonnetModel:c,opusModel:l}=e,u={base_url:a,api_key:o,haiku_model:s,sonnet_model:c,opus_model:l},[d,f]=(0,BY.useState)(()=>u[i]),[p,m]=(0,BY.useState)(()=>u[i].length),h=(0,BY.useCallback)((e,t,n)=>{let r={state:`custom_platform`,activeField:n??i,baseUrl:a,apiKey:o,haikuModel:s,sonnetModel:c,opusModel:l};switch(e){case`base_url`:return{...r,baseUrl:t};case`api_key`:return{...r,apiKey:t};case`haiku_model`:return{...r,haikuModel:t};case`sonnet_model`:return{...r,sonnetModel:t};case`opus_model`:return{...r,opusModel:t}}},[i,a,o,s,c,l]),g=(0,BY.useCallback)(()=>{let e={...u,[i]:d},r={};if(e.base_url){try{new URL(e.base_url)}catch{t({state:`error`,message:`Invalid base URL: please enter a full URL including protocol (e.g., https://api.example.com)`,toRetry:{state:`custom_platform`,baseUrl:``,apiKey:``,haikuModel:``,sonnetModel:``,opusModel:``,activeField:`base_url`}});return}r.ANTHROPIC_BASE_URL=e.base_url}e.api_key&&(r.ANTHROPIC_AUTH_TOKEN=e.api_key),e.haiku_model&&(r.ANTHROPIC_DEFAULT_HAIKU_MODEL=e.haiku_model),e.sonnet_model&&(r.ANTHROPIC_DEFAULT_SONNET_MODEL=e.sonnet_model),e.opus_model&&(r.ANTHROPIC_DEFAULT_OPUS_MODEL=e.opus_model);let{error:a}=li(`userSettings`,{modelType:`anthropic`,env:r});if(a)t({state:`error`,message:`Failed to save settings. Please try again.`,toRetry:{state:`custom_platform`,baseUrl:e.base_url??``,apiKey:e.api_key??``,haikuModel:e.haiku_model??``,sonnetModel:e.sonnet_model??``,opusModel:e.opus_model??``,activeField:`base_url`}});else{for(let[e,t]of Object.entries(r))process.env[e]=t;t({state:`success`}),n()}},[i,d,u,t,n]),_=(0,BY.useCallback)(()=>{let e=r.indexOf(i);if(e===r.length-1)t(h(i,d)),g();else{let n=r[e+1];t(h(i,d,n)),f(u[n]??``),m((u[n]??``).length)}},[i,d,h,g,u,t]);Fe(`tabs:next`,()=>{let e=r.indexOf(i);e<r.length-1&&(t(h(i,d,r[e+1])),f(u[r[e+1]]??``),m((u[r[e+1]]??``).length))},{context:`FormField`}),Fe(`tabs:previous`,()=>{let e=r.indexOf(i);e>0&&(t(h(i,d,r[e-1])),f(u[r[e-1]]??``),m((u[r[e-1]]??``).length))},{context:`FormField`}),Fe(`confirm:no`,()=>{n()},{context:`Confirmation`});let v=Xe().columns-20,y=(e,t,n)=>{let r=i===e,a=u[e];return(0,VY.jsxs)(P,{children:[(0,VY.jsx)(F,{backgroundColor:r?`suggestion`:void 0,color:r?`inverseText`:void 0,children:` ${t} `}),(0,VY.jsx)(F,{children:` `}),r?(0,VY.jsx)(LY,{value:d,onChange:f,onSubmit:_,cursorOffset:p,onChangeCursorOffset:m,columns:v,mask:n?.mask?`*`:void 0,focus:!0}):a?(0,VY.jsx)(F,{color:`success`,children:n?.mask?a.slice(0,8)+`·`.repeat(Math.max(0,a.length-8)):a}):null]})};return(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,VY.jsx)(F,{bold:!0,children:`Compatible API Setup`}),(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[y(`base_url`,`Base URL `),y(`api_key`,`API Key `,{mask:!0}),y(`haiku_model`,`Haiku `),y(`sonnet_model`,`Sonnet `),y(`opus_model`,`Opus `)]}),(0,VY.jsx)(F,{dimColor:!0,children:`↑↓/Tab to switch · Enter on last field to save · Esc to go back`})]})}case`about_to_retry`:return(0,VY.jsx)(P,{flexDirection:`column`,gap:1,children:(0,VY.jsx)(F,{color:`permission`,children:`Retrying…`})});case`success`:return(0,VY.jsx)(P,{flexDirection:`column`,children:(0,VY.jsxs)(F,{color:`success`,children:[`Login successful. Press `,(0,VY.jsx)(F,{bold:!0,children:`Enter`}),` to continue…`]})});case`error`:return(0,VY.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,VY.jsxs)(F,{color:`error`,children:[`OAuth error: `,e.message]}),e.toRetry&&(0,VY.jsx)(P,{marginTop:1,children:(0,VY.jsxs)(F,{color:`permission`,children:[`Press `,(0,VY.jsx)(F,{bold:!0,children:`Enter`}),` to retry.`]})})]});default:return null}}var BY,VY,htt=n((()=>{BY=r(ze(),1),Da(),eb(),I(),ub(),Vr(),zY(),VY=et()}));function gtt({imageId:e,backgroundColor:t,isSelected:n=!1}){let r=M6e(e),i=`[Image #${e}]`;if(r&&pe()){let e=Vl(r).href;return(0,HY.jsx)(Te,{url:e,fallback:(0,HY.jsx)(F,{backgroundColor:t,inverse:n,children:i}),children:(0,HY.jsx)(F,{backgroundColor:t,inverse:n,bold:n,children:i})})}return(0,HY.jsx)(F,{backgroundColor:t,inverse:n,children:i})}var HY,_tt=n((()=>{I(),gq(),HY=et()}));function UY({isFocused:e,isSelected:t,children:n,description:r,shouldShowDownArrow:i,shouldShowUpArrow:a,declareCursor:o}){return(0,vtt.jsx)(Re,{isFocused:e,isSelected:t,description:r,showScrollDown:i,showScrollUp:a,styled:!1,declareCursor:o,children:n})}var vtt,WY=n((()=>{I(),vtt=et()}));function GY({option:e,isFocused:t,isSelected:n,shouldShowDownArrow:r,shouldShowUpArrow:i,maxIndexWidth:a,index:o,inputValue:s,onInputChange:c,onSubmit:l,onExit:u,layout:d,children:f,showLabel:p=!1,onOpenEditor:m,resetCursorOnUpdate:h=!1,onImagePaste:g,pastedContents:_,onRemoveImage:v,imagesSelected:y,selectedImageIndex:b=0,onImagesSelectedChange:x,onSelectedImageIndexChange:S}){let C=_?Object.values(_).filter(e=>e.type===`image`):[],w=p||e.showLabelWithValue===!0,[T,E]=(0,KY.useState)(s.length),D=(0,KY.useRef)(!1);(0,KY.useEffect)(()=>{h&&t&&(D.current?D.current=!1:E(s.length))},[h,t,s]),Fe(`chat:externalEditor`,()=>{m?.(s,c)},{context:`Chat`,isActive:t&&!!m}),Fe(`chat:imagePaste`,()=>{g&&nY().then(e=>{e&&g(e.base64,e.mediaType,void 0,e.dimensions)})},{context:`Chat`,isActive:t&&!!g}),Fe(`attachments:remove`,()=>{C.length>0&&v&&v(C.at(-1).id)},{context:`Attachments`,isActive:t&&!y&&s===``&&C.length>0&&!!v}),be({"attachments:next":()=>{C.length>1&&S?.((b+1)%C.length)},"attachments:previous":()=>{C.length>1&&S?.((b-1+C.length)%C.length)},"attachments:remove":()=>{let e=C[b];e&&v&&(v(e.id),C.length<=1?x?.(!1):S?.(Math.min(b,C.length-2)))},"attachments:exit":()=>{x?.(!1)}},{context:`Attachments`,isActive:t&&!!y}),Je((e,t)=>{t.upArrow&&x?.(!1)},{isActive:t&&!!y}),(0,KY.useEffect)(()=>{!t&&y&&x?.(!1)},[t,y,x]);let O=d===`expanded`?a+3:a+4;return(0,qY.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,qY.jsx)(UY,{isFocused:t,isSelected:n,shouldShowDownArrow:r,shouldShowUpArrow:i,declareCursor:!1,children:(0,qY.jsxs)(P,{flexDirection:`row`,flexShrink:d===`compact`?0:void 0,children:[(0,qY.jsx)(F,{dimColor:!0,children:`${o}.`.padEnd(a+2)}),f,w?(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(F,{color:t?`suggestion`:void 0,children:e.label}),t?(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(F,{color:`suggestion`,children:e.labelValueSeparator??`, `}),(0,qY.jsx)(LY,{value:s,onChange:t=>{D.current=!0,c(t),e.onChange(t)},onSubmit:l,onExit:u,placeholder:e.placeholder,focus:!y,showCursor:!0,multiline:!0,cursorOffset:T,onChangeCursorOffset:E,columns:80,onImagePaste:g,onPaste:t=>{D.current=!0;let n=s.slice(0,T),r=s.slice(T),i=n+t+r;c(i),e.onChange(i),E(n.length+t.length)}})]}):s&&(0,qY.jsxs)(F,{children:[e.labelValueSeparator??`, `,s]})]}):t?(0,qY.jsx)(LY,{value:s,onChange:t=>{D.current=!0,c(t),e.onChange(t)},onSubmit:l,onExit:u,placeholder:e.placeholder||(typeof e.label==`string`?e.label:void 0),focus:!y,showCursor:!0,multiline:!0,cursorOffset:T,onChangeCursorOffset:E,columns:80,onImagePaste:g,onPaste:t=>{D.current=!0;let n=s.slice(0,T),r=s.slice(T),i=n+t+r;c(i),e.onChange(i),E(n.length+t.length)}}):(0,qY.jsx)(F,{color:s?void 0:`inactive`,children:s||e.placeholder||e.label})]})}),e.description&&(0,qY.jsx)(P,{paddingLeft:O,children:(0,qY.jsx)(F,{dimColor:e.dimDescription!==!1,color:n?`success`:t?`suggestion`:void 0,children:e.description})}),C.length>0&&(0,qY.jsxs)(P,{flexDirection:`row`,gap:1,paddingLeft:O,children:[C.map((e,t)=>(0,qY.jsx)(gtt,{imageId:e.id,isSelected:!!y&&t===b},e.id)),(0,qY.jsx)(P,{flexGrow:1,justifyContent:`flex-start`,flexDirection:`row`,children:(0,qY.jsx)(F,{dimColor:!0,children:y?(0,qY.jsxs)(je,{children:[C.length>1&&(0,qY.jsxs)(qY.Fragment,{children:[(0,qY.jsx)(hK,{action:`attachments:next`,context:`Attachments`,fallback:`→`,description:`next`}),(0,qY.jsx)(hK,{action:`attachments:previous`,context:`Attachments`,fallback:`←`,description:`prev`})]}),(0,qY.jsx)(hK,{action:`attachments:remove`,context:`Attachments`,fallback:`backspace`,description:`remove`}),(0,qY.jsx)(hK,{action:`attachments:exit`,context:`Attachments`,fallback:`esc`,description:`cancel`})]}):t?`(↓ to select)`:null})})]}),d===`expanded`&&(0,qY.jsx)(F,{children:` `})]})}var KY,qY,ytt=n((()=>{KY=r(ze(),1),I(),ub(),aY(),_tt(),gK(),zY(),WY(),qY=et()}));function JY(e,t=!0){let n=(0,YY.useContext)(fV)?.setState;(0,YY.useEffect)(()=>{if(!(!t||!n))return n(t=>{if(t.activeOverlays.has(e))return t;let n=new Set(t.activeOverlays);return n.add(e),{...t,activeOverlays:n}}),()=>{n(t=>{if(!t.activeOverlays.has(e))return t;let n=new Set(t.activeOverlays);return n.delete(e),{...t,activeOverlays:n}})}},[e,t,n]),(0,YY.useLayoutEffect)(()=>{if(t)return()=>Ae.get(process.stdout)?.invalidatePrevFrame()},[t])}function btt(){return sV(e=>e.activeOverlays.size>0)}function xtt(){return sV(e=>{for(let t of e.activeOverlays)if(!Stt.has(t))return!0;return!1})}var YY,Stt,XY=n((()=>{YY=r(ze(),1),I(),mV(),Stt=new Set([`autocomplete`])})),Ctt,wtt=n((()=>{b(),Ctt=class extends Map{constructor(e){let t=[],n,r,i,a=0;for(let o of e){let e={label:o.label,value:o.value,description:o.description,previous:i,next:void 0,index:a};i&&(i.next=e),n||(n=e),r=e,t.push([o.value,e]),a++,i=e}super(t),x(this,`first`,void 0),x(this,`last`,void 0),this.first=n,this.last=r}}}));function Ttt({visibleOptionCount:e=5,options:t,initialFocusValue:n,onFocus:r,focusValue:i}){let[a,o]=(0,ZY.useReducer)(Ett,{visibleOptionCount:e,options:t,initialFocusValue:i||n},QY),s=(0,ZY.useRef)(r);s.current=r;let[c,l]=(0,ZY.useState)(t);t!==c&&!hue(t,c)&&(o({type:`reset`,state:QY({visibleOptionCount:e,options:t,initialFocusValue:i??a.focusedValue??n,currentViewport:{visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex}})}),l(t));let u=(0,ZY.useCallback)(()=>{o({type:`focus-next-option`})},[]),d=(0,ZY.useCallback)(()=>{o({type:`focus-previous-option`})},[]),f=(0,ZY.useCallback)(()=>{o({type:`focus-next-page`})},[]),p=(0,ZY.useCallback)(()=>{o({type:`focus-previous-page`})},[]),m=(0,ZY.useCallback)(e=>{e!==void 0&&o({type:`set-focus`,value:e})},[]),h=(0,ZY.useMemo)(()=>t.map((e,t)=>({...e,index:t})).slice(a.visibleFromIndex,a.visibleToIndex),[t,a.visibleFromIndex,a.visibleToIndex]),g=(0,ZY.useMemo)(()=>{if(a.focusedValue!==void 0)return t.some(e=>e.value===a.focusedValue)?a.focusedValue:t[0]?.value},[a.focusedValue,t]),_=(0,ZY.useMemo)(()=>t.find(e=>e.value===g)?.type===`input`,[g,t]);return(0,ZY.useEffect)(()=>{g!==void 0&&s.current?.(g)},[g]),(0,ZY.useEffect)(()=>{i!==void 0&&o({type:`set-focus`,value:i})},[i]),{focusedValue:g,focusedIndex:(0,ZY.useMemo)(()=>{if(g===void 0)return 0;let e=t.findIndex(e=>e.value===g);return e>=0?e+1:0},[g,t]),visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex,visibleOptions:h,isInInput:_??!1,focusNextOption:u,focusPreviousOption:d,focusNextPage:f,focusPreviousPage:p,focusOption:m,options:t}}var ZY,Ett,QY,Dtt=n((()=>{ZY=r(ze(),1),wtt(),Ett=(e,t)=>{switch(t.type){case`focus-next-option`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=t.next||e.optionMap.first;if(!n)return e;if(!t.next&&n===e.optionMap.first)return{...e,focusedValue:n.value,visibleFromIndex:0,visibleToIndex:e.visibleOptionCount};if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let r=Math.min(e.optionMap.size,e.visibleToIndex+1),i=r-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:i,visibleToIndex:r}}case`focus-previous-option`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=t.previous||e.optionMap.last;if(!n)return e;if(!t.previous&&n===e.optionMap.last){let t=e.optionMap.size,r=Math.max(0,t-e.visibleOptionCount);return{...e,focusedValue:n.value,visibleFromIndex:r,visibleToIndex:t}}if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let r=Math.max(0,e.visibleFromIndex-1),i=r+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:r,visibleToIndex:i}}case`focus-next-page`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=Math.min(e.optionMap.size-1,t.index+e.visibleOptionCount),r=e.optionMap.first;for(;r&&r.index<n&&r.next;)r=r.next;if(!r)return e;let i=Math.min(e.optionMap.size,r.index+1),a=Math.max(0,i-e.visibleOptionCount);return{...e,focusedValue:r.value,visibleFromIndex:a,visibleToIndex:i}}case`focus-previous-page`:{if(e.focusedValue===void 0)return e;let t=e.optionMap.get(e.focusedValue);if(!t)return e;let n=Math.max(0,t.index-e.visibleOptionCount),r=e.optionMap.first;for(;r&&r.index<n&&r.next;)r=r.next;if(!r)return e;let i=Math.max(0,r.index),a=Math.min(e.optionMap.size,i+e.visibleOptionCount);return{...e,focusedValue:r.value,visibleFromIndex:i,visibleToIndex:a}}case`reset`:return t.state;case`set-focus`:{if(e.focusedValue===t.value)return e;let n=e.optionMap.get(t.value);if(!n)return e;if(n.index>=e.visibleFromIndex&&n.index<e.visibleToIndex)return{...e,focusedValue:t.value};let r,i;return n.index<e.visibleFromIndex?(r=n.index,i=Math.min(e.optionMap.size,r+e.visibleOptionCount)):(i=Math.min(e.optionMap.size,n.index+1),r=Math.max(0,i-e.visibleOptionCount)),{...e,focusedValue:t.value,visibleFromIndex:r,visibleToIndex:i}}}},QY=({visibleOptionCount:e,options:t,initialFocusValue:n,currentViewport:r})=>{let i=typeof e==`number`?Math.min(e,t.length):t.length,a=new Ctt(t),o=n!==void 0&&a.get(n),s=o?n:a.first?.value,c=0,l=i;if(o){let e=o.index;r?e>=r.visibleFromIndex&&e<r.visibleToIndex?(c=r.visibleFromIndex,l=Math.min(a.size,r.visibleToIndex)):e<r.visibleFromIndex?(c=e,l=Math.min(a.size,c+i)):(l=Math.min(a.size,e+1),c=Math.max(0,l-i)):e>=i&&(l=Math.min(a.size,e+1),c=Math.max(0,l-i)),c=Math.max(0,Math.min(c,a.size-1)),l=Math.min(a.size,Math.max(i,l))}return{optionMap:a,visibleOptionCount:i,focusedValue:s,visibleFromIndex:c,visibleToIndex:l}}}));function Ott({isDisabled:e=!1,visibleOptionCount:t=5,options:n,defaultValue:r=[],onChange:i,onCancel:a,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,hideIndexes:p=!1}){let[m,h]=(0,$Y.useState)(r),[g,_]=(0,$Y.useState)(!1),[v,y]=(0,$Y.useState)(n);n!==v&&!hue(n,v)&&(h(r),y(n));let[b,x]=(0,$Y.useState)(()=>{let e=new Map;return n.forEach(t=>{t.type===`input`&&t.initialValue&&e.set(t.value,t.initialValue)}),e}),S=(0,$Y.useCallback)(e=>{let t=typeof e==`function`?e(m):e;h(t),i?.(t)},[m,i]),C=Ttt({visibleOptionCount:t,options:n,initialFocusValue:f?n[n.length-1]?.value:void 0,onFocus:o,focusValue:s});JY(`multi-select`,void 0);let w=(0,$Y.useCallback)((e,t)=>{x(n=>{let r=new Map(n);return r.set(e,t),r});let r=n.find(t=>t.value===e);r&&r.type===`input`&&r.onChange(t),S(n=>t?n.includes(e)?n:[...n,e]:n.filter(t=>t!==e))},[n,S]);return Je((e,t,r)=>{let i=Xa(e),o=n.find(e=>e.value===C.focusedValue)?.type===`input`;if(o&&!(t.upArrow||t.downArrow||t.escape||t.tab||t.return||t.ctrl&&(e===`n`||e===`p`||t.return)))return;let s=n[n.length-1]?.value;if(t.tab&&!t.shift){c&&l&&C.focusedValue===s&&!g?_(!0):g||C.focusNextOption();return}if(t.tab&&t.shift){c&&l&&g?(_(!1),C.focusOption(s)):C.focusPreviousOption();return}if(t.downArrow||t.ctrl&&e===`n`||!t.ctrl&&!t.shift&&e===`j`){g&&u?u():c&&l&&C.focusedValue===s&&!g?_(!0):!c&&u&&C.focusedValue===s?u():g||C.focusNextOption();return}if(t.upArrow||t.ctrl&&e===`p`||!t.ctrl&&!t.shift&&e===`k`){c&&l&&g?(_(!1),C.focusOption(s)):d&&C.focusedValue===n[0]?.value?d():C.focusPreviousOption();return}if(t.pageDown){C.focusNextPage();return}if(t.pageUp){C.focusPreviousPage();return}if(t.return||Ga(e)===` `){if(t.ctrl&&t.return&&o&&l){l(m);return}if(g&&l){l(m);return}if(t.return&&!c&&l){l(m);return}if(C.focusedValue!==void 0){let e=m.includes(C.focusedValue)?m.filter(e=>e!==C.focusedValue):[...m,C.focusedValue];S(e)}return}if(!p&&/^[0-9]+$/.test(i)){let e=parseInt(i,10)-1;if(e>=0&&e<n.length){let t=n[e].value,r=m.includes(t)?m.filter(e=>e!==t):[...m,t];S(r)}return}t.escape&&(a(),r.stopImmediatePropagation())},{isActive:!e}),{...C,selectedValues:m,inputValues:b,isSubmitFocused:g,updateInputValue:w,onCancel:a}}var $Y,ktt=n((()=>{$Y=r(ze(),1),XY(),I(),Ja(),Dtt()}));function Att({isDisabled:e=!1,visibleOptionCount:t=5,options:n,defaultValue:r=[],onCancel:i,onChange:a,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,onOpenEditor:p,hideIndexes:m=!1,onImagePaste:h,pastedContents:g,onRemoveImage:_}){let v=Ott({isDisabled:e,visibleOptionCount:t,options:n,defaultValue:r,onChange:a,onCancel:i,onFocus:o,focusValue:s,submitButtonText:c,onSubmit:l,onDownFromLastItem:u,onUpFromFirstItem:d,initialFocusLast:f,hideIndexes:m}),y=n.length.toString().length;return(0,eX.jsxs)(P,{flexDirection:`column`,children:[(0,eX.jsx)(P,{flexDirection:`column`,children:v.visibleOptions.map((t,r)=>{let a=!e&&v.focusedValue===t.value&&!v.isSubmitFocused,o=v.selectedValues.includes(t.value),s=t.index===v.visibleFromIndex,c=t.index===v.visibleToIndex-1,l=v.visibleToIndex<n.length,u=v.visibleFromIndex>0,d=v.visibleFromIndex+r+1;if(t.type===`input`){let e=v.inputValues.get(t.value)||``;return(0,eX.jsx)(P,{gap:1,children:(0,eX.jsx)(GY,{option:t,isFocused:a,isSelected:!1,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&s,maxIndexWidth:y,index:d,inputValue:e,onInputChange:e=>{v.updateInputValue(t.value,e)},onSubmit:()=>{},onExit:()=>{i()},layout:`compact`,onOpenEditor:p,onImagePaste:h,pastedContents:g,onRemoveImage:_,children:(0,eX.jsxs)(F,{color:o?`success`:void 0,children:[`[`,o?ie.tick:` `,`] `]})})},String(t.value))}return(0,eX.jsx)(P,{gap:1,children:(0,eX.jsxs)(UY,{isFocused:a,isSelected:!1,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&s,description:t.description,children:[!m&&(0,eX.jsx)(F,{dimColor:!0,children:`${d}.`.padEnd(y)}),(0,eX.jsxs)(F,{color:o?`success`:void 0,children:[`[`,o?ie.tick:` `,`]`]}),(0,eX.jsx)(F,{color:a?`suggestion`:void 0,children:t.label})]})},String(t.value))})}),c&&l&&(0,eX.jsxs)(P,{marginTop:0,gap:1,children:[v.isSubmitFocused?(0,eX.jsx)(F,{color:`suggestion`,children:ie.pointer}):(0,eX.jsx)(F,{children:` `}),(0,eX.jsx)(P,{marginLeft:3,children:(0,eX.jsx)(F,{color:v.isSubmitFocused?`suggestion`:void 0,bold:!0,children:c})})]})]})}var eX,jtt=n((()=>{ne(),I(),ytt(),WY(),ktt(),eX=et()})),tX,Mtt,Ntt=n((()=>{tX=r(ze(),1),XY(),I(),ub(),Ja(),Mtt=({isDisabled:e=!1,disableSelection:t=!1,state:n,options:r,isMultiSelect:i=!1,onUpFromFirstItem:a,onDownFromLastItem:o,onInputModeToggle:s,inputValues:c,imagesSelected:l=!1,onEnterImageSelection:u})=>{JY(`select`,!!n.onCancel);let d=(0,tX.useMemo)(()=>r.find(e=>e.value===n.focusedValue)?.type===`input`,[r,n.focusedValue]);be((0,tX.useMemo)(()=>{let e={};return d||(e[`select:next`]=()=>{if(o){let e=r[r.length-1];if(e&&n.focusedValue===e.value){o();return}}n.focusNextOption()},e[`select:previous`]=()=>{if(a&&n.visibleFromIndex===0){let e=r[0];if(e&&n.focusedValue===e.value){a();return}}n.focusPreviousOption()},e[`select:accept`]=()=>{t!==!0&&n.focusedValue!==void 0&&r.find(e=>e.value===n.focusedValue)?.disabled!==!0&&(n.selectFocusedOption?.(),n.onChange?.(n.focusedValue))}),n.onCancel&&(e[`select:cancel`]=()=>{n.onCancel()}),e},[r,n,o,a,d,t]),{context:`Select`,isActive:!e}),Je((e,d,f)=>{let p=Xa(e),m=r.find(e=>e.value===n.focusedValue),h=m?.type===`input`;if(d.tab&&s&&n.focusedValue!==void 0){s(n.focusedValue);return}if(h){if(l)return;if(d.downArrow&&u?.()){f.stopImmediatePropagation();return}if(d.downArrow||d.ctrl&&e===`n`){if(o){let e=r[r.length-1];if(e&&n.focusedValue===e.value){o(),f.stopImmediatePropagation();return}}n.focusNextOption(),f.stopImmediatePropagation();return}if(d.upArrow||d.ctrl&&e===`p`){if(a&&n.visibleFromIndex===0){let e=r[0];if(e&&n.focusedValue===e.value){a(),f.stopImmediatePropagation();return}}n.focusPreviousOption(),f.stopImmediatePropagation();return}return}if(d.pageDown&&n.focusNextPage(),d.pageUp&&n.focusPreviousPage(),t!==!0&&(i&&Ga(e)===` `&&n.focusedValue!==void 0&&m?.disabled!==!0&&(n.selectFocusedOption?.(),n.onChange?.(n.focusedValue)),t!==`numeric`&&/^[0-9]+$/.test(p))){let e=parseInt(p,10)-1;if(e>=0&&e<n.options.length){let t=n.options[e];if(t.disabled===!0)return;if(t.type===`input`){if((c?.get(t.value)??``).trim()){n.onChange?.(t.value);return}if(t.allowEmptySubmitToCancel){n.onChange?.(t.value);return}n.focusOption(t.value);return}n.onChange?.(t.value);return}}},{isActive:!e})}}));function Ptt({visibleOptionCount:e=5,options:t,defaultValue:n,onChange:r,onCancel:i,onFocus:a,focusValue:o}){let[s,c]=(0,nX.useState)(n),l=Ttt({visibleOptionCount:e,options:t,initialFocusValue:void 0,onFocus:a,focusValue:o}),u=(0,nX.useCallback)(()=>{c(l.focusedValue)},[l.focusedValue]);return{...l,value:s,selectFocusedOption:u,onChange:r,onCancel:i}}var nX,Ftt=n((()=>{nX=r(ze(),1),Dtt()}));function rX(e){return typeof e==`string`?e:typeof e==`number`?String(e):e?Array.isArray(e)?e.map(rX).join(``):aX.isValidElement(e)?rX(e.props.children):``:``}function iX({isDisabled:e=!1,hideIndexes:t=!1,visibleOptionCount:n=5,highlightText:r,options:i,defaultValue:a,onCancel:o,onChange:s,onFocus:c,defaultFocusValue:l,layout:u=`compact`,disableSelection:d=!1,inlineDescriptions:f=!1,onUpFromFirstItem:p,onDownFromLastItem:m,onInputModeToggle:h,onOpenEditor:g,onImagePaste:_,pastedContents:v,onRemoveImage:y}){let[b,x]=(0,aX.useState)(!1),[S,C]=(0,aX.useState)(0),[w,T]=(0,aX.useState)(()=>{let e=new Map;return i.forEach(t=>{t.type===`input`&&t.initialValue&&e.set(t.value,t.initialValue)}),e}),E=(0,aX.useRef)(new Map);(0,aX.useEffect)(()=>{for(let e of i)if(e.type===`input`&&e.initialValue!==void 0){let t=E.current.get(e.value)??``,n=w.get(e.value)??``,r=e.initialValue;r!==t&&n===t&&T(t=>{let n=new Map(t);return n.set(e.value,r),n}),E.current.set(e.value,r)}},[i,w]);let D=Ptt({visibleOptionCount:n,options:i,defaultValue:a,onChange:s,onCancel:o,onFocus:c,focusValue:l});Mtt({isDisabled:e,disableSelection:d||(t?`numeric`:!1),state:D,options:i,isMultiSelect:!1,onUpFromFirstItem:p,onDownFromLastItem:m,onInputModeToggle:h,inputValues:w,imagesSelected:b,onEnterImageSelection:()=>{if(v&&Object.values(v).some(e=>e.type===`image`)){let e=hr(Object.values(v),e=>e.type===`image`);return x(!0),C(e-1),!0}return!1}});let O={container:()=>({flexDirection:`column`}),highlightedText:()=>({bold:!0})};if(u===`expanded`){let t=D.options.length.toString().length;return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((n,a)=>{let c=n.index===D.visibleFromIndex,l=n.index===D.visibleToIndex-1,u=D.visibleToIndex<i.length,d=D.visibleFromIndex>0,p=D.visibleFromIndex+a+1,m=!e&&D.focusedValue===n.value,h=D.value===n.value;if(n.type===`input`){let e=w.has(n.value)?w.get(n.value):n.initialValue||``;return(0,oX.jsx)(GY,{option:n,isFocused:m,isSelected:h,shouldShowDownArrow:u&&l,shouldShowUpArrow:d&&c,maxIndexWidth:t,index:p,inputValue:e,onInputChange:e=>{T(t=>{let r=new Map(t);return r.set(n.value,e),r})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||n.allowEmptySubmitToCancel?s?.(n.value):o?.()},onExit:o,layout:`expanded`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:n.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(n.value))}let E=n.label;if(typeof n.label==`string`&&r&&n.label.includes(r)){let e=n.label,t=e.indexOf(r);E=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let k=n.disabled===!0,A=k?void 0:h?`success`:m?`suggestion`:void 0;return(0,oX.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,oX.jsx)(UY,{isFocused:m,isSelected:h,shouldShowDownArrow:u&&l,shouldShowUpArrow:d&&c,children:(0,oX.jsx)(F,{dimColor:k,color:A,children:E})}),n.description&&(0,oX.jsx)(P,{paddingLeft:2,children:(0,oX.jsx)(F,{dimColor:k||n.dimDescription!==!1,color:A,children:(0,oX.jsx)(_e,{children:n.description})})}),(0,oX.jsx)(F,{children:` `})]},String(n.value))})})}if(u===`compact-vertical`){let n=t?0:D.options.length.toString().length;return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((a,c)=>{let l=a.index===D.visibleFromIndex,u=a.index===D.visibleToIndex-1,d=D.visibleToIndex<i.length,p=D.visibleFromIndex>0,m=D.visibleFromIndex+c+1,h=!e&&D.focusedValue===a.value,E=D.value===a.value;if(a.type===`input`){let e=w.has(a.value)?w.get(a.value):a.initialValue||``;return(0,oX.jsx)(GY,{option:a,isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,maxIndexWidth:n,index:m,inputValue:e,onInputChange:e=>{T(t=>{let n=new Map(t);return n.set(a.value,e),n})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||a.allowEmptySubmitToCancel?s?.(a.value):o?.()},onExit:o,layout:`compact`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:a.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(a.value))}let k=a.label;if(typeof a.label==`string`&&r&&a.label.includes(r)){let e=a.label,t=e.indexOf(r);k=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let A=a.disabled===!0;return(0,oX.jsxs)(P,{flexDirection:`column`,flexShrink:0,children:[(0,oX.jsxs)(UY,{isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${m}.`.padEnd(n+1)}),(0,oX.jsx)(F,{dimColor:A,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:k})]}),a.description&&(0,oX.jsx)(P,{paddingLeft:t?4:n+4,children:(0,oX.jsx)(F,{dimColor:A||a.dimDescription!==!1,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:a.description})})})]},String(a.value))})})}let k=t?0:D.options.length.toString().length,A=D.visibleOptions.some(e=>e.type===`input`),ee=!f&&!A&&D.visibleOptions.some(e=>e.description),te=D.visibleOptions.map((t,n)=>{let a=t.index===D.visibleFromIndex,o=t.index===D.visibleToIndex-1,s=D.visibleToIndex<i.length,c=D.visibleFromIndex>0,l=D.visibleFromIndex+n+1,u=!e&&D.focusedValue===t.value,d=D.value===t.value,f=t.disabled===!0,p=t.label;if(typeof t.label==`string`&&r&&t.label.includes(r)){let e=t.label,n=e.indexOf(r);p=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,n),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(n+r.length)]})}return{option:t,index:l,label:p,isFocused:u,isSelected:d,isOptionDisabled:f,shouldShowDownArrow:s&&o,shouldShowUpArrow:c&&a}});if(ee){let e=Math.max(...te.map(e=>{if(e.option.type===`input`)return 0;let n=rX(e.option.label),r=t?0:k+2,i=e.isSelected?2:0;return 2+r+ye(n)+i}));return(0,oX.jsx)(P,{...O.container(),children:te.map(n=>{if(n.option.type===`input`)return null;let r=rX(n.option.label),i=t?0:k+2,a=n.isSelected?2:0,o=2+i+ye(r)+a,s=e-o;return(0,oX.jsxs)(Itt,{isFocused:n.isFocused,children:[(0,oX.jsxs)(P,{flexDirection:`row`,flexShrink:0,children:[n.isFocused?(0,oX.jsx)(F,{color:`suggestion`,children:ie.pointer}):n.shouldShowDownArrow?(0,oX.jsx)(F,{dimColor:!0,children:ie.arrowDown}):n.shouldShowUpArrow?(0,oX.jsx)(F,{dimColor:!0,children:ie.arrowUp}):(0,oX.jsx)(F,{children:` `}),(0,oX.jsx)(F,{children:` `}),(0,oX.jsxs)(F,{dimColor:n.isOptionDisabled,color:n.isOptionDisabled?void 0:n.isSelected?`success`:n.isFocused?`suggestion`:void 0,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${n.index}.`.padEnd(k+2)}),n.label]}),n.isSelected&&(0,oX.jsxs)(F,{color:`success`,children:[` `,ie.tick]}),s>0&&(0,oX.jsx)(F,{children:` `.repeat(s)})]}),(0,oX.jsx)(P,{flexGrow:1,marginLeft:2,children:(0,oX.jsx)(F,{wrap:`wrap`,dimColor:n.isOptionDisabled||n.option.dimDescription!==!1,color:n.isOptionDisabled?void 0:n.isSelected?`success`:n.isFocused?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:n.option.description||` `})})})]},String(n.option.value))})})}return(0,oX.jsx)(P,{...O.container(),children:D.visibleOptions.map((n,a)=>{if(n.type===`input`){let t=w.has(n.value)?w.get(n.value):n.initialValue||``,r=n.index===D.visibleFromIndex,c=n.index===D.visibleToIndex-1,l=D.visibleToIndex<i.length,u=D.visibleFromIndex>0,d=D.visibleFromIndex+a+1;return(0,oX.jsx)(GY,{option:n,isFocused:!e&&D.focusedValue===n.value,isSelected:D.value===n.value,shouldShowDownArrow:l&&c,shouldShowUpArrow:u&&r,maxIndexWidth:k,index:d,inputValue:t,onInputChange:e=>{T(t=>{let r=new Map(t);return r.set(n.value,e),r})},onSubmit:e=>{let t=v&&Object.values(v).some(e=>e.type===`image`);e.trim()||t||n.allowEmptySubmitToCancel?s?.(n.value):o?.()},onExit:o,layout:`compact`,showLabel:f,onOpenEditor:g,resetCursorOnUpdate:n.resetCursorOnUpdate,onImagePaste:_,pastedContents:v,onRemoveImage:y,imagesSelected:b,selectedImageIndex:S,onImagesSelectedChange:x,onSelectedImageIndexChange:C},String(n.value))}let c=n.label;if(typeof n.label==`string`&&r&&n.label.includes(r)){let e=n.label,t=e.indexOf(r);c=(0,oX.jsxs)(oX.Fragment,{children:[e.slice(0,t),(0,oX.jsx)(F,{...O.highlightedText(),children:r}),e.slice(t+r.length)]})}let l=n.index===D.visibleFromIndex,u=n.index===D.visibleToIndex-1,d=D.visibleToIndex<i.length,p=D.visibleFromIndex>0,m=D.visibleFromIndex+a+1,h=!e&&D.focusedValue===n.value,E=D.value===n.value,A=n.disabled===!0;return(0,oX.jsxs)(UY,{isFocused:h,isSelected:E,shouldShowDownArrow:d&&u,shouldShowUpArrow:p&&l,children:[(0,oX.jsxs)(P,{flexDirection:`row`,flexShrink:0,children:[!t&&(0,oX.jsx)(F,{dimColor:!0,children:`${m}.`.padEnd(k+2)}),(0,oX.jsxs)(F,{dimColor:A,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:[c,f&&n.description&&(0,oX.jsxs)(F,{dimColor:A||n.dimDescription!==!1,children:[` `,n.description]})]})]}),!f&&n.description&&(0,oX.jsx)(P,{flexShrink:99,marginLeft:2,children:(0,oX.jsx)(F,{wrap:`wrap-trim`,dimColor:A||n.dimDescription!==!1,color:A?void 0:E?`success`:h?`suggestion`:void 0,children:(0,oX.jsx)(_e,{children:n.description})})})]},String(n.value))})})}function Itt({isFocused:e,children:t}){return(0,oX.jsx)(P,{ref:ve({line:0,column:0,active:e}),flexDirection:`row`,children:t})}var aX,oX,Ltt=n((()=>{ne(),aX=r(ze(),1),I(),Cr(),ytt(),WY(),Ntt(),Ftt(),oX=et()})),sX=n((()=>{jtt(),Ltt()})),cX,lX,Rtt=n((()=>{Wt(),b(),cX=class e{constructor(e){x(this,`activeOperations`,new Set),x(this,`lastUserActivityTime`,0),x(this,`lastCLIRecordedTime`,void 0),x(this,`isCLIActive`,!1),x(this,`USER_ACTIVITY_TIMEOUT_MS`,5e3),x(this,`getNow`,void 0),x(this,`getActiveTimeCounter`,void 0),this.getNow=e?.getNow??(()=>Date.now()),this.getActiveTimeCounter=e?.getActiveTimeCounter??qte,this.lastCLIRecordedTime=this.getNow()}static getInstance(){return e.instance||(e.instance=new e),e.instance}static resetInstance(){e.instance=null}static createInstance(t){return e.instance=new e(t),e.instance}recordUserActivity(){if(!this.isCLIActive&&this.lastUserActivityTime!==0){let e=(this.getNow()-this.lastUserActivityTime)/1e3;if(e>0){let t=this.getActiveTimeCounter();t&&e<this.USER_ACTIVITY_TIMEOUT_MS/1e3&&t.add(e,{type:`user`})}}this.lastUserActivityTime=this.getNow()}startCLIActivity(e){this.activeOperations.has(e)&&this.endCLIActivity(e);let t=this.activeOperations.size===0;this.activeOperations.add(e),t&&(this.isCLIActive=!0,this.lastCLIRecordedTime=this.getNow())}endCLIActivity(e){if(this.activeOperations.delete(e),this.activeOperations.size===0){let e=this.getNow(),t=(e-this.lastCLIRecordedTime)/1e3;if(t>0){let e=this.getActiveTimeCounter();e&&e.add(t,{type:`cli`})}this.lastCLIRecordedTime=e,this.isCLIActive=!1}}async trackOperation(e,t){this.startCLIActivity(e);try{return await t()}finally{this.endCLIActivity(e)}}getActivityStates(){return{isUserActive:(this.getNow()-this.lastUserActivityTime)/1e3<this.USER_ACTIVITY_TIMEOUT_MS/1e3,isCLIActive:this.isCLIActive,activeOperationCount:this.activeOperations.size}}},x(cX,`instance`,null),lX=cX.getInstance()}));function ztt(){let e=Xr().spinnerVerbs;return e?e.mode===`replace`?e.verbs.length>0?e.verbs:uX:[...uX,...e.verbs]:uX}var uX,Btt=n((()=>{Vr(),uX=`Accomplishing.Actioning.Actualizing.Architecting.Baking.Beaming.Beboppin'.Befuddling.Billowing.Blanching.Bloviating.Boogieing.Boondoggling.Booping.Bootstrapping.Brewing.Bunning.Burrowing.Calculating.Canoodling.Caramelizing.Cascading.Catapulting.Cerebrating.Channeling.Channelling.Choreographing.Churning.Clauding.Coalescing.Cogitating.Combobulating.Composing.Computing.Concocting.Considering.Contemplating.Cooking.Crafting.Creating.Crunching.Crystallizing.Cultivating.Deciphering.Deliberating.Determining.Dilly-dallying.Discombobulating.Doing.Doodling.Drizzling.Ebbing.Effecting.Elucidating.Embellishing.Enchanting.Envisioning.Evaporating.Fermenting.Fiddle-faddling.Finagling.Flambéing.Flibbertigibbeting.Flowing.Flummoxing.Fluttering.Forging.Forming.Frolicking.Frosting.Gallivanting.Galloping.Garnishing.Generating.Gesticulating.Germinating.Gitifying.Grooving.Gusting.Harmonizing.Hashing.Hatching.Herding.Honking.Hullaballooing.Hyperspacing.Ideating.Imagining.Improvising.Incubating.Inferring.Infusing.Ionizing.Jitterbugging.Julienning.Kneading.Leavening.Levitating.Lollygagging.Manifesting.Marinating.Meandering.Metamorphosing.Misting.Moonwalking.Moseying.Mulling.Mustering.Musing.Nebulizing.Nesting.Newspapering.Noodling.Nucleating.Orbiting.Orchestrating.Osmosing.Perambulating.Percolating.Perusing.Philosophising.Photosynthesizing.Pollinating.Pondering.Pontificating.Pouncing.Precipitating.Prestidigitating.Processing.Proofing.Propagating.Puttering.Puzzling.Quantumizing.Razzle-dazzling.Razzmatazzing.Recombobulating.Reticulating.Roosting.Ruminating.Sautéing.Scampering.Schlepping.Scurrying.Seasoning.Shenaniganing.Shimmying.Simmering.Skedaddling.Sketching.Slithering.Smooshing.Sock-hopping.Spelunking.Spinning.Sprouting.Stewing.Sublimating.Swirling.Swooping.Symbioting.Synthesizing.Tempering.Thinking.Thundering.Tinkering.Tomfoolering.Topsy-turvying.Transfiguring.Transmuting.Twisting.Undulating.Unfurling.Unravelling.Vibing.Waddling.Wandering.Warping.Whatchamacalliting.Whirlpooling.Whirring.Whisking.Wibbling.Working.Wrangling.Zesting.Zigzagging`.split(`.`)}));function dX(e,t){let n=parseInt(e.id,10),r=parseInt(t.id,10);return!isNaN(n)&&!isNaN(r)?n-r:e.id.localeCompare(t.id)}function Vtt({tasks:e,isStandalone:t=!1}){let[,n]=fX.useState(0),{rows:r,columns:i}=Xe(),a=fX.useRef(new Map),o=fX.useRef(null);o.current===null&&(o.current=new Set(e.filter(e=>e.status===`completed`).map(e=>e.id)));let s=r<=10?0:Math.min(10,Math.max(3,r-14)),c=new Set(e.filter(e=>e.status===`completed`).map(e=>e.id)),l=Date.now();for(let e of c)o.current.has(e)||a.current.set(e,l);for(let e of a.current.keys())c.has(e)||a.current.delete(e);if(o.current=c,fX.useEffect(()=>{if(a.current.size===0)return;let e=Date.now(),t=1/0;for(let n of a.current.values()){let r=n+mX;r>e&&r<t&&(t=r)}if(t===1/0)return;let r=setTimeout(e=>e(e=>e+1),t-e,n);return()=>clearTimeout(r)},[e]),!ax()||e.length===0)return null;let u=hr(e,e=>e.status===`completed`),d=hr(e,e=>e.status===`pending`),f=e.length-u-d,p=new Set(e.filter(e=>e.status!==`completed`).map(e=>e.id)),m=e.length>s,h,g;if(m){let t=[],n=[];for(let r of e.filter(e=>e.status===`completed`)){let e=a.current.get(r.id);e&&l-e<mX?t.push(r):n.push(r)}t.sort(dX),n.sort(dX);let r=e.filter(e=>e.status===`in_progress`).sort(dX),i=e.filter(e=>e.status===`pending`).sort((e,t)=>{let n=e.blockedBy.some(e=>p.has(e));return n===t.blockedBy.some(e=>p.has(e))?dX(e,t):n?1:-1}),o=[...t,...r,...i,...n];h=o.slice(0,s),g=o.slice(s)}else h=[...e].sort(dX),g=[];let _=``;if(g.length>0){let e=[],t=hr(g,e=>e.status===`pending`),n=hr(g,e=>e.status===`in_progress`),r=hr(g,e=>e.status===`completed`);n>0&&e.push(`${n} in progress`),t>0&&e.push(`${t} pending`),r>0&&e.push(`${r} completed`),_=` … +${e.join(`, `)}`}let v=(0,pX.jsxs)(pX.Fragment,{children:[h.map(e=>(0,pX.jsx)(Utt,{task:e,openBlockers:e.blockedBy.filter(e=>p.has(e)),columns:i},e.id)),s>0&&_&&(0,pX.jsx)(F,{dimColor:!0,children:_})]});return t?(0,pX.jsxs)(P,{flexDirection:`column`,marginTop:1,marginLeft:2,children:[(0,pX.jsx)(P,{children:(0,pX.jsxs)(F,{dimColor:!0,children:[(0,pX.jsx)(F,{bold:!0,children:e.length}),` tasks (`,(0,pX.jsx)(F,{bold:!0,children:u}),` done, `,f>0&&(0,pX.jsxs)(pX.Fragment,{children:[(0,pX.jsx)(F,{bold:!0,children:f}),` in progress, `]}),(0,pX.jsx)(F,{bold:!0,children:d}),` open)`]})}),v]}):(0,pX.jsx)(P,{flexDirection:`column`,children:v})}function Htt(e){switch(e){case`completed`:return{icon:ie.tick,color:`success`};case`in_progress`:return{icon:ie.squareSmallFilled,color:`claude`};case`pending`:return{icon:ie.squareSmall,color:void 0}}}function Utt({task:e,openBlockers:t,columns:n}){let r=e.status===`completed`,i=e.status===`in_progress`,a=t.length>0,{icon:o,color:s}=Htt(e.status),c=Math.max(15,n-15),l=Aa(e.subject,c);return(0,pX.jsx)(P,{flexDirection:`column`,children:(0,pX.jsxs)(P,{children:[(0,pX.jsxs)(F,{color:s,children:[o,` `]}),(0,pX.jsx)(F,{bold:i,strikethrough:r,dimColor:r||a,children:l}),a&&(0,pX.jsxs)(F,{dimColor:!0,children:[` `,ie.pointerSmall,` blocked by`,` `,[...t].sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>`#${e}`).join(`, `)]})]})})}var fX,pX,mX,Wtt=n((()=>{ne(),fX=r(ze(),1),eb(),I(),Cr(),Ba(),hx(),pX=et(),mX=3e4}));function Gtt(){D(TX,this).emit()}function Ktt(e){if(!(e===D(bX,this)&&D(yX,this)!==null)){D(yX,this)?.close(),k(yX,this,null),k(bX,this,e);try{k(yX,this,zle(e,D(kX,this))),D(yX,this).unref()}catch{}}}function qtt(e){k(xX,this,null);let t=ox();t===e&&dx(t).then(async e=>{e.length>0&&e.every(e=>e.status===`completed`)&&(await bwe(t),k(_X,this,[]),k(vX,this,!0)),S(OX,this,Gtt).call(this)})}function Jtt(){D(xX,this)&&(clearTimeout(D(xX,this)),k(xX,this,null))}function Ytt(){D(yX,this)?.close(),k(yX,this,null),k(bX,this,null),D(wX,this)?.call(this),k(wX,this,null),S(OX,this,Jtt).call(this),D(SX,this)&&clearTimeout(D(SX,this)),D(CX,this)&&clearTimeout(D(CX,this)),k(SX,this,null),k(CX,this,null),k(DX,this,!1)}function Xtt(){return jX??(jX=new tnt)}function hX(){let e=ax()?Xtt():null;return(0,gX.useSyncExternalStore)(e?e.subscribe:rnt,e?e.getSnapshot:int)}function Ztt(){let e=hX(),t=cV(),n=e===void 0;return(0,gX.useEffect)(()=>{n&&t(e=>e.expandedView===`tasks`?{...e,expandedView:`none`}:e)},[n,t]),e}var gX,Qtt,$tt,ent,_X,vX,yX,bX,xX,SX,CX,wX,TX,EX,DX,OX,kX,AX,tnt,jX,nnt,rnt,int,ant=n((()=>{gX=r(ze(),1),mV(),fn(),hx(),A(),C(),b(),w(),T(),E(),Qtt=5e3,$tt=50,ent=5e3,_X=new WeakMap,vX=new WeakMap,yX=new WeakMap,bX=new WeakMap,xX=new WeakMap,SX=new WeakMap,CX=new WeakMap,wX=new WeakMap,TX=new WeakMap,EX=new WeakMap,DX=new WeakMap,OX=new WeakSet,kX=new WeakMap,AX=new WeakMap,tnt=class{constructor(){ee(this,OX),O(this,_X,void 0),O(this,vX,!1),O(this,yX,null),O(this,bX,null),O(this,xX,null),O(this,SX,null),O(this,CX,null),O(this,wX,null),O(this,TX,rn()),O(this,EX,0),O(this,DX,!1),x(this,`getSnapshot`,()=>D(vX,this)?void 0:D(_X,this)),x(this,`subscribe`,e=>{var t;let n=D(TX,this).subscribe(e);k(EX,this,(t=D(EX,this),t++,t)),D(DX,this)||(k(DX,this,!0),k(wX,this,jwe(D(kX,this))),D(AX,this).call(this));let r=!1;return()=>{var e;r||(r=!0,n(),k(EX,this,(e=D(EX,this),e--,e)),D(EX,this)===0&&S(OX,this,Ytt).call(this))}}),O(this,kX,()=>{D(SX,this)&&clearTimeout(D(SX,this)),k(SX,this,setTimeout(()=>void D(AX,this).call(this),$tt)),D(SX,this).unref()}),O(this,AX,async()=>{let e=ox();S(OX,this,Ktt).call(this,sx(e));let t=(await dx(e)).filter(e=>!e.metadata?._internal);k(_X,this,t);let n=t.some(e=>e.status!==`completed`);n||t.length===0?(k(vX,this,t.length===0),S(OX,this,Jtt).call(this)):D(xX,this)===null&&!D(vX,this)&&(k(xX,this,setTimeout(S(OX,this,qtt).bind(this,e),Qtt)),D(xX,this).unref()),S(OX,this,Gtt).call(this),D(CX,this)&&(clearTimeout(D(CX,this)),k(CX,this,null)),n&&(k(CX,this,setTimeout(D(kX,this),ent)),D(CX,this).unref())})}},jX=null,nnt=()=>{},rnt=()=>nnt,int=()=>void 0}));function MX(e){switch(e){case`light`:return snt;case`light-ansi`:return cnt;case`dark-ansi`:return lnt;case`light-daltonized`:return unt;case`dark-daltonized`:return fnt;default:return dnt}}var ont,snt,cnt,lnt,unt,dnt,fnt,NX=n((()=>{Ge(),Ar(),ont=[`dark`,`light`,`light-daltonized`,`dark-daltonized`,`light-ansi`,`dark-ansi`],[...ont],snt={autoAccept:`rgb(135,0,255)`,bashBorder:`rgb(255,0,135)`,claude:`rgb(215,119,87)`,claudeShimmer:`rgb(245,149,117)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(87,105,247)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(117,135,255)`,permission:`rgb(87,105,247)`,permissionShimmer:`rgb(137,155,255)`,planMode:`rgb(0,102,102)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(153,153,153)`,promptBorderShimmer:`rgb(183,183,183)`,text:`rgb(0,0,0)`,inverseText:`rgb(255,255,255)`,inactive:`rgb(102,102,102)`,inactiveShimmer:`rgb(142,142,142)`,subtle:`rgb(175,175,175)`,suggestion:`rgb(87,105,247)`,remember:`rgb(0,0,255)`,background:`rgb(0,153,153)`,success:`rgb(44,122,57)`,error:`rgb(171,43,63)`,warning:`rgb(150,108,30)`,merged:`rgb(135,0,255)`,warningShimmer:`rgb(200,158,80)`,diffAdded:`rgb(105,219,124)`,diffRemoved:`rgb(255,168,180)`,diffAddedDimmed:`rgb(199,225,203)`,diffRemovedDimmed:`rgb(253,210,216)`,diffAddedWord:`rgb(47,157,68)`,diffRemovedWord:`rgb(209,69,75)`,red_FOR_SUBAGENTS_ONLY:`rgb(220,38,38)`,blue_FOR_SUBAGENTS_ONLY:`rgb(37,99,235)`,green_FOR_SUBAGENTS_ONLY:`rgb(22,163,74)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(202,138,4)`,purple_FOR_SUBAGENTS_ONLY:`rgb(147,51,234)`,orange_FOR_SUBAGENTS_ONLY:`rgb(234,88,12)`,pink_FOR_SUBAGENTS_ONLY:`rgb(219,39,119)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(8,145,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(240, 240, 240)`,userMessageBackgroundHover:`rgb(252, 252, 252)`,messageActionsBackground:`rgb(232, 236, 244)`,selectionBg:`rgb(180, 213, 255)`,bashMessageBackgroundColor:`rgb(250, 245, 250)`,memoryBackgroundColor:`rgb(230, 245, 250)`,rate_limit_fill:`rgb(87,105,247)`,rate_limit_empty:`rgb(39,47,111)`,fastMode:`rgb(255,106,0)`,fastModeShimmer:`rgb(255,150,50)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},cnt={autoAccept:`ansi:magenta`,bashBorder:`ansi:magenta`,claude:`ansi:redBright`,claudeShimmer:`ansi:yellowBright`,claudeBlue_FOR_SYSTEM_SPINNER:`ansi:blue`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`ansi:blueBright`,permission:`ansi:blue`,permissionShimmer:`ansi:blueBright`,planMode:`ansi:cyan`,ide:`ansi:blueBright`,promptBorder:`ansi:white`,promptBorderShimmer:`ansi:whiteBright`,text:`ansi:black`,inverseText:`ansi:white`,inactive:`ansi:blackBright`,inactiveShimmer:`ansi:white`,subtle:`ansi:blackBright`,suggestion:`ansi:blue`,remember:`ansi:blue`,background:`ansi:cyan`,success:`ansi:green`,error:`ansi:red`,warning:`ansi:yellow`,merged:`ansi:magenta`,warningShimmer:`ansi:yellowBright`,diffAdded:`ansi:green`,diffRemoved:`ansi:red`,diffAddedDimmed:`ansi:green`,diffRemovedDimmed:`ansi:red`,diffAddedWord:`ansi:greenBright`,diffRemovedWord:`ansi:redBright`,red_FOR_SUBAGENTS_ONLY:`ansi:red`,blue_FOR_SUBAGENTS_ONLY:`ansi:blue`,green_FOR_SUBAGENTS_ONLY:`ansi:green`,yellow_FOR_SUBAGENTS_ONLY:`ansi:yellow`,purple_FOR_SUBAGENTS_ONLY:`ansi:magenta`,orange_FOR_SUBAGENTS_ONLY:`ansi:redBright`,pink_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,cyan_FOR_SUBAGENTS_ONLY:`ansi:cyan`,professionalBlue:`ansi:blueBright`,chromeYellow:`ansi:yellow`,clawd_body:`ansi:redBright`,clawd_background:`ansi:black`,userMessageBackground:`ansi:white`,userMessageBackgroundHover:`ansi:whiteBright`,messageActionsBackground:`ansi:white`,selectionBg:`ansi:cyan`,bashMessageBackgroundColor:`ansi:whiteBright`,memoryBackgroundColor:`ansi:white`,rate_limit_fill:`ansi:yellow`,rate_limit_empty:`ansi:black`,fastMode:`ansi:red`,fastModeShimmer:`ansi:redBright`,rainbow_red:`ansi:red`,rainbow_orange:`ansi:redBright`,rainbow_yellow:`ansi:yellow`,rainbow_green:`ansi:green`,rainbow_blue:`ansi:cyan`,rainbow_indigo:`ansi:blue`,rainbow_violet:`ansi:magenta`,rainbow_red_shimmer:`ansi:redBright`,rainbow_orange_shimmer:`ansi:yellow`,rainbow_yellow_shimmer:`ansi:yellowBright`,rainbow_green_shimmer:`ansi:greenBright`,rainbow_blue_shimmer:`ansi:cyanBright`,rainbow_indigo_shimmer:`ansi:blueBright`,rainbow_violet_shimmer:`ansi:magentaBright`},lnt={autoAccept:`ansi:magentaBright`,bashBorder:`ansi:magentaBright`,claude:`ansi:redBright`,claudeShimmer:`ansi:yellowBright`,claudeBlue_FOR_SYSTEM_SPINNER:`ansi:blueBright`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`ansi:blueBright`,permission:`ansi:blueBright`,permissionShimmer:`ansi:blueBright`,planMode:`ansi:cyanBright`,ide:`ansi:blue`,promptBorder:`ansi:white`,promptBorderShimmer:`ansi:whiteBright`,text:`ansi:whiteBright`,inverseText:`ansi:black`,inactive:`ansi:white`,inactiveShimmer:`ansi:whiteBright`,subtle:`ansi:white`,suggestion:`ansi:blueBright`,remember:`ansi:blueBright`,background:`ansi:cyanBright`,success:`ansi:greenBright`,error:`ansi:redBright`,warning:`ansi:yellowBright`,merged:`ansi:magentaBright`,warningShimmer:`ansi:yellowBright`,diffAdded:`ansi:green`,diffRemoved:`ansi:red`,diffAddedDimmed:`ansi:green`,diffRemovedDimmed:`ansi:red`,diffAddedWord:`ansi:greenBright`,diffRemovedWord:`ansi:redBright`,red_FOR_SUBAGENTS_ONLY:`ansi:redBright`,blue_FOR_SUBAGENTS_ONLY:`ansi:blueBright`,green_FOR_SUBAGENTS_ONLY:`ansi:greenBright`,yellow_FOR_SUBAGENTS_ONLY:`ansi:yellowBright`,purple_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,orange_FOR_SUBAGENTS_ONLY:`ansi:redBright`,pink_FOR_SUBAGENTS_ONLY:`ansi:magentaBright`,cyan_FOR_SUBAGENTS_ONLY:`ansi:cyanBright`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`ansi:yellowBright`,clawd_body:`ansi:redBright`,clawd_background:`ansi:black`,userMessageBackground:`ansi:blackBright`,userMessageBackgroundHover:`ansi:white`,messageActionsBackground:`ansi:blackBright`,selectionBg:`ansi:blue`,bashMessageBackgroundColor:`ansi:black`,memoryBackgroundColor:`ansi:blackBright`,rate_limit_fill:`ansi:yellow`,rate_limit_empty:`ansi:white`,fastMode:`ansi:redBright`,fastModeShimmer:`ansi:redBright`,rainbow_red:`ansi:red`,rainbow_orange:`ansi:redBright`,rainbow_yellow:`ansi:yellow`,rainbow_green:`ansi:green`,rainbow_blue:`ansi:cyan`,rainbow_indigo:`ansi:blue`,rainbow_violet:`ansi:magenta`,rainbow_red_shimmer:`ansi:redBright`,rainbow_orange_shimmer:`ansi:yellow`,rainbow_yellow_shimmer:`ansi:yellowBright`,rainbow_green_shimmer:`ansi:greenBright`,rainbow_blue_shimmer:`ansi:cyanBright`,rainbow_indigo_shimmer:`ansi:blueBright`,rainbow_violet_shimmer:`ansi:magentaBright`},unt={autoAccept:`rgb(135,0,255)`,bashBorder:`rgb(0,102,204)`,claude:`rgb(255,153,51)`,claudeShimmer:`rgb(255,183,101)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(51,102,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(101,152,255)`,permission:`rgb(51,102,255)`,permissionShimmer:`rgb(101,152,255)`,planMode:`rgb(51,102,102)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(153,153,153)`,promptBorderShimmer:`rgb(183,183,183)`,text:`rgb(0,0,0)`,inverseText:`rgb(255,255,255)`,inactive:`rgb(102,102,102)`,inactiveShimmer:`rgb(142,142,142)`,subtle:`rgb(175,175,175)`,suggestion:`rgb(51,102,255)`,remember:`rgb(51,102,255)`,background:`rgb(0,153,153)`,success:`rgb(0,102,153)`,error:`rgb(204,0,0)`,warning:`rgb(255,153,0)`,merged:`rgb(135,0,255)`,warningShimmer:`rgb(255,183,50)`,diffAdded:`rgb(153,204,255)`,diffRemoved:`rgb(255,204,204)`,diffAddedDimmed:`rgb(209,231,253)`,diffRemovedDimmed:`rgb(255,233,233)`,diffAddedWord:`rgb(51,102,204)`,diffRemovedWord:`rgb(153,51,51)`,red_FOR_SUBAGENTS_ONLY:`rgb(204,0,0)`,blue_FOR_SUBAGENTS_ONLY:`rgb(0,102,204)`,green_FOR_SUBAGENTS_ONLY:`rgb(0,204,0)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(255,204,0)`,purple_FOR_SUBAGENTS_ONLY:`rgb(128,0,128)`,orange_FOR_SUBAGENTS_ONLY:`rgb(255,128,0)`,pink_FOR_SUBAGENTS_ONLY:`rgb(255,102,178)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(0,178,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(220, 220, 220)`,userMessageBackgroundHover:`rgb(232, 232, 232)`,messageActionsBackground:`rgb(210, 216, 226)`,selectionBg:`rgb(180, 213, 255)`,bashMessageBackgroundColor:`rgb(250, 245, 250)`,memoryBackgroundColor:`rgb(230, 245, 250)`,rate_limit_fill:`rgb(51,102,255)`,rate_limit_empty:`rgb(23,46,114)`,fastMode:`rgb(255,106,0)`,fastModeShimmer:`rgb(255,150,50)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},dnt={autoAccept:`rgb(175,135,255)`,bashBorder:`rgb(253,93,177)`,claude:`rgb(215,119,87)`,claudeShimmer:`rgb(235,159,127)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(147,165,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(177,195,255)`,permission:`rgb(177,185,249)`,permissionShimmer:`rgb(207,215,255)`,planMode:`rgb(72,150,140)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(136,136,136)`,promptBorderShimmer:`rgb(166,166,166)`,text:`rgb(255,255,255)`,inverseText:`rgb(0,0,0)`,inactive:`rgb(153,153,153)`,inactiveShimmer:`rgb(193,193,193)`,subtle:`rgb(80,80,80)`,suggestion:`rgb(177,185,249)`,remember:`rgb(177,185,249)`,background:`rgb(0,204,204)`,success:`rgb(78,186,101)`,error:`rgb(255,107,128)`,warning:`rgb(255,193,7)`,merged:`rgb(175,135,255)`,warningShimmer:`rgb(255,223,57)`,diffAdded:`rgb(34,92,43)`,diffRemoved:`rgb(122,41,54)`,diffAddedDimmed:`rgb(71,88,74)`,diffRemovedDimmed:`rgb(105,72,77)`,diffAddedWord:`rgb(56,166,96)`,diffRemovedWord:`rgb(179,89,107)`,red_FOR_SUBAGENTS_ONLY:`rgb(220,38,38)`,blue_FOR_SUBAGENTS_ONLY:`rgb(37,99,235)`,green_FOR_SUBAGENTS_ONLY:`rgb(22,163,74)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(202,138,4)`,purple_FOR_SUBAGENTS_ONLY:`rgb(147,51,234)`,orange_FOR_SUBAGENTS_ONLY:`rgb(234,88,12)`,pink_FOR_SUBAGENTS_ONLY:`rgb(219,39,119)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(8,145,178)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(55, 55, 55)`,userMessageBackgroundHover:`rgb(70, 70, 70)`,messageActionsBackground:`rgb(44, 50, 62)`,selectionBg:`rgb(38, 79, 120)`,bashMessageBackgroundColor:`rgb(65, 60, 65)`,memoryBackgroundColor:`rgb(55, 65, 70)`,rate_limit_fill:`rgb(177,185,249)`,rate_limit_empty:`rgb(80,83,112)`,fastMode:`rgb(255,120,20)`,fastModeShimmer:`rgb(255,165,70)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},fnt={autoAccept:`rgb(175,135,255)`,bashBorder:`rgb(51,153,255)`,claude:`rgb(255,153,51)`,claudeShimmer:`rgb(255,183,101)`,claudeBlue_FOR_SYSTEM_SPINNER:`rgb(153,204,255)`,claudeBlueShimmer_FOR_SYSTEM_SPINNER:`rgb(183,224,255)`,permission:`rgb(153,204,255)`,permissionShimmer:`rgb(183,224,255)`,planMode:`rgb(102,153,153)`,ide:`rgb(71,130,200)`,promptBorder:`rgb(136,136,136)`,promptBorderShimmer:`rgb(166,166,166)`,text:`rgb(255,255,255)`,inverseText:`rgb(0,0,0)`,inactive:`rgb(153,153,153)`,inactiveShimmer:`rgb(193,193,193)`,subtle:`rgb(80,80,80)`,suggestion:`rgb(153,204,255)`,remember:`rgb(153,204,255)`,background:`rgb(0,204,204)`,success:`rgb(51,153,255)`,error:`rgb(255,102,102)`,warning:`rgb(255,204,0)`,merged:`rgb(175,135,255)`,warningShimmer:`rgb(255,234,50)`,diffAdded:`rgb(0,68,102)`,diffRemoved:`rgb(102,0,0)`,diffAddedDimmed:`rgb(62,81,91)`,diffRemovedDimmed:`rgb(62,44,44)`,diffAddedWord:`rgb(0,119,179)`,diffRemovedWord:`rgb(179,0,0)`,red_FOR_SUBAGENTS_ONLY:`rgb(255,102,102)`,blue_FOR_SUBAGENTS_ONLY:`rgb(102,178,255)`,green_FOR_SUBAGENTS_ONLY:`rgb(102,255,102)`,yellow_FOR_SUBAGENTS_ONLY:`rgb(255,255,102)`,purple_FOR_SUBAGENTS_ONLY:`rgb(178,102,255)`,orange_FOR_SUBAGENTS_ONLY:`rgb(255,178,102)`,pink_FOR_SUBAGENTS_ONLY:`rgb(255,153,204)`,cyan_FOR_SUBAGENTS_ONLY:`rgb(102,204,204)`,professionalBlue:`rgb(106,155,204)`,chromeYellow:`rgb(251,188,4)`,clawd_body:`rgb(215,119,87)`,clawd_background:`rgb(0,0,0)`,userMessageBackground:`rgb(55, 55, 55)`,userMessageBackgroundHover:`rgb(70, 70, 70)`,messageActionsBackground:`rgb(44, 50, 62)`,selectionBg:`rgb(38, 79, 120)`,bashMessageBackgroundColor:`rgb(65, 60, 65)`,memoryBackgroundColor:`rgb(55, 65, 70)`,rate_limit_fill:`rgb(153,204,255)`,rate_limit_empty:`rgb(69,92,115)`,fastMode:`rgb(255,120,20)`,fastModeShimmer:`rgb(255,165,70)`,rainbow_red:`rgb(235,95,87)`,rainbow_orange:`rgb(245,139,87)`,rainbow_yellow:`rgb(250,195,95)`,rainbow_green:`rgb(145,200,130)`,rainbow_blue:`rgb(130,170,220)`,rainbow_indigo:`rgb(155,130,200)`,rainbow_violet:`rgb(200,130,180)`,rainbow_red_shimmer:`rgb(250,155,147)`,rainbow_orange_shimmer:`rgb(255,185,137)`,rainbow_yellow_shimmer:`rgb(255,225,155)`,rainbow_green_shimmer:`rgb(185,230,180)`,rainbow_blue_shimmer:`rgb(180,205,240)`,rainbow_indigo_shimmer:`rgb(195,180,230)`,rainbow_violet_shimmer:`rgb(230,180,210)`},pr.terminal===`Apple_Terminal`&&new mee({level:2})}));function pnt(){return process.env.TERM===`xterm-ghostty`?[`·`,`✢`,`✱`,`✶`,`✻`,`*`]:(process.platform,[`·`,`✢`,`✱`,`✶`,`✻`,`✽`])}function PX(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n)}}function FX(e){return`rgb(${e.r},${e.g},${e.b})`}function mnt(e){let t=(e%360+360)%360,n=.8*.7,r=n*(1-Math.abs(t/60%2-1)),i=.6-n/2,a=0,o=0,s=0;return t<60?(a=n,o=r):t<120?(a=r,o=n):t<180?(o=n,s=r):t<240?(o=r,s=n):t<300?(a=r,s=n):(a=n,s=r),{r:Math.round((a+i)*255),g:Math.round((o+i)*255),b:Math.round((s+i)*255)}}function IX(e){let t=LX.get(e);if(t!==void 0)return t;let n=e.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/),r=n?{r:parseInt(n[1],10),g:parseInt(n[2],10),b:parseInt(n[3],10)}:null;return LX.set(e,r),r}var LX,RX=n((()=>{LX=new Map})),hnt=n((()=>{I(),NX(),et()}));function gnt({message:e,mode:t,messageColor:n,glimmerIndex:r,flashOpacity:i,shimmerColor:a,stalledIntensity:o=0}){let[s]=xe(),c=MX(s),{segments:l,messageWidth:u}=_nt.useMemo(()=>{let t=[];for(let{segment:n}of Oa().segment(e))t.push({segment:n,width:ye(n)});return{segments:t,messageWidth:ye(e)}},[e]);if(!e)return null;if(o>0){let t=c[n],r=t?IX(t):null;if(r){let t=FX(PX(r,vnt,o));return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:t,children:e}),(0,zX.jsx)(F,{color:t,children:` `})]})}let i=o>.5?`error`:n;return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:i,children:e}),(0,zX.jsx)(F,{color:i,children:` `})]})}if(t===`tool-use`){let t=c[n],r=c[a],o=t?IX(t):null,s=r?IX(r):null;return o&&s?(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:FX(PX(o,s,i)),children:e}),(0,zX.jsx)(F,{color:n,children:` `})]}):(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:i>.5?a:n,children:e}),(0,zX.jsx)(F,{color:n,children:` `})]})}let d=r-1,f=r+1;if(d>=u||f<0)return(0,zX.jsxs)(zX.Fragment,{children:[(0,zX.jsx)(F,{color:n,children:e}),(0,zX.jsx)(F,{color:n,children:` `})]});let p=Math.max(0,d),m=0,h=``,g=``,_=``;for(let{segment:e,width:t}of l)m+t<=p?h+=e:m>f?_+=e:g+=e,m+=t;return(0,zX.jsxs)(zX.Fragment,{children:[h&&(0,zX.jsx)(F,{color:n,children:h}),(0,zX.jsx)(F,{color:a,children:g}),_&&(0,zX.jsx)(F,{color:n,children:_}),(0,zX.jsx)(F,{color:n,children:` `})]})}var _nt,zX,vnt,ynt=n((()=>{_nt=r(ze(),1),I(),ka(),NX(),RX(),zX=et(),vnt={r:171,g:43,b:63}}));function bnt({frame:e,messageColor:t,stalledIntensity:n=0,reducedMotion:r=!1,time:i=0}){let[a]=xe(),o=MX(a);if(r)return(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:t,dimColor:Math.floor(i/(Snt/2))%2==1,children:xnt})});let s=HX[e%HX.length];if(n>0){let e=o[t],r=e?IX(e):null;return r?(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:FX(PX(r,Cnt,n)),children:s})}):(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:n>.5?`error`:t,children:s})})}return(0,BX.jsx)(P,{flexWrap:`wrap`,height:1,width:2,children:(0,BX.jsx)(F,{color:t,children:s})})}var BX,VX,HX,xnt,Snt,Cnt,UX=n((()=>{I(),NX(),RX(),BX=et(),VX=pnt(),HX=[...VX,...[...VX].reverse()],xnt=`●`,Snt=2e3,Cnt={r:171,g:43,b:63}}));function wnt(e,t,n){let r=e===`requesting`?50:200,[i,a]=Ye(n?null:r),o=(0,Tnt.useMemo)(()=>ye(t),[t]);if(n)return[i,-100];let s=Math.floor(a/r),c=o+20;return e===`requesting`?[i,s%c-10]:[i,o+10-s%c]}var Tnt,Ent=n((()=>{Tnt=r(ze(),1),I()}));function Dnt(e,t,n=!1,r=!1){let i=(0,WX.useRef)(e),a=(0,WX.useRef)(t),o=(0,WX.useRef)(e),s=(0,WX.useRef)(0),c=(0,WX.useRef)(e);t>a.current&&(i.current=e,a.current=t,s.current=0,c.current=e);let l;n?(l=0,i.current=e):l=t>0?e-i.current:e-o.current;let u=l>3e3&&!n,d=u?Math.min((l-3e3)/2e3,1):0;if(!r&&(d>0||s.current>0)){let t=e-c.current;if(t>=50){let n=Math.floor(t/50),r=s.current;for(let e=0;e<n;e++){let e=d-r;if(Math.abs(e)<.01){r=d;break}r+=e*.1}s.current=r,c.current=e}}else s.current=d,c.current=e;return{isStalled:u,stalledIntensity:r?d:s.current}}var WX,Ont=n((()=>{WX=r(ze(),1)})),knt=n((()=>{hnt(),ynt(),PY(),UX(),Ent(),Ont(),RX()}));function Ant({mode:e,reducedMotion:t,hasActiveTools:n,responseLengthRef:r,message:i,messageColor:a,shimmerColor:o,overrideColor:s,loadingStartTimeRef:c,totalPausedMsRef:l,pauseStartTimeRef:u,spinnerSuffix:d,verbose:f,columns:p,agentTokens:m,leaderIsIdle:h=!1,thinkingStatus:g}){let[_,v]=Ye(t?null:50),y=Date.now(),b=u.current===null?y-c.current-l.current:u.current-c.current-l.current,x=r.current,{isStalled:S,stalledIntensity:C}=Dnt(v,x,n||h,t),w=t?0:Math.floor(v/120),T=e===`requesting`?50:200,E=(0,GX.useMemo)(()=>ye(i),[i]),D=E+20,O=Math.floor(v/T),k=t||S?-100:e===`requesting`?O%D-10:E+10-O%D,A=t?0:e===`tool-use`?(Math.sin(v/1e3*Math.PI)+1)/2:0,ee=(0,GX.useRef)(x);if(t)ee.current=x;else{let e=x-ee.current;if(e>0){let t;t=e<70?3:e<200?Math.max(8,Math.ceil(e*.15)):50,ee.current=Math.min(ee.current+t,x)}}let te=ee.current,ne=Math.round(te/4),re=La(b),ae=ye(re),j=ne+m,oe=Pa(j),se=ye(`${ie.arrowDown} ${oe} tokens`),ce=g===`thinking`?`thinking`:typeof g==`number`?`thought for ${Math.max(1,Math.round(g/1e3))}s`:null,M=ce?ye(ce):0,N=E+2,le=Mnt,ue=g!==null,de=f||b>Nnt,fe=p-N-5,pe=ue&&fe>M;!pe&&ue&&g===`thinking`&&fe>qX&&(ce=`thinking`,M=qX,pe=!0);let me=pe?M+le:0,he=de&&fe>me+ae,ge=me+(he?ae+le:0),_e=de&&j>0&&fe>ge+se,ve=pe&&g===`thinking`&&!d&&!he&&!_e&&!0,be=(v-JX)/1e3,xe=v<JX?0:(Math.sin(be*Math.PI*2/Int)+1)/2,Se=FX(PX(Pnt,Fnt,xe)),Ce=[...d?[(0,KX.jsx)(F,{dimColor:!0,children:d},`suffix`)]:[],...he?[(0,KX.jsx)(F,{dimColor:!0,children:re},`elapsedTime`)]:[],..._e?[(0,KX.jsxs)(P,{flexDirection:`row`,children:[(0,KX.jsx)(jnt,{mode:e}),(0,KX.jsxs)(F,{dimColor:!0,children:[oe,` tokens`]})]},`tokens`)]:[],...pe&&ce?[g===`thinking`&&!t?(0,KX.jsx)(F,{color:Se,children:ve?`(${ce})`:ce},`thinking`):(0,KX.jsx)(F,{dimColor:!0,children:ce},`thinking`)]:[]],we=Ce.length>0?ve?(0,KX.jsx)(je,{children:Ce}):(0,KX.jsxs)(KX.Fragment,{children:[(0,KX.jsx)(F,{dimColor:!0,children:`(`}),(0,KX.jsx)(je,{children:Ce}),(0,KX.jsx)(F,{dimColor:!0,children:`)`})]}):null;return(0,KX.jsxs)(P,{ref:_,flexDirection:`row`,flexWrap:`wrap`,marginTop:1,width:`100%`,children:[(0,KX.jsx)(bnt,{frame:w,messageColor:a,stalledIntensity:s?0:C,reducedMotion:t,time:v}),(0,KX.jsx)(gnt,{message:i,mode:e,messageColor:a,glimmerIndex:k,flashOpacity:A,shimmerColor:o,stalledIntensity:s?0:C}),we]})}function jnt({mode:e}){switch(e){case`tool-input`:case`tool-use`:case`responding`:case`thinking`:return(0,KX.jsx)(P,{width:2,children:(0,KX.jsx)(F,{dimColor:!0,children:ie.arrowDown})});case`requesting`:return(0,KX.jsx)(P,{width:2,children:(0,KX.jsx)(F,{dimColor:!0,children:ie.arrowUp})})}}var GX,KX,Mnt,qX,Nnt,Pnt,Fnt,JX,Int,Lnt=n((()=>{ne(),GX=r(ze(),1),I(),Ba(),ynt(),UX(),Ont(),RX(),KX=et(),Mnt=ye(` · `),qX=ye(`thinking`),Nnt=3e4,Pnt={r:153,g:153,b:153},Fnt={r:185,g:185,b:185},JX=3e3,Int=2}));function Rnt(e){return(0,ZX.jsx)(znt,{...e})}function znt({mode:e,loadingStartTimeRef:t,totalPausedMsRef:n,pauseStartTimeRef:r,spinnerTip:i,responseLengthRef:a,overrideColor:o,overrideShimmerColor:s,overrideMessage:c,spinnerSuffix:l,verbose:u,hasActiveTools:d=!1,leaderIsIdle:f=!1}){let p=hV(),m=p.prefersReducedMotion??!1,h=sV(e=>e.tasks),g=sV(e=>e.expandedView)===`tasks`,{columns:_}=Xe(),v=hX(),[y,b]=(0,XX.useState)(null),x=(0,XX.useRef)(null);(0,XX.useEffect)(()=>{let t=null,n=null;if(e===`thinking`)x.current===null&&(x.current=Date.now(),b(`thinking`));else if(x.current!==null){let e=Date.now()-x.current,r=Date.now()-x.current,i=Math.max(0,2e3-r);x.current=null;let a=()=>{b(e),n=setTimeout(b,2e3,null)};i>0?t=setTimeout(a,i):a()}return()=>{t&&clearTimeout(t),n&&clearTimeout(n)}},[e]);let S=v?.find(e=>e.status!==`pending`&&e.status!==`completed`),C=Bnt(v),[w]=(0,XX.useState)(()=>ch(ztt())),T=`${c??S?.activeForm??S?.subject??w}…`;(0,XX.useEffect)(()=>{let t=`spinner-${e}`;return lX.startCLIActivity(t),()=>{lX.endCLIActivity(t)}},[e]);let E=0;for(let e of Object.values(h))e.status===`running`&&s0(e)&&e.progress?.tokenCount&&(E+=e.progress.tokenCount);let D=r.current===null?Date.now()-t.current-n.current:r.current-t.current-n.current,O=o??`claude`,k=s??`claudeShimmer`,A=p.spinnerTipsEnabled!==!1,ee=A&&D>18e5,te=A&&D>3e4&&!yi().btwUseCount,ne=ee&&!C?`Use /clear to start fresh when switching topics and free up context`:te&&!C?`Use /btw to ask a quick side question without interrupting Work Mate's current work`:i;return(0,ZX.jsxs)(P,{flexDirection:`column`,width:`100%`,alignItems:`flex-start`,children:[(0,ZX.jsx)(Ant,{mode:e,reducedMotion:m,hasActiveTools:d,responseLengthRef:a,message:T,messageColor:O,shimmerColor:k,overrideColor:o,loadingStartTimeRef:t,totalPausedMsRef:n,pauseStartTimeRef:r,spinnerSuffix:l,verbose:u,columns:_,agentTokens:E,leaderIsIdle:f,thinkingStatus:y}),g&&v&&v.length>0?(0,ZX.jsx)(P,{width:`100%`,flexDirection:`column`,children:(0,ZX.jsx)(Z,{children:(0,ZX.jsx)(Vtt,{tasks:v})})}):C||ne?(0,ZX.jsxs)(P,{width:`100%`,flexDirection:`column`,children:[null,(C||ne)&&(0,ZX.jsx)(Z,{children:(0,ZX.jsx)(F,{dimColor:!0,children:C?`Next: ${C.subject}`:`Tip: ${ne}`})})]}):null]})}function YX(){let e=hV().prefersReducedMotion??!1,[t,n]=Ye(e?null:120);if(e)return(0,ZX.jsx)(P,{ref:t,flexWrap:`wrap`,height:1,width:2,children:(0,ZX.jsx)(F,{color:`text`,children:`●`})});let r=Math.floor(n/120)%$X.length;return(0,ZX.jsx)(P,{ref:t,flexWrap:`wrap`,height:1,width:2,children:(0,ZX.jsx)(F,{color:`text`,children:$X[r]})})}function Bnt(e){if(!e)return;let t=e.filter(e=>e.status===`pending`);if(t.length===0)return;let n=new Set(e.filter(e=>e.status!==`completed`).map(e=>e.id));return t.find(e=>!e.blockedBy.some(e=>n.has(e)))??t[0]}var XX,ZX,QX,$X,Vnt=n((()=>{I(),XX=r(ze(),1),lh(),Ba(),Rtt(),Btt(),Rb(),Wtt(),ant(),mV(),eb(),knt(),Lnt(),gV(),p0(),Wt(),bi(),ZX=et(),QX=pnt(),$X=[...QX,...[...QX].reverse()]}));function Hnt({onStashAndContinue:e,onCancel:t}){let[n,r]=(0,eZ.useState)(null),i=n===null?[]:[...n.tracked,...n.untracked],[a,o]=(0,eZ.useState)(!0),[s,c]=(0,eZ.useState)(!1),[l,u]=(0,eZ.useState)(null);(0,eZ.useEffect)(()=>{(async()=>{try{let e=await bie();r(e)}catch(e){U(`Error getting changed files: ${e instanceof Error?e.message:String(e)}`,{level:`error`}),u(`Failed to get changed files`)}finally{o(!1)}})()},[]);let d=async()=>{c(!0);try{U(`Stashing changes before teleport...`),await gie(`Teleport auto-stash`)?(U(`Successfully stashed changes`),e()):u(`Failed to stash changes`)}catch(e){U(`Error stashing changes: ${e instanceof Error?e.message:String(e)}`,{level:`error`}),u(`Failed to stash changes`)}finally{c(!1)}},f=e=>{e===`stash`?d():t()};if(a)return(0,tZ.jsx)(P,{flexDirection:`column`,padding:1,children:(0,tZ.jsxs)(P,{marginBottom:1,children:[(0,tZ.jsx)(YX,{}),(0,tZ.jsxs)(F,{children:[` Checking git status`,ie.ellipsis]})]})});if(l)return(0,tZ.jsxs)(P,{flexDirection:`column`,padding:1,children:[(0,tZ.jsxs)(F,{bold:!0,color:`error`,children:[`Error: `,l]}),(0,tZ.jsxs)(P,{marginTop:1,children:[(0,tZ.jsx)(F,{dimColor:!0,children:`Press `}),(0,tZ.jsx)(F,{bold:!0,children:`Escape`}),(0,tZ.jsx)(F,{dimColor:!0,children:` to cancel`})]})]});let p=i.length>8;return(0,tZ.jsxs)($e,{title:`Working Directory Has Changes`,onCancel:t,children:[(0,tZ.jsx)(F,{children:`Teleport will switch git branches. The following changes were found:`}),(0,tZ.jsx)(P,{flexDirection:`column`,paddingLeft:2,children:i.length>0?p?(0,tZ.jsxs)(F,{children:[i.length,` files changed`]}):i.map((e,t)=>(0,tZ.jsx)(F,{children:e},t)):(0,tZ.jsx)(F,{dimColor:!0,children:`No changes detected`})}),(0,tZ.jsx)(F,{children:`Would you like to stash these changes and continue with teleport?`}),s?(0,tZ.jsxs)(P,{children:[(0,tZ.jsx)(YX,{}),(0,tZ.jsx)(F,{children:` Stashing changes...`})]}):(0,tZ.jsx)(iX,{options:[{label:`Stash changes and continue`,value:`stash`},{label:`Exit`,value:`exit`}],onChange:f})]})}var eZ,tZ,Unt=n((()=>{ne(),eZ=r(ze(),1),I(),W(),Mi(),sX(),Vnt(),tZ=et()}));function Wnt({onComplete:e,errorsToIgnore:t=Knt}){let[n,r]=(0,nZ.useState)(null),[i,a]=(0,nZ.useState)(!1),o=(0,nZ.useCallback)(async()=>{let n=await Gnt(),i=new Set(Array.from(n).filter(e=>!t.has(e)));if(i.size===0){e();return}i.has(`needsLogin`)?r(`needsLogin`):i.has(`needsGitStash`)&&r(`needsGitStash`)},[e,t]);(0,nZ.useEffect)(()=>{o()},[o]);let s=(0,nZ.useCallback)(()=>{UJ(0)},[]),c=(0,nZ.useCallback)(()=>{a(!1),o()},[o]),l=(0,nZ.useCallback)(()=>{a(!0)},[a]),u=(0,nZ.useCallback)(e=>{e===`login`?l():s()},[l,s]),d=(0,nZ.useCallback)(()=>{o()},[o]);if(!n)return null;switch(n){case`needsGitStash`:return(0,rZ.jsx)(Hnt,{onStashAndContinue:d,onCancel:s});case`needsLogin`:return i?(0,rZ.jsx)(ptt,{onDone:c}):(0,rZ.jsxs)($e,{title:`Log in to Work Mate`,onCancel:s,children:[(0,rZ.jsxs)(P,{flexDirection:`column`,children:[(0,rZ.jsx)(F,{dimColor:!0,children:`Teleport requires a Claude.ai account.`}),(0,rZ.jsx)(F,{dimColor:!0,children:`Your Claude Pro/Max subscription will be used by Work Mate.`})]}),(0,rZ.jsx)(iX,{options:[{label:`Login with Work Mate account`,value:`login`},{label:`Exit`,value:`exit`}],onChange:u})]})}}async function Gnt(){let e=new Set,[t,n]=await Promise.all([F9e(),I9e()]);return t&&e.add(`needsLogin`),n||e.add(`needsGitStash`),e}var nZ,rZ,Knt,qnt=n((()=>{nZ=r(ze(),1),zJ(),YJ(),I(),htt(),sX(),Unt(),rZ=et(),Knt=new Set}));function Jnt({children:e}){let{addNotification:t,removeNotification:n}=XJ();return(0,Xnt.jsx)(Pe,{loadBindings:fm,subscribeToChanges:ome,initWatcher:$pe,onWarnings:(0,Ynt.useCallback)((e,r)=>{let i=`keybinding-config-warning`;if(e.length===0){n(i);return}let a=hr(e,e=>e.severity===`error`),o=hr(e,e=>e.severity===`warning`),s;s=a>0&&o>0?`Found ${a} keybinding ${qa(a,`error`)} and ${o} ${qa(o,`warning`)}`:a>0?`Found ${a} keybinding ${qa(a,`error`)}`:`Found ${o} keybinding ${qa(o,`warning`)}`,s+=` · /doctor for details`,t({key:i,text:s,color:a>0?`error`:`warning`,priority:a>0?`immediate`:`high`,timeoutMs:6e4})},[t,n]),onDebugLog:U,children:e})}var Ynt,Xnt,Znt=n((()=>{Ynt=r(ze(),1),tY(),Cr(),W(),Ja(),I(),bm(),Xnt=et()}));function Qnt(e){let t=sZ.get(e);return t||(t=Fae(async(t,n,r)=>await $nt(e,t,n,r)),sZ.set(e,t)),t}async function $nt(e,t,n,r){for(let i=1;i<=oZ;i++){try{let a=aZ.get(e),o={...r};a&&(o[`Last-Uuid`]=a);let s=await ue.put(n,t,{headers:o,validateStatus:e=>e<500});if(s.status===200||s.status===201)return aZ.set(e,t.uuid),U(`Successfully persisted session log entry for session ${e}`),!0;if(s.status===409){let i=s.headers[`x-last-uuid`];if(i===t.uuid)return aZ.set(e,t.uuid),U(`Session entry ${t.uuid} already present on server, recovering from stale state`),Ai(`info`,`session_persist_recovered_from_409`),!0;if(i)aZ.set(e,i),U(`Session 409: adopting server lastUuid=${i} from header, retrying entry ${t.uuid}`);else{let i=await iZ(e,n,r),a=irt(i);if(a)aZ.set(e,a),U(`Session 409: re-fetched ${i.length} entries, adopting lastUuid=${a}, retrying entry ${t.uuid}`);else{let n=s.data.error?.message||`Concurrent modification detected`;return q(Error(`Session persistence conflict: UUID mismatch for session ${e}, entry ${t.uuid}. ${n}`)),Ai(`error`,`session_persist_fail_concurrent_modification`),!1}}Ai(`info`,`session_persist_409_adopt_server_uuid`);continue}if(s.status===401)return U(`Session token expired or invalid`),Ai(`error`,`session_persist_fail_bad_token`),!1;U(`Failed to persist session log: ${s.status} ${s.statusText}`),Ai(`error`,`session_persist_fail_status`,{status:s.status,attempt:i})}catch(e){let t=e;q(Error(`Error persisting session log: ${t.message}`)),Ai(`error`,`session_persist_fail_status`,{status:t.status,attempt:i})}if(i===oZ)return U(`Remote persistence failed after ${oZ} attempts`),Ai(`error`,`session_persist_error_retries_exhausted`,{attempt:i}),!1;let a=Math.min(ort*2**(i-1),8e3);U(`Remote persistence attempt ${i}/${oZ} failed, retrying in ${a}ms…`),await $o(a)}return!1}async function ert(e,t,n){let r=$s();if(!r)return U(`No session token available for session persistence`),Ai(`error`,`session_persist_fail_jwt_no_token`),!1;let i={Authorization:`Bearer ${r}`,"Content-Type":`application/json`};return Qnt(e)(t,n,i)}async function trt(e,t){let n=$s();if(!n)return U(`No session token available for fetching session logs`),Ai(`error`,`session_get_fail_no_token`),null;let r=await iZ(e,t,{Authorization:`Bearer ${n}`});if(r&&r.length>0){let t=r.at(-1);t&&`uuid`in t&&t.uuid&&aZ.set(e,t.uuid)}return r}async function nrt(e,t,n){let r=`${Va().BASE_API_URL}/v1/session_ingress/session/${e}`;return U(`[session-ingress] Fetching session logs from: ${r}`),await iZ(e,r,{...Bc(t),"x-organization-uuid":n})}async function rrt(e,t,n){let r=`${Va().BASE_API_URL}/v1/code/sessions/${e}/teleport-events`,i={...Bc(t),"x-organization-uuid":n};U(`[teleport] Fetching events from: ${r}`);let a=[],o,s=0;for(;s<100;){let t={limit:1e3};o!==void 0&&(t.cursor=o);let n;try{n=await ue.get(r,{headers:i,params:t,timeout:2e4,validateStatus:e=>e<500})}catch(e){return q(Error(`Teleport events fetch failed: ${e.message}`)),Ai(`error`,`teleport_events_fetch_fail`),null}if(n.status===404)return U(`[teleport] Session ${e} not found (page ${s})`),Ai(`warn`,`teleport_events_not_found`),s===0?null:a;if(n.status===401)throw Ai(`error`,`teleport_events_bad_token`),Error(`Your session has expired.`);if(n.status!==200)return q(Error(`Teleport events returned ${n.status}: ${V(n.data)}`)),Ai(`error`,`teleport_events_bad_status`),null;let{data:c,next_cursor:l}=n.data;if(!Array.isArray(c))return q(Error(`Teleport events invalid response shape: ${V(n.data)}`)),Ai(`error`,`teleport_events_invalid_shape`),null;for(let e of c)e.payload!==null&&a.push(e.payload);if(s++,l==null)break;o=l}return s>=100&&(q(Error(`Teleport events hit page cap (100) for ${e}`)),Ai(`warn`,`teleport_events_page_cap`)),U(`[teleport] Fetched ${a.length} events over ${s} page(s) for ${e}`),a}async function iZ(e,t,n){try{let r=await ue.get(t,{headers:n,timeout:2e4,validateStatus:e=>e<500,params:m(process.env.CLAUDE_AFTER_LAST_COMPACT)?{after_last_compact:!0}:void 0});if(r.status===200){let t=r.data;if(!t||typeof t!=`object`||!Array.isArray(t.loglines))return q(Error(`Invalid session logs response format: ${V(t)}`)),Ai(`error`,`session_get_fail_invalid_response`),null;let n=t.loglines;return U(`Fetched ${n.length} session logs for session ${e}`),n}if(r.status===404)return U(`No existing logs for session ${e}`),Ai(`warn`,`session_get_no_logs_for_session`),[];if(r.status===401)throw U(`Auth token expired or invalid`),Ai(`error`,`session_get_fail_bad_token`),Error(`Your session has expired.`);return U(`Failed to fetch session logs: ${r.status} ${r.statusText}`),Ai(`error`,`session_get_fail_status`,{status:r.status}),null}catch(e){let t=e;return q(Error(`Error fetching session logs: ${t.message}`)),Ai(`error`,`session_get_fail_status`,{status:t.status}),null}}function irt(e){if(!e)return;let t=e.findLast(e=>`uuid`in e&&e.uuid);return t&&`uuid`in t?t.uuid:void 0}function art(){aZ.clear(),sZ.clear()}var aZ,oZ,ort,sZ,cZ=n((()=>{de(),Ha(),W(),Ei(),h(),Qi(),$a(),Pse(),Po(),Yn(),Vc(),aZ=new Map,oZ=10,ort=500,sZ=new Map}));function srt(e){if(e.type!==`attachment`)return e;let t=e.attachment;if(t.type===`new_file`)return{...e,attachment:{...t,type:`file`,displayPath:$c(yn(),t.filename)}};if(t.type===`new_directory`)return{...e,attachment:{...t,type:`directory`,displayPath:$c(yn(),t.path)}};if(!(`displayPath`in t)){let n=`filename`in t?t.filename:`path`in t?t.path:`skillDir`in t?t.skillDir:void 0;if(n)return{...e,attachment:{...t,displayPath:$c(yn(),n)}}}return e}function crt(e){return lrt(e).messages}function lrt(e){try{let t=e.map(srt),n=new Set($n);for(let e of t)e.type===`user`&&e.permissionMode!==void 0&&!n.has(e.permissionMode)&&(e.permissionMode=void 0);let r=_xt(yxt(Hbt(t))),i=urt(r),a;if(i.kind===`interrupted_turn`){let[e]=F4([$({content:`Continue from where you left off.`,isMeta:!0})]);r.push(e),a={kind:`interrupted_prompt`,message:e}}else a=i;let o=r.findLastIndex(e=>e.type!==`system`&&e.type!==`progress`);return o!==-1&&r[o].type===`user`&&r.splice(o+1,0,k4({content:l3})),{messages:r,turnInterruptionState:a}}catch(e){throw q(e),e}}function urt(e){if(e.length===0)return{kind:`none`};let t=e.findLastIndex(e=>e.type!==`system`&&e.type!==`progress`&&!(e.type===`assistant`&&e.isApiErrorMessage)),n=t===-1?void 0:e[t];return!n||n.type===`assistant`?{kind:`none`}:n.type===`user`?n.isMeta||n.isCompactSummary?{kind:`none`}:bbt(n)?{kind:`interrupted_turn`}:{kind:`interrupted_prompt`,message:n}:n.type===`attachment`?{kind:`interrupted_turn`}:{kind:`none`}}function drt(e){for(let t of e)if(t.type===`attachment`){if(t.attachment.type===`invoked_skills`){let e=t.attachment.skills;for(let t of e)t.name&&t.path&&t.content&&sne(t.name,t.path,t.content,null)}t.attachment.type===`skill_listing`&&Bgt()}Bgt(),Vgt()}async function frt(e){let{messages:t,leafUuids:n}=await H6(e),r=null,i=0;for(let e of t.values()){if(e.isSidechain||!n.has(e.uuid))continue;let t=new Date(e.timestamp).getTime();t>i&&(i=t,r=e)}return r?{messages:w6(E6(t,r)),sessionId:r.sessionId}:{messages:[],sessionId:void 0}}async function prt(e,t){try{let n=null,r=null,i;if(e===void 0){let e=q6(),t=new Set;try{let{listAllLiveSessions:e}=await import(`./udsClient-DSvRPCvR.js`),n=await e();t=new Set(n.flatMap(e=>e.kind&&e.kind!==`interactive`&&e.sessionId?[e.sessionId]:[]))}catch{}n=(await e).find(e=>{let n=z6(e);return!n||!t.has(n)})??null}else if(t){let e=await frt(t);r=e.messages,i=e.sessionId}else typeof e==`string`?(n=await K6(e),i=e):n=e;if(!n&&!r)return null;n&&(B6(n)&&(n=await V6(n)),i||(i=z6(n)),i&&await cf(n,OB(i)),uHe(n),r=n.messages,D6(r)),drt(r);let a=lrt(r);r=a.messages;let o=await Mz(`resume`,{sessionId:i});return r.push(...o),{messages:r,turnInterruptionState:a.turnInterruptionState,fileHistorySnapshots:n?.fileHistorySnapshots,attributionSnapshots:n?.attributionSnapshots,contentReplacements:n?.contentReplacements,contextCollapseCommits:n?.contextCollapseCommits,contextCollapseSnapshot:n?.contextCollapseSnapshot,sessionId:i,agentName:n?.agentName,agentColor:n?.agentColor,agentSetting:n?.agentSetting,customTitle:n?.customTitle,tag:n?.tag,mode:n?.mode,worktreeSession:n?.worktreeSession,prNumber:n?.prNumber,prUrl:n?.prUrl,prRepository:n?.prRepository,fullPath:n?.fullPath,goal:n?.goal}}catch(e){throw q(e),e}}var mrt=n((()=>{vn(),Wt(),AB(),nre(),H0(),ZB(),Qi(),m3(),ff(),Pz(),h8()}));function hrt(){return process.env.ANTHROPIC_BASE_URL||process.env.CLAUDE_CODE_API_BASE_URL||`https://api.anthropic.com`}function lZ(e){U(`[files-api] ${e}`,{level:`error`})}function uZ(e){U(`[files-api] ${e}`)}async function grt(e,t){let n=``;for(let r=1;r<=pZ;r++){let i=await t(r);if(i.done)return i.value;if(n=i.error||`${e} failed`,uZ(`${e} attempt ${r}/${pZ} failed: ${n}`),r<pZ){let t=wrt*2**(r-1);uZ(`Retrying ${e} in ${t}ms...`),await $o(t)}}throw Error(`${n} after ${pZ} attempts`)}async function _rt(e,t){let n=`${t.baseUrl||hrt()}/v1/files/${e}/content`,r={Authorization:`Bearer ${t.oauthToken}`,"anthropic-version":fZ,"anthropic-beta":dZ};return uZ(`Downloading file ${e} from ${n}`),grt(`Download file ${e}`,async()=>{try{let t=await ue.get(n,{headers:r,responseType:`arraybuffer`,timeout:6e4,validateStatus:e=>e<500});if(t.status===200)return uZ(`Downloaded file ${e} (${t.data.length} bytes)`),{done:!0,value:Buffer.from(t.data)};if(t.status===404)throw Error(`File not found: ${e}`);if(t.status===401)throw Error(`Authentication failed: invalid or missing API key`);if(t.status===403)throw Error(`Access denied to file: ${e}`);return{done:!1,error:`status ${t.status}`}}catch(e){if(!ue.isAxiosError(e))throw e;return{done:!1,error:e.message}}})}function vrt(e,t,n){let r=Gc.normalize(n);if(r.startsWith(`..`))return lZ(`Invalid file path: ${n}. Path must not traverse above workspace`),null;let i=Gc.join(e,t,`uploads`),a=[Gc.join(e,t,`uploads`)+Gc.sep,`${Gc.sep}uploads${Gc.sep}`].find(e=>r.startsWith(e)),o=a?r.slice(a.length):r;return Gc.join(i,o)}async function yrt(e,t){let{fileId:n,relativePath:r}=e,i=vrt(yn(),t.sessionId,r);if(!i)return{fileId:n,path:``,success:!1,error:`Invalid file path: ${r}`};try{let e=await _rt(n,t),r=Gc.dirname(i);return await xl.mkdir(r,{recursive:!0}),await xl.writeFile(i,e),uZ(`Saved file ${n} to ${i} (${e.length} bytes)`),{fileId:n,path:i,success:!0,bytesWritten:e.length}}catch(e){return lZ(`Failed to download file ${n}: ${H(e)}`),e instanceof Error&&q(e),{fileId:n,path:i,success:!1,error:H(e)}}}async function brt(e,t,n){let r=Array(e.length),i=0;async function a(){for(;i<e.length;){let n=i++,a=e[n];a!==void 0&&(r[n]=await t(a,n))}}let o=[],s=Math.min(n,e.length);for(let e=0;e<s;e++)o.push(a());return await Promise.all(o),r}async function xrt(e,t,n=Trt){if(e.length===0)return[];uZ(`Downloading ${e.length} file(s) for session ${t.sessionId}`);let r=Date.now(),i=await brt(e,e=>yrt(e,t),n),a=Date.now()-r;return uZ(`Downloaded ${hr(i,e=>e.success)}/${e.length} file(s) in ${a}ms`),i}async function Srt(e,t,n,r){let i=`${n.baseUrl||hrt()}/v1/files`,a={Authorization:`Bearer ${n.oauthToken}`,"anthropic-version":fZ,"anthropic-beta":dZ};uZ(`Uploading file ${e} as ${t}`);let o;try{o=await xl.readFile(e)}catch(e){return J(`tengu_file_upload_failed`,{error_type:`file_read`}),{path:t,error:H(e),success:!1}}let s=o.length;if(s>mZ)return J(`tengu_file_upload_failed`,{error_type:`file_too_large`}),{path:t,error:`File exceeds maximum size of ${mZ} bytes (actual: ${s})`,success:!1};let c=`----FormBoundary${bl()}`,l=Gc.basename(t),u=[];u.push(Buffer.from(`--${c}\r\nContent-Disposition: form-data; name="file"; filename="${l}"\r\nContent-Type: application/octet-stream\r\n\r\n`)),u.push(o),u.push(Buffer.from(`\r
1673
1673
  `)),u.push(Buffer.from(`--${c}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nuser_data\r\n`)),u.push(Buffer.from(`--${c}--\r\n`));let d=Buffer.concat(u);try{return await grt(`Upload file ${t}`,async()=>{try{let n=await ue.post(i,d,{headers:{...a,"Content-Type":`multipart/form-data; boundary=${c}`,"Content-Length":d.length.toString()},timeout:12e4,signal:r?.signal,validateStatus:e=>e<500});if(n.status===200||n.status===201){let r=n.data?.id;return r?(uZ(`Uploaded file ${e} -> ${r} (${s} bytes)`),{done:!0,value:{path:t,fileId:r,size:s,success:!0}}):{done:!1,error:`Upload succeeded but no file ID returned`}}if(n.status===401)throw J(`tengu_file_upload_failed`,{error_type:`auth`}),new hZ(`Authentication failed: invalid or missing API key`);if(n.status===403)throw J(`tengu_file_upload_failed`,{error_type:`forbidden`}),new hZ(`Access denied for upload`);if(n.status===413)throw J(`tengu_file_upload_failed`,{error_type:`size`}),new hZ(`File too large for upload`);return{done:!1,error:`status ${n.status}`}}catch(e){if(e instanceof hZ)throw e;if(ue.isCancel(e))throw new hZ(`Upload canceled`);if(ue.isAxiosError(e))return{done:!1,error:e.message};throw e}})}catch(e){return e instanceof hZ?{path:t,error:e.message,success:!1}:(J(`tengu_file_upload_failed`,{error_type:`network`}),{path:t,error:H(e),success:!1})}}function Crt(e){let t=[],n=e.flatMap(e=>e.split(` `).filter(Boolean));for(let e of n){let n=e.indexOf(`:`);if(n===-1)continue;let r=e.substring(0,n),i=e.substring(n+1);if(!r||!i){lZ(`Invalid file spec: ${e}. Both file_id and path are required`);continue}t.push({fileId:r,relativePath:i})}return t}var dZ,fZ,pZ,wrt,mZ,Trt,hZ,Ert=n((()=>{de(),Cr(),vn(),W(),On(),Qi(),Po(),Da(),dZ=`files-api-2025-04-14,oauth-2025-04-20`,fZ=`2023-06-01`,pZ=3,wrt=500,mZ=500*1024*1024,Trt=5,hZ=class extends Error{constructor(e){super(e),this.name=`UploadNonRetriableError`}}}));function Drt(e=`claude-prompt`,t=`.md`,n){let r=n?.contentHash?vl(`sha256`).update(n.contentHash).digest(`hex`).slice(0,16):bl();return Y(Wc(),`${e}-${r}${t}`)}var Ort=n((()=>{}));async function krt(e,t,n,r,i){let a=r?[`refs/seed/stash`]:[],o=n=>Li(Pi(),[`bundle`,`create`,t,n,...a],{cwd:e,abortSignal:i}),s=await o(`--all`);if(s.code!==0)return{ok:!1,error:`git bundle create --all failed (${s.code}): ${s.stderr.slice(0,200)}`,failReason:`git_error`};let{size:c}=await Nl(t);if(c<=n)return{ok:!0,size:c,scope:`all`};U(`[gitBundle] --all bundle is ${(c/1024/1024).toFixed(1)}MB (> ${(n/1024/1024).toFixed(0)}MB), retrying HEAD-only`);let l=await o(`HEAD`);if(l.code!==0)return{ok:!1,error:`git bundle create HEAD failed (${l.code}): ${l.stderr.slice(0,200)}`,failReason:`git_error`};let{size:u}=await Nl(t);if(u<=n)return{ok:!0,size:u,scope:`head`};U(`[gitBundle] HEAD bundle is ${(u/1024/1024).toFixed(1)}MB, retrying squashed-root`);let d=r?`refs/seed/stash^{tree}`:`HEAD^{tree}`,f=await Li(Pi(),[`commit-tree`,d,`-m`,`seed`],{cwd:e,abortSignal:i});if(f.code!==0)return{ok:!1,error:`git commit-tree failed (${f.code}): ${f.stderr.slice(0,200)}`,failReason:`git_error`};let p=f.stdout.trim();await Li(Pi(),[`update-ref`,`refs/seed/root`,p],{cwd:e});let m=await Li(Pi(),[`bundle`,`create`,t,`refs/seed/root`],{cwd:e,abortSignal:i});if(m.code!==0)return{ok:!1,error:`git bundle create refs/seed/root failed (${m.code}): ${m.stderr.slice(0,200)}`,failReason:`git_error`};let{size:h}=await Nl(t);return h<=n?{ok:!0,size:h,scope:`squashed`}:{ok:!1,error:`Repo is too large to bundle. Please setup GitHub on https://claude.ai/code`,failReason:`too_large`}}async function Art(e,t){let n=Fi(t?.cwd??yn());if(!n)return{success:!1,error:`Not in a git repository`};for(let e of[`refs/seed/stash`,`refs/seed/root`])await Li(Pi(),[`update-ref`,`-d`,e],{cwd:n});let r=await Li(Pi(),[`for-each-ref`,`--count=1`,`refs/`],{cwd:n});if(r.code===0&&r.stdout.trim()===``)return J(`tengu_ccr_bundle_upload`,{outcome:`empty_repo`}),{success:!1,error:`Repository has no commits yet`,failReason:`empty_repo`};let i=await Li(Pi(),[`stash`,`create`],{cwd:n,abortSignal:t?.signal}),a=i.code===0?i.stdout.trim():``,o=a!==``;i.code===0?o&&(U(`[gitBundle] Captured WIP as stash ${a}`),await Li(Pi(),[`update-ref`,`refs/seed/stash`,a],{cwd:n})):U(`[gitBundle] git stash create failed (${i.code}), proceeding without WIP: ${i.stderr.slice(0,200)}`);let s=Drt(`ccr-seed`,`.bundle`);try{let r=jrt,i=await krt(n,s,r,o,t?.signal);if(!i.ok){let e=i;return U(`[gitBundle] ${e.error}`),J(`tengu_ccr_bundle_upload`,{outcome:e.failReason,max_bytes:r}),{success:!1,error:e.error,failReason:e.failReason}}let a=await Srt(s,`_source_seed.bundle`,e,{signal:t?.signal});return a.success?(U(`[gitBundle] Uploaded ${a.size} bytes as file_id ${a.fileId}`),J(`tengu_ccr_bundle_upload`,{outcome:`success`,size_bytes:a.size,scope:i.scope,has_wip:o}),{success:!0,fileId:a.fileId,bundleSizeBytes:a.size,scope:i.scope,hasWip:o}):(J(`tengu_ccr_bundle_upload`,{outcome:`failed`}),{success:!1,error:a.error})}finally{try{await Fl(s)}catch{U(`[gitBundle] Could not delete ${s} (non-fatal)`)}for(let e of[`refs/seed/stash`,`refs/seed/root`])await Li(Pi(),[`update-ref`,`-d`,e],{cwd:n})}}var jrt,Mrt=n((()=>{Da(),Ert(),vn(),W(),zi(),Mi(),Ort(),jrt=100*1024*1024}));function Nrt(e){return e===null?$4(`Session resumed`,`suggestion`):$4(`Session resumed without branch: ${e instanceof En?e.formattedMessage:e.message}`,`warning`)}function Prt(){return $({content:`This session is being continued from another machine. Application state may have changed. The updated working directory is ${Xt()}`,isMeta:!0})}async function Frt(e,t){let n=Aa(e,75),r=`claude/task`;try{let i=Xrt.replace(`{description}`,e),a=(await e9({systemPrompt:Qs([]),userPrompt:i,outputFormat:{type:`json_schema`,schema:{type:`object`,properties:{title:{type:`string`},branch:{type:`string`}},required:[`title`,`branch`],additionalProperties:!1}},signal:t,options:{querySource:`teleport_generate_title`,agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[]}})).message.content?.[0];if(a?.type!==`text`)return{title:n,branchName:r};let o=Ea(a.text.trim()),s=B({title:L(),branch:L()}).safeParse(o);return s.success?{title:s.data.title||n,branchName:s.data.branch||r}:{title:n,branchName:r}}catch(e){return q(Error(`Error generating title and branch: ${e}`)),{title:n,branchName:r}}}async function Irt(){if(!await vie({ignoreUntracked:!0}))throw J(`tengu_teleport_error_git_not_clean`,{}),new En(`Git working directory is not clean. Please commit or stash your changes before using --teleport.`,Ue.red(`Error: Git working directory is not clean. Please commit or stash your changes before using --teleport.
1674
1674
  `))}async function Lrt(e){let t=e?[`fetch`,`origin`,`${e}:${e}`]:[`fetch`,`origin`],{code:n,stderr:r}=await Bi(Pi(),t);if(n!==0)if(e&&r.includes(`refspec`)){U(`Specific branch fetch failed, trying to fetch ref: ${e}`);let{code:t,stderr:n}=await Bi(Pi(),[`fetch`,`origin`,e]);t!==0&&q(Error(`Failed to fetch from remote origin: ${n}`))}else q(Error(`Failed to fetch from remote origin: ${r}`))}async function Rrt(e){let{code:t}=await Bi(Pi(),[`rev-parse`,`--abbrev-ref`,`${e}@{upstream}`]);if(t===0){U(`Branch '${e}' already has upstream set`);return}let{code:n}=await Bi(Pi(),[`rev-parse`,`--verify`,`origin/${e}`]);if(n===0){U(`Setting upstream for '${e}' to 'origin/${e}'`);let{code:t,stderr:n}=await Bi(Pi(),[`branch`,`--set-upstream-to`,`origin/${e}`,e]);U(t===0?`Successfully set upstream for '${e}'`:`Failed to set upstream for '${e}': ${n}`)}else U(`Remote branch 'origin/${e}' does not exist, skipping upstream setup`)}async function zrt(e){let{code:t,stderr:n}=await Bi(Pi(),[`checkout`,e]);if(t!==0){U(`Local checkout failed, trying to checkout from origin: ${n}`);let r=await Bi(Pi(),[`checkout`,`-b`,e,`--track`,`origin/${e}`]);if(t=r.code,n=r.stderr,t!==0){U(`Remote checkout with -b failed, trying without -b: ${n}`);let r=await Bi(Pi(),[`checkout`,`--track`,`origin/${e}`]);t=r.code,n=r.stderr}}if(t!==0)throw J(`tengu_teleport_error_branch_checkout_failed`,{}),new En(`Failed to checkout branch '${e}': ${n}`,Ue.red(`Failed to checkout branch '${e}'\n`));await Rrt(e)}async function gZ(){let{stdout:e}=await Bi(Pi(),[`branch`,`--show-current`]);return e.trim()}function Brt(e,t){return[...crt(e),Prt(),Nrt(t)]}async function Vrt(e){try{return U(`Current branch before teleport: '${await gZ()}'`),e?(U(`Switching to branch '${e}'...`),await Lrt(e),await zrt(e),U(`Branch after checkout: '${await gZ()}'`)):U(`No branch specified, staying on current branch`),{branchName:await gZ(),branchError:null}}catch(e){return{branchName:await gZ(),branchError:jn(e)}}}async function Hrt(e){let t=await zc(),n=t?`${t.owner}/${t.name}`:null,r=e.session_context.sources.find(e=>e.type===`git_repository`);if(!r?.url)return U(n?`Session has no associated repository, proceeding without validation`:`Session has no repo requirement and not in git directory, proceeding`),{status:`no_repo_required`};let i=tle(r.url),a=i?`${i.owner}/${i.name}`:ele(r.url);if(!a)return{status:`no_repo_required`};if(U(`Session is for repository: ${a}, current repo: ${n??`none`}`),!n)return{status:`not_in_repo`,sessionRepo:a,sessionHost:i?.host,currentRepo:null};let o=e=>e.replace(/:\d+$/,``),s=n.toLowerCase()===a.toLowerCase(),c=!t||!i||o(t.host.toLowerCase())===o(i.host.toLowerCase());return s&&c?{status:`match`,sessionRepo:a,currentRepo:n}:{status:`mismatch`,sessionRepo:a,currentRepo:n,sessionHost:i?.host,currentHost:t?.host}}async function Urt(e,t){if(!b9e(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);U(`Resuming code session ID: ${e}`);try{let n=vo()?.accessToken;if(!n)throw J(`tengu_teleport_resume_error`,{error_type:`no_access_token`}),Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let r=await _o();if(!r)throw J(`tengu_teleport_resume_error`,{error_type:`no_org_uuid`}),Error(`Unable to get organization UUID for constructing session URL`);t?.(`validating`);let i=await Hc(e),a=await Hrt(i);switch(a.status){case`match`:case`no_repo_required`:break;case`not_in_repo`:{J(`tengu_teleport_error_repo_not_in_git_dir_sessions_api`,{sessionId:e});let t=a.sessionHost&&a.sessionHost.toLowerCase()!==`github.com`?`${a.sessionHost}/${a.sessionRepo}`:a.sessionRepo;throw new En(`You must run claude --teleport ${e} from a checkout of ${t}.`,Ue.red(`You must run claude --teleport ${e} from a checkout of ${Ue.bold(t)}.\n`))}case`mismatch`:{J(`tengu_teleport_error_repo_mismatch_sessions_api`,{sessionId:e});let t=a.sessionHost&&a.currentHost&&a.sessionHost.replace(/:\d+$/,``).toLowerCase()!==a.currentHost.replace(/:\d+$/,``).toLowerCase(),n=t?`${a.sessionHost}/${a.sessionRepo}`:a.sessionRepo,r=t?`${a.currentHost}/${a.currentRepo}`:a.currentRepo;throw new En(`You must run claude --teleport ${e} from a checkout of ${n}.\nThis repo is ${r}.`,Ue.red(`You must run claude --teleport ${e} from a checkout of ${Ue.bold(n)}.\nThis repo is ${Ue.bold(r)}.\n`))}case`error`:throw new En(a.errorMessage||`Failed to validate session repository`,Ue.red(`Error: ${a.errorMessage||`Failed to validate session repository`}\n`));default:{let e=a.status;throw Error(`Unhandled repo validation status: ${e}`)}}return await Krt(e,r,n,t,i)}catch(e){if(e instanceof En)throw e;let t=jn(e);throw q(t),J(`tengu_teleport_resume_error`,{error_type:`resume_session_id_catch`}),new En(t.message,Ue.red(`Error: ${t.message}\n`))}}async function Wrt(e,t){let n=await Gnt();n.size>0&&(J(`tengu_teleport_errors_detected`,{error_types:Array.from(n).join(`,`),errors_ignored:Array.from(t||[]).join(`,`)}),await new Promise(r=>{e.render((0,_Z.jsx)(EHe,{children:(0,_Z.jsx)(Jnt,{children:(0,_Z.jsx)(Wnt,{errorsToIgnore:t,onComplete:()=>{J(`tengu_teleport_errors_resolved`,{error_types:Array.from(n).join(`,`)}),r()}})})}))}))}async function Grt(e,t,n,r){return await Wrt(e,new Set([`needsGitStash`])),Jrt({initialMessage:t,signal:n,branchName:r,onBundleFail:e=>process.stderr.write(`\n${e}\n`)})}async function Krt(e,t,n,r,i){let a=Date.now();try{U(`[teleport] Starting fetch for session: ${e}`),r?.(`fetching_logs`);let o=Date.now(),s=await rrt(e,n,t);if(s===null&&(U(`[teleport] v2 endpoint returned null, trying session-ingress`),s=await nrt(e,n,t)),U(`[teleport] Session logs fetched in ${Date.now()-o}ms`),s===null)throw Error(`Failed to fetch session logs`);let c=Date.now(),l=s.filter(e=>t6(e)&&!e.isSidechain);U(`[teleport] Filtered ${s.length} entries to ${l.length} messages in ${Date.now()-c}ms`),r?.(`fetching_branch`);let u=i?nle(i):void 0;return u&&U(`[teleport] Found branch: ${u}`),U(`[teleport] Total teleportFromSessionsAPI time: ${Date.now()-a}ms`),{log:l,branch:u}}catch(t){let n=jn(t);throw ue.isAxiosError(t)&&t.response?.status===404?(J(`tengu_teleport_error_session_not_found_404`,{sessionId:e}),new En(`${e} not found.`,`${e} not found.\n${Ue.dim(`Run /status in Work Mate to check your account.`)}`)):(q(n),Error(`Failed to fetch session from Sessions API: ${n.message}`))}}async function qrt(e,t=null,n){let r=vo()?.accessToken;if(!r)throw Error(`No access token for polling`);let i=await _o();if(!i)throw Error(`No org UUID for polling`);let a={...Bc(r),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":i},o=`${Va().BASE_API_URL}/v1/sessions/${e}/events`,s=[],c=t;for(let e=0;e<50;e++){let e=await ue.get(o,{headers:a,params:c?{after_id:c}:void 0,timeout:3e4});if(e.status!==200)throw Error(`Failed to fetch session events: ${e.statusText}`);let t=e.data;if(!t?.data||!Array.isArray(t.data))throw Error(`Invalid events response`);for(let e of t.data)if(e&&typeof e==`object`&&`type`in e){if(e.type===`env_manager_log`||e.type===`control_response`)continue;`session_id`in e&&s.push(e)}if(!t.last_id||(c=t.last_id,!t.has_more))break}if(n?.skipMetadata)return{newEvents:s,lastEventId:c};let l,u;try{let t=await Hc(e);l=nle(t),u=t.session_status}catch(t){U(`teleport: failed to fetch session ${e} metadata: ${t}`,{level:`debug`})}return{newEvents:s,lastEventId:c,branch:l,sessionStatus:u}}async function Jrt(e){let{initialMessage:t,signal:n}=e;try{await Ko();let r=vo()?.accessToken;if(!r)return q(Error(`No access token found for remote session creation`)),null;let i=await _o();if(!i)return q(Error(`Unable to get organization UUID for remote session creation`)),null;if(e.environmentId){let t=`${Va().BASE_API_URL}/v1/sessions`,a={...Bc(r),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":i},o={CLAUDE_CODE_OAUTH_TOKEN:r,...e.environmentVariables??{}},s=null,c=null;if(e.useBundle){let e=await Art({oauthToken:r,sessionId:sn(),baseUrl:Va().BASE_API_URL},{signal:n});if(!e.success)return q(Error(`Bundle upload failed: ${e.error}`)),null;c=e.fileId,J(`tengu_teleport_bundle_mode`,{size_bytes:e.bundleSizeBytes,scope:e.scope,has_wip:e.hasWip,reason:`explicit_env_bundle`})}else{let t=await zc();t&&(s={type:`git_repository`,url:`https://${t.host}/${t.owner}/${t.name}`,revision:e.branchName})}let l={title:e.title||e.description||`Remote task`,events:[],session_context:{sources:s?[s]:[],...c&&{seed_bundle_file_id:c},outcomes:[],environment_variables:o},environment_id:e.environmentId};U(`[teleportToRemote] explicit env ${e.environmentId}, ${Object.keys(o).length} env vars, ${c?`bundle=${c}`:`source=${s?.url??`none`}@${e.branchName??`default`}`}`);let u=await ue.post(t,l,{headers:a,signal:n});if(u.status!==200&&u.status!==201)return q(Error(`CreateSession ${u.status}: ${V(u.data)}`)),null;let d=u.data;return!d||typeof d.id!=`string`?(q(Error(`No session id in response: ${V(u.data)}`)),null):{id:d.id,title:d.title||l.title}}let a=null,o=null,s=null,c=await zc(),l,u;if(e.title&&e.reuseOutcomeBranch)l=e.title,u=e.reuseOutcomeBranch;else{let r=await Frt(e.description||t||`Background task`,n);l=e.title||r.title,u=e.reuseOutcomeBranch||r.branchName}let d=!1,f=`no_git_at_all`,p=Fi(yn()),h=!e.skipBundle&&m(process.env.CCR_FORCE_BUNDLE),g=!e.skipBundle&&p!==null&&(m(process.env.CCR_ENABLE_BUNDLE)||await!1);if(c&&!h?c.host===`github.com`?(d=await L9e(c.owner,c.name,n),f=d?`github_preflight_ok`:`github_preflight_failed`):(d=!0,f=`ghes_optimistic`):h?f=`forced_bundle`:p&&(f=`no_github_remote`),!d&&!g&&c&&(d=!0),d&&c){let{host:t,owner:n,name:r}=c,i=e.branchName??await Oi()??void 0;U(`[teleportToRemote] Git source: ${t}/${n}/${r}, revision: ${i??`none`}`),a={type:`git_repository`,url:`https://${t}/${n}/${r}`,revision:i,...e.reuseOutcomeBranch&&{allow_unrestricted_git_push:!0}},o={type:`git_repository`,git_info:{type:`github`,repo:`${n}/${r}`,branches:[u]}}}if(!a&&g){U(`[teleportToRemote] Bundling (reason: ${f})`);let t=await Art({oauthToken:r,sessionId:sn(),baseUrl:Va().BASE_API_URL},{signal:n});if(!t.success){let n=t;q(Error(`Bundle upload failed: ${n.error}`));let r=c?`. Please setup GitHub on https://claude.ai/code`:``,i;switch(n.failReason){case`empty_repo`:i='Repository has no commits — run `git add . && git commit -m "initial"` then retry';break;case`too_large`:i=`Repo is too large to teleport${r}`;break;case`git_error`:i=`Failed to create git bundle (${n.error})${r}`;break;case void 0:i=`Bundle upload failed: ${n.error}${r}`;break;default:i=`Bundle upload failed: ${n.error}`}return e.onBundleFail?.(i),null}s=t.fileId,J(`tengu_teleport_bundle_mode`,{size_bytes:t.bundleSizeBytes,scope:t.scope,has_wip:t.hasWip,reason:f})}J(`tengu_teleport_source_decision`,{reason:f,path:a?`github`:s?`bundle`:`empty`}),!a&&!s&&U(`[teleportToRemote] No repository detected — session will have an empty sandbox`);let _=await N9e();if(!_||_.length===0)return q(Error(`No environments available for session creation`)),null;U(`Available environments: ${_.map(e=>`${e.environment_id} (${e.name}, ${e.kind})`).join(`, `)}`);let v=zr(),y=e.useDefaultEnvironment?void 0:v?.remote?.defaultEnvironmentId,b=_.find(e=>e.kind===`anthropic_cloud`);if(e.useDefaultEnvironment&&!b){U(`No anthropic_cloud in env list (${_.length} envs); retrying fetchEnvironments`);let e=await N9e();if(b=e?.find(e=>e.kind===`anthropic_cloud`),!b)return q(Error(`No anthropic_cloud environment available after retry (got: ${(e??_).map(e=>`${e.name} (${e.kind})`).join(`, `)}). Silent byoc fallthrough would launch into a dead env — fail fast instead.`)),null;e&&(_=e)}let x=y&&_.find(e=>e.environment_id===y)||b||_.find(e=>e.kind!==`bridge`)||_[0];if(!x)return q(Error(`No environments available for session creation`)),null;y&&U(x.environment_id===y?`Using configured default environment: ${y}`:`Configured default environment ${y} not found, using first available`);let S=x.environment_id;U(`Selected environment: ${S} (${x.name}, ${x.kind})`);let C=`${Va().BASE_API_URL}/v1/sessions`,w={...Bc(r),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":i},T={sources:a?[a]:[],...s&&{seed_bundle_file_id:s},outcomes:o?[o]:[],model:e.model??Qo(),...e.reuseOutcomeBranch&&{reuse_outcome_branches:!0},...e.githubPr&&{github_pr:e.githubPr},...e.source&&{source:e.source}},E=[];e.permissionMode&&E.push({type:`event`,data:{type:`control_request`,request_id:`set-mode-${bl()}`,request:{subtype:`set_permission_mode`,mode:e.permissionMode}}}),t&&E.push({type:`event`,data:{uuid:bl(),session_id:``,type:`user`,parent_tool_use_id:null,message:{role:`user`,content:t}}});let D={title:l,events:E,session_context:T,environment_id:S};U(`Creating session with payload: ${V(D,null,2)}`);let O=await ue.post(C,D,{headers:w,signal:n,validateStatus:e=>e<500});if(!(O.status===200||O.status===201))return q(Error(`API request failed with status ${O.status}: ${O.statusText}\n\nResponse data: ${V(O.data,null,2)}`)),e.onCreateFail?.(`${O.status} ${O.statusText}: ${V(O.data)}`),null;let k=O.data;return!k||typeof k.id!=`string`?(q(Error(`Cannot determine session ID from API response: ${V(O.data)}`)),null):(U(`Successfully created remote session: ${k.id}`),{id:k.id,title:k.title||D.title})}catch(e){return q(jn(e)),null}}async function Yrt(e,t=1e4){let n=vo()?.accessToken;if(!n)return;let r=await _o();if(!r)return;let i={...Bc(n),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":r},a=`${Va().BASE_API_URL}/v1/sessions/${e}/archive`;try{let n=await ue.post(a,{},{headers:i,timeout:t,validateStatus:e=>e<500});n.status===200||n.status===409?U(`[archiveRemoteSession] archived ${e}`):U(`[archiveRemoteSession] ${e} failed ${n.status}: ${V(n.data)}`)}catch(e){q(e)}}var _Z,Xrt,Zrt=n((()=>{de(),Ge(),Wt(),Da(),RJ(),gt(),qnt(),Ha(),Znt(),r9(),cZ(),bo(),mV(),no(),zJ(),mrt(),vn(),W(),Rc(),h(),On(),zi(),Ba(),Mi(),wa(),Qi(),m3(),No(),h8(),Vr(),Yn(),BI(),Vc(),P9e(),Mrt(),_Z=et(),Xrt=`You are coming up with a succinct title and git branch name for a coding session based on the provided description. The title should be clear, concise, and accurately reflect the content of the coding task.
1675
1675
  You should keep it short and simple, ideally no more than 6 words. Avoid using jargon or overly technical terms unless absolutely necessary. The title should be easy to understand for anyone reading it.
@@ -2142,7 +2142,7 @@ Use this when:
2142
2142
 
2143
2143
  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.`})),Uct,Wct,Gct=n((()=>{gt(),Ks(),_t(),Hct(),Uct=ht(()=>ut({description:L().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:R().optional().describe(`Maximum number of results to return (default: 5)`)})),Wct=Os({name:jQ,searchHint:`find search discover skills commands tools capabilities`,maxResultSizeChars:1e4,strict:!0,get inputSchema(){return Uct()},async description(){return Bct},async prompt(){return Vct},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 Ss(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 Ss(t,`Found ${e.count} relevant skill(s):\n\n${n.join(`
2144
2144
 
2145
- `)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-hOERAH9v.js`),{getCwd:i}=await import(`./cwd-DpqwaYHw.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 Kct(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function qct(e){return yoe(e)}function Jct(e){return joe(e)}var MQ=n((()=>{Es()}));function Yct(e,t=$ct){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&&Qct.has(e.status)&&t(Xct(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function Xct(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`<${Vi}>
2145
+ `)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-LcgRjjl3.js`),{getCwd:i}=await import(`./cwd-DpqwaYHw.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 Kct(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function qct(e){return yoe(e)}function Jct(e){return joe(e)}var MQ=n((()=>{Es()}));function Yct(e,t=$ct){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&&Qct.has(e.status)&&t(Xct(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function Xct(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`<${Vi}>
2146
2146
  <${ta}>${e.runId}</${ta}>
2147
2147
  <${Ji}>${Zct}</${Ji}>
2148
2148
  <${Ui}>${e.status}</${Ui}>
@@ -2488,7 +2488,7 @@ ${t?`${t}\n`:``}\
2488
2488
  `,wft=new Set([`select-string`,`get-childitem`,`findstr`,`where.exe`]),Tft=new Set([`get-content`,`get-item`,`test-path`,`resolve-path`,`get-process`,`get-service`,`get-childitem`,`get-location`,`get-filehash`,`get-acl`,`format-hex`]),Eft=new Set([`write-output`,`write-host`]),K$=2e3,Dft=1e3,Oft=15e3,kft=[`start-sleep`,`sleep`],q$=`Enterprise policy requires sandboxing, but sandboxing is not available on native Windows. Shell command execution is blocked on this platform by policy.`,J$=m(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS),Y$=ht(()=>ut({command:L().describe(`The PowerShell command to execute`),timeout:Zy(R().optional()).describe(`Optional timeout in milliseconds (max ${z$()})`),description:L().optional().describe(`Clear, concise description of what this command does in active voice.`),run_in_background:tV(ft().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),dangerouslyDisableSandbox:tV(ft().optional()).describe(`Set this to true to dangerously override sandbox mode and run commands without sandboxing.`)})),Aft=ht(()=>J$?Y$().omit({run_in_background:!0}):Y$()),jft=ht(()=>B({stdout:L().describe(`The standard output of the command`),stderr:L().describe(`The standard error output of the command`),interrupted:ft().describe(`Whether the command was interrupted`),returnCodeInterpretation:L().optional().describe(`Semantic interpretation for non-error exit codes with special meaning`),isImage:ft().optional().describe(`Flag to indicate if stdout contains image data`),persistedOutputPath:L().optional().describe(`Path to persisted full output when too large for inline`),persistedOutputSize:R().optional().describe(`Total output size in bytes when persisted`),backgroundTaskId:L().optional().describe(`ID of the background task if command is running in background`),backgroundedByUser:ft().optional().describe(`True if the user manually backgrounded the command with Ctrl+B`),assistantAutoBackgrounded:ft().optional().describe(`True if the command was auto-backgrounded by the assistant-mode blocking budget`)})),Mft=[`npm`,`yarn`,`pnpm`,`node`,`python`,`python3`,`go`,`cargo`,`make`,`docker`,`terraform`,`webpack`,`vite`,`jest`,`pytest`,`curl`,`Invoke-WebRequest`,`build`,`test`,`serve`,`watch`,`dev`],X$=Os({name:Gs,searchHint:`execute Windows PowerShell commands`,maxResultSizeChars:3e4,strict:!0,async description({description:e}){return e||`Run PowerShell command`},async prompt(){return dft()},isConcurrencySafe(e){return this.isReadOnly?.(e)??!1},isSearchOrReadCommand(e){return e?.command?yft(e.command):{isSearch:!1,isRead:!1}},isReadOnly(e){return!jut(e.command)&&Mut(e.command)},toAutoClassifierInput(e){return e.command},get inputSchema(){return Aft()},get outputSchema(){return jft()},userFacingName(){return`PowerShell`},getToolUseSummary(e){if(!e?.command)return null;let{command:t,description:n}=e;return n||Ma(t,50)},getActivityDescription(e){return e?.command?`Running ${e.description??Ma(e.command,50)}`:`Running command`},isEnabled(){return!0},async validateInput(e){return xft()?{result:!1,message:q$,errorCode:11}:{result:!0}},async checkPermissions(e,t){return await ift(e,t)},renderToolUseMessage:pft,renderToolUseProgressMessage:mft,renderToolUseQueuedMessage:hft,renderToolResultMessage:gft,renderToolUseErrorMessage:_ft,mapToolResultToToolResultBlockParam({interrupted:e,stdout:t,stderr:n,isImage:r,persistedOutputPath:i,persistedOutputSize:a,backgroundTaskId:o,backgroundedByUser:s,assistantAutoBackgrounded:c},l){if(r){let e=uSe(t,l);if(e)return e}let u=t;if(i){let e=Fy(t?t.replace(/^(\s*\n)+/,``).trimEnd():``,Ry);u=Ny({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+=G$),d+=`<error>Command was aborted before completion</error>`);let f=``;if(o){let e=V8(o);f=c?`Command exceeded the assistant-mode blocking budget (${Oft/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(`
2489
2489
  `),is_error:e}},async call(e,t,n,r,i){if(xft())throw Error(q$);let{abortController:a,setAppState:o,setToolJSX:s}=t,c=!t.agentId,l=0;try{let n=Sft({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||Jqe(e.command,u.code,u.stdout);let d=u.interrupted&&a.signal.reason===`interrupt`,f=``;if(c&&pSe(t.getAppState().toolPermissionContext)&&(f=Cy(``)),u.backgroundTaskId){let t=BB(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(`
2490
2490
  `),interrupted:!1,backgroundTaskId:u.backgroundTaskId,backgroundedByUser:u.backgroundedByUser,assistantAutoBackgrounded:u.assistantAutoBackgrounded}}}let p=new Za,m=(u.stdout||``).trimEnd();p.append(m+G$);let h=Ult(e.command,u.code,m,u.stderr||``),g=cSe(p.toString()),_=BB(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 bn(g,u.stderr||``,u.code,u.interrupted);let v=64*1024*1024,y,b;if(u.outputFilePath&&u.outputTaskId)try{let e=await Nl(u.outputFilePath);b=e.size,await jy();let t=Ay(u.outputTaskId,!1);e.size>v&&await pue(u.outputFilePath,v);try{await Tl(u.outputFilePath,t)}catch{await wl(u.outputFilePath,t)}y=t}catch{}let x=Sy(g),S=g;if(x){let e=await dSe(g,u.outputFilePath,b);e?S=e:x=!1}let C=[u.stderr||``,f].filter(Boolean).join(`
2491
- `);return J(`tengu_powershell_tool_command_executed`,{command_type:W$(e.command),stdout_length:S.length,stderr_length:C.length,exit_code:u.code,interrupted: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 Nb(e.stdout)||Nb(e.stderr)}})}));function Nft(e){let t=e.toLowerCase();return Ift.includes(t)?t:null}function Pft(){let e=Q$(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function Q$(){return[dJ,LZ,SW,...oy()?[]:[fU,lU],VZ,ex,xq,QH,Tq,gU,jZ,JZ,xJ,cQ,uct,Tst,...ax()?[_ct,wct,jct,Rct]:[],...m(process.env.ENABLE_LSP_TOOL)?[nQ]:[],...dle()?[zot,Xot]:[],...t1?[t1]:[],Fft,Fit,Zit,...n1()?[n1()]:[],Wct,Aw,tD,...uz()?[wz]:[],got]}function $$(e,t){return e.filter(e=>!w9(t,e))}function e1(e,t){let n=r1(e),r=$$(t,e),i=(e,t)=>e.name.localeCompare(t.name);return uh([...n].sort(i).concat(r.sort(i)),`name`)}var t1,Fft,n1,Ift,r1,i1=n((()=>{Ks(),fJ(),B7e(),CW(),Sq(),nx(),$H(),pU(),Eq(),Oit(),Iit(),Qit(),aat(),_U(),HZ(),hat(),uU(),Sat(),sot(),jw(),nD(),Tz(),_ot(),jot(),Bot(),Zot(),Est(),dct(),vct(),Tct(),Mct(),zct(),dh(),vz(),hx(),xs(),Cs(),Gct(),Ilt(),j9(),sy(),h(),qs(),fle(),Dq(),t1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(Blt(),e(Llt)).VerifyPlanExecutionTool:null,Fft=Flt(),n1=()=>Uoe()?(Z$(),e(U$)).PowerShellTool:null,Ift=[`default`],r1=e=>{if(m(process.env.CLAUDE_CODE_SIMPLE))return $$([SW,ex,xq],e);let t=new Set([Aw.name,tD.name,Is]),n=$$(Q$().filter(e=>!t.has(e.name)),e);p8e()&&n.some(e=>Ws(e,`REPL`))&&(n=n.filter(e=>!m8e.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),Lft,a1,Rft=n((()=>{b(),Lft=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}[Lft](){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 zft(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var Bft=n((()=>{}));async function*Vft(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let c=e.getAppState().toolPermissionContext.mode,u=a;for await(let a of uEt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:j0({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:j0({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&GT(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;J(`tengu_post_tool_hook_error`,{messageID:r,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){q(e)}}async function*Hft(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let l=e.getAppState().toolPermissionContext.mode;for await(let d of dEt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}d.message&&!(d.message.type===`attachment`&&d.message.attachment.type===`hook_blocking_error`)&&(yield{message:d.message}),d.blockingError&&(yield{message:j0({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:j0({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;J(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){q(e)}}async function Uft(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 U(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await skt(t,l,r);return d===null?(U(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`?(U(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(U(`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 U(`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*Wft(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of lEt(t.name,r,n,e,s.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(l.message&&(yield{type:`message`,message:{message:l.message}}),l.blockingError){let e=iEt(`PreToolUse:${t.name}`,l.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(l.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},l.stopReason&&(yield{type:`stopReason`,stopReason:l.stopReason})),l.permissionBehavior!==void 0){U(`Hook result has permissionBehavior=${l.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:l.hookSource,reason:l.hookPermissionDecisionReason};l.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:l.updatedInput,decisionReason:e}}:l.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:l.updatedInput,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${zft(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${zft(l.permissionBehavior)} this tool`,decisionReason:e}}}if(l.updatedInput&&l.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:l.updatedInput}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:j0({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){J(`tengu_pre_tool_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:j0({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){q(n);let s=Date.now()-c;J(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:s,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...o?{mcpServerType:o}:{},...a?{requestId:a}:{}}),yield{type:`message`,message:{message:j0({type:`hook_error_during_execution`,content:rQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){q(e),yield{type:`stop`};return}}var Gft=n((()=>{Da(),Cc(),H0(),W(),_7(),Qi(),Bft(),j9(),iQ(),YT()}));function Kft(){return s1||(s1=import(`./toolEventObserver-D7WbjgFR.js`).catch(e=>{throw s1=void 0,e})),s1}function qft(e){if(e instanceof Hn)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Cn(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 Jft(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 Yft(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 Jft(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 Xft(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 Zft(e,t){if(!e.startsWith(`mcp__`))return;let n=Fr(e);if(n)return t.find(e=>ri(e.name)===n.serverName)}function Qft(e,t){let n=Zft(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function $ft(e,t){let n=Zft(e,t);if(n?.type===`connected`)return JT(n.config)}async function*o1(e,t,n,r){let i=e.name,a=_s(r.options.tools,i);if(!a){let e=_s(Q$(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=Qft(i,r.options.mcpClients),l=$ft(i,r.options.mcpClients);if(!a){let n=Dc(i);U(`Unknown tool ${i}: ${e.id}`),J(`tengu_tool_use_error`,{error:`No such tool available: ${n}`,toolName:n,toolUseID:e.id,isMcp:i.startsWith(`mcp__`),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(i,c,l)}),yield{message:$({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){J(`tengu_tool_use_cancelled`,{toolName:Dc(a.name),toolUseID:e.id,isMcp:a.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(a.name,c,l)});let n=vbt(e.id);n.content=E4(o3),yield{message:$({content:[n],toolUseResult:o3,sourceToolAssistantUUID:t.uuid})};return}for await(let i of ept(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){q(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:$({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 ept(e,t,n,r,i,a,o,s,c,l){let u=new a1;return npt(e,t,n,r,i,a,o,s,c,l,n=>{J(`tengu_tool_use_progress`,{messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),u.enqueue({message:_bt({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 tpt(e,t,n){if(!uz()||!dz(n)||!As(e)||mz(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: ${Vs}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Vs}("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: ${Vs}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function npt(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=uot(e.name,d.error),i=tpt(e,r.messages,r.options.tools);return i&&(J(`tengu_deferred_tool_schema_not_sent`,{toolName:Dc(e.name),isMcp:e.isMcp??!1}),n+=i),U(`${e.name} tool input error: ${n.slice(0,200)}`),J(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),[{message:$({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 U(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),J(`tengu_tool_use_error`,{messageID:o,toolName:Dc(e.name),error:f.message,errorCode:f.errorCode,isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),[{message:$({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();g$e(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 Wft(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 qt()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:$({content:[vbt(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;qt()?.observe(`pre_tool_hook_duration_ms`,S),S>=c1&&U(`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)),Vce(e.name,C,Mc()?V(m):void 0),Kce();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await Uft(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=c1&&w===`auto`&&U(`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=Yft(D.decisionReason,D.behavior);Nc(`tool_decision`,{decision:t,source:n,tool_name:Dc(e.name)}),F0e(e.name)&&I0e(e,m,t,n).then(e=>dne()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:j0({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){U(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);Lce(`reject`,n?.source||`unknown`),Fc(),J(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Dc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)});let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let u=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],d=D.behavior===`ask`?D.contentBlocks:void 0;d?.length&&u.push(...d);let f;if(d?.length){let e=hr(d,e=>e.type===`image`);if(e>0){let t=Xft(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:$({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}J(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Dc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=wce(m),A={};if(kce()){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=Cce(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=Tce(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);Lce(ee?.decision||`unknown`,ee?.source||`unknown`),Uce();let te=Date.now();Use(`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})}),d=ple()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await Kft();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(Xte(f),d.data&&typeof d.data==`object`){let t={};e.name===`Read`&&`content`in d.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(d.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in d.data&&(t.diff=String(d.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 d.data&&(t.output=String(d.data.output))),Object.keys(t).length>0&&qce(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:j0({type:`structured_output`,data:d.structured_output})}),Gce({success:!0}),Fc(d.data&&typeof d.data==`object`?V(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:V(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=xc(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=xc(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=Sce(e.command,e._simulatedSedEdit?.filePath)}}if(J(`tengu_tool_use_success`,{messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,durationMs:f,preToolHookDurationMs:S,toolResultSizeBytes:b,...x!==void 0&&{fileExtension:x},queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),kce()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&d.data&&typeof d.data==`object`&&`stdout`in d.data){let e=Uqe(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=GT(e)?qT(e.name):null;Nc(`tool_result`,{tool_name:Dc(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},tool_result_size_bytes:String(b),...ee&&{decision_source:ee.source,decision_type:ee.decision},...C&&{mcp_server_scope:C}});let w=d.data,T=[],E=d.contextModifier,O=d.mcpMeta;async function ne(n,i){let o=[i?await jSe(i,e.name,e.maxResultSizeChars):await Py(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=hr(s,e=>e.type===`image`);if(e>0){let t=Xft(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:$({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:O,sourceToolAssistantUUID:a.uuid}),contextModifier:E?{toolUseID:t,modifyContext:E}:void 0})}GT(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Vft(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)GT(e)&&(w=n.updatedMCPToolOutput);else if(GT(e)){if(T.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&&re.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&&re.push({command:e.command,durationMs:e.durationMs})}let ae=Date.now()-ie;if(ae>=c1&&U(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),GT(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:j0({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of T)p.push(e);return p}catch(n){let i=Date.now()-te;if(Xte(i),Gce({success:!1,error:H(n)}),Fc(),n instanceof SM&&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 Sn)){let a=H(n);U(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof bn||q(n),J(`tengu_tool_use_error`,{messageID:o,toolName:Dc(e.name),error:qft(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)});let u=GT(e)?qT(e.name):null;Nc(`tool_result`,{tool_name:Dc(e.name),use_id:t,success:`false`,duration_ms:String(i),error:H(n),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=rQ(n),d=n instanceof Sn,f=[];for await(let n of Hft(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:$({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof wM?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{Vse(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var s1,c1,rpt=n((()=>{Da(),Cc(),Wt(),H0e(),Ks(),HW(),bs(),Ns(),Fs(),vs(),Ps(),ds(),SH(),zs(),i1(),Cr(),H0(),W(),On(),_7(),Qi(),m3(),ac(),Yn(),Rft(),Ic(),Pc(),iQ(),zy(),vz(),BM(),Ur(),$r(),YT(),Gft(),mle(),c1=2e3}));function ipt(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var l1,apt=n((()=>{m3(),Ks(),bs(),oD(),rpt(),b(),l1=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=iD(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=_s(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[$({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 $({content:[{type:`tool_result`,content:E4(s3),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return $({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 $({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=_s(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=iD(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=o1(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};ipt(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 opt(){d1&&(Ra().clearMarks(),f1.clear(),m1=null,p1++,u1(`query_user_input_received`))}function u1(e){if(!d1)return;let t=Ra();if(t.mark(e),f1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&m1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(m1=e[e.length-1]?.startTime??0)}}function spt(){d1&&u1(`query_profile_end`)}function cpt(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 lpt(){if(!d1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=Ra().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${p1}`),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(nae(e,s,o.name,f1.get(o.name),10,9,cpt(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: ${ja(a)}ms`),t.push(` - Pre-request overhead: ${ja(e)}ms (${r}%)`),t.push(` - Network latency: ${ja(n)}ms (${o}%)`)}else t.push(`Total time: ${ja(s)}ms`);return t.push(upt(e,n)),t.push(`=`.repeat(80)),t.join(`
2491
+ `);return J(`tengu_powershell_tool_command_executed`,{command_type:W$(e.command),stdout_length:S.length,stderr_length:C.length,exit_code:u.code,interrupted: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 Nb(e.stdout)||Nb(e.stderr)}})}));function Nft(e){let t=e.toLowerCase();return Ift.includes(t)?t:null}function Pft(){let e=Q$(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function Q$(){return[dJ,LZ,SW,...oy()?[]:[fU,lU],VZ,ex,xq,QH,Tq,gU,jZ,JZ,xJ,cQ,uct,Tst,...ax()?[_ct,wct,jct,Rct]:[],...m(process.env.ENABLE_LSP_TOOL)?[nQ]:[],...dle()?[zot,Xot]:[],...t1?[t1]:[],Fft,Fit,Zit,...n1()?[n1()]:[],Wct,Aw,tD,...uz()?[wz]:[],got]}function $$(e,t){return e.filter(e=>!w9(t,e))}function e1(e,t){let n=r1(e),r=$$(t,e),i=(e,t)=>e.name.localeCompare(t.name);return uh([...n].sort(i).concat(r.sort(i)),`name`)}var t1,Fft,n1,Ift,r1,i1=n((()=>{Ks(),fJ(),B7e(),CW(),Sq(),nx(),$H(),pU(),Eq(),Oit(),Iit(),Qit(),aat(),_U(),HZ(),hat(),uU(),Sat(),sot(),jw(),nD(),Tz(),_ot(),jot(),Bot(),Zot(),Est(),dct(),vct(),Tct(),Mct(),zct(),dh(),vz(),hx(),xs(),Cs(),Gct(),Ilt(),j9(),sy(),h(),qs(),fle(),Dq(),t1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(Blt(),e(Llt)).VerifyPlanExecutionTool:null,Fft=Flt(),n1=()=>Uoe()?(Z$(),e(U$)).PowerShellTool:null,Ift=[`default`],r1=e=>{if(m(process.env.CLAUDE_CODE_SIMPLE))return $$([SW,ex,xq],e);let t=new Set([Aw.name,tD.name,Is]),n=$$(Q$().filter(e=>!t.has(e.name)),e);p8e()&&n.some(e=>Ws(e,`REPL`))&&(n=n.filter(e=>!m8e.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),Lft,a1,Rft=n((()=>{b(),Lft=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}[Lft](){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 zft(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var Bft=n((()=>{}));async function*Vft(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let c=e.getAppState().toolPermissionContext.mode,u=a;for await(let a of uEt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:j0({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:j0({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&GT(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;J(`tengu_post_tool_hook_error`,{messageID:r,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){q(e)}}async function*Hft(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let l=e.getAppState().toolPermissionContext.mode;for await(let d of dEt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}d.message&&!(d.message.type===`attachment`&&d.message.attachment.type===`hook_blocking_error`)&&(yield{message:d.message}),d.blockingError&&(yield{message:j0({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:j0({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;J(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){q(e)}}async function Uft(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 U(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await skt(t,l,r);return d===null?(U(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`?(U(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(U(`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 U(`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*Wft(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of lEt(t.name,r,n,e,s.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(l.message&&(yield{type:`message`,message:{message:l.message}}),l.blockingError){let e=iEt(`PreToolUse:${t.name}`,l.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(l.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},l.stopReason&&(yield{type:`stopReason`,stopReason:l.stopReason})),l.permissionBehavior!==void 0){U(`Hook result has permissionBehavior=${l.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:l.hookSource,reason:l.hookPermissionDecisionReason};l.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:l.updatedInput,decisionReason:e}}:l.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:l.updatedInput,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${zft(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${zft(l.permissionBehavior)} this tool`,decisionReason:e}}}if(l.updatedInput&&l.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:l.updatedInput}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:j0({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){J(`tengu_pre_tool_hooks_cancelled`,{toolName:Dc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:j0({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){q(n);let s=Date.now()-c;J(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Dc(t.name),isMcp:t.isMcp??!1,duration:s,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...o?{mcpServerType:o}:{},...a?{requestId:a}:{}}),yield{type:`message`,message:{message:j0({type:`hook_error_during_execution`,content:rQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){q(e),yield{type:`stop`};return}}var Gft=n((()=>{Da(),Cc(),H0(),W(),_7(),Qi(),Bft(),j9(),iQ(),YT()}));function Kft(){return s1||(s1=import(`./toolEventObserver-Cq-uBb0-.js`).catch(e=>{throw s1=void 0,e})),s1}function qft(e){if(e instanceof Hn)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Cn(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 Jft(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 Yft(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 Jft(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 Xft(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 Zft(e,t){if(!e.startsWith(`mcp__`))return;let n=Fr(e);if(n)return t.find(e=>ri(e.name)===n.serverName)}function Qft(e,t){let n=Zft(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function $ft(e,t){let n=Zft(e,t);if(n?.type===`connected`)return JT(n.config)}async function*o1(e,t,n,r){let i=e.name,a=_s(r.options.tools,i);if(!a){let e=_s(Q$(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=Qft(i,r.options.mcpClients),l=$ft(i,r.options.mcpClients);if(!a){let n=Dc(i);U(`Unknown tool ${i}: ${e.id}`),J(`tengu_tool_use_error`,{error:`No such tool available: ${n}`,toolName:n,toolUseID:e.id,isMcp:i.startsWith(`mcp__`),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(i,c,l)}),yield{message:$({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){J(`tengu_tool_use_cancelled`,{toolName:Dc(a.name),toolUseID:e.id,isMcp:a.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(a.name,c,l)});let n=vbt(e.id);n.content=E4(o3),yield{message:$({content:[n],toolUseResult:o3,sourceToolAssistantUUID:t.uuid})};return}for await(let i of ept(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){q(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:$({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 ept(e,t,n,r,i,a,o,s,c,l){let u=new a1;return npt(e,t,n,r,i,a,o,s,c,l,n=>{J(`tengu_tool_use_progress`,{messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),u.enqueue({message:_bt({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 tpt(e,t,n){if(!uz()||!dz(n)||!As(e)||mz(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: ${Vs}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Vs}("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: ${Vs}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function npt(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=uot(e.name,d.error),i=tpt(e,r.messages,r.options.tools);return i&&(J(`tengu_deferred_tool_schema_not_sent`,{toolName:Dc(e.name),isMcp:e.isMcp??!1}),n+=i),U(`${e.name} tool input error: ${n.slice(0,200)}`),J(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),[{message:$({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 U(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),J(`tengu_tool_use_error`,{messageID:o,toolName:Dc(e.name),error:f.message,errorCode:f.errorCode,isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),[{message:$({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();g$e(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 Wft(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 qt()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:$({content:[vbt(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;qt()?.observe(`pre_tool_hook_duration_ms`,S),S>=c1&&U(`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)),Vce(e.name,C,Mc()?V(m):void 0),Kce();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await Uft(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=c1&&w===`auto`&&U(`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=Yft(D.decisionReason,D.behavior);Nc(`tool_decision`,{decision:t,source:n,tool_name:Dc(e.name)}),F0e(e.name)&&I0e(e,m,t,n).then(e=>dne()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:j0({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){U(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);Lce(`reject`,n?.source||`unknown`),Fc(),J(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Dc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)});let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let u=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],d=D.behavior===`ask`?D.contentBlocks:void 0;d?.length&&u.push(...d);let f;if(d?.length){let e=hr(d,e=>e.type===`image`);if(e>0){let t=Xft(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:$({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}J(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Dc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=wce(m),A={};if(kce()){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=Cce(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=Tce(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);Lce(ee?.decision||`unknown`,ee?.source||`unknown`),Uce();let te=Date.now();Use(`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})}),d=ple()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await Kft();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(Xte(f),d.data&&typeof d.data==`object`){let t={};e.name===`Read`&&`content`in d.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(d.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in d.data&&(t.diff=String(d.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 d.data&&(t.output=String(d.data.output))),Object.keys(t).length>0&&qce(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:j0({type:`structured_output`,data:d.structured_output})}),Gce({success:!0}),Fc(d.data&&typeof d.data==`object`?V(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:V(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=xc(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=xc(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=Sce(e.command,e._simulatedSedEdit?.filePath)}}if(J(`tengu_tool_use_success`,{messageID:o,toolName:Dc(e.name),isMcp:e.isMcp??!1,durationMs:f,preToolHookDurationMs:S,toolResultSizeBytes:b,...x!==void 0&&{fileExtension:x},queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)}),kce()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&d.data&&typeof d.data==`object`&&`stdout`in d.data){let e=Uqe(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=GT(e)?qT(e.name):null;Nc(`tool_result`,{tool_name:Dc(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},tool_result_size_bytes:String(b),...ee&&{decision_source:ee.source,decision_type:ee.decision},...C&&{mcp_server_scope:C}});let w=d.data,T=[],E=d.contextModifier,O=d.mcpMeta;async function ne(n,i){let o=[i?await jSe(i,e.name,e.maxResultSizeChars):await Py(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=hr(s,e=>e.type===`image`);if(e>0){let t=Xft(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:$({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:O,sourceToolAssistantUUID:a.uuid}),contextModifier:E?{toolUseID:t,modifyContext:E}:void 0})}GT(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Vft(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)GT(e)&&(w=n.updatedMCPToolOutput);else if(GT(e)){if(T.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&&re.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&&re.push({command:e.command,durationMs:e.durationMs})}let ae=Date.now()-ie;if(ae>=c1&&U(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),GT(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:j0({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of T)p.push(e);return p}catch(n){let i=Date.now()-te;if(Xte(i),Gce({success:!1,error:H(n)}),Fc(),n instanceof SM&&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 Sn)){let a=H(n);U(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof bn||q(n),J(`tengu_tool_use_error`,{messageID:o,toolName:Dc(e.name),error:qft(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Tc(e.name,c,l)});let u=GT(e)?qT(e.name):null;Nc(`tool_result`,{tool_name:Dc(e.name),use_id:t,success:`false`,duration_ms:String(i),error:H(n),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=rQ(n),d=n instanceof Sn,f=[];for await(let n of Hft(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:$({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof wM?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{Vse(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var s1,c1,rpt=n((()=>{Da(),Cc(),Wt(),H0e(),Ks(),HW(),bs(),Ns(),Fs(),vs(),Ps(),ds(),SH(),zs(),i1(),Cr(),H0(),W(),On(),_7(),Qi(),m3(),ac(),Yn(),Rft(),Ic(),Pc(),iQ(),zy(),vz(),BM(),Ur(),$r(),YT(),Gft(),mle(),c1=2e3}));function ipt(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var l1,apt=n((()=>{m3(),Ks(),bs(),oD(),rpt(),b(),l1=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=iD(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=_s(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[$({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 $({content:[{type:`tool_result`,content:E4(s3),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return $({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 $({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=_s(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=iD(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=o1(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};ipt(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 opt(){d1&&(Ra().clearMarks(),f1.clear(),m1=null,p1++,u1(`query_user_input_received`))}function u1(e){if(!d1)return;let t=Ra();if(t.mark(e),f1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&m1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(m1=e[e.length-1]?.startTime??0)}}function spt(){d1&&u1(`query_profile_end`)}function cpt(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 lpt(){if(!d1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=Ra().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${p1}`),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(nae(e,s,o.name,f1.get(o.name),10,9,cpt(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: ${ja(a)}ms`),t.push(` - Pre-request overhead: ${ja(e)}ms (${r}%)`),t.push(` - Network latency: ${ja(n)}ms (${o}%)`)}else t.push(`Total time: ${ja(s)}ms`);return t.push(upt(e,n)),t.push(`=`.repeat(80)),t.join(`
2492
2492
  `)}function upt(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)} ${ja(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)} ${ja(a).padStart(10)}ms`)),i.join(`
2493
2493
  `)}function dpt(){d1&&U(lpt())}var d1,f1,p1,m1,h1=n((()=>{W(),h(),Na(),d1=m(process.env.CLAUDE_CODE_PROFILE_QUERY),f1=new Map,p1=0,m1=null}));async function fpt(e){let t;do t=await e.next();while(!t.done);return t.value}async function*ppt(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 mpt(e){let t=[];for await(let n of e)t.push(n);return t}async function*hpt(e){for(let t of e)yield t}var g1=n((()=>{}));function gpt(){return parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY||``,10)||10}async function*_pt(e,t,n,r){let i=r;for(let{isConcurrencySafe:r,blocks:a}of vpt(e,i))if(r){let e={};for await(let r of bpt(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 ypt(a,t,n,i))e.newContext&&(i=e.newContext),yield{message:e.message,newContext:i}}function vpt(e,t){return e.reduce((e,n)=>{let r=_s(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*ypt(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 o1(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};xpt(r,a.id)}}async function*bpt(e,t,n,r){yield*ppt(e.map(async function*(e){r.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),yield*o1(e,t.find(t=>Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_use`&&t.id===e.id)),n,r),xpt(r,e.id)}),gpt())}function xpt(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var Spt=n((()=>{Ks(),g1(),rpt()}));async function Cpt(e,t){let n=Y(e,`state.json`),r;try{r=JSON.parse(dl(n,`utf-8`))}catch{return}let i=wpt(t);r.status=i,r.updatedAt=new Date().toISOString(),Ble(n,JSON.stringify(r,null,2),`utf-8`)}function wpt(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 Tpt=n((()=>{}));function Ept(){let e=Xr().autoDreamEnabled;return e!==void 0&&e}var Dpt=n((()=>{Vr()}));async function Opt(e,t){try{let n=(await kl(e,{recursive:!0})).filter(e=>e.endsWith(`.md`)&&Kc(e)!==`MEMORY.md`);return(await Promise.allSettled(n.map(async n=>{let r=Y(e,n),{content:i,mtimeMs:a}=await qy(r,0,jpt,void 0,t),{frontmatter:o}=od(i,r);return{filename:n,filePath:r,mtimeMs:a,description:o.description||null,type:Kfe(o.type)}}))).filter(e=>e.status===`fulfilled`).map(e=>e.value).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,Apt)}catch{return[]}}function kpt(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(`
2494
2494
  `)}var Apt,jpt,Mpt=n((()=>{gd(),Xy(),Nd(),Apt=200,jpt=30}));function Npt(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: ${gs}, ${rs}, ${Us}, read-only ${js} (ls/find/cat/stat/wc/head/tail and similar), and ${ws}/${ks} for paths inside the memory directory only. ${js} rm is not permitted. All other tools — MCP, Agent, write-capable ${js}, etc — will be denied.`,``,`You have a limited turn budget. ${ws} requires a prior ${gs} of the same file, so the efficient strategy is: turn 1 — issue all ${gs} calls in parallel for every file you might update; turn 2 — issue all ${ks}/${ws} 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(`
@@ -2548,7 +2548,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
2548
2548
 
2549
2549
  Sessions since last consolidation (${c.length}):
2550
2550
  ${c.map(e=>`- ${e}`).join(`
2551
- `)}`)})],cacheSafeParams:P1(t),canUseTool:v1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:Zpt(p,d)});s9e(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&i9e(i)&&i.filesTouched.length>0&&n({...axt(i.filesTouched),verb:`Improved`}),U(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),J(`tengu_auto_dream_completed`,{cache_read:r.totalUsage.cache_read_input_tokens,cache_created:r.totalUsage.cache_creation_input_tokens,output:r.totalUsage.output_tokens,sessions_reviewed:c.length})}catch(e){if(f.signal.aborted){U(`[autoDream] aborted by user`);return}U(`[autoDream] fork failed: ${e.message}`),J(`tengu_auto_dream_failed`,{}),c9e(p,d),await $7e(u)}}}function Zpt(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)}o9e(e,{text:r.trim(),toolUseCount:i},a,t)}}async function Qpt(e,t){await x1?.(e,t)}var $pt,emt,x1,tmt=n((()=>{R1(),m3(),W(),Da(),hi(),Dpt(),h8(),Wt(),Wpt(),Kpt(),wJ(),EJ(),Ns(),vs(),$pt=600*1e3,emt={minHours:24,minSessions:5},x1=null}));async function*nmt(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`)&&Lmt(P1(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=Cpt(process.env.CLAUDE_JOB_DIR,e).catch(e=>{U(`[job] classifier error: ${H(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-XDBnxTiF.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&Jmt(l),!a.agentId&&eie()&&!u&&import(`./extractMemories-WmPLOLUT.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&Qpt(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=pEt(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=$({content:aEt(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 j0({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return J(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield j4({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield rxt(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=ib(`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 J(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield $4(`Stop hook failed: ${H(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var rmt=n((()=>{ob(),hi(),Da(),H0(),W(),On(),_7(),m3(),Tpt(),tmt(),U1(),h(),R1()}));function imt(){return{sessionId:sn(),gates:{streamingToolExecution:!1,emitToolUseSummaries:m(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!m(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var amt=n((()=>{Wt(),h()}));function omt(){return{callModel:vOt,microcompact:VR,autocompact:n1e,uuid:bl}}var smt=n((()=>{r9(),sG(),UR()}));function S1(e,t){return parseFloat(e)*fmt[t.toLowerCase()]}function cmt(e){let t=e.match(umt);if(t)return S1(t[1],t[2]);let n=e.match(dmt);if(n)return S1(n[1],n[2]);let r=e.match(C1);return r?S1(r[1],r[2]):null}function lmt(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 umt,dmt,C1,fmt,pmt=n((()=>{umt=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,dmt=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,C1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(C1.source,`gi`),fmt={k:1e3,m:1e6,b:1e9}}));function mmt(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function hmt(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<w1&&e.lastDeltaTokens<w1;return!s&&i<n*gmt?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:lmt(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 gmt,w1,_mt=n((()=>{pmt(),gmt=.9,w1=500}));function T1(){return Y(p(),`sessions`)}function vmt(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`||e===`daemon`||e===`daemon-worker`)return e}function ymt(){return vmt()===`bg`}async function bmt(){let e=vmt()??`interactive`,t=T1(),n=Y(t,`${process.pid}.json`);Gn(async()=>{try{await Fl(n)}catch{}});try{return await El(t,{recursive:!0,mode:448}),await Cl(t,448),await Il(n,V({pid:process.pid,sessionId:sn(),cwd:Xt(),startedAt:Date.now(),kind:e,entrypoint:process.env.CLAUDE_CODE_ENTRYPOINT,name:process.env.CLAUDE_CODE_SESSION_NAME,logPath:process.env.CLAUDE_CODE_SESSION_LOG,agent:process.env.CLAUDE_CODE_AGENT})),_te(e=>{E1({sessionId:e})}),!0}catch(e){return U(`[concurrentSessions] register failed: ${H(e)}`),!1}}async function E1(e){let t=Y(T1(),`${process.pid}.json`);try{await Il(t,V({...kn(await Ol(t,`utf8`)),...e}))}catch(e){U(`[concurrentSessions] updatePidFile failed: ${H(e)}`)}}async function xmt(e){e&&await E1({name:e})}async function Smt(e){await E1({bridgeSessionId:e})}async function Cmt(e){await E1({...e,updatedAt:Date.now()})}async function wmt(){let e=T1(),t;try{t=await kl(e)}catch(e){return Mn(e)||U(`[concurrentSessions] readdir failed: ${H(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}yc(t)?n++:la()!==`wsl`&&Fl(Y(e,r)).catch(()=>{})}return n}var D1=n((()=>{Wt(),Jn(),W(),h(),On(),bc(),ua(),Yn()}));function Tmt(){return ymt()?Date.now()-O1>=Dmt:!1}function Emt(e){O1=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`}`)}}Cmt({status:r,waitingFor:i}).catch(e=>{U(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){U(`[taskSummary] error: ${e}`)}}var Dmt,O1,Omt=n((()=>{D1(),W(),Dmt=3e4,O1=0}));function*k1(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 $({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function kmt(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function Amt(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*A1(e){let t=[],n=[],r,i=!1,a;try{r=yield*jmt(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await T0e({commands:n,outcome:Amt({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)hL(t)}).catch(q);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)OG(e,`completed`);return r}async function*jmt(e,t,n){try{var r=One();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??omt(),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=mmt(),h,g=imt(),_=r.u(Ngt(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=YPe(null,v,r),D=vFe(r.options.tools??[],v);yield{type:`stream_request_start`},u1(`query_fn_entry`),r.agentId||AG(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0},k=O.chainId;r={...r,queryTracking:O};let A=n3(v);A=A.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let ee=y,te=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);A=await YSe(A,r.contentReplacementState,te?e=>void x6(e,r.agentId).catch(q):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;u1(`query_microcompact_start`);let re=await f.microcompact(A,r,l);if(A=re.messages,re.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of re.clearedToolUseIds)e.delete(t)}u1(`query_microcompact_end`);let ie=Qs(VDt(i,o));u1(`query_autocompact_start`);let{compactionResult:ae,consecutiveFailures:j}=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);if(u1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(J(`tengu_auto_compact_succeeded`,{originalMessageCount:v.length,compactedMessageCount:ae.summaryMessages.length+ae.attachments.length+ae.hookResults.length,preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionInputTokens:i?.input_tokens,compactionOutputTokens:i?.output_tokens,compactionCacheReadTokens:i?.cache_read_input_tokens??0,compactionCacheCreationTokens:i?.cache_creation_input_tokens??0,compactionTotalTokens:i?i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens:0,queryChainId:k,queryDepth:O.depth}),e.taskBudget){let t=yLe(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=zz(ae);for(let e of a)yield e;A=a}else j!==void 0&&(ee={...ee??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:j});r={...r,messages:A};let oe=[],se=[],ce=[],M=!1;u1(`query_setup_start`);let N=g.gates.streamingToolExecution?new l1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Go({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&xLe(A)});if(u1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=tG(SR(A)-ne,r.options.mainLoopModel);if(e)return yield A4({content:YL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&nG()){let e=r.options.mainLoopModel,t=SR(A)-ne,n=e1e(e);if(t>$W(e)-n){let e=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);e.compactionResult&&(A=zz(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;u1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;u1(`query_api_streaming_start`);for await(let n of f.callModel({messages:HDt(A,a),systemPrompt:ie,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:de,...g.gates.fastModeEnabled&&{fastMode:le.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:le.mcp.tools,hasPendingMcpServers:le.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:le.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 oe)yield{type:`tombstone`,message:e};J(`tengu_orphaned_messages_tombstoned`,{orphanedMessageCount:oe.length,queryChainId:k,queryDepth:O.depth}),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(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=_s(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(kmt(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;oe.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(ce.push(...t),M=!0),N&&!r.abortController.signal.aborted)for(let n of t)N.addTool(n,e)}if(N&&!r.abortController.signal.aborted)for(let e of N.getCompletedResults())e.message&&(yield e.message,se.push(...R4([e.message],r.options.tools).filter(e=>e.type===`user`)))}u1(`query_api_streaming_end`)}catch(e){if(e instanceof _R&&c){de=c,fe=!0,yield*k1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(r.options.tools,s,r)),r.options.mainLoopModel=c,J(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield $4(`Switched to ${Eo(e.fallbackModel)} due to high demand for ${Eo(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){q(e);let t=e instanceof Error?e.message:String(e);return J(`tengu_query_error`,{assistantMessages:oe.length,toolUses:oe.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,queryChainId:k,queryDepth:O.depth}),e instanceof jL||e instanceof nv?(yield A4({content:e.message}),{reason:`image_error`}):(yield*k1(oe,t),yield A4({content:t}),qn(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&SRe()){let t=wRe(e,l,xRe());t&&(yield TRe(t))}}if(oe.length>0&&N0e(A.concat(oe),i,a,o,r,l),r.abortController.signal.aborted){if(N)for await(let e of N.getRemainingResults())e.message&&(yield e.message);else yield*k1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield j4({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!M){let e=oe.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&NIe(e),kmt(e)){if(b<Mmt){let e=$({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:[...A,...oe,e],toolUseContext:r,autoCompactTracking:ee,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 fEt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*nmt(A,oe,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...A,...oe,...t.blockingErrors],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=hmt(m,r.agentId,Lee(),Vee());if(e.action===`continue`){fte(),U(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,$({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:ee,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&&U(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),J(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;u1(`query_tool_execution_start`),J(N?`tengu_streaming_tool_execution_used`:`tengu_streaming_tool_execution_not_used`,{tool_count:ce.length,queryChainId:k,queryDepth:O.depth});let he=N?N.getRemainingResults():_pt(ce,oe,s,r);for await(let e of he)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(pe=!0),se.push(...R4([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});u1(`query_tool_execution_end`);let ge;if(g.gates.emitToolUseSummaries&&ce.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=oe.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=ce.map(e=>e.id);ge=s1e({tools:ce.map(e=>{let t=se.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?bxt(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield j4({toolUse:!0}));let e=T+1;return u&&e>u&&(yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,J(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),J(`tengu_query_before_attachments`,{messagesForQueryCount:A.length,assistantMessagesCount:oe.length,toolResultsCount:se.length,queryChainId:k,queryDepth:O.depth});let _e=ce.some(e=>e.name===ts),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await x0e(bL(_e?`later`:`next`).filter(e=>nIe(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&vL(be.staleCommands);let xe=be.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(xe.length>0){n.push(...xe);for(let e of xe)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));vL(xe)}for await(let e of Xgt(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Lgt(await _.promise,r.readFileState);for(let t of e){let e=j0(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(UPe&&E){let e=await XPe(E);for(let t of e){let e=j0(t);yield e,se.push(e)}}if(uFe&&D){let e=await bFe(D);for(let t of e){let e=j0(t);yield e,se.push(e)}}let Se=new Set(xe),P=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(P.length>0){for(let e of P)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));vL(P)}let Ce=hr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(J(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:Ce,queryChainId:k,queryDepth:O.depth}),me.options.refreshTools){let e=me.options.refreshTools();e!==me.options.tools&&(me={...me,options:{...me.options,tools:e}})}let we={...me,queryTracking:O},Te=T+1;if(!r.agentId&&Tmt()&&Emt({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Te>u)return yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:Te}),{reason:`max_turns`,turnCount:Te};u1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:we,autoCompactTracking:ee,turnCount:Te,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Mmt,j1=n((()=>{vR(),sG(),Kz(),kne(),Da(),ML(),rv(),Ks(),BI(),Qi(),aR(),W(),m3(),u1e(),W7(),H0(),qI(),nL(),EL(),E0e(),O0e(),IG(),No(),CR(),ho(),Hs(),P0e(),_7(),apt(),h1(),Spt(),zy(),h8(),rmt(),amt(),smt(),Wt(),_mt(),Cr(),kRe(),Omt(),Mmt=3}));function Nmt(){return{consecutiveDenials:0,totalDenials:0}}function Pmt(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function M1(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function Fmt(e){return e.consecutiveDenials>=N1.maxConsecutive||e.totalDenials>=N1.maxTotal}var N1,Imt=n((()=>{N1={maxConsecutive:3,maxTotal:20}}));function Lmt(e){L1=e}function Rmt(){return L1}function P1(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function zmt(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 Bmt(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
2551
+ `)}`)})],cacheSafeParams:P1(t),canUseTool:v1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:Zpt(p,d)});s9e(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&i9e(i)&&i.filesTouched.length>0&&n({...axt(i.filesTouched),verb:`Improved`}),U(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),J(`tengu_auto_dream_completed`,{cache_read:r.totalUsage.cache_read_input_tokens,cache_created:r.totalUsage.cache_creation_input_tokens,output:r.totalUsage.output_tokens,sessions_reviewed:c.length})}catch(e){if(f.signal.aborted){U(`[autoDream] aborted by user`);return}U(`[autoDream] fork failed: ${e.message}`),J(`tengu_auto_dream_failed`,{}),c9e(p,d),await $7e(u)}}}function Zpt(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)}o9e(e,{text:r.trim(),toolUseCount:i},a,t)}}async function Qpt(e,t){await x1?.(e,t)}var $pt,emt,x1,tmt=n((()=>{R1(),m3(),W(),Da(),hi(),Dpt(),h8(),Wt(),Wpt(),Kpt(),wJ(),EJ(),Ns(),vs(),$pt=600*1e3,emt={minHours:24,minSessions:5},x1=null}));async function*nmt(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`)&&Lmt(P1(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=Cpt(process.env.CLAUDE_JOB_DIR,e).catch(e=>{U(`[job] classifier error: ${H(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-DD88nPJ4.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&Jmt(l),!a.agentId&&eie()&&!u&&import(`./extractMemories-B1KbTMY0.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&Qpt(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=pEt(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=$({content:aEt(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 j0({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return J(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield j4({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield rxt(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=ib(`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 J(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield $4(`Stop hook failed: ${H(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var rmt=n((()=>{ob(),hi(),Da(),H0(),W(),On(),_7(),m3(),Tpt(),tmt(),U1(),h(),R1()}));function imt(){return{sessionId:sn(),gates:{streamingToolExecution:!1,emitToolUseSummaries:m(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!m(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var amt=n((()=>{Wt(),h()}));function omt(){return{callModel:vOt,microcompact:VR,autocompact:n1e,uuid:bl}}var smt=n((()=>{r9(),sG(),UR()}));function S1(e,t){return parseFloat(e)*fmt[t.toLowerCase()]}function cmt(e){let t=e.match(umt);if(t)return S1(t[1],t[2]);let n=e.match(dmt);if(n)return S1(n[1],n[2]);let r=e.match(C1);return r?S1(r[1],r[2]):null}function lmt(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 umt,dmt,C1,fmt,pmt=n((()=>{umt=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,dmt=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,C1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(C1.source,`gi`),fmt={k:1e3,m:1e6,b:1e9}}));function mmt(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function hmt(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<w1&&e.lastDeltaTokens<w1;return!s&&i<n*gmt?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:lmt(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 gmt,w1,_mt=n((()=>{pmt(),gmt=.9,w1=500}));function T1(){return Y(p(),`sessions`)}function vmt(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`||e===`daemon`||e===`daemon-worker`)return e}function ymt(){return vmt()===`bg`}async function bmt(){let e=vmt()??`interactive`,t=T1(),n=Y(t,`${process.pid}.json`);Gn(async()=>{try{await Fl(n)}catch{}});try{return await El(t,{recursive:!0,mode:448}),await Cl(t,448),await Il(n,V({pid:process.pid,sessionId:sn(),cwd:Xt(),startedAt:Date.now(),kind:e,entrypoint:process.env.CLAUDE_CODE_ENTRYPOINT,name:process.env.CLAUDE_CODE_SESSION_NAME,logPath:process.env.CLAUDE_CODE_SESSION_LOG,agent:process.env.CLAUDE_CODE_AGENT})),_te(e=>{E1({sessionId:e})}),!0}catch(e){return U(`[concurrentSessions] register failed: ${H(e)}`),!1}}async function E1(e){let t=Y(T1(),`${process.pid}.json`);try{await Il(t,V({...kn(await Ol(t,`utf8`)),...e}))}catch(e){U(`[concurrentSessions] updatePidFile failed: ${H(e)}`)}}async function xmt(e){e&&await E1({name:e})}async function Smt(e){await E1({bridgeSessionId:e})}async function Cmt(e){await E1({...e,updatedAt:Date.now()})}async function wmt(){let e=T1(),t;try{t=await kl(e)}catch(e){return Mn(e)||U(`[concurrentSessions] readdir failed: ${H(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}yc(t)?n++:la()!==`wsl`&&Fl(Y(e,r)).catch(()=>{})}return n}var D1=n((()=>{Wt(),Jn(),W(),h(),On(),bc(),ua(),Yn()}));function Tmt(){return ymt()?Date.now()-O1>=Dmt:!1}function Emt(e){O1=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`}`)}}Cmt({status:r,waitingFor:i}).catch(e=>{U(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){U(`[taskSummary] error: ${e}`)}}var Dmt,O1,Omt=n((()=>{D1(),W(),Dmt=3e4,O1=0}));function*k1(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 $({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function kmt(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function Amt(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*A1(e){let t=[],n=[],r,i=!1,a;try{r=yield*jmt(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await T0e({commands:n,outcome:Amt({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)hL(t)}).catch(q);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)OG(e,`completed`);return r}async function*jmt(e,t,n){try{var r=One();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??omt(),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=mmt(),h,g=imt(),_=r.u(Ngt(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=YPe(null,v,r),D=vFe(r.options.tools??[],v);yield{type:`stream_request_start`},u1(`query_fn_entry`),r.agentId||AG(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0},k=O.chainId;r={...r,queryTracking:O};let A=n3(v);A=A.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let ee=y,te=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);A=await YSe(A,r.contentReplacementState,te?e=>void x6(e,r.agentId).catch(q):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;u1(`query_microcompact_start`);let re=await f.microcompact(A,r,l);if(A=re.messages,re.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of re.clearedToolUseIds)e.delete(t)}u1(`query_microcompact_end`);let ie=Qs(VDt(i,o));u1(`query_autocompact_start`);let{compactionResult:ae,consecutiveFailures:j}=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);if(u1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(J(`tengu_auto_compact_succeeded`,{originalMessageCount:v.length,compactedMessageCount:ae.summaryMessages.length+ae.attachments.length+ae.hookResults.length,preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionInputTokens:i?.input_tokens,compactionOutputTokens:i?.output_tokens,compactionCacheReadTokens:i?.cache_read_input_tokens??0,compactionCacheCreationTokens:i?.cache_creation_input_tokens??0,compactionTotalTokens:i?i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens:0,queryChainId:k,queryDepth:O.depth}),e.taskBudget){let t=yLe(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=zz(ae);for(let e of a)yield e;A=a}else j!==void 0&&(ee={...ee??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:j});r={...r,messages:A};let oe=[],se=[],ce=[],M=!1;u1(`query_setup_start`);let N=g.gates.streamingToolExecution?new l1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Go({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&xLe(A)});if(u1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=tG(SR(A)-ne,r.options.mainLoopModel);if(e)return yield A4({content:YL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&nG()){let e=r.options.mainLoopModel,t=SR(A)-ne,n=e1e(e);if(t>$W(e)-n){let e=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);e.compactionResult&&(A=zz(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;u1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;u1(`query_api_streaming_start`);for await(let n of f.callModel({messages:HDt(A,a),systemPrompt:ie,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:de,...g.gates.fastModeEnabled&&{fastMode:le.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:le.mcp.tools,hasPendingMcpServers:le.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:le.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 oe)yield{type:`tombstone`,message:e};J(`tengu_orphaned_messages_tombstoned`,{orphanedMessageCount:oe.length,queryChainId:k,queryDepth:O.depth}),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(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=_s(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(kmt(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;oe.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(ce.push(...t),M=!0),N&&!r.abortController.signal.aborted)for(let n of t)N.addTool(n,e)}if(N&&!r.abortController.signal.aborted)for(let e of N.getCompletedResults())e.message&&(yield e.message,se.push(...R4([e.message],r.options.tools).filter(e=>e.type===`user`)))}u1(`query_api_streaming_end`)}catch(e){if(e instanceof _R&&c){de=c,fe=!0,yield*k1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(r.options.tools,s,r)),r.options.mainLoopModel=c,J(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield $4(`Switched to ${Eo(e.fallbackModel)} due to high demand for ${Eo(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){q(e);let t=e instanceof Error?e.message:String(e);return J(`tengu_query_error`,{assistantMessages:oe.length,toolUses:oe.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,queryChainId:k,queryDepth:O.depth}),e instanceof jL||e instanceof nv?(yield A4({content:e.message}),{reason:`image_error`}):(yield*k1(oe,t),yield A4({content:t}),qn(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&SRe()){let t=wRe(e,l,xRe());t&&(yield TRe(t))}}if(oe.length>0&&N0e(A.concat(oe),i,a,o,r,l),r.abortController.signal.aborted){if(N)for await(let e of N.getRemainingResults())e.message&&(yield e.message);else yield*k1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield j4({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!M){let e=oe.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&NIe(e),kmt(e)){if(b<Mmt){let e=$({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:[...A,...oe,e],toolUseContext:r,autoCompactTracking:ee,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 fEt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*nmt(A,oe,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...A,...oe,...t.blockingErrors],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=hmt(m,r.agentId,Lee(),Vee());if(e.action===`continue`){fte(),U(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,$({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:ee,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&&U(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),J(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;u1(`query_tool_execution_start`),J(N?`tengu_streaming_tool_execution_used`:`tengu_streaming_tool_execution_not_used`,{tool_count:ce.length,queryChainId:k,queryDepth:O.depth});let he=N?N.getRemainingResults():_pt(ce,oe,s,r);for await(let e of he)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(pe=!0),se.push(...R4([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});u1(`query_tool_execution_end`);let ge;if(g.gates.emitToolUseSummaries&&ce.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=oe.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=ce.map(e=>e.id);ge=s1e({tools:ce.map(e=>{let t=se.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?bxt(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield j4({toolUse:!0}));let e=T+1;return u&&e>u&&(yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,J(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),J(`tengu_query_before_attachments`,{messagesForQueryCount:A.length,assistantMessagesCount:oe.length,toolResultsCount:se.length,queryChainId:k,queryDepth:O.depth});let _e=ce.some(e=>e.name===ts),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await x0e(bL(_e?`later`:`next`).filter(e=>nIe(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&vL(be.staleCommands);let xe=be.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(xe.length>0){n.push(...xe);for(let e of xe)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));vL(xe)}for await(let e of Xgt(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Lgt(await _.promise,r.readFileState);for(let t of e){let e=j0(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(UPe&&E){let e=await XPe(E);for(let t of e){let e=j0(t);yield e,se.push(e)}}if(uFe&&D){let e=await bFe(D);for(let t of e){let e=j0(t);yield e,se.push(e)}}let Se=new Set(xe),P=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(P.length>0){for(let e of P)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));vL(P)}let Ce=hr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(J(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:Ce,queryChainId:k,queryDepth:O.depth}),me.options.refreshTools){let e=me.options.refreshTools();e!==me.options.tools&&(me={...me,options:{...me.options,tools:e}})}let we={...me,queryTracking:O},Te=T+1;if(!r.agentId&&Tmt()&&Emt({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Te>u)return yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:Te}),{reason:`max_turns`,turnCount:Te};u1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:we,autoCompactTracking:ee,turnCount:Te,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Mmt,j1=n((()=>{vR(),sG(),Kz(),kne(),Da(),ML(),rv(),Ks(),BI(),Qi(),aR(),W(),m3(),u1e(),W7(),H0(),qI(),nL(),EL(),E0e(),O0e(),IG(),No(),CR(),ho(),Hs(),P0e(),_7(),apt(),h1(),Spt(),zy(),h8(),rmt(),amt(),smt(),Wt(),_mt(),Cr(),kRe(),Omt(),Mmt=3}));function Nmt(){return{consecutiveDenials:0,totalDenials:0}}function Pmt(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function M1(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function Fmt(e){return e.consecutiveDenials>=N1.maxConsecutive||e.totalDenials>=N1.maxTotal}var N1,Imt=n((()=>{N1={maxConsecutive:3,maxTotal:20}}));function Lmt(e){L1=e}function Rmt(){return L1}function P1(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function zmt(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 Bmt(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
2552
2552
  `),i=P9(e.allowedTools??[]),a=zmt(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:[$({content:r})]}}function Vmt(e,t=`Execution completed`){let n=O4(e);return n&&q4(Array.isArray(n.message.content)?n.message.content:[],`
2553
2553
  `)||t}function F1(e,t){let n=t?.abortController??(t?.shareAbortController?e.abortController:iD(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:aF(t?.readFileState??e.readFileState),nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:new Set,dynamicSkillDirTriggers:new Set,discoveredSkillNames:new Set,toolDecisions:void 0,contentReplacementState:t?.contentReplacementState??(e.contentReplacementState?FSe(e.contentReplacementState):void 0),abortController:n,getAppState:r,setAppState:t?.shareSetAppState?e.setAppState:()=>{},setAppStateForTasks:e.setAppStateForTasks??e.setAppState,localDenialTracking:t?.shareSetAppState?e.localDenialTracking:Nmt(),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??GG(),agentType:t?.agentType,queryTracking:{chainId:bl(),depth:(e.queryTracking?.depth??-1)+1},fileReadingLimits:e.fileReadingLimits,userModified:e.userModified,criticalSystemReminder_EXPERIMENTAL:t?.criticalSystemReminder_EXPERIMENTAL,requireCanUseTool:t?.requireCanUseTool}}function Hmt(e){return e.type===`stream_event`&&typeof e.event==`object`&&e.event!==null&&`type`in e.event&&e.event.type===`message_delta`}async function I1({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={...rc},{systemPrompt:m,userContext:h,systemContext:g,toolUseContext:_,forkContextMessages:v}=t,y=F1(_,a),b=[...v,...e],x=l?void 0:GG(i),S=null;x&&(await v6(b,x).catch(e=>U(`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 A1({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(Hmt(e)){let t=$7({...rc},e.event.usage);p=EOt(p,t)}continue}if(e.type===`stream_request_start`)continue;U(`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 v6([t],x,S).catch(e=>U(`Forked agent [${i}] failed to record transcript: ${e}`)),t.type!==`progress`&&(S=t.uuid))}}finally{y.readFileState.clear(),b.length=0}return U(`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}`),Umt({forkLabel:i,querySource:r,durationMs:Date.now()-d,messageCount:f.length,totalUsage:p,queryTracking:_.queryTracking}),{messages:f,totalUsage:p}}function Umt({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,s=o>0?i.cache_read_input_tokens/o:0;J(`tengu_fork_agent_query`,{forkLabel:e,querySource:t,durationMs:n,messageCount:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cacheReadInputTokens:i.cache_read_input_tokens,cacheCreationInputTokens:i.cache_creation_input_tokens,serviceTier:i.service_tier,cacheCreationEphemeral1hTokens:i.cache_creation.ephemeral_1h_input_tokens,cacheCreationEphemeral5mTokens:i.cache_creation.ephemeral_5m_input_tokens,cacheHitRate:s,...a?{queryChainId:a.chainId,queryDepth:a.depth}:{}})}var L1,R1=n((()=>{j1(),Da(),r9(),ec(),oD(),W(),lF(),m3(),Imt(),z9(),h8(),zy(),KG(),L1=null}));function z1(){return`user_intent`}function Wmt(){let e=process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION;return f(e)?(J(`tengu_prompt_suggestion_init`,{enabled:!1,source:`env`}),!1):m(e)?(J(`tengu_prompt_suggestion_init`,{enabled:!0,source:`env`}),!0):(J(`tengu_prompt_suggestion_init`,{enabled:!1,source:`growthbook`}),!1)}function Gmt(){V1&&(V1.abort(),V1=null)}function Kmt(e){return e.promptSuggestionEnabled?e.elicitation.queue.length>0?`elicitation_active`:e.toolPermissionContext.mode===`plan`?`plan_mode`:BL.status===`allowed`?null:`rate_limit`:`disabled`}async function qmt(e,t,n,r,i){if(e.signal.aborted)return B1(`aborted`,void 0,void 0,i),null;if(hr(t,e=>e.type===`assistant`)<2)return B1(`early_conversation`,void 0,void 0,i),null;let a=O4(t);if(a?.isApiErrorMessage)return B1(`last_response_error`,void 0,void 0,i),null;let o=Ymt(a);if(o)return B1(o,void 0,void 0,i),null;let s=Kmt(n());if(s)return B1(s,void 0,void 0,i),null;let c=z1(),{suggestion:l,generationRequestId:u}=await Xmt(e,c,r);return e.signal.aborted?(B1(`aborted`,void 0,void 0,i),null):l?Zmt(l,c,i)?null:{suggestion:l,promptId:c,generationRequestId:u}:(B1(`empty`,void 0,c,i),null)}async function Jmt(e){if(e.querySource!==`repl_main_thread`)return;V1=new AbortController;let t=V1,n=P1(e);try{let r=await qmt(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}})),bht()&&r.suggestion&&Sht(r.suggestion,e,e.toolUseContext.setAppState,!1,n)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){B1(`aborted`,void 0,void 0,`cli`);return}q(jn(e))}finally{V1===t&&(V1=null)}}function Ymt(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>$mt?`cache_cold`:null}async function Xmt(e,t,n){let r=eht[t],i=await I1({promptMessages:[$({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 Zmt(e,t,n){if(!e)return B1(`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 B1(r,e,t,n),!0;return!1}function Qmt(e,t,n,r,i){let a=Math.round(t.length/(e.length||1)*100)/100,o=t===e,s=Math.max(0,Date.now()-n);J(`tengu_prompt_suggestion`,{source:`sdk`,outcome:o?`accepted`:`ignored`,prompt_id:r,...i&&{generationRequestId:i},...o&&{timeToAcceptMs:s},...!o&&{timeToIgnoreMs:s},similarity:a})}function B1(e,t,n,r){let i=n??z1();J(`tengu_prompt_suggestion`,{...r&&{source:r},outcome:`suppressed`,reason:e,prompt_id:i})}var V1,$mt,H1,eht,U1=n((()=>{Wt(),Cr(),h(),On(),R1(),Qi(),m3(),Vr(),Da(),UL(),t0(),V1=null,$mt=1e4,H1=`[SUGGESTION MODE: Suggest what the user might naturally type next into Work Mate.]
2554
2554
 
@@ -2561,8 +2561,8 @@ THE TEST: Would they think "I was just about to type that"?
2561
2561
  EXAMPLES:
2562
2562
  User asked "fix the bug and run tests", bug is fixed → "run the tests"
2563
2563
  After code written → "try it out"
2564
- Claude offers options → suggest the one the user would likely pick, based on conversation
2565
- Claude asks to continue → "yes" or "go ahead"
2564
+ Work Mate offers options → suggest the one the user would likely pick, based on conversation
2565
+ Work Mate asks to continue → "yes" or "go ahead"
2566
2566
  Task complete, obvious follow-up → "commit this" or "push it"
2567
2567
  After error or misunderstanding → silence (let them assess/correct)
2568
2568
 
@@ -2571,7 +2571,7 @@ Be specific: "run the tests" beats "continue".
2571
2571
  NEVER SUGGEST:
2572
2572
  - Evaluative ("looks good", "thanks")
2573
2573
  - Questions ("what about...?")
2574
- - Claude-voice ("Let me...", "I'll...", "Here's...")
2574
+ - Work Mate-voice ("Let me...", "I'll...", "Here's...")
2575
2575
  - New ideas they didn't ask about
2576
2576
  - Multiple sentences
2577
2577
 
@@ -2598,19 +2598,19 @@ Return a list of filenames for the memories that will clearly be useful to Work
2598
2598
  `);return J(`tengu_at_mention_extracting_directory_success`,{}),{type:`directory`,path:o,content:i,displayPath:$c(yn(),o)}}catch{return null}}catch{}return await Qgt(o,t,`tengu_at_mention_extracting_filename_success`,`tengu_at_mention_extracting_filename_error`,`at-mention`,{offset:i,limit:a&&i?a-i+1:void 0})}catch{J(`tengu_at_mention_extracting_filename_error`,{})}}))).filter(Boolean)}function Tgt(e,t){let n=Kgt(e);return n.length===0?[]:n.map(e=>{let n=e.replace(`agent-`,``),r=t.find(e=>e.agentType===n);return r?(J(`tengu_at_mention_agent_success`,{}),{type:`agent_mention`,agentType:r.agentType}):(J(`tengu_at_mention_agent_not_found`,{}),null)}).filter(e=>e!==null)}async function Egt(e,t){let n=Ggt(e);if(n.length===0)return[];let r=t.options.mcpClients||[];return(await Promise.all(n.map(async e=>{try{let[n,...i]=e.split(`:`),a=i.join(`:`);if(!n||!a)return J(`tengu_at_mention_mcp_resource_error`,{}),null;let o=r.find(e=>e.name===n);if(o?.type!==`connected`)return J(`tengu_at_mention_mcp_resource_error`,{}),null;let s=(t.options.mcpResources?.[n]||[]).find(e=>e.uri===a);if(!s)return J(`tengu_at_mention_mcp_resource_error`,{}),null;try{let e=await o.client.readResource({uri:a});return J(`tengu_at_mention_mcp_resource_success`,{}),{type:`mcp_resource`,server:n,uri:a,name:s.name||a,description:s.description,content:e}}catch(e){return J(`tengu_at_mention_mcp_resource_error`,{}),q(e),null}}catch{return J(`tengu_at_mention_mcp_resource_error`,{}),null}}))).filter(e=>e!==null)}async function Dgt(e){let t=iF(e.readFileState);if(t.length===0)return[];let n=e.getAppState();return(await Promise.all(t.map(async t=>{let r=e.readFileState.get(t);if(!r||r.offset!==void 0||r.limit!==void 0)return null;let i=Qr(t);if(M0(i,n.toolPermissionContext))return null;try{if(await er(i)<=r.timestamp)return null;let t={file_path:i};if(!(await ex.validateInput(t,e)).result)return null;let n=await ex.call(t,e);if(n.data.type===`text`){let e=CPe(r.content,n.data.file.content);return e===``?null:{type:`edited_text_file`,filename:i,snippet:e}}if(n.data.type===`image`)try{return{type:`edited_image_file`,filename:i,content:await fwe(i)}}catch(e){return q(e),J(`tengu_watched_file_compression_failed`,{file:i}),null}return null}catch(n){return xn(n)&&e.readFileState.delete(t),null}}))).filter(e=>e!=null)}async function Ogt(e){if(!e.nestedMemoryAttachmentTriggers||e.nestedMemoryAttachmentTriggers.size===0)return[];let t=e.getAppState(),n=[];for(let r of e.nestedMemoryAttachmentTriggers){let i=await Sgt(r,e,t);n.push(...i)}return e.nestedMemoryAttachmentTriggers.clear(),n}async function kgt(e,t,n,r,i,a){let o=Kgt(e).flatMap(e=>{let n=e.replace(`agent-`,``),r=t.find(e=>e.agentType===n);return r?.memory?[Gd(n,r.memory)]:[]}),s=o.length>0?o:[xi()],c=await jgt((await Promise.all(s.map(t=>tgt(e,t,i,r,a).catch(()=>[])))).flat().filter(e=>!n.has(e.path)&&!a.has(e.path)).slice(0,5),i);return c.length===0?[]:[{type:`relevant_memories`,memories:c}]}function Agt(e){let t=new Set,n=0;for(let r of e)if(r.type===`attachment`&&r.attachment.type===`relevant_memories`)for(let e of r.attachment.memories)t.add(e.path),n+=e.content.length;return{paths:t,totalBytes:n}}async function jgt(e,t){return(await Promise.all(e.map(async({path:e,mtimeMs:n})=>{try{let r=await qy(e,0,L0,R0,t,{truncateOnByteLimit:!0}),i=r.totalLines>L0||r.truncatedByBytes;return{path:e,content:i?r.content+`\n\n> This memory file was truncated (${r.truncatedByBytes?`${R0} byte limit`:`first ${L0} lines`}). Use the ${gs} tool to view the complete file at: ${e}`:r.content,mtimeMs:n,header:Mgt(e,n),limit:i?r.lineCount:void 0}}catch{return null}}))).filter(e=>e!==null)}function Mgt(e,t){let n=hbe(t);return n?`${n}\n\nMemory: ${e}:`:`Memory (saved ${mbe(t)}): ${e}:`}function Ngt(t,n){if(!_i()||!0)return;let{isPoorModeActive:r}=(Lc(),e($ce));if(r())return;let i=t.findLast(e=>e.type===`user`&&!e.isMeta);if(!i)return;let a=K4(i);if(!a||!/\s/.test(a.trim()))return;let o=Agt(t);if(o.totalBytes>=u_t.MAX_SESSION_BYTES)return;let s=iD(n.abortController),c=Date.now(),l=kgt(a,n.options.agentDefinitions.activeAgents,n.readFileState,Igt(t,i),s.signal,o.paths).catch(e=>(Ane(e)||q(e),[])),u={promise:l,settledAt:null,consumedOnIteration:-1,[Symbol.dispose](){s.abort(),J(`tengu_memdir_prefetch_collected`,{hidden_by_first_iteration:u.settledAt!==null&&u.consumedOnIteration===0,consumed_on_iteration:u.consumedOnIteration,latency_ms:(u.settledAt??Date.now())-c})}};return l.finally(()=>{u.settledAt=Date.now()}),u}function Pgt(e){return typeof e==`object`&&!!e&&e.type===`tool_result`&&typeof e.tool_use_id==`string`}function Fgt(e){return Array.isArray(e)&&e.some(Pgt)}function Igt(e,t){let n=new Map,r=new Map;for(let i=e.length-1;i>=0;i--){let a=e[i];if(a){if($ht(a)&&a!==t)break;if(a.type===`assistant`&&typeof a.message.content!=`string`)for(let e of a.message.content)e.type===`tool_use`&&n.set(e.id,e.name);else if(a.type===`user`&&`message`in a&&Array.isArray(a.message.content))for(let e of a.message.content)Pgt(e)&&r.set(e.tool_use_id,e.is_error===!0)}}let i=new Set,a=new Set;for(let[e,t]of n){let n=r.get(e);n!==void 0&&(n?i.add(t):a.add(t))}return[...a].filter(e=>!i.has(e))}function Lgt(e,t){return e.map(e=>{if(e.type!==`relevant_memories`)return e;let n=e.memories.filter(e=>!t.has(e.path));for(let e of n)t.set(e.path,{content:e.content,timestamp:e.mtimeMs,offset:void 0,limit:e.limit});return n.length>0?{...e,memories:n}:null}).filter(e=>e!==null)}async function Rgt(e){let t=[];if(e.dynamicSkillDirTriggers&&e.dynamicSkillDirTriggers.size>0){let n=await Promise.all(Array.from(e.dynamicSkillDirTriggers).map(async e=>{try{let t=(await kl(e,{withFileTypes:!0})).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name);return{skillDir:e,skillNames:(await Promise.all(t.map(async t=>{try{return await Nl(el(e,t,`SKILL.md`)),t}catch{return null}}))).filter(e=>e!==null)}}catch{return{skillDir:e,skillNames:[]}}}));for(let{skillDir:e,skillNames:r}of n)r.length>0&&t.push({type:`dynamic_skill`,skillDir:e,skillNames:r,displayPath:$c(yn(),e)});e.dynamicSkillDirTriggers.clear()}return t}function zgt(){z0.clear(),B0=!1,V0=!1}function Bgt(){B0=!0}function Vgt(){V0=!0}function Hgt(e){let t=e.filter(e=>e.loadedFrom===`bundled`||e.loadedFrom===`mcp`);return t.length>f_t?t.filter(e=>e.loadedFrom===`bundled`):t}async function Ugt(e){if(!e.options.tools.some(e=>Ws(e,`Skill`)))return[];let t=await Z3(en()),n=JSt(e.getAppState().mcp.commands),r=n.length>0?uh([...t,...n],`name`):t;N0.featureCheck.isSkillSearchEnabled()&&(r=Hgt(r));let i=e.agentId??``,a=z0.get(i);if(a||(a=new Set,z0.set(i,a)),B0){B0=!1;for(let e of r)a.add(e.name);return[]}let o=r.filter(e=>!a.has(e.name));if(o.length===0)return[];let s=a.size===0;for(let e of o)a.add(e.name);return U(`Sending ${o.length} skills via attachment (${s?`initial`:`dynamic`}, ${a.size} total sent)`),[{type:`skill_listing`,content:sbe(o,ko(e.options.mainLoopModel,Yt())),skillCount:o.length,isInitial:s}]}function Wgt(e){let t=/(^|\s)@"([^"]+)"/g,n=/(^|\s)@([^\s]+)\b/g,r=[],i=[],a;for(;(a=t.exec(e))!==null;)a[2]&&!a[2].endsWith(` (agent)`)&&r.push(a[2]);return(e.match(n)??[]).forEach(e=>{let t=e.slice(e.indexOf(`@`)+1);t.startsWith(`"`)||i.push(t)}),Qn([...r,...i])}function Ggt(e){return Qn((e.match(/(^|\s)@([^\s]+:[^\s]+)\b/g)||[]).map(e=>e.slice(e.indexOf(`@`)+1)))}function Kgt(e){let t=[],n=/(^|\s)@"([\w:.@-]+) \(agent\)"/g,r;for(;(r=n.exec(e))!==null;)r[2]&&t.push(r[2]);let i=e.match(/(^|\s)@(agent-[\w:.@-]+)/g)||[];for(let e of i)t.push(e.slice(e.indexOf(`@`)+1));return Qn(t)}function qgt(e){let t=e.match(/^([^#]+)(?:#L(\d+)(?:-(\d+))?)?(?:#[^#]*)?$/);if(!t)return{filename:e};let[,n,r,i]=t,a=r?parseInt(r,10):void 0;return{filename:n??e,lineStart:a,lineEnd:i?parseInt(i,10):a}}async function Jgt(e){if(!e.options.tools.some(e=>Ws(e,`Bash`)))return[];let t=await FF.getNewDiagnostics();return t.length===0?[]:[{type:`diagnostics`,files:t,isNew:!0}]}async function Ygt(e){if(!e.options.tools.some(e=>Ws(e,`Bash`)))return[];U(`LSP Diagnostics: getLSPDiagnosticAttachments called`);try{let e=SJe();if(e.length===0)return[];U(`LSP Diagnostics: Found ${e.length} pending diagnostic set(s)`);let t=e.map(({files:e})=>({type:`diagnostics`,files:e,isNew:!0}));return e.length>0&&(CJe(),U(`LSP Diagnostics: Cleared ${e.length} delivered diagnostic(s) from registry`)),U(`LSP Diagnostics: Returning ${t.length} diagnostic attachment(s)`),t}catch(e){let t=jn(e);return q(Error(`Failed to get LSP diagnostic attachments: ${t.message}`)),[]}}async function*Xgt(e,t,n,r,i,a,o){let s=await agt(e,t,n,r,i,a,o);if(s.length!==0){J(`tengu_attachments`,{attachment_types:s.map(e=>e.type)});for(let e of s)yield j0(e)}}async function Zgt(e){if(!Bs(Zc(e).ext.toLowerCase()))return null;try{let[t,n]=await Promise.all([G().stat(e),tCe(e)]),r=n??Math.ceil(t.size/(100*1024));if(r>10)return J(`tengu_pdf_reference_attachment`,{pageCount:r,fileSize:t.size,hadPdfinfo:n!==null}),{type:`pdf_reference`,filename:e,pageCount:r,fileSize:t.size,displayPath:$c(yn(),e)}}catch{}return null}async function Qgt(e,t,n,r,i,a){let{offset:o,limit:s}=a??{};if(M0(e,t.getAppState().toolPermissionContext))return null;if(i===`at-mention`&&!Rne(e,$y().maxSizeBytes)&&!Bs(Zc(e).ext.toLowerCase()))try{return J(`tengu_attachment_file_too_large`,{size_bytes:(await G().stat(e)).size,mode:i}),null}catch{}if(i===`at-mention`){let t=await Zgt(e);if(t)return t}let c=t.readFileState.get(e);if(c&&i===`at-mention`)try{let t=await er(e);if(c.timestamp<=t&&t===c.timestamp)return J(n,{}),{type:`already_read_file`,filename:e,displayPath:$c(yn(),e),content:{type:`text`,file:{filePath:e,content:c.content,numLines:Ya(c.content,`
2599
2599
  `)+1,startLine:o??1,totalLines:Ya(c.content,`
2600
2600
  `)+1}}}}catch{}try{let a={file_path:e,offset:o,limit:s};async function c(){if(i===`compact`)return{type:`compact_file_reference`,filename:e,displayPath:$c(yn(),e)};if(M0(e,t.getAppState().toolPermissionContext))return null;try{let r={file_path:e,offset:o??1,limit:uoe},i=await ex.call(r,t);return J(n,{}),{type:`file`,filename:e,content:i.data,truncated:!0,displayPath:$c(yn(),e)}}catch{return J(r,{}),null}}if(!(await ex.validateInput(a,t)).result)return null;try{let r=await ex.call(a,t);return J(n,{}),{type:`file`,filename:e,content:r.data,displayPath:$c(yn(),e)}}catch(e){if(e instanceof Qb||e instanceof Yy)return await c();throw e}}catch{return J(r,{}),null}}function j0(e){return{attachment:e,type:`attachment`,uuid:bl(),timestamp:new Date().toISOString()}}function $gt(e){let t=-1,n=-1,r=0,i=0;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o?.type===`assistant`){if(dxt(o))continue;t===-1&&`message`in o&&Array.isArray(o.message?.content)&&o.message.content.some(e=>e.type===`tool_use`&&e.name===`TodoWrite`)&&(t=a),t===-1&&r++,n===-1&&i++}else n===-1&&o?.type===`attachment`&&o.attachment.type===`todo_reminder`&&(n=a);if(t!==-1&&n!==-1)break}return{turnsSinceLastTodoWrite:r,turnsSinceLastReminder:i}}async function e_t(e,t){if(!t.options.tools.some(e=>Ws(e,`TodoWrite`))||!e||e.length===0)return[];let{turnsSinceLastTodoWrite:n,turnsSinceLastReminder:r}=$gt(e);if(n>=P0.TURNS_SINCE_WRITE&&r>=P0.TURNS_BETWEEN_REMINDERS){let e=t.agentId??sn(),n=t.getAppState().todos[e]??[];return[{type:`todo_reminder`,content:n,itemCount:n.length}]}return[]}function t_t(e){let t=-1,n=-1,r=0,i=0;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o?.type===`assistant`){if(dxt(o))continue;t===-1&&`message`in o&&Array.isArray(o.message?.content)&&o.message.content.some(e=>e.type===`tool_use`&&(e.name===`TaskCreate`||e.name===`TaskUpdate`))&&(t=a),t===-1&&r++,n===-1&&i++}else n===-1&&o?.type===`attachment`&&o.attachment.type===`task_reminder`&&(n=a);if(t!==-1&&n!==-1)break}return{turnsSinceLastTaskManagement:r,turnsSinceLastReminder:i}}async function n_t(e,t){if(!ax()||!t.options.tools.some(e=>Ws(e,`TaskUpdate`))||!e||e.length===0)return[];let{turnsSinceLastTaskManagement:n,turnsSinceLastReminder:r}=t_t(e);if(n>=P0.TURNS_SINCE_WRITE&&r>=P0.TURNS_BETWEEN_REMINDERS){let e=await dx(ox());return[{type:`task_reminder`,content:e,itemCount:e.length}]}return[]}async function r_t(e){let{attachments:t,updatedTaskOffsets:n,evictedTaskIds:r}=await aIe(e.getAppState());return oIe(e.setAppState,n,r),t.map(e=>({type:`task_status`,taskId:e.taskId,taskType:e.taskType,status:e.status,description:e.description,deltaSummary:e.deltaSummary,outputFilePath:V8(e.taskId)}))}async function i_t(){let e=await Xht();if(e.length===0)return[];U(`Hooks: getAsyncHookResponseAttachments found ${e.length} responses`);let t=e.map(({processId:e,response:t,hookName:n,hookEvent:r,toolName:i,pluginId:a,stdout:o,stderr:s,exitCode:c})=>(U(`Hooks: Creating attachment for ${e} (${n}): ${V(t)}`),{type:`async_hook_response`,processId:e,hookName:n,hookEvent:r,toolName:i,response:t,stdout:o,stderr:s,exitCode:c}));if(e.length>0){let t=e.map(e=>e.processId);Zht(t),U(`Hooks: Removed ${t.length} delivered hooks from registry`)}return U(`Hooks: getAsyncHookResponseAttachments found ${t.length} attachments`),t}function a_t(e,t){if(!m(process.env.CLAUDE_CODE_ENABLE_TOKEN_USAGE_ATTACHMENT))return[];let n=$W(t),r=xR(e);return[{type:`token_usage`,used:r,total:n,remaining:n-r}]}function o_t(){let e=Lee();return e===null||e<=0?[]:[{type:`output_token_usage`,turn:Vee(),session:tn(),budget:e}]}function s_t(e){if(e===void 0)return[];let t=Tt();return[{type:`budget_usd`,used:t,total:e,remaining:e-t}]}async function c_t(e,t){return[]}function M0(e,t){return k8(e,t,`read`,`deny`)!==null}var N0,l_t,P0,F0,I0,L0,R0,u_t,d_t,z0,B0,V0,f_t,H0=n((()=>{Da(),Ks(),nx(),Xy(),Lr(),Ja(),Cr(),Bn(),is(),ps(),ms(),bs(),Js(),hx(),ff(),CN(),jF(),vn(),Qi(),W(),On(),IF(),RF(),zI(),rv(),Vr(),e6(),dh(),Wt(),V_(),ho(),Om(),qI(),nL(),cL(),Fs(),gCe(),lF(),oD(),ci(),$9(),xr(),IFe(),j9(),no(),Ur(),R8(),AL(),o5(),p0(),vz(),Vht(),w0(),NH(),m3(),egt(),h(),CR(),sG(),_7(),Yn(),sse(),KR(),iCe(),G_(),igt(),_be(),hi(),Jd(),N0={featureCheck:nhe,prefetch:UPe},l_t={prefetch:uFe},P0={TURNS_SINCE_WRITE:10,TURNS_BETWEEN_REMINDERS:10},F0={TURNS_BETWEEN_ATTACHMENTS:5,FULL_REMINDER_EVERY_N_ATTACHMENTS:5},I0={TURNS_BETWEEN_ATTACHMENTS:5,FULL_REMINDER_EVERY_N_ATTACHMENTS:5},L0=200,R0=4096,u_t={MAX_SESSION_BYTES:60*1024},d_t=new Set([`prompt`,`task-notification`]),z0=new Map,B0=!1,V0=!1,f_t=30}));async function U0(e,t,n={}){let r=G(),i=n.logLabel??`plugin`;async function a(e,o){try{let i=await r.readdir(e);if(n.stopAtSkillDir&&i.some(e=>e.isFile()&&p_t.test(e.name))){await Promise.all(i.map(n=>n.isFile()&&n.name.toLowerCase().endsWith(`.md`)?t(Y(e,n.name),o):void 0));return}await Promise.all(i.map(n=>{let r=Y(e,n.name);if(n.isDirectory())return a(r,[...o,n.name]);if(n.isFile()&&n.name.toLowerCase().endsWith(`.md`))return t(r,o)}))}catch(t){U(`Failed to scan ${i} directory ${e}: ${t}`,{level:`error`})}}await a(e,[])}var p_t,W0=n((()=>{W(),Bn(),p_t=/^skill\.md$/i}));async function m_t(e,t,n,r,i,a){let o=[];return await U0(e,async(e,s)=>{let c=await h_t(e,t,s,n,r,i,a);c&&o.push(c)},{logLabel:`agents`}),o}async function h_t(e,t,n,r,i,a,o){let s=G();if(Kn(s,e,o))return null;try{let{frontmatter:o,content:c}=od(await s.readFile(e,{encoding:`utf-8`}),e),l=o.name||Kc(e).replace(/\.md$/,``),u=[t,...n,l].join(`:`),d=ud(o.description,u)??ud(o[`when-to-use`],u)??`Agent from ${t} plugin`,f=V9(o.tools),p=H9(o.skills),m=o.color,h=o.model,g;if(typeof h==`string`&&h.trim().length>0){let e=h.trim();g=e.toLowerCase()===`inherit`?`inherit`:e}let _=o.background,v=_===`true`||_===!0||void 0,y=rT(c.trim(),{path:i,source:r});a.userConfig&&(y=Hke(y,aT(r),a.userConfig));let b=o.memory,x;b!==void 0&&(G0.includes(b)?x=b:U(`Plugin agent file ${e} has invalid memory value '${b}'. Valid options: ${G0.join(`, `)}`));let S=o.isolation===`worktree`?`worktree`:void 0;for(let t of[`permissionMode`,`hooks`,`mcpServers`])o[t]!==void 0&&U(`Plugin agent file ${e} sets ${t}, which is ignored for plugin agents. Use .workmate/agents/ for this level of control.`,{level:`warn`});let C=o.maxTurns,w=ld(C);C!==void 0&&w===void 0&&U(`Plugin agent file ${e} has invalid maxTurns '${C}'. Must be a positive integer.`);let T=o.disallowedTools===void 0?void 0:V9(o.disallowedTools);if(_i()&&x&&f!==void 0){let e=new Set(f);for(let t of[ks,ws,gs])e.has(t)||(f=[...f,t])}return{agentType:u,whenToUse:d,tools:f,...T===void 0?{}:{disallowedTools:T},...p===void 0?{}:{skills:p},getSystemPrompt:()=>{if(_i()&&x){let e=qd(u,x);return`${y}\n\n${e}`}return y},source:`plugin`,color:m,model:g,filename:l,plugin:r,...v?{background:v}:{},...x?{memory:x}:{},...S?{isolation:S}:{},...w===void 0?{}:{maxTurns:w}}}catch(t){return U(`Failed to load agent from ${e}: ${t}`,{level:`error`}),null}}function g_t(){K0.cache?.clear?.()}var G0,K0,q0=n((()=>{d(),hi(),Jd(),Ns(),Fs(),vs(),Wg(),W(),gd(),Bn(),K9(),d4(),oT(),W0(),G0=[`user`,`project`,`local`],K0=u(async()=>{let{enabled:e,errors:t}=await u4();t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`);let n=(await Promise.all(e.map(async e=>{let t=new Set,n=[];if(e.agentsPath)try{let r=await m_t(e.agentsPath,e.name,e.source,e.path,e.manifest,t);n.push(...r),r.length>0&&U(`Loaded ${r.length} agents from plugin ${e.name} default directory`)}catch(t){U(`Failed to load agents from plugin ${e.name} default directory: ${t}`,{level:`error`})}if(e.agentsPaths){let r=await Promise.all(e.agentsPaths.map(async n=>{try{let r=await G().stat(n);if(r.isDirectory()){let r=await m_t(n,e.name,e.source,e.path,e.manifest,t);return r.length>0&&U(`Loaded ${r.length} agents from plugin ${e.name} custom path: ${n}`),r}else if(r.isFile()&&n.endsWith(`.md`)){let r=await h_t(n,e.name,[],e.source,e.path,e.manifest,t);if(r)return U(`Loaded agent from plugin ${e.name} custom file: ${n}`),[r]}return[]}catch(t){return U(`Failed to load agents from plugin ${e.name} custom path ${n}: ${t}`,{level:`error`}),[]}}));for(let e of r)n.push(...e)}return n}))).flat();return U(`Total plugin agents loaded: ${n.length}`),n})}));function __t(e){if(!e?.trim())return[];let t=uc(e,e=>`$${e}`);return t.success?t.tokens.filter(e=>typeof e==`string`):e.split(/\s+/).filter(Boolean)}function v_t(e){if(!e)return[];let t=e=>typeof e==`string`&&e.trim()!==``&&!/^\d+$/.test(e);return Array.isArray(e)?e.filter(t):typeof e==`string`?e.split(/\s+/).filter(t):[]}function y_t(e,t){let n=e.slice(t.length);if(n.length!==0)return n.map(e=>`[${e}]`).join(` `)}function J0(e,t,n=!0,r=[]){if(t==null)return e;let i=__t(t),a=e;for(let t=0;t<r.length;t++){let n=r[t];n&&(e=e.replace(RegExp(`\\$${n}(?![\\[\\w])`,`g`),i[t]??``))}return e=e.replace(/\$ARGUMENTS\[(\d+)\]/g,(e,t)=>i[parseInt(t,10)]??``),e=e.replace(/\$(\d+)(?!\w)/g,(e,t)=>i[parseInt(t,10)]??``),e=e.replaceAll(`$ARGUMENTS`,t),e===a&&n&&t&&(e=`${e}\n\nARGUMENTS: ${t}`),e}var Y0=n((()=>{pc()}));async function b_t(e,t,n,r){let i=e,a=r===`powershell`&&Uoe()?C_t():SW,o=e.matchAll(w_t),s=e.includes("!`")?e.matchAll(T_t):[];return await Promise.all([...o,...s].map(async e=>{let r=e[1]?.trim();if(r)try{let o=await A9(a,{command:r},t,k4({content:[]}),``);if(o.behavior!==`allow`)throw U(`Shell command permission check failed for command in ${n}: ${r}. Error: ${o.message}`),new Un(`Shell command permission check failed for pattern "${e[0]}": ${o.message||`Permission denied`}`);let{data:s}=await a.call({command:r},t),c=await Py(a,s,bl()),l=typeof c.content==`string`?c.content:x_t(s.stdout,s.stderr);i=i.replace(e[0],()=>l)}catch(t){if(t instanceof Un)throw t;S_t(t,e[0])}})),i}function x_t(e,t,n=!1){let r=[];return e.trim()&&r.push(e.trim()),t.trim()&&(n?r.push(`[stderr: ${t.trim()}]`):r.push(`[stderr]\n${t.trim()}`)),r.join(n?` `:`
2601
- `)}function S_t(e,t,n=!1){if(e instanceof bn)throw e.interrupted?new Un(`Shell command interrupted for pattern "${t}": [Command interrupted]`):new Un(`Shell command failed for pattern "${t}": ${x_t(e.stdout,e.stderr,n)}`);let r=H(e);throw new Un(n?`[Error: ${r}]`:`[Error]\n${r}`)}var C_t,w_t,T_t,E_t=n((()=>{CW(),W(),On(),m3(),j9(),zy(),qs(),C_t=(()=>{let t;return()=>(t||(t=(Z$(),e(U$)).PowerShellTool),t)})(),w_t=/```!\s*\n?([\s\S]*?)\n?```/g,T_t=/(?<=^|\s)!`([^`]+)`/gm}));function X0(e){return/^skill\.md$/i.test(Kc(e))}function D_t(e,t,n){if(X0(e)){let r=qc(e),i=qc(r),a=Kc(r),o=i.startsWith(t)?i.slice(t.length).replace(/^\//,``):``,s=o?o.split(`/`).join(`:`):``;return s?`${n}:${s}:${a}`:`${n}:${a}`}else{let r=qc(e),i=Kc(e).replace(/\.md$/,``),a=r.startsWith(t)?r.slice(t.length).replace(/^\//,``):``,o=a?a.split(`/`).join(`:`):``;return o?`${n}:${o}:${i}`:`${n}:${i}`}}async function O_t(e,t,n){let r=[],i=G();return await U0(e,async e=>{if(Kn(i,e,n))return;let{frontmatter:a,content:o}=od(await i.readFile(e,{encoding:`utf-8`}),e);r.push({filePath:e,baseDir:t,frontmatter:a,content:o})},{stopAtSkillDir:!0,logLabel:`commands`}),r}function k_t(e){let t=new Map;for(let n of e){let e=qc(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=>X0(e.filePath));if(t.length>0){let r=t[0];t.length>1&&U(`Multiple skill files found in ${e}, using ${Kc(r.filePath)}`),n.push(r)}else n.push(...r)}return n}async function A_t(e,t,n,r,i,a={isSkillMode:!1},o=new Set){let s=k_t(await O_t(e,e,o)),c=[];for(let e of s){let o=Z0(D_t(e.filePath,e.baseDir,t),e,n,r,i,X0(e.filePath),a);o&&c.push(o)}return c}function Z0(e,t,n,r,i,a,o={isSkillMode:!1}){try{let{frontmatter:s,content:c}=t,l=ud(s.description,e),u=l??B9(c,a?`Plugin skill`:`Plugin command`),d=s[`allowed-tools`],f=H9(typeof d==`string`?rT(d,{path:i,source:n}):Array.isArray(d)?d.map(e=>typeof e==`string`?rT(e,{path:i,source:n}):e):d),p=s[`argument-hint`],m=v_t(s.arguments),h=s.when_to_use,g=s.version,_=s.name,v=s.model===`inherit`?void 0:s.model?ro(s.model):void 0,y=dd(s[`disable-model-invocation`]),b=s[`user-invocable`],x=b===void 0||dd(b),S=fd(s.shell,e);return{type:`prompt`,name:e,description:u,hasUserSpecifiedDescription:l!==null,allowedTools:f,argumentHint:p,argNames:m.length>0?m:void 0,whenToUse:h,version:g,model:v,disableModelInvocation:y,userInvocable:x,contentLength:c.length,source:`plugin`,loadedFrom:a||o.isSkillMode?`plugin`:void 0,pluginInfo:{pluginManifest:r,repository:n},isHidden:!x,progressMessage:a||o.isSkillMode?`loading`:`running`,userFacingName(){return _||e},async getPromptForCommand(a,s){let l=o.isSkillMode?`Base directory for this skill: ${qc(t.filePath)}\n\n${c}`:c;if(l=J0(l,a,!0,m),l=rT(l,{path:i,source:n}),r.userConfig&&(l=Hke(l,aT(n),r.userConfig)),o.isSkillMode){let e=qc(t.filePath),n=process.platform===`win32`?e.replace(/\\/g,`/`):e;l=l.replace(/\$\{CLAUDE_SKILL_DIR\}/g,n)}return l=l.replace(/\$\{CLAUDE_SESSION_ID\}/g,sn()),l=await b_t(l,{...s,getAppState(){let e=s.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:f}}}}},`/${e}`,S),[{type:`text`,text:l}]}}}catch(e){return U(`Failed to create command from ${t.filePath}: ${e}`,{level:`error`}),null}}function j_t(){Q0.cache?.clear?.()}async function M_t(e,t,n,r,i,a){let o=G(),s=[],c=Y(e,`SKILL.md`),l=null;try{l=await o.readFile(c,{encoding:`utf-8`})}catch(e){if(!xn(e))return U(`Failed to load skill from ${c}: ${e}`,{level:`error`}),s}if(l!==null){if(Kn(o,c,a))return s;try{let{frontmatter:a,content:o}=od(l,c),u=Z0(`${t}:${Kc(e)}`,{filePath:c,baseDir:qc(c),frontmatter:a,content:o},n,r,i,!0,{isSkillMode:!0});u&&s.push(u)}catch(e){U(`Failed to load skill from ${c}: ${e}`,{level:`error`})}return s}let u;try{u=await o.readdir(e)}catch(t){return xn(t)||U(`Failed to load skills from directory ${e}: ${t}`,{level:`error`}),s}return await Promise.all(u.map(async c=>{if(!c.isDirectory()&&!c.isSymbolicLink())return;let l=Y(Y(e,c.name),`SKILL.md`),u;try{u=await o.readFile(l,{encoding:`utf-8`})}catch(e){xn(e)||U(`Failed to load skill from ${l}: ${e}`,{level:`error`});return}if(!Kn(o,l,a))try{let{frontmatter:e,content:a}=od(u,l),o=Z0(`${t}:${c.name}`,{filePath:l,baseDir:qc(l),frontmatter:e,content:a},n,r,i,!0,{isSkillMode:!0});o&&s.push(o)}catch(e){U(`Failed to load skill from ${l}: ${e}`,{level:`error`})}})),s}function N_t(){$0.cache?.clear?.()}var Q0,$0,e2=n((()=>{d(),Wt(),Wg(),Y0(),W(),h(),On(),gd(),Bn(),K9(),No(),E_t(),d4(),oT(),W0(),Q0=u(async()=>{if(v()&&kt().length===0)return[];let{enabled:e,errors:t}=await u4();t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`);let n=(await Promise.all(e.map(async e=>{let t=new Set,n=[];if(e.commandsPath)try{let r=await A_t(e.commandsPath,e.name,e.source,e.manifest,e.path,{isSkillMode:!1},t);n.push(...r),r.length>0&&U(`Loaded ${r.length} commands from plugin ${e.name} default directory`)}catch(t){U(`Failed to load commands from plugin ${e.name} default directory: ${t}`,{level:`error`})}if(e.commandsPaths){U(`Plugin ${e.name} has commandsPaths: ${e.commandsPaths.join(`, `)}`);let r=await Promise.all(e.commandsPaths.map(async n=>{try{let r=G(),i=await r.stat(n);if(U(`Checking commandPath ${n} - isDirectory: ${i.isDirectory()}, isFile: ${i.isFile()}`),i.isDirectory()){let r=await A_t(n,e.name,e.source,e.manifest,e.path,{isSkillMode:!1},t);return r.length>0?U(`Loaded ${r.length} commands from plugin ${e.name} custom path: ${n}`):U(`Warning: No commands found in plugin ${e.name} custom directory: ${n}. Expected .md files or SKILL.md in subdirectories.`,{level:`warn`}),r}else if(i.isFile()&&n.endsWith(`.md`)){if(Kn(r,n,t))return[];let{frontmatter:i,content:a}=od(await r.readFile(n,{encoding:`utf-8`}),n),o,s;if(e.commandsMetadata){for(let[t,r]of Object.entries(e.commandsMetadata))if(r.source&&n===Y(e.path,r.source)){o=`${e.name}:${t}`,s=r;break}}o||(o=`${e.name}:${Kc(n).replace(/\.md$/,``)}`);let c=s?{...i,...s.description&&{description:s.description},...s.argumentHint&&{"argument-hint":s.argumentHint},...s.model&&{model:s.model},...s.allowedTools&&{"allowed-tools":s.allowedTools.join(`,`)}}:i,l={filePath:n,baseDir:qc(n),frontmatter:c,content:a},u=Z0(o,l,e.source,e.manifest,e.path,!1);if(u)return U(`Loaded command from plugin ${e.name} custom file: ${n}${s?` (with metadata override)`:``}`),[u]}return[]}catch(t){return U(`Failed to load commands from plugin ${e.name} custom path ${n}: ${t}`,{level:`error`}),[]}}));for(let e of r)n.push(...e)}if(e.commandsMetadata){for(let[t,r]of Object.entries(e.commandsMetadata))if(r.content&&!r.source)try{let{frontmatter:i,content:a}=od(r.content,`<inline:${e.name}:${t}>`),o={...i,...r.description&&{description:r.description},...r.argumentHint&&{"argument-hint":r.argumentHint},...r.model&&{model:r.model},...r.allowedTools&&{"allowed-tools":r.allowedTools.join(`,`)}},s=`${e.name}:${t}`,c=Z0(s,{filePath:`<inline:${s}>`,baseDir:e.path,frontmatter:o,content:a},e.source,e.manifest,e.path,!1);c&&(n.push(c),U(`Loaded inline content command from plugin ${e.name}: ${s}`))}catch(n){U(`Failed to load inline content command ${t} from plugin ${e.name}: ${n}`,{level:`error`})}}return n}))).flat();return U(`Total plugin commands loaded: ${n.length}`),n}),$0=u(async()=>{if(v()&&kt().length===0)return[];let{enabled:e,errors:t}=await u4();t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`),U(`getPluginSkills: Processing ${e.length} enabled plugins`);let n=(await Promise.all(e.map(async e=>{let t=new Set,n=[];if(U(`Checking plugin ${e.name}: skillsPath=${e.skillsPath?`exists`:`none`}, skillsPaths=${e.skillsPaths?e.skillsPaths.length:0} paths`),e.skillsPath){U(`Attempting to load skills from plugin ${e.name} default skillsPath: ${e.skillsPath}`);try{let r=await M_t(e.skillsPath,e.name,e.source,e.manifest,e.path,t);n.push(...r),U(`Loaded ${r.length} skills from plugin ${e.name} default directory`)}catch(t){U(`Failed to load skills from plugin ${e.name} default directory: ${t}`,{level:`error`})}}if(e.skillsPaths){U(`Attempting to load skills from plugin ${e.name} skillsPaths: ${e.skillsPaths.join(`, `)}`);let r=await Promise.all(e.skillsPaths.map(async n=>{try{U(`Loading from skillPath: ${n} for plugin ${e.name}`);let r=await M_t(n,e.name,e.source,e.manifest,e.path,t);return U(`Loaded ${r.length} skills from plugin ${e.name} custom path: ${n}`),r}catch(t){return U(`Failed to load skills from plugin ${e.name} custom path ${n}: ${t}`,{level:`error`}),[]}}));for(let e of r)n.push(...e)}return n}))).flat();return U(`Total plugin skills loaded: ${n.length}`),n})}));function t2(){return m(process.env.CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE)}function n2(){if(!t2())return;let e=process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR;return e?T_(e):void 0}function P_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`known_marketplaces.json`)}function F_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`marketplaces`)}function I_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`plugins`)}async function L_t(){return r2||(i2||(i2=(async()=>{let e=yl(8).toString(`hex`),t=Y(Wc(),`claude-plugin-session-${e}`);return await G().mkdir(t),r2=t,U(`Created session plugin cache at ${t}`),t})()),i2)}async function R_t(){if(r2)try{await Ml(r2,{recursive:!0,force:!0}),U(`Cleaned up session plugin cache at ${r2}`)}catch(e){U(`Failed to clean up session plugin cache: ${e}`)}finally{r2=null,i2=null}}async function z_t(e,t){let n=qc(e);await G().mkdir(n);let r=Y(n,`.${Kc(e)}.tmp.${yl(4).toString(`hex`)}`);try{typeof t==`string`?await Il(r,t,{encoding:`utf-8`}):await Il(r,t),await jl(r,e)}catch(e){try{await Ml(r,{force:!0})}catch{}throw e}}async function B_t(e){let t={};await V_t(e,``,t,new Set);let{zipSync:n}=await import(`./esm-wGnzjq4Z.js`),r=n(t,{level:6});return U(`Created ZIP from ${e}: ${Object.keys(t).length} files, ${r.length} bytes`),r}async function V_t(e,t,n,r){let i=t?Y(e,t):e,a;try{a=await kl(i)}catch{return}try{let e=await Nl(i,{bigint:!0});if(e.dev!==0n||e.ino!==0n){let t=`${e.dev}:${e.ino}`;if(r.has(t)){U(`Skipping symlink cycle at ${i}`);return}r.add(t)}}catch{return}for(let o of a){if(o===`.git`)continue;let a=Y(i,o),s=t?`${t}/${o}`:o,c;try{c=await uue(a)}catch{continue}if(c.isSymbolicLink())try{let e=await Nl(a);if(e.isDirectory())continue;c=e}catch{continue}if(c.isDirectory())await V_t(e,s,n,r);else if(c.isFile())try{let e=await Ol(a);n[s]=[new Uint8Array(e),{os:3,attrs:(c.mode&65535)<<16}]}catch(e){U(`Failed to read file for zip: ${s}: ${e}`)}}}async function H_t(e,t){let n=await G().readFileBytes(e),r=await Ww(n),i=Gw(n);await G().mkdir(t);for(let[e,n]of Object.entries(r)){if(e.endsWith(`/`)){await G().mkdir(Y(t,e));continue}let r=Y(t,e);await G().mkdir(qc(r)),await Il(r,n);let a=i[e];a&&a&73&&await Cl(r,a&511).catch(()=>{})}U(`Extracted ZIP to ${t}: ${Object.keys(r).length} entries`)}async function U_t(e,t){await z_t(t,await B_t(e)),await Ml(e,{recursive:!0,force:!0})}function W_t(e){return Y(`marketplaces`,`${e.replace(/[^a-zA-Z0-9\-_]/g,`-`)}.json`)}function G_t(e){return[`github`,`git`,`url`,`settings`].includes(e.source)}var r2,i2,a2=n((()=>{W(),qw(),h(),Bn(),j_(),r2=null,i2=null}));function K_t(){c4(),j_t(),g_t(),Ez(),xze().catch(e=>q(e)),nT(),Hyt(),Gyt()}function q_t(){K_t(),qSt(),Ykt(),ube(),zgt()}async function o2(e){try{await Il(s2(e),`${Date.now()}`,`utf-8`)}catch(t){U(`Failed to write .orphaned_at: ${e}: ${t}`)}}async function J_t(){if(!t2())try{let e=X_t();if(!e)return;let t=$2(),n=Date.now();await Promise.all([...e].map(e=>Y_t(e)));for(let r of await c2(t)){let i=Y(t,r);for(let t of await c2(i)){let r=Y(i,t);for(let t of await c2(r)){let i=Y(r,t);e.has(i)||await Z_t(i,n)}await Q_t(r)}await Q_t(i)}}catch(e){U(`Plugin cache cleanup failed: ${e}`)}}function s2(e){return Y(e,$_t)}async function Y_t(e){let t=s2(e);try{await Fl(t)}catch(t){if(Cn(t)===`ENOENT`)return;U(`Failed to remove .orphaned_at: ${e}: ${t}`)}}function X_t(){try{let e=new Set,t=V2();for(let n of Object.values(t.plugins))for(let t of n)e.add(t.installPath);return e}catch(e){return U(`Failed to load installed plugins: ${e}`),null}}async function Z_t(e,t){let n=s2(e),r;try{r=(await Nl(n)).mtimeMs}catch(t){if(Cn(t)===`ENOENT`){await o2(e);return}U(`Failed to stat orphaned marker: ${e}: ${t}`);return}if(t-r>evt)try{await Ml(e,{recursive:!0,force:!0})}catch(t){U(`Failed to delete orphaned version: ${e}: ${t}`)}}async function Q_t(e){if((await c2(e)).length===0)try{await Ml(e,{recursive:!0,force:!0})}catch(t){U(`Failed to remove empty dir: ${e}: ${t}`)}}async function c2(e){try{return(await kl(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}var $_t,evt,l2=n((()=>{e6(),v4(),$9(),V_(),H0(),W(),On(),Qi(),K2(),q0(),e2(),jz(),p4(),d4(),oT(),a2(),$_t=`.orphaned_at`,evt=10080*60*1e3}));function tvt(e,t){let n=e.slice(0,2).map(e=>{let n=e.reason||e.error||`unknown error`;return t?`${e.name} (${n})`:e.name}).join(t?`; `:`, `),r=e.length-2;return`${n}${r>0?` and ${r} more`:``}`}function nvt(e){switch(e.source){case`github`:return e.repo;case`url`:return e.url;case`git`:return e.url;case`directory`:return e.path;case`file`:return e.path;case`settings`:return`settings:${e.name}`;default:return`Unknown source`}}function rvt(e,t){return`${e}@${t}`}async function ivt(e){let t=[],n=[];for(let[r,i]of Object.entries(e)){if(!p2(i.source))continue;let e=null;try{e=await P2(r)}catch(e){let t=e instanceof Error?e.message:String(e);n.push({name:r,error:t}),q(jn(e))}t.push({name:r,config:i,data:e})}return{marketplaces:t,failures:n}}function avt(e,t){return e.length===0?null:t>0?{type:`warning`,message:e.length===1?`Warning: Failed to load marketplace '${e[0].name}': ${e[0].error}`:`Warning: Failed to load ${e.length} marketplaces: ${ovt(e)}`}:{type:`error`,message:`Failed to load all marketplaces. Errors: ${svt(e)}`}}function ovt(e){return e.map(e=>e.name).join(`, `)}function svt(e){return e.map(e=>`${e.name}: ${e.error}`).join(`; `)}function u2(){let e=Ir(`policySettings`);return e?.strictKnownMarketplaces?e.strictKnownMarketplaces:null}function cvt(){let e=Ir(`policySettings`);return e?.blockedMarketplaces?e.blockedMarketplaces:null}function lvt(){return Ir(`policySettings`)?.pluginTrustMessage}function uvt(e,t){if(e.source!==t.source)return!1;switch(e.source){case`url`:return e.url===t.url;case`github`:return e.repo===t.repo&&(e.ref||void 0)===(t.ref||void 0)&&(e.path||void 0)===(t.path||void 0);case`git`:return e.url===t.url&&(e.ref||void 0)===(t.ref||void 0)&&(e.path||void 0)===(t.path||void 0);case`npm`:return e.package===t.package;case`file`:return e.path===t.path;case`directory`:return e.path===t.path;case`settings`:return e.name===t.name&&Io(e.plugins,t.plugins);default:return!1}}function dvt(e){switch(e.source){case`github`:return`github.com`;case`git`:{let t=e.url.match(/^[^@]+@([^:]+):/);if(t?.[1])return t[1];try{return new URL(e.url).hostname}catch{return null}}case`url`:try{return new URL(e.url).hostname}catch{return null}default:return null}}function fvt(e,t){let n=dvt(e);if(!n)return!1;try{return new RegExp(t.hostPattern).test(n)}catch{return q(Error(`Invalid hostPattern regex: ${t.hostPattern}`)),!1}}function pvt(e,t){if(e.source!==`file`&&e.source!==`directory`)return!1;try{return new RegExp(t.pathPattern).test(e.path)}catch{return q(Error(`Invalid pathPattern regex: ${t.pathPattern}`)),!1}}function mvt(){let e=u2();return e?e.filter(e=>e.source===`hostPattern`).map(e=>e.hostPattern):[]}function hvt(e){let t=e.match(/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);if(t?.[1])return t[1];let n=e.match(/^https?:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);return n?.[1]?n[1]:null}function d2(e,t){return!e||(e||void 0)===(t||void 0)}function gvt(e,t){if(e.source===t.source)switch(e.source){case`github`:{let n=t;return e.repo===n.repo&&d2(n.ref,e.ref)&&d2(n.path,e.path)}case`git`:{let n=t;return e.url===n.url&&d2(n.ref,e.ref)&&d2(n.path,e.path)}case`url`:return e.url===t.url;case`npm`:return e.package===t.package;case`file`:return e.path===t.path;case`directory`:return e.path===t.path;case`settings`:return e.name===t.name;default:return!1}return e.source===`git`&&t.source===`github`&&hvt(e.url)===t.repo||e.source===`github`&&t.source===`git`&&hvt(t.url)===e.repo?d2(t.ref,e.ref)&&d2(t.path,e.path):!1}function f2(e){let t=cvt();return t!==null&&t.some(t=>gvt(e,t))}function p2(e){if(f2(e))return!1;let t=u2();return t===null||t.some(t=>t.source===`hostPattern`?fvt(e,t):t.source===`pathPattern`?pvt(e,t):uvt(e,t))}function m2(e){switch(e.source){case`github`:return`github:${e.repo}${e.ref?`@${e.ref}`:``}`;case`url`:return e.url;case`git`:return`git:${e.url}${e.ref?`@${e.ref}`:``}`;case`npm`:return`npm:${e.package}`;case`file`:return`file:${e.path}`;case`directory`:return`dir:${e.path}`;case`hostPattern`:return`hostPattern:${e.hostPattern}`;case`pathPattern`:return`pathPattern:${e.pathPattern}`;case`settings`:return`settings:${e.name} (${e.plugins.length} ${qa(e.plugins.length,`plugin`)})`;default:return`unknown source`}}async function _vt({configuredMarketplaceCount:e,failedMarketplaceCount:t}){if(!await c_())return`git-not-installed`;let n=u2();if(n!==null){if(n.length===0)return`all-blocked-by-policy`;if(e===0)return`policy-restricts-sources`}return e===0?`no-marketplaces-configured`:t>0&&t===e?`all-marketplaces-failed`:`all-plugins-installed`}var h2=n((()=>{Ho(),On(),Qi(),Vr(),Ja(),l_(),F2()}));async function g2(e,t){let n=el(t),r=el(e);if(r!==n&&!r.startsWith(n+tl))return U(`fetchOfficialMarketplaceFromGcs: refusing path outside cache dir: ${e}`,{level:`error`}),null;await jte();let i=performance.now(),a=`failed`,o,s,c;try{let t=await ue.get(`${_2}/latest`,{responseType:`text`,timeout:1e4});if(o=String(t.data).trim(),!o)throw Error(`latest pointer returned empty body`);if(await Ol(Y(e,`.gcs-sha`),`utf8`).then(e=>e.trim(),()=>null)===o)return a=`noop`,o;let n=await ue.get(`${_2}/${o}.zip`,{responseType:`arraybuffer`,timeout:6e4}),r=Buffer.from(n.data);s=r.length;let i=await Ww(r),c=Gw(r),l=`${e}.staging`;await Ml(l,{recursive:!0,force:!0}),await El(l,{recursive:!0});for(let[e,t]of Object.entries(i)){if(!e.startsWith(yvt))continue;let n=e.slice(37);if(!n||n.endsWith(`/`))continue;let r=Y(l,n);await El(qc(r),{recursive:!0}),await Il(r,t);let i=c[e];i&&i&73&&await Cl(r,i&511).catch(()=>{})}return await Il(Y(l,`.gcs-sha`),o),await Ml(e,{recursive:!0,force:!0}),await jl(l,e),a=`updated`,o}catch(e){return c=vvt(e),U(`Official marketplace GCS fetch failed: ${H(e)}`,{level:`warn`}),null}finally{J(`tengu_plugin_remote_fetch`,{source:`marketplace_gcs`,host:`downloads.workmate.ai`,is_official:!0,outcome:a,duration_ms:Math.round(performance.now()-i),...s!==void 0&&{bytes:s},...o&&{sha:o},...c&&{error_kind:c}})}}function vvt(e){if(ue.isAxiosError(e))return e.code===`ECONNABORTED`?`timeout`:e.response?`http_${e.response.status}`:`network`;let t=Cn(e);if(t&&/^E[A-Z]+$/.test(t)&&!t.startsWith(`ERR_`))return bvt.has(t)?`fs_${t}`:`fs_other`;if(typeof e?.code==`number`)return`zip_parse`;let n=H(e);return/unzip|invalid zip|central directory/i.test(n)?`zip_parse`:/empty body/.test(n)?`empty_latest`:`other`}var _2,yvt,bvt,xvt=n((()=>{de(),Wt(),Da(),W(),qw(),On(),_2=`https://downloads.workmate.ai/claude-code-releases/plugins/claude-plugins-official`,yvt=`marketplaces/claude-plugins-official/`,bvt=new Set([`ENOSPC`,`EACCES`,`EPERM`,`EXDEV`,`EBUSY`,`ENOENT`,`ENOTDIR`,`EROFS`,`EMFILE`,`ENAMETOOLONG`])}));function v2(){return Y(M_(),`known_marketplaces.json`)}function y2(){return Y(M_(),`marketplaces`)}function Svt(){P2.cache?.clear?.()}function Cvt(){let e={},t={...Jg(),...Xr().enabledPlugins??{}};for(let[n,r]of Object.entries(t))if(r&&Zg(n).marketplace===`claude-plugins-official`){e[r_]={source:n_,sourceIsFallback:!0};break}return{...e,...Tye(),...Xr().extraKnownMarketplaces??{}}}function wvt(e){for(let t of[`localSettings`,`projectSettings`,`userSettings`])if(Ir(t)?.extraKnownMarketplaces?.[e])return t;return null}function Tvt(e,t,n=`userSettings`){let r={...(Ir(n)??{}).extraKnownMarketplaces};r[e]=t,li(n,{extraKnownMarketplaces:r})}async function b2(){let e=G(),t=v2();try{let n=kn(await e.readFile(t,{encoding:`utf-8`})),r=Rr().safeParse(n);if(!r.success){let e=`Marketplace configuration file is corrupted: ${r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`;throw U(e,{level:`error`}),new Dn(e,t,n)}return r.data}catch(e){if(xn(e))return{};if(e instanceof Dn)throw e;let t=`Failed to load marketplace configuration: ${H(e)}`;throw U(t,{level:`error`}),Error(t)}}async function Evt(){try{return await b2()}catch{return{}}}async function x2(e){let t=Rr().safeParse(e),n=v2();if(!t.success)throw new Dn(`Invalid marketplace config: ${t.error.message}`,n,e);let r=G(),i=Y(n,`..`);await r.mkdir(i),An(n,V(t.data,null,2),{encoding:`utf-8`,flush:!0})}async function Dvt(){let e=N_();if(e.length===0)return!1;let t=await b2(),n=new Set,r=0;for(let i of e){let e=await Ovt(i);if(e)for(let[a,o]of Object.entries(e)){if(n.has(a))continue;let e=await kvt(i,a);if(!e){U(`Seed marketplace '${a}' not found under ${i}/marketplaces/, skipping`,{level:`warn`});continue}n.add(a);let s={source:o.source,installLocation:e,lastUpdated:o.lastUpdated,autoUpdate:!1};Io(t[a],s)||(t[a]=s,r++)}}return r>0?(await x2(t),U(`Synced ${r} marketplace(s) from seed dir(s)`),!0):!1}async function Ovt(e){let t=Y(e,`known_marketplaces.json`);try{let n=await G().readFile(t,{encoding:`utf-8`}),r=Rr().safeParse(kn(n));return r.success?r.data:(U(`Seed known_marketplaces.json invalid at ${e}: ${r.error.message}`,{level:`warn`}),null)}catch(t){return xn(t)||U(`Failed to read seed known_marketplaces.json at ${e}: ${t}`,{level:`warn`}),null}}async function kvt(e,t){let n=Y(e,`marketplaces`,t),r=Y(e,`marketplaces`,`${t}.json`);for(let e of[n,r])try{return await A2(e),e}catch{}return null}function S2(e){return N_().find(t=>e===t||e.startsWith(t+tl))}function C2(){let e=process.env.CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS;if(e){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}return Kvt}async function Avt(e,t,n){U(`git pull: cwd=${e} ref=${t??`default`}`);let r={...process.env,...N2},i=n?.disableCredentialHelper?[`-c`,`credential.helper=`]:[];if(t){let a=await Li(Pi(),[...i,`fetch`,`origin`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});if(a.code!==0)return w2(a);let o=await Li(Pi(),[...i,`checkout`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});if(o.code!==0)return w2(o);let s=await Li(Pi(),[...i,`pull`,`origin`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});return s.code===0?(await jvt(e,i,r,n?.sparsePaths),s):w2(s)}let a=await Li(Pi(),[...i,`pull`,`origin`,`HEAD`],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});return a.code===0?(await jvt(e,i,r,n?.sparsePaths),a):w2(a)}async function jvt(e,t,n,r){if(r&&r.length>0||!await G().stat(Y(e,`.gitmodules`)).then(()=>!0,()=>!1))return;let i=await Li(Pi(),[`-c`,`core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes`,...t,`submodule`,`update`,`--init`,`--recursive`,`--depth`,`1`],{cwd:e,timeout:C2(),stdin:`ignore`,env:n});i.code!==0&&U(`git submodule update failed (non-fatal): ${i.stderr}`,{level:`warn`})}function w2(e){if(e.code===0)return e;if(e.error?.includes(`timed out`)){let t=Math.round(C2()/1e3);return{...e,stderr:`Git pull timed out after ${t}s. Try increasing the timeout via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS environment variable.\n\nOriginal error: ${e.stderr}`}}return e.stderr.includes(`REMOTE HOST IDENTIFICATION HAS CHANGED`)?{...e,stderr:`SSH host key for this marketplace's git host has changed (server key rotation or possible MITM). Remove the stale entry with: ssh-keygen -R <host>\nThen connect once manually to accept the new key.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`Host key verification failed`)?{...e,stderr:`SSH host key verification failed while updating marketplace. The host key is not in your known_hosts file. Connect once manually to add it (e.g., ssh -T git@<host>), or remove and re-add the marketplace with an HTTPS URL.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`Permission denied (publickey)`)||e.stderr.includes(`Could not read from remote repository`)?{...e,stderr:`SSH authentication failed while updating marketplace. Please ensure your SSH keys are configured.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`timed out`)||e.stderr.includes(`Could not resolve host`)?{...e,stderr:`Network error while updating marketplace. Please check your internet connection.\n\nOriginal error: ${e.stderr}`}:e}async function Mvt(){try{let e=await Bi(`ssh`,[`-T`,`-o`,`BatchMode=yes`,`-o`,`ConnectTimeout=2`,`-o`,`StrictHostKeyChecking=yes`,`git@github.com`],{timeout:3e3}),t=e.code===1&&(e.stderr?.includes(`successfully authenticated`)||e.stdout?.includes(`successfully authenticated`));return U(`SSH config check: code=${e.code} configured=${t}`),t}catch(e){return U(`SSH configuration check failed: ${H(e)}`,{level:`warn`}),!1}}function Nvt(e){return e.includes(`Authentication failed`)||e.includes(`could not read Username`)||e.includes(`terminal prompts disabled`)||e.includes(`403`)||e.includes(`401`)}function Pvt(e){return e.match(/^[^@]+@([^:]+):/)?.[1]??null}async function Fvt(e,t,n,r){let i=r&&r.length>0,a=[`-c`,`core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes`,`clone`,`--depth`,`1`];i?a.push(`--filter=blob:none`,`--no-checkout`):a.push(`--recurse-submodules`,`--shallow-submodules`),n&&a.push(`--branch`,n),a.push(e,t);let o=C2();U(`git clone: url=${D2(e)} ref=${n??`default`} timeout=${o}ms`);let s=await Li(Pi(),a,{timeout:o,stdin:`ignore`,env:{...process.env,...N2}}),c=D2(e);if(e!==c&&(s.error&&(s.error=s.error.replaceAll(e,c)),s.stderr&&(s.stderr=s.stderr.replaceAll(e,c))),s.code===0){if(i){let e=await Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,...r],{cwd:t,timeout:o,stdin:`ignore`,env:{...process.env,...N2}});if(e.code!==0)return{code:e.code,stderr:`git sparse-checkout set failed: ${e.stderr}`};let n=await Li(Pi(),[`checkout`,`HEAD`],{cwd:t,timeout:o,stdin:`ignore`,env:{...process.env,...N2}});if(n.code!==0)return{code:n.code,stderr:`git checkout after sparse-checkout failed: ${n.stderr}`}}return U(`git clone succeeded: ${D2(e)}`),s}if(U(`git clone failed: url=${D2(e)} code=${s.code} error=${s.error??`none`} stderr=${s.stderr}`,{level:`warn`}),s.error?.includes(`timed out`))return{...s,stderr:`Git clone timed out after ${Math.round(o/1e3)}s. The repository may be too large for the current timeout. Set CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to increase it (e.g., 300000 for 5 minutes).\n\nOriginal error: ${s.stderr}`};if(s.stderr){if(s.stderr.includes(`REMOTE HOST IDENTIFICATION HAS CHANGED`)){let t=Pvt(e),n=t?`ssh-keygen -R ${t}`:`ssh-keygen -R <host>`;return{...s,stderr:`SSH host key has changed (server key rotation or possible MITM). Remove the stale known_hosts entry:\n ${n}\nThen connect once manually to verify and accept the new key.\n\nOriginal error: ${s.stderr}`}}if(s.stderr.includes(`Host key verification failed`)){let t=Pvt(e),n=t?`ssh -T git@${t}`:`ssh -T git@<host>`;return{...s,stderr:`SSH host key is not in your known_hosts file. To add it, connect once manually (this will show the fingerprint for you to verify):\n ${n}\n\nOr use an HTTPS URL instead (recommended for public repos).\n\nOriginal error: ${s.stderr}`}}if(s.stderr.includes(`Permission denied (publickey)`)||s.stderr.includes(`Could not read from remote repository`))return{...s,stderr:`SSH authentication failed. Please ensure your SSH keys are configured for GitHub, or use an HTTPS URL instead.\n\nOriginal error: ${s.stderr}`};if(Nvt(s.stderr))return{...s,stderr:`HTTPS authentication failed. Please ensure your credential helper is configured (e.g., gh auth login).\n\nOriginal error: ${s.stderr}`};if(s.stderr.includes(`timed out`)||s.stderr.includes(`timeout`)||s.stderr.includes(`Could not resolve host`))return{...s,stderr:`Network error or timeout while cloning repository. Please check your internet connection and try again.\n\nOriginal error: ${s.stderr}`}}return s.stderr?s:{code:s.code,stderr:s.error||`git clone exited with code ${s.code} (no stderr output). Run with --debug to see the full command.`}}function T2(e,t){if(e)try{e(t)}catch(e){U(`Progress callback error: ${H(e)}`,{level:`warn`})}}async function Ivt(e,t){let n={...process.env,...N2};if(t&&t.length>0)return Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,...t],{cwd:e,timeout:C2(),stdin:`ignore`,env:n});let r=await Li(Pi(),[`config`,`--get`,`core.sparseCheckout`],{cwd:e,stdin:`ignore`,env:n});return r.code===0&&r.stdout.trim()===`true`?{code:1,stderr:`sparsePaths removed from config but repository is sparse; re-cloning for full checkout`}:{code:0,stderr:``}}async function E2(e,t,n,r,i,a){let o=G(),s=Math.round(C2()/1e3);T2(i,`Refreshing marketplace cache (timeout: ${s}s)…`);let c=await Ivt(t,r);if(c.code===0){let i=performance.now(),o=await Avt(t,n,{disableCredentialHelper:a?.disableCredentialHelper,sparsePaths:r});if(a_(`marketplace_pull`,e,o.code===0?`success`:`failure`,performance.now()-i,o.code===0?void 0:o_(o.stderr)),o.code===0)return;U(`git pull failed, will re-clone: ${o.stderr}`,{level:`warn`})}else U(`sparse-checkout reconcile requires re-clone: ${c.stderr}`);try{await o.rm(t,{recursive:!0}),U(`Found stale marketplace directory at ${t}, cleaning up to allow re-clone`,{level:`warn`}),T2(i,`Found stale directory, cleaning up and re-cloning…`)}catch(e){if(!xn(e)){let n=H(e);throw Error(`Failed to clean up existing marketplace directory. Please manually delete the directory at ${t} and try again.\n\nTechnical details: ${n}`)}}let l=n?` (ref: ${n})`:``;T2(i,`Cloning repository (timeout: ${s}s): ${D2(e)}${l}`);let u=performance.now(),d=await Fvt(e,t,n,r);if(a_(`marketplace_clone`,e,d.code===0?`success`:`failure`,performance.now()-u,d.code===0?void 0:o_(d.stderr)),d.code!==0){try{await o.rm(t,{recursive:!0,force:!0})}catch{}throw Error(`Failed to clone marketplace repository: ${d.stderr}`)}T2(i,`Clone complete, validating marketplace…`)}function Lvt(e){return Object.fromEntries(Object.entries(e).map(([e])=>[e,`***REDACTED***`]))}function D2(e){try{let t=new URL(e);if((t.protocol===`http:`||t.protocol===`https:`)&&(t.username||t.password))return t.username&&(t.username=`***`),t.password&&(t.password=`***`),t.toString()}catch{}return e}async function Rvt(e,t,n,r){let i=G(),a=D2(e);T2(r,`Downloading marketplace from ${a}`),U(`Downloading marketplace from URL: ${a}`),n&&Object.keys(n).length>0&&U(`Using custom headers: ${V(Lvt(n))}`);let o={...n,"User-Agent":`Claude-Code-Plugin-Manager`},s,c=performance.now();try{s=await ue.get(e,{timeout:1e4,headers:o})}catch(t){if(a_(`marketplace_url`,e,`failure`,performance.now()-c,o_(t)),ue.isAxiosError(t)){if(t.code===`ECONNREFUSED`||t.code===`ENOTFOUND`)throw Error(`Could not connect to ${a}. Please check your internet connection and verify the URL is correct.\n\nTechnical details: ${t.message}`);if(t.code===`ETIMEDOUT`)throw Error(`Request timed out while downloading marketplace from ${a}. The server may be slow or unreachable.\n\nTechnical details: ${t.message}`);if(t.response)throw Error(`HTTP ${t.response.status} error while downloading marketplace from ${a}. The marketplace file may not exist at this URL.\n\nTechnical details: ${t.message}`)}throw Error(`Failed to download marketplace from ${a}: ${H(t)}`)}T2(r,`Validating marketplace data`);let l=Nr().safeParse(s.data);if(!l.success)throw a_(`marketplace_url`,e,`failure`,performance.now()-c,`invalid_schema`),new Dn(`Invalid marketplace schema from URL: ${l.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`,a,s.data);a_(`marketplace_url`,e,`success`,performance.now()-c),T2(r,`Saving marketplace to cache`);let u=Y(t,`..`);await i.mkdir(u),An(t,V(l.data,null,2),{encoding:`utf-8`,flush:!0})}function zvt(e){return e.source===`github`?e.repo.replace(`/`,`-`):e.source===`npm`?e.package.replace(`@`,``).replace(`/`,`-`):e.source===`file`?Kc(e.path).replace(`.json`,``):e.source===`directory`?Kc(e.path):`temp_${Date.now()}`}async function O2(e,t){let n=await G().readFile(e,{encoding:`utf-8`}),r;try{r=kn(n)}catch(t){throw new Dn(`Invalid JSON in ${e}: ${H(t)}`,e,n)}let i=t.safeParse(r);if(!i.success)throw new Dn(`Invalid schema: ${e} ${i.error?.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`,e,r);return i.data}async function k2(e,t){let n=G(),r=y2();await n.mkdir(r);let i,a,o=!1,s=zvt(e);try{switch(e.source){case`url`:i=Y(r,`${s}.json`),o=!0,await Rvt(e.url,i,e.headers,t),a=i;break;case`github`:{let c=`git@github.com:${e.repo}.git`,l=`https://github.com/${e.repo}.git`;i=Y(r,s),o=!0;let u=null;if(await Mvt()){T2(t,`Cloning via SSH: ${c}`);try{await E2(c,i,e.ref,e.sparsePaths,t)}catch(r){u=jn(r),q(u),T2(t,`SSH clone failed, retrying with HTTPS: ${l}`),U(`SSH clone failed for ${e.repo} despite SSH being configured, falling back to HTTPS`,{level:`info`}),await n.rm(i,{recursive:!0,force:!0});try{await E2(l,i,e.ref,e.sparsePaths,t),u=null}catch(e){u=jn(e),q(u)}}}else{T2(t,`SSH not configured, cloning via HTTPS: ${l}`),U(`SSH not configured for GitHub, using HTTPS for ${e.repo}`,{level:`info`});try{await E2(l,i,e.ref,e.sparsePaths,t)}catch(r){u=jn(r),q(u),T2(t,`HTTPS clone failed, retrying with SSH: ${c}`),U(`HTTPS clone failed for ${e.repo} (${u.message}), falling back to SSH`,{level:`info`}),await n.rm(i,{recursive:!0,force:!0});try{await E2(c,i,e.ref,e.sparsePaths,t),u=null}catch(e){u=jn(e),q(u)}}}if(u)throw u;a=Y(i,e.path||`.claude-plugin/marketplace.json`);break}case`git`:i=Y(r,s),o=!0,await E2(e.url,i,e.ref,e.sparsePaths,t),a=Y(i,e.path||`.claude-plugin/marketplace.json`);break;case`npm`:throw Error(`NPM marketplace sources not yet implemented`);case`file`:{let t=el(e.path);a=t,i=qc(qc(t)),o=!1;break}case`directory`:{let t=el(e.path);a=Y(t,`.claude-plugin`,`marketplace.json`),i=t,o=!1;break}case`settings`:i=Y(r,e.name),a=Y(i,`.claude-plugin`,`marketplace.json`),o=!1,await n.mkdir(qc(a)),await Il(a,V({name:e.name,owner:e.owner??{name:`settings`},plugins:e.plugins},null,2));break;default:throw Error(`Unsupported marketplace source type`)}U(`Reading marketplace from ${a}`);let c;try{c=await O2(a,Nr())}catch(e){throw xn(e)?Error(`Marketplace file not found at ${a}`):Error(`Failed to parse marketplace file at ${a}: ${H(e)}`)}let l=Y(r,c.name),u=el(l),d=el(r);if(!u.startsWith(d+tl))throw Error(`Marketplace name '${c.name}' resolves to a path outside the cache directory`);if(i!==l&&!di(e))try{try{t?.(`Cleaning up old marketplace cache…`)}catch(e){U(`Progress callback error: ${H(e)}`,{level:`warn`})}await n.rm(l,{recursive:!0,force:!0}),await n.rename(i,l),i=l,o=!1}catch(e){let t=H(e);throw Error(`Failed to finalize marketplace cache. Please manually delete the directory at ${l} if it exists and try again.\n\nTechnical details: ${t}`)}return{marketplace:c,cachePath:i}}catch(t){if(o&&i&&!di(e))try{await n.rm(i,{recursive:!0,force:!0})}catch(e){U(`Warning: Failed to clean up temporary marketplace cache at ${i}: ${H(e)}`,{level:`warn`})}throw t}}async function Bvt(e,t){let n=e;if(di(e)&&!Yc(e.path)&&(n={...e,path:el(e.path)}),!p2(n)){if(f2(n))throw Error(`Marketplace source '${m2(n)}' is blocked by enterprise policy.`);let e=u2()||[],t=mvt(),r=dvt(n),i=`Marketplace source '${m2(n)}'`;throw r&&(i+=` (${r})`),i+=` is blocked by enterprise policy.`,e.length>0?i+=` Allowed sources: ${e.map(e=>m2(e)).join(`, `)}`:i+=` No external marketplaces are allowed.`,n.source===`github`&&t.length>0&&(i+=`\n\nTip: The shorthand "${n.repo}" assumes github.com. For internal GitHub Enterprise, use the full URL:\n git@your-github-host.com:${n.repo}.git`),Error(i)}let r=await b2();for(let[e,t]of Object.entries(r))if(Io(t.source,n))return U(`Source already materialized as '${e}', skipping clone`),{name:e,alreadyMaterialized:!0,resolvedSource:n};let{marketplace:i,cachePath:a}=await k2(n,t),o=Qne(i.name,n);if(o)throw Error(o);let s=await b2(),c=s[i.name];if(c){let e=S2(c.installLocation);if(e)throw Error(`Marketplace '${i.name}' is seed-managed (${e}). To use a different source, ask your admin to update the seed, or use a different marketplace name.`);if(U(`Marketplace '${i.name}' exists with different source — overwriting`),!di(c.source)){let e=el(y2()),t=el(c.installLocation);t===el(a)||(t===e||t.startsWith(e+tl)?await G().rm(c.installLocation,{recursive:!0,force:!0}):U(`Skipping cleanup of old installLocation (${c.installLocation}) — outside ${e}. The path is corrupted; leaving it alone and overwriting the config entry.`,{level:`warn`}))}}return s[i.name]={source:n,installLocation:a,lastUpdated:new Date().toISOString()},await x2(s),U(`Added marketplace source: ${i.name}`),{name:i.name,alreadyMaterialized:!1,resolvedSource:n}}async function Vvt(e){let t=await b2();if(!t[e])throw Error(`Marketplace '${e}' not found`);let n=t[e],r=S2(n.installLocation);if(r)throw Error(`Marketplace '${e}' is registered from the read-only seed directory (${r}) and will be re-registered on next startup. To stop using its plugins: claude plugin disable <plugin>@${e}`);delete t[e],await x2(t);let i=G(),a=y2(),o=Y(a,e);await i.rm(o,{recursive:!0,force:!0});let s=Y(a,`${e}.json`);await i.rm(s,{force:!0});for(let t of[`userSettings`,`projectSettings`,`localSettings`]){let n=Ir(t);if(!n)continue;let r=!1,i={};if(n.extraKnownMarketplaces?.[e]){let t={...n.extraKnownMarketplaces};t[e]=void 0,i.extraKnownMarketplaces=t,r=!0}if(n.enabledPlugins){let t=`@${e}`,a={...n.enabledPlugins},o=!1;for(let e in a)e.endsWith(t)&&(a[e]=void 0,o=!0);o&&(i.enabledPlugins=a,r=!0)}if(r){let n=li(t,i);n.error?(q(n.error),U(`Failed to clean up marketplace '${e}' from ${t} settings: ${n.error.message}`)):U(`Cleaned up marketplace '${e}' from ${t} settings`)}}let{orphanedPaths:c,removedPluginIds:l}=eyt(e);for(let e of c)await o2(e);for(let e of l)Bke(e),await tbe(e);U(`Removed marketplace source: ${e}`)}async function A2(e){let t=Y(e,`.claude-plugin`,`marketplace.json`);try{return await O2(t,Nr())}catch(e){if(e instanceof Dn)throw e;let t=Cn(e);if(t!==`ENOENT`&&t!==`ENOTDIR`)throw e}return await O2(e,Nr())}async function j2(e){let t=G(),n=v2();try{let r=kn(await t.readFile(n,{encoding:`utf-8`}))[e];return r?await A2(r.installLocation):null}catch(t){return xn(t)||U(`Failed to read cached marketplace ${e}: ${H(t)}`,{level:`warn`}),null}}async function Hvt(e){let{name:t,marketplace:n}=Zg(e);if(!t||!n)return null;let r=G(),i=v2();try{let e=kn(await r.readFile(i,{encoding:`utf-8`}))[n];if(!e)return null;let a=await j2(n);if(!a)return null;let o=a.plugins.find(e=>e.name===t);return o?{entry:o,marketplaceInstallLocation:e.installLocation}:null}catch{return null}}async function M2(e){let t=await Hvt(e);if(t)return t;let{name:n,marketplace:r}=Zg(e);if(!n||!r)return null;try{let e=(await b2())[r];if(!e)return null;let t=(await P2(r)).plugins.find(e=>e.name===n);return t?{entry:t,marketplaceInstallLocation:e.installLocation}:null}catch(t){return U(`Could not find plugin ${e}: ${H(t)}`,{level:`debug`}),null}}async function Uvt(){let e=await b2();for(let[t,n]of Object.entries(e)){if(S2(n.installLocation)){U(`Skipping seed-managed marketplace '${t}' in bulk refresh`);continue}if(n.source.source!==`settings`){if(t===`claude-plugins-official`&&await g2(n.installLocation,y2())!==null){e[t].lastUpdated=new Date().toISOString();continue}try{let{cachePath:r}=await k2(n.source);e[t].lastUpdated=new Date().toISOString(),e[t].installLocation=r}catch(e){U(`Failed to refresh marketplace ${t}: ${H(e)}`,{level:`error`})}}}await x2(e)}async function Wvt(e,t,n){let r=await b2(),i=r[e];if(!i)throw Error(`Marketplace '${e}' not found. Available marketplaces: ${Object.keys(r).join(`, `)}`);if(P2.cache?.delete?.(e),i.source.source===`settings`){U(`Skipping refresh for settings-sourced marketplace '${e}' — no upstream`);return}try{let a=i.installLocation,o=i.source,s=S2(a);if(s)throw Error(`Marketplace '${e}' is seed-managed (${s}) and its content is controlled by the seed image. To update: ask your admin to update the seed.`);if(!di(o)){let t=el(y2()),n=el(a);if(n!==t&&!n.startsWith(t+tl))throw Error(`Marketplace '${e}' has a corrupted installLocation (${a}) — expected a path inside ${t}. This can happen after cross-platform path writes or manual edits to known_marketplaces.json. Run: claude plugin marketplace remove "${e}" and re-add it.`)}if(e===`claude-plugins-official`){if(await g2(a,y2())!==null){r[e]={...i,lastUpdated:new Date().toISOString()},await x2(r);return}U(`Official marketplace GCS failed; falling back to git`,{level:`warn`})}if(o.source===`github`||o.source===`git`){if(o.source===`github`){let e=`git@github.com:${o.repo}.git`,r=`https://github.com/${o.repo}.git`;if(m(process.env.CLAUDE_CODE_REMOTE))await E2(r,a,o.ref,o.sparsePaths,t,n);else{let i=await Mvt(),s=i?e:r,c=i?r:e;try{await E2(s,a,o.ref,o.sparsePaths,t,n)}catch{U(`Marketplace refresh failed with ${i?`SSH`:`HTTPS`} for ${o.repo}, falling back to ${i?`HTTPS`:`SSH`}`,{level:`info`}),await E2(c,a,o.ref,o.sparsePaths,t,n)}}}else await E2(o.url,a,o.ref,o.sparsePaths,t,n);try{await A2(a)}catch{let t=o.source===`github`?o.repo:D2(o.url);throw Error(`The marketplace.json file is no longer present in this repository.\n\n${e===`claude-code-plugins`?`We've deprecated "claude-code-plugins" in favor of "claude-plugins-official".`:`This marketplace may have been deprecated or moved to a new location.`}\nSource: ${t}\n\nYou can remove this marketplace with: claude plugin marketplace remove "${e}"`)}}else if(o.source===`url`)await Rvt(o.url,a,o.headers,t);else if(di(o))T2(t,`Validating local marketplace`),await A2(a);else throw Error(`Unsupported marketplace source type for refresh`);r[e].lastUpdated=new Date().toISOString(),await x2(r),U(`Successfully refreshed marketplace: ${e}`)}catch(t){let n=t instanceof Error?t.message:String(t);throw U(`Failed to refresh marketplace ${e}: ${n}`,{level:`error`}),Error(`Failed to refresh marketplace '${e}': ${n}`)}}async function Gvt(e,t){let n=await b2(),r=n[e];if(!r)throw Error(`Marketplace '${e}' not found. Available marketplaces: ${Object.keys(n).join(`, `)}`);let i=S2(r.installLocation);if(i)throw Error(`Marketplace '${e}' is seed-managed (${i}) and auto-update is always disabled for seed content. To update: ask your admin to update the seed.`);if(r.autoUpdate===t)return;n[e]={...r,autoUpdate:t},await x2(n);let a=wvt(e);if(a){let n=Ir(a)?.extraKnownMarketplaces?.[e];n&&Tvt(e,{source:n.source,autoUpdate:t},a)}U(`Set autoUpdate=${t} for marketplace: ${e}`)}var N2,Kvt,P2,F2=n((()=>{de(),Ho(),d(),W(),h(),On(),zi(),Bn(),Mi(),Qi(),Vr(),Yn(),Xg(),l2(),s_(),K2(),h2(),i_(),xvt(),I_(),$g(),oT(),si(),N2={GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``},Kvt=120*1e3,P2=u(async e=>{let t=await b2(),n=t[e];if(!n)throw Error(`Marketplace '${e}' not found in configuration. Available marketplaces: ${Object.keys(t).join(`, `)}`);if(di(n.source)&&!Yc(n.source.path))throw Error(`Marketplace "${e}" has a relative source path (${n.source.path}) in known_marketplaces.json — this is stale state from an older Work Mate version. Run 'claude marketplace remove ${e}' and re-add it from the original project directory.`);try{return await A2(n.installLocation)}catch(t){U(`Cache corrupted or missing for marketplace ${e}, re-fetching from source: ${H(t)}`,{level:`warn`})}let r;try{({marketplace:r}=await k2(n.source))}catch(t){throw Error(`Failed to load marketplace "${e}" from source (${n.source.source}): ${H(t)}`)}return t[e].lastUpdated=new Date().toISOString(),await x2(t),r})}));function I2(){return Y(M_(),`installed_plugins.json`)}function qvt(){return Y(M_(),`installed_plugins_v2.json`)}function Jvt(){if(U2)return;let e=G(),t=I2(),n=qvt();try{try{e.renameSync(n,t),U(`Renamed installed_plugins_v2.json to installed_plugins.json`),Yvt(z2()),U2=!0;return}catch(e){if(!xn(e))throw e}let r;try{r=e.readFileSync(t,{encoding:`utf-8`})}catch(e){if(!xn(e))throw e;U2=!0;return}let i=kn(r);if((typeof i?.version==`number`?i.version:1)===1){let e=Jr().parse(i),n=R2(e);An(t,V(n,null,2),{encoding:`utf-8`,flush:!0}),U(`Converted installed_plugins.json from V1 to V2 format (${Object.keys(e.plugins).length} plugins)`),Yvt(n)}U2=!0}catch(e){U(`Failed to migrate plugin files: ${H(e)}`,{level:`error`}),q(jn(e)),U2=!0}}function Yvt(e){let t=G(),n=$2();try{let r=new Set;for(let t of Object.values(e.plugins))for(let e of t)r.add(e.installPath);let i=t.readdirSync(n);for(let e of i){if(!e.isDirectory())continue;let i=e.name,a=Y(n,i);t.readdirSync(a).some(e=>{if(!e.isDirectory())return!1;let n=Y(a,e.name);return t.readdirSync(n).some(e=>e.isDirectory())})||r.has(a)||(t.rmSync(a,{recursive:!0,force:!0}),U(`Cleaned up legacy cache directory: ${i}`))}}catch(e){U(`Failed to clean up legacy cache: ${H(e)}`,{level:`warn`})}}function L2(){let e=G(),t=I2(),n;try{n=e.readFileSync(t,{encoding:`utf-8`})}catch(e){if(xn(e))return null;throw e}let r=kn(n);return{version:typeof r?.version==`number`?r.version:1,data:r}}function R2(e){let t={};for(let[n,r]of Object.entries(e.plugins))t[n]=[{scope:`user`,installPath:t4(n,r.version),version:r.version,installedAt:r.installedAt,lastUpdated:r.lastUpdated,gitCommitSha:r.gitCommitSha}];return{version:2,plugins:t}}function z2(){if(W2!==null)return W2;let e=I2();try{let t=L2();if(t){if(t.version===2){let n=oi().parse(t.data);return W2=n,U(`Loaded ${Object.keys(n.plugins).length} installed plugins from ${e}`),n}let n=Jr().parse(t.data),r=R2(n);return W2=r,U(`Loaded and converted ${Object.keys(n.plugins).length} plugins from V1 format`),r}return U(`installed_plugins.json doesn't exist, returning empty V2 object`),W2={version:2,plugins:{}},W2}catch(e){return U(`Failed to load installed_plugins.json: ${H(e)}. Starting with empty state.`,{level:`error`}),q(jn(e)),W2={version:2,plugins:{}},W2}}function B2(e){let t=G(),n=I2();try{t.mkdirSync(M_()),An(n,V(e,null,2),{encoding:`utf-8`,flush:!0}),W2=e,U(`Saved ${Object.keys(e.plugins).length} installed plugins to ${n}`)}catch(e){throw H(e),q(jn(e)),e}}function Xvt(e,t,n){let r=V2(),i=r.plugins[e];i&&(r.plugins[e]=i.filter(e=>!(e.scope===t&&e.projectPath===n)),r.plugins[e].length===0&&delete r.plugins[e],B2(r),U(`Removed installation for ${e} at scope ${t}`))}function Zvt(){return G2===null&&(G2=z2()),G2}function V2(){try{let e=L2();return e?e.version===2?oi().parse(e.data):R2(Jr().parse(e.data)):{version:2,plugins:{}}}catch(e){return U(`Failed to load installed plugins from disk: ${H(e)}`,{level:`error`}),{version:2,plugins:{}}}}function Qvt(e,t,n,r,i,a){let o=V2(),s=o.plugins[e];if(!s){U(`Cannot update ${e} on disk: plugin not found in installed plugins`);return}let c=s.find(e=>e.scope===t&&e.projectPath===n);c?(c.installPath=r,c.version=i,c.lastUpdated=new Date().toISOString(),a!==void 0&&(c.gitCommitSha=a),An(I2(),V(o,null,2),{encoding:`utf-8`,flush:!0}),W2=null,U(`Updated ${e} on disk to version ${i} at ${r}`)):U(`Cannot update ${e} on disk: no installation for scope ${t}`)}async function $vt(){Jvt();try{await oyt()}catch(e){q(e)}let e=Zvt();U(`Initialized versioned plugins system with ${Object.keys(e.plugins).length} plugins`)}function eyt(e){if(!e)return{orphanedPaths:[],removedPluginIds:[]};let t=V2(),n=`@${e}`,r=new Set,i=[];for(let e of Object.keys(t.plugins))if(e.endsWith(n)){for(let n of t.plugins[e]??[])n.installPath&&r.add(n.installPath);delete t.plugins[e],i.push(e),U(`Removed installed plugin for marketplace removal: ${e}`)}return i.length>0&&B2(t),{orphanedPaths:Array.from(r),removedPluginIds:i}}function tyt(e){return e.scope===`user`||e.scope===`managed`||e.projectPath===Xt()}function nyt(e){let t=z2().plugins[e];return!t||t.length===0||!t.some(tyt)?!1:zr().enabledPlugins?.[e]!==void 0}function ryt(e){let t=z2().plugins[e];return!t||t.length===0||!t.some(e=>e.scope===`user`||e.scope===`managed`)?!1:zr().enabledPlugins?.[e]!==void 0}function iyt(e,t,n=`user`,r){let i=V2(),a={scope:n,installPath:t.installPath,version:t.version,installedAt:t.installedAt,lastUpdated:t.lastUpdated,gitCommitSha:t.gitCommitSha,...r&&{projectPath:r}},o=i.plugins[e]||[],s=o.findIndex(e=>e.scope===n&&e.projectPath===r),c=s>=0;c?o[s]=a:o.push(a),i.plugins[e]=o,B2(i),U(`${c?`Updated`:`Added`} installed plugin: ${e} (scope: ${n})`)}async function H2(e){return await _ie(e)??void 0}function ayt(e,t){let n=G(),r=Y(e,`.claude-plugin`,`plugin.json`);try{return kn(n.readFileSync(r,{encoding:`utf-8`})).version||`unknown`}catch{return U(`Could not read version from manifest for ${t}`),`unknown`}}async function oyt(){let e=zr().enabledPlugins||{};if(Object.keys(e).length===0)return;let t=L2(),n=t!==null;if(n&&t?.version===2&&t){let n=oi().safeParse(t.data);if(n?.success){let t=n.data.plugins;if(Object.keys(e).filter(e=>e.includes(`@`)).every(e=>{let n=t[e];return n&&n.length>0})){U(`All plugins already exist, skipping migration`);return}}}U(n?`Syncing installed_plugins.json with enabledPlugins from all settings.json files`:`Creating installed_plugins.json from settings.json files`);let r=new Date().toISOString(),i=yn(),a=new Map;for(let e of[`userSettings`,`projectSettings`,`localSettings`]){let t=Ir(e)?.enabledPlugins||{};for(let n of Object.keys(t)){if(!n.includes(`@`))continue;let t=Dye(e);a.set(n,{scope:t,projectPath:t===`user`?void 0:i})}}let o={};n&&(o={...z2().plugins});let s=0,c=0;for(let[e,t]of a){let n=o[e];if(n&&n.length>0){let i=n[0];i&&(i.scope!==t.scope||i.projectPath!==t.projectPath)&&(i.scope=t.scope,t.projectPath?i.projectPath=t.projectPath:delete i.projectPath,i.lastUpdated=r,s++,U(`Updated ${e} scope to ${t.scope} (settings.json is source of truth)`))}else{let{name:n,marketplace:i}=Zg(e);if(!n||!i)continue;try{U(`Looking up plugin ${e} in marketplace ${i}`);let a=await M2(e);if(!a){U(`Plugin ${e} not found in any marketplace, skipping`);continue}let{entry:s,marketplaceInstallLocation:l}=a,u,d=`unknown`,f;if(typeof s.source==`string`)u=Y(l,s.source),d=ayt(u,e),f=await H2(u);else{let t=Y($2(),n.replace(/[^a-zA-Z0-9-_]/g,`-`)),r;try{r=(await G().readdir(t)).map(e=>typeof e==`string`?e:e.name)}catch(t){if(!xn(t))throw t;U(`External plugin ${e} not in cache, skipping`);continue}u=t,r.includes(`.claude-plugin`)&&(d=ayt(t,e)),f=await H2(t)}d===`unknown`&&s.version&&(d=s.version),d===`unknown`&&f&&(d=f.substring(0,12)),o[e]=[{scope:t.scope,installPath:t4(e,d),version:d,installedAt:r,lastUpdated:r,gitCommitSha:f,...t.projectPath&&{projectPath:t.projectPath}}],c++,U(`Added ${e} with scope ${t.scope}`)}catch(t){U(`Failed to add plugin ${e}: ${t}`)}}}(!n||s>0||c>0)&&(B2({version:2,plugins:o}),U(`Sync completed: ${c} added, ${s} updated in installed_plugins.json`))}var U2,W2,G2,K2=n((()=>{W(),On(),Bn(),Qi(),Yn(),I_(),si(),Wt(),vn(),Di(),Vr(),F2(),$g(),d4(),U2=!1,W2=null,G2=null}));function q2(){let e=Ir(`policySettings`)?.enabledPlugins;if(!e)return null;let t=new Set;for(let[n,r]of Object.entries(e)){if(typeof r!=`boolean`||!n.includes(`@`))continue;let e=n.split(`@`)[0];e&&t.add(e)}return t.size>0?t:null}var J2=n((()=>{Vr()}));async function Y2(e,t,n,r,i,a){if(n?.version)return U(`Using manifest version for ${e}: ${n.version}`),n.version;if(i)return U(`Using provided version for ${e}: ${i}`),i;if(a){let n=a.substring(0,12);if(typeof t==`object`&&t.source===`git-subdir`){let r=t.path.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``),i=`${n}-${vl(`sha256`).update(r).digest(`hex`).substring(0,8)}`;return U(`Using git-subdir SHA+path version for ${e}: ${i} (path=${r})`),i}return U(`Using pre-resolved git SHA for ${e}: ${n}`),n}if(r){let t=await syt(r);if(t){let n=t.substring(0,12);return U(`Using git SHA for ${e}: ${n}`),n}}return U(`No version found for ${e}, using 'unknown'`),`unknown`}function syt(e){return _ie(e)}var X2=n((()=>{W(),Di()}));function cyt(){return new Date().toISOString()}function Z2(e,t){let n=el(e,t),r=el(e)+tl;if(!n.startsWith(r)&&n!==el(e))throw Error(`Path traversal detected: "${t}" would escape the base directory`);return n}async function lyt(e,t,n=`user`,r,i){let a=await a4(typeof t.source==`string`&&i?i:t.source,{manifest:t}),o=i||a.path,s=a.gitCommitSha??await H2(o),c=cyt(),l=await Y2(e,t.source,a.manifest,o,t.version,a.gitCommitSha),u=t4(e,l),d=a.path;if(a.path!==u){await G().mkdir(qc(u)),await Ml(u,{recursive:!0,force:!0});let e=a.path.endsWith(tl)?a.path:a.path+tl;if(u.startsWith(e)){let e=Y(qc(a.path),`.claude-plugin-temp-${Date.now()}-${yl(4).toString(`hex`)}`);await jl(a.path,e),await G().mkdir(qc(u)),await jl(e,u)}else await jl(a.path,u);d=u}if(t2()){let t=n4(e,l);await U_t(d,t),d=t}return iyt(e,{version:l,installedAt:c,lastUpdated:c,installPath:d,gitCommitSha:s},n,r),d}function Q2(e){switch(e.reason){case`cycle`:return`Dependency cycle: ${e.chain.join(` → `)}`;case`cross-marketplace`:{let t=Zg(e.dependency).marketplace,n=t?`marketplace "${t}"`:`a different marketplace`,r=t?` Add "${t}" to allowCrossMarketplaceDependenciesOn in the ROOT marketplace's marketplace.json (the marketplace of the plugin you're installing — only its allowlist applies; no transitive trust).`:``;return`Dependency "${e.dependency}" (required by ${e.requiredBy}) is in ${n}, which is not in the allowlist — cross-marketplace dependencies are blocked by default. Install it manually first.${r}`}case`not-found`:{let{marketplace:t}=Zg(e.missing);return t?`Dependency "${e.missing}" (required by ${e.requiredBy}) not found. Is the "${t}" marketplace added?`:`Dependency "${e.missing}" (required by ${e.requiredBy}) not found in any configured marketplace`}}}async function uyt({pluginId:e,entry:t,scope:n,marketplaceInstallLocation:r}){let i=Eye(n);if(QB(e))return{ok:!1,reason:`blocked-by-policy`,pluginName:t.name};let a=new Map;if(ure(t.source)&&!r)return{ok:!1,reason:`local-source-no-location`,pluginName:t.name};r&&a.set(e,{entry:t,marketplaceInstallLocation:r});let o=Zg(e).marketplace,s=new Set((o?(await j2(o))?.allowCrossMarketplaceDependenciesOn:void 0)??[]),c=await Aye(e,async n=>{if(a.has(n))return a.get(n).entry;if(n===e)return t;let r=await M2(n);return r&&a.set(n,r),r?.entry??null},Nye(i),s);if(!c.ok)return{ok:!1,reason:`resolution-failed`,resolution:c};for(let n of c.closure)if(n!==e&&QB(n))return{ok:!1,reason:`dependency-blocked-by-policy`,pluginName:t.name,blockedDependency:n};let l={};for(let e of c.closure)l[e]=!0;let{error:u}=li(i,{enabledPlugins:{...Ir(i)?.enabledPlugins,...l}});if(u)return{ok:!1,reason:`settings-write-failed`,message:u.message};let d=n===`user`?void 0:yn();for(let r of c.closure){let i=a.get(r);if(!i&&r===e){let e=(await M2(r))?.marketplaceInstallLocation;e&&(i={entry:t,marketplaceInstallLocation:e})}if(!i)continue;let o,{source:s}=i.entry;ure(s)&&(o=Z2(i.marketplaceInstallLocation,s)),await lyt(r,i.entry,n,d,o)}q_t();let f=Pye(c.closure.filter(t=>t!==e));return{ok:!0,closure:c.closure,depNote:f}}async function dyt({pluginId:e,entry:t,marketplaceName:n,scope:r=`user`,trigger:i=`user`}){try{let a=(await M2(e))?.marketplaceInstallLocation,o=await uyt({pluginId:e,entry:t,scope:r,marketplaceInstallLocation:a});if(!o.ok){let e=o;switch(e.reason){case`local-source-no-location`:return{success:!1,error:`Cannot install local plugin "${e.pluginName}" without marketplace install location`};case`settings-write-failed`:return{success:!1,error:`Failed to update settings: ${e.message}`};case`resolution-failed`:return{success:!1,error:Q2(e.resolution)};case`blocked-by-policy`:return{success:!1,error:`Plugin "${e.pluginName}" is blocked by your organization's policy and cannot be installed`};case`dependency-blocked-by-policy`:return{success:!1,error:`Cannot install "${e.pluginName}": dependency "${e.blockedDependency}" is blocked by your organization's policy`}}}return J(`tengu_plugin_installed`,{_PROTO_plugin_name:t.name,_PROTO_marketplace_name:n,plugin_id:Qg(n)?e:`third-party`,trigger:i,install_source:i===`hint`?`ui-suggestion`:`ui-discover`,...pJ(t.name,n,q2()),...t.version&&{version:t.version}}),{success:!0,message:`✓ Installed ${t.name}${o.depNote}. Run /reload-plugins to activate.`}}catch(e){let t=e instanceof Error?e.message:String(e);return q(jn(e)),{success:!1,error:`Failed to install: ${t}`}}}var fyt=n((()=>{Da(),vn(),On(),Bn(),Qi(),Vr(),hJ(),l2(),t_(),K2(),J2(),F2(),$g(),d4(),$B(),X2(),si(),a2()}));function $2(){return Y(M_(),`cache`)}function e4(e,t,n){let{name:r,marketplace:i}=Zg(t);return Y(e,`cache`,(i||`unknown`).replace(/[^a-zA-Z0-9\-_]/g,`-`),(r||t).replace(/[^a-zA-Z0-9\-_]/g,`-`),n.replace(/[^a-zA-Z0-9\-_.]/g,`-`))}function t4(e,t){return e4(M_(),e,t)}function n4(e,t){return`${t4(e,t)}.zip`}async function pyt(e,t){for(let n of N_()){let r=e4(n,e,t);try{if((await kl(r)).length>0)return r}catch{}}return null}async function myt(e){for(let t of N_()){let n=qc(e4(t,e,`_`));try{let e=await kl(n);if(e.length!==1)continue;let t=Y(n,e[0]);if((await kl(t)).length>0)return t}catch{}}return null}async function r4(e,t){await G().mkdir(t);let n=await kl(e,{withFileTypes:!0});for(let r of n){let n=Y(e,r.name),i=Y(t,r.name);if(r.isDirectory())await r4(n,i);else if(r.isFile())await wl(n,i);else if(r.isSymbolicLink()){let r=await due(n),a;try{a=await Al(n)}catch{await Pl(r,i);continue}let o;try{o=await Al(e)}catch{o=e}let s=o.endsWith(tl)?o:o+tl;if(a.startsWith(s)||a===o){let e=Y(t,$c(o,a));await Pl($c(qc(i),e),i)}else await Pl(a,i)}}}async function i4(e,t,n,r,i){let a=t2(),o=t4(t,n),s=n4(t,n);if(a){if(await Gr(s))return U(`Plugin ${t} version ${n} already cached at ${s}`),s}else if(await Gr(o)){if((await kl(o)).length>0)return U(`Plugin ${t} version ${n} already cached at ${o}`),o;U(`Removing empty cache directory for ${t} at ${o}`),await fue(o)}let c=await pyt(t,n);if(c)return U(`Using seed cache for ${t}@${n} at ${c}`),c;if(await G().mkdir(qc(o)),r&&typeof r.source==`string`&&i){let e=Z2(i,r.source);U(`Copying source directory ${r.source} for plugin ${t}`);try{await r4(e,o)}catch(t){throw xn(t)&&xne(t)===e?Error(`Plugin source directory not found: ${e} (from entry.source: ${r.source})`):t}}else U(`Copying plugin ${t} to versioned cache (fallback to full copy)`),await r4(e,o);if(await Ml(Y(o,`.git`),{recursive:!0,force:!0}),(await kl(o)).length===0)throw Error(`Failed to copy plugin ${t} to versioned cache: destination is empty after copy`);return a?(await U_t(o,s),U(`Successfully cached plugin ${t} as ZIP at ${s}`),s):(U(`Successfully cached plugin ${t} at ${o}`),o)}function hyt(e){try{let t=new URL(e);if(![`https:`,`http:`,`file:`].includes(t.protocol)&&!/^git@[a-zA-Z0-9.-]+:/.test(e))throw Error(`Invalid git URL protocol: ${t.protocol}. Only HTTPS, HTTP, file:// and SSH (git@) URLs are supported.`);return e}catch{if(/^git@[a-zA-Z0-9.-]+:/.test(e))return e;throw Error(`Invalid git URL: ${e}`)}}async function gyt(e,t,n={}){let r=Y(M_(),`npm-cache`);await G().mkdir(r);let i=n.version?`${e}@${n.version}`:e,a=Y(r,`node_modules`,e);if(!await Gr(a)){U(`Installing npm package ${i} to cache`);let e=[`install`,i,`--prefix`,r];n.registry&&e.push(`--registry`,n.registry);let t=await Bi(`npm`,e,{useCwd:!1});if(t.code!==0)throw Error(`Failed to install npm package: ${t.stderr}`)}await r4(a,t),U(`Copied npm package ${e} from cache to ${t}`)}async function _yt(e,t,n,r){let i=[`clone`,`--depth`,`1`,`--recurse-submodules`,`--shallow-submodules`];n&&i.push(`--branch`,n),r&&i.push(`--no-checkout`),i.push(e,t);let a=performance.now(),o=await Bi(Pi(),i);if(o.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(o.stderr)),Error(`Failed to clone repository: ${o.stderr}`);if(r){if((await Li(Pi(),[`fetch`,`--depth`,`1`,`origin`,r],{cwd:t})).code!==0){U(`Shallow fetch of SHA ${r} failed, falling back to unshallow fetch`);let n=await Li(Pi(),[`fetch`,`--unshallow`],{cwd:t});if(n.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(n.stderr)),Error(`Failed to fetch commit ${r}: ${n.stderr}`)}let n=await Li(Pi(),[`checkout`,r],{cwd:t});if(n.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(n.stderr)),Error(`Failed to checkout commit ${r}: ${n.stderr}`)}a_(`plugin_clone`,e,`success`,performance.now()-a)}async function vyt(e,t,n,r){let i=hyt(e);await _yt(i,t,n,r),U(`Cloned repository from ${i}${n?` (ref: ${n})`:``} to ${t}`)}async function yyt(e,t,n,r){if(!/^[a-zA-Z0-9-_.]+\/[a-zA-Z0-9-_.]+$/.test(e))throw Error(`Invalid GitHub repository format: ${e}. Expected format: owner/repo`);return vyt(m(process.env.CLAUDE_CODE_REMOTE)?`https://github.com/${e}.git`:`git@github.com:${e}.git`,t,n,r)}function byt(e){return/^[a-zA-Z0-9-_.]+\/[a-zA-Z0-9-_.]+$/.test(e)?m(process.env.CLAUDE_CODE_REMOTE)?`https://github.com/${e}.git`:`git@github.com:${e}.git`:hyt(e)}async function xyt(e,t,n,r,i){if(!await c_())throw Error(`git-subdir plugin source requires git to be installed and on PATH. Install git (version 2.25 or later for sparse-checkout cone mode) and try again.`);let a=byt(e),o=`${t}.clone`,s=[`clone`,`--depth`,`1`,`--filter=tree:0`,`--no-checkout`];r&&s.push(`--branch`,r),s.push(a,o);let c=await Bi(Pi(),s);if(c.code!==0)throw Error(`Failed to clone repository for git-subdir source: ${c.stderr}`);try{let e=await Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,n],{cwd:o});if(e.code!==0)throw Error(`git sparse-checkout set failed (git >= 2.25 required for cone mode): ${e.stderr}`);let s;if(i){if((await Li(Pi(),[`fetch`,`--depth`,`1`,`origin`,i],{cwd:o})).code!==0){U(`Shallow fetch of SHA ${i} failed for git-subdir, falling back to unshallow fetch`);let e=await Li(Pi(),[`fetch`,`--unshallow`],{cwd:o});if(e.code!==0)throw Error(`Failed to fetch commit ${i}: ${e.stderr}`)}let e=await Li(Pi(),[`checkout`,i],{cwd:o});if(e.code!==0)throw Error(`Failed to checkout commit ${i}: ${e.stderr}`);s=i}else{let[e,t]=await Promise.all([Li(Pi(),[`checkout`,`HEAD`],{cwd:o}),Li(Pi(),[`rev-parse`,`HEAD`],{cwd:o})]);if(e.code!==0)throw Error(`git checkout after sparse-checkout failed: ${e.stderr}`);t.code===0&&(s=t.stdout.trim())}let c=Z2(o,n);try{await jl(c,t)}catch(e){throw xn(e)?Error(`Subdirectory '${n}' not found in repository ${a}${r?` (ref: ${r})`:``}. Check that the path is correct and exists at the specified ref/sha.`):e}return U(`Extracted subdir ${n} from ${a}${r?` ref=${r}`:``}${s?` sha=${s}`:``} to ${t}`),s}finally{await Ml(o,{recursive:!0,force:!0})}}async function Syt(e,t){if(!await Gr(e))throw Error(`Source path does not exist: ${e}`);await r4(e,t),await Ml(Y(t,`.git`),{recursive:!0,force:!0})}function Cyt(e){let t=Date.now(),n=Math.random().toString(36).substring(2,8),r;if(typeof e==`string`)r=`local`;else switch(e.source){case`npm`:r=`npm`;break;case`pip`:r=`pip`;break;case`github`:r=`github`;break;case`url`:r=`git`;break;case`git-subdir`:r=`subdir`;break;default:r=`unknown`}return`temp_${r}_${t}_${n}`}async function a4(e,t){let n=$2();await G().mkdir(n);let r=Cyt(e),i=Y(n,r),a=!1,o;try{if(U(`Caching plugin from source: ${V(e)} to temporary path ${i}`),a=!0,typeof e==`string`)await Syt(e,i);else switch(e.source){case`npm`:await gyt(e.package,i,{registry:e.registry,version:e.version});break;case`github`:await yyt(e.repo,i,e.ref,e.sha);break;case`url`:await vyt(e.url,i,e.ref,e.sha);break;case`git-subdir`:o=await xyt(e.url,i,e.path,e.ref,e.sha);break;case`pip`:throw Error(`Python package plugins are not yet supported`);default:throw Error(`Unsupported plugin source type`)}}catch(e){if(a&&await Gr(i)){U(`Cleaning up failed installation at ${i}`);try{await Ml(i,{recursive:!0,force:!0})}catch(e){U(`Failed to clean up installation: ${e}`,{level:`error`})}}throw e}let s=Y(i,`.claude-plugin`,`plugin.json`),c=Y(i,`plugin.json`),l;if(await Gr(s))try{let e=kn(await Ol(s,{encoding:`utf-8`})),t=Hr().safeParse(e);if(t.success)l=t.data;else{let e=t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw U(`Invalid manifest at ${s}: ${e}`,{level:`error`}),Error(`Plugin has an invalid manifest file at ${s}. Validation errors: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(`invalid manifest file`))throw e;let t=H(e);throw U(`Failed to parse manifest at ${s}: ${t}`,{level:`error`}),Error(`Plugin has a corrupt manifest file at ${s}. JSON parse error: ${t}`)}else if(await Gr(c))try{let e=kn(await Ol(c,{encoding:`utf-8`})),t=Hr().safeParse(e);if(t.success)l=t.data;else{let e=t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw U(`Invalid legacy manifest at ${c}: ${e}`,{level:`error`}),Error(`Plugin has an invalid manifest file at ${c}. Validation errors: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(`invalid manifest file`))throw e;let t=H(e);throw U(`Failed to parse legacy manifest at ${c}: ${t}`,{level:`error`}),Error(`Plugin has a corrupt manifest file at ${c}. JSON parse error: ${t}`)}else l=t?.manifest||{name:r,description:`Plugin cached from ${typeof e==`string`?e:e.source}`};let u=Y(n,l.name.replace(/[^a-zA-Z0-9-_]/g,`-`));return await Gr(u)&&(U(`Removing old cached version at ${u}`),await Ml(u,{recursive:!0,force:!0})),await jl(i,u),U(`Successfully cached plugin ${l.name} to ${u}`),{path:u,manifest:l,...o&&{gitCommitSha:o}}}async function o4(e,t,n){if(!await Gr(e))return{name:t,description:`Plugin from ${n}`};try{let n=kn(await Ol(e,{encoding:`utf-8`})),r=Hr().safeParse(n);if(r.success)return r.data;let i=r.error.issues.map(e=>e.path.length>0?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `);throw U(`Plugin ${t} has an invalid manifest file at ${e}. Validation errors: ${i}`,{level:`error`}),Error(`Plugin ${t} has an invalid manifest file at ${e}.\n\nValidation errors: ${i}`)}catch(n){if(n instanceof Error&&n.message.includes(`invalid manifest file`))throw n;let r=H(n);throw U(`Plugin ${t} has a corrupt manifest file at ${e}. Parse error: ${r}`,{level:`error`}),Error(`Plugin ${t} has a corrupt manifest file at ${e}.\n\nJSON parse error: ${r}`)}}async function wyt(e,t){if(!await Gr(e))throw Error(`Hooks file not found at ${e} for plugin ${t}. If the manifest declares hooks, the file must exist.`);let n=kn(await Ol(e,{encoding:`utf-8`}));return Lre().parse(n).hooks}async function s4(e,t,n,r,i,a,o,s){let c=await Promise.all(e.map(async e=>{let n=Y(t,e);return{relPath:e,fullPath:n,exists:await Gr(n)}})),l=[];for(let{relPath:e,fullPath:t,exists:u}of c)u?l.push(t):(U(`${a} path ${e} ${o} not found at ${t} for ${n}`,{level:`warn`}),q(Error(`Plugin component file not found: ${t} for ${n}`)),s.push({type:`path-not-found`,source:r,plugin:n,path:t,component:i}));return l}async function Tyt(e,t,n,r,i=!0){let a=[],o=await o4(Y(e,`.claude-plugin`,`plugin.json`),r,t),s={name:o.name,manifest:o,path:e,source:t,repository:t,enabled:n},[c,l,u,d]=await Promise.all([!o.commands&&Gr(Y(e,`commands`)),!o.agents&&Gr(Y(e,`agents`)),!o.skills&&Gr(Y(e,`skills`)),!o.outputStyles&&Gr(Y(e,`output-styles`))]),f=Y(e,`commands`);if(c&&(s.commandsPath=f),o.commands){let n=Object.values(o.commands)[0];if(typeof o.commands==`object`&&!Array.isArray(o.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={},r=[],i=Object.entries(o.commands),c=await Promise.all(i.map(async([t,n])=>{if(!n||typeof n!=`object`)return{commandName:t,metadata:n,kind:`skip`};if(n.source){let r=Y(e,n.source);return{commandName:t,metadata:n,kind:`source`,fullPath:r,exists:await Gr(r)}}return n.content?{commandName:t,metadata:n,kind:`content`}:{commandName:t,metadata:n,kind:`skip`}}));for(let e of c)if(e.kind!==`skip`){if(e.kind===`content`){n[e.commandName]=e.metadata;continue}e.exists?(r.push(e.fullPath),n[e.commandName]=e.metadata):(U(`Command ${e.commandName} path ${e.metadata.source} specified in manifest but not found at ${e.fullPath} for ${o.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${e.fullPath} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:e.fullPath,component:`commands`}))}r.length>0&&(s.commandsPaths=r),Object.keys(n).length>0&&(s.commandsMetadata=n)}else{let n=Array.isArray(o.commands)?o.commands:[o.commands],r=await Promise.all(n.map(async t=>{if(typeof t!=`string`)return{cmdPath:t,kind:`invalid`};let n=Y(e,t);return{cmdPath:t,kind:`path`,fullPath:n,exists:await Gr(n)}})),i=[];for(let e of r){if(e.kind===`invalid`){U(`Unexpected command format in manifest for ${o.name}`,{level:`error`});continue}e.exists?i.push(e.fullPath):(U(`Command path ${e.cmdPath} specified in manifest but not found at ${e.fullPath} for ${o.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${e.fullPath} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:e.fullPath,component:`commands`}))}i.length>0&&(s.commandsPaths=i)}}let p=Y(e,`agents`);if(l&&(s.agentsPath=p),o.agents){let n=await s4(Array.isArray(o.agents)?o.agents:[o.agents],e,o.name,t,`agents`,`Agent`,`specified in manifest but`,a);n.length>0&&(s.agentsPaths=n)}let m=Y(e,`skills`);if(u&&(s.skillsPath=m),o.skills){let n=await s4(Array.isArray(o.skills)?o.skills:[o.skills],e,o.name,t,`skills`,`Skill`,`specified in manifest but`,a);n.length>0&&(s.skillsPaths=n)}let h=Y(e,`output-styles`);if(d&&(s.outputStylesPath=h),o.outputStyles){let n=await s4(Array.isArray(o.outputStyles)?o.outputStyles:[o.outputStyles],e,o.name,t,`output-styles`,`Output style`,`specified in manifest but`,a);n.length>0&&(s.outputStylesPaths=n)}let g,_=new Set,v=Y(e,`hooks`,`hooks.json`);if(await Gr(v))try{g=await wyt(v,o.name);try{_.add(await Al(v))}catch{_.add(v)}U(`Loaded hooks from standard location for plugin ${o.name}: ${v}`)}catch(e){let n=H(e);U(`Failed to load hooks for ${o.name}: ${n}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:v,reason:n})}if(o.hooks){let n=Array.isArray(o.hooks)?o.hooks:[o.hooks];for(let r of n)if(typeof r==`string`){let n=Y(e,r);if(!await Gr(n)){U(`Hooks file ${r} specified in manifest but not found at ${n} for ${o.name}`,{level:`error`}),q(Error(`Plugin component file not found: ${n} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:n,component:`hooks`});continue}let s;try{s=await Al(n)}catch{s=n}if(_.has(s)){if(U(`Skipping duplicate hooks file for plugin ${o.name}: ${r} (resolves to already-loaded file: ${s})`),i){let e=`Duplicate hooks file detected: ${r} resolves to already-loaded file ${s}. The standard hooks/hooks.json is loaded automatically, so manifest.hooks should only reference additional hook files.`;q(Error(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:e})}continue}try{let e=await wyt(n,o.name);try{g=Oyt(g,e),_.add(s),U(`Loaded and merged hooks from manifest for plugin ${o.name}: ${r}`)}catch(e){let i=H(e);U(`Failed to merge hooks from ${r} for ${o.name}: ${i}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:`Failed to merge: ${i}`})}}catch(e){let i=H(e);U(`Failed to load hooks from ${r} for ${o.name}: ${i}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:i})}}else typeof r==`object`&&(g=Oyt(g,r))}g&&(s.hooksConfig=g);let y=await Dyt(e,o);return y&&(s.settings=y),{plugin:s,errors:a}}function Eyt(e){let t=zyt().safeParse(e);if(!t.success)return;let n=t.data;if(Object.keys(n).length!==0)return n}async function Dyt(e,t){let n=Y(e,`settings.json`);try{let e=kn(await Ol(n,{encoding:`utf-8`}));if(Ryt(e)){let n=Eyt(e);if(n)return U(`Loaded settings from settings.json for plugin ${t.name}`),n}}catch(e){Mn(e)||U(`Failed to parse settings.json for plugin ${t.name}: ${e}`,{level:`warn`})}if(t.settings){let e=Eyt(t.settings);if(e)return U(`Loaded settings from manifest for plugin ${t.name}`),e}}function Oyt(e,t){if(!e)return t;let n={...e};for(let[e,r]of Object.entries(t))n[e]?n[e]=[...n[e]??[],...r]:n[e]=r;return n}async function kyt({cacheOnly:e}){let t=zr(),n={...Jg(),...t.enabledPlugins||{}},r=[],i=[],a=Object.entries(n).filter(([e,t])=>{if(!kre().safeParse(e).success||t===void 0)return!1;let{marketplace:n}=Zg(e);return n!==Kg}),o=await Evt(),s=u2(),c=cvt(),l=s!==null||c!==null&&c.length>0,u=new Set(a.map(([e])=>Zg(e).marketplace).filter(e=>!!e)),d=new Map;await Promise.all([...u].map(async e=>{d.set(e,await j2(e))}));let f=Zvt(),p=await Promise.allSettled(a.map(async([t,n])=>{let{name:r,marketplace:a}=Zg(t),c=o[a];if(!c&&l)return i.push({type:`marketplace-blocked-by-policy`,source:t,plugin:r,marketplace:a,blockedByBlocklist:s===null,allowedSources:(s??[]).map(e=>m2(e))}),null;if(c&&!p2(c.source)){let e=f2(c.source),n=u2()||[];return i.push({type:`marketplace-blocked-by-policy`,source:t,plugin:r,marketplace:a,blockedByBlocklist:e,allowedSources:e?[]:n.map(e=>m2(e))}),null}let u=null,p=d.get(a);if(p&&c){let e=p.plugins.find(e=>e.name===r);e&&(u={entry:e,marketplaceInstallLocation:c.installLocation})}else u=await Hvt(t);if(!u)return i.push({type:`plugin-not-found`,source:t,pluginId:r,marketplace:a}),null;let m=f.plugins[t]?.[0];return e?Ayt(u.entry,u.marketplaceInstallLocation,t,n===!0,i,m?.installPath):jyt(u.entry,u.marketplaceInstallLocation,t,n===!0,i,m?.version)}));for(let[e,t]of p.entries())if(t.status===`fulfilled`&&t.value)r.push(t.value);else if(t.status===`rejected`){let n=jn(t.reason);q(n);let r=a[e][0];i.push({type:`generic-error`,source:r,plugin:r.split(`@`)[0],error:n.message})}return{plugins:r,errors:i}}async function Ayt(e,t,n,r,i,a){let o;if(typeof e.source==`string`){let r;try{r=(await Nl(t)).isDirectory()?t:Y(t,`..`)}catch{return i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:t}),null}o=Y(r,e.source)}else{if(!a||!await Gr(a))return i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:a??`(not recorded)`}),null;o=a}if(t2()&&o.endsWith(`.zip`)){let t=Y(await L_t(),n.replace(/[^a-zA-Z0-9@\-_]/g,`-`));try{await H_t(o,t),o=t}catch(t){return U(`Failed to extract plugin ZIP ${o}: ${t}`,{level:`error`}),i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:o}),null}}return Myt(e,n,r,i,o)}async function jyt(e,t,n,r,i,a){U(`Loading plugin ${e.name} from source: ${V(e.source)}`);let o;if(typeof e.source==`string`){let r=(await Nl(t)).isDirectory()?t:Y(t,`..`),a=Y(r,e.source);if(!await Gr(a)){let e=Error(`Plugin path not found: ${a}`);return U(`Plugin path not found: ${a}`,{level:`error`}),q(e),i.push({type:`generic-error`,source:n,error:`Plugin directory not found at path: ${a}. Check that the marketplace entry has the correct path.`}),null}try{let t=Y(a,`.claude-plugin`,`plugin.json`),i;try{i=await o4(t,e.name,e.source)}catch{}o=await i4(a,n,await Y2(n,e.source,i,r,e.version),e,r),U(`Resolved local plugin ${e.name} to versioned cache: ${o}`)}catch(t){let n=H(t);U(`Failed to copy plugin ${e.name} to versioned cache: ${n}. Using marketplace path.`,{level:`warn`}),o=a}}else try{let t=await Y2(n,e.source,void 0,void 0,a??e.version,`sha`in e.source?e.source.sha:void 0),r=t4(n,t),i=n4(n,t);if(t2()&&await Gr(i))U(`Using versioned cached plugin ZIP ${e.name} from ${i}`),o=i;else if(await Gr(r))U(`Using versioned cached plugin ${e.name} from ${r}`),o=r;else{let r=await pyt(n,t)??(t===`unknown`?await myt(n):null);if(r)o=r,U(`Using seed cache for external plugin ${e.name} at ${r}`);else{let r=await a4(e.source,{manifest:{name:e.name}}),i=t===`unknown`?await Y2(n,e.source,r.manifest,r.path,a??e.version,r.gitCommitSha):t;o=await i4(r.path,n,i,e,void 0),r.path!==o&&await Ml(r.path,{recursive:!0,force:!0})}}}catch(t){let r=H(t);return U(`Failed to cache plugin ${e.name}: ${r}`,{level:`error`}),q(jn(t)),i.push({type:`generic-error`,source:n,error:`Failed to download/cache plugin ${e.name}: ${r}`}),null}if(t2()&&o.endsWith(`.zip`)){let e=Y(await L_t(),n.replace(/[^a-zA-Z0-9@\-_]/g,`-`));try{await H_t(o,e),U(`Extracted plugin ZIP to session dir: ${e}`),o=e}catch(e){throw U(`Failed to extract plugin ZIP ${o}, deleting corrupt file: ${e}`),await Ml(o,{force:!0}).catch(()=>{}),e}}return Myt(e,n,r,i,o)}async function Myt(e,t,n,r,i){let a=[],o=await Gr(Y(i,`.claude-plugin`,`plugin.json`)),{plugin:s,errors:c}=await Tyt(i,t,n,e.name,e.strict??!0);if(a.push(...c),typeof e.source==`object`&&`sha`in e.source&&e.source.sha&&(s.sha=e.source.sha),!o){if(s.manifest={...e,id:void 0,source:void 0,strict:void 0},s.name=s.manifest.name,e.commands){let n=Object.values(e.commands)[0];if(typeof e.commands==`object`&&!Array.isArray(e.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={},r=[],o=Object.entries(e.commands),c=await Promise.all(o.map(async([e,t])=>{if(!t||typeof t!=`object`||!t.source)return{commandName:e,metadata:t,skip:!0};let n=Y(i,t.source);return{commandName:e,metadata:t,skip:!1,fullPath:n,exists:await Gr(n)}}));for(let i of c)i.skip||(i.exists?(r.push(i.fullPath),n[i.commandName]=i.metadata):(U(`Command ${i.commandName} path ${i.metadata.source} from marketplace entry not found at ${i.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i.fullPath,component:`commands`})));r.length>0&&(s.commandsPaths=r,s.commandsMetadata=n)}else{let n=Array.isArray(e.commands)?e.commands:[e.commands],r=await Promise.all(n.map(async e=>{if(typeof e!=`string`)return{cmdPath:e,kind:`invalid`};let t=Y(i,e);return{cmdPath:e,kind:`path`,fullPath:t,exists:await Gr(t)}})),o=[];for(let n of r){if(n.kind===`invalid`){U(`Unexpected command format in marketplace entry for ${e.name}`,{level:`error`});continue}n.exists?o.push(n.fullPath):(U(`Command path ${n.cmdPath} from marketplace entry not found at ${n.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${n.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:n.fullPath,component:`commands`}))}o.length>0&&(s.commandsPaths=o)}}if(e.agents){let n=await s4(Array.isArray(e.agents)?e.agents:[e.agents],i,e.name,t,`agents`,`Agent`,`from marketplace entry`,a);n.length>0&&(s.agentsPaths=n)}if(e.skills){U(`Processing ${Array.isArray(e.skills)?e.skills.length:1} skill paths for plugin ${e.name}`);let n=Array.isArray(e.skills)?e.skills:[e.skills],r=await Promise.all(n.map(async e=>{let t=Y(i,e);return{skillPath:e,fullPath:t,exists:await Gr(t)}})),o=[];for(let{skillPath:n,fullPath:i,exists:s}of r)U(`Checking skill path: ${n} -> ${i} (exists: ${s})`),s?o.push(i):(U(`Skill path ${n} from marketplace entry not found at ${i} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i,component:`skills`}));U(`Found ${o.length} valid skill paths for plugin ${e.name}, setting skillsPaths`),o.length>0&&(s.skillsPaths=o)}else U(`Plugin ${e.name} has no entry.skills defined`);if(e.outputStyles){let n=await s4(Array.isArray(e.outputStyles)?e.outputStyles:[e.outputStyles],i,e.name,t,`output-styles`,`Output style`,`from marketplace entry`,a);n.length>0&&(s.outputStylesPaths=n)}e.hooks&&(s.hooksConfig=e.hooks)}else if(!e.strict&&o&&(e.commands||e.agents||e.skills||e.hooks||e.outputStyles)){let n=Error(`Plugin ${e.name} has both plugin.json and marketplace manifest entries for commands/agents/skills/hooks/outputStyles. This is a conflict.`);return U(`Plugin ${e.name} has both plugin.json and marketplace manifest entries for commands/agents/skills/hooks/outputStyles. This is a conflict.`,{level:`error`}),q(n),r.push({type:`generic-error`,source:t,error:`Plugin ${e.name} has conflicting manifests: both plugin.json and marketplace entry specify components. Set strict: true in marketplace entry or remove component specs from one location.`}),null}else if(o){if(e.commands){let n=Object.values(e.commands)[0];if(typeof e.commands==`object`&&!Array.isArray(e.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={...s.commandsMetadata||{}},r=[],o=Object.entries(e.commands),c=await Promise.all(o.map(async([e,t])=>{if(!t||typeof t!=`object`||!t.source)return{commandName:e,metadata:t,skip:!0};let n=Y(i,t.source);return{commandName:e,metadata:t,skip:!1,fullPath:n,exists:await Gr(n)}}));for(let i of c)i.skip||(i.exists?(r.push(i.fullPath),n[i.commandName]=i.metadata):(U(`Command ${i.commandName} path ${i.metadata.source} from marketplace entry not found at ${i.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i.fullPath,component:`commands`})));r.length>0&&(s.commandsPaths=[...s.commandsPaths||[],...r],s.commandsMetadata=n)}else{let n=Array.isArray(e.commands)?e.commands:[e.commands],r=await Promise.all(n.map(async e=>{if(typeof e!=`string`)return{cmdPath:e,kind:`invalid`};let t=Y(i,e);return{cmdPath:e,kind:`path`,fullPath:t,exists:await Gr(t)}})),o=[];for(let n of r){if(n.kind===`invalid`){U(`Unexpected command format in marketplace entry for ${e.name}`,{level:`error`});continue}n.exists?o.push(n.fullPath):(U(`Command path ${n.cmdPath} from marketplace entry not found at ${n.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${n.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:n.fullPath,component:`commands`}))}o.length>0&&(s.commandsPaths=[...s.commandsPaths||[],...o])}}if(e.agents){let n=await s4(Array.isArray(e.agents)?e.agents:[e.agents],i,e.name,t,`agents`,`Agent`,`from marketplace entry`,a);n.length>0&&(s.agentsPaths=[...s.agentsPaths||[],...n])}if(e.skills){let n=await s4(Array.isArray(e.skills)?e.skills:[e.skills],i,e.name,t,`skills`,`Skill`,`from marketplace entry`,a);n.length>0&&(s.skillsPaths=[...s.skillsPaths||[],...n])}if(e.outputStyles){let n=await s4(Array.isArray(e.outputStyles)?e.outputStyles:[e.outputStyles],i,e.name,t,`output-styles`,`Output style`,`from marketplace entry`,a);n.length>0&&(s.outputStylesPaths=[...s.outputStylesPaths||[],...n])}e.hooks&&(s.hooksConfig={...s.hooksConfig||{},...e.hooks})}return r.push(...a),s}async function Nyt(e){if(e.length===0)return{plugins:[],errors:[]};let t=[],n=[];for(let[r,i]of e.entries())try{let e=el(i);if(!await Gr(e)){U(`Plugin path does not exist: ${e}, skipping`,{level:`warn`}),n.push({type:`path-not-found`,source:`inline[${r}]`,path:e,component:`commands`});continue}let a=Kc(e),{plugin:o,errors:s}=await Tyt(e,`${a}@inline`,!0,a);o.source=`${o.name}@inline`,o.repository=`${o.name}@inline`,t.push(o),n.push(...s),U(`Loaded inline plugin from path: ${o.name}`)}catch(e){let t=H(e);U(`Failed to load session plugin from ${i}: ${t}`,{level:`warn`}),n.push({type:`generic-error`,source:`inline[${r}]`,error:`Failed to load plugin: ${t}`})}return t.length>0&&U(`Loaded ${t.length} session-only plugins from --plugin-dir`),{plugins:t,errors:n}}function Pyt(e){let t=[],n=e.managedNames,r=e.session.filter(e=>n?.has(e.name)?(U(`Plugin "${e.name}" from --plugin-dir is blocked by managed settings`,{level:`warn`}),t.push({type:`generic-error`,source:e.source,plugin:e.name,error:`--plugin-dir copy of "${e.name}" ignored: plugin is locked by managed settings`}),!1):!0),i=new Set(r.map(e=>e.name)),a=e.marketplace.filter(e=>i.has(e.name)?(U(`Plugin "${e.name}" from --plugin-dir overrides installed version`),!1):!0);return{plugins:[...r,...a,...e.builtin],errors:t}}async function Fyt(e){let t=kt(),[n,r]=await Promise.all([e(),t.length>0?Nyt(t):Promise.resolve({plugins:[],errors:[]})]),i=Sye(),{plugins:a,errors:o}=Pyt({session:r.plugins,marketplace:n.plugins,builtin:[...i.enabled,...i.disabled],managedNames:q2()}),s=[...n.errors,...r.errors,...o],{demoted:c,errors:l}=jye(a);for(let e of a)c.has(e.source)&&(e.enabled=!1);s.push(...l);let u=a.filter(e=>e.enabled);return U(`Found ${a.length} plugins (${u.length} enabled, ${a.length-u.length} disabled)`),Lyt(u),{enabled:u,disabled:a.filter(e=>!e.enabled),errors:s}}function c4(e){e&&U(`clearPluginCache: invalidating loadAllPlugins cache (${e})`),l4.cache?.clear?.(),u4.cache?.clear?.(),Yte()!==void 0&&Kt(),Fte()}function Iyt(e){let t;for(let n of e)if(n.settings){t||(t={});for(let[e,r]of Object.entries(n.settings))e in t&&U(`Plugin "${n.name}" overrides setting "${e}" (previously set by another plugin)`),t[e]=r}return t}function Lyt(e){let t=Iyt(e);Ete(t),t&&Object.keys(t).length>0&&(Kt(),U(`Cached plugin settings with keys: ${Object.keys(t).join(`, `)}`))}function Ryt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var zyt,l4,u4,d4=n((()=>{d(),Wt(),qg(),W(),h(),On(),zi(),ci(),Bn(),Mi(),_t(),Qi(),Vr(),Zt(),yr(),Yn(),Xg(),t_(),s_(),l_(),K2(),J2(),h2(),F2(),I_(),$g(),fyt(),X2(),si(),a2(),zyt=ht(()=>Kne().pick({agent:!0}).strip()),l4=u(async()=>{let e=await Fyt(()=>kyt({cacheOnly:!1}));return u4.cache?.set(void 0,Promise.resolve(e)),e}),u4=u(async()=>m(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?l4():Fyt(()=>kyt({cacheOnly:!0})))}));async function Byt(e,t,n){let r=[];return await U0(e,async e=>{let i=await Vyt(e,t,n);i&&r.push(i)},{logLabel:`output-styles`}),r}async function Vyt(e,t,n){let r=G();if(Kn(r,e,n))return null;try{let{frontmatter:n,content:i}=od(await r.readFile(e,{encoding:`utf-8`}),e),a=Kc(e,`.md`),o=`${t}:${n.name||a}`,s=ud(n.description,o)??B9(i,`Output style from ${t} plugin`),c=n[`force-for-plugin`],l=c===!0||c===`true`?!0:c===!1||c===`false`?!1:void 0;return{name:o,description:s,prompt:i.trim(),source:`plugin`,forceForPlugin:l}}catch(t){return U(`Failed to load output style from ${e}: ${t}`,{level:`error`}),null}}function Hyt(){f4.cache?.clear?.()}var f4,p4=n((()=>{d(),Wg(),W(),gd(),Bn(),K9(),d4(),W0(),f4=u(async()=>{let{enabled:e,errors:t}=await u4(),n=[];t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`);for(let t of e){let e=new Set;if(t.outputStylesPath)try{let r=await Byt(t.outputStylesPath,t.name,e);n.push(...r),r.length>0&&U(`Loaded ${r.length} output styles from plugin ${t.name} default directory`)}catch(e){U(`Failed to load output styles from plugin ${t.name} default directory: ${e}`,{level:`error`})}if(t.outputStylesPaths)for(let r of t.outputStylesPaths)try{let i=await G().stat(r);if(i.isDirectory()){let i=await Byt(r,t.name,e);n.push(...i),i.length>0&&U(`Loaded ${i.length} output styles from plugin ${t.name} custom path: ${r}`)}else if(i.isFile()&&r.endsWith(`.md`)){let i=await Vyt(r,t.name,e);i&&(n.push(i),U(`Loaded output style from plugin ${t.name} custom file: ${r}`))}}catch(e){U(`Failed to load output styles from plugin ${t.name} custom path ${r}: ${e}`,{level:`error`})}}return U(`Total plugin output styles loaded: ${n.length}`),n})})),Uyt,Wyt=n((()=>{d(),W(),gd(),Qi(),K9(),p4(),Uyt=u(async e=>{try{return(await G9(`output-styles`,e)).map(({filePath:e,frontmatter:t,content:n,source:r})=>{try{let i=Kc(e).replace(/\.md$/,``),a=t.name||i,o=ud(t.description,i)??B9(n,`Custom ${i} output style`),s=t[`keep-coding-instructions`],c=s===!0||s===`true`?!0:s===!1||s===`false`?!1:void 0;return t[`force-for-plugin`]!==void 0&&U(`Output style "${a}" has force-for-plugin set, but this option only applies to plugin output styles. Ignoring.`,{level:`warn`}),{name:a,description:o,prompt:n.trim(),source:r,keepCodingInstructions:c}}catch(e){return q(e),null}}).filter(e=>e!==null)}catch(e){return q(e),[]}})}));function Gyt(){_4.cache?.clear?.()}async function Kyt(){let e=await _4(yn()),t=Object.values(e).filter(e=>e!==null&&e.source===`plugin`&&e.forceForPlugin===!0),n=t[0];return n?(t.length>1&&U(`Multiple plugins have forced output styles: ${t.map(e=>e.name).join(`, `)}. Using: ${n.name}`,{level:`warn`}),U(`Using forced plugin output style: ${n.name}`),n):e[zr()?.outputStyle||`default`]??null}var m4,h4,g4,_4,v4=n((()=>{ne(),d(),Wyt(),vn(),W(),p4(),Vr(),m4=`
2601
+ `)}function S_t(e,t,n=!1){if(e instanceof bn)throw e.interrupted?new Un(`Shell command interrupted for pattern "${t}": [Command interrupted]`):new Un(`Shell command failed for pattern "${t}": ${x_t(e.stdout,e.stderr,n)}`);let r=H(e);throw new Un(n?`[Error: ${r}]`:`[Error]\n${r}`)}var C_t,w_t,T_t,E_t=n((()=>{CW(),W(),On(),m3(),j9(),zy(),qs(),C_t=(()=>{let t;return()=>(t||(t=(Z$(),e(U$)).PowerShellTool),t)})(),w_t=/```!\s*\n?([\s\S]*?)\n?```/g,T_t=/(?<=^|\s)!`([^`]+)`/gm}));function X0(e){return/^skill\.md$/i.test(Kc(e))}function D_t(e,t,n){if(X0(e)){let r=qc(e),i=qc(r),a=Kc(r),o=i.startsWith(t)?i.slice(t.length).replace(/^\//,``):``,s=o?o.split(`/`).join(`:`):``;return s?`${n}:${s}:${a}`:`${n}:${a}`}else{let r=qc(e),i=Kc(e).replace(/\.md$/,``),a=r.startsWith(t)?r.slice(t.length).replace(/^\//,``):``,o=a?a.split(`/`).join(`:`):``;return o?`${n}:${o}:${i}`:`${n}:${i}`}}async function O_t(e,t,n){let r=[],i=G();return await U0(e,async e=>{if(Kn(i,e,n))return;let{frontmatter:a,content:o}=od(await i.readFile(e,{encoding:`utf-8`}),e);r.push({filePath:e,baseDir:t,frontmatter:a,content:o})},{stopAtSkillDir:!0,logLabel:`commands`}),r}function k_t(e){let t=new Map;for(let n of e){let e=qc(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=>X0(e.filePath));if(t.length>0){let r=t[0];t.length>1&&U(`Multiple skill files found in ${e}, using ${Kc(r.filePath)}`),n.push(r)}else n.push(...r)}return n}async function A_t(e,t,n,r,i,a={isSkillMode:!1},o=new Set){let s=k_t(await O_t(e,e,o)),c=[];for(let e of s){let o=Z0(D_t(e.filePath,e.baseDir,t),e,n,r,i,X0(e.filePath),a);o&&c.push(o)}return c}function Z0(e,t,n,r,i,a,o={isSkillMode:!1}){try{let{frontmatter:s,content:c}=t,l=ud(s.description,e),u=l??B9(c,a?`Plugin skill`:`Plugin command`),d=s[`allowed-tools`],f=H9(typeof d==`string`?rT(d,{path:i,source:n}):Array.isArray(d)?d.map(e=>typeof e==`string`?rT(e,{path:i,source:n}):e):d),p=s[`argument-hint`],m=v_t(s.arguments),h=s.when_to_use,g=s.version,_=s.name,v=s.model===`inherit`?void 0:s.model?ro(s.model):void 0,y=dd(s[`disable-model-invocation`]),b=s[`user-invocable`],x=b===void 0||dd(b),S=fd(s.shell,e);return{type:`prompt`,name:e,description:u,hasUserSpecifiedDescription:l!==null,allowedTools:f,argumentHint:p,argNames:m.length>0?m:void 0,whenToUse:h,version:g,model:v,disableModelInvocation:y,userInvocable:x,contentLength:c.length,source:`plugin`,loadedFrom:a||o.isSkillMode?`plugin`:void 0,pluginInfo:{pluginManifest:r,repository:n},isHidden:!x,progressMessage:a||o.isSkillMode?`loading`:`running`,userFacingName(){return _||e},async getPromptForCommand(a,s){let l=o.isSkillMode?`Base directory for this skill: ${qc(t.filePath)}\n\n${c}`:c;if(l=J0(l,a,!0,m),l=rT(l,{path:i,source:n}),r.userConfig&&(l=Hke(l,aT(n),r.userConfig)),o.isSkillMode){let e=qc(t.filePath),n=process.platform===`win32`?e.replace(/\\/g,`/`):e;l=l.replace(/\$\{CLAUDE_SKILL_DIR\}/g,n)}return l=l.replace(/\$\{CLAUDE_SESSION_ID\}/g,sn()),l=await b_t(l,{...s,getAppState(){let e=s.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:f}}}}},`/${e}`,S),[{type:`text`,text:l}]}}}catch(e){return U(`Failed to create command from ${t.filePath}: ${e}`,{level:`error`}),null}}function j_t(){Q0.cache?.clear?.()}async function M_t(e,t,n,r,i,a){let o=G(),s=[],c=Y(e,`SKILL.md`),l=null;try{l=await o.readFile(c,{encoding:`utf-8`})}catch(e){if(!xn(e))return U(`Failed to load skill from ${c}: ${e}`,{level:`error`}),s}if(l!==null){if(Kn(o,c,a))return s;try{let{frontmatter:a,content:o}=od(l,c),u=Z0(`${t}:${Kc(e)}`,{filePath:c,baseDir:qc(c),frontmatter:a,content:o},n,r,i,!0,{isSkillMode:!0});u&&s.push(u)}catch(e){U(`Failed to load skill from ${c}: ${e}`,{level:`error`})}return s}let u;try{u=await o.readdir(e)}catch(t){return xn(t)||U(`Failed to load skills from directory ${e}: ${t}`,{level:`error`}),s}return await Promise.all(u.map(async c=>{if(!c.isDirectory()&&!c.isSymbolicLink())return;let l=Y(Y(e,c.name),`SKILL.md`),u;try{u=await o.readFile(l,{encoding:`utf-8`})}catch(e){xn(e)||U(`Failed to load skill from ${l}: ${e}`,{level:`error`});return}if(!Kn(o,l,a))try{let{frontmatter:e,content:a}=od(u,l),o=Z0(`${t}:${c.name}`,{filePath:l,baseDir:qc(l),frontmatter:e,content:a},n,r,i,!0,{isSkillMode:!0});o&&s.push(o)}catch(e){U(`Failed to load skill from ${l}: ${e}`,{level:`error`})}})),s}function N_t(){$0.cache?.clear?.()}var Q0,$0,e2=n((()=>{d(),Wt(),Wg(),Y0(),W(),h(),On(),gd(),Bn(),K9(),No(),E_t(),d4(),oT(),W0(),Q0=u(async()=>{if(v()&&kt().length===0)return[];let{enabled:e,errors:t}=await u4();t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`);let n=(await Promise.all(e.map(async e=>{let t=new Set,n=[];if(e.commandsPath)try{let r=await A_t(e.commandsPath,e.name,e.source,e.manifest,e.path,{isSkillMode:!1},t);n.push(...r),r.length>0&&U(`Loaded ${r.length} commands from plugin ${e.name} default directory`)}catch(t){U(`Failed to load commands from plugin ${e.name} default directory: ${t}`,{level:`error`})}if(e.commandsPaths){U(`Plugin ${e.name} has commandsPaths: ${e.commandsPaths.join(`, `)}`);let r=await Promise.all(e.commandsPaths.map(async n=>{try{let r=G(),i=await r.stat(n);if(U(`Checking commandPath ${n} - isDirectory: ${i.isDirectory()}, isFile: ${i.isFile()}`),i.isDirectory()){let r=await A_t(n,e.name,e.source,e.manifest,e.path,{isSkillMode:!1},t);return r.length>0?U(`Loaded ${r.length} commands from plugin ${e.name} custom path: ${n}`):U(`Warning: No commands found in plugin ${e.name} custom directory: ${n}. Expected .md files or SKILL.md in subdirectories.`,{level:`warn`}),r}else if(i.isFile()&&n.endsWith(`.md`)){if(Kn(r,n,t))return[];let{frontmatter:i,content:a}=od(await r.readFile(n,{encoding:`utf-8`}),n),o,s;if(e.commandsMetadata){for(let[t,r]of Object.entries(e.commandsMetadata))if(r.source&&n===Y(e.path,r.source)){o=`${e.name}:${t}`,s=r;break}}o||(o=`${e.name}:${Kc(n).replace(/\.md$/,``)}`);let c=s?{...i,...s.description&&{description:s.description},...s.argumentHint&&{"argument-hint":s.argumentHint},...s.model&&{model:s.model},...s.allowedTools&&{"allowed-tools":s.allowedTools.join(`,`)}}:i,l={filePath:n,baseDir:qc(n),frontmatter:c,content:a},u=Z0(o,l,e.source,e.manifest,e.path,!1);if(u)return U(`Loaded command from plugin ${e.name} custom file: ${n}${s?` (with metadata override)`:``}`),[u]}return[]}catch(t){return U(`Failed to load commands from plugin ${e.name} custom path ${n}: ${t}`,{level:`error`}),[]}}));for(let e of r)n.push(...e)}if(e.commandsMetadata){for(let[t,r]of Object.entries(e.commandsMetadata))if(r.content&&!r.source)try{let{frontmatter:i,content:a}=od(r.content,`<inline:${e.name}:${t}>`),o={...i,...r.description&&{description:r.description},...r.argumentHint&&{"argument-hint":r.argumentHint},...r.model&&{model:r.model},...r.allowedTools&&{"allowed-tools":r.allowedTools.join(`,`)}},s=`${e.name}:${t}`,c=Z0(s,{filePath:`<inline:${s}>`,baseDir:e.path,frontmatter:o,content:a},e.source,e.manifest,e.path,!1);c&&(n.push(c),U(`Loaded inline content command from plugin ${e.name}: ${s}`))}catch(n){U(`Failed to load inline content command ${t} from plugin ${e.name}: ${n}`,{level:`error`})}}return n}))).flat();return U(`Total plugin commands loaded: ${n.length}`),n}),$0=u(async()=>{if(v()&&kt().length===0)return[];let{enabled:e,errors:t}=await u4();t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`),U(`getPluginSkills: Processing ${e.length} enabled plugins`);let n=(await Promise.all(e.map(async e=>{let t=new Set,n=[];if(U(`Checking plugin ${e.name}: skillsPath=${e.skillsPath?`exists`:`none`}, skillsPaths=${e.skillsPaths?e.skillsPaths.length:0} paths`),e.skillsPath){U(`Attempting to load skills from plugin ${e.name} default skillsPath: ${e.skillsPath}`);try{let r=await M_t(e.skillsPath,e.name,e.source,e.manifest,e.path,t);n.push(...r),U(`Loaded ${r.length} skills from plugin ${e.name} default directory`)}catch(t){U(`Failed to load skills from plugin ${e.name} default directory: ${t}`,{level:`error`})}}if(e.skillsPaths){U(`Attempting to load skills from plugin ${e.name} skillsPaths: ${e.skillsPaths.join(`, `)}`);let r=await Promise.all(e.skillsPaths.map(async n=>{try{U(`Loading from skillPath: ${n} for plugin ${e.name}`);let r=await M_t(n,e.name,e.source,e.manifest,e.path,t);return U(`Loaded ${r.length} skills from plugin ${e.name} custom path: ${n}`),r}catch(t){return U(`Failed to load skills from plugin ${e.name} custom path ${n}: ${t}`,{level:`error`}),[]}}));for(let e of r)n.push(...e)}return n}))).flat();return U(`Total plugin skills loaded: ${n.length}`),n})}));function t2(){return m(process.env.CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE)}function n2(){if(!t2())return;let e=process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR;return e?T_(e):void 0}function P_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`known_marketplaces.json`)}function F_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`marketplaces`)}function I_t(){let e=n2();if(!e)throw Error(`Plugin zip cache is not enabled`);return Y(e,`plugins`)}async function L_t(){return r2||(i2||(i2=(async()=>{let e=yl(8).toString(`hex`),t=Y(Wc(),`claude-plugin-session-${e}`);return await G().mkdir(t),r2=t,U(`Created session plugin cache at ${t}`),t})()),i2)}async function R_t(){if(r2)try{await Ml(r2,{recursive:!0,force:!0}),U(`Cleaned up session plugin cache at ${r2}`)}catch(e){U(`Failed to clean up session plugin cache: ${e}`)}finally{r2=null,i2=null}}async function z_t(e,t){let n=qc(e);await G().mkdir(n);let r=Y(n,`.${Kc(e)}.tmp.${yl(4).toString(`hex`)}`);try{typeof t==`string`?await Il(r,t,{encoding:`utf-8`}):await Il(r,t),await jl(r,e)}catch(e){try{await Ml(r,{force:!0})}catch{}throw e}}async function B_t(e){let t={};await V_t(e,``,t,new Set);let{zipSync:n}=await import(`./esm-wGnzjq4Z.js`),r=n(t,{level:6});return U(`Created ZIP from ${e}: ${Object.keys(t).length} files, ${r.length} bytes`),r}async function V_t(e,t,n,r){let i=t?Y(e,t):e,a;try{a=await kl(i)}catch{return}try{let e=await Nl(i,{bigint:!0});if(e.dev!==0n||e.ino!==0n){let t=`${e.dev}:${e.ino}`;if(r.has(t)){U(`Skipping symlink cycle at ${i}`);return}r.add(t)}}catch{return}for(let o of a){if(o===`.git`)continue;let a=Y(i,o),s=t?`${t}/${o}`:o,c;try{c=await uue(a)}catch{continue}if(c.isSymbolicLink())try{let e=await Nl(a);if(e.isDirectory())continue;c=e}catch{continue}if(c.isDirectory())await V_t(e,s,n,r);else if(c.isFile())try{let e=await Ol(a);n[s]=[new Uint8Array(e),{os:3,attrs:(c.mode&65535)<<16}]}catch(e){U(`Failed to read file for zip: ${s}: ${e}`)}}}async function H_t(e,t){let n=await G().readFileBytes(e),r=await Ww(n),i=Gw(n);await G().mkdir(t);for(let[e,n]of Object.entries(r)){if(e.endsWith(`/`)){await G().mkdir(Y(t,e));continue}let r=Y(t,e);await G().mkdir(qc(r)),await Il(r,n);let a=i[e];a&&a&73&&await Cl(r,a&511).catch(()=>{})}U(`Extracted ZIP to ${t}: ${Object.keys(r).length} entries`)}async function U_t(e,t){await z_t(t,await B_t(e)),await Ml(e,{recursive:!0,force:!0})}function W_t(e){return Y(`marketplaces`,`${e.replace(/[^a-zA-Z0-9\-_]/g,`-`)}.json`)}function G_t(e){return[`github`,`git`,`url`,`settings`].includes(e.source)}var r2,i2,a2=n((()=>{W(),qw(),h(),Bn(),j_(),r2=null,i2=null}));function K_t(){c4(),j_t(),g_t(),Ez(),xze().catch(e=>q(e)),nT(),Hyt(),Gyt()}function q_t(){K_t(),qSt(),Ykt(),ube(),zgt()}async function o2(e){try{await Il(s2(e),`${Date.now()}`,`utf-8`)}catch(t){U(`Failed to write .orphaned_at: ${e}: ${t}`)}}async function J_t(){if(!t2())try{let e=X_t();if(!e)return;let t=$2(),n=Date.now();await Promise.all([...e].map(e=>Y_t(e)));for(let r of await c2(t)){let i=Y(t,r);for(let t of await c2(i)){let r=Y(i,t);for(let t of await c2(r)){let i=Y(r,t);e.has(i)||await Z_t(i,n)}await Q_t(r)}await Q_t(i)}}catch(e){U(`Plugin cache cleanup failed: ${e}`)}}function s2(e){return Y(e,$_t)}async function Y_t(e){let t=s2(e);try{await Fl(t)}catch(t){if(Cn(t)===`ENOENT`)return;U(`Failed to remove .orphaned_at: ${e}: ${t}`)}}function X_t(){try{let e=new Set,t=V2();for(let n of Object.values(t.plugins))for(let t of n)e.add(t.installPath);return e}catch(e){return U(`Failed to load installed plugins: ${e}`),null}}async function Z_t(e,t){let n=s2(e),r;try{r=(await Nl(n)).mtimeMs}catch(t){if(Cn(t)===`ENOENT`){await o2(e);return}U(`Failed to stat orphaned marker: ${e}: ${t}`);return}if(t-r>evt)try{await Ml(e,{recursive:!0,force:!0})}catch(t){U(`Failed to delete orphaned version: ${e}: ${t}`)}}async function Q_t(e){if((await c2(e)).length===0)try{await Ml(e,{recursive:!0,force:!0})}catch(t){U(`Failed to remove empty dir: ${e}: ${t}`)}}async function c2(e){try{return(await kl(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}var $_t,evt,l2=n((()=>{e6(),v4(),$9(),V_(),H0(),W(),On(),Qi(),K2(),q0(),e2(),jz(),p4(),d4(),oT(),a2(),$_t=`.orphaned_at`,evt=10080*60*1e3}));function tvt(e,t){let n=e.slice(0,2).map(e=>{let n=e.reason||e.error||`unknown error`;return t?`${e.name} (${n})`:e.name}).join(t?`; `:`, `),r=e.length-2;return`${n}${r>0?` and ${r} more`:``}`}function nvt(e){switch(e.source){case`github`:return e.repo;case`url`:return e.url;case`git`:return e.url;case`directory`:return e.path;case`file`:return e.path;case`settings`:return`settings:${e.name}`;default:return`Unknown source`}}function rvt(e,t){return`${e}@${t}`}async function ivt(e){let t=[],n=[];for(let[r,i]of Object.entries(e)){if(!p2(i.source))continue;let e=null;try{e=await P2(r)}catch(e){let t=e instanceof Error?e.message:String(e);n.push({name:r,error:t}),q(jn(e))}t.push({name:r,config:i,data:e})}return{marketplaces:t,failures:n}}function avt(e,t){return e.length===0?null:t>0?{type:`warning`,message:e.length===1?`Warning: Failed to load marketplace '${e[0].name}': ${e[0].error}`:`Warning: Failed to load ${e.length} marketplaces: ${ovt(e)}`}:{type:`error`,message:`Failed to load all marketplaces. Errors: ${svt(e)}`}}function ovt(e){return e.map(e=>e.name).join(`, `)}function svt(e){return e.map(e=>`${e.name}: ${e.error}`).join(`; `)}function u2(){let e=Ir(`policySettings`);return e?.strictKnownMarketplaces?e.strictKnownMarketplaces:null}function cvt(){let e=Ir(`policySettings`);return e?.blockedMarketplaces?e.blockedMarketplaces:null}function lvt(){return Ir(`policySettings`)?.pluginTrustMessage}function uvt(e,t){if(e.source!==t.source)return!1;switch(e.source){case`url`:return e.url===t.url;case`github`:return e.repo===t.repo&&(e.ref||void 0)===(t.ref||void 0)&&(e.path||void 0)===(t.path||void 0);case`git`:return e.url===t.url&&(e.ref||void 0)===(t.ref||void 0)&&(e.path||void 0)===(t.path||void 0);case`npm`:return e.package===t.package;case`file`:return e.path===t.path;case`directory`:return e.path===t.path;case`settings`:return e.name===t.name&&Io(e.plugins,t.plugins);default:return!1}}function dvt(e){switch(e.source){case`github`:return`github.com`;case`git`:{let t=e.url.match(/^[^@]+@([^:]+):/);if(t?.[1])return t[1];try{return new URL(e.url).hostname}catch{return null}}case`url`:try{return new URL(e.url).hostname}catch{return null}default:return null}}function fvt(e,t){let n=dvt(e);if(!n)return!1;try{return new RegExp(t.hostPattern).test(n)}catch{return q(Error(`Invalid hostPattern regex: ${t.hostPattern}`)),!1}}function pvt(e,t){if(e.source!==`file`&&e.source!==`directory`)return!1;try{return new RegExp(t.pathPattern).test(e.path)}catch{return q(Error(`Invalid pathPattern regex: ${t.pathPattern}`)),!1}}function mvt(){let e=u2();return e?e.filter(e=>e.source===`hostPattern`).map(e=>e.hostPattern):[]}function hvt(e){let t=e.match(/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);if(t?.[1])return t[1];let n=e.match(/^https?:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);return n?.[1]?n[1]:null}function d2(e,t){return!e||(e||void 0)===(t||void 0)}function gvt(e,t){if(e.source===t.source)switch(e.source){case`github`:{let n=t;return e.repo===n.repo&&d2(n.ref,e.ref)&&d2(n.path,e.path)}case`git`:{let n=t;return e.url===n.url&&d2(n.ref,e.ref)&&d2(n.path,e.path)}case`url`:return e.url===t.url;case`npm`:return e.package===t.package;case`file`:return e.path===t.path;case`directory`:return e.path===t.path;case`settings`:return e.name===t.name;default:return!1}return e.source===`git`&&t.source===`github`&&hvt(e.url)===t.repo||e.source===`github`&&t.source===`git`&&hvt(t.url)===e.repo?d2(t.ref,e.ref)&&d2(t.path,e.path):!1}function f2(e){let t=cvt();return t!==null&&t.some(t=>gvt(e,t))}function p2(e){if(f2(e))return!1;let t=u2();return t===null||t.some(t=>t.source===`hostPattern`?fvt(e,t):t.source===`pathPattern`?pvt(e,t):uvt(e,t))}function m2(e){switch(e.source){case`github`:return`github:${e.repo}${e.ref?`@${e.ref}`:``}`;case`url`:return e.url;case`git`:return`git:${e.url}${e.ref?`@${e.ref}`:``}`;case`npm`:return`npm:${e.package}`;case`file`:return`file:${e.path}`;case`directory`:return`dir:${e.path}`;case`hostPattern`:return`hostPattern:${e.hostPattern}`;case`pathPattern`:return`pathPattern:${e.pathPattern}`;case`settings`:return`settings:${e.name} (${e.plugins.length} ${qa(e.plugins.length,`plugin`)})`;default:return`unknown source`}}async function _vt({configuredMarketplaceCount:e,failedMarketplaceCount:t}){if(!await c_())return`git-not-installed`;let n=u2();if(n!==null){if(n.length===0)return`all-blocked-by-policy`;if(e===0)return`policy-restricts-sources`}return e===0?`no-marketplaces-configured`:t>0&&t===e?`all-marketplaces-failed`:`all-plugins-installed`}var h2=n((()=>{Ho(),On(),Qi(),Vr(),Ja(),l_(),F2()}));async function g2(e,t){let n=el(t),r=el(e);if(r!==n&&!r.startsWith(n+tl))return U(`fetchOfficialMarketplaceFromGcs: refusing path outside cache dir: ${e}`,{level:`error`}),null;await jte();let i=performance.now(),a=`failed`,o,s,c;try{let t=await ue.get(`${_2}/latest`,{responseType:`text`,timeout:1e4});if(o=String(t.data).trim(),!o)throw Error(`latest pointer returned empty body`);if(await Ol(Y(e,`.gcs-sha`),`utf8`).then(e=>e.trim(),()=>null)===o)return a=`noop`,o;let n=await ue.get(`${_2}/${o}.zip`,{responseType:`arraybuffer`,timeout:6e4}),r=Buffer.from(n.data);s=r.length;let i=await Ww(r),c=Gw(r),l=`${e}.staging`;await Ml(l,{recursive:!0,force:!0}),await El(l,{recursive:!0});for(let[e,t]of Object.entries(i)){if(!e.startsWith(yvt))continue;let n=e.slice(37);if(!n||n.endsWith(`/`))continue;let r=Y(l,n);await El(qc(r),{recursive:!0}),await Il(r,t);let i=c[e];i&&i&73&&await Cl(r,i&511).catch(()=>{})}return await Il(Y(l,`.gcs-sha`),o),await Ml(e,{recursive:!0,force:!0}),await jl(l,e),a=`updated`,o}catch(e){return c=vvt(e),U(`Official marketplace GCS fetch failed: ${H(e)}`,{level:`warn`}),null}finally{J(`tengu_plugin_remote_fetch`,{source:`marketplace_gcs`,host:`downloads.workmate.ai`,is_official:!0,outcome:a,duration_ms:Math.round(performance.now()-i),...s!==void 0&&{bytes:s},...o&&{sha:o},...c&&{error_kind:c}})}}function vvt(e){if(ue.isAxiosError(e))return e.code===`ECONNABORTED`?`timeout`:e.response?`http_${e.response.status}`:`network`;let t=Cn(e);if(t&&/^E[A-Z]+$/.test(t)&&!t.startsWith(`ERR_`))return bvt.has(t)?`fs_${t}`:`fs_other`;if(typeof e?.code==`number`)return`zip_parse`;let n=H(e);return/unzip|invalid zip|central directory/i.test(n)?`zip_parse`:/empty body/.test(n)?`empty_latest`:`other`}var _2,yvt,bvt,xvt=n((()=>{de(),Wt(),Da(),W(),qw(),On(),_2=`https://downloads.workmate.ai/claude-code-releases/plugins/claude-plugins-official`,yvt=`marketplaces/claude-plugins-official/`,bvt=new Set([`ENOSPC`,`EACCES`,`EPERM`,`EXDEV`,`EBUSY`,`ENOENT`,`ENOTDIR`,`EROFS`,`EMFILE`,`ENAMETOOLONG`])}));function v2(){return Y(M_(),`known_marketplaces.json`)}function y2(){return Y(M_(),`marketplaces`)}function Svt(){P2.cache?.clear?.()}function Cvt(){let e={},t={...Jg(),...Xr().enabledPlugins??{}};for(let[n,r]of Object.entries(t))if(r&&Zg(n).marketplace===`claude-plugins-official`){e[r_]={source:n_,sourceIsFallback:!0};break}return{...e,...Tye(),...Xr().extraKnownMarketplaces??{}}}function wvt(e){for(let t of[`localSettings`,`projectSettings`,`userSettings`])if(Ir(t)?.extraKnownMarketplaces?.[e])return t;return null}function Tvt(e,t,n=`userSettings`){let r={...(Ir(n)??{}).extraKnownMarketplaces};r[e]=t,li(n,{extraKnownMarketplaces:r})}async function b2(){let e=G(),t=v2();try{let n=kn(await e.readFile(t,{encoding:`utf-8`})),r=Rr().safeParse(n);if(!r.success){let e=`Marketplace configuration file is corrupted: ${r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`;throw U(e,{level:`error`}),new Dn(e,t,n)}return r.data}catch(e){if(xn(e))return{};if(e instanceof Dn)throw e;let t=`Failed to load marketplace configuration: ${H(e)}`;throw U(t,{level:`error`}),Error(t)}}async function Evt(){try{return await b2()}catch{return{}}}async function x2(e){let t=Rr().safeParse(e),n=v2();if(!t.success)throw new Dn(`Invalid marketplace config: ${t.error.message}`,n,e);let r=G(),i=Y(n,`..`);await r.mkdir(i),An(n,V(t.data,null,2),{encoding:`utf-8`,flush:!0})}async function Dvt(){let e=N_();if(e.length===0)return!1;let t=await b2(),n=new Set,r=0;for(let i of e){let e=await Ovt(i);if(e)for(let[a,o]of Object.entries(e)){if(n.has(a))continue;let e=await kvt(i,a);if(!e){U(`Seed marketplace '${a}' not found under ${i}/marketplaces/, skipping`,{level:`warn`});continue}n.add(a);let s={source:o.source,installLocation:e,lastUpdated:o.lastUpdated,autoUpdate:!1};Io(t[a],s)||(t[a]=s,r++)}}return r>0?(await x2(t),U(`Synced ${r} marketplace(s) from seed dir(s)`),!0):!1}async function Ovt(e){let t=Y(e,`known_marketplaces.json`);try{let n=await G().readFile(t,{encoding:`utf-8`}),r=Rr().safeParse(kn(n));return r.success?r.data:(U(`Seed known_marketplaces.json invalid at ${e}: ${r.error.message}`,{level:`warn`}),null)}catch(t){return xn(t)||U(`Failed to read seed known_marketplaces.json at ${e}: ${t}`,{level:`warn`}),null}}async function kvt(e,t){let n=Y(e,`marketplaces`,t),r=Y(e,`marketplaces`,`${t}.json`);for(let e of[n,r])try{return await A2(e),e}catch{}return null}function S2(e){return N_().find(t=>e===t||e.startsWith(t+tl))}function C2(){let e=process.env.CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS;if(e){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}return Kvt}async function Avt(e,t,n){U(`git pull: cwd=${e} ref=${t??`default`}`);let r={...process.env,...N2},i=n?.disableCredentialHelper?[`-c`,`credential.helper=`]:[];if(t){let a=await Li(Pi(),[...i,`fetch`,`origin`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});if(a.code!==0)return w2(a);let o=await Li(Pi(),[...i,`checkout`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});if(o.code!==0)return w2(o);let s=await Li(Pi(),[...i,`pull`,`origin`,t],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});return s.code===0?(await jvt(e,i,r,n?.sparsePaths),s):w2(s)}let a=await Li(Pi(),[...i,`pull`,`origin`,`HEAD`],{cwd:e,timeout:C2(),stdin:`ignore`,env:r});return a.code===0?(await jvt(e,i,r,n?.sparsePaths),a):w2(a)}async function jvt(e,t,n,r){if(r&&r.length>0||!await G().stat(Y(e,`.gitmodules`)).then(()=>!0,()=>!1))return;let i=await Li(Pi(),[`-c`,`core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes`,...t,`submodule`,`update`,`--init`,`--recursive`,`--depth`,`1`],{cwd:e,timeout:C2(),stdin:`ignore`,env:n});i.code!==0&&U(`git submodule update failed (non-fatal): ${i.stderr}`,{level:`warn`})}function w2(e){if(e.code===0)return e;if(e.error?.includes(`timed out`)){let t=Math.round(C2()/1e3);return{...e,stderr:`Git pull timed out after ${t}s. Try increasing the timeout via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS environment variable.\n\nOriginal error: ${e.stderr}`}}return e.stderr.includes(`REMOTE HOST IDENTIFICATION HAS CHANGED`)?{...e,stderr:`SSH host key for this marketplace's git host has changed (server key rotation or possible MITM). Remove the stale entry with: ssh-keygen -R <host>\nThen connect once manually to accept the new key.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`Host key verification failed`)?{...e,stderr:`SSH host key verification failed while updating marketplace. The host key is not in your known_hosts file. Connect once manually to add it (e.g., ssh -T git@<host>), or remove and re-add the marketplace with an HTTPS URL.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`Permission denied (publickey)`)||e.stderr.includes(`Could not read from remote repository`)?{...e,stderr:`SSH authentication failed while updating marketplace. Please ensure your SSH keys are configured.\n\nOriginal error: ${e.stderr}`}:e.stderr.includes(`timed out`)||e.stderr.includes(`Could not resolve host`)?{...e,stderr:`Network error while updating marketplace. Please check your internet connection.\n\nOriginal error: ${e.stderr}`}:e}async function Mvt(){try{let e=await Bi(`ssh`,[`-T`,`-o`,`BatchMode=yes`,`-o`,`ConnectTimeout=2`,`-o`,`StrictHostKeyChecking=yes`,`git@github.com`],{timeout:3e3}),t=e.code===1&&(e.stderr?.includes(`successfully authenticated`)||e.stdout?.includes(`successfully authenticated`));return U(`SSH config check: code=${e.code} configured=${t}`),t}catch(e){return U(`SSH configuration check failed: ${H(e)}`,{level:`warn`}),!1}}function Nvt(e){return e.includes(`Authentication failed`)||e.includes(`could not read Username`)||e.includes(`terminal prompts disabled`)||e.includes(`403`)||e.includes(`401`)}function Pvt(e){return e.match(/^[^@]+@([^:]+):/)?.[1]??null}async function Fvt(e,t,n,r){let i=r&&r.length>0,a=[`-c`,`core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes`,`clone`,`--depth`,`1`];i?a.push(`--filter=blob:none`,`--no-checkout`):a.push(`--recurse-submodules`,`--shallow-submodules`),n&&a.push(`--branch`,n),a.push(e,t);let o=C2();U(`git clone: url=${D2(e)} ref=${n??`default`} timeout=${o}ms`);let s=await Li(Pi(),a,{timeout:o,stdin:`ignore`,env:{...process.env,...N2}}),c=D2(e);if(e!==c&&(s.error&&(s.error=s.error.replaceAll(e,c)),s.stderr&&(s.stderr=s.stderr.replaceAll(e,c))),s.code===0){if(i){let e=await Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,...r],{cwd:t,timeout:o,stdin:`ignore`,env:{...process.env,...N2}});if(e.code!==0)return{code:e.code,stderr:`git sparse-checkout set failed: ${e.stderr}`};let n=await Li(Pi(),[`checkout`,`HEAD`],{cwd:t,timeout:o,stdin:`ignore`,env:{...process.env,...N2}});if(n.code!==0)return{code:n.code,stderr:`git checkout after sparse-checkout failed: ${n.stderr}`}}return U(`git clone succeeded: ${D2(e)}`),s}if(U(`git clone failed: url=${D2(e)} code=${s.code} error=${s.error??`none`} stderr=${s.stderr}`,{level:`warn`}),s.error?.includes(`timed out`))return{...s,stderr:`Git clone timed out after ${Math.round(o/1e3)}s. The repository may be too large for the current timeout. Set CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to increase it (e.g., 300000 for 5 minutes).\n\nOriginal error: ${s.stderr}`};if(s.stderr){if(s.stderr.includes(`REMOTE HOST IDENTIFICATION HAS CHANGED`)){let t=Pvt(e),n=t?`ssh-keygen -R ${t}`:`ssh-keygen -R <host>`;return{...s,stderr:`SSH host key has changed (server key rotation or possible MITM). Remove the stale known_hosts entry:\n ${n}\nThen connect once manually to verify and accept the new key.\n\nOriginal error: ${s.stderr}`}}if(s.stderr.includes(`Host key verification failed`)){let t=Pvt(e),n=t?`ssh -T git@${t}`:`ssh -T git@<host>`;return{...s,stderr:`SSH host key is not in your known_hosts file. To add it, connect once manually (this will show the fingerprint for you to verify):\n ${n}\n\nOr use an HTTPS URL instead (recommended for public repos).\n\nOriginal error: ${s.stderr}`}}if(s.stderr.includes(`Permission denied (publickey)`)||s.stderr.includes(`Could not read from remote repository`))return{...s,stderr:`SSH authentication failed. Please ensure your SSH keys are configured for GitHub, or use an HTTPS URL instead.\n\nOriginal error: ${s.stderr}`};if(Nvt(s.stderr))return{...s,stderr:`HTTPS authentication failed. Please ensure your credential helper is configured (e.g., gh auth login).\n\nOriginal error: ${s.stderr}`};if(s.stderr.includes(`timed out`)||s.stderr.includes(`timeout`)||s.stderr.includes(`Could not resolve host`))return{...s,stderr:`Network error or timeout while cloning repository. Please check your internet connection and try again.\n\nOriginal error: ${s.stderr}`}}return s.stderr?s:{code:s.code,stderr:s.error||`git clone exited with code ${s.code} (no stderr output). Run with --debug to see the full command.`}}function T2(e,t){if(e)try{e(t)}catch(e){U(`Progress callback error: ${H(e)}`,{level:`warn`})}}async function Ivt(e,t){let n={...process.env,...N2};if(t&&t.length>0)return Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,...t],{cwd:e,timeout:C2(),stdin:`ignore`,env:n});let r=await Li(Pi(),[`config`,`--get`,`core.sparseCheckout`],{cwd:e,stdin:`ignore`,env:n});return r.code===0&&r.stdout.trim()===`true`?{code:1,stderr:`sparsePaths removed from config but repository is sparse; re-cloning for full checkout`}:{code:0,stderr:``}}async function E2(e,t,n,r,i,a){let o=G(),s=Math.round(C2()/1e3);T2(i,`Refreshing marketplace cache (timeout: ${s}s)…`);let c=await Ivt(t,r);if(c.code===0){let i=performance.now(),o=await Avt(t,n,{disableCredentialHelper:a?.disableCredentialHelper,sparsePaths:r});if(a_(`marketplace_pull`,e,o.code===0?`success`:`failure`,performance.now()-i,o.code===0?void 0:o_(o.stderr)),o.code===0)return;U(`git pull failed, will re-clone: ${o.stderr}`,{level:`warn`})}else U(`sparse-checkout reconcile requires re-clone: ${c.stderr}`);try{await o.rm(t,{recursive:!0}),U(`Found stale marketplace directory at ${t}, cleaning up to allow re-clone`,{level:`warn`}),T2(i,`Found stale directory, cleaning up and re-cloning…`)}catch(e){if(!xn(e)){let n=H(e);throw Error(`Failed to clean up existing marketplace directory. Please manually delete the directory at ${t} and try again.\n\nTechnical details: ${n}`)}}let l=n?` (ref: ${n})`:``;T2(i,`Cloning repository (timeout: ${s}s): ${D2(e)}${l}`);let u=performance.now(),d=await Fvt(e,t,n,r);if(a_(`marketplace_clone`,e,d.code===0?`success`:`failure`,performance.now()-u,d.code===0?void 0:o_(d.stderr)),d.code!==0){try{await o.rm(t,{recursive:!0,force:!0})}catch{}throw Error(`Failed to clone marketplace repository: ${d.stderr}`)}T2(i,`Clone complete, validating marketplace…`)}function Lvt(e){return Object.fromEntries(Object.entries(e).map(([e])=>[e,`***REDACTED***`]))}function D2(e){try{let t=new URL(e);if((t.protocol===`http:`||t.protocol===`https:`)&&(t.username||t.password))return t.username&&(t.username=`***`),t.password&&(t.password=`***`),t.toString()}catch{}return e}async function Rvt(e,t,n,r){let i=G(),a=D2(e);T2(r,`Downloading marketplace from ${a}`),U(`Downloading marketplace from URL: ${a}`),n&&Object.keys(n).length>0&&U(`Using custom headers: ${V(Lvt(n))}`);let o={...n,"User-Agent":`Work Mate-Code-Plugin-Manager`},s,c=performance.now();try{s=await ue.get(e,{timeout:1e4,headers:o})}catch(t){if(a_(`marketplace_url`,e,`failure`,performance.now()-c,o_(t)),ue.isAxiosError(t)){if(t.code===`ECONNREFUSED`||t.code===`ENOTFOUND`)throw Error(`Could not connect to ${a}. Please check your internet connection and verify the URL is correct.\n\nTechnical details: ${t.message}`);if(t.code===`ETIMEDOUT`)throw Error(`Request timed out while downloading marketplace from ${a}. The server may be slow or unreachable.\n\nTechnical details: ${t.message}`);if(t.response)throw Error(`HTTP ${t.response.status} error while downloading marketplace from ${a}. The marketplace file may not exist at this URL.\n\nTechnical details: ${t.message}`)}throw Error(`Failed to download marketplace from ${a}: ${H(t)}`)}T2(r,`Validating marketplace data`);let l=Nr().safeParse(s.data);if(!l.success)throw a_(`marketplace_url`,e,`failure`,performance.now()-c,`invalid_schema`),new Dn(`Invalid marketplace schema from URL: ${l.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`,a,s.data);a_(`marketplace_url`,e,`success`,performance.now()-c),T2(r,`Saving marketplace to cache`);let u=Y(t,`..`);await i.mkdir(u),An(t,V(l.data,null,2),{encoding:`utf-8`,flush:!0})}function zvt(e){return e.source===`github`?e.repo.replace(`/`,`-`):e.source===`npm`?e.package.replace(`@`,``).replace(`/`,`-`):e.source===`file`?Kc(e.path).replace(`.json`,``):e.source===`directory`?Kc(e.path):`temp_${Date.now()}`}async function O2(e,t){let n=await G().readFile(e,{encoding:`utf-8`}),r;try{r=kn(n)}catch(t){throw new Dn(`Invalid JSON in ${e}: ${H(t)}`,e,n)}let i=t.safeParse(r);if(!i.success)throw new Dn(`Invalid schema: ${e} ${i.error?.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`,e,r);return i.data}async function k2(e,t){let n=G(),r=y2();await n.mkdir(r);let i,a,o=!1,s=zvt(e);try{switch(e.source){case`url`:i=Y(r,`${s}.json`),o=!0,await Rvt(e.url,i,e.headers,t),a=i;break;case`github`:{let c=`git@github.com:${e.repo}.git`,l=`https://github.com/${e.repo}.git`;i=Y(r,s),o=!0;let u=null;if(await Mvt()){T2(t,`Cloning via SSH: ${c}`);try{await E2(c,i,e.ref,e.sparsePaths,t)}catch(r){u=jn(r),q(u),T2(t,`SSH clone failed, retrying with HTTPS: ${l}`),U(`SSH clone failed for ${e.repo} despite SSH being configured, falling back to HTTPS`,{level:`info`}),await n.rm(i,{recursive:!0,force:!0});try{await E2(l,i,e.ref,e.sparsePaths,t),u=null}catch(e){u=jn(e),q(u)}}}else{T2(t,`SSH not configured, cloning via HTTPS: ${l}`),U(`SSH not configured for GitHub, using HTTPS for ${e.repo}`,{level:`info`});try{await E2(l,i,e.ref,e.sparsePaths,t)}catch(r){u=jn(r),q(u),T2(t,`HTTPS clone failed, retrying with SSH: ${c}`),U(`HTTPS clone failed for ${e.repo} (${u.message}), falling back to SSH`,{level:`info`}),await n.rm(i,{recursive:!0,force:!0});try{await E2(c,i,e.ref,e.sparsePaths,t),u=null}catch(e){u=jn(e),q(u)}}}if(u)throw u;a=Y(i,e.path||`.claude-plugin/marketplace.json`);break}case`git`:i=Y(r,s),o=!0,await E2(e.url,i,e.ref,e.sparsePaths,t),a=Y(i,e.path||`.claude-plugin/marketplace.json`);break;case`npm`:throw Error(`NPM marketplace sources not yet implemented`);case`file`:{let t=el(e.path);a=t,i=qc(qc(t)),o=!1;break}case`directory`:{let t=el(e.path);a=Y(t,`.claude-plugin`,`marketplace.json`),i=t,o=!1;break}case`settings`:i=Y(r,e.name),a=Y(i,`.claude-plugin`,`marketplace.json`),o=!1,await n.mkdir(qc(a)),await Il(a,V({name:e.name,owner:e.owner??{name:`settings`},plugins:e.plugins},null,2));break;default:throw Error(`Unsupported marketplace source type`)}U(`Reading marketplace from ${a}`);let c;try{c=await O2(a,Nr())}catch(e){throw xn(e)?Error(`Marketplace file not found at ${a}`):Error(`Failed to parse marketplace file at ${a}: ${H(e)}`)}let l=Y(r,c.name),u=el(l),d=el(r);if(!u.startsWith(d+tl))throw Error(`Marketplace name '${c.name}' resolves to a path outside the cache directory`);if(i!==l&&!di(e))try{try{t?.(`Cleaning up old marketplace cache…`)}catch(e){U(`Progress callback error: ${H(e)}`,{level:`warn`})}await n.rm(l,{recursive:!0,force:!0}),await n.rename(i,l),i=l,o=!1}catch(e){let t=H(e);throw Error(`Failed to finalize marketplace cache. Please manually delete the directory at ${l} if it exists and try again.\n\nTechnical details: ${t}`)}return{marketplace:c,cachePath:i}}catch(t){if(o&&i&&!di(e))try{await n.rm(i,{recursive:!0,force:!0})}catch(e){U(`Warning: Failed to clean up temporary marketplace cache at ${i}: ${H(e)}`,{level:`warn`})}throw t}}async function Bvt(e,t){let n=e;if(di(e)&&!Yc(e.path)&&(n={...e,path:el(e.path)}),!p2(n)){if(f2(n))throw Error(`Marketplace source '${m2(n)}' is blocked by enterprise policy.`);let e=u2()||[],t=mvt(),r=dvt(n),i=`Marketplace source '${m2(n)}'`;throw r&&(i+=` (${r})`),i+=` is blocked by enterprise policy.`,e.length>0?i+=` Allowed sources: ${e.map(e=>m2(e)).join(`, `)}`:i+=` No external marketplaces are allowed.`,n.source===`github`&&t.length>0&&(i+=`\n\nTip: The shorthand "${n.repo}" assumes github.com. For internal GitHub Enterprise, use the full URL:\n git@your-github-host.com:${n.repo}.git`),Error(i)}let r=await b2();for(let[e,t]of Object.entries(r))if(Io(t.source,n))return U(`Source already materialized as '${e}', skipping clone`),{name:e,alreadyMaterialized:!0,resolvedSource:n};let{marketplace:i,cachePath:a}=await k2(n,t),o=Qne(i.name,n);if(o)throw Error(o);let s=await b2(),c=s[i.name];if(c){let e=S2(c.installLocation);if(e)throw Error(`Marketplace '${i.name}' is seed-managed (${e}). To use a different source, ask your admin to update the seed, or use a different marketplace name.`);if(U(`Marketplace '${i.name}' exists with different source — overwriting`),!di(c.source)){let e=el(y2()),t=el(c.installLocation);t===el(a)||(t===e||t.startsWith(e+tl)?await G().rm(c.installLocation,{recursive:!0,force:!0}):U(`Skipping cleanup of old installLocation (${c.installLocation}) — outside ${e}. The path is corrupted; leaving it alone and overwriting the config entry.`,{level:`warn`}))}}return s[i.name]={source:n,installLocation:a,lastUpdated:new Date().toISOString()},await x2(s),U(`Added marketplace source: ${i.name}`),{name:i.name,alreadyMaterialized:!1,resolvedSource:n}}async function Vvt(e){let t=await b2();if(!t[e])throw Error(`Marketplace '${e}' not found`);let n=t[e],r=S2(n.installLocation);if(r)throw Error(`Marketplace '${e}' is registered from the read-only seed directory (${r}) and will be re-registered on next startup. To stop using its plugins: claude plugin disable <plugin>@${e}`);delete t[e],await x2(t);let i=G(),a=y2(),o=Y(a,e);await i.rm(o,{recursive:!0,force:!0});let s=Y(a,`${e}.json`);await i.rm(s,{force:!0});for(let t of[`userSettings`,`projectSettings`,`localSettings`]){let n=Ir(t);if(!n)continue;let r=!1,i={};if(n.extraKnownMarketplaces?.[e]){let t={...n.extraKnownMarketplaces};t[e]=void 0,i.extraKnownMarketplaces=t,r=!0}if(n.enabledPlugins){let t=`@${e}`,a={...n.enabledPlugins},o=!1;for(let e in a)e.endsWith(t)&&(a[e]=void 0,o=!0);o&&(i.enabledPlugins=a,r=!0)}if(r){let n=li(t,i);n.error?(q(n.error),U(`Failed to clean up marketplace '${e}' from ${t} settings: ${n.error.message}`)):U(`Cleaned up marketplace '${e}' from ${t} settings`)}}let{orphanedPaths:c,removedPluginIds:l}=eyt(e);for(let e of c)await o2(e);for(let e of l)Bke(e),await tbe(e);U(`Removed marketplace source: ${e}`)}async function A2(e){let t=Y(e,`.claude-plugin`,`marketplace.json`);try{return await O2(t,Nr())}catch(e){if(e instanceof Dn)throw e;let t=Cn(e);if(t!==`ENOENT`&&t!==`ENOTDIR`)throw e}return await O2(e,Nr())}async function j2(e){let t=G(),n=v2();try{let r=kn(await t.readFile(n,{encoding:`utf-8`}))[e];return r?await A2(r.installLocation):null}catch(t){return xn(t)||U(`Failed to read cached marketplace ${e}: ${H(t)}`,{level:`warn`}),null}}async function Hvt(e){let{name:t,marketplace:n}=Zg(e);if(!t||!n)return null;let r=G(),i=v2();try{let e=kn(await r.readFile(i,{encoding:`utf-8`}))[n];if(!e)return null;let a=await j2(n);if(!a)return null;let o=a.plugins.find(e=>e.name===t);return o?{entry:o,marketplaceInstallLocation:e.installLocation}:null}catch{return null}}async function M2(e){let t=await Hvt(e);if(t)return t;let{name:n,marketplace:r}=Zg(e);if(!n||!r)return null;try{let e=(await b2())[r];if(!e)return null;let t=(await P2(r)).plugins.find(e=>e.name===n);return t?{entry:t,marketplaceInstallLocation:e.installLocation}:null}catch(t){return U(`Could not find plugin ${e}: ${H(t)}`,{level:`debug`}),null}}async function Uvt(){let e=await b2();for(let[t,n]of Object.entries(e)){if(S2(n.installLocation)){U(`Skipping seed-managed marketplace '${t}' in bulk refresh`);continue}if(n.source.source!==`settings`){if(t===`claude-plugins-official`&&await g2(n.installLocation,y2())!==null){e[t].lastUpdated=new Date().toISOString();continue}try{let{cachePath:r}=await k2(n.source);e[t].lastUpdated=new Date().toISOString(),e[t].installLocation=r}catch(e){U(`Failed to refresh marketplace ${t}: ${H(e)}`,{level:`error`})}}}await x2(e)}async function Wvt(e,t,n){let r=await b2(),i=r[e];if(!i)throw Error(`Marketplace '${e}' not found. Available marketplaces: ${Object.keys(r).join(`, `)}`);if(P2.cache?.delete?.(e),i.source.source===`settings`){U(`Skipping refresh for settings-sourced marketplace '${e}' — no upstream`);return}try{let a=i.installLocation,o=i.source,s=S2(a);if(s)throw Error(`Marketplace '${e}' is seed-managed (${s}) and its content is controlled by the seed image. To update: ask your admin to update the seed.`);if(!di(o)){let t=el(y2()),n=el(a);if(n!==t&&!n.startsWith(t+tl))throw Error(`Marketplace '${e}' has a corrupted installLocation (${a}) — expected a path inside ${t}. This can happen after cross-platform path writes or manual edits to known_marketplaces.json. Run: claude plugin marketplace remove "${e}" and re-add it.`)}if(e===`claude-plugins-official`){if(await g2(a,y2())!==null){r[e]={...i,lastUpdated:new Date().toISOString()},await x2(r);return}U(`Official marketplace GCS failed; falling back to git`,{level:`warn`})}if(o.source===`github`||o.source===`git`){if(o.source===`github`){let e=`git@github.com:${o.repo}.git`,r=`https://github.com/${o.repo}.git`;if(m(process.env.CLAUDE_CODE_REMOTE))await E2(r,a,o.ref,o.sparsePaths,t,n);else{let i=await Mvt(),s=i?e:r,c=i?r:e;try{await E2(s,a,o.ref,o.sparsePaths,t,n)}catch{U(`Marketplace refresh failed with ${i?`SSH`:`HTTPS`} for ${o.repo}, falling back to ${i?`HTTPS`:`SSH`}`,{level:`info`}),await E2(c,a,o.ref,o.sparsePaths,t,n)}}}else await E2(o.url,a,o.ref,o.sparsePaths,t,n);try{await A2(a)}catch{let t=o.source===`github`?o.repo:D2(o.url);throw Error(`The marketplace.json file is no longer present in this repository.\n\n${e===`claude-code-plugins`?`We've deprecated "claude-code-plugins" in favor of "claude-plugins-official".`:`This marketplace may have been deprecated or moved to a new location.`}\nSource: ${t}\n\nYou can remove this marketplace with: claude plugin marketplace remove "${e}"`)}}else if(o.source===`url`)await Rvt(o.url,a,o.headers,t);else if(di(o))T2(t,`Validating local marketplace`),await A2(a);else throw Error(`Unsupported marketplace source type for refresh`);r[e].lastUpdated=new Date().toISOString(),await x2(r),U(`Successfully refreshed marketplace: ${e}`)}catch(t){let n=t instanceof Error?t.message:String(t);throw U(`Failed to refresh marketplace ${e}: ${n}`,{level:`error`}),Error(`Failed to refresh marketplace '${e}': ${n}`)}}async function Gvt(e,t){let n=await b2(),r=n[e];if(!r)throw Error(`Marketplace '${e}' not found. Available marketplaces: ${Object.keys(n).join(`, `)}`);let i=S2(r.installLocation);if(i)throw Error(`Marketplace '${e}' is seed-managed (${i}) and auto-update is always disabled for seed content. To update: ask your admin to update the seed.`);if(r.autoUpdate===t)return;n[e]={...r,autoUpdate:t},await x2(n);let a=wvt(e);if(a){let n=Ir(a)?.extraKnownMarketplaces?.[e];n&&Tvt(e,{source:n.source,autoUpdate:t},a)}U(`Set autoUpdate=${t} for marketplace: ${e}`)}var N2,Kvt,P2,F2=n((()=>{de(),Ho(),d(),W(),h(),On(),zi(),Bn(),Mi(),Qi(),Vr(),Yn(),Xg(),l2(),s_(),K2(),h2(),i_(),xvt(),I_(),$g(),oT(),si(),N2={GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``},Kvt=120*1e3,P2=u(async e=>{let t=await b2(),n=t[e];if(!n)throw Error(`Marketplace '${e}' not found in configuration. Available marketplaces: ${Object.keys(t).join(`, `)}`);if(di(n.source)&&!Yc(n.source.path))throw Error(`Marketplace "${e}" has a relative source path (${n.source.path}) in known_marketplaces.json — this is stale state from an older Work Mate version. Run 'claude marketplace remove ${e}' and re-add it from the original project directory.`);try{return await A2(n.installLocation)}catch(t){U(`Cache corrupted or missing for marketplace ${e}, re-fetching from source: ${H(t)}`,{level:`warn`})}let r;try{({marketplace:r}=await k2(n.source))}catch(t){throw Error(`Failed to load marketplace "${e}" from source (${n.source.source}): ${H(t)}`)}return t[e].lastUpdated=new Date().toISOString(),await x2(t),r})}));function I2(){return Y(M_(),`installed_plugins.json`)}function qvt(){return Y(M_(),`installed_plugins_v2.json`)}function Jvt(){if(U2)return;let e=G(),t=I2(),n=qvt();try{try{e.renameSync(n,t),U(`Renamed installed_plugins_v2.json to installed_plugins.json`),Yvt(z2()),U2=!0;return}catch(e){if(!xn(e))throw e}let r;try{r=e.readFileSync(t,{encoding:`utf-8`})}catch(e){if(!xn(e))throw e;U2=!0;return}let i=kn(r);if((typeof i?.version==`number`?i.version:1)===1){let e=Jr().parse(i),n=R2(e);An(t,V(n,null,2),{encoding:`utf-8`,flush:!0}),U(`Converted installed_plugins.json from V1 to V2 format (${Object.keys(e.plugins).length} plugins)`),Yvt(n)}U2=!0}catch(e){U(`Failed to migrate plugin files: ${H(e)}`,{level:`error`}),q(jn(e)),U2=!0}}function Yvt(e){let t=G(),n=$2();try{let r=new Set;for(let t of Object.values(e.plugins))for(let e of t)r.add(e.installPath);let i=t.readdirSync(n);for(let e of i){if(!e.isDirectory())continue;let i=e.name,a=Y(n,i);t.readdirSync(a).some(e=>{if(!e.isDirectory())return!1;let n=Y(a,e.name);return t.readdirSync(n).some(e=>e.isDirectory())})||r.has(a)||(t.rmSync(a,{recursive:!0,force:!0}),U(`Cleaned up legacy cache directory: ${i}`))}}catch(e){U(`Failed to clean up legacy cache: ${H(e)}`,{level:`warn`})}}function L2(){let e=G(),t=I2(),n;try{n=e.readFileSync(t,{encoding:`utf-8`})}catch(e){if(xn(e))return null;throw e}let r=kn(n);return{version:typeof r?.version==`number`?r.version:1,data:r}}function R2(e){let t={};for(let[n,r]of Object.entries(e.plugins))t[n]=[{scope:`user`,installPath:t4(n,r.version),version:r.version,installedAt:r.installedAt,lastUpdated:r.lastUpdated,gitCommitSha:r.gitCommitSha}];return{version:2,plugins:t}}function z2(){if(W2!==null)return W2;let e=I2();try{let t=L2();if(t){if(t.version===2){let n=oi().parse(t.data);return W2=n,U(`Loaded ${Object.keys(n.plugins).length} installed plugins from ${e}`),n}let n=Jr().parse(t.data),r=R2(n);return W2=r,U(`Loaded and converted ${Object.keys(n.plugins).length} plugins from V1 format`),r}return U(`installed_plugins.json doesn't exist, returning empty V2 object`),W2={version:2,plugins:{}},W2}catch(e){return U(`Failed to load installed_plugins.json: ${H(e)}. Starting with empty state.`,{level:`error`}),q(jn(e)),W2={version:2,plugins:{}},W2}}function B2(e){let t=G(),n=I2();try{t.mkdirSync(M_()),An(n,V(e,null,2),{encoding:`utf-8`,flush:!0}),W2=e,U(`Saved ${Object.keys(e.plugins).length} installed plugins to ${n}`)}catch(e){throw H(e),q(jn(e)),e}}function Xvt(e,t,n){let r=V2(),i=r.plugins[e];i&&(r.plugins[e]=i.filter(e=>!(e.scope===t&&e.projectPath===n)),r.plugins[e].length===0&&delete r.plugins[e],B2(r),U(`Removed installation for ${e} at scope ${t}`))}function Zvt(){return G2===null&&(G2=z2()),G2}function V2(){try{let e=L2();return e?e.version===2?oi().parse(e.data):R2(Jr().parse(e.data)):{version:2,plugins:{}}}catch(e){return U(`Failed to load installed plugins from disk: ${H(e)}`,{level:`error`}),{version:2,plugins:{}}}}function Qvt(e,t,n,r,i,a){let o=V2(),s=o.plugins[e];if(!s){U(`Cannot update ${e} on disk: plugin not found in installed plugins`);return}let c=s.find(e=>e.scope===t&&e.projectPath===n);c?(c.installPath=r,c.version=i,c.lastUpdated=new Date().toISOString(),a!==void 0&&(c.gitCommitSha=a),An(I2(),V(o,null,2),{encoding:`utf-8`,flush:!0}),W2=null,U(`Updated ${e} on disk to version ${i} at ${r}`)):U(`Cannot update ${e} on disk: no installation for scope ${t}`)}async function $vt(){Jvt();try{await oyt()}catch(e){q(e)}let e=Zvt();U(`Initialized versioned plugins system with ${Object.keys(e.plugins).length} plugins`)}function eyt(e){if(!e)return{orphanedPaths:[],removedPluginIds:[]};let t=V2(),n=`@${e}`,r=new Set,i=[];for(let e of Object.keys(t.plugins))if(e.endsWith(n)){for(let n of t.plugins[e]??[])n.installPath&&r.add(n.installPath);delete t.plugins[e],i.push(e),U(`Removed installed plugin for marketplace removal: ${e}`)}return i.length>0&&B2(t),{orphanedPaths:Array.from(r),removedPluginIds:i}}function tyt(e){return e.scope===`user`||e.scope===`managed`||e.projectPath===Xt()}function nyt(e){let t=z2().plugins[e];return!t||t.length===0||!t.some(tyt)?!1:zr().enabledPlugins?.[e]!==void 0}function ryt(e){let t=z2().plugins[e];return!t||t.length===0||!t.some(e=>e.scope===`user`||e.scope===`managed`)?!1:zr().enabledPlugins?.[e]!==void 0}function iyt(e,t,n=`user`,r){let i=V2(),a={scope:n,installPath:t.installPath,version:t.version,installedAt:t.installedAt,lastUpdated:t.lastUpdated,gitCommitSha:t.gitCommitSha,...r&&{projectPath:r}},o=i.plugins[e]||[],s=o.findIndex(e=>e.scope===n&&e.projectPath===r),c=s>=0;c?o[s]=a:o.push(a),i.plugins[e]=o,B2(i),U(`${c?`Updated`:`Added`} installed plugin: ${e} (scope: ${n})`)}async function H2(e){return await _ie(e)??void 0}function ayt(e,t){let n=G(),r=Y(e,`.claude-plugin`,`plugin.json`);try{return kn(n.readFileSync(r,{encoding:`utf-8`})).version||`unknown`}catch{return U(`Could not read version from manifest for ${t}`),`unknown`}}async function oyt(){let e=zr().enabledPlugins||{};if(Object.keys(e).length===0)return;let t=L2(),n=t!==null;if(n&&t?.version===2&&t){let n=oi().safeParse(t.data);if(n?.success){let t=n.data.plugins;if(Object.keys(e).filter(e=>e.includes(`@`)).every(e=>{let n=t[e];return n&&n.length>0})){U(`All plugins already exist, skipping migration`);return}}}U(n?`Syncing installed_plugins.json with enabledPlugins from all settings.json files`:`Creating installed_plugins.json from settings.json files`);let r=new Date().toISOString(),i=yn(),a=new Map;for(let e of[`userSettings`,`projectSettings`,`localSettings`]){let t=Ir(e)?.enabledPlugins||{};for(let n of Object.keys(t)){if(!n.includes(`@`))continue;let t=Dye(e);a.set(n,{scope:t,projectPath:t===`user`?void 0:i})}}let o={};n&&(o={...z2().plugins});let s=0,c=0;for(let[e,t]of a){let n=o[e];if(n&&n.length>0){let i=n[0];i&&(i.scope!==t.scope||i.projectPath!==t.projectPath)&&(i.scope=t.scope,t.projectPath?i.projectPath=t.projectPath:delete i.projectPath,i.lastUpdated=r,s++,U(`Updated ${e} scope to ${t.scope} (settings.json is source of truth)`))}else{let{name:n,marketplace:i}=Zg(e);if(!n||!i)continue;try{U(`Looking up plugin ${e} in marketplace ${i}`);let a=await M2(e);if(!a){U(`Plugin ${e} not found in any marketplace, skipping`);continue}let{entry:s,marketplaceInstallLocation:l}=a,u,d=`unknown`,f;if(typeof s.source==`string`)u=Y(l,s.source),d=ayt(u,e),f=await H2(u);else{let t=Y($2(),n.replace(/[^a-zA-Z0-9-_]/g,`-`)),r;try{r=(await G().readdir(t)).map(e=>typeof e==`string`?e:e.name)}catch(t){if(!xn(t))throw t;U(`External plugin ${e} not in cache, skipping`);continue}u=t,r.includes(`.claude-plugin`)&&(d=ayt(t,e)),f=await H2(t)}d===`unknown`&&s.version&&(d=s.version),d===`unknown`&&f&&(d=f.substring(0,12)),o[e]=[{scope:t.scope,installPath:t4(e,d),version:d,installedAt:r,lastUpdated:r,gitCommitSha:f,...t.projectPath&&{projectPath:t.projectPath}}],c++,U(`Added ${e} with scope ${t.scope}`)}catch(t){U(`Failed to add plugin ${e}: ${t}`)}}}(!n||s>0||c>0)&&(B2({version:2,plugins:o}),U(`Sync completed: ${c} added, ${s} updated in installed_plugins.json`))}var U2,W2,G2,K2=n((()=>{W(),On(),Bn(),Qi(),Yn(),I_(),si(),Wt(),vn(),Di(),Vr(),F2(),$g(),d4(),U2=!1,W2=null,G2=null}));function q2(){let e=Ir(`policySettings`)?.enabledPlugins;if(!e)return null;let t=new Set;for(let[n,r]of Object.entries(e)){if(typeof r!=`boolean`||!n.includes(`@`))continue;let e=n.split(`@`)[0];e&&t.add(e)}return t.size>0?t:null}var J2=n((()=>{Vr()}));async function Y2(e,t,n,r,i,a){if(n?.version)return U(`Using manifest version for ${e}: ${n.version}`),n.version;if(i)return U(`Using provided version for ${e}: ${i}`),i;if(a){let n=a.substring(0,12);if(typeof t==`object`&&t.source===`git-subdir`){let r=t.path.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``),i=`${n}-${vl(`sha256`).update(r).digest(`hex`).substring(0,8)}`;return U(`Using git-subdir SHA+path version for ${e}: ${i} (path=${r})`),i}return U(`Using pre-resolved git SHA for ${e}: ${n}`),n}if(r){let t=await syt(r);if(t){let n=t.substring(0,12);return U(`Using git SHA for ${e}: ${n}`),n}}return U(`No version found for ${e}, using 'unknown'`),`unknown`}function syt(e){return _ie(e)}var X2=n((()=>{W(),Di()}));function cyt(){return new Date().toISOString()}function Z2(e,t){let n=el(e,t),r=el(e)+tl;if(!n.startsWith(r)&&n!==el(e))throw Error(`Path traversal detected: "${t}" would escape the base directory`);return n}async function lyt(e,t,n=`user`,r,i){let a=await a4(typeof t.source==`string`&&i?i:t.source,{manifest:t}),o=i||a.path,s=a.gitCommitSha??await H2(o),c=cyt(),l=await Y2(e,t.source,a.manifest,o,t.version,a.gitCommitSha),u=t4(e,l),d=a.path;if(a.path!==u){await G().mkdir(qc(u)),await Ml(u,{recursive:!0,force:!0});let e=a.path.endsWith(tl)?a.path:a.path+tl;if(u.startsWith(e)){let e=Y(qc(a.path),`.claude-plugin-temp-${Date.now()}-${yl(4).toString(`hex`)}`);await jl(a.path,e),await G().mkdir(qc(u)),await jl(e,u)}else await jl(a.path,u);d=u}if(t2()){let t=n4(e,l);await U_t(d,t),d=t}return iyt(e,{version:l,installedAt:c,lastUpdated:c,installPath:d,gitCommitSha:s},n,r),d}function Q2(e){switch(e.reason){case`cycle`:return`Dependency cycle: ${e.chain.join(` → `)}`;case`cross-marketplace`:{let t=Zg(e.dependency).marketplace,n=t?`marketplace "${t}"`:`a different marketplace`,r=t?` Add "${t}" to allowCrossMarketplaceDependenciesOn in the ROOT marketplace's marketplace.json (the marketplace of the plugin you're installing — only its allowlist applies; no transitive trust).`:``;return`Dependency "${e.dependency}" (required by ${e.requiredBy}) is in ${n}, which is not in the allowlist — cross-marketplace dependencies are blocked by default. Install it manually first.${r}`}case`not-found`:{let{marketplace:t}=Zg(e.missing);return t?`Dependency "${e.missing}" (required by ${e.requiredBy}) not found. Is the "${t}" marketplace added?`:`Dependency "${e.missing}" (required by ${e.requiredBy}) not found in any configured marketplace`}}}async function uyt({pluginId:e,entry:t,scope:n,marketplaceInstallLocation:r}){let i=Eye(n);if(QB(e))return{ok:!1,reason:`blocked-by-policy`,pluginName:t.name};let a=new Map;if(ure(t.source)&&!r)return{ok:!1,reason:`local-source-no-location`,pluginName:t.name};r&&a.set(e,{entry:t,marketplaceInstallLocation:r});let o=Zg(e).marketplace,s=new Set((o?(await j2(o))?.allowCrossMarketplaceDependenciesOn:void 0)??[]),c=await Aye(e,async n=>{if(a.has(n))return a.get(n).entry;if(n===e)return t;let r=await M2(n);return r&&a.set(n,r),r?.entry??null},Nye(i),s);if(!c.ok)return{ok:!1,reason:`resolution-failed`,resolution:c};for(let n of c.closure)if(n!==e&&QB(n))return{ok:!1,reason:`dependency-blocked-by-policy`,pluginName:t.name,blockedDependency:n};let l={};for(let e of c.closure)l[e]=!0;let{error:u}=li(i,{enabledPlugins:{...Ir(i)?.enabledPlugins,...l}});if(u)return{ok:!1,reason:`settings-write-failed`,message:u.message};let d=n===`user`?void 0:yn();for(let r of c.closure){let i=a.get(r);if(!i&&r===e){let e=(await M2(r))?.marketplaceInstallLocation;e&&(i={entry:t,marketplaceInstallLocation:e})}if(!i)continue;let o,{source:s}=i.entry;ure(s)&&(o=Z2(i.marketplaceInstallLocation,s)),await lyt(r,i.entry,n,d,o)}q_t();let f=Pye(c.closure.filter(t=>t!==e));return{ok:!0,closure:c.closure,depNote:f}}async function dyt({pluginId:e,entry:t,marketplaceName:n,scope:r=`user`,trigger:i=`user`}){try{let a=(await M2(e))?.marketplaceInstallLocation,o=await uyt({pluginId:e,entry:t,scope:r,marketplaceInstallLocation:a});if(!o.ok){let e=o;switch(e.reason){case`local-source-no-location`:return{success:!1,error:`Cannot install local plugin "${e.pluginName}" without marketplace install location`};case`settings-write-failed`:return{success:!1,error:`Failed to update settings: ${e.message}`};case`resolution-failed`:return{success:!1,error:Q2(e.resolution)};case`blocked-by-policy`:return{success:!1,error:`Plugin "${e.pluginName}" is blocked by your organization's policy and cannot be installed`};case`dependency-blocked-by-policy`:return{success:!1,error:`Cannot install "${e.pluginName}": dependency "${e.blockedDependency}" is blocked by your organization's policy`}}}return J(`tengu_plugin_installed`,{_PROTO_plugin_name:t.name,_PROTO_marketplace_name:n,plugin_id:Qg(n)?e:`third-party`,trigger:i,install_source:i===`hint`?`ui-suggestion`:`ui-discover`,...pJ(t.name,n,q2()),...t.version&&{version:t.version}}),{success:!0,message:`✓ Installed ${t.name}${o.depNote}. Run /reload-plugins to activate.`}}catch(e){let t=e instanceof Error?e.message:String(e);return q(jn(e)),{success:!1,error:`Failed to install: ${t}`}}}var fyt=n((()=>{Da(),vn(),On(),Bn(),Qi(),Vr(),hJ(),l2(),t_(),K2(),J2(),F2(),$g(),d4(),$B(),X2(),si(),a2()}));function $2(){return Y(M_(),`cache`)}function e4(e,t,n){let{name:r,marketplace:i}=Zg(t);return Y(e,`cache`,(i||`unknown`).replace(/[^a-zA-Z0-9\-_]/g,`-`),(r||t).replace(/[^a-zA-Z0-9\-_]/g,`-`),n.replace(/[^a-zA-Z0-9\-_.]/g,`-`))}function t4(e,t){return e4(M_(),e,t)}function n4(e,t){return`${t4(e,t)}.zip`}async function pyt(e,t){for(let n of N_()){let r=e4(n,e,t);try{if((await kl(r)).length>0)return r}catch{}}return null}async function myt(e){for(let t of N_()){let n=qc(e4(t,e,`_`));try{let e=await kl(n);if(e.length!==1)continue;let t=Y(n,e[0]);if((await kl(t)).length>0)return t}catch{}}return null}async function r4(e,t){await G().mkdir(t);let n=await kl(e,{withFileTypes:!0});for(let r of n){let n=Y(e,r.name),i=Y(t,r.name);if(r.isDirectory())await r4(n,i);else if(r.isFile())await wl(n,i);else if(r.isSymbolicLink()){let r=await due(n),a;try{a=await Al(n)}catch{await Pl(r,i);continue}let o;try{o=await Al(e)}catch{o=e}let s=o.endsWith(tl)?o:o+tl;if(a.startsWith(s)||a===o){let e=Y(t,$c(o,a));await Pl($c(qc(i),e),i)}else await Pl(a,i)}}}async function i4(e,t,n,r,i){let a=t2(),o=t4(t,n),s=n4(t,n);if(a){if(await Gr(s))return U(`Plugin ${t} version ${n} already cached at ${s}`),s}else if(await Gr(o)){if((await kl(o)).length>0)return U(`Plugin ${t} version ${n} already cached at ${o}`),o;U(`Removing empty cache directory for ${t} at ${o}`),await fue(o)}let c=await pyt(t,n);if(c)return U(`Using seed cache for ${t}@${n} at ${c}`),c;if(await G().mkdir(qc(o)),r&&typeof r.source==`string`&&i){let e=Z2(i,r.source);U(`Copying source directory ${r.source} for plugin ${t}`);try{await r4(e,o)}catch(t){throw xn(t)&&xne(t)===e?Error(`Plugin source directory not found: ${e} (from entry.source: ${r.source})`):t}}else U(`Copying plugin ${t} to versioned cache (fallback to full copy)`),await r4(e,o);if(await Ml(Y(o,`.git`),{recursive:!0,force:!0}),(await kl(o)).length===0)throw Error(`Failed to copy plugin ${t} to versioned cache: destination is empty after copy`);return a?(await U_t(o,s),U(`Successfully cached plugin ${t} as ZIP at ${s}`),s):(U(`Successfully cached plugin ${t} at ${o}`),o)}function hyt(e){try{let t=new URL(e);if(![`https:`,`http:`,`file:`].includes(t.protocol)&&!/^git@[a-zA-Z0-9.-]+:/.test(e))throw Error(`Invalid git URL protocol: ${t.protocol}. Only HTTPS, HTTP, file:// and SSH (git@) URLs are supported.`);return e}catch{if(/^git@[a-zA-Z0-9.-]+:/.test(e))return e;throw Error(`Invalid git URL: ${e}`)}}async function gyt(e,t,n={}){let r=Y(M_(),`npm-cache`);await G().mkdir(r);let i=n.version?`${e}@${n.version}`:e,a=Y(r,`node_modules`,e);if(!await Gr(a)){U(`Installing npm package ${i} to cache`);let e=[`install`,i,`--prefix`,r];n.registry&&e.push(`--registry`,n.registry);let t=await Bi(`npm`,e,{useCwd:!1});if(t.code!==0)throw Error(`Failed to install npm package: ${t.stderr}`)}await r4(a,t),U(`Copied npm package ${e} from cache to ${t}`)}async function _yt(e,t,n,r){let i=[`clone`,`--depth`,`1`,`--recurse-submodules`,`--shallow-submodules`];n&&i.push(`--branch`,n),r&&i.push(`--no-checkout`),i.push(e,t);let a=performance.now(),o=await Bi(Pi(),i);if(o.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(o.stderr)),Error(`Failed to clone repository: ${o.stderr}`);if(r){if((await Li(Pi(),[`fetch`,`--depth`,`1`,`origin`,r],{cwd:t})).code!==0){U(`Shallow fetch of SHA ${r} failed, falling back to unshallow fetch`);let n=await Li(Pi(),[`fetch`,`--unshallow`],{cwd:t});if(n.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(n.stderr)),Error(`Failed to fetch commit ${r}: ${n.stderr}`)}let n=await Li(Pi(),[`checkout`,r],{cwd:t});if(n.code!==0)throw a_(`plugin_clone`,e,`failure`,performance.now()-a,o_(n.stderr)),Error(`Failed to checkout commit ${r}: ${n.stderr}`)}a_(`plugin_clone`,e,`success`,performance.now()-a)}async function vyt(e,t,n,r){let i=hyt(e);await _yt(i,t,n,r),U(`Cloned repository from ${i}${n?` (ref: ${n})`:``} to ${t}`)}async function yyt(e,t,n,r){if(!/^[a-zA-Z0-9-_.]+\/[a-zA-Z0-9-_.]+$/.test(e))throw Error(`Invalid GitHub repository format: ${e}. Expected format: owner/repo`);return vyt(m(process.env.CLAUDE_CODE_REMOTE)?`https://github.com/${e}.git`:`git@github.com:${e}.git`,t,n,r)}function byt(e){return/^[a-zA-Z0-9-_.]+\/[a-zA-Z0-9-_.]+$/.test(e)?m(process.env.CLAUDE_CODE_REMOTE)?`https://github.com/${e}.git`:`git@github.com:${e}.git`:hyt(e)}async function xyt(e,t,n,r,i){if(!await c_())throw Error(`git-subdir plugin source requires git to be installed and on PATH. Install git (version 2.25 or later for sparse-checkout cone mode) and try again.`);let a=byt(e),o=`${t}.clone`,s=[`clone`,`--depth`,`1`,`--filter=tree:0`,`--no-checkout`];r&&s.push(`--branch`,r),s.push(a,o);let c=await Bi(Pi(),s);if(c.code!==0)throw Error(`Failed to clone repository for git-subdir source: ${c.stderr}`);try{let e=await Li(Pi(),[`sparse-checkout`,`set`,`--cone`,`--`,n],{cwd:o});if(e.code!==0)throw Error(`git sparse-checkout set failed (git >= 2.25 required for cone mode): ${e.stderr}`);let s;if(i){if((await Li(Pi(),[`fetch`,`--depth`,`1`,`origin`,i],{cwd:o})).code!==0){U(`Shallow fetch of SHA ${i} failed for git-subdir, falling back to unshallow fetch`);let e=await Li(Pi(),[`fetch`,`--unshallow`],{cwd:o});if(e.code!==0)throw Error(`Failed to fetch commit ${i}: ${e.stderr}`)}let e=await Li(Pi(),[`checkout`,i],{cwd:o});if(e.code!==0)throw Error(`Failed to checkout commit ${i}: ${e.stderr}`);s=i}else{let[e,t]=await Promise.all([Li(Pi(),[`checkout`,`HEAD`],{cwd:o}),Li(Pi(),[`rev-parse`,`HEAD`],{cwd:o})]);if(e.code!==0)throw Error(`git checkout after sparse-checkout failed: ${e.stderr}`);t.code===0&&(s=t.stdout.trim())}let c=Z2(o,n);try{await jl(c,t)}catch(e){throw xn(e)?Error(`Subdirectory '${n}' not found in repository ${a}${r?` (ref: ${r})`:``}. Check that the path is correct and exists at the specified ref/sha.`):e}return U(`Extracted subdir ${n} from ${a}${r?` ref=${r}`:``}${s?` sha=${s}`:``} to ${t}`),s}finally{await Ml(o,{recursive:!0,force:!0})}}async function Syt(e,t){if(!await Gr(e))throw Error(`Source path does not exist: ${e}`);await r4(e,t),await Ml(Y(t,`.git`),{recursive:!0,force:!0})}function Cyt(e){let t=Date.now(),n=Math.random().toString(36).substring(2,8),r;if(typeof e==`string`)r=`local`;else switch(e.source){case`npm`:r=`npm`;break;case`pip`:r=`pip`;break;case`github`:r=`github`;break;case`url`:r=`git`;break;case`git-subdir`:r=`subdir`;break;default:r=`unknown`}return`temp_${r}_${t}_${n}`}async function a4(e,t){let n=$2();await G().mkdir(n);let r=Cyt(e),i=Y(n,r),a=!1,o;try{if(U(`Caching plugin from source: ${V(e)} to temporary path ${i}`),a=!0,typeof e==`string`)await Syt(e,i);else switch(e.source){case`npm`:await gyt(e.package,i,{registry:e.registry,version:e.version});break;case`github`:await yyt(e.repo,i,e.ref,e.sha);break;case`url`:await vyt(e.url,i,e.ref,e.sha);break;case`git-subdir`:o=await xyt(e.url,i,e.path,e.ref,e.sha);break;case`pip`:throw Error(`Python package plugins are not yet supported`);default:throw Error(`Unsupported plugin source type`)}}catch(e){if(a&&await Gr(i)){U(`Cleaning up failed installation at ${i}`);try{await Ml(i,{recursive:!0,force:!0})}catch(e){U(`Failed to clean up installation: ${e}`,{level:`error`})}}throw e}let s=Y(i,`.claude-plugin`,`plugin.json`),c=Y(i,`plugin.json`),l;if(await Gr(s))try{let e=kn(await Ol(s,{encoding:`utf-8`})),t=Hr().safeParse(e);if(t.success)l=t.data;else{let e=t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw U(`Invalid manifest at ${s}: ${e}`,{level:`error`}),Error(`Plugin has an invalid manifest file at ${s}. Validation errors: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(`invalid manifest file`))throw e;let t=H(e);throw U(`Failed to parse manifest at ${s}: ${t}`,{level:`error`}),Error(`Plugin has a corrupt manifest file at ${s}. JSON parse error: ${t}`)}else if(await Gr(c))try{let e=kn(await Ol(c,{encoding:`utf-8`})),t=Hr().safeParse(e);if(t.success)l=t.data;else{let e=t.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw U(`Invalid legacy manifest at ${c}: ${e}`,{level:`error`}),Error(`Plugin has an invalid manifest file at ${c}. Validation errors: ${e}`)}}catch(e){if(e instanceof Error&&e.message.includes(`invalid manifest file`))throw e;let t=H(e);throw U(`Failed to parse legacy manifest at ${c}: ${t}`,{level:`error`}),Error(`Plugin has a corrupt manifest file at ${c}. JSON parse error: ${t}`)}else l=t?.manifest||{name:r,description:`Plugin cached from ${typeof e==`string`?e:e.source}`};let u=Y(n,l.name.replace(/[^a-zA-Z0-9-_]/g,`-`));return await Gr(u)&&(U(`Removing old cached version at ${u}`),await Ml(u,{recursive:!0,force:!0})),await jl(i,u),U(`Successfully cached plugin ${l.name} to ${u}`),{path:u,manifest:l,...o&&{gitCommitSha:o}}}async function o4(e,t,n){if(!await Gr(e))return{name:t,description:`Plugin from ${n}`};try{let n=kn(await Ol(e,{encoding:`utf-8`})),r=Hr().safeParse(n);if(r.success)return r.data;let i=r.error.issues.map(e=>e.path.length>0?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `);throw U(`Plugin ${t} has an invalid manifest file at ${e}. Validation errors: ${i}`,{level:`error`}),Error(`Plugin ${t} has an invalid manifest file at ${e}.\n\nValidation errors: ${i}`)}catch(n){if(n instanceof Error&&n.message.includes(`invalid manifest file`))throw n;let r=H(n);throw U(`Plugin ${t} has a corrupt manifest file at ${e}. Parse error: ${r}`,{level:`error`}),Error(`Plugin ${t} has a corrupt manifest file at ${e}.\n\nJSON parse error: ${r}`)}}async function wyt(e,t){if(!await Gr(e))throw Error(`Hooks file not found at ${e} for plugin ${t}. If the manifest declares hooks, the file must exist.`);let n=kn(await Ol(e,{encoding:`utf-8`}));return Lre().parse(n).hooks}async function s4(e,t,n,r,i,a,o,s){let c=await Promise.all(e.map(async e=>{let n=Y(t,e);return{relPath:e,fullPath:n,exists:await Gr(n)}})),l=[];for(let{relPath:e,fullPath:t,exists:u}of c)u?l.push(t):(U(`${a} path ${e} ${o} not found at ${t} for ${n}`,{level:`warn`}),q(Error(`Plugin component file not found: ${t} for ${n}`)),s.push({type:`path-not-found`,source:r,plugin:n,path:t,component:i}));return l}async function Tyt(e,t,n,r,i=!0){let a=[],o=await o4(Y(e,`.claude-plugin`,`plugin.json`),r,t),s={name:o.name,manifest:o,path:e,source:t,repository:t,enabled:n},[c,l,u,d]=await Promise.all([!o.commands&&Gr(Y(e,`commands`)),!o.agents&&Gr(Y(e,`agents`)),!o.skills&&Gr(Y(e,`skills`)),!o.outputStyles&&Gr(Y(e,`output-styles`))]),f=Y(e,`commands`);if(c&&(s.commandsPath=f),o.commands){let n=Object.values(o.commands)[0];if(typeof o.commands==`object`&&!Array.isArray(o.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={},r=[],i=Object.entries(o.commands),c=await Promise.all(i.map(async([t,n])=>{if(!n||typeof n!=`object`)return{commandName:t,metadata:n,kind:`skip`};if(n.source){let r=Y(e,n.source);return{commandName:t,metadata:n,kind:`source`,fullPath:r,exists:await Gr(r)}}return n.content?{commandName:t,metadata:n,kind:`content`}:{commandName:t,metadata:n,kind:`skip`}}));for(let e of c)if(e.kind!==`skip`){if(e.kind===`content`){n[e.commandName]=e.metadata;continue}e.exists?(r.push(e.fullPath),n[e.commandName]=e.metadata):(U(`Command ${e.commandName} path ${e.metadata.source} specified in manifest but not found at ${e.fullPath} for ${o.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${e.fullPath} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:e.fullPath,component:`commands`}))}r.length>0&&(s.commandsPaths=r),Object.keys(n).length>0&&(s.commandsMetadata=n)}else{let n=Array.isArray(o.commands)?o.commands:[o.commands],r=await Promise.all(n.map(async t=>{if(typeof t!=`string`)return{cmdPath:t,kind:`invalid`};let n=Y(e,t);return{cmdPath:t,kind:`path`,fullPath:n,exists:await Gr(n)}})),i=[];for(let e of r){if(e.kind===`invalid`){U(`Unexpected command format in manifest for ${o.name}`,{level:`error`});continue}e.exists?i.push(e.fullPath):(U(`Command path ${e.cmdPath} specified in manifest but not found at ${e.fullPath} for ${o.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${e.fullPath} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:e.fullPath,component:`commands`}))}i.length>0&&(s.commandsPaths=i)}}let p=Y(e,`agents`);if(l&&(s.agentsPath=p),o.agents){let n=await s4(Array.isArray(o.agents)?o.agents:[o.agents],e,o.name,t,`agents`,`Agent`,`specified in manifest but`,a);n.length>0&&(s.agentsPaths=n)}let m=Y(e,`skills`);if(u&&(s.skillsPath=m),o.skills){let n=await s4(Array.isArray(o.skills)?o.skills:[o.skills],e,o.name,t,`skills`,`Skill`,`specified in manifest but`,a);n.length>0&&(s.skillsPaths=n)}let h=Y(e,`output-styles`);if(d&&(s.outputStylesPath=h),o.outputStyles){let n=await s4(Array.isArray(o.outputStyles)?o.outputStyles:[o.outputStyles],e,o.name,t,`output-styles`,`Output style`,`specified in manifest but`,a);n.length>0&&(s.outputStylesPaths=n)}let g,_=new Set,v=Y(e,`hooks`,`hooks.json`);if(await Gr(v))try{g=await wyt(v,o.name);try{_.add(await Al(v))}catch{_.add(v)}U(`Loaded hooks from standard location for plugin ${o.name}: ${v}`)}catch(e){let n=H(e);U(`Failed to load hooks for ${o.name}: ${n}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:v,reason:n})}if(o.hooks){let n=Array.isArray(o.hooks)?o.hooks:[o.hooks];for(let r of n)if(typeof r==`string`){let n=Y(e,r);if(!await Gr(n)){U(`Hooks file ${r} specified in manifest but not found at ${n} for ${o.name}`,{level:`error`}),q(Error(`Plugin component file not found: ${n} for ${o.name}`)),a.push({type:`path-not-found`,source:t,plugin:o.name,path:n,component:`hooks`});continue}let s;try{s=await Al(n)}catch{s=n}if(_.has(s)){if(U(`Skipping duplicate hooks file for plugin ${o.name}: ${r} (resolves to already-loaded file: ${s})`),i){let e=`Duplicate hooks file detected: ${r} resolves to already-loaded file ${s}. The standard hooks/hooks.json is loaded automatically, so manifest.hooks should only reference additional hook files.`;q(Error(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:e})}continue}try{let e=await wyt(n,o.name);try{g=Oyt(g,e),_.add(s),U(`Loaded and merged hooks from manifest for plugin ${o.name}: ${r}`)}catch(e){let i=H(e);U(`Failed to merge hooks from ${r} for ${o.name}: ${i}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:`Failed to merge: ${i}`})}}catch(e){let i=H(e);U(`Failed to load hooks from ${r} for ${o.name}: ${i}`,{level:`error`}),q(jn(e)),a.push({type:`hook-load-failed`,source:t,plugin:o.name,hookPath:n,reason:i})}}else typeof r==`object`&&(g=Oyt(g,r))}g&&(s.hooksConfig=g);let y=await Dyt(e,o);return y&&(s.settings=y),{plugin:s,errors:a}}function Eyt(e){let t=zyt().safeParse(e);if(!t.success)return;let n=t.data;if(Object.keys(n).length!==0)return n}async function Dyt(e,t){let n=Y(e,`settings.json`);try{let e=kn(await Ol(n,{encoding:`utf-8`}));if(Ryt(e)){let n=Eyt(e);if(n)return U(`Loaded settings from settings.json for plugin ${t.name}`),n}}catch(e){Mn(e)||U(`Failed to parse settings.json for plugin ${t.name}: ${e}`,{level:`warn`})}if(t.settings){let e=Eyt(t.settings);if(e)return U(`Loaded settings from manifest for plugin ${t.name}`),e}}function Oyt(e,t){if(!e)return t;let n={...e};for(let[e,r]of Object.entries(t))n[e]?n[e]=[...n[e]??[],...r]:n[e]=r;return n}async function kyt({cacheOnly:e}){let t=zr(),n={...Jg(),...t.enabledPlugins||{}},r=[],i=[],a=Object.entries(n).filter(([e,t])=>{if(!kre().safeParse(e).success||t===void 0)return!1;let{marketplace:n}=Zg(e);return n!==Kg}),o=await Evt(),s=u2(),c=cvt(),l=s!==null||c!==null&&c.length>0,u=new Set(a.map(([e])=>Zg(e).marketplace).filter(e=>!!e)),d=new Map;await Promise.all([...u].map(async e=>{d.set(e,await j2(e))}));let f=Zvt(),p=await Promise.allSettled(a.map(async([t,n])=>{let{name:r,marketplace:a}=Zg(t),c=o[a];if(!c&&l)return i.push({type:`marketplace-blocked-by-policy`,source:t,plugin:r,marketplace:a,blockedByBlocklist:s===null,allowedSources:(s??[]).map(e=>m2(e))}),null;if(c&&!p2(c.source)){let e=f2(c.source),n=u2()||[];return i.push({type:`marketplace-blocked-by-policy`,source:t,plugin:r,marketplace:a,blockedByBlocklist:e,allowedSources:e?[]:n.map(e=>m2(e))}),null}let u=null,p=d.get(a);if(p&&c){let e=p.plugins.find(e=>e.name===r);e&&(u={entry:e,marketplaceInstallLocation:c.installLocation})}else u=await Hvt(t);if(!u)return i.push({type:`plugin-not-found`,source:t,pluginId:r,marketplace:a}),null;let m=f.plugins[t]?.[0];return e?Ayt(u.entry,u.marketplaceInstallLocation,t,n===!0,i,m?.installPath):jyt(u.entry,u.marketplaceInstallLocation,t,n===!0,i,m?.version)}));for(let[e,t]of p.entries())if(t.status===`fulfilled`&&t.value)r.push(t.value);else if(t.status===`rejected`){let n=jn(t.reason);q(n);let r=a[e][0];i.push({type:`generic-error`,source:r,plugin:r.split(`@`)[0],error:n.message})}return{plugins:r,errors:i}}async function Ayt(e,t,n,r,i,a){let o;if(typeof e.source==`string`){let r;try{r=(await Nl(t)).isDirectory()?t:Y(t,`..`)}catch{return i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:t}),null}o=Y(r,e.source)}else{if(!a||!await Gr(a))return i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:a??`(not recorded)`}),null;o=a}if(t2()&&o.endsWith(`.zip`)){let t=Y(await L_t(),n.replace(/[^a-zA-Z0-9@\-_]/g,`-`));try{await H_t(o,t),o=t}catch(t){return U(`Failed to extract plugin ZIP ${o}: ${t}`,{level:`error`}),i.push({type:`plugin-cache-miss`,source:n,plugin:e.name,installPath:o}),null}}return Myt(e,n,r,i,o)}async function jyt(e,t,n,r,i,a){U(`Loading plugin ${e.name} from source: ${V(e.source)}`);let o;if(typeof e.source==`string`){let r=(await Nl(t)).isDirectory()?t:Y(t,`..`),a=Y(r,e.source);if(!await Gr(a)){let e=Error(`Plugin path not found: ${a}`);return U(`Plugin path not found: ${a}`,{level:`error`}),q(e),i.push({type:`generic-error`,source:n,error:`Plugin directory not found at path: ${a}. Check that the marketplace entry has the correct path.`}),null}try{let t=Y(a,`.claude-plugin`,`plugin.json`),i;try{i=await o4(t,e.name,e.source)}catch{}o=await i4(a,n,await Y2(n,e.source,i,r,e.version),e,r),U(`Resolved local plugin ${e.name} to versioned cache: ${o}`)}catch(t){let n=H(t);U(`Failed to copy plugin ${e.name} to versioned cache: ${n}. Using marketplace path.`,{level:`warn`}),o=a}}else try{let t=await Y2(n,e.source,void 0,void 0,a??e.version,`sha`in e.source?e.source.sha:void 0),r=t4(n,t),i=n4(n,t);if(t2()&&await Gr(i))U(`Using versioned cached plugin ZIP ${e.name} from ${i}`),o=i;else if(await Gr(r))U(`Using versioned cached plugin ${e.name} from ${r}`),o=r;else{let r=await pyt(n,t)??(t===`unknown`?await myt(n):null);if(r)o=r,U(`Using seed cache for external plugin ${e.name} at ${r}`);else{let r=await a4(e.source,{manifest:{name:e.name}}),i=t===`unknown`?await Y2(n,e.source,r.manifest,r.path,a??e.version,r.gitCommitSha):t;o=await i4(r.path,n,i,e,void 0),r.path!==o&&await Ml(r.path,{recursive:!0,force:!0})}}}catch(t){let r=H(t);return U(`Failed to cache plugin ${e.name}: ${r}`,{level:`error`}),q(jn(t)),i.push({type:`generic-error`,source:n,error:`Failed to download/cache plugin ${e.name}: ${r}`}),null}if(t2()&&o.endsWith(`.zip`)){let e=Y(await L_t(),n.replace(/[^a-zA-Z0-9@\-_]/g,`-`));try{await H_t(o,e),U(`Extracted plugin ZIP to session dir: ${e}`),o=e}catch(e){throw U(`Failed to extract plugin ZIP ${o}, deleting corrupt file: ${e}`),await Ml(o,{force:!0}).catch(()=>{}),e}}return Myt(e,n,r,i,o)}async function Myt(e,t,n,r,i){let a=[],o=await Gr(Y(i,`.claude-plugin`,`plugin.json`)),{plugin:s,errors:c}=await Tyt(i,t,n,e.name,e.strict??!0);if(a.push(...c),typeof e.source==`object`&&`sha`in e.source&&e.source.sha&&(s.sha=e.source.sha),!o){if(s.manifest={...e,id:void 0,source:void 0,strict:void 0},s.name=s.manifest.name,e.commands){let n=Object.values(e.commands)[0];if(typeof e.commands==`object`&&!Array.isArray(e.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={},r=[],o=Object.entries(e.commands),c=await Promise.all(o.map(async([e,t])=>{if(!t||typeof t!=`object`||!t.source)return{commandName:e,metadata:t,skip:!0};let n=Y(i,t.source);return{commandName:e,metadata:t,skip:!1,fullPath:n,exists:await Gr(n)}}));for(let i of c)i.skip||(i.exists?(r.push(i.fullPath),n[i.commandName]=i.metadata):(U(`Command ${i.commandName} path ${i.metadata.source} from marketplace entry not found at ${i.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i.fullPath,component:`commands`})));r.length>0&&(s.commandsPaths=r,s.commandsMetadata=n)}else{let n=Array.isArray(e.commands)?e.commands:[e.commands],r=await Promise.all(n.map(async e=>{if(typeof e!=`string`)return{cmdPath:e,kind:`invalid`};let t=Y(i,e);return{cmdPath:e,kind:`path`,fullPath:t,exists:await Gr(t)}})),o=[];for(let n of r){if(n.kind===`invalid`){U(`Unexpected command format in marketplace entry for ${e.name}`,{level:`error`});continue}n.exists?o.push(n.fullPath):(U(`Command path ${n.cmdPath} from marketplace entry not found at ${n.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${n.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:n.fullPath,component:`commands`}))}o.length>0&&(s.commandsPaths=o)}}if(e.agents){let n=await s4(Array.isArray(e.agents)?e.agents:[e.agents],i,e.name,t,`agents`,`Agent`,`from marketplace entry`,a);n.length>0&&(s.agentsPaths=n)}if(e.skills){U(`Processing ${Array.isArray(e.skills)?e.skills.length:1} skill paths for plugin ${e.name}`);let n=Array.isArray(e.skills)?e.skills:[e.skills],r=await Promise.all(n.map(async e=>{let t=Y(i,e);return{skillPath:e,fullPath:t,exists:await Gr(t)}})),o=[];for(let{skillPath:n,fullPath:i,exists:s}of r)U(`Checking skill path: ${n} -> ${i} (exists: ${s})`),s?o.push(i):(U(`Skill path ${n} from marketplace entry not found at ${i} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i,component:`skills`}));U(`Found ${o.length} valid skill paths for plugin ${e.name}, setting skillsPaths`),o.length>0&&(s.skillsPaths=o)}else U(`Plugin ${e.name} has no entry.skills defined`);if(e.outputStyles){let n=await s4(Array.isArray(e.outputStyles)?e.outputStyles:[e.outputStyles],i,e.name,t,`output-styles`,`Output style`,`from marketplace entry`,a);n.length>0&&(s.outputStylesPaths=n)}e.hooks&&(s.hooksConfig=e.hooks)}else if(!e.strict&&o&&(e.commands||e.agents||e.skills||e.hooks||e.outputStyles)){let n=Error(`Plugin ${e.name} has both plugin.json and marketplace manifest entries for commands/agents/skills/hooks/outputStyles. This is a conflict.`);return U(`Plugin ${e.name} has both plugin.json and marketplace manifest entries for commands/agents/skills/hooks/outputStyles. This is a conflict.`,{level:`error`}),q(n),r.push({type:`generic-error`,source:t,error:`Plugin ${e.name} has conflicting manifests: both plugin.json and marketplace entry specify components. Set strict: true in marketplace entry or remove component specs from one location.`}),null}else if(o){if(e.commands){let n=Object.values(e.commands)[0];if(typeof e.commands==`object`&&!Array.isArray(e.commands)&&n&&typeof n==`object`&&(`source`in n||`content`in n)){let n={...s.commandsMetadata||{}},r=[],o=Object.entries(e.commands),c=await Promise.all(o.map(async([e,t])=>{if(!t||typeof t!=`object`||!t.source)return{commandName:e,metadata:t,skip:!0};let n=Y(i,t.source);return{commandName:e,metadata:t,skip:!1,fullPath:n,exists:await Gr(n)}}));for(let i of c)i.skip||(i.exists?(r.push(i.fullPath),n[i.commandName]=i.metadata):(U(`Command ${i.commandName} path ${i.metadata.source} from marketplace entry not found at ${i.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${i.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:i.fullPath,component:`commands`})));r.length>0&&(s.commandsPaths=[...s.commandsPaths||[],...r],s.commandsMetadata=n)}else{let n=Array.isArray(e.commands)?e.commands:[e.commands],r=await Promise.all(n.map(async e=>{if(typeof e!=`string`)return{cmdPath:e,kind:`invalid`};let t=Y(i,e);return{cmdPath:e,kind:`path`,fullPath:t,exists:await Gr(t)}})),o=[];for(let n of r){if(n.kind===`invalid`){U(`Unexpected command format in marketplace entry for ${e.name}`,{level:`error`});continue}n.exists?o.push(n.fullPath):(U(`Command path ${n.cmdPath} from marketplace entry not found at ${n.fullPath} for ${e.name}`,{level:`warn`}),q(Error(`Plugin component file not found: ${n.fullPath} for ${e.name}`)),a.push({type:`path-not-found`,source:t,plugin:e.name,path:n.fullPath,component:`commands`}))}o.length>0&&(s.commandsPaths=[...s.commandsPaths||[],...o])}}if(e.agents){let n=await s4(Array.isArray(e.agents)?e.agents:[e.agents],i,e.name,t,`agents`,`Agent`,`from marketplace entry`,a);n.length>0&&(s.agentsPaths=[...s.agentsPaths||[],...n])}if(e.skills){let n=await s4(Array.isArray(e.skills)?e.skills:[e.skills],i,e.name,t,`skills`,`Skill`,`from marketplace entry`,a);n.length>0&&(s.skillsPaths=[...s.skillsPaths||[],...n])}if(e.outputStyles){let n=await s4(Array.isArray(e.outputStyles)?e.outputStyles:[e.outputStyles],i,e.name,t,`output-styles`,`Output style`,`from marketplace entry`,a);n.length>0&&(s.outputStylesPaths=[...s.outputStylesPaths||[],...n])}e.hooks&&(s.hooksConfig={...s.hooksConfig||{},...e.hooks})}return r.push(...a),s}async function Nyt(e){if(e.length===0)return{plugins:[],errors:[]};let t=[],n=[];for(let[r,i]of e.entries())try{let e=el(i);if(!await Gr(e)){U(`Plugin path does not exist: ${e}, skipping`,{level:`warn`}),n.push({type:`path-not-found`,source:`inline[${r}]`,path:e,component:`commands`});continue}let a=Kc(e),{plugin:o,errors:s}=await Tyt(e,`${a}@inline`,!0,a);o.source=`${o.name}@inline`,o.repository=`${o.name}@inline`,t.push(o),n.push(...s),U(`Loaded inline plugin from path: ${o.name}`)}catch(e){let t=H(e);U(`Failed to load session plugin from ${i}: ${t}`,{level:`warn`}),n.push({type:`generic-error`,source:`inline[${r}]`,error:`Failed to load plugin: ${t}`})}return t.length>0&&U(`Loaded ${t.length} session-only plugins from --plugin-dir`),{plugins:t,errors:n}}function Pyt(e){let t=[],n=e.managedNames,r=e.session.filter(e=>n?.has(e.name)?(U(`Plugin "${e.name}" from --plugin-dir is blocked by managed settings`,{level:`warn`}),t.push({type:`generic-error`,source:e.source,plugin:e.name,error:`--plugin-dir copy of "${e.name}" ignored: plugin is locked by managed settings`}),!1):!0),i=new Set(r.map(e=>e.name)),a=e.marketplace.filter(e=>i.has(e.name)?(U(`Plugin "${e.name}" from --plugin-dir overrides installed version`),!1):!0);return{plugins:[...r,...a,...e.builtin],errors:t}}async function Fyt(e){let t=kt(),[n,r]=await Promise.all([e(),t.length>0?Nyt(t):Promise.resolve({plugins:[],errors:[]})]),i=Sye(),{plugins:a,errors:o}=Pyt({session:r.plugins,marketplace:n.plugins,builtin:[...i.enabled,...i.disabled],managedNames:q2()}),s=[...n.errors,...r.errors,...o],{demoted:c,errors:l}=jye(a);for(let e of a)c.has(e.source)&&(e.enabled=!1);s.push(...l);let u=a.filter(e=>e.enabled);return U(`Found ${a.length} plugins (${u.length} enabled, ${a.length-u.length} disabled)`),Lyt(u),{enabled:u,disabled:a.filter(e=>!e.enabled),errors:s}}function c4(e){e&&U(`clearPluginCache: invalidating loadAllPlugins cache (${e})`),l4.cache?.clear?.(),u4.cache?.clear?.(),Yte()!==void 0&&Kt(),Fte()}function Iyt(e){let t;for(let n of e)if(n.settings){t||(t={});for(let[e,r]of Object.entries(n.settings))e in t&&U(`Plugin "${n.name}" overrides setting "${e}" (previously set by another plugin)`),t[e]=r}return t}function Lyt(e){let t=Iyt(e);Ete(t),t&&Object.keys(t).length>0&&(Kt(),U(`Cached plugin settings with keys: ${Object.keys(t).join(`, `)}`))}function Ryt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var zyt,l4,u4,d4=n((()=>{d(),Wt(),qg(),W(),h(),On(),zi(),ci(),Bn(),Mi(),_t(),Qi(),Vr(),Zt(),yr(),Yn(),Xg(),t_(),s_(),l_(),K2(),J2(),h2(),F2(),I_(),$g(),fyt(),X2(),si(),a2(),zyt=ht(()=>Kne().pick({agent:!0}).strip()),l4=u(async()=>{let e=await Fyt(()=>kyt({cacheOnly:!1}));return u4.cache?.set(void 0,Promise.resolve(e)),e}),u4=u(async()=>m(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?l4():Fyt(()=>kyt({cacheOnly:!0})))}));async function Byt(e,t,n){let r=[];return await U0(e,async e=>{let i=await Vyt(e,t,n);i&&r.push(i)},{logLabel:`output-styles`}),r}async function Vyt(e,t,n){let r=G();if(Kn(r,e,n))return null;try{let{frontmatter:n,content:i}=od(await r.readFile(e,{encoding:`utf-8`}),e),a=Kc(e,`.md`),o=`${t}:${n.name||a}`,s=ud(n.description,o)??B9(i,`Output style from ${t} plugin`),c=n[`force-for-plugin`],l=c===!0||c===`true`?!0:c===!1||c===`false`?!1:void 0;return{name:o,description:s,prompt:i.trim(),source:`plugin`,forceForPlugin:l}}catch(t){return U(`Failed to load output style from ${e}: ${t}`,{level:`error`}),null}}function Hyt(){f4.cache?.clear?.()}var f4,p4=n((()=>{d(),Wg(),W(),gd(),Bn(),K9(),d4(),W0(),f4=u(async()=>{let{enabled:e,errors:t}=await u4(),n=[];t.length>0&&U(`Plugin loading errors: ${t.map(e=>Ug(e)).join(`, `)}`);for(let t of e){let e=new Set;if(t.outputStylesPath)try{let r=await Byt(t.outputStylesPath,t.name,e);n.push(...r),r.length>0&&U(`Loaded ${r.length} output styles from plugin ${t.name} default directory`)}catch(e){U(`Failed to load output styles from plugin ${t.name} default directory: ${e}`,{level:`error`})}if(t.outputStylesPaths)for(let r of t.outputStylesPaths)try{let i=await G().stat(r);if(i.isDirectory()){let i=await Byt(r,t.name,e);n.push(...i),i.length>0&&U(`Loaded ${i.length} output styles from plugin ${t.name} custom path: ${r}`)}else if(i.isFile()&&r.endsWith(`.md`)){let i=await Vyt(r,t.name,e);i&&(n.push(i),U(`Loaded output style from plugin ${t.name} custom file: ${r}`))}}catch(e){U(`Failed to load output styles from plugin ${t.name} custom path ${r}: ${e}`,{level:`error`})}}return U(`Total plugin output styles loaded: ${n.length}`),n})})),Uyt,Wyt=n((()=>{d(),W(),gd(),Qi(),K9(),p4(),Uyt=u(async e=>{try{return(await G9(`output-styles`,e)).map(({filePath:e,frontmatter:t,content:n,source:r})=>{try{let i=Kc(e).replace(/\.md$/,``),a=t.name||i,o=ud(t.description,i)??B9(n,`Custom ${i} output style`),s=t[`keep-coding-instructions`],c=s===!0||s===`true`?!0:s===!1||s===`false`?!1:void 0;return t[`force-for-plugin`]!==void 0&&U(`Output style "${a}" has force-for-plugin set, but this option only applies to plugin output styles. Ignoring.`,{level:`warn`}),{name:a,description:o,prompt:n.trim(),source:r,keepCodingInstructions:c}}catch(e){return q(e),null}}).filter(e=>e!==null)}catch(e){return q(e),[]}})}));function Gyt(){_4.cache?.clear?.()}async function Kyt(){let e=await _4(yn()),t=Object.values(e).filter(e=>e!==null&&e.source===`plugin`&&e.forceForPlugin===!0),n=t[0];return n?(t.length>1&&U(`Multiple plugins have forced output styles: ${t.map(e=>e.name).join(`, `)}. Using: ${n.name}`,{level:`warn`}),U(`Using forced plugin output style: ${n.name}`),n):e[zr()?.outputStyle||`default`]??null}var m4,h4,g4,_4,v4=n((()=>{ne(),d(),Wyt(),vn(),W(),p4(),Vr(),m4=`
2602
2602
  ## Insights
2603
2603
  In order to encourage learning, before and after writing code, always provide brief educational explanations about implementation choices using (with backticks):
2604
2604
  "\`${ie.star} Insight ─────────────────────────────────────\`
2605
2605
  [2-3 key educational points]
2606
2606
  \`─────────────────────────────────────────────────\`"
2607
2607
 
2608
- These insights should be included in the conversation, not in the codebase. You should generally focus on interesting insights that are specific to the codebase or the code you just wrote, rather than general programming concepts.`,h4=`default`,g4={[h4]:null,Explanatory:{name:`Explanatory`,source:`built-in`,description:`Claude explains its implementation choices and codebase patterns`,keepCodingInstructions:!0,prompt:`You are an interactive CLI tool that helps users with software engineering tasks. In addition to software engineering tasks, you should provide educational insights about the codebase along the way.
2608
+ These insights should be included in the conversation, not in the codebase. You should generally focus on interesting insights that are specific to the codebase or the code you just wrote, rather than general programming concepts.`,h4=`default`,g4={[h4]:null,Explanatory:{name:`Explanatory`,source:`built-in`,description:`Work Mate explains its implementation choices and codebase patterns`,keepCodingInstructions:!0,prompt:`You are an interactive CLI tool that helps users with software engineering tasks. In addition to software engineering tasks, you should provide educational insights about the codebase along the way.
2609
2609
 
2610
2610
  You should be clear and educational, providing helpful explanations while remaining focused on the task. Balance educational content with task completion. When providing insights, you may exceed typical length constraints, but remain focused and relevant.
2611
2611
 
2612
2612
  # Explanatory Style Active
2613
- ${m4}`},Learning:{name:`Learning`,source:`built-in`,description:`Claude pauses and asks you to write small pieces of code for hands-on practice`,keepCodingInstructions:!0,prompt:`You are an interactive CLI tool that helps users with software engineering tasks. In addition to software engineering tasks, you should help users learn more about the codebase through hands-on practice and educational insights.
2613
+ ${m4}`},Learning:{name:`Learning`,source:`built-in`,description:`Work Mate pauses and asks you to write small pieces of code for hands-on practice`,keepCodingInstructions:!0,prompt:`You are an interactive CLI tool that helps users with software engineering tasks. In addition to software engineering tasks, you should help users learn more about the codebase through hands-on practice and educational insights.
2614
2614
 
2615
2615
  You should be collaborative and encouraging. Balance task completion with learning by requesting user input for meaningful design decisions while handling routine implementation yourself.
2616
2616
 
@@ -3167,15 +3167,15 @@ Goal: Write your final plan to the plan file (the only file you can edit).
3167
3167
  - **Hard limit: 40 lines.** If the plan is longer, delete prose — not file paths.`}));function h3(){return!1}async function Fxt(e,t,n){if(!h3())return await n();let r=vl(`sha1`).update(V(e)).digest(`hex`).slice(0,12),i=Y(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??yn(),`fixtures/${t}-${r}.json`);try{return kn(await Ol(i,{encoding:`utf8`}))}catch(e){if(Cn(e)!==`ENOENT`)throw e}if((pr.isCI||process.env.CI)&&!m(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 El(qc(i),{recursive:!0}),await Il(i,V(a,null,2),{encoding:`utf8`}),a}async function Ixt(e,t){if(!h3())return await t();let n=Rxt(R4(e.filter(e=>e.type!==`user`||!e.isMeta)).map(e=>e.message.content),_3),r=Y(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??yn(),`fixtures/${n.map(e=>vl(`sha1`).update(V(e)).digest(`hex`).slice(0,6)).join(`-`)}.json`);try{let e=kn(await Ol(r,{encoding:`utf8`}));return e.output.forEach(Lxt),e.output.map((e,t)=>Bxt(e,Vxt,t,bl()))}catch(e){if(Cn(e)!==`ENOENT`)throw e}if(pr.isCI&&!m(process.env.VCR_RECORD))throw Error(`API fixture missing: ${r}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${V(n,null,2)}`);let i=await t();return pr.isCI&&!m(process.env.VCR_RECORD)?i:(await El(qc(r),{recursive:!0}),await Il(r,V({input:n,output:i.map((e,t)=>Bxt(e,_3,t))},null,2),{encoding:`utf8`}),i)}function Lxt(e){if(e.type===`stream_event`)return;let t=e.message.model,n=e.message.usage;SI(Oo(t,n),n,t)}function Rxt(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:g3(e.input,t)};case`image`:return e;default:return}}))}function g3(e,t){return ih(e,(n,r)=>Array.isArray(n)?n.map(e=>g3(e,t)):Are(n)?g3(n,t):t(n,r,e))}function zxt(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:g3(e.input,t)};default:return e}}).filter(Boolean)},type:`assistant`}}function Bxt(e,t,n,r){return e.type===`assistant`?zxt(e,t,n,r):e}function _3(e){if(typeof e!=`string`)return e;let t=yn(),n=p(),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=V(t).slice(1,-1),o=V(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 Vxt(e){return typeof e==`string`?e.replaceAll(`[NUM]`,`1`).replaceAll(`[DURATION]`,`100`).replaceAll(`[CONFIG_HOME]`,p()).replaceAll(`[CWD]`,yn()):e}async function*Hxt(e,t){if(!h3())return yield*t();let n=[],r=await Ixt(e,async()=>{for await(let e of t())n.push(e);return n});if(r.length>0){yield*r;return}yield*n}async function Uxt(e,t,n){let r=yn().replace(/[^a-zA-Z0-9]/g,`-`);return(await Fxt(_3(V({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 Wxt=n((()=>{Wre(),ah(),CI(),Ao(),vn(),Ar(),h(),On(),m3(),Yn()}));function Gxt(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 Kxt(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=>!pz(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 qxt(e){return e?v3([{role:`user`,content:e}],[]):0}async function v3(e,t){return Uxt(e,t,async()=>{try{let n=Vo();if(n===`gemini`)return Qxt(e,t);let r=Qo(),i=eo(r),a=Gxt(e);if(n===`bedrock`)return eSt({model:So(r),messages:e,tools:t,betas:i,containsThinking:a});let o=await jo({maxRetries:1,model:r,source:`count_tokens`}),s=Vo()===`vertex`?i.filter(e=>Gae.has(e)):i,c=await o.beta.messages.countTokens({model:So(r),messages:e.length>0?e:[{role:`user`,content:`foo`}],tools:t,...s.length>0&&{betas:s},...a&&{thinking:{type:`enabled`,budget_tokens:S3}}});return typeof c.input_tokens==`number`?c.input_tokens:null}catch(e){return q(e),null}})}function y3(e,t=4){return Math.round(e.length/t)}function Jxt(e){switch(e){case`json`:case`jsonl`:case`jsonc`:return 2;default:return 4}}function Yxt(e,t){return y3(e,Jxt(t))}async function Xxt(e,t){if(Vo()===`gemini`)return Qxt(e,t);let n=Gxt(e),r=m(process.env.CLAUDE_CODE_USE_VERTEX)&&_(zo())===`global`,i=m(process.env.CLAUDE_CODE_USE_BEDROCK)&&n,a=m(process.env.CLAUDE_CODE_USE_VERTEX)&&n,o=r||i||a?Wo():zo(),s=await jo({maxRetries:1,model:o,source:`count_tokens`}),c=Kxt(e),l=c.length>0?c:[{role:`user`,content:`count`}],u=eo(o),d=Vo()===`vertex`?u.filter(e=>Gae.has(e)):u,f=(await s.beta.messages.create({model:So(o),max_tokens:n?C3:1,messages:l,tools:t.length>0?t:void 0,...d.length>0&&{betas:d},metadata:X7(),...J7(),...n&&{thinking:{type:`enabled`,budget_tokens:S3}}})).usage,p=f.input_tokens,h=f.cache_creation_input_tokens||0,g=f.cache_read_input_tokens||0;return p+h+g}function b3(e){let t=0;for(let n of e)t+=Zxt(n);return t}function Zxt(e){if((e.type===`assistant`||e.type===`user`)&&e.message?.content)return x3(e.message?.content);if(e.type===`attachment`&&e.attachment){let t=txt(e.attachment),n=0;for(let e of t)n+=x3(e.message.content);return n}return 0}function x3(e){if(!e)return 0;if(typeof e==`string`)return y3(e);let t=0;for(let n of e)t+=$xt(n);return t}function Qxt(e,t){let n=0;for(let t of e)n+=x3(t.content);return t.length>0&&(n+=y3(V(t))),n}function $xt(e){return typeof e==`string`?y3(e):e.type===`text`?y3(e.text):e.type===`image`||e.type===`document`?2e3:e.type===`tool_result`?x3(e.content):e.type===`tool_use`?y3(e.name+V(e.input??{})):e.type===`thinking`?y3(e.thinking):e.type===`redacted_thinking`?y3(e.data):y3(V(e))}async function eSt({model:e,messages:t,tools:n,betas:r,containsThinking:i}){try{let a=await mae(),o=wae(e)?e:await Oae(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?C3:1,...n.length>0&&{tools:n},...r.length>0&&{anthropic_beta:r},...i&&{thinking:{type:`enabled`,budget_tokens:S3}}},{CountTokensCommand:c}=await import(`./dist-es-Gt_DpXlP.js`),l={modelId:o,input:{invokeModel:{body:new TextEncoder().encode(V(s))}}};return(await a.send(new c(l))).inputTokens??null}catch(e){return q(e),null}}var S3,C3,w3=n((()=>{Jo(),Bo(),Uo(),h(),Qi(),m3(),Mo(),No(),Yn(),vz(),r9(),xo(),Wxt(),S3=1024,C3=2048}));function tSt(e){nSt=e}var nSt,rSt=n((()=>{}));function iSt(e,t){switch(e){case`policySettings`:return Y(kr(),`.workmate`,t);case`userSettings`:return Y(p(),t);case`projectSettings`:return`.workmate/${t}`;case`plugin`:return`plugin`;default:return``}}function aSt(e){return y3([e.name,e.description,e.whenToUse].filter(Boolean).join(` `))}async function oSt(e){try{return await Al(e)}catch{return null}}function sSt(e,t){if(!e.hooks)return;let n=nr().safeParse(e.hooks);if(!n.success){U(`Invalid hooks in skill '${t}': ${n.error.message}`);return}return n.data}function cSt(e){if(!e.paths)return;let t=sd(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 T3(e,t,n,r=`Skill`){let i=ud(e.description,n),a=i??B9(t,r),o=e[`user-invocable`]===void 0||dd(e[`user-invocable`]),s=e.model===`inherit`?void 0:e.model?ro(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:v_t(e.arguments),whenToUse:e.when_to_use,version:e.version,model:s,disableModelInvocation:dd(e[`disable-model-invocation`]),userInvocable:o,hooks:sSt(e,n),executionContext:e.context===`fork`?`fork`:void 0,agent:e.agent,shell:fd(e.shell,n)}}function E3({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=J0(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,sn()),h!==`mcp`&&(r=await b_t(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 D3(e,t){let n=G(),r;try{r=await n.readdir(e)}catch(e){return Mn(e)||q(e),[]}return(await Promise.all(r.map(async r=>{try{if(!r.isDirectory()&&!r.isSymbolicLink())return null;let i=Y(e,r.name),a=Y(i,`SKILL.md`),o;try{o=await n.readFile(a,{encoding:`utf-8`})}catch(e){return xn(e)||U(`[skills] failed to read ${a}: ${e}`,{level:`warn`}),null}let{frontmatter:s,content:c}=od(o,a),l=r.name,u=T3(s,c,l),d=cSt(s);return{skill:E3({...u,skillName:l,markdownContent:c,source:t,baseDir:i,loadedFrom:`skills`,paths:d}),filePath:a}}catch(e){return q(e),null}}))).filter(e=>e!==null)}function O3(e){return/^skill\.md$/i.test(Kc(e))}function lSt(e){let t=new Map;for(let n of e){let e=qc(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=>O3(e.filePath));if(t.length>0){let r=t[0];t.length>1&&U(`Multiple skill files found in ${e}, using ${Kc(r.filePath)}`),n.push(r)}else n.push(...r)}return n}function uSt(e,t){let n=t.endsWith(tl)?t.slice(0,-1):t;if(e===n)return``;let r=e.slice(n.length+1);return r?r.split(tl).join(`:`):``}function dSt(e,t){let n=qc(e),r=qc(n),i=Kc(n),a=uSt(r,t);return a?`${a}:${i}`:i}function fSt(e,t){let n=Kc(e),r=qc(e),i=n.replace(/\.md$/,``),a=uSt(r,t);return a?`${a}:${i}`:i}function pSt(e){return O3(e.filePath)?dSt(e.filePath,e.baseDir):fSt(e.filePath,e.baseDir)}async function mSt(e){try{let t=lSt(await G9(`commands`,e)),n=[];for(let{baseDir:e,filePath:r,frontmatter:i,content:a,source:o}of t)try{let t=O3(r)?qc(r):void 0,s=pSt({baseDir:e,filePath:r,frontmatter:i,content:a,source:o}),c=T3(i,a,s,`Custom command`);n.push({skill:E3({...c,skillName:s,displayName:void 0,markdownContent:a,source:o,baseDir:t,loadedFrom:`commands_DEPRECATED`,paths:void 0}),filePath:r})}catch(e){q(e)}return n}catch(e){return q(e),[]}}function hSt(){M3.cache?.clear?.(),G9.cache?.clear?.(),F3.clear(),I3.clear()}function gSt(e){return L3.subscribe(()=>{try{e()}catch(e){q(e)}})}async function k3(e,t){let n=G(),r=t.endsWith(tl)?t.slice(0,-1):t,i=[];for(let t of e){let e=qc(t);for(;e.startsWith(r+tl);){let t=Y(e,`.workmate`,`skills`);if(!N3.has(t)){N3.add(t);try{if(await n.stat(t),await Fre(e,r)){U(`[skills] Skipped gitignored skills dir: ${t}`);continue}i.push(t)}catch{}}let a=qc(e);if(a===e)break;e=a}}return i.sort((e,t)=>t.split(tl).length-e.split(tl).length)}async function A3(e){if(!ii(`projectSettings`)||Bv(`skills`)){U(`[skills] Dynamic skill discovery skipped: projectSettings disabled or plugin-only policy`);return}if(e.length===0)return;let t=new Set(P3.keys()),n=await Promise.all(e.map(e=>D3(e,`projectSettings`)));for(let e=n.length-1;e>=0;e--)for(let{skill:t}of n[e]??[])t.type===`prompt`&&P3.set(t.name,t);let r=n.flat().length;if(r>0){let n=[...P3.keys()].filter(e=>!t.has(e));U(`[skills] Dynamically discovered ${r} skills from ${e.length} directories`),n.length>0&&J(`tengu_dynamic_skills_changed`,{source:`file_operation`,previousCount:t.size,newCount:P3.size,addedCount:n.length,directoryCount:e.length})}L3.emit()}function _St(){return Array.from(P3.values())}function j3(e,t){if(F3.size===0)return[];let n=[];for(let[r,i]of F3){if(i.type!==`prompt`||!i.paths||i.paths.length===0)continue;let a=(0,ySt.default)().add(i.paths);for(let o of e){let e=Yc(o)?$c(t,o):o;if(!(!e||e.startsWith(`..`)||Yc(e))&&a.ignores(e)){P3.set(r,i),F3.delete(r),I3.add(r),n.push(r),U(`[skills] Activated conditional skill '${r}' (matched path: ${e})`);break}}}return n.length>0&&(J(`tengu_dynamic_skills_changed`,{source:`conditional_paths`,previousCount:P3.size-n.length,newCount:P3.size,addedCount:n.length,directoryCount:0}),L3.emit()),n}function vSt(){N3.clear(),P3.clear(),F3.clear(),I3.clear()}var ySt,M3,N3,P3,F3,I3,L3,R3=n((()=>{ySt=r(ce(),1),d(),Wt(),Da(),w3(),Y0(),W(),h(),On(),gd(),Bn(),mre(),Qi(),K9(),No(),E_t(),qr(),Sr(),Hv(),yr(),fn(),rSt(),M3=u(async e=>{let t=Y(p(),`skills`),n=Y(kr(),`.workmate`,`skills`),r=U9(`skills`,e);U(`Loading skills from: managed=${n}, user=${t}, project=[${r.join(`, `)}]`);let i=Qt(),a=Bv(`skills`),o=ii(`projectSettings`)&&!a;if(v())return i.length===0||!o?(U(`[bare] Skipping skill dir discovery (${i.length===0?`no --add-dir`:`projectSettings disabled or skillsLocked`})`),[]):(await Promise.all(i.map(e=>D3(Y(e,`.workmate`,`skills`),`projectSettings`)))).flat().map(e=>e.skill);let[s,c,l,u,d]=await Promise.all([m(process.env.CLAUDE_CODE_DISABLE_POLICY_SKILLS)?Promise.resolve([]):D3(n,`policySettings`),ii(`userSettings`)&&!a?D3(t,`userSettings`):Promise.resolve([]),o?Promise.all(r.map(e=>D3(e,`projectSettings`))):Promise.resolve([]),o?Promise.all(i.map(e=>D3(Y(e,`.workmate`,`skills`),`projectSettings`))):Promise.resolve([]),a?Promise.resolve([]):mSt(e)]),f=[...s,...c,...l.flat(),...u.flat(),...d],h=await Promise.all(f.map(({skill:e,filePath:t})=>e.type===`prompt`?oSt(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=h[e];if(r==null){_.push(n);continue}let i=g.get(r);if(i!==void 0){U(`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&&U(`Deduplicated ${y} skills (same file)`);let b=[],x=[];for(let e of _)e.type===`prompt`&&e.paths&&e.paths.length>0&&!I3.has(e.name)?x.push(e):b.push(e);for(let e of x)F3.set(e.name,e);return x.length>0&&U(`[skills] ${x.length} conditional skills stored (activated when matching files are touched)`),U(`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}),N3=new Set,P3=new Map,F3=new Map,I3=new Set,L3=rn(),tSt({createSkillCommand:E3,parseSkillFrontmatterFields:T3})}));function bSt(e){let{files:t}=e,n,r=e.getPromptForCommand;if(t&&Object.keys(t).length>0){n=SSt(e.name);let i,a=e.getPromptForCommand;r=async(n,r)=>{i??(i=CSt(e.name,t));let o=await i,s=await a(n,r);return o===null?s:DSt(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};z3.push(i)}function xSt(){return[...z3]}function SSt(e){return Y(L8(),e)}async function CSt(e,t){let n=SSt(e);try{return await wSt(n,t),n}catch(t){return U(`Failed to extract bundled skill '${e}' to ${n}: ${t instanceof Error?t.message:String(t)}`),null}}async function wSt(e,t){let n=new Map;for(let[r,i]of Object.entries(t)){let t=ESt(e,r),a=qc(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 El(e,{recursive:!0,mode:448}),await Promise.all(t.map(([e,t])=>TSt(e,t)))}))}async function TSt(e,t){let n=await Dl(e,kSt,384);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}function ESt(e,t){let n=Xc(t);if(Yc(n)||n.split(tl).includes(`..`)||n.split(`/`).includes(`..`))throw Error(`bundled skill file path escapes skill dir: ${t}`);return Y(e,n)}function DSt(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 z3,OSt,kSt,ASt=n((()=>{W(),R8(),z3=[],OSt=ul.O_NOFOLLOW??0,kSt=process.platform===`win32`?`wx`:ul.O_WRONLY|ul.O_CREAT|ul.O_EXCL|OSt}));function jSt(e){return ISt.some(t=>t.test(e))}function MSt(e){return e.length<=8?`***`:`${e.slice(0,4)}…${e.slice(-2)} (${e.length} chars)`}function NSt(e){return LSt.some(t=>e.startsWith(t))}function PSt(){let e=Object.entries(process.env).filter(([e])=>NSt(e)).map(([e,t])=>[e,jSt(e)&&t?MSt(t):t??``]).sort(([e],[t])=>e.localeCompare(t));return e.length===0?` (no recognized env vars set)`:e.map(([e,t])=>` ${e}=${t}`).join(`
3168
3168
  `)}function FSt(){return[` platform: ${process.platform} ${process.arch}`,` cwd: ${process.cwd()}`,` pid: ${process.pid}`,` bun: ${typeof Bun<`u`?Bun.version:`n/a`}`,` node: ${process.version}`,` session: ${sn()}`].join(`
3169
3169
  `)}var ISt,LSt,RSt,zSt=n((()=>{Wt(),ISt=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/auth/i,/private/i,/credential/i,/jwt/i,/session[_-]?id$/i],LSt=[`CLAUDE_`,`FEATURE_`,`ANTHROPIC_`,`BUN_`,`NODE_`,`GEMINI_`,`OPENAI_`,`GROK_`,`CCR_`,`BUGHUNTER_`],RSt={type:`local`,name:`env`,description:`显示当前环境、运行时与 feature flag`,isHidden:!1,isEnabled:()=>!0,supportsNonInteractive:!0,load:async()=>({call:async()=>({type:`text`,value:[`## Runtime`,FSt(),``,`## Environment Variables (allowlisted prefixes)`,PSt(),``,"_Secrets matching token/password/auth/api_key are masked. Set additional `CLAUDE_*` / `FEATURE_*` env vars to see them here._"].join(`
3170
- `)})})}})),B3,BSt=n((()=>{B3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-pjN4EJHV.js`)}})),VSt,HSt=n((()=>{Rme(),No(),VSt={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${Eo(Qo())})`},argumentHint:`[model]`,get immediate(){return Lme()},load:()=>import(`./model-BCM7RpVk.js`)}})),V3,USt=n((()=>{xr(),V3={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[ur,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${ur} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function H3(e){return(e.userFacingName?.()??e.name)||``}function U3(e){return e.isEnabled?.()??!0}var WSt=n((()=>{}));async function GSt(e){try{let[t,n]=await Promise.all([M3(e).catch(e=>(q(jn(e)),U(`Skill directory commands failed to load, continuing without them`),[])),$0().catch(e=>(q(jn(e)),U(`Plugin skills failed to load, continuing without them`),[]))]),r=xSt(),i=Cye();return U(`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 q(jn(e)),U(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}function W3(e){if(!e.availability||e.availability.length===0)return!0;for(let t of e.availability)switch(t){case`claude-ai`:if(uo())return!0;break;case`console`:if(!uo()&&!qae()&&Zo())return!0;break;default:break}return!1}async function G3(e){let t=await X3(e),n=_St(),r=t.filter(e=>W3(e)&&U3(e));if(n.length===0)return r;let i=new Set(r.map(e=>e.name)),a=n.filter(e=>!i.has(e.name)&&W3(e)&&U3(e));if(a.length===0)return r;let o=new Set(J3().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 KSt(){X3.cache?.clear?.(),Z3.cache?.clear?.(),Q3.cache?.clear?.(),cce()}function qSt(){KSt(),j_t(),N_t(),hSt()}function JSt(e){return[]}function YSt(e){return e.filter(e=>$3.has(e))}function K3(e,t){return t.find(t=>t.name===e||H3(t)===e||t.aliases?.includes(e))}function q3(e,t){return K3(e,t)!==void 0}function XSt(e,t){let n=K3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=H3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function ZSt(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} (${Vre(e.source)})`}var J3,Y3,X3,Z3,Q3,$3,e6=n((()=>{rpe(),ipe(),ape(),ope(),spe(),cpe(),lpe(),upe(),dpe(),fpe(),ppe(),wpe(),Tpe(),sme(),tce(),lme(),dme(),pme(),hme(),gme(),vme(),bme(),Sme(),wme(),Eme(),Dme(),Ome(),kme(),lc(),jme(),Nme(),Fme(),Ime(),Bme(),Hme(),Wme(),Kme(),Jme(),Xme(),Qme(),the(),ahe(),Kve(),uye(),yye(),Qi(),On(),W(),R3(),ASt(),qg(),e2(),d(),no(),Jo(),zSt(),BSt(),HSt(),USt(),qr(),WSt(),J3=u(()=>[pf,lye,Cme,vye,Gme,Ume,mf,hf,gf,_f,vf,yf,bf,xf,B3,zme,wf,Lf,xm,cme,Sf,Cf,VSt,qme,Yme,fme,mme,Sm,_me,yme,V3,Cm,Zme,Tme,wm,Mme,Tm,Pme,Em,Vme,Gve,xme,Ame,ihe,ehe,Rf,RSt,nce,ece,ume]),Y3=u(()=>new Set(J3().flatMap(e=>[e.name,...e.aliases??[]]))),X3=u(async e=>{let[{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i},a]=await Promise.all([GSt(e),Q0()]);return[...r,...i,...t,...a,...n,...J3()]}),Z3=u(async e=>(await G3(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))),Q3=u(async e=>{try{return(await G3(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 q(jn(e)),U(`Returning empty skills array due to load failure`),[]}}),$3=new Set([Sm,B3,hf,wf,Cm,wm,mf,Em,Tm,xm,V3])}));async function QSt(e){let t=Date.now(),{stdout:n,code:r}=await Li(Pi(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1}),i=Date.now()-t;if(r!==0)return J(`tengu_worktree_detection`,{duration_ms:i,worktree_count:0,success:!1}),[];let a=n.split(`
3170
+ `)})})}})),B3,BSt=n((()=>{B3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-Af27f74w.js`)}})),VSt,HSt=n((()=>{Rme(),No(),VSt={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${Eo(Qo())})`},argumentHint:`[model]`,get immediate(){return Lme()},load:()=>import(`./model-C73ETGu9.js`)}})),V3,USt=n((()=>{xr(),V3={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[ur,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${ur} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function H3(e){return(e.userFacingName?.()??e.name)||``}function U3(e){return e.isEnabled?.()??!0}var WSt=n((()=>{}));async function GSt(e){try{let[t,n]=await Promise.all([M3(e).catch(e=>(q(jn(e)),U(`Skill directory commands failed to load, continuing without them`),[])),$0().catch(e=>(q(jn(e)),U(`Plugin skills failed to load, continuing without them`),[]))]),r=xSt(),i=Cye();return U(`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 q(jn(e)),U(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}function W3(e){if(!e.availability||e.availability.length===0)return!0;for(let t of e.availability)switch(t){case`claude-ai`:if(uo())return!0;break;case`console`:if(!uo()&&!qae()&&Zo())return!0;break;default:break}return!1}async function G3(e){let t=await X3(e),n=_St(),r=t.filter(e=>W3(e)&&U3(e));if(n.length===0)return r;let i=new Set(r.map(e=>e.name)),a=n.filter(e=>!i.has(e.name)&&W3(e)&&U3(e));if(a.length===0)return r;let o=new Set(J3().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 KSt(){X3.cache?.clear?.(),Z3.cache?.clear?.(),Q3.cache?.clear?.(),cce()}function qSt(){KSt(),j_t(),N_t(),hSt()}function JSt(e){return[]}function YSt(e){return e.filter(e=>$3.has(e))}function K3(e,t){return t.find(t=>t.name===e||H3(t)===e||t.aliases?.includes(e))}function q3(e,t){return K3(e,t)!==void 0}function XSt(e,t){let n=K3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=H3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function ZSt(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} (${Vre(e.source)})`}var J3,Y3,X3,Z3,Q3,$3,e6=n((()=>{rpe(),ipe(),ape(),ope(),spe(),cpe(),lpe(),upe(),dpe(),fpe(),ppe(),wpe(),Tpe(),sme(),tce(),lme(),dme(),pme(),hme(),gme(),vme(),bme(),Sme(),wme(),Eme(),Dme(),Ome(),kme(),lc(),jme(),Nme(),Fme(),Ime(),Bme(),Hme(),Wme(),Kme(),Jme(),Xme(),Qme(),the(),ahe(),Kve(),uye(),yye(),Qi(),On(),W(),R3(),ASt(),qg(),e2(),d(),no(),Jo(),zSt(),BSt(),HSt(),USt(),qr(),WSt(),J3=u(()=>[pf,lye,Cme,vye,Gme,Ume,mf,hf,gf,_f,vf,yf,bf,xf,B3,zme,wf,Lf,xm,cme,Sf,Cf,VSt,qme,Yme,fme,mme,Sm,_me,yme,V3,Cm,Zme,Tme,wm,Mme,Tm,Pme,Em,Vme,Gve,xme,Ame,ihe,ehe,Rf,RSt,nce,ece,ume]),Y3=u(()=>new Set(J3().flatMap(e=>[e.name,...e.aliases??[]]))),X3=u(async e=>{let[{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i},a]=await Promise.all([GSt(e),Q0()]);return[...r,...i,...t,...a,...n,...J3()]}),Z3=u(async e=>(await G3(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))),Q3=u(async e=>{try{return(await G3(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 q(jn(e)),U(`Returning empty skills array due to load failure`),[]}}),$3=new Set([Sm,B3,hf,wf,Cm,wm,mf,Em,Tm,xm,V3])}));async function QSt(e){let t=Date.now(),{stdout:n,code:r}=await Li(Pi(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1}),i=Date.now()-t;if(r!==0)return J(`tengu_worktree_detection`,{duration_ms:i,worktree_count:0,success:!1}),[];let a=n.split(`
3171
3171
  `).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));J(`tengu_worktree_detection`,{duration_ms:i,worktree_count:a.length,success:!0});let o=a.find(t=>e===t||e.startsWith(t+tl)),s=a.filter(e=>e!==o).sort((e,t)=>e.localeCompare(t));return o?[o,...s]:s}var $St=n((()=>{Da(),zi(),Mi()})),eCt=i({MAX_TRANSCRIPT_READ_BYTES:()=>a8,adoptResumedSessionFile:()=>yCt,buildConversationChain:()=>E6,cacheSessionTitle:()=>UCt,checkResumeConsistency:()=>D6,cleanMessagesForLogging:()=>$6,clearAgentTranscriptSubdir:()=>s6,clearGoalEntry:()=>F6,clearSessionMessagesCache:()=>G6,clearSessionMetadata:()=>BCt,deleteRemoteAgentMetadata:()=>d6,doesMessageExistInSession:()=>ZCt,enrichLogs:()=>r8,extractAgentIdsFromMessages:()=>nwt,fetchLogs:()=>M6,findUnresolvedToolUse:()=>swt,flushSessionStorage:()=>SCt,getAgentTranscript:()=>X6,getAgentTranscriptPath:()=>c6,getCurrentSessionTag:()=>RCt,getCurrentSessionTitle:()=>I6,getFirstMeaningfulUserMessageTextContent:()=>C6,getLastSessionLog:()=>K6,getLogByIndex:()=>owt,getNodeEnv:()=>m6,getProjectDir:()=>s8,getProjectsDir:()=>r6,getSessionFilesLite:()=>n8,getSessionFilesWithMtime:()=>e8,getSessionIdFromLog:()=>z6,getSessionMessages:()=>U6,getSessionMessagesCache:()=>W6,getTranscriptPath:()=>i6,getTranscriptPathForSession:()=>a6,getUserType:()=>h6,hydrateFromCCRv2InternalEvents:()=>wCt,hydrateRemoteSession:()=>CCt,isChainParticipant:()=>n6,isCustomTitleEnabled:()=>lCt,isEphemeralToolProgress:()=>nCt,isLiteLog:()=>B6,isLoggableMessage:()=>Q6,isTranscriptMessage:()=>t6,linkSessionToPR:()=>LCt,listRemoteAgentMetadata:()=>f6,loadAllLogsFromSessionFile:()=>t8,loadAllProjectsMessageLogs:()=>QCt,loadAllProjectsMessageLogsProgressive:()=>J6,loadAllSubagentTranscriptsFromDisk:()=>rwt,loadFullLog:()=>V6,loadMessageLogs:()=>q6,loadSameRepoMessageLogs:()=>ewt,loadSameRepoMessageLogsProgressive:()=>Y6,loadSubagentTranscripts:()=>Z6,loadTranscriptFile:()=>H6,loadTranscriptFromFile:()=>OCt,reAppendSessionMetadata:()=>L6,readAgentMetadata:()=>iCt,readRemoteAgentMetadata:()=>sCt,recordAttributionSnapshot:()=>_Ct,recordContentReplacement:()=>x6,recordContextCollapseCommit:()=>bCt,recordContextCollapseSnapshot:()=>xCt,recordFileHistorySnapshot:()=>b6,recordQueueOperation:()=>y6,recordSidechainTranscript:()=>v6,recordTranscript:()=>_6,removeExtraFields:()=>w6,removeTranscriptMessage:()=>gCt,resetProjectFlushStateForTesting:()=>uCt,resetProjectForTesting:()=>dCt,resetSessionFilePointer:()=>vCt,restoreSessionMetadata:()=>zCt,saveAgentName:()=>VCt,saveAgentSetting:()=>HCt,saveAiGeneratedTitle:()=>PCt,saveCustomTitle:()=>NCt,saveGoal:()=>P6,saveMode:()=>WCt,saveTag:()=>ICt,saveTaskSummary:()=>FCt,saveWorktreeState:()=>R6,searchSessionsByCustomTitle:()=>GCt,sessionIdExists:()=>p6,setAgentTranscriptSubdir:()=>o6,setInternalEventReader:()=>mCt,setInternalEventWriter:()=>pCt,setRemoteIngressUrlForTesting:()=>hCt,setSessionFileForTesting:()=>fCt,writeAgentMetadata:()=>l6,writeRemoteAgentMetadata:()=>oCt});function t6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function n6(e){return e.type!==`progress`}function tCt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function nCt(e){return typeof e==`string`&&gwt.has(e)}function r6(){return Y(p(),`projects`)}function i6(){return Y($t()??s8(Xt()),`${sn()}.jsonl`)}function a6(e){return e===sn()?i6():Y(s8(Xt()),`${e}.jsonl`)}function o6(e,t){o8.set(e,t)}function s6(e){o8.delete(e)}function c6(e){let t=$t()??s8(Xt()),n=sn(),r=o8.get(e);return Y(r?Y(t,n,`subagents`,r):Y(t,n,`subagents`),`agent-${e}.jsonl`)}function rCt(e){return c6(e).replace(/\.jsonl$/,`.meta.json`)}async function l6(e,t){let n=rCt(e);await El(qc(n),{recursive:!0}),await Il(n,JSON.stringify(t))}async function iCt(e){let t=rCt(e);try{let e=await Ol(t,`utf-8`);return JSON.parse(e)}catch(e){if(Mn(e))return null;throw e}}function aCt(){return Y($t()??s8(Xt()),sn(),`remote-agents`)}function u6(e){return Y(aCt(),`remote-agent-${e}.meta.json`)}async function oCt(e,t){let n=u6(e);await El(qc(n),{recursive:!0}),await Il(n,JSON.stringify(t))}async function sCt(e){let t=u6(e);try{let e=await Ol(t,`utf-8`);return JSON.parse(e)}catch(e){if(Mn(e))return null;throw e}}async function d6(e){let t=u6(e);try{await Fl(t)}catch(e){if(Mn(e))return;throw e}}async function f6(){let e=aCt(),t;try{t=await kl(e,{withFileTypes:!0})}catch(e){if(Mn(e))return[];throw e}let n=[];for(let r of t)if(!(!r.isFile()||!r.name.endsWith(`.meta.json`)))try{let t=await Ol(Y(e,r.name),`utf-8`);n.push(JSON.parse(t))}catch(e){U(`listRemoteAgentMetadata: skipping ${r.name}: ${String(e)}`)}return n}function p6(e){let t=Y(s8(Xt()),`${e}.jsonl`),n=G();try{return n.statSync(t),!0}catch{return!1}}function m6(){return`production`}function h6(){return`external`}function cCt(){return process.env.CLAUDE_CODE_ENTRYPOINT}function lCt(){return!0}function g6(){return c8||(c8=new _wt,l8||(Gn(async()=>{await c8?.flush();try{c8?.reAppendSessionMetadata()}catch{}}),l8=!0)),c8}function uCt(){c8?._resetFlushState()}function dCt(){c8=null}function fCt(e){g6().sessionFile=e}function pCt(e){g6().setInternalEventWriter(e)}function mCt(e,t){g6().setInternalEventReader(e),g6().setInternalSubagentEventReader(t)}function hCt(e){g6().setRemoteIngressUrl(e)}async function _6(e,t,n,r){let i=$6(e,r),a=await U6(sn()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&n6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await g6().insertMessageChain(o,!1,void 0,s,t),o.findLast(n6)?.uuid??s??null}async function v6(e,t,n){await g6().insertMessageChain($6(e),!0,t,n)}async function y6(e){await g6().insertQueueOperation(e)}async function gCt(e){await g6().removeMessageByUuid(e)}async function b6(e,t,n){await g6().insertFileHistorySnapshot(e,t,n)}async function _Ct(e){await g6().insertAttributionSnapshot(e)}async function x6(e,t){await g6().insertContentReplacement(e,t)}async function vCt(){g6().resetSessionFile()}function yCt(){let e=g6();e.sessionFile=i6(),e.reAppendSessionMetadata(!0)}async function bCt(e){let t=sn();t&&await g6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function xCt(e){let t=sn();t&&await g6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function SCt(){await g6().flush()}async function CCt(e,t){$te(OB(e));let n=g6();try{let n=await trt(e,t)||[];return await El(s8(Xt()),{recursive:!0,mode:448}),await Il(a6(e),n.map(e=>`${V(e)}\n`).join(``),{encoding:`utf8`,mode:384}),U(`Hydrated ${n.length} entries from remote`),n.length>0}catch(e){return U(`Error hydrating session from remote: ${e}`),Ai(`error`,`hydrate_remote_session_fail`),!1}finally{n.setRemoteIngressUrl(t)}}async function wCt(e){let t=Date.now();$te(OB(e));let n=g6(),r=n.getInternalEventReader();if(!r)return U(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return U(`Failed to read internal events for resume`),Ai(`error`,`hydrate_ccr_v2_read_fail`),!1;await El(s8(Xt()),{recursive:!0,mode:448}),await Il(a6(e),i.map(e=>`${V(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),U(`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=c6(kB(e));await El(qc(t),{recursive:!0,mode:448}),await Il(t,n.map(e=>`${V(e)}\n`).join(``),{encoding:`utf8`,mode:384})}U(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return Ai(`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 U(`Error hydrating session from CCR v2: ${e}`),Ai(`error`,`hydrate_ccr_v2_fail`),!1}}function S6(e){let t=C6(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 C6(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=M4(e,Ki);if(t){let n=t.replace(/^\//,``);if(Y3().has(n))continue;{let n=M4(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=M4(e,`bash-input`);if(n)return`! ${n}`;if(!i8.test(e))return e}}}function w6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function TCt(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),t3(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){J(`tengu_relink_walk_broken`,{tailInTranscript:e.has(t.tailUuid),headInTranscript:e.has(t.headUuid),anchorInTranscript:e.has(t.anchorUuid),walkSteps:n.size,transcriptSize: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 ECt(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++);J(`tengu_snip_resume_filtered`,{removed_count:r,relinked_count:a})}function T6(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 E6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){q(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`)),J(`tengu_chain_parent_cycle`,{});break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),DCt(e,n,r)}function DCt(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;J(`tengu_chain_parallel_tr_recovered`,{recovered_count:l});let u=[];for(let e of t){u.push(e);let t=c.get(e.uuid);t&&u.push(...t)}return u}function D6(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;let i=t;J(`tengu_resume_consistency_delta`,{expected:r,actual:i,delta:i-r,chain_length:e.length,checkpoint_age_entries:e.length-1-t});return}}function O6(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 k6(e,t){return Array.from(e.values())}async function OCt(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 H6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=T6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=E6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...j6(p,0,m,h,O6(a,p),g,e,k6(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 Ol(e,{encoding:`utf-8`}),n;try{n=kn(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 j6(r,0,void 0,void 0,void 0,void 0,e)}function kCt(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 ACt(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 A6(e){let t=0;for(let n of e)switch(n.type){case`user`:kCt(n)&&t++;break;case`assistant`:ACt(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function j6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=S6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:w6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:A6(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 jCt(e){let t=new Map,n=0;for(let r of e){let e=z6(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);J(`tengu_session_forked_branches_fetched`,{total_sessions:t.size,sessions_with_branches:i,max_branches_per_session:Math.max(...r),avg_branches_per_session:Math.round(a/i),total_transcript_count:e.length})}async function M6(e){let t=await n8(s8(Xt()),e,Xt());return await jCt(t),t}function N6(e,t){let n=G(),r=`${V(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(qc(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function MCt(e){let t;try{t=Mle(e,`r`);let n=Ale(t),r=Math.max(0,n.size-ba),i=Buffer.allocUnsafe(Math.min(ba,n.size-r)),a=Nle(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Ele(t)}catch{}}}async function NCt(e,t,n,r=`user`){N6(n??a6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===sn()&&(g6().currentSessionTitle=t),J(`tengu_session_renamed`,{source:r})}function PCt(e,t){N6(a6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function FCt(e,t){N6(a6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function ICt(e,t,n){N6(n??a6(e),{type:`tag`,tag:t,sessionId:e}),e===sn()&&(g6().currentSessionTag=t),J(`tengu_session_tagged`,{})}function P6(e,t,n){N6(n??a6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===sn()&&(g6().currentSessionGoal=t)}function F6(e,t){N6(t??a6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===sn()&&(g6().currentSessionGoal=void 0)}async function LCt(e,t,n,r,i){if(N6(i??a6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===sn()){let e=g6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}J(`tengu_session_linked_to_pr`,{prNumber:t})}function RCt(e){if(e===sn())return g6().currentSessionTag}function I6(e){if(e===sn())return g6().currentSessionTitle}function zCt(e){let t=g6();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 BCt(){let e=g6();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 L6(){g6().reAppendSessionMetadata()}async function VCt(e,t,n,r=`user`){N6(n??a6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===sn()&&(g6().currentSessionAgentName=t,xmt(t)),J(`tengu_agent_name_set`,{source:r})}function HCt(e){g6().currentSessionAgentSetting=e}function UCt(e){g6().currentSessionTitle=e}function WCt(e){g6().currentSessionMode=e}function R6(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=g6();n.currentSessionWorktree=t,n.sessionFile&&N6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:sn()})}function z6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function B6(e){return e.messages.length===0&&e.sessionId!==void 0}async function V6(e){if(!B6(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 H6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=T6(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=E6(n,x),C=x.sessionId;return{...e,messages:w6(S),firstPrompt:S6(S),messageCount:A6(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:O6(h,S),attributionSnapshots:k6(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 GCt(e,t){let{limit:n,exact:r}=t||{},i=await twt(await QSt(Xt())),{logs:a}=await r8(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=z6(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 KCt(e,t){if(e===null||e.length===0)return t;if(e.length<vwt)return Buffer.concat([e,t]);if(e[0]===123){for(let n of f8)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 qCt(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=KCt(a,e);if(t===null){a=null;continue}let n=!1;for(let e of f8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of f8){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 f8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function JCt(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 YCt(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?JCt(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 H6(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,h=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!m(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await Nl(e);if(t>5242880){let n=await Gie(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await qCt(e,n.boundaryStartOffset))}}if(S??(S=await Ol(e)),!t?.keepAllLeaves&&!w&&!m(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=YCt(S)),C&&C.length>0){let e=Sa(Buffer.from(C.join(`
3172
3172
  `)));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?h.set(t.sessionId,t.state):t.type===`goal-cleared`&&t.sessionId?h.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=Sa(S),E=new Map;for(let e of T){if(tCt(e)){let t=e.parentUuid;E.set(e.uuid,t&&E.has(t)?E.get(t)??null:t);continue}if(t6(e))e.parentUuid&&E.has(e.parentUuid)&&(e.parentUuid=E.get(e.parentUuid)??null),n.set(e.uuid,e),t3(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)h.set(e.sessionId,e.state);else if(e.type===`goal-cleared`&&e.sessionId)h.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{}TCt(n),ECt(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,E=!1;for(let e of w){let t=new Set,r=e;for(;r;){if(t.has(r.uuid)){E=!0;break}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 E&&J(`tengu_transcript_parent_cycle`,{}),{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:h,fileHistorySnapshots:g,attributionSnapshots:_,contentReplacements:v,agentContentReplacements:y,contextCollapseCommits:b,contextCollapseSnapshot:x,leafUuids:T}}async function XCt(e){return H6(Y($t()??s8(Xt()),`${e}.jsonl`))}async function U6(e){let t=p8.get(e);if(t!==void 0)return t;if(p8.size>=d8){let e=p8.keys().next().value;e!==void 0&&p8.delete(e)}let n=(async()=>{let{messages:t}=await XCt(e);return new Set(t.keys())})();return p8.set(e,n),n}function W6(){return p8}function G6(){p8.clear()}async function ZCt(e,t){return(await U6(e)).has(t)}async function K6(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 XCt(e);if(t.size===0)return null;let p=W6();p.has(e)||p.set(e,Promise.resolve(new Set(t.keys())));let m=T6(t.values(),e=>!e.isSidechain);if(!m)return null;let h=E6(t,m),g=n.get(m.uuid),_=r.get(m.sessionId),v=i.get(m.sessionId),y=a.get(e);return{...j6(h,0,g,_,O6(s,h),v,a6(e),k6(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 q6(e){let t=await M6(e),{logs:n}=await r8(t,0,t.length),r=lu(n);return r.forEach((e,t)=>{e.value=t}),r}async function QCt(e,t){return t?.skipIndex?$Ct(e):(await J6(e,t?.initialEnrichCount??m8)).logs}async function $Ct(e){let t=r6(),n;try{n=await kl(t,{withFileTypes:!0})}catch{return[]}let r=n.filter(e=>e.isDirectory()).map(e=>Y(t,e.name)),i=(await Promise.all(r.map(t=>cwt(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=lu([...a.values()]);return o.forEach((e,t)=>{e.value=t}),o}async function J6(e,t=m8){let n=r6(),r;try{r=await kl(n,{withFileTypes:!0})}catch{return{logs:[],allStatLogs:[],nextIndex:0}}let i=r.filter(e=>e.isDirectory()).map(e=>Y(n,e.name)),a=[];for(let t of i)a.push(...await n8(t,e));let o=fwt(a),{logs:s,nextIndex:c}=await r8(o,0,t);return s.forEach((e,t)=>{e.value=t}),{logs:s,allStatLogs:o,nextIndex:c}}async function ewt(e,t,n=m8){return(await Y6(e,t,n)).logs}async function Y6(e,t,n=m8){U(`/resume: loading sessions for cwd=${Xt()}, worktrees=[${e.join(`, `)}]`);let r=await twt(e,t);U(`/resume: found ${r.length} session files on disk`);let{logs:i,nextIndex:a}=await r8(r,0,n);return i.forEach((e,t)=>{e.value=t}),{logs:i,allStatLogs:r,nextIndex:a}}async function twt(e,t){let n=r6();if(e.length<=1){let e=Xt();return n8(s8(e),void 0,e)}let r=process.platform===`win32`,i=e.map(e=>{let t=_a(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 kl(n,{withFileTypes:!0})}catch(e){return U(`Failed to read projects dir ${n}, falling back to current project: ${e}`),n8(s8(Xt()),t,Xt())}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 n8(Y(n,e.name),void 0,r));break}}}return fwt(a)}async function X6(e){let t=c6(e);try{let{messages:n,agentContentReplacements:r}=await H6(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=T6(i,e=>!a.has(e.uuid));return o?{messages:E6(n,o).filter(t=>t.agentId===e).map(({isSidechain:e,parentUuid:t,...n})=>n),contentReplacements:r.get(e)??[]}:null}catch{return null}}function nwt(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 Qn(t)}async function Z6(e){let t=await Promise.all(e.map(async e=>{try{let t=await X6(kB(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 rwt(){let e=Y($t()??s8(Xt()),sn(),`subagents`),t;try{t=await kl(e,{withFileTypes:!0})}catch{return{}}return Z6(t.filter(e=>e.isFile()&&e.name.startsWith(`agent-`)&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(6,-6)))}function Q6(e){return e.type===`progress`?!1:e.type===`attachment`&&h6()!==`ant`?!!(e.attachment.type===`hook_additional_context`&&m(process.env.CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT)):!0}function iwt(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 awt(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 $6(e,t=e){let n=e.filter(Q6);return h6()===`ant`?n:awt(n,iwt(t))}async function owt(e){return(await q6())[e]||null}async function swt(e){try{let{messages:t}=await H6(i6()),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 e8(e){let t=new Map,n;try{n=await kl(e,{withFileTypes:!0})}catch{return t}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=p2e(Kc(t.name,`.jsonl`));n&&r.push({sessionId:n,filePath:Y(e,t.name)})}return await Promise.all(r.map(async({sessionId:e,filePath:n})=>{try{let r=await Nl(n);t.set(e,{path:n,mtime:r.mtime.getTime(),ctime:r.birthtime.getTime(),size:r.size})}catch{U(`Failed to stat session file: ${n}`)}})),t}async function t8(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 H6(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 _=E6(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:w6(_),fullPath:e,value:0,created:new Date(x.timestamp),modified:new Date(g.timestamp),firstPrompt:S6(_),messageCount:A6(_),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:O6(p,_),attributionSnapshots:k6(m,_),contentReplacements:h.get(S)??[]})}return y}async function cwt(e,t){let n=await e8(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 t8(e.path);i.push(...t)}catch{U(`Failed to load session file: ${e.path}`)}return i}async function lwt(e,t,n){let{head:r,tail:i}=await Xie(e,t,n);if(!r)return{firstPrompt:``,isSidechain:!1};let a=r.includes(`"isSidechain":true`)||r.includes(`"isSidechain": true`),o=ma(r,`cwd`),s=ma(r,`agentSetting`),c=va(i,`lastPrompt`)||uwt(r)||dwt(r,`content`,200)||dwt(r,`text`,200)||``,l=va(i,`customTitle`)??va(r,`customTitle`)??va(i,`aiTitle`)??va(r,`aiTitle`),u=va(i,`summary`),d=va(i,`tag`),f=va(i,`gitBranch`)??ma(r,`gitBranch`),p=va(i,`prUrl`),m=va(i,`prRepository`),h,g=va(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 uwt(e){let t=0,n=!1,r=``;for(;t<e.length;){let i=e.indexOf(`
3173
- `,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=kn(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=M4(t,Ki);if(i){let e=i.replace(/^\//,``),n=M4(t,`command-args`)?.trim()||``;if(Y3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=M4(t,`bash-input`);if(a)return`! ${a}`;if(i8.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 dwt(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 fwt(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 lu([...t.values()]).map((e,t)=>({...e,value:t}))}async function n8(e,t,n){let r=[...(await e8(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=lu(i);return a.forEach((e,t)=>{e.value=t}),a}async function pwt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await lwt(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?(U(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function r8(e,t,n){let r=[],i=Buffer.alloc(ba),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await pwt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&U(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var mwt,hwt,i8,gwt,a8,o8,s8,c8,l8,u8,d8,_wt,f8,vwt,p8,m8,h8=n((()=>{d(),Da(),Wt(),e6(),$i(),cZ(),Dq(),AB(),_fe(),Cr(),Jn(),D1(),vn(),W(),Ei(),h(),On(),Ba(),Bn(),$St(),Mi(),YJ(),wa(),Qi(),m3(),Lr(),ga(),Vr(),Yn(),KG(),b(),mwt=typeof MACRO<`u`?`0.0.14`:`unknown`,hwt=50*1024*1024,i8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,gwt=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),a8=50*1024*1024,o8=new Map,s8=u(e=>Y(r6(),_a(e))),c8=null,l8=!1,u8=10,d8=200,_wt=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,`remoteIngressUrl`,null),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 Sl(e,t,{mode:384})}catch{await El(qc(e),{recursive:!0,mode:448}),await Sl(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=`${V(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=sn();if(!t)return;let n=MCt(this.sessionFile).split(`
3173
+ `,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=kn(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=M4(t,Ki);if(i){let e=i.replace(/^\//,``),n=M4(t,`command-args`)?.trim()||``;if(Y3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=M4(t,`bash-input`);if(a)return`! ${a}`;if(i8.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 dwt(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 fwt(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 lu([...t.values()]).map((e,t)=>({...e,value:t}))}async function n8(e,t,n){let r=[...(await e8(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=lu(i);return a.forEach((e,t)=>{e.value=t}),a}async function pwt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await lwt(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?(U(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function r8(e,t,n){let r=[],i=Buffer.alloc(ba),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await pwt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&U(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var mwt,hwt,i8,gwt,a8,o8,s8,c8,l8,u8,d8,_wt,f8,vwt,p8,m8,h8=n((()=>{d(),Da(),Wt(),e6(),$i(),cZ(),Dq(),AB(),_fe(),Cr(),Jn(),D1(),vn(),W(),Ei(),h(),On(),Ba(),Bn(),$St(),Mi(),YJ(),wa(),Qi(),m3(),Lr(),ga(),Vr(),Yn(),KG(),b(),mwt=typeof MACRO<`u`?`0.0.15`:`unknown`,hwt=50*1024*1024,i8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,gwt=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),a8=50*1024*1024,o8=new Map,s8=u(e=>Y(r6(),_a(e))),c8=null,l8=!1,u8=10,d8=200,_wt=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,`remoteIngressUrl`,null),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 Sl(e,t,{mode:384})}catch{await El(qc(e),{recursive:!0,mode:448}),await Sl(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=`${V(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=sn();if(!t)return;let n=MCt(this.sessionFile).split(`
3174
3174
  `);if(!e){let e=n.findLast(e=>e.startsWith(`{"type":"custom-title"`));if(e){let t=va(e,`customTitle`);t!==void 0&&(this.currentSessionTitle=t||void 0)}}let r=n.findLast(e=>e.startsWith(`{"type":"tag"`));if(r){let e=va(r,`tag`);e!==void 0&&(this.currentSessionTag=e||void 0)}this.currentSessionLastPrompt&&N6(this.sessionFile,{type:`last-prompt`,lastPrompt:this.currentSessionLastPrompt,sessionId:t}),this.currentSessionTitle&&N6(this.sessionFile,{type:`custom-title`,customTitle:this.currentSessionTitle,sessionId:t}),this.currentSessionTag&&N6(this.sessionFile,{type:`tag`,tag:this.currentSessionTag,sessionId:t}),this.currentSessionAgentName&&N6(this.sessionFile,{type:`agent-name`,agentName:this.currentSessionAgentName,sessionId:t}),this.currentSessionAgentColor&&N6(this.sessionFile,{type:`agent-color`,agentColor:this.currentSessionAgentColor,sessionId:t}),this.currentSessionAgentSetting&&N6(this.sessionFile,{type:`agent-setting`,agentSetting:this.currentSessionAgentSetting,sessionId:t}),this.currentSessionMode&&N6(this.sessionFile,{type:`mode`,mode:this.currentSessionMode,sessionId:t}),this.currentSessionGoal&&N6(this.sessionFile,{type:`goal`,sessionId:t,state:this.currentSessionGoal,timestamp:new Date().toISOString()}),this.currentSessionWorktree!==void 0&&N6(this.sessionFile,{type:`worktree-state`,worktreeSession:this.currentSessionWorktree,sessionId:t}),this.currentSessionPrNumber!==void 0&&this.currentSessionPrUrl&&this.currentSessionPrRepository&&N6(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 Dl(this.sessionFile,`r+`);try{let{size:r}=await n.stat();if(t=r,r===0)return;let i=Math.min(r,ba),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>hwt){U(`Skipping tombstone removal: session file too large (${za(t)})`,{level:`warn`});return}let r=(await Ol(this.sessionFile,{encoding:`utf-8`})).split(`
3175
3175
  `).filter(t=>{if(!t.trim())return!0;try{return kn(t).uuid!==e}catch{return!0}});await Il(this.sessionFile,r.join(`
3176
- `),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=m(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return m6()===`test`&&!e||zr()?.cleanupPeriodDays===0||Dt()||m(process.env.CLAUDE_CODE_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 ki()}catch{o=void 0}let s=sn(),c=on().get(s);for(let r of e){let e=t3(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`?one()??void 0:void 0,agentId:n,...r,userType:h6(),entrypoint:cCt(),cwd:yn(),sessionId:s,timestamp:new Date().toISOString(),version:mwt,gitBranch:o,slug:c};await this.appendEntry(u),n6(r)&&(a=r.uuid)}if(!t){let t=C6(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:sn(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=sn()){if(this.shouldSkipPersistence())return;let n=t===sn(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){q(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?c6(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 U6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?c6(kB(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),t6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=i6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=a6(e);try{if(await Nl(n),this.existingSessionFiles.size>=d8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(Mn(e))return null;throw e}}async persistToRemote(e,t){if(!z9e()){if(this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...t3(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{J(`tengu_session_persistence_failed`,{}),U(`Failed to write transcript as internal event`)}return}!m(process.env.ENABLE_SESSION_PERSISTENCE)||!this.remoteIngressUrl||await ert(e,t,this.remoteIngressUrl)||(J(`tengu_session_persistence_failed`,{}),UJ(1,`other`))}}setRemoteIngressUrl(e){this.remoteIngressUrl=e,U(`Remote persistence enabled with URL: ${e}`),e&&(this.FLUSH_INTERVAL_MS=u8)}setInternalEventWriter(e){this.internalEventWriter=e,U(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=u8}setInternalEventReader(e){this.internalEventReader=e,U(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,U(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},f8=[`"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)),vwt=25,p8=new Map,m8=50}));function g8(e){return e.toLowerCase()}function ywt(e){let t=Qr(e),n=g8(t),r=[{dir:Qr(Y(Xt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:Qr(Y(Uc(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=g8(e);for(let a of[tl,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=tl===`\\`?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 bwt(e,t){if(la()===`windows`){let n=pa(e),r=pa(t);return Qc.relative(n,r)}return Qc.relative(e,t)}function xwt(e){return la()===`windows`?pa(e):e}function Swt(){return Zr.map(e=>ti(e)).filter(e=>e!==void 0)}function Cwt(e){let t=g8(Qr(e));return t.endsWith(`${tl}.workmate${tl}settings.json`)||t.endsWith(`${tl}.workmate${tl}settings.local.json`)?!0:Swt().some(e=>g8(e)===t)}function wwt(e){if(Cwt(e))return!0;let t=Y(Xt(),`.workmate`,`commands`),n=Y(Xt(),`.workmate`,`agents`),r=Y(Xt(),`.workmate`,`skills`);return T8(e,t)||T8(e,n)||T8(e,r)}function Twt(e){let t=Y(df(),nf()),n=Xc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function _8(){return Y(s8(yn()),sn(),`session-memory`)+tl}function v8(){return Y(_8(),`summary.md`)}function Ewt(e){return Xc(e).startsWith(_8())}function Dwt(e){let t=s8(yn()),n=Xc(e);return n===t||n.startsWith(t+tl)}function y8(){return!1}function Owt(){return la()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function b8(){return Y(I8(),_a(Xt()))+tl}function x8(){return Y(b8(),sn(),`scratchpad`)}async function kwt(){if(!y8())throw Error(`Scratchpad directory feature is not enabled`);let e=G(),t=x8();return await e.mkdir(t,{mode:448}),t}function Awt(e){if(!y8())return!1;let t=x8(),n=Xc(e);return n===t||n.startsWith(t+tl)}function jwt(e){let t=Qr(e).split(tl),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=g8(n);for(let n of zwt)if(r===g8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&g8(n)===`worktrees`)break}return!0}}if(n){let e=g8(n);if(Rwt.some(t=>g8(t)===e))return!0}return!1}function Mwt(e){return!!((la()===`windows`||la()===`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)||u_(e))}function S8(e,t){let n=t??zn(e);for(let t of n)if(Mwt(t))return{safe:!1,message:`Claude 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(wwt(t))return{safe:!1,message:`Claude requested permissions to write to ${e}, but you haven't granted it yet.`,classifierApprovable:!0};for(let t of n)if(jwt(t))return{safe:!1,message:`Claude requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function C8(e){return new Set([Xt(),...e.additionalWorkingDirectories.keys()])}function w8(e,t,n){let r=n??zn(e),i=Array.from(C8(t)).flatMap(e=>Bwt(e));return r.every(e=>i.some(t=>T8(e,t)))}function T8(e,t){let n=Qr(e),r=Qr(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=g8(i),s=bwt(g8(a),o);return s===``||!Pr(s)&&!Qc.isAbsolute(s)}function Nwt(e){switch(e){case`cliArg`:case`command`:case`session`:return Qr(Xt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return Kr(e)}}function E8(e){return Qc.join(F8,e)}function Pwt({patternRoot:e,pattern:t,rootPath:n}){let r=Qc.join(e,t);if(e===n)return E8(t);if(r.startsWith(`${n}${F8}`))return E8(r.slice(n.length));{let r=Qc.relative(n,e);return!r||r.startsWith(`..${F8}`)||r===`..`?null:E8(Qc.join(r,t))}}function D8(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=Pwt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function O8(e){let t=Iwt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Fwt(e,t){if(e.startsWith(`${F8}${F8}`)){let t=e.slice(1);if(la()===`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:F8}}else if(e.startsWith(`~${F8}`))return{relativePattern:e.slice(1),root:Uc().normalize(`NFC`)};else if(e.startsWith(F8))return{relativePattern:e,root:Nwt(t)};let n=e;return e.startsWith(`.${F8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Iwt(e,t,n){let r=D9(e,(()=>{switch(t){case`edit`:return ws;case`read`:return gs}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Fwt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function k8(e,t,n,r){let i=Qr(e);la()===`windows`&&i.includes(`\\`)&&(i=pa(i));let a=Iwt(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,Lwt.default)().add(n),a=bwt(e??yn(),i??yn());if(a.startsWith(`..${F8}`)||!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 A8(e,t,n){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Claude requested permissions to use ${e.name}, but you haven't granted it yet.`};let r=e.getPath(t),i=zn(r);for(let e of i)if(e.startsWith(`\\\\`)||e.startsWith(`//`))return{behavior:`ask`,message:`Claude 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(Mwt(e))return{behavior:`ask`,message:`Claude 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=k8(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=k8(e,n,`read`,`ask`);if(t)return{behavior:`ask`,message:`Claude requested permissions to read from ${r}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let a=j8(e,t,n,i);if(a.behavior===`allow`)return a;if(w8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=P8(Qr(r),t);if(o.behavior!==`passthrough`)return o;let s=k8(r,n,`read`,`allow`);return s?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}:{behavior:`ask`,message:`Claude requested permissions to read from ${r}, but you haven't granted it yet.`,suggestions:M8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(e,t,n,r){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Claude requested permissions to use ${e.name}, but you haven't granted it yet.`};let i=e.getPath(t),a=r??zn(i);for(let e of a){let t=k8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=N8(Qr(i),t);if(o.behavior!==`passthrough`)return o;let s=k8(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=S8(i,a);if(!c.safe){let e=ywt(i),t=e?[{type:`addRules`,rules:[{toolName:ws,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:M8(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=k8(e,n,`edit`,`ask`);if(t)return{behavior:`ask`,message:`Claude requested permissions to write to ${i}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let l=w8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=k8(i,n,`edit`,`allow`);return u?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:u}}:{behavior:`ask`,message:`Claude requested permissions to write to ${i}, but you haven't granted it yet.`,suggestions:M8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function M8(e,t,n,r){let i=!w8(e,n,r);if(t===`read`&&i)return zn(ni(e)).map(e=>SB(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=zn(ni(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function N8(e,t){let n=Xc(e);if(Twt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Awt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.CLAUDE_JOB_DIR;if(r){let n=Y(p(),`jobs`),i=zn(r).map(Xc),a=zn(n).map(Xc);if(i.every(e=>a.some(t=>e.startsWith(t+tl)))&&zn(e).every(e=>{let t=Xc(e);return i.some(e=>t===e||t.startsWith(e+tl))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Kd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!oie()&&gi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:g8(n)===g8(Y(Xt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function P8(e,t){let n=Xc(e);if(Ewt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(Dwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Twt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=ky(),i=r.endsWith(tl)?r:r+tl;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Awt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=b8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Kd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(gi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=Y(p(),`tasks`)+tl;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=Y(p(),`teams`)+tl;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=L8()+tl;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Lwt,Rwt,zwt,F8,I8,L8,Bwt,R8=n((()=>{Lwt=r(ce(),1),d(),hi(),Jd(),Ns(),Wt(),Fs(),vn(),h(),Bn(),Lr(),ff(),ua(),h8(),qr(),Vr(),w_(),zy(),fa(),CB(),j9(),Rwt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],zwt=[`.git`,`.vscode`,`.idea`,`.workmate`],F8=Qc.sep,I8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||Wc(),t=G(),n=e;try{n=t.realpathSync(e)}catch{}return Y(n,Owt())+tl}),L8=u(function(){let e=yl(16).toString(`hex`);return Y(I8(),`bundled-skills`,`0.0.14`,e)}),Bwt=u(zn)}));function z8(){return J8===void 0&&(J8=Y(b8(),sn(),`tasks`)),J8}async function B8(){await El(z8(),{recursive:!0})}function V8(e){return Y(z8(),`${e}.output`)}function H8(e){return Y8.add(e),e.finally(()=>Y8.delete(e)).catch(()=>{}),e}async function Vwt(){for(;;){try{for(D(Z8,this)||(await B8(),k(Z8,this,await Dl(D(X8,this),process.platform===`win32`?`a`:ul.O_WRONLY|ul.O_APPEND|ul.O_CREAT|G8)));await S(r5,this,Hwt).call(this),D(Q8,this).length!==0;);}finally{if(D(Z8,this)){let e=D(Z8,this);k(Z8,this,null),await e.close()}}if(!D(Q8,this).length)break}}function Hwt(){return D(Z8,this).appendFile(S(r5,this,Uwt).call(this))}function Uwt(){let e=D(Q8,this).splice(0,D(Q8,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 Wwt(){try{await S(r5,this,Vwt).call(this)}catch(e){if(q(e),D(Q8,this).length>0)try{await S(r5,this,Vwt).call(this)}catch(e){q(e)}}finally{let e=D(n5,this);k(t5,this,null),k(n5,this,null),e()}}function Gwt(e){let t=a5.get(e);return t||(t=new i5(e),a5.set(e,t)),t}function Kwt(e,t){Gwt(e).append(t)}function U8(e){return H8((async()=>{let t=a5.get(e);t&&(await t.flush(),a5.delete(e))})())}async function qwt(e,t,n=K8){try{let r=await Wn(V8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Cn(e)===`ENOENT`||q(e),{content:``,newOffset:t}}}async function Jwt(e,t=K8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Ln(V8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Cn(e)===`ENOENT`||q(e),``}}function Ywt(e){return H8((async()=>{await B8();let t=V8(e);return await(await Dl(t,process.platform===`win32`?`wx`:ul.O_WRONLY|ul.O_CREAT|ul.O_EXCL|G8)).close(),t})())}function W8(e,t){return H8((async()=>{try{await B8();let n=V8(e);try{await Pl(t,n)}catch{await Fl(n),await Pl(t,n)}return n}catch(t){return q(t),Ywt(e)}})())}var G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5,o5=n((()=>{Wt(),On(),Bn(),Qi(),R8(),A(),C(),T(),w(),E(),G8=ul.O_NOFOLLOW??0,K8=8*1024*1024,q8=5*1024*1024*1024,Y8=new Set,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakSet,i5=class{constructor(e){ee(this,r5),O(this,X8,void 0),O(this,Z8,null),O(this,Q8,[]),O(this,$8,0),O(this,e5,!1),O(this,t5,null),O(this,n5,null),k(X8,this,V8(e))}append(e){D(e5,this)||(k($8,this,D($8,this)+e.length),D($8,this)>5368709120?(k(e5,this,!0),D(Q8,this).push(`
3176
+ `),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=m(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return m6()===`test`&&!e||zr()?.cleanupPeriodDays===0||Dt()||m(process.env.CLAUDE_CODE_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 ki()}catch{o=void 0}let s=sn(),c=on().get(s);for(let r of e){let e=t3(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`?one()??void 0:void 0,agentId:n,...r,userType:h6(),entrypoint:cCt(),cwd:yn(),sessionId:s,timestamp:new Date().toISOString(),version:mwt,gitBranch:o,slug:c};await this.appendEntry(u),n6(r)&&(a=r.uuid)}if(!t){let t=C6(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:sn(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=sn()){if(this.shouldSkipPersistence())return;let n=t===sn(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){q(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?c6(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 U6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?c6(kB(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),t6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=i6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=a6(e);try{if(await Nl(n),this.existingSessionFiles.size>=d8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(Mn(e))return null;throw e}}async persistToRemote(e,t){if(!z9e()){if(this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...t3(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{J(`tengu_session_persistence_failed`,{}),U(`Failed to write transcript as internal event`)}return}!m(process.env.ENABLE_SESSION_PERSISTENCE)||!this.remoteIngressUrl||await ert(e,t,this.remoteIngressUrl)||(J(`tengu_session_persistence_failed`,{}),UJ(1,`other`))}}setRemoteIngressUrl(e){this.remoteIngressUrl=e,U(`Remote persistence enabled with URL: ${e}`),e&&(this.FLUSH_INTERVAL_MS=u8)}setInternalEventWriter(e){this.internalEventWriter=e,U(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=u8}setInternalEventReader(e){this.internalEventReader=e,U(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,U(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},f8=[`"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)),vwt=25,p8=new Map,m8=50}));function g8(e){return e.toLowerCase()}function ywt(e){let t=Qr(e),n=g8(t),r=[{dir:Qr(Y(Xt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:Qr(Y(Uc(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=g8(e);for(let a of[tl,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=tl===`\\`?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 bwt(e,t){if(la()===`windows`){let n=pa(e),r=pa(t);return Qc.relative(n,r)}return Qc.relative(e,t)}function xwt(e){return la()===`windows`?pa(e):e}function Swt(){return Zr.map(e=>ti(e)).filter(e=>e!==void 0)}function Cwt(e){let t=g8(Qr(e));return t.endsWith(`${tl}.workmate${tl}settings.json`)||t.endsWith(`${tl}.workmate${tl}settings.local.json`)?!0:Swt().some(e=>g8(e)===t)}function wwt(e){if(Cwt(e))return!0;let t=Y(Xt(),`.workmate`,`commands`),n=Y(Xt(),`.workmate`,`agents`),r=Y(Xt(),`.workmate`,`skills`);return T8(e,t)||T8(e,n)||T8(e,r)}function Twt(e){let t=Y(df(),nf()),n=Xc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function _8(){return Y(s8(yn()),sn(),`session-memory`)+tl}function v8(){return Y(_8(),`summary.md`)}function Ewt(e){return Xc(e).startsWith(_8())}function Dwt(e){let t=s8(yn()),n=Xc(e);return n===t||n.startsWith(t+tl)}function y8(){return!1}function Owt(){return la()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function b8(){return Y(I8(),_a(Xt()))+tl}function x8(){return Y(b8(),sn(),`scratchpad`)}async function kwt(){if(!y8())throw Error(`Scratchpad directory feature is not enabled`);let e=G(),t=x8();return await e.mkdir(t,{mode:448}),t}function Awt(e){if(!y8())return!1;let t=x8(),n=Xc(e);return n===t||n.startsWith(t+tl)}function jwt(e){let t=Qr(e).split(tl),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=g8(n);for(let n of zwt)if(r===g8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&g8(n)===`worktrees`)break}return!0}}if(n){let e=g8(n);if(Rwt.some(t=>g8(t)===e))return!0}return!1}function Mwt(e){return!!((la()===`windows`||la()===`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)||u_(e))}function S8(e,t){let n=t??zn(e);for(let t of n)if(Mwt(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(wwt(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(jwt(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function C8(e){return new Set([Xt(),...e.additionalWorkingDirectories.keys()])}function w8(e,t,n){let r=n??zn(e),i=Array.from(C8(t)).flatMap(e=>Bwt(e));return r.every(e=>i.some(t=>T8(e,t)))}function T8(e,t){let n=Qr(e),r=Qr(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=g8(i),s=bwt(g8(a),o);return s===``||!Pr(s)&&!Qc.isAbsolute(s)}function Nwt(e){switch(e){case`cliArg`:case`command`:case`session`:return Qr(Xt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return Kr(e)}}function E8(e){return Qc.join(F8,e)}function Pwt({patternRoot:e,pattern:t,rootPath:n}){let r=Qc.join(e,t);if(e===n)return E8(t);if(r.startsWith(`${n}${F8}`))return E8(r.slice(n.length));{let r=Qc.relative(n,e);return!r||r.startsWith(`..${F8}`)||r===`..`?null:E8(Qc.join(r,t))}}function D8(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=Pwt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function O8(e){let t=Iwt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Fwt(e,t){if(e.startsWith(`${F8}${F8}`)){let t=e.slice(1);if(la()===`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:F8}}else if(e.startsWith(`~${F8}`))return{relativePattern:e.slice(1),root:Uc().normalize(`NFC`)};else if(e.startsWith(F8))return{relativePattern:e,root:Nwt(t)};let n=e;return e.startsWith(`.${F8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Iwt(e,t,n){let r=D9(e,(()=>{switch(t){case`edit`:return ws;case`read`:return gs}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Fwt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function k8(e,t,n,r){let i=Qr(e);la()===`windows`&&i.includes(`\\`)&&(i=pa(i));let a=Iwt(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,Lwt.default)().add(n),a=bwt(e??yn(),i??yn());if(a.startsWith(`..${F8}`)||!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 A8(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=zn(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(Mwt(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=k8(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=k8(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=j8(e,t,n,i);if(a.behavior===`allow`)return a;if(w8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=P8(Qr(r),t);if(o.behavior!==`passthrough`)return o;let s=k8(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:M8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(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??zn(i);for(let e of a){let t=k8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=N8(Qr(i),t);if(o.behavior!==`passthrough`)return o;let s=k8(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=S8(i,a);if(!c.safe){let e=ywt(i),t=e?[{type:`addRules`,rules:[{toolName:ws,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:M8(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=k8(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=w8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=k8(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:M8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function M8(e,t,n,r){let i=!w8(e,n,r);if(t===`read`&&i)return zn(ni(e)).map(e=>SB(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=zn(ni(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function N8(e,t){let n=Xc(e);if(Twt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Awt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.CLAUDE_JOB_DIR;if(r){let n=Y(p(),`jobs`),i=zn(r).map(Xc),a=zn(n).map(Xc);if(i.every(e=>a.some(t=>e.startsWith(t+tl)))&&zn(e).every(e=>{let t=Xc(e);return i.some(e=>t===e||t.startsWith(e+tl))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Kd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!oie()&&gi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:g8(n)===g8(Y(Xt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function P8(e,t){let n=Xc(e);if(Ewt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(Dwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Twt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=ky(),i=r.endsWith(tl)?r:r+tl;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Awt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=b8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Kd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(gi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=Y(p(),`tasks`)+tl;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=Y(p(),`teams`)+tl;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=L8()+tl;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Lwt,Rwt,zwt,F8,I8,L8,Bwt,R8=n((()=>{Lwt=r(ce(),1),d(),hi(),Jd(),Ns(),Wt(),Fs(),vn(),h(),Bn(),Lr(),ff(),ua(),h8(),qr(),Vr(),w_(),zy(),fa(),CB(),j9(),Rwt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],zwt=[`.git`,`.vscode`,`.idea`,`.workmate`],F8=Qc.sep,I8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||Wc(),t=G(),n=e;try{n=t.realpathSync(e)}catch{}return Y(n,Owt())+tl}),L8=u(function(){let e=yl(16).toString(`hex`);return Y(I8(),`bundled-skills`,`0.0.15`,e)}),Bwt=u(zn)}));function z8(){return J8===void 0&&(J8=Y(b8(),sn(),`tasks`)),J8}async function B8(){await El(z8(),{recursive:!0})}function V8(e){return Y(z8(),`${e}.output`)}function H8(e){return Y8.add(e),e.finally(()=>Y8.delete(e)).catch(()=>{}),e}async function Vwt(){for(;;){try{for(D(Z8,this)||(await B8(),k(Z8,this,await Dl(D(X8,this),process.platform===`win32`?`a`:ul.O_WRONLY|ul.O_APPEND|ul.O_CREAT|G8)));await S(r5,this,Hwt).call(this),D(Q8,this).length!==0;);}finally{if(D(Z8,this)){let e=D(Z8,this);k(Z8,this,null),await e.close()}}if(!D(Q8,this).length)break}}function Hwt(){return D(Z8,this).appendFile(S(r5,this,Uwt).call(this))}function Uwt(){let e=D(Q8,this).splice(0,D(Q8,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 Wwt(){try{await S(r5,this,Vwt).call(this)}catch(e){if(q(e),D(Q8,this).length>0)try{await S(r5,this,Vwt).call(this)}catch(e){q(e)}}finally{let e=D(n5,this);k(t5,this,null),k(n5,this,null),e()}}function Gwt(e){let t=a5.get(e);return t||(t=new i5(e),a5.set(e,t)),t}function Kwt(e,t){Gwt(e).append(t)}function U8(e){return H8((async()=>{let t=a5.get(e);t&&(await t.flush(),a5.delete(e))})())}async function qwt(e,t,n=K8){try{let r=await Wn(V8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Cn(e)===`ENOENT`||q(e),{content:``,newOffset:t}}}async function Jwt(e,t=K8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Ln(V8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Cn(e)===`ENOENT`||q(e),``}}function Ywt(e){return H8((async()=>{await B8();let t=V8(e);return await(await Dl(t,process.platform===`win32`?`wx`:ul.O_WRONLY|ul.O_CREAT|ul.O_EXCL|G8)).close(),t})())}function W8(e,t){return H8((async()=>{try{await B8();let n=V8(e);try{await Pl(t,n)}catch{await Fl(n),await Pl(t,n)}return n}catch(t){return q(t),Ywt(e)}})())}var G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5,o5=n((()=>{Wt(),On(),Bn(),Qi(),R8(),A(),C(),T(),w(),E(),G8=ul.O_NOFOLLOW??0,K8=8*1024*1024,q8=5*1024*1024*1024,Y8=new Set,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakSet,i5=class{constructor(e){ee(this,r5),O(this,X8,void 0),O(this,Z8,null),O(this,Q8,[]),O(this,$8,0),O(this,e5,!1),O(this,t5,null),O(this,n5,null),k(X8,this,V8(e))}append(e){D(e5,this)||(k($8,this,D($8,this)+e.length),D($8,this)>5368709120?(k(e5,this,!0),D(Q8,this).push(`
3177
3177
  [output truncated: exceeded 5GB disk cap]
3178
- `)):D(Q8,this).push(e),D(t5,this)||(k(t5,this,new Promise(e=>{k(n5,this,e)})),H8(S(r5,this,Wwt).call(this))))}flush(){return D(t5,this)??Promise.resolve()}cancel(){D(Q8,this).length=0}},a5=new Map}));function Xwt(e){return e===`completed`||e===`failed`||e===`killed`}function Zwt(e){return Qwt[e]??`x`}function s5(e){let t=Zwt(e),n=yl(8),r=t;for(let e=0;e<8;e++)r+=$wt[n[e]%36];return r}function c5(e,t,n,r){return{id:e,type:t,status:`pending`,description:n,toolUseId:r,startTime:Date.now(),outputFile:V8(e),outputOffset:0,notified:!1}}var Qwt,$wt,l5=n((()=>{o5(),Qwt={local_bash:`b`,local_agent:`a`,remote_agent:`r`,local_workflow:`w`,dream:`d`},$wt=`0123456789abcdefghijklmnopqrstuvwxyz`}));function eTt(e,t){return t?`${e} ${t}`:e}function tTt(e){let t=typeof e==`string`?e:e.toString();D(v5,this)?D(_5,this).writeStderr(t):D(_5,this).writeStdout(t)}function nTt(e){D(P5,e)&&D(M5,e)?D(M5,e).call(e,e.background.bind(e)):S(R5,e,f5).call(e,m5)}function rTt(){D(j5,this).reason!==`interrupt`&&this.kill()}function iTt(e,t){let n=e??(t===`SIGTERM`?144:1);S(R5,this,u5).call(this,n)}function aTt(){S(R5,this,u5).call(this,1)}function u5(e){D(I5,this)&&(D(I5,this).call(this,e),k(I5,this,null))}function d5(){S(R5,this,oTt).call(this);let e=D(D5,this);e&&(clearTimeout(e),k(D5,this,null));let t=D(L5,this);t&&(D(j5,this).removeEventListener(`abort`,t),k(L5,this,null))}function oTt(){D(O5,this)&&(clearInterval(D(O5,this)),k(O5,this,null))}function sTt(){k(O5,this,setInterval(()=>{Nl(this.taskOutput.path).then(e=>{e.size>D(A5,this)&&D(S5,this)===`backgrounded`&&D(O5,this)!==null&&(k(k5,this,!0),S(R5,this,oTt).call(this),S(R5,this,f5).call(this,p5))},()=>{})},mTt)),D(O5,this).unref()}function cTt(){k(L5,this,S(R5,this,rTt).bind(this)),D(j5,this).addEventListener(`abort`,D(L5,this),{once:!0}),D(E5,this).once(`exit`,S(R5,this,iTt).bind(this)),D(E5,this).once(`error`,S(R5,this,aTt).bind(this)),k(D5,this,setTimeout(nTt,D(N5,this),this));let e=new Promise(e=>{k(I5,this,e)});return new Promise(t=>{k(F5,this,t),e.then(S(R5,this,lTt).bind(this))})}async function lTt(e){S(R5,this,d5).call(this),(D(S5,this)===`running`||D(S5,this)===`backgrounded`)&&k(S5,this,`completed`);let t={code:e,stdout:await this.taskOutput.getStdout(),stderr:this.taskOutput.getStderr(),interrupted:e===p5,backgroundTaskId:D(C5,this)};this.taskOutput.stdoutToFile&&!D(C5,this)&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(t.outputFilePath=this.taskOutput.path,t.outputFileSize=this.taskOutput.outputFileSize,t.outputTaskId=this.taskOutput.taskId)),D(k5,this)?t.stderr=eTt(`Background command killed: output file exceeded 5GB`,t.stderr):e===m5&&(t.stderr=eTt(`Command timed out after ${La(D(N5,this))}`,t.stderr));let n=D(F5,this);n&&(k(F5,this,null),n(t))}function f5(e){k(S5,this,`killed`),D(E5,this).pid&&(0,pTt.default)(D(E5,this).pid,`SIGKILL`),S(R5,this,u5).call(this,e??p5)}function uTt(e,t,n,r,i=!1,a=q8){return new hTt(e,t,n,r,i,a)}function dTt(e,t){return new gTt({backgroundTaskId:e,...t})}function fTt(e){let t=new kv(s5(`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 pTt,p5,m5,mTt,h5,g5,_5,v5,y5,b5,x5,S5,C5,w5,T5,E5,D5,O5,k5,A5,j5,M5,N5,P5,F5,I5,L5,R5,hTt,gTt,_Tt=n((()=>{pTt=r(Gfe(),1),l5(),Ba(),o5(),Nv(),A(),C(),E(),T(),w(),b(),p5=137,m5=143,mTt=5e3,h5=new WeakMap,g5=new WeakMap,_5=new WeakMap,v5=new WeakMap,y5=new WeakMap,b5=new WeakSet,x5=class{constructor(e,t,n){ee(this,b5),O(this,h5,void 0),O(this,g5,!1),O(this,_5,void 0),O(this,v5,void 0),O(this,y5,S(b5,this,tTt).bind(this)),k(h5,this,e),k(_5,this,t),k(v5,this,n),e.setEncoding(`utf-8`),e.on(`data`,D(y5,this))}cleanup(){D(g5,this)||(k(g5,this,!0),D(h5,this).removeListener(`data`,D(y5,this)),k(h5,this,null),k(_5,this,null),k(y5,this,()=>{}))}},S5=new WeakMap,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 WeakSet,hTt=class{constructor(e,t,n,r,i=!1,a=q8){ee(this,R5),O(this,S5,`running`),O(this,C5,void 0),O(this,w5,void 0),O(this,T5,void 0),O(this,E5,void 0),O(this,D5,null),O(this,O5,null),O(this,k5,!1),O(this,A5,void 0),O(this,j5,void 0),O(this,M5,void 0),O(this,N5,void 0),O(this,P5,void 0),O(this,F5,null),O(this,I5,null),O(this,L5,null),x(this,`taskOutput`,void 0),x(this,`result`,void 0),x(this,`onTimeout`,void 0),k(E5,this,e),k(j5,this,t),k(N5,this,n),k(P5,this,i),k(A5,this,a),this.taskOutput=r,k(T5,this,e.stderr?new x5(e.stderr,r,!0):null),k(w5,this,e.stdout?new x5(e.stdout,r,!1):null),i&&(this.onTimeout=e=>{k(M5,this,e)}),this.result=S(R5,this,cTt).call(this)}get status(){return D(S5,this)}kill(){S(R5,this,f5).call(this)}background(e){return D(S5,this)===`running`?(k(C5,this,e),k(S5,this,`backgrounded`),S(R5,this,d5).call(this),this.taskOutput.stdoutToFile?S(R5,this,sTt).call(this):this.taskOutput.spillToDisk(),!0):!1}cleanup(){D(w5,this)?.cleanup(),D(T5,this)?.cleanup(),this.taskOutput.clear(),S(R5,this,d5).call(this),k(E5,this,null),k(j5,this,null),k(M5,this,void 0)}},gTt=class{constructor(e){x(this,`status`,`killed`),x(this,`result`,void 0),x(this,`taskOutput`,void 0),this.taskOutput=new kv(s5(`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(){}}})),z5,B5,vTt=n((()=>{gt(),_t(),z5=ht(()=>mt.enum([`allow`,`deny`,`ask`])),B5=ht(()=>mt.object({toolName:mt.string(),ruleContent:mt.string().optional()}))})),V5,H5,yTt=n((()=>{gt(),_t(),gr(),vTt(),V5=ht(()=>mt.enum([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),H5=ht(()=>mt.discriminatedUnion(`type`,[mt.object({type:mt.literal(`addRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`replaceRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`removeRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`setMode`),mode:Fne(),destination:V5()}),mt.object({type:mt.literal(`addDirectories`),directories:mt.array(mt.string()),destination:V5()}),mt.object({type:mt.literal(`removeDirectories`),directories:mt.array(mt.string()),destination:V5()})]))}));function U5(e){return!(`async`in e&&e.async===!0)}function W5(e){return`async`in e&&e.async===!0}var bTt,xTt,G5,STt=n((()=>{gt(),_t(),rr(),vTt(),yTt(),bTt=ht(()=>B({prompt:L(),message:L(),options:z(B({key:L(),label:L(),description:L().optional()}))})),xTt=ht(()=>B({continue:ft().describe(`Whether Claude should continue after hook (default: true)`).optional(),suppressOutput:ft().describe(`Hide stdout from transcript (default: false)`).optional(),stopReason:L().describe(`Message shown when continue is false`).optional(),decision:dt([`approve`,`block`]).optional(),reason:L().describe(`Explanation for the decision`).optional(),systemMessage:L().describe(`Warning message shown to the user`).optional(),hookSpecificOutput:lt([B({hookEventName:ot(`PreToolUse`),permissionDecision:z5().optional(),permissionDecisionReason:L().optional(),updatedInput:rt(L(),nt()).optional(),additionalContext:L().optional()}),B({hookEventName:ot(`UserPromptSubmit`),additionalContext:L().optional()}),B({hookEventName:ot(`SessionStart`),additionalContext:L().optional(),initialUserMessage:L().optional(),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`Setup`),additionalContext:L().optional()}),B({hookEventName:ot(`SubagentStart`),additionalContext:L().optional()}),B({hookEventName:ot(`PostToolUse`),additionalContext:L().optional(),updatedMCPToolOutput:nt().describe(`Updates the output for MCP tools`).optional()}),B({hookEventName:ot(`PostToolUseFailure`),additionalContext:L().optional()}),B({hookEventName:ot(`PermissionDenied`),retry:ft().optional()}),B({hookEventName:ot(`Notification`),additionalContext:L().optional()}),B({hookEventName:ot(`PermissionRequest`),decision:lt([B({behavior:ot(`allow`),updatedInput:rt(L(),nt()).optional(),updatedPermissions:z(H5()).optional()}),B({behavior:ot(`deny`),message:L().optional(),interrupt:ft().optional()})])}),B({hookEventName:ot(`Elicitation`),action:dt([`accept`,`decline`,`cancel`]).optional(),content:rt(L(),nt()).optional()}),B({hookEventName:ot(`ElicitationResult`),action:dt([`accept`,`decline`,`cancel`]).optional(),content:rt(L(),nt()).optional()}),B({hookEventName:ot(`CwdChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`FileChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`WorktreeCreate`),worktreePath:L()})]).optional()})),G5=ht(()=>lt([B({async:ot(!0),asyncTimeout:R().optional()}),xTt()]))}));function K5(e,t){let{signalB:n,timeoutMs:r}=t??{},i=rD();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 q5=n((()=>{oD()}));function CTt(e,t){return J0(e,t)}function wTt(){return{...dse,inputSchema:J5(),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 TTt(e,t){x4e(e,t,`Stop`,``,e=>pxt(e,Is),`You MUST call the ${Is} tool to complete this request. Call this tool now.`,{timeout:5e3})}var J5,Y5=n((()=>{gt(),xs(),Y0(),_t(),m3(),fK(),J5=ht(()=>B({ok:ft().describe(`Whether the condition was met`),reason:L().describe(`Reason, if the condition was not met`).optional()}))}));async function ETt(e,t,n,r,i,a,o,s){let c=s||`hook-${bl()}`;try{let s=CTt(e.prompt,r);U(`Hooks: Processing prompt hook with prompt: ${s}`);let l=$({content:s}),u=o&&o.length>0?[...o,l]:[l];U(`Hooks: Querying model with ${u.length} messages`);let{signal:d,cleanup:f}=K5(i,{timeoutMs:e.timeout?e.timeout*1e3:3e4});try{let r=await Z7({messages:u,systemPrompt:Qs([`You are evaluating a hook in Work Mate.
3178
+ `)):D(Q8,this).push(e),D(t5,this)||(k(t5,this,new Promise(e=>{k(n5,this,e)})),H8(S(r5,this,Wwt).call(this))))}flush(){return D(t5,this)??Promise.resolve()}cancel(){D(Q8,this).length=0}},a5=new Map}));function Xwt(e){return e===`completed`||e===`failed`||e===`killed`}function Zwt(e){return Qwt[e]??`x`}function s5(e){let t=Zwt(e),n=yl(8),r=t;for(let e=0;e<8;e++)r+=$wt[n[e]%36];return r}function c5(e,t,n,r){return{id:e,type:t,status:`pending`,description:n,toolUseId:r,startTime:Date.now(),outputFile:V8(e),outputOffset:0,notified:!1}}var Qwt,$wt,l5=n((()=>{o5(),Qwt={local_bash:`b`,local_agent:`a`,remote_agent:`r`,local_workflow:`w`,dream:`d`},$wt=`0123456789abcdefghijklmnopqrstuvwxyz`}));function eTt(e,t){return t?`${e} ${t}`:e}function tTt(e){let t=typeof e==`string`?e:e.toString();D(v5,this)?D(_5,this).writeStderr(t):D(_5,this).writeStdout(t)}function nTt(e){D(P5,e)&&D(M5,e)?D(M5,e).call(e,e.background.bind(e)):S(R5,e,f5).call(e,m5)}function rTt(){D(j5,this).reason!==`interrupt`&&this.kill()}function iTt(e,t){let n=e??(t===`SIGTERM`?144:1);S(R5,this,u5).call(this,n)}function aTt(){S(R5,this,u5).call(this,1)}function u5(e){D(I5,this)&&(D(I5,this).call(this,e),k(I5,this,null))}function d5(){S(R5,this,oTt).call(this);let e=D(D5,this);e&&(clearTimeout(e),k(D5,this,null));let t=D(L5,this);t&&(D(j5,this).removeEventListener(`abort`,t),k(L5,this,null))}function oTt(){D(O5,this)&&(clearInterval(D(O5,this)),k(O5,this,null))}function sTt(){k(O5,this,setInterval(()=>{Nl(this.taskOutput.path).then(e=>{e.size>D(A5,this)&&D(S5,this)===`backgrounded`&&D(O5,this)!==null&&(k(k5,this,!0),S(R5,this,oTt).call(this),S(R5,this,f5).call(this,p5))},()=>{})},mTt)),D(O5,this).unref()}function cTt(){k(L5,this,S(R5,this,rTt).bind(this)),D(j5,this).addEventListener(`abort`,D(L5,this),{once:!0}),D(E5,this).once(`exit`,S(R5,this,iTt).bind(this)),D(E5,this).once(`error`,S(R5,this,aTt).bind(this)),k(D5,this,setTimeout(nTt,D(N5,this),this));let e=new Promise(e=>{k(I5,this,e)});return new Promise(t=>{k(F5,this,t),e.then(S(R5,this,lTt).bind(this))})}async function lTt(e){S(R5,this,d5).call(this),(D(S5,this)===`running`||D(S5,this)===`backgrounded`)&&k(S5,this,`completed`);let t={code:e,stdout:await this.taskOutput.getStdout(),stderr:this.taskOutput.getStderr(),interrupted:e===p5,backgroundTaskId:D(C5,this)};this.taskOutput.stdoutToFile&&!D(C5,this)&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(t.outputFilePath=this.taskOutput.path,t.outputFileSize=this.taskOutput.outputFileSize,t.outputTaskId=this.taskOutput.taskId)),D(k5,this)?t.stderr=eTt(`Background command killed: output file exceeded 5GB`,t.stderr):e===m5&&(t.stderr=eTt(`Command timed out after ${La(D(N5,this))}`,t.stderr));let n=D(F5,this);n&&(k(F5,this,null),n(t))}function f5(e){k(S5,this,`killed`),D(E5,this).pid&&(0,pTt.default)(D(E5,this).pid,`SIGKILL`),S(R5,this,u5).call(this,e??p5)}function uTt(e,t,n,r,i=!1,a=q8){return new hTt(e,t,n,r,i,a)}function dTt(e,t){return new gTt({backgroundTaskId:e,...t})}function fTt(e){let t=new kv(s5(`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 pTt,p5,m5,mTt,h5,g5,_5,v5,y5,b5,x5,S5,C5,w5,T5,E5,D5,O5,k5,A5,j5,M5,N5,P5,F5,I5,L5,R5,hTt,gTt,_Tt=n((()=>{pTt=r(Gfe(),1),l5(),Ba(),o5(),Nv(),A(),C(),E(),T(),w(),b(),p5=137,m5=143,mTt=5e3,h5=new WeakMap,g5=new WeakMap,_5=new WeakMap,v5=new WeakMap,y5=new WeakMap,b5=new WeakSet,x5=class{constructor(e,t,n){ee(this,b5),O(this,h5,void 0),O(this,g5,!1),O(this,_5,void 0),O(this,v5,void 0),O(this,y5,S(b5,this,tTt).bind(this)),k(h5,this,e),k(_5,this,t),k(v5,this,n),e.setEncoding(`utf-8`),e.on(`data`,D(y5,this))}cleanup(){D(g5,this)||(k(g5,this,!0),D(h5,this).removeListener(`data`,D(y5,this)),k(h5,this,null),k(_5,this,null),k(y5,this,()=>{}))}},S5=new WeakMap,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 WeakSet,hTt=class{constructor(e,t,n,r,i=!1,a=q8){ee(this,R5),O(this,S5,`running`),O(this,C5,void 0),O(this,w5,void 0),O(this,T5,void 0),O(this,E5,void 0),O(this,D5,null),O(this,O5,null),O(this,k5,!1),O(this,A5,void 0),O(this,j5,void 0),O(this,M5,void 0),O(this,N5,void 0),O(this,P5,void 0),O(this,F5,null),O(this,I5,null),O(this,L5,null),x(this,`taskOutput`,void 0),x(this,`result`,void 0),x(this,`onTimeout`,void 0),k(E5,this,e),k(j5,this,t),k(N5,this,n),k(P5,this,i),k(A5,this,a),this.taskOutput=r,k(T5,this,e.stderr?new x5(e.stderr,r,!0):null),k(w5,this,e.stdout?new x5(e.stdout,r,!1):null),i&&(this.onTimeout=e=>{k(M5,this,e)}),this.result=S(R5,this,cTt).call(this)}get status(){return D(S5,this)}kill(){S(R5,this,f5).call(this)}background(e){return D(S5,this)===`running`?(k(C5,this,e),k(S5,this,`backgrounded`),S(R5,this,d5).call(this),this.taskOutput.stdoutToFile?S(R5,this,sTt).call(this):this.taskOutput.spillToDisk(),!0):!1}cleanup(){D(w5,this)?.cleanup(),D(T5,this)?.cleanup(),this.taskOutput.clear(),S(R5,this,d5).call(this),k(E5,this,null),k(j5,this,null),k(M5,this,void 0)}},gTt=class{constructor(e){x(this,`status`,`killed`),x(this,`result`,void 0),x(this,`taskOutput`,void 0),this.taskOutput=new kv(s5(`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(){}}})),z5,B5,vTt=n((()=>{gt(),_t(),z5=ht(()=>mt.enum([`allow`,`deny`,`ask`])),B5=ht(()=>mt.object({toolName:mt.string(),ruleContent:mt.string().optional()}))})),V5,H5,yTt=n((()=>{gt(),_t(),gr(),vTt(),V5=ht(()=>mt.enum([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),H5=ht(()=>mt.discriminatedUnion(`type`,[mt.object({type:mt.literal(`addRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`replaceRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`removeRules`),rules:mt.array(B5()),behavior:z5(),destination:V5()}),mt.object({type:mt.literal(`setMode`),mode:Fne(),destination:V5()}),mt.object({type:mt.literal(`addDirectories`),directories:mt.array(mt.string()),destination:V5()}),mt.object({type:mt.literal(`removeDirectories`),directories:mt.array(mt.string()),destination:V5()})]))}));function U5(e){return!(`async`in e&&e.async===!0)}function W5(e){return`async`in e&&e.async===!0}var bTt,xTt,G5,STt=n((()=>{gt(),_t(),rr(),vTt(),yTt(),bTt=ht(()=>B({prompt:L(),message:L(),options:z(B({key:L(),label:L(),description:L().optional()}))})),xTt=ht(()=>B({continue:ft().describe(`Whether Work Mate should continue after hook (default: true)`).optional(),suppressOutput:ft().describe(`Hide stdout from transcript (default: false)`).optional(),stopReason:L().describe(`Message shown when continue is false`).optional(),decision:dt([`approve`,`block`]).optional(),reason:L().describe(`Explanation for the decision`).optional(),systemMessage:L().describe(`Warning message shown to the user`).optional(),hookSpecificOutput:lt([B({hookEventName:ot(`PreToolUse`),permissionDecision:z5().optional(),permissionDecisionReason:L().optional(),updatedInput:rt(L(),nt()).optional(),additionalContext:L().optional()}),B({hookEventName:ot(`UserPromptSubmit`),additionalContext:L().optional()}),B({hookEventName:ot(`SessionStart`),additionalContext:L().optional(),initialUserMessage:L().optional(),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`Setup`),additionalContext:L().optional()}),B({hookEventName:ot(`SubagentStart`),additionalContext:L().optional()}),B({hookEventName:ot(`PostToolUse`),additionalContext:L().optional(),updatedMCPToolOutput:nt().describe(`Updates the output for MCP tools`).optional()}),B({hookEventName:ot(`PostToolUseFailure`),additionalContext:L().optional()}),B({hookEventName:ot(`PermissionDenied`),retry:ft().optional()}),B({hookEventName:ot(`Notification`),additionalContext:L().optional()}),B({hookEventName:ot(`PermissionRequest`),decision:lt([B({behavior:ot(`allow`),updatedInput:rt(L(),nt()).optional(),updatedPermissions:z(H5()).optional()}),B({behavior:ot(`deny`),message:L().optional(),interrupt:ft().optional()})])}),B({hookEventName:ot(`Elicitation`),action:dt([`accept`,`decline`,`cancel`]).optional(),content:rt(L(),nt()).optional()}),B({hookEventName:ot(`ElicitationResult`),action:dt([`accept`,`decline`,`cancel`]).optional(),content:rt(L(),nt()).optional()}),B({hookEventName:ot(`CwdChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`FileChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:ot(`WorktreeCreate`),worktreePath:L()})]).optional()})),G5=ht(()=>lt([B({async:ot(!0),asyncTimeout:R().optional()}),xTt()]))}));function K5(e,t){let{signalB:n,timeoutMs:r}=t??{},i=rD();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 q5=n((()=>{oD()}));function CTt(e,t){return J0(e,t)}function wTt(){return{...dse,inputSchema:J5(),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 TTt(e,t){x4e(e,t,`Stop`,``,e=>pxt(e,Is),`You MUST call the ${Is} tool to complete this request. Call this tool now.`,{timeout:5e3})}var J5,Y5=n((()=>{gt(),xs(),Y0(),_t(),m3(),fK(),J5=ht(()=>B({ok:ft().describe(`Whether the condition was met`),reason:L().describe(`Reason, if the condition was not met`).optional()}))}));async function ETt(e,t,n,r,i,a,o,s){let c=s||`hook-${bl()}`;try{let s=CTt(e.prompt,r);U(`Hooks: Processing prompt hook with prompt: ${s}`);let l=$({content:s}),u=o&&o.length>0?[...o,l]:[l];U(`Hooks: Querying model with ${u.length} messages`);let{signal:d,cleanup:f}=K5(i,{timeoutMs:e.timeout?e.timeout*1e3:3e4});try{let r=await Z7({messages:u,systemPrompt:Qs([`You are evaluating a hook in Work Mate.
3179
3179
 
3180
3180
  Your response must be a JSON object matching one of the following schemas:
3181
3181
  1. If the condition is met, return: {"ok": true}
@@ -3186,7 +3186,7 @@ Use as few steps as possible - be efficient and direct.
3186
3186
 
3187
3187
  When done, return your result using the ${Is} tool with:
3188
3188
  - ok: true if the condition is met
3189
- - ok: false with reason if the condition is not met`]),f=e.model??zo(),_=kB(`hook-agent-${bl()}`),v={...a,agentId:_,abortController:p,options:{...a.options,tools:i,mainLoopModel:f,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})`]}}}}};TTt(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of A1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:A9,toolUseContext:v,querySource:`hook_agent`}))if(Wbt(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(b++,b>=50)){x=!0,U(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(OTt(e)){let t=J5().safeParse(e.attachment.data);if(t.success){y=t.data,U(`Hooks: Got structured output: ${V(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),dK(a.setAppState,_),y?y.ok?(U(`Hooks: Agent hook condition was met`),J(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:j0({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(U(`Hooks: Agent hook condition was not met: ${y.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${y.reason}`,command:e.prompt}}):x?(U(`Hooks: Agent hook did not complete within 50 turns`),J(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(U(`Hooks: Agent hook did not return structured output`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,turnCount:b,errorType:1,agentName:c}),{hook:e,outcome:`cancelled`})}catch(t){if(m.removeEventListener(`abort`,g),h(),_.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=H(r);return U(`Hooks: Agent hook error: ${i}`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:j0({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var ATt=n((()=>{j1(),Da(),Ks(),xs(),i1(),AB(),oD(),H0(),q5(),W(),On(),m3(),No(),j9(),h8(),Yn(),BI(),Y5(),fK()}));function jTt(e){let t=xue(e);return t===4?MTt(e):t===6&&NTt(e)}function MTt(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 NTt(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=FTt(t);if(n!==null)return MTt(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 PTt(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 FTt(e){let t=PTt(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 ITt(e,t,n){let r=`all`in t&&t.all===!0,i=xue(e);if(i!==0){if(jTt(e)){n(LTt(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}Pue(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(jTt(t)){n(LTt(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 LTt(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 RTt=n((()=>{}));async function zTt(){let{SandboxManager:e}=await import(`./sandbox-adapter-DQ_fJSIo.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 BTt(){let e=Xr();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function VTt(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function HTt(e){return e.replace(/[\r\n\x00]/g,``)}function UTt(e,t){return HTt(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]??``:(U(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function WTt(e,t,n,r){let i=BTt();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>VTt(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return U(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=K5(r,{timeoutMs:e.timeout?e.timeout*1e3:GTt});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]=UTt(r,a)}let r=await zTt(),s=!r&&wse()!==void 0&&!Ese(e.url);U(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:ITt});o();let l=c.data??``;return U(`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=H(e);return U(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var GTt,KTt=n((()=>{de(),q5(),W(),On(),Xs(),Vr(),RTt(),GTt=600*1e3}));function qTt(){let e=process.env.CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:NEt}function JTt({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(),_0({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&&gL({value:Y4(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(Yht({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function X5(){return!gn()&&!lie()}function Z5(e,t,n){let r=t??sn(),i=n?.agentType??vte();return{session_id:r,transcript_path:a6(r),cwd:yn(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function YTt(e){let t=kn(e),n=G5().safeParse(t);return n.success?(U(`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(`
3189
+ - ok: false with reason if the condition is not met`]),f=e.model??zo(),_=kB(`hook-agent-${bl()}`),v={...a,agentId:_,abortController:p,options:{...a.options,tools:i,mainLoopModel:f,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})`]}}}}};TTt(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of A1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:A9,toolUseContext:v,querySource:`hook_agent`}))if(Wbt(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(b++,b>=50)){x=!0,U(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(OTt(e)){let t=J5().safeParse(e.attachment.data);if(t.success){y=t.data,U(`Hooks: Got structured output: ${V(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),dK(a.setAppState,_),y?y.ok?(U(`Hooks: Agent hook condition was met`),J(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:j0({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(U(`Hooks: Agent hook condition was not met: ${y.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${y.reason}`,command:e.prompt}}):x?(U(`Hooks: Agent hook did not complete within 50 turns`),J(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(U(`Hooks: Agent hook did not return structured output`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,turnCount:b,errorType:1,agentName:c}),{hook:e,outcome:`cancelled`})}catch(t){if(m.removeEventListener(`abort`,g),h(),_.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=H(r);return U(`Hooks: Agent hook error: ${i}`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:j0({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var ATt=n((()=>{j1(),Da(),Ks(),xs(),i1(),AB(),oD(),H0(),q5(),W(),On(),m3(),No(),j9(),h8(),Yn(),BI(),Y5(),fK()}));function jTt(e){let t=xue(e);return t===4?MTt(e):t===6&&NTt(e)}function MTt(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 NTt(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=FTt(t);if(n!==null)return MTt(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 PTt(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 FTt(e){let t=PTt(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 ITt(e,t,n){let r=`all`in t&&t.all===!0,i=xue(e);if(i!==0){if(jTt(e)){n(LTt(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}Pue(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(jTt(t)){n(LTt(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 LTt(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 RTt=n((()=>{}));async function zTt(){let{SandboxManager:e}=await import(`./sandbox-adapter-Cmrd6tBj.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 BTt(){let e=Xr();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function VTt(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function HTt(e){return e.replace(/[\r\n\x00]/g,``)}function UTt(e,t){return HTt(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]??``:(U(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function WTt(e,t,n,r){let i=BTt();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>VTt(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return U(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=K5(r,{timeoutMs:e.timeout?e.timeout*1e3:GTt});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]=UTt(r,a)}let r=await zTt(),s=!r&&wse()!==void 0&&!Ese(e.url);U(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:ITt});o();let l=c.data??``;return U(`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=H(e);return U(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var GTt,KTt=n((()=>{de(),q5(),W(),On(),Xs(),Vr(),RTt(),GTt=600*1e3}));function qTt(){let e=process.env.CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:NEt}function JTt({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(),_0({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&&gL({value:Y4(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(Yht({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function X5(){return!gn()&&!lie()}function Z5(e,t,n){let r=t??sn(),i=n?.agentType??vte();return{session_id:r,transcript_path:a6(r),cwd:yn(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function YTt(e){let t=kn(e),n=G5().safeParse(t);return n.success?(U(`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(`
3190
3190
  `)}\n\nThe hook's output was: ${V(t,null,2)}`}}function XTt(e){let t=e.trim();if(!t.startsWith(`{`))return U(`Hook output does not start with {, treating as plain text`),{plainText:e};try{let n=YTt(t);if(`json`in n)return n;let r=`${n.validationError}\n\nExpected schema:\n${V({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 U(r),{plainText:e,validationError:r}}catch(t){return U(`Failed to parse hook output as JSON: ${t}`),{plainText:e}}}function ZTt(e){let t=e.trim();if(t===``){let e=G5().safeParse({});if(e.success)return U(`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 U(e),{validationError:e}}try{let e=YTt(t);return`json`in e||U(e.validationError),e}catch(e){let t=`HTTP hook must return valid JSON, but parsing failed: ${e}`;return U(t),{validationError:t}}}function Q5({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: ${V(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?j0({type:`hook_blocking_error`,hookName:n,toolUseID:r,hookEvent:i,blockingError:u.blockingError}):j0({type:`hook_success`,hookName:n,toolUseID:r,hookEvent:i,content:``,stdout:o,stderr:s,exitCode:c,command:t,durationMs:l})}}async function $5(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=la()===`windows`,_=e.shell??`bash`,v=_===`powershell`,y=g&&!v?e=>pa(e):e=>e,b=en(),x=e.command,S;if(s){if(!await Gr(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(F_(c));x=x.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>e)}c&&(S=aT(c),x=iT(x,S))}g&&!v&&x.trim().match(/\.sh(\s|$|")/)&&(x.trim().startsWith(`bash `)||(x=`bash ${x}`));let C=!v&&process.env.CLAUDE_CODE_SHELL_PREFIX?Pxe(process.env.CLAUDE_CODE_SHELL_PREFIX,x):x,w=e.timeout?e.timeout*1e3:g7,T={...kc(),CLAUDE_PROJECT_DIR:y(b)};if(s&&(T.CLAUDE_PLUGIN_ROOT=y(s),c&&(T.CLAUDE_PLUGIN_DATA=y(F_(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 txe(t,o));let E=yn(),D=await Gr(E)?E:Xt();D!==E&&U(`Hooks: cwd ${E} not found, falling back to original cwd`,{level:`warn`});let O=C;if(!v&&Tg.isSandboxingEnabled())try{O=await Tg.wrapWithSandbox(C,void 0,{network:{allowedDomains:[],deniedDomains:[]},filesystem:{allowWrite:[`/`],denyWrite:[],allowRead:[],denyRead:[]}},i),U(`Hook command sandboxed (network-only): ${e.command}`,{level:`verbose`})}catch(e){U(`Failed to sandbox hook command, running unsandboxed: ${H(e)}`,{level:`warn`})}let k;if(_===`powershell`){let t=await hy();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=Rl(t,Qxe(C),{env:T,cwd:D,windowsHide:!0})}else{let e=!g||Hie();k=Rl(O,[],{env:T,cwd:D,shell:e,windowsHide:!0})}let A=new kv(`hook_${k.pid}`,null),ee=uTt(k,i,w,A),te=!1,ne=!1;if((e.async||e.asyncRewake)&&!u){let i=`async_hook_${k.pid}`;if(U(`Hooks: Config-based async hook, backgrounding process ${i}`),k.stdin.write(`${r}\n`,`utf8`),k.stdin.end(),ne=!0,JTt({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(`
3191
3191
  `);N=e.pop()??``;for(let t of e){let e=t.trim();if(e)try{let t=kn(e),n=bTt().safeParse(t);if(n.success){ce.add(e),U(`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(`${V(e)}\n`,`utf8`)}catch(e){U(`Hooks: Prompt request handling failed: ${e}`),k.stdin.destroy()}})}}catch{}}}if(!j){let r=Wa(re).trim();if(!r.includes(`}`))return;j=!0,U(`Hooks: Checking first line for async: ${r}`);try{let i=kn(r);if(U(`Hooks: Parsed initial response: ${V(i)}`),W5(i)&&!u){let r=`async_hook_${k.pid}`;U(`Hooks: Detected async hook, backgrounding process ${r}`),JTt({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 W5(i)&&u?U(`Hooks: Detected async hook but forceSyncExecution is true, waiting for completion`):U(`Hooks: Initial response is not async, continuing normal processing`)}catch(e){U(`Hooks: Failed to parse initial response as JSON: ${e}`)}}}),k.stderr.on(`data`,e=>{ie+=e,ae+=e});let le=Ght({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?U(`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(`
3192
3192
  `).filter(e=>!ce.has(e.trim())).join(`
@@ -3287,7 +3287,7 @@ Avoid making negative assumptions about the user's abilities or judgment. When p
3287
3287
  When referencing code, include file_path:line_number. For GitHub issues/PRs, use owner/repo#123 format.
3288
3288
  Do not use a colon before tool calls — "Let me read the file:" should be "Let me read the file." with a period.
3289
3289
 
3290
- These instructions do not apply to code or tool calls.`}function DDt(){let e=sDt();return e.systemPrompt?e.systemPrompt:null}async function I7(e,t,n,r){if(m(process.env.CLAUDE_CODE_SIMPLE))return[`You are Work Mate, a CLI for Claude.\n\nCWD: ${yn()}\nDate: ${GR()}`];let i=yn(),[a,o,s]=await Promise.all([Z3(i),Kyt(),ADt(t,n)]),c=Xr(),l=new Set(e.map(e=>e.name));if(ic())return U(`[SystemPrompt] path=simple-proactive`),[`
3290
+ These instructions do not apply to code or tool calls.`}function DDt(){let e=sDt();return e.systemPrompt?e.systemPrompt:null}async function I7(e,t,n,r){if(m(process.env.CLAUDE_CODE_SIMPLE))return[`You are Work Mate, a CLI for Work Mate.\n\nCWD: ${yn()}\nDate: ${GR()}`];let i=yn(),[a,o,s]=await Promise.all([Z3(i),Kyt(),ADt(t,n)]),c=Xr(),l=new Set(e.map(e=>e.name));if(ic())return U(`[SystemPrompt] path=simple-proactive`),[`
3291
3291
  You are an autonomous agent. Use the available tools to do useful work.`,pDt(),await Rd(),s,hDt(c.language),m0()?null:_Dt(r),PDt(),B7,FDt()].filter(e=>e!==null);let u=await oBe([qz(`mode_persona`,()=>DDt()),qz(`session_guidance`,()=>TDt(l,a)),qz(`memory`,()=>Rd()),qz(`ant_model_override`,()=>mDt()),qz(`env_info_simple`,()=>ADt(t,n)),qz(`language`,()=>hDt(c.language)),qz(`output_style`,()=>gDt(o)),aBe(`mcp_instructions`,()=>m0()?null:_Dt(r),`MCP servers connect/disconnect between turns`),qz(`scratchpad`,()=>PDt()),qz(`summarize_tool_results`,()=>B7),qz(`token_budget`,()=>`When the user specifies a token target (e.g., "+500k", "spend 2M tokens", "use 1B tokens"), your output token count will be shown each turn. Keep working until you approach the target — plan your work to fill it productively. The target is a hard minimum, not a suggestion. If you stop early, the system will automatically continue you.`)]);return[vDt(o),yDt(),o===null||o.keepCodingInstructions===!0?bDt():null,xDt(),SDt(l),EDt(),...so()?[R7]:[],...u].filter(e=>e!==null)}function ODt(e){let t=e.filter(e=>e.type===`connected`).filter(e=>e.instructions);return t.length===0?null:`# MCP Server Instructions
3292
3292
 
3293
3293
  The following MCP servers have provided instructions for how to use their tools and resources:
@@ -3303,7 +3303,7 @@ ${a}Platform: ${pr.platform}
3303
3303
  ${MDt()}
3304
3304
  OS Version: ${r}
3305
3305
  </env>
3306
- ${i}${s}`}async function ADt(e,t){let[n,r]=await Promise.all([ji(),NDt()]),i=null;{let t=Mae(e);i=t?`You are powered by the model named ${t}. The exact model ID is ${e}.`:`You are powered by the model ${e}.`}let a=jDt(e),o=a?`Assistant knowledge cutoff is ${a}.`:null,s=yn(),c=y7()!==null;return[`# Environment`,`You have been invoked in the following environment: `,...F7([`Primary working directory: ${s}`,c?"This is a git worktree — an isolated copy of the repository. Run all commands from this directory. Do NOT `cd` to the original repository root.":null,[`Is a git repository: ${n}`],t&&t.length>0?`Additional working directories:`:null,t&&t.length>0?t:null,`Platform: ${pr.platform}`,MDt(),`OS Version: ${r}`,i,o,`The most recent Claude model family is Claude 4.5/4.6/4.7. Model IDs — Opus 4.7: '${z7.opus}', Sonnet 4.6: '${z7.sonnet}', Haiku 4.5: '${z7.haiku}'. When building AI applications, default to the latest and most capable Claude models.`,`Work Mate is available as a CLI in the terminal, desktop app (Mac/Windows), web app (claude.ai/code), and IDE extensions (VS Code, JetBrains).`,`Fast mode for Work Mate uses the same ${IDt} model with faster output. It does NOT switch to a different model. It can be toggled with /fast.`].filter(e=>e!==null))].join(`
3306
+ ${i}${s}`}async function ADt(e,t){let[n,r]=await Promise.all([ji(),NDt()]),i=null;{let t=Mae(e);i=t?`You are powered by the model named ${t}. The exact model ID is ${e}.`:`You are powered by the model ${e}.`}let a=jDt(e),o=a?`Assistant knowledge cutoff is ${a}.`:null,s=yn(),c=y7()!==null;return[`# Environment`,`You have been invoked in the following environment: `,...F7([`Primary working directory: ${s}`,c?"This is a git worktree — an isolated copy of the repository. Run all commands from this directory. Do NOT `cd` to the original repository root.":null,[`Is a git repository: ${n}`],t&&t.length>0?`Additional working directories:`:null,t&&t.length>0?t:null,`Platform: ${pr.platform}`,MDt(),`OS Version: ${r}`,i,o,`The most recent Work Mate model family is Claude 4.5/4.6/4.7. Model IDs — Opus 4.7: '${z7.opus}', Sonnet 4.6: '${z7.sonnet}', Haiku 4.5: '${z7.haiku}'. When building AI applications, default to the latest and most capable Work Mate models.`,`Work Mate is available as a CLI in the terminal, desktop app (Mac/Windows), web app (claude.ai/code), and IDE extensions (VS Code, JetBrains).`,`Fast mode for Work Mate uses the same ${IDt} model with faster output. It does NOT switch to a different model. It can be toggled with /fast.`].filter(e=>e!==null))].join(`
3307
3307
  `)}function jDt(e){let t=Yo(e);return t.includes(`claude-sonnet-4-6`)?`August 2025`:t.includes(`claude-opus-4-7`)?`January 2026`:t.includes(`claude-opus-4-6`)||t.includes(`claude-opus-4-5`)?`May 2025`:t.includes(`claude-haiku-4`)?`February 2025`:t.includes(`claude-opus-4`)||t.includes(`claude-sonnet-4`)?`January 2025`:null}function MDt(){let e=process.env.SHELL||`unknown`,t=e.includes(`zsh`)?`zsh`:e.includes(`bash`)?`bash`:e;return pr.platform===`win32`?`Shell: ${t} (use Unix shell syntax, not Windows — e.g., /dev/null not NUL, forward slashes in paths)`:`Shell: ${t}`}function NDt(){return pr.platform===`win32`?`${yle()} ${_le()}`:`${vle()} ${_le()}`}async function L7(e,t,n,r){let i=Dm()&&(r?.has(`DiscoverSkills`)??!0)?wDt():null,a=await kDt(t,n);return[...e,`Notes:
3308
3308
  - Agent threads always have their cwd reset between bash calls, as a result please only use absolute file paths.
3309
3309
  - In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing (e.g., a bug you found, a function signature the caller asked for) — do not recap code you merely read.
@@ -3371,7 +3371,7 @@ Do not narrate each step, list every file you read, or explain routine actions.
3371
3371
 
3372
3372
  The user context may include a \`terminalFocus\` field indicating whether the user's terminal is focused or unfocused. Use this to calibrate how autonomous you are:
3373
3373
  - **Unfocused**: The user is away. Lean heavily into autonomous action — make decisions, explore, commit, push. Only pause for genuinely irreversible or high-risk actions.
3374
- - **Focused**: The user is watching. Be more collaborative — surface choices, ask before committing to large changes, and keep your output concise so it's easy to follow in real time.`:null}var R7,IDt,z7,LDt,B7,V7=n((()=>{Ar(),Mi(),vn(),Wt(),k7(),KR(),Vr(),xr(),Fs(),Ns(),is(),ps(),bs(),No(),e6(),Js(),v4(),fs(),ls(),sy(),cs(),b4(),T4(),R8(),h(),Dq(),Uo(),fL(),Yz(),Hs(),$i(),W(),Ud(),Vht(),dDt(),tc(),Hct(),Om(),R7=`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`,IDt=`Claude Opus 4.7`,z7={opus:`claude-opus-4-7`,sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5-20251001`},LDt=`You are an agent for Work Mate, a CLI for Claude. Given the user's message, you should use the tools available to complete the task. Complete the task fully—don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.`,B7=`When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.`}));async function H7(e,t){let n=`inputJSONSchema`in e&&e.inputJSONSchema?`${e.name}:${V(e.inputJSONSchema)}`:e.name,r=Bae(),i=r.get(n);if(!i){let a=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);i={name:e.name,description:await e.prompt({getToolPermissionContext:t.getToolPermissionContext,tools:t.tools,agents:t.agents,allowedAgentTypes:t.allowedAgentTypes}),input_schema:a},Vo()===`firstParty`&&Zo()&&m(process.env.CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING)&&(i.eager_input_streaming=!0),r.set(n,i)}let a={name:i.name,description:i.description,input_schema:i.input_schema,...i.strict&&{strict:!0},...i.eager_input_streaming&&{eager_input_streaming:!0}};if(t.deferLoading&&(a.defer_loading=!0),t.cacheControl&&(a.cache_control=t.cacheControl),m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS)){let e=new Set([`name`,`description`,`input_schema`,`cache_control`]),t=Object.keys(a).filter(t=>!e.has(t));if(t.length>0)return RDt(t),{name:a.name,description:a.description,input_schema:a.input_schema,...a.cache_control&&{cache_control:a.cache_control}}}return a}function RDt(e){U7||(U7=!0,U(`[betas] Stripped from tool schemas: [${e.join(`, `)}] (CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)`))}function zDt(e){let[t]=BDt(e),n=t?.text;J(`tengu_sysprompt_block`,{snippet:n?.slice(0,20),length:n?.length??0,hash:n?vl(`sha256`).update(n).digest(`hex`):``})}function BDt(e,t){let n=so();if(n&&t?.skipGlobalCacheForSystemPrompt){J(`tengu_sysprompt_using_tool_based_cache`,{promptBlockCount:e.length});let t,n,r=[];for(let i of e)i&&i!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`&&(i.startsWith(`x-anthropic-billing-header`)?t=i:Cd.has(i)?n=i:r.push(i));let i=[];t&&i.push({text:t,cacheScope:null}),n&&i.push({text:n,cacheScope:`org`});let a=r.join(`
3374
+ - **Focused**: The user is watching. Be more collaborative — surface choices, ask before committing to large changes, and keep your output concise so it's easy to follow in real time.`:null}var R7,IDt,z7,LDt,B7,V7=n((()=>{Ar(),Mi(),vn(),Wt(),k7(),KR(),Vr(),xr(),Fs(),Ns(),is(),ps(),bs(),No(),e6(),Js(),v4(),fs(),ls(),sy(),cs(),b4(),T4(),R8(),h(),Dq(),Uo(),fL(),Yz(),Hs(),$i(),W(),Ud(),Vht(),dDt(),tc(),Hct(),Om(),R7=`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`,IDt=`Claude Opus 4.7`,z7={opus:`claude-opus-4-7`,sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5-20251001`},LDt=`You are an agent for Work Mate, a CLI for Work Mate. Given the user's message, you should use the tools available to complete the task. Complete the task fully—don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.`,B7=`When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.`}));async function H7(e,t){let n=`inputJSONSchema`in e&&e.inputJSONSchema?`${e.name}:${V(e.inputJSONSchema)}`:e.name,r=Bae(),i=r.get(n);if(!i){let a=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);i={name:e.name,description:await e.prompt({getToolPermissionContext:t.getToolPermissionContext,tools:t.tools,agents:t.agents,allowedAgentTypes:t.allowedAgentTypes}),input_schema:a},Vo()===`firstParty`&&Zo()&&m(process.env.CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING)&&(i.eager_input_streaming=!0),r.set(n,i)}let a={name:i.name,description:i.description,input_schema:i.input_schema,...i.strict&&{strict:!0},...i.eager_input_streaming&&{eager_input_streaming:!0}};if(t.deferLoading&&(a.defer_loading=!0),t.cacheControl&&(a.cache_control=t.cacheControl),m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS)){let e=new Set([`name`,`description`,`input_schema`,`cache_control`]),t=Object.keys(a).filter(t=>!e.has(t));if(t.length>0)return RDt(t),{name:a.name,description:a.description,input_schema:a.input_schema,...a.cache_control&&{cache_control:a.cache_control}}}return a}function RDt(e){U7||(U7=!0,U(`[betas] Stripped from tool schemas: [${e.join(`, `)}] (CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)`))}function zDt(e){let[t]=BDt(e),n=t?.text;J(`tengu_sysprompt_block`,{snippet:n?.slice(0,20),length:n?.length??0,hash:n?vl(`sha256`).update(n).digest(`hex`):``})}function BDt(e,t){let n=so();if(n&&t?.skipGlobalCacheForSystemPrompt){J(`tengu_sysprompt_using_tool_based_cache`,{promptBlockCount:e.length});let t,n,r=[];for(let i of e)i&&i!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`&&(i.startsWith(`x-anthropic-billing-header`)?t=i:Cd.has(i)?n=i:r.push(i));let i=[];t&&i.push({text:t,cacheScope:null}),n&&i.push({text:n,cacheScope:`org`});let a=r.join(`
3375
3375
 
3376
3376
  `);return a&&i.push({text:a,cacheScope:`org`}),i}if(n){let t=e.indexOf(R7);if(t!==-1){let n,r,i=[],a=[];for(let o=0;o<e.length;o++){let s=e[o];!s||s===`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`||(s.startsWith(`x-anthropic-billing-header`)?n=s:Cd.has(s)?r=s:o<t?i.push(s):a.push(s))}let o=[];n&&o.push({text:n,cacheScope:null}),r&&o.push({text:r,cacheScope:null});let s=i.join(`
3377
3377
 
@@ -3383,12 +3383,12 @@ The user context may include a \`terminalFocus\` field indicating whether the us
3383
3383
  `)].filter(Boolean)}function HDt(e,t){if(Object.entries(t).length===0)return e;let{agentsMd:n,...r}=t,i=[];n&&i.push($({content:`<project-instructions>\n${n}\n</project-instructions>\n`,isMeta:!0}));let a=Object.entries(r);return a.length>0&&i.push($({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(`
3384
3384
  `)}
3385
3385
 
3386
- 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 UDt(e,t){if(ale())return;let[{tools:n},r,i,a]=await Promise.all([gM(e),r1(t),XR(),YR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=yn(),u=D8(O8(t),l),d=await dce(l,AbortSignal.timeout(1e3),u),f=0,p=0,m=0,h=0,g=0,_=r.filter(e=>!e.isMcp);f=n.length,h=_.length;let v=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&v.add(t[1])}p=v.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);m+=y3(V(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);g+=y3(V(t))}J(`tengu_context_size`,{git_status_size:o,claude_md_size:s,total_context_size:c,project_file_count_rounded:d,mcp_tools_count:f,mcp_servers_count:p,mcp_tools_tokens:m,non_mcp_tools_count:h,non_mcp_tools_tokens:g})}function WDt(e,t,n){switch(e.name){case Rs:{let e=of(n),r=af(n);return lf(),e===null?t:{...t,plan:e,planFilePath:r}}case SW.name:{let e=SW.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=yn(),o=n.replace(`cd ${a} && `,``);la()===`windows`&&(o=o.replace(`cd ${pa(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&J(`tengu_bash_tool_simple_echo`,{});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 xq.name:{let e=xq.inputSchema.parse(t),{file_path:n,edits:r}=EPe({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 QH.name:{let e=QH.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:PI(e.content)}}case fr:{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 GDt(e,t){switch(e.name){case Rs:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case xq.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(),ZR(),rle(),Da(),BM(),CW(),Sq(),zI(),$H(),i1(),wd(),w3(),os(),ei(),Uo(),vn(),W(),h(),m3(),Jo(),R8(),ff(),ua(),mc(),Yn(),Rae(),fa(),sz(),U7=!1}));function KDt(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||m(process.env.USE_API_CLEAR_TOOL_RESULTS),o=m(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:qDt};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:JDt};i.push(n)}return i.length>0?{edits:i}:void 0}var G7,K7,qDt,JDt,YDt=n((()=>{Ns(),Fs(),vs(),fs(),ls(),Ps(),qs(),h(),G7=18e4,K7=4e4,qDt=[...vse,Us,rs,gs],JDt=[ws,ks,Ls]})),XDt,ZDt=n((()=>{XDt={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 QDt(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 $Dt=n((()=>{})),eOt=n((()=>{ec()}));function tOt(e){if(e instanceof Pn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function nOt({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(cOt))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(lOt))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 rOt(){let e=new Date(`2026-08-13T18:38:19.460Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function iOt({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){let u=s?.type??`disabled`,d=s?.type===`enabled`?s.budgetTokens:void 0;J(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Fo(),buildAgeMins:rOt(),...r?.length?{betas:r.join(`,`)}:{},permissionMode:i,querySource:a,...o?{queryChainId:o.chainId,queryDepth:o.depth}:{},thinkingType:u,...d!==void 0&&{thinkingBudgetTokens:d},fastMode:c,...l?{previousRequestId:l}:{},...q7()})}function aOt({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 _=nOt({headers:e instanceof Pn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=tOt(e),y=e instanceof Pn?String(e.status):void 0,b=GIe(e),x=Zs(e);if(x){let e=x.isSSLError?` (SSL error)`:``;U(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=Ece();c&&U(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),q(e),J(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Fo(),requestId:s||void 0,...S?{invokingRequestId:S.invokingRequestId,invocationKind:S.invocationKind}:{},clientRequestId:c||void 0,didFallBackToNonStreaming:l,...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{},fastMode:h,...g?{previousRequestId:g}:{},...q7()}),Nc(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),Hce(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o});let C=Dte();C?.isTeleported&&!C.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_error`,{session_id:C.sessionId,error_type:b}),jt())}function oOt({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,connectorTextBlockCount:x,fastMode:S,previousRequestId:C,betas:w}){let T=gn(),E=tne(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=Ot(),A=k===null?void 0:O-k,ee=Ece();J(`tengu_api_success`,{model:e,...t===e?{}:{preNormalizedModel:t},...w?.length?{betas:w.join(`,`)}:{},messageCount:n,messageTokens:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cache_read_input_tokens??0,uncachedInputTokens:i.cache_creation_input_tokens??0,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c??void 0,buildAgeMins:rOt(),provider:Fo(),requestId:l??void 0,...ee?{invokingRequestId:ee.invokingRequestId,invocationKind:ee.invocationKind}:{},stop_reason:u??void 0,costUSD:d,didFallBackToNonStreaming:f,isNonInteractiveSession:T,print:D,isTTY:process.stdout.isTTY??!1,querySource:p,...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{},permissionMode:g,..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:V(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...q7(),timeSinceLastApiCallMs:A}),wt(O)}function sOt({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=nOt({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O,k;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=V(i.input).length,t=Dc(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0,k=void 0}let A=Date.now()-n,ee=Date.now()-r;Bte(ee,A),oOt({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:A,durationMsIncludingRetries:ee,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,connectorTextBlockCount:k,fastMode:S,previousRequestId:C,betas:w}),Nc(`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(A),speed:S?`fast`:`normal`});let te,ne;Mc()&&_&&(te=_.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(`
3387
- `)||void 0,ne=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),Hce(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:te,thinkingOutput:void 0,hasToolCall:ne,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x});let re=Dte();re?.isTeleported&&!re.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_success`,{session_id:re.sessionId}),jt())}var cOt,lOt,uOt=n((()=>{Nn(),Wt(),W(),Qi(),Jo(),Yn(),Ic(),Pc(),Sc(),Da(),Cc(),eOt(),aR(),WL(),cOt={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-`]}},lOt={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function J7(e){let t=process.env.CLAUDE_CODE_EXTRA_BODY,n={};if(t)try{let e=Ea(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:U(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){U(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${H(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 dOt(e){return!(m(process.env.DISABLE_PROMPT_CACHING)||m(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===zo()||m(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Wo()||m(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===jae())}function Y7({scope:e,querySource:t}={}){return{type:`ephemeral`,...fOt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function fOt(e){if(Vo()===`bedrock`&&m(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=ene();if(t===null&&(t=uo()&&!BL.isUsingOverage,gte(t)),!t)return!1;let n=Tte();return n===null&&(n={}.allowlist??[],ute(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function pOt(e,t,n){!e||`task_budget`in t||!yo()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Xae))}function X7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Ea(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:U(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:V({...e,device_id:aie(),account_uuid:Hae()?.accountUuid??``,session_id:sn()})}}async function mOt(e,t){if(t)return!0;try{let t=zo(),n=eo(t);return await fpt(sR(()=>jo({apiKey:e,maxRetries:3,model:t,source:`verify_api_key`}),async e=>(await e.beta.messages.create({model:t,max_tokens:1,messages:[{role:`user`,content:`test`}],temperature:1,...n.length>0&&{betas:n.filter(Boolean)},metadata:X7(),...J7()}),!0),{maxRetries:2,model:t,thinkingConfig:{type:`disabled`}}))}catch(e){let t=e;if(e instanceof gR&&(t=e.originalError),q(t),t instanceof Error&&t.message.includes(`{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`))return!1;throw t}}function hOt(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 gOt(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=_Ot(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Td(a)&&n?{cache_control:Y7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(_Ot)}}function _Ot(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 Hxt(e,async function*(){yield*wOt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new In:Error(`No assistant message found`);return o}async function*vOt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*Hxt(e,async function*(){yield*wOt(e,t,n,r,i,a)})}function yOt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(m(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*bOt(e,t,n,r,i,a){let o=yOt(),s=sR(()=>jo({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(s,c,l)=>{let u=Date.now(),d=n(l);i(d),r(c,u,d.max_tokens);let f=AOt(d,MOt);try{return await s.beta.messages.create({...f,model:So(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof In?t:(Ai(`error`,`cli_nonstreaming_fallback_error`),J(`tengu_nonstreaming_fallback_error`,{model:e.model,error:t instanceof Error?t.name:`unknown`,attempt:c,timeout_ms:o,request_id:a??`unknown`}),t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...Xo()&&{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 xOt(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 SOt(e){return e.type===`tool_result`}function COt(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++,SOt(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||!SOt(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*wOt(e,t,n,r,i,a){if(!uo()&&es(a.model)&&{activated:!1}.activated){J(`tengu_off_switch_query`,{}),yield qL(Error(rR),a.model);return}let o=xOt(e),s=Vo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await Oae(a.model)??a.model:a.model;u1(`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=Uae(a.model,{isAgenticQuery:c});kg()&&l.push(Yae);let u;if(c&&kg()){let e=a.advisorModel,t=qve();if(t!==void 0&&So(t.baseModel)===So(a.model)&&(e=t.advisorModel),e){let t=So(ro(e));jg(a.model)?Mg(t)?(u=t,U(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):U(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):U(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await fz(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)As(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(U(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Ws(e,`SearchExtraTools`))):r.filter(e=>!Ws(e,Vs));let h=so(),g=h&&p.some(e=>e.isMcp===!0);h&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(roe);let _=h?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&&U(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),u1(`query_tool_schema_build_end`),J(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),u1(`query_message_normalization_start`);let y=R4(e,p);if(u1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return Mbt(e);case`assistant`:return Nbt(e);default:return e}})),y=xxt(y),l.includes(`advisor-tool-2026-03-01`)||(y=Sxt(y)),y=COt(y,100),Vo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-qW8mATAs.js`);yield*e(y,t,r,i,a);return}if(Vo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-BC-BxZmj.js`);yield*e(y,t,p,i,a,n);return}if(Vo()===`grok`){let{queryModelGrok:e}=await import(`./grok-BBo3jGfP.js`);yield*e(y,t,p,i,a);return}if(J(`tengu_api_after_normalize`,{postNormalizedMessageCount:y.length}),d&&!hz()){let e=r.filter(e=>f.has(e.name)).map(pse).sort().join(`
3386
+ 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 UDt(e,t){if(ale())return;let[{tools:n},r,i,a]=await Promise.all([gM(e),r1(t),XR(),YR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=yn(),u=D8(O8(t),l),d=await dce(l,AbortSignal.timeout(1e3),u),f=0,p=0,m=0,h=0,g=0,_=r.filter(e=>!e.isMcp);f=n.length,h=_.length;let v=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&v.add(t[1])}p=v.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);m+=y3(V(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:az(e.inputSchema);g+=y3(V(t))}J(`tengu_context_size`,{git_status_size:o,claude_md_size:s,total_context_size:c,project_file_count_rounded:d,mcp_tools_count:f,mcp_servers_count:p,mcp_tools_tokens:m,non_mcp_tools_count:h,non_mcp_tools_tokens:g})}function WDt(e,t,n){switch(e.name){case Rs:{let e=of(n),r=af(n);return lf(),e===null?t:{...t,plan:e,planFilePath:r}}case SW.name:{let e=SW.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=yn(),o=n.replace(`cd ${a} && `,``);la()===`windows`&&(o=o.replace(`cd ${pa(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&J(`tengu_bash_tool_simple_echo`,{});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 xq.name:{let e=xq.inputSchema.parse(t),{file_path:n,edits:r}=EPe({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 QH.name:{let e=QH.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:PI(e.content)}}case fr:{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 GDt(e,t){switch(e.name){case Rs:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case xq.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(),ZR(),rle(),Da(),BM(),CW(),Sq(),zI(),$H(),i1(),wd(),w3(),os(),ei(),Uo(),vn(),W(),h(),m3(),Jo(),R8(),ff(),ua(),mc(),Yn(),Rae(),fa(),sz(),U7=!1}));function KDt(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||m(process.env.USE_API_CLEAR_TOOL_RESULTS),o=m(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:qDt};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:JDt};i.push(n)}return i.length>0?{edits:i}:void 0}var G7,K7,qDt,JDt,YDt=n((()=>{Ns(),Fs(),vs(),fs(),ls(),Ps(),qs(),h(),G7=18e4,K7=4e4,qDt=[...vse,Us,rs,gs],JDt=[ws,ks,Ls]})),XDt,ZDt=n((()=>{XDt={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 QDt(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 $Dt=n((()=>{})),eOt=n((()=>{ec()}));function tOt(e){if(e instanceof Pn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function nOt({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(cOt))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(lOt))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 rOt(){let e=new Date(`2026-08-14T02:22:06.766Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function iOt({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){let u=s?.type??`disabled`,d=s?.type===`enabled`?s.budgetTokens:void 0;J(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Fo(),buildAgeMins:rOt(),...r?.length?{betas:r.join(`,`)}:{},permissionMode:i,querySource:a,...o?{queryChainId:o.chainId,queryDepth:o.depth}:{},thinkingType:u,...d!==void 0&&{thinkingBudgetTokens:d},fastMode:c,...l?{previousRequestId:l}:{},...q7()})}function aOt({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 _=nOt({headers:e instanceof Pn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=tOt(e),y=e instanceof Pn?String(e.status):void 0,b=GIe(e),x=Zs(e);if(x){let e=x.isSSLError?` (SSL error)`:``;U(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=Ece();c&&U(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),q(e),J(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Fo(),requestId:s||void 0,...S?{invokingRequestId:S.invokingRequestId,invocationKind:S.invocationKind}:{},clientRequestId:c||void 0,didFallBackToNonStreaming:l,...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{},fastMode:h,...g?{previousRequestId:g}:{},...q7()}),Nc(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),Hce(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o});let C=Dte();C?.isTeleported&&!C.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_error`,{session_id:C.sessionId,error_type:b}),jt())}function oOt({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,connectorTextBlockCount:x,fastMode:S,previousRequestId:C,betas:w}){let T=gn(),E=tne(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=Ot(),A=k===null?void 0:O-k,ee=Ece();J(`tengu_api_success`,{model:e,...t===e?{}:{preNormalizedModel:t},...w?.length?{betas:w.join(`,`)}:{},messageCount:n,messageTokens:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cache_read_input_tokens??0,uncachedInputTokens:i.cache_creation_input_tokens??0,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c??void 0,buildAgeMins:rOt(),provider:Fo(),requestId:l??void 0,...ee?{invokingRequestId:ee.invokingRequestId,invocationKind:ee.invocationKind}:{},stop_reason:u??void 0,costUSD:d,didFallBackToNonStreaming:f,isNonInteractiveSession:T,print:D,isTTY:process.stdout.isTTY??!1,querySource:p,...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{},permissionMode:g,..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:V(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...q7(),timeSinceLastApiCallMs:A}),wt(O)}function sOt({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=nOt({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O,k;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=V(i.input).length,t=Dc(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0,k=void 0}let A=Date.now()-n,ee=Date.now()-r;Bte(ee,A),oOt({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:A,durationMsIncludingRetries:ee,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,connectorTextBlockCount:k,fastMode:S,previousRequestId:C,betas:w}),Nc(`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(A),speed:S?`fast`:`normal`});let te,ne;Mc()&&_&&(te=_.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(`
3387
+ `)||void 0,ne=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),Hce(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:te,thinkingOutput:void 0,hasToolCall:ne,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x});let re=Dte();re?.isTeleported&&!re.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_success`,{session_id:re.sessionId}),jt())}var cOt,lOt,uOt=n((()=>{Nn(),Wt(),W(),Qi(),Jo(),Yn(),Ic(),Pc(),Sc(),Da(),Cc(),eOt(),aR(),WL(),cOt={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-`]}},lOt={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function J7(e){let t=process.env.CLAUDE_CODE_EXTRA_BODY,n={};if(t)try{let e=Ea(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:U(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){U(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${H(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 dOt(e){return!(m(process.env.DISABLE_PROMPT_CACHING)||m(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===zo()||m(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Wo()||m(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===jae())}function Y7({scope:e,querySource:t}={}){return{type:`ephemeral`,...fOt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function fOt(e){if(Vo()===`bedrock`&&m(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=ene();if(t===null&&(t=uo()&&!BL.isUsingOverage,gte(t)),!t)return!1;let n=Tte();return n===null&&(n={}.allowlist??[],ute(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function pOt(e,t,n){!e||`task_budget`in t||!yo()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Xae))}function X7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Ea(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:U(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:V({...e,device_id:aie(),account_uuid:Hae()?.accountUuid??``,session_id:sn()})}}async function mOt(e,t){if(t)return!0;try{let t=zo(),n=eo(t);return await fpt(sR(()=>jo({apiKey:e,maxRetries:3,model:t,source:`verify_api_key`}),async e=>(await e.beta.messages.create({model:t,max_tokens:1,messages:[{role:`user`,content:`test`}],temperature:1,...n.length>0&&{betas:n.filter(Boolean)},metadata:X7(),...J7()}),!0),{maxRetries:2,model:t,thinkingConfig:{type:`disabled`}}))}catch(e){let t=e;if(e instanceof gR&&(t=e.originalError),q(t),t instanceof Error&&t.message.includes(`{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`))return!1;throw t}}function hOt(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 gOt(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=_Ot(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Td(a)&&n?{cache_control:Y7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(_Ot)}}function _Ot(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 Hxt(e,async function*(){yield*wOt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new In:Error(`No assistant message found`);return o}async function*vOt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*Hxt(e,async function*(){yield*wOt(e,t,n,r,i,a)})}function yOt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(m(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*bOt(e,t,n,r,i,a){let o=yOt(),s=sR(()=>jo({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(s,c,l)=>{let u=Date.now(),d=n(l);i(d),r(c,u,d.max_tokens);let f=AOt(d,MOt);try{return await s.beta.messages.create({...f,model:So(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof In?t:(Ai(`error`,`cli_nonstreaming_fallback_error`),J(`tengu_nonstreaming_fallback_error`,{model:e.model,error:t instanceof Error?t.name:`unknown`,attempt:c,timeout_ms:o,request_id:a??`unknown`}),t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...Xo()&&{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 xOt(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 SOt(e){return e.type===`tool_result`}function COt(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++,SOt(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||!SOt(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*wOt(e,t,n,r,i,a){if(!uo()&&es(a.model)&&{activated:!1}.activated){J(`tengu_off_switch_query`,{}),yield qL(Error(rR),a.model);return}let o=xOt(e),s=Vo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await Oae(a.model)??a.model:a.model;u1(`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=Uae(a.model,{isAgenticQuery:c});kg()&&l.push(Yae);let u;if(c&&kg()){let e=a.advisorModel,t=qve();if(t!==void 0&&So(t.baseModel)===So(a.model)&&(e=t.advisorModel),e){let t=So(ro(e));jg(a.model)?Mg(t)?(u=t,U(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):U(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):U(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await fz(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)As(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(U(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Ws(e,`SearchExtraTools`))):r.filter(e=>!Ws(e,Vs));let h=so(),g=h&&p.some(e=>e.isMcp===!0);h&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(roe);let _=h?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&&U(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),u1(`query_tool_schema_build_end`),J(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),u1(`query_message_normalization_start`);let y=R4(e,p);if(u1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return Mbt(e);case`assistant`:return Nbt(e);default:return e}})),y=xxt(y),l.includes(`advisor-tool-2026-03-01`)||(y=Sxt(y)),y=COt(y,100),Vo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-Dx5mvMjY.js`);yield*e(y,t,r,i,a);return}if(Vo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-Cll4fVQn.js`);yield*e(y,t,p,i,a,n);return}if(Vo()===`grok`){let{queryModelGrok:e}=await import(`./grok-HF1PHxXb.js`);yield*e(y,t,p,i,a);return}if(J(`tengu_api_after_normalize`,{postNormalizedMessageCount:y.length}),d&&!hz()){let e=r.filter(e=>f.has(e.name)).map(pse).sort().join(`
3388
3388
  `);if(e){let t=new Set(e.split(`
3389
3389
  `));if([...t].some(e=>!n9.has(e))){n9.clear();for(let e of t)n9.add(e);y=[...y,$({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=Qs([vd(),_d({isNonInteractive:a.isNonInteractiveSession,hasAppendSystemPrompt:a.hasAppendSystemPrompt}),...t,...u?[Xve]:[]].filter(Boolean));{let e=Qse(),n=$se();if(ml(e)||ml(n)){let n=bl();if(t=Qs([...t,`<!-- cache-break nonce: ${n} -->`]),ml(e))try{$le(e)}catch{}}}zDt(t);let b=a.enablePromptCaching??dOt(a.model),x=kOt(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=Xo()&&noe()&&!qo()&&Vae(a.model)&&!!a.fastMode,E=Rte()===!0;!E&&c&&yo()&&iL()&&(E=!0,wte(!0));let D=Hte()===!0;!D&&T&&(D=!0,Jte(!0));let O=mne()===!0;kLe({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:BL.isUsingOverage??!1,cachedMCEnabled:O,extraBodyParams:J7()});let k=Mc()?{systemPrompt:t.join(`
3390
3390
 
3391
- `),querySource:a.querySource,tools:V(w)}:void 0,A=zce(a.model,k,y,T),ee=Date.now(),te=Date.now(),ne=0,re=[],ie,ae,j,oe;function se(){TOt(ie),ie=void 0,oe&&(oe.body?.cancel().catch(()=>{}),oe=void 0)}let ce=[],M,N=e=>{let t=[...l];!t.includes(`context-1m-2025-08-07`)&&Dae(e.model)&&t.push(eoe);let r=J7(Vo()===`bedrock`?[...xae(e.model)]:[]),i={...r.output_config??{}};pOt(a.taskBudget,i,t),a.outputFormat&&!(`format`in i)&&(i.format=a.outputFormat,yae(a.model)&&!t.includes(`structured-outputs-2025-12-15`)&&t.push(Iae));let o=e?.maxTokensOverride||a.maxOutputTokensOverride||t9(a.model),s=n.type!==`disabled`&&!m(process.env.CLAUDE_CODE_DISABLE_THINKING),u;if(s&&i6e(a.model))if(!m(process.env.CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING)&&a6e(a.model))u={type:`adaptive`};else{let e=pae(a.model);n.type===`enabled`&&n.budgetTokens!==void 0&&(e=n.budgetTokens),e=Math.min(o-1,e),u={budget_tokens:e,type:`enabled`}}let d=KDt({hasThinking:s,isRedactThinkingActive:t.includes(Nae),clearAllThinking:!1}),f=a.enablePromptCaching??dOt(e.model),p;Xo()&&noe()&&!qo()&&Vae(a.model)&&e.fastMode&&(p=`fast`),D&&!t.includes(`fast-mode-2026-02-01`)&&t.push(Wae),E&&yo()&&c&&!t.includes(``)&&t.push(``);let h=s?void 0:a.temperatureOverride??1,g=t.filter(Boolean);return M=g,{model:So(a.model),messages:OOt(y,f,a.querySource,!1,null,ce,a.skipCacheWrite),system:x,tools:w,tool_choice:a.toolChoice,...S&&{betas:g},metadata:X7(),max_tokens:o,thinking:u,...h!==void 0&&{temperature:h},...d&&S&&t.includes(`context-management-2025-06-27`)&&{context_management:d},...r,...Object.keys(i).length>0&&{output_config:i},...p!==void 0&&{speed:p}}};{let e=N({model:a.model,thinkingConfig:n}),t=e.messages.length,r=S?e.betas??[]:[];a.getToolPermissionContext().then(e=>{iOt({model:a.model,messagesLength:t,temperature:a.temperatureOverride??1,betas:r,permissionMode:e.mode,querySource:a.querySource,queryTracking:a.queryTracking,thinkingConfig:n,fastMode:T,previousRequestId:o})})}let le=[],ue=0,de,fe=[],pe=new Map,me=rc,he=0,ge=null,_e=!1,ve,ye=0,be,xe=T,Se=!1;try{u1(`query_client_creation_start`);let t=sR(()=>jo({maxRetries:0,model:a.model,fetchOverride:a.fetchOverride,source:a.querySource}),async(e,t,n)=>{ne=t,xe=n.fastMode??!1,te=Date.now(),re.push(te),u1(`query_client_creation_end`);let r=N(n);Zi(r,a.querySource),ye=r.max_tokens,u1(`query_api_request_sent`),a.agentId||AG(`api_request_sent`),j=Vo()===`firstParty`&&Zo()?bl():void 0;let o=await e.beta.messages.create({...r,stream:!0},{signal:i,...j&&{headers:{"x-client-request-id":j}}}).withResponse();return u1(`query_response_headers_received`),ae=o.request_id,oe=o.response,o.data},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()?{fastMode:T}:!1,signal:i,querySource:a.querySource}),o;do o=await t.next(),`controller`in o.value||(yield o.value);while(!o.done);ie=o.value,le.length=0,ue=0,de=void 0,fe.length=0,pe.clear(),me=rc,ge=null,Se=!1;let c=m(process.env.CLAUDE_ENABLE_STREAM_WATCHDOG),l=parseInt(process.env.CLAUDE_STREAM_IDLE_TIMEOUT_MS||``,10)||9e4,d=l/2,f=!1,p=null,h=null,g=null;function _(){h!==null&&(clearTimeout(h),h=null),g!==null&&(clearTimeout(g),g=null)}function v(){_(),c&&(h=setTimeout(e=>{U(`Streaming idle warning: no chunks received for ${e/1e3}s`,{level:`warn`}),Ai(`warn`,`cli_streaming_idle_warning`)},d,d),g=setTimeout(()=>{f=!0,p=performance.now(),U(`Streaming idle timeout: no chunks received for ${l/1e3}s, aborting stream`,{level:`error`}),Ai(`error`,`cli_streaming_idle_timeout`),J(`tengu_streaming_idle_timeout`,{model:a.model,request_id:ae??`unknown`,timeout_ms:l}),se()},l))}v(),Use(`api_call`);try{let t=!0,n=null,i=0,o=0;for await(let e of ie){v();let c=Date.now();if(n!==null){let t=c-n;t>3e4&&(o++,i+=t,U(`Streaming stall detected: ${(t/1e3).toFixed(1)}s gap between events (stall #${o})`,{level:`warn`}),J(`tengu_streaming_stall`,{stall_duration_ms:t,stall_count:o,total_stall_time_ms:i,event_type:e.type,model:a.model,request_id:ae??`unknown`}))}switch(n=c,t&&(U(`Stream started - received first chunk`),u1(`query_first_chunk_received`),a.agentId||AG(`first_chunk`),spt(),t=!1),e.type){case`message_start`:de=e.message,ue=Date.now()-te,me=$7(me,e.message?.usage);break;case`content_block_start`:switch(e.content_block.type){case`tool_use`:fe[e.index]={...e.content_block,input:``};break;case`server_tool_use`:fe[e.index]={...e.content_block,input:``},e.content_block.name===`advisor`&&(Se=!0,U(`[AdvisorTool] Advisor tool called`),J(`tengu_advisor_tool_call`,{model:a.model,advisor_model:u??`unknown`}));break;case`text`:pe.set(e.index,[]),fe[e.index]={...e.content_block,text:``};break;case`thinking`:fe[e.index]={...e.content_block,thinking:``,signature:``};break;default:fe[e.index]={...e.content_block},e.content_block.type===`advisor_tool_result`&&(Se=!1,U(`[AdvisorTool] Advisor tool result received`));break}break;case`content_block_delta`:{let t=fe[e.index],n=e.delta;if(!t)throw J(`tengu_streaming_error`,{error_type:`content_block_not_found_delta`,part_type:e.type,part_index:e.index}),RangeError(`Content block not found`);if(n.type===`connector_text_delta`){if(t.type!==`connector_text`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_connector_text`,expected_type:`connector_text`,actual_type:t.type}),Error(`Content block is not a connector_text block`);t.connector_text+=n.connector_text}else switch(n.type){case`citations_delta`:break;case`input_json_delta`:if(t.type!==`tool_use`&&t.type!==`server_tool_use`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_input_json`,expected_type:`tool_use`,actual_type:t.type}),Error(`Content block is not a input_json block`);if(typeof t.input!=`string`)throw J(`tengu_streaming_error`,{error_type:`content_block_input_not_string`,input_type:typeof t.input}),Error(`Content block input is not a string`);t.input+=n.partial_json;break;case`text_delta`:if(t.type!==`text`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_text`,expected_type:`text`,actual_type:t.type}),Error(`Content block is not a text block`);pe.get(e.index)?.push(n.text);break;case`signature_delta`:if(t.type===`connector_text`){t.signature=n.signature;break}if(t.type!==`thinking`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_thinking_signature`,expected_type:`thinking`,actual_type:t.type}),Error(`Content block is not a thinking block`);t.signature=n.signature;break;case`thinking_delta`:if(t.type!==`thinking`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_thinking_delta`,expected_type:`thinking`,actual_type:t.type}),Error(`Content block is not a thinking block`);t.thinking+=n.thinking;break}break}case`content_block_stop`:{let t=fe[e.index];if(!t)throw J(`tengu_streaming_error`,{error_type:`content_block_not_found_stop`,part_type:e.type,part_index:e.index}),RangeError(`Content block not found`);if(!de)throw J(`tengu_streaming_error`,{error_type:`partial_message_not_found`,part_type:e.type}),Error(`Message not found`);let n=pe.get(e.index);n&&(t.text=n.join(``),pe.delete(e.index));let i={message:{...de,usage:de.usage??{...rc},content:V4([t],r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(i),yield i;break}case`message_delta`:{me=$7(me,e.usage),ge=e.delta.stop_reason;let t=le.at(-1);t&&(t.message.usage=me,t.message.stop_reason=ge);let n=Oo(s,me);he+=SI(n,me,a.model);let r=qIe(e.delta.stop_reason,a.model);r&&(yield r),ge===`max_tokens`&&(J(`tengu_max_tokens_reached`,{max_tokens:ye}),yield A4({content:`${JL}: Claude's response exceeded the ${ye} output token maximum. To configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable.`,apiError:`max_output_tokens`,error:`max_output_tokens`})),ge===`model_context_window_exceeded`&&(J(`tengu_context_window_exceeded`,{max_tokens:ye,output_tokens:me.output_tokens}),yield A4({content:`${JL}: The model has reached its context window limit.`,apiError:`max_output_tokens`,error:`max_output_tokens`}));break}case`message_stop`:break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:ue}:void 0}}if(_(),f){let e=p===null?-1:Math.round(performance.now()-p);throw Ai(`info`,`cli_stream_loop_exited_after_watchdog_clean`),J(`tengu_stream_loop_exited_after_watchdog`,{request_id:ae??`unknown`,exit_delay_ms:e,exit_path:`clean`,model:a.model}),p=null,Error(`Stream idle timeout - no chunks received`)}if(!de||le.length===0&&!ge)throw U(de?`Stream completed with message_start but no content blocks completed - triggering non-streaming fallback`:`Stream completed without receiving message_start event - triggering non-streaming fallback`,{level:`error`}),J(`tengu_stream_no_events`,{model:a.model,request_id:ae??`unknown`}),Error(`Stream ended without receiving any events`);o>0&&(U(`Streaming completed with ${o} stall(s), total stall time: ${(i/1e3).toFixed(1)}s`,{level:`warn`}),J(`tengu_streaming_stall_summary`,{stall_count:o,total_stall_time_ms:i,model:a.model,request_id:ae??`unknown`})),ALe(a.querySource,me.cache_read_input_tokens,me.cache_creation_input_tokens,e,a.agentId,ae);let c=oe;c&&(AIe(c.headers),Vo()===`bedrock`&&_c(`bedrock`,XDt.parseHeaders(c.headers)),be=c.headers)}catch(e){if(_(),f&&p!==null){let t=Math.round(performance.now()-p);Ai(`info`,`cli_stream_loop_exited_after_watchdog_error`),J(`tengu_stream_loop_exited_after_watchdog`,{request_id:ae??`unknown`,exit_delay_ms:t,exit_path:`error`,error_name:e instanceof Error?e.name:`unknown`,model:a.model})}if(e instanceof In)throw i.aborted?(U(`Streaming aborted by user: ${H(e)}`),Se&&J(`tengu_advisor_tool_interrupted`,{model:a.model,advisor_model:u??`unknown`}),e):(U(`Streaming timeout (SDK abort): ${e.message}`,{level:`error`}),new Fn({message:`Request timed out`}));if(m(process.env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK))throw U(`Error streaming (non-streaming fallback disabled): ${H(e)}`,{level:`error`}),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:e instanceof Error?e.name:String(e),attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},fallback_disabled:!0,request_id:ae??`unknown`,fallback_cause:f?`watchdog`:`other`}),e;U(`Error streaming, falling back to non-streaming mode: ${H(e)}`,{level:`error`}),_e=!0,a.onStreamingFallback&&a.onStreamingFallback(),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:e instanceof Error?e.name:String(e),attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},fallback_disabled:!1,request_id:ae??`unknown`,fallback_cause:f?`watchdog`:`other`}),Ai(`info`,`cli_nonstreaming_fallback_started`),J(`tengu_nonstreaming_fallback_started`,{request_id:ae??`unknown`,model:a.model,fallback_cause:f?`watchdog`:`other`});let t=yield*bOt({model:a.model,source:a.querySource},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()&&{fastMode:T},signal:i,initialConsecutive529Errors:+!!lR(e),querySource:a.querySource},N,(e,t,n)=>{ne=e,ye=n},e=>Zi(e,a.querySource),ae),o={message:{...t,content:V4(t.content,r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(o),ve=o,yield o}finally{_()}}catch(t){if(t instanceof _R)throw t;if(!_e&&t instanceof gR&&t.originalError instanceof Pn&&t.originalError.status===404){let s=t.originalError.requestID??`unknown`;U(`Streaming endpoint returned 404, falling back to non-streaming mode`,{level:`warn`}),_e=!0,a.onStreamingFallback&&a.onStreamingFallback(),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:`404_stream_creation`,attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},request_id:s,fallback_cause:`404_stream_creation`});try{let e=yield*bOt({model:a.model,source:a.querySource},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()&&{fastMode:T},signal:i},N,(e,t,n)=>{ne=e,ye=n},e=>Zi(e,a.querySource),s),t={message:{...e,content:V4(e.content,r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(t),ve=t,yield t}catch(t){if(t instanceof _R)throw t;U(`Non-streaming fallback also failed: ${H(t)}`,{level:`error`});let n=t,r=a.model;t instanceof gR&&(n=t.originalError,r=t.retryContext.model),n instanceof Pn&&zL(n);let i=ae||(n instanceof Pn?n.requestID:void 0)||(n instanceof Pn?n.error?.request_id:void 0);if(aOt({error:n,model:r,messageCount:y.length,messageTokens:xR(y),durationMs:Date.now()-te,durationMsIncludingRetries:Date.now()-ee,attempt:ne,requestId:i,clientRequestId:j,didFallBackToNonStreaming:_e,queryTracking:a.queryTracking,querySource:a.querySource,llmSpan:A,fastMode:xe,previousRequestId:o}),n instanceof In){se();return}yield qL(n,r,{messages:e,messagesForAPI:y}),se();return}}else{U(`Error in API request: ${H(t)}`,{level:`error`});let n=t,r=a.model;t instanceof gR&&(n=t.originalError,r=t.retryContext.model),n instanceof Pn&&zL(n);let i=ae||(n instanceof Pn?n.requestID:void 0)||(n instanceof Pn?n.error?.request_id:void 0);if(aOt({error:n,model:r,messageCount:y.length,messageTokens:xR(y),durationMs:Date.now()-te,durationMsIncludingRetries:Date.now()-ee,attempt:ne,requestId:i,clientRequestId:j,didFallBackToNonStreaming:_e,queryTracking:a.queryTracking,querySource:a.querySource,llmSpan:A,fastMode:xe,previousRequestId:o}),n instanceof In){se();return}yield qL(n,r,{messages:e,messagesForAPI:y}),se();return}}finally{if(Vse(`api_call`),se(),ve){let e=ve.message.usage;me=$7(rc,e),ge=ve.message.stop_reason;let t=Oo(s,e);he+=SI(t,e,a.model)}}ae&&!Ec()&&(a.querySource.startsWith(`repl_main_thread`)||a.querySource===`sdk`)&&Gte(ae);let P=y.length,Ce=xR(y);a.getToolPermissionContext().then(e=>{sOt({model:le[0]?.message.model??de?.model??a.model,preNormalizedModel:a.model,usage:me,start:te,startIncludingRetries:ee,attempt:ne,messageCount:P,messageTokens:Ce,requestId:ae??null,stopReason:ge,ttftMs:ue,didFallBackToNonStreaming:_e,querySource:a.querySource,headers:be,costUSD:he,queryTracking:a.queryTracking,permissionMode:e.mode,newMessages:le,llmSpan:A,globalCacheStrategy:_,requestSetupMs:te-ee,attemptStartTimes:re,fastMode:xe,previousRequestId:o,betas:M})}),se()}function TOt(e){if(e)try{e.controller.signal.aborted||e.controller.abort()}catch{}}function $7(e,t){return t?{input_tokens:t.input_tokens!==null&&t.input_tokens>0?t.input_tokens:e.input_tokens,cache_creation_input_tokens:t.cache_creation_input_tokens!==null&&t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:e.cache_creation_input_tokens,cache_read_input_tokens:t.cache_read_input_tokens!==null&&t.cache_read_input_tokens>0?t.cache_read_input_tokens:e.cache_read_input_tokens,output_tokens:t.output_tokens??e.output_tokens,server_tool_use:{web_search_requests:t.server_tool_use?.web_search_requests??e.server_tool_use.web_search_requests,web_fetch_requests:t.server_tool_use?.web_fetch_requests??e.server_tool_use.web_fetch_requests},service_tier:e.service_tier,cache_creation:{ephemeral_1h_input_tokens:t.cache_creation?.ephemeral_1h_input_tokens??e.cache_creation.ephemeral_1h_input_tokens,ephemeral_5m_input_tokens:t.cache_creation?.ephemeral_5m_input_tokens??e.cache_creation.ephemeral_5m_input_tokens},inference_geo:e.inference_geo,iterations:t.iterations??e.iterations,speed:t.speed??e.speed}:{...e}}function EOt(e,t){return{input_tokens:e.input_tokens+t.input_tokens,cache_creation_input_tokens:e.cache_creation_input_tokens+t.cache_creation_input_tokens,cache_read_input_tokens:e.cache_read_input_tokens+t.cache_read_input_tokens,output_tokens:e.output_tokens+t.output_tokens,server_tool_use:{web_search_requests:e.server_tool_use.web_search_requests+t.server_tool_use.web_search_requests,web_fetch_requests:e.server_tool_use.web_fetch_requests+t.server_tool_use.web_fetch_requests},service_tier:t.service_tier,cache_creation:{ephemeral_1h_input_tokens:e.cache_creation.ephemeral_1h_input_tokens+t.cache_creation.ephemeral_1h_input_tokens,ephemeral_5m_input_tokens:e.cache_creation.ephemeral_5m_input_tokens+t.cache_creation.ephemeral_5m_input_tokens},inference_geo:t.inference_geo,iterations:t.iterations,speed:t.speed}}function DOt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`tool_use_id`in e}function OOt(e,t,n,r=!1,i,a,o=!1){J(`tengu_api_cache_breakpoints`,{totalMessageCount:e.length,cachingEnabled:t,skipCacheWrite:o});let s=o?e.length-2:e.length-1,c=e.map((e,r)=>{let i=r===s;return e.type===`user`?hOt(e,i,t,n):gOt(e,i,t,n)});if(!r)return c;let l=new Set,u=e=>{let t=e.edits.filter(e=>l.has(e.cache_reference)?!1:(l.add(e.cache_reference),!0));return{...e,edits:t}};for(let e of a??[]){let t=c[e.userMessageIndex];if(t&&t.role===`user`){Array.isArray(t.content)||(t.content=[{type:`text`,text:t.content}]);let n=u(e.block);n.edits.length>0&&QDt(t.content,n)}}if(i&&c.length>0){let e=u(i);if(e.edits.length>0)for(let t=c.length-1;t>=0;t--){let n=c[t];if(n&&n.role===`user`){Array.isArray(n.content)||(n.content=[{type:`text`,text:n.content}]),QDt(n.content,e),U(`Added cache_edits block with ${e.edits.length} deletion(s) to message[${t}]: ${e.edits.map(e=>e.cache_reference).join(`, `)}`);break}}}if(t){let e=-1;for(let t=0;t<c.length;t++){let n=c[t];if(Array.isArray(n.content))for(let r of n.content)r&&typeof r==`object`&&`cache_control`in r&&(e=t)}if(e>=0)for(let t=0;t<e;t++){let e=c[t];if(e.role!==`user`||!Array.isArray(e.content))continue;let n=!1;for(let t=0;t<e.content.length;t++){let r=e.content[t];r&&DOt(r)&&(n||(e.content=[...e.content],n=!0),e.content[t]=Object.assign({},r,{cache_reference:r.tool_use_id}))}}}return c}function kOt(e,t,n){return BDt(e,{skipGlobalCacheForSystemPrompt:n?.skipGlobalCacheForSystemPrompt}).map(e=>({type:`text`,text:e.text,...t&&e.cacheScope!==null&&{cache_control:Y7({scope:e.cacheScope,querySource:n?.querySource})}}))}async function e9({systemPrompt:e=Qs([]),userPrompt:t,outputFormat:n,signal:r,options:i}){return(await Ixt([$({content:e.map(e=>({type:`text`,text:e}))}),$({content:t})],async()=>[await Z7({messages:[$({content:t})],systemPrompt:e,thinkingConfig:{type:`disabled`},tools:[],signal:r,options:{...i,model:zo(),enablePromptCaching:i.enablePromptCaching??!1,outputFormat:n,async getToolPermissionContext(){return _se()}}})]))[0]}function AOt(e,t){let n=Math.min(e.max_tokens,t),r={...e};return r.thinking?.type===`enabled`&&r.thinking.budget_tokens&&(r.thinking={...r.thinking,budget_tokens:Math.min(r.thinking.budget_tokens,n-1)}),{...r,max_tokens:n}}function jOt(){return!1}function t9(e){let t=Do(e),n=jOt()?Math.min(t.default,Tae):t.default;return fv(`CLAUDE_CODE_MAX_OUTPUT_TOKENS`,process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS,n,t.upperLimit).effective}var n9,MOt,r9=n((()=>{Jo(),wd(),Ks(),Wfe(),W7(),no(),Uo(),bi(),ho(),h(),On(),Qi(),m3(),No(),BI(),tce(),CR(),UL(),YDt(),ZDt(),gce(),cL(),Tne(),Wt(),Bo(),CI(),Ng(),Sc(),W(),Ei(),Ro(),g1(),IG(),Ao(),h1(),iq(),vz(),G_(),zs(),$Dt(),pv(),wa(),Mo(),ac(),Yn(),Pc(),Da(),UR(),qH(),Wxt(),xo(),aR(),uOt(),OR(),vR(),n9=new Set,MOt=64e3}));function NOt(e){let{toolName:t,policySpec:n,eventName:r,querySource:i,preCheck:a}=e,o=aa((e,s,c)=>{let l=FOt(e,s,c,t,n,r,i,a);return l.catch(()=>{o.cache.get(e)===l&&o.cache.delete(e)}),l},e=>e,200);return o}function POt(e,t){let n=aa((r,i,a)=>{let o=IOt(r,i,a,e,t);return o.catch(()=>{n.cache.get(r)===o&&n.cache.delete(r)}),o},e=>e,200);return n}async function FOt(e,t,n,r,i,a,o,s){if(s){let t=s(e);if(t!==null)return t}let c,l=Date.now(),u=null;try{c=setTimeout((e,t)=>{let n=`[${e}Tool] Pre-flight check is taking longer than expected. Run with ANTHROPIC_LOG=debug to check for failed or slow API requests.`;t?process.stderr.write(`${V({level:`warn`,message:n})}\n`):console.warn(Ue.yellow(`⚠️ ${n}`))},1e4,r,n);let s=await e9({systemPrompt:Qs([`Your task is to process ${r} commands that an AI coding agent wants to run.\n\nThis policy spec defines how to determine the prefix of a ${r} command:`]),userPrompt:`${i}\n\nCommand: ${e}`,signal:t,options:{enablePromptCaching:!1,querySource:o,agents:[],isNonInteractiveSession:n,hasAppendSystemPrompt:!1,mcpTools:[]}});clearTimeout(c);let d=Date.now()-l,f=typeof s.message.content==`string`?s.message.content:Array.isArray(s.message.content)?s.message.content.find(e=>e.type===`text`)?.text??`none`:`none`;return GL(f)?(J(a,{success:!1,error:`API error`,durationMs:d}),u=null):f===`command_injection_detected`?(J(a,{success:!1,error:`command_injection_detected`,durationMs:d}),u={commandPrefix:null}):f===`git`||LOt.has(f.toLowerCase())?(J(a,{success:!1,error:`dangerous_shell_prefix`,durationMs:d}),u={commandPrefix:null}):f===`none`?(J(a,{success:!1,error:`prefix "none"`,durationMs:d}),u={commandPrefix:null}):e.startsWith(f)?(J(a,{success:!0,durationMs:d}),u={commandPrefix:f}):(J(a,{success:!1,error:`command did not start with prefix`,durationMs:d}),u={commandPrefix:null}),u}catch(e){throw clearTimeout(c),e}}async function IOt(e,t,n,r,i){let a=await i(e),[o,...s]=await Promise.all([r(e,t,n),...a.map(async e=>({subcommand:e,prefix:await r(e,t,n)}))]);if(!o)return null;let c=s.reduce((e,{subcommand:t,prefix:n})=>(n&&e.set(t,n),e),new Map);return{...o,subcommandPrefixes:c}}var LOt,ROt=n((()=>{Ge(),Da(),r9(),aR(),oa(),Yn(),BI(),LOt=new Set([`sh`,`bash`,`zsh`,`fish`,`csh`,`tcsh`,`ksh`,`dash`,`cmd`,`cmd.exe`,`powershell`,`powershell.exe`,`pwsh`,`pwsh.exe`,`bash.exe`])}));function zOt(){let e=yl(8).toString(`hex`);return{SINGLE_QUOTE:`__SINGLE_QUOTE_${e}__`,DOUBLE_QUOTE:`__DOUBLE_QUOTE_${e}__`,NEW_LINE:`__NEW_LINE_${e}__`,ESCAPED_OPEN_PAREN:`__ESCAPED_OPEN_PAREN_${e}__`,ESCAPED_CLOSE_PAREN:`__ESCAPED_CLOSE_PAREN_${e}__`}}function BOt(e){return/[\s'"]/.test(e)||e.length===0||e.startsWith(`#`)?!1:!e.startsWith(`!`)&&!e.startsWith(`=`)&&!e.includes(`$`)&&!e.includes("`")&&!e.includes(`*`)&&!e.includes(`?`)&&!e.includes(`[`)&&!e.includes(`{`)&&!e.includes(`~`)&&!e.includes(`(`)&&!e.includes(`<`)&&!e.startsWith(`&`)}function i9(e){let t=[],n=zOt(),{processedCommand:r,heredocs:i}=xU(e),a=r.replace(/\\+\n/g,e=>{let t=e.length-1;return t%2==1?`\\`.repeat(t-1):e}),o=e.replace(/\\+\n/g,e=>{let t=e.length-1;return t%2==1?`\\`.repeat(t-1):e}),s=uc(a.replaceAll(`"`,`"${n.DOUBLE_QUOTE}`).replaceAll(`'`,`'${n.SINGLE_QUOTE}`).replaceAll(`
3391
+ `),querySource:a.querySource,tools:V(w)}:void 0,A=zce(a.model,k,y,T),ee=Date.now(),te=Date.now(),ne=0,re=[],ie,ae,j,oe;function se(){TOt(ie),ie=void 0,oe&&(oe.body?.cancel().catch(()=>{}),oe=void 0)}let ce=[],M,N=e=>{let t=[...l];!t.includes(`context-1m-2025-08-07`)&&Dae(e.model)&&t.push(eoe);let r=J7(Vo()===`bedrock`?[...xae(e.model)]:[]),i={...r.output_config??{}};pOt(a.taskBudget,i,t),a.outputFormat&&!(`format`in i)&&(i.format=a.outputFormat,yae(a.model)&&!t.includes(`structured-outputs-2025-12-15`)&&t.push(Iae));let o=e?.maxTokensOverride||a.maxOutputTokensOverride||t9(a.model),s=n.type!==`disabled`&&!m(process.env.CLAUDE_CODE_DISABLE_THINKING),u;if(s&&i6e(a.model))if(!m(process.env.CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING)&&a6e(a.model))u={type:`adaptive`};else{let e=pae(a.model);n.type===`enabled`&&n.budgetTokens!==void 0&&(e=n.budgetTokens),e=Math.min(o-1,e),u={budget_tokens:e,type:`enabled`}}let d=KDt({hasThinking:s,isRedactThinkingActive:t.includes(Nae),clearAllThinking:!1}),f=a.enablePromptCaching??dOt(e.model),p;Xo()&&noe()&&!qo()&&Vae(a.model)&&e.fastMode&&(p=`fast`),D&&!t.includes(`fast-mode-2026-02-01`)&&t.push(Wae),E&&yo()&&c&&!t.includes(``)&&t.push(``);let h=s?void 0:a.temperatureOverride??1,g=t.filter(Boolean);return M=g,{model:So(a.model),messages:OOt(y,f,a.querySource,!1,null,ce,a.skipCacheWrite),system:x,tools:w,tool_choice:a.toolChoice,...S&&{betas:g},metadata:X7(),max_tokens:o,thinking:u,...h!==void 0&&{temperature:h},...d&&S&&t.includes(`context-management-2025-06-27`)&&{context_management:d},...r,...Object.keys(i).length>0&&{output_config:i},...p!==void 0&&{speed:p}}};{let e=N({model:a.model,thinkingConfig:n}),t=e.messages.length,r=S?e.betas??[]:[];a.getToolPermissionContext().then(e=>{iOt({model:a.model,messagesLength:t,temperature:a.temperatureOverride??1,betas:r,permissionMode:e.mode,querySource:a.querySource,queryTracking:a.queryTracking,thinkingConfig:n,fastMode:T,previousRequestId:o})})}let le=[],ue=0,de,fe=[],pe=new Map,me=rc,he=0,ge=null,_e=!1,ve,ye=0,be,xe=T,Se=!1;try{u1(`query_client_creation_start`);let t=sR(()=>jo({maxRetries:0,model:a.model,fetchOverride:a.fetchOverride,source:a.querySource}),async(e,t,n)=>{ne=t,xe=n.fastMode??!1,te=Date.now(),re.push(te),u1(`query_client_creation_end`);let r=N(n);Zi(r,a.querySource),ye=r.max_tokens,u1(`query_api_request_sent`),a.agentId||AG(`api_request_sent`),j=Vo()===`firstParty`&&Zo()?bl():void 0;let o=await e.beta.messages.create({...r,stream:!0},{signal:i,...j&&{headers:{"x-client-request-id":j}}}).withResponse();return u1(`query_response_headers_received`),ae=o.request_id,oe=o.response,o.data},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()?{fastMode:T}:!1,signal:i,querySource:a.querySource}),o;do o=await t.next(),`controller`in o.value||(yield o.value);while(!o.done);ie=o.value,le.length=0,ue=0,de=void 0,fe.length=0,pe.clear(),me=rc,ge=null,Se=!1;let c=m(process.env.CLAUDE_ENABLE_STREAM_WATCHDOG),l=parseInt(process.env.CLAUDE_STREAM_IDLE_TIMEOUT_MS||``,10)||9e4,d=l/2,f=!1,p=null,h=null,g=null;function _(){h!==null&&(clearTimeout(h),h=null),g!==null&&(clearTimeout(g),g=null)}function v(){_(),c&&(h=setTimeout(e=>{U(`Streaming idle warning: no chunks received for ${e/1e3}s`,{level:`warn`}),Ai(`warn`,`cli_streaming_idle_warning`)},d,d),g=setTimeout(()=>{f=!0,p=performance.now(),U(`Streaming idle timeout: no chunks received for ${l/1e3}s, aborting stream`,{level:`error`}),Ai(`error`,`cli_streaming_idle_timeout`),J(`tengu_streaming_idle_timeout`,{model:a.model,request_id:ae??`unknown`,timeout_ms:l}),se()},l))}v(),Use(`api_call`);try{let t=!0,n=null,i=0,o=0;for await(let e of ie){v();let c=Date.now();if(n!==null){let t=c-n;t>3e4&&(o++,i+=t,U(`Streaming stall detected: ${(t/1e3).toFixed(1)}s gap between events (stall #${o})`,{level:`warn`}),J(`tengu_streaming_stall`,{stall_duration_ms:t,stall_count:o,total_stall_time_ms:i,event_type:e.type,model:a.model,request_id:ae??`unknown`}))}switch(n=c,t&&(U(`Stream started - received first chunk`),u1(`query_first_chunk_received`),a.agentId||AG(`first_chunk`),spt(),t=!1),e.type){case`message_start`:de=e.message,ue=Date.now()-te,me=$7(me,e.message?.usage);break;case`content_block_start`:switch(e.content_block.type){case`tool_use`:fe[e.index]={...e.content_block,input:``};break;case`server_tool_use`:fe[e.index]={...e.content_block,input:``},e.content_block.name===`advisor`&&(Se=!0,U(`[AdvisorTool] Advisor tool called`),J(`tengu_advisor_tool_call`,{model:a.model,advisor_model:u??`unknown`}));break;case`text`:pe.set(e.index,[]),fe[e.index]={...e.content_block,text:``};break;case`thinking`:fe[e.index]={...e.content_block,thinking:``,signature:``};break;default:fe[e.index]={...e.content_block},e.content_block.type===`advisor_tool_result`&&(Se=!1,U(`[AdvisorTool] Advisor tool result received`));break}break;case`content_block_delta`:{let t=fe[e.index],n=e.delta;if(!t)throw J(`tengu_streaming_error`,{error_type:`content_block_not_found_delta`,part_type:e.type,part_index:e.index}),RangeError(`Content block not found`);if(n.type===`connector_text_delta`){if(t.type!==`connector_text`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_connector_text`,expected_type:`connector_text`,actual_type:t.type}),Error(`Content block is not a connector_text block`);t.connector_text+=n.connector_text}else switch(n.type){case`citations_delta`:break;case`input_json_delta`:if(t.type!==`tool_use`&&t.type!==`server_tool_use`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_input_json`,expected_type:`tool_use`,actual_type:t.type}),Error(`Content block is not a input_json block`);if(typeof t.input!=`string`)throw J(`tengu_streaming_error`,{error_type:`content_block_input_not_string`,input_type:typeof t.input}),Error(`Content block input is not a string`);t.input+=n.partial_json;break;case`text_delta`:if(t.type!==`text`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_text`,expected_type:`text`,actual_type:t.type}),Error(`Content block is not a text block`);pe.get(e.index)?.push(n.text);break;case`signature_delta`:if(t.type===`connector_text`){t.signature=n.signature;break}if(t.type!==`thinking`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_thinking_signature`,expected_type:`thinking`,actual_type:t.type}),Error(`Content block is not a thinking block`);t.signature=n.signature;break;case`thinking_delta`:if(t.type!==`thinking`)throw J(`tengu_streaming_error`,{error_type:`content_block_type_mismatch_thinking_delta`,expected_type:`thinking`,actual_type:t.type}),Error(`Content block is not a thinking block`);t.thinking+=n.thinking;break}break}case`content_block_stop`:{let t=fe[e.index];if(!t)throw J(`tengu_streaming_error`,{error_type:`content_block_not_found_stop`,part_type:e.type,part_index:e.index}),RangeError(`Content block not found`);if(!de)throw J(`tengu_streaming_error`,{error_type:`partial_message_not_found`,part_type:e.type}),Error(`Message not found`);let n=pe.get(e.index);n&&(t.text=n.join(``),pe.delete(e.index));let i={message:{...de,usage:de.usage??{...rc},content:V4([t],r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(i),yield i;break}case`message_delta`:{me=$7(me,e.usage),ge=e.delta.stop_reason;let t=le.at(-1);t&&(t.message.usage=me,t.message.stop_reason=ge);let n=Oo(s,me);he+=SI(n,me,a.model);let r=qIe(e.delta.stop_reason,a.model);r&&(yield r),ge===`max_tokens`&&(J(`tengu_max_tokens_reached`,{max_tokens:ye}),yield A4({content:`${JL}: Work Mate's response exceeded the ${ye} output token maximum. To configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable.`,apiError:`max_output_tokens`,error:`max_output_tokens`})),ge===`model_context_window_exceeded`&&(J(`tengu_context_window_exceeded`,{max_tokens:ye,output_tokens:me.output_tokens}),yield A4({content:`${JL}: The model has reached its context window limit.`,apiError:`max_output_tokens`,error:`max_output_tokens`}));break}case`message_stop`:break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:ue}:void 0}}if(_(),f){let e=p===null?-1:Math.round(performance.now()-p);throw Ai(`info`,`cli_stream_loop_exited_after_watchdog_clean`),J(`tengu_stream_loop_exited_after_watchdog`,{request_id:ae??`unknown`,exit_delay_ms:e,exit_path:`clean`,model:a.model}),p=null,Error(`Stream idle timeout - no chunks received`)}if(!de||le.length===0&&!ge)throw U(de?`Stream completed with message_start but no content blocks completed - triggering non-streaming fallback`:`Stream completed without receiving message_start event - triggering non-streaming fallback`,{level:`error`}),J(`tengu_stream_no_events`,{model:a.model,request_id:ae??`unknown`}),Error(`Stream ended without receiving any events`);o>0&&(U(`Streaming completed with ${o} stall(s), total stall time: ${(i/1e3).toFixed(1)}s`,{level:`warn`}),J(`tengu_streaming_stall_summary`,{stall_count:o,total_stall_time_ms:i,model:a.model,request_id:ae??`unknown`})),ALe(a.querySource,me.cache_read_input_tokens,me.cache_creation_input_tokens,e,a.agentId,ae);let c=oe;c&&(AIe(c.headers),Vo()===`bedrock`&&_c(`bedrock`,XDt.parseHeaders(c.headers)),be=c.headers)}catch(e){if(_(),f&&p!==null){let t=Math.round(performance.now()-p);Ai(`info`,`cli_stream_loop_exited_after_watchdog_error`),J(`tengu_stream_loop_exited_after_watchdog`,{request_id:ae??`unknown`,exit_delay_ms:t,exit_path:`error`,error_name:e instanceof Error?e.name:`unknown`,model:a.model})}if(e instanceof In)throw i.aborted?(U(`Streaming aborted by user: ${H(e)}`),Se&&J(`tengu_advisor_tool_interrupted`,{model:a.model,advisor_model:u??`unknown`}),e):(U(`Streaming timeout (SDK abort): ${e.message}`,{level:`error`}),new Fn({message:`Request timed out`}));if(m(process.env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK))throw U(`Error streaming (non-streaming fallback disabled): ${H(e)}`,{level:`error`}),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:e instanceof Error?e.name:String(e),attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},fallback_disabled:!0,request_id:ae??`unknown`,fallback_cause:f?`watchdog`:`other`}),e;U(`Error streaming, falling back to non-streaming mode: ${H(e)}`,{level:`error`}),_e=!0,a.onStreamingFallback&&a.onStreamingFallback(),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:e instanceof Error?e.name:String(e),attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},fallback_disabled:!1,request_id:ae??`unknown`,fallback_cause:f?`watchdog`:`other`}),Ai(`info`,`cli_nonstreaming_fallback_started`),J(`tengu_nonstreaming_fallback_started`,{request_id:ae??`unknown`,model:a.model,fallback_cause:f?`watchdog`:`other`});let t=yield*bOt({model:a.model,source:a.querySource},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()&&{fastMode:T},signal:i,initialConsecutive529Errors:+!!lR(e),querySource:a.querySource},N,(e,t,n)=>{ne=e,ye=n},e=>Zi(e,a.querySource),ae),o={message:{...t,content:V4(t.content,r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(o),ve=o,yield o}finally{_()}}catch(t){if(t instanceof _R)throw t;if(!_e&&t instanceof gR&&t.originalError instanceof Pn&&t.originalError.status===404){let s=t.originalError.requestID??`unknown`;U(`Streaming endpoint returned 404, falling back to non-streaming mode`,{level:`warn`}),_e=!0,a.onStreamingFallback&&a.onStreamingFallback(),J(`tengu_streaming_fallback_to_non_streaming`,{model:a.model,error:`404_stream_creation`,attemptNumber:ne,maxOutputTokens:ye,thinkingType:n.type,...n.type===`enabled`&&{thinkingBudgetTokens:n.budgetTokens},request_id:s,fallback_cause:`404_stream_creation`});try{let e=yield*bOt({model:a.model,source:a.querySource},{model:a.model,fallbackModel:a.fallbackModel,thinkingConfig:n,...Xo()&&{fastMode:T},signal:i},N,(e,t,n)=>{ne=e,ye=n},e=>Zi(e,a.querySource),s),t={message:{...e,content:V4(e.content,r,a.agentId)},requestId:ae??void 0,type:`assistant`,uuid:bl(),timestamp:new Date().toISOString(),...u&&{advisorModel:u}};le.push(t),ve=t,yield t}catch(t){if(t instanceof _R)throw t;U(`Non-streaming fallback also failed: ${H(t)}`,{level:`error`});let n=t,r=a.model;t instanceof gR&&(n=t.originalError,r=t.retryContext.model),n instanceof Pn&&zL(n);let i=ae||(n instanceof Pn?n.requestID:void 0)||(n instanceof Pn?n.error?.request_id:void 0);if(aOt({error:n,model:r,messageCount:y.length,messageTokens:xR(y),durationMs:Date.now()-te,durationMsIncludingRetries:Date.now()-ee,attempt:ne,requestId:i,clientRequestId:j,didFallBackToNonStreaming:_e,queryTracking:a.queryTracking,querySource:a.querySource,llmSpan:A,fastMode:xe,previousRequestId:o}),n instanceof In){se();return}yield qL(n,r,{messages:e,messagesForAPI:y}),se();return}}else{U(`Error in API request: ${H(t)}`,{level:`error`});let n=t,r=a.model;t instanceof gR&&(n=t.originalError,r=t.retryContext.model),n instanceof Pn&&zL(n);let i=ae||(n instanceof Pn?n.requestID:void 0)||(n instanceof Pn?n.error?.request_id:void 0);if(aOt({error:n,model:r,messageCount:y.length,messageTokens:xR(y),durationMs:Date.now()-te,durationMsIncludingRetries:Date.now()-ee,attempt:ne,requestId:i,clientRequestId:j,didFallBackToNonStreaming:_e,queryTracking:a.queryTracking,querySource:a.querySource,llmSpan:A,fastMode:xe,previousRequestId:o}),n instanceof In){se();return}yield qL(n,r,{messages:e,messagesForAPI:y}),se();return}}finally{if(Vse(`api_call`),se(),ve){let e=ve.message.usage;me=$7(rc,e),ge=ve.message.stop_reason;let t=Oo(s,e);he+=SI(t,e,a.model)}}ae&&!Ec()&&(a.querySource.startsWith(`repl_main_thread`)||a.querySource===`sdk`)&&Gte(ae);let P=y.length,Ce=xR(y);a.getToolPermissionContext().then(e=>{sOt({model:le[0]?.message.model??de?.model??a.model,preNormalizedModel:a.model,usage:me,start:te,startIncludingRetries:ee,attempt:ne,messageCount:P,messageTokens:Ce,requestId:ae??null,stopReason:ge,ttftMs:ue,didFallBackToNonStreaming:_e,querySource:a.querySource,headers:be,costUSD:he,queryTracking:a.queryTracking,permissionMode:e.mode,newMessages:le,llmSpan:A,globalCacheStrategy:_,requestSetupMs:te-ee,attemptStartTimes:re,fastMode:xe,previousRequestId:o,betas:M})}),se()}function TOt(e){if(e)try{e.controller.signal.aborted||e.controller.abort()}catch{}}function $7(e,t){return t?{input_tokens:t.input_tokens!==null&&t.input_tokens>0?t.input_tokens:e.input_tokens,cache_creation_input_tokens:t.cache_creation_input_tokens!==null&&t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:e.cache_creation_input_tokens,cache_read_input_tokens:t.cache_read_input_tokens!==null&&t.cache_read_input_tokens>0?t.cache_read_input_tokens:e.cache_read_input_tokens,output_tokens:t.output_tokens??e.output_tokens,server_tool_use:{web_search_requests:t.server_tool_use?.web_search_requests??e.server_tool_use.web_search_requests,web_fetch_requests:t.server_tool_use?.web_fetch_requests??e.server_tool_use.web_fetch_requests},service_tier:e.service_tier,cache_creation:{ephemeral_1h_input_tokens:t.cache_creation?.ephemeral_1h_input_tokens??e.cache_creation.ephemeral_1h_input_tokens,ephemeral_5m_input_tokens:t.cache_creation?.ephemeral_5m_input_tokens??e.cache_creation.ephemeral_5m_input_tokens},inference_geo:e.inference_geo,iterations:t.iterations??e.iterations,speed:t.speed??e.speed}:{...e}}function EOt(e,t){return{input_tokens:e.input_tokens+t.input_tokens,cache_creation_input_tokens:e.cache_creation_input_tokens+t.cache_creation_input_tokens,cache_read_input_tokens:e.cache_read_input_tokens+t.cache_read_input_tokens,output_tokens:e.output_tokens+t.output_tokens,server_tool_use:{web_search_requests:e.server_tool_use.web_search_requests+t.server_tool_use.web_search_requests,web_fetch_requests:e.server_tool_use.web_fetch_requests+t.server_tool_use.web_fetch_requests},service_tier:t.service_tier,cache_creation:{ephemeral_1h_input_tokens:e.cache_creation.ephemeral_1h_input_tokens+t.cache_creation.ephemeral_1h_input_tokens,ephemeral_5m_input_tokens:e.cache_creation.ephemeral_5m_input_tokens+t.cache_creation.ephemeral_5m_input_tokens},inference_geo:t.inference_geo,iterations:t.iterations,speed:t.speed}}function DOt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`tool_use_id`in e}function OOt(e,t,n,r=!1,i,a,o=!1){J(`tengu_api_cache_breakpoints`,{totalMessageCount:e.length,cachingEnabled:t,skipCacheWrite:o});let s=o?e.length-2:e.length-1,c=e.map((e,r)=>{let i=r===s;return e.type===`user`?hOt(e,i,t,n):gOt(e,i,t,n)});if(!r)return c;let l=new Set,u=e=>{let t=e.edits.filter(e=>l.has(e.cache_reference)?!1:(l.add(e.cache_reference),!0));return{...e,edits:t}};for(let e of a??[]){let t=c[e.userMessageIndex];if(t&&t.role===`user`){Array.isArray(t.content)||(t.content=[{type:`text`,text:t.content}]);let n=u(e.block);n.edits.length>0&&QDt(t.content,n)}}if(i&&c.length>0){let e=u(i);if(e.edits.length>0)for(let t=c.length-1;t>=0;t--){let n=c[t];if(n&&n.role===`user`){Array.isArray(n.content)||(n.content=[{type:`text`,text:n.content}]),QDt(n.content,e),U(`Added cache_edits block with ${e.edits.length} deletion(s) to message[${t}]: ${e.edits.map(e=>e.cache_reference).join(`, `)}`);break}}}if(t){let e=-1;for(let t=0;t<c.length;t++){let n=c[t];if(Array.isArray(n.content))for(let r of n.content)r&&typeof r==`object`&&`cache_control`in r&&(e=t)}if(e>=0)for(let t=0;t<e;t++){let e=c[t];if(e.role!==`user`||!Array.isArray(e.content))continue;let n=!1;for(let t=0;t<e.content.length;t++){let r=e.content[t];r&&DOt(r)&&(n||(e.content=[...e.content],n=!0),e.content[t]=Object.assign({},r,{cache_reference:r.tool_use_id}))}}}return c}function kOt(e,t,n){return BDt(e,{skipGlobalCacheForSystemPrompt:n?.skipGlobalCacheForSystemPrompt}).map(e=>({type:`text`,text:e.text,...t&&e.cacheScope!==null&&{cache_control:Y7({scope:e.cacheScope,querySource:n?.querySource})}}))}async function e9({systemPrompt:e=Qs([]),userPrompt:t,outputFormat:n,signal:r,options:i}){return(await Ixt([$({content:e.map(e=>({type:`text`,text:e}))}),$({content:t})],async()=>[await Z7({messages:[$({content:t})],systemPrompt:e,thinkingConfig:{type:`disabled`},tools:[],signal:r,options:{...i,model:zo(),enablePromptCaching:i.enablePromptCaching??!1,outputFormat:n,async getToolPermissionContext(){return _se()}}})]))[0]}function AOt(e,t){let n=Math.min(e.max_tokens,t),r={...e};return r.thinking?.type===`enabled`&&r.thinking.budget_tokens&&(r.thinking={...r.thinking,budget_tokens:Math.min(r.thinking.budget_tokens,n-1)}),{...r,max_tokens:n}}function jOt(){return!1}function t9(e){let t=Do(e),n=jOt()?Math.min(t.default,Tae):t.default;return fv(`CLAUDE_CODE_MAX_OUTPUT_TOKENS`,process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS,n,t.upperLimit).effective}var n9,MOt,r9=n((()=>{Jo(),wd(),Ks(),Wfe(),W7(),no(),Uo(),bi(),ho(),h(),On(),Qi(),m3(),No(),BI(),tce(),CR(),UL(),YDt(),ZDt(),gce(),cL(),Tne(),Wt(),Bo(),CI(),Ng(),Sc(),W(),Ei(),Ro(),g1(),IG(),Ao(),h1(),iq(),vz(),G_(),zs(),$Dt(),pv(),wa(),Mo(),ac(),Yn(),Pc(),Da(),UR(),qH(),Wxt(),xo(),aR(),uOt(),OR(),vR(),n9=new Set,MOt=64e3}));function NOt(e){let{toolName:t,policySpec:n,eventName:r,querySource:i,preCheck:a}=e,o=aa((e,s,c)=>{let l=FOt(e,s,c,t,n,r,i,a);return l.catch(()=>{o.cache.get(e)===l&&o.cache.delete(e)}),l},e=>e,200);return o}function POt(e,t){let n=aa((r,i,a)=>{let o=IOt(r,i,a,e,t);return o.catch(()=>{n.cache.get(r)===o&&n.cache.delete(r)}),o},e=>e,200);return n}async function FOt(e,t,n,r,i,a,o,s){if(s){let t=s(e);if(t!==null)return t}let c,l=Date.now(),u=null;try{c=setTimeout((e,t)=>{let n=`[${e}Tool] Pre-flight check is taking longer than expected. Run with ANTHROPIC_LOG=debug to check for failed or slow API requests.`;t?process.stderr.write(`${V({level:`warn`,message:n})}\n`):console.warn(Ue.yellow(`⚠️ ${n}`))},1e4,r,n);let s=await e9({systemPrompt:Qs([`Your task is to process ${r} commands that an AI coding agent wants to run.\n\nThis policy spec defines how to determine the prefix of a ${r} command:`]),userPrompt:`${i}\n\nCommand: ${e}`,signal:t,options:{enablePromptCaching:!1,querySource:o,agents:[],isNonInteractiveSession:n,hasAppendSystemPrompt:!1,mcpTools:[]}});clearTimeout(c);let d=Date.now()-l,f=typeof s.message.content==`string`?s.message.content:Array.isArray(s.message.content)?s.message.content.find(e=>e.type===`text`)?.text??`none`:`none`;return GL(f)?(J(a,{success:!1,error:`API error`,durationMs:d}),u=null):f===`command_injection_detected`?(J(a,{success:!1,error:`command_injection_detected`,durationMs:d}),u={commandPrefix:null}):f===`git`||LOt.has(f.toLowerCase())?(J(a,{success:!1,error:`dangerous_shell_prefix`,durationMs:d}),u={commandPrefix:null}):f===`none`?(J(a,{success:!1,error:`prefix "none"`,durationMs:d}),u={commandPrefix:null}):e.startsWith(f)?(J(a,{success:!0,durationMs:d}),u={commandPrefix:f}):(J(a,{success:!1,error:`command did not start with prefix`,durationMs:d}),u={commandPrefix:null}),u}catch(e){throw clearTimeout(c),e}}async function IOt(e,t,n,r,i){let a=await i(e),[o,...s]=await Promise.all([r(e,t,n),...a.map(async e=>({subcommand:e,prefix:await r(e,t,n)}))]);if(!o)return null;let c=s.reduce((e,{subcommand:t,prefix:n})=>(n&&e.set(t,n),e),new Map);return{...o,subcommandPrefixes:c}}var LOt,ROt=n((()=>{Ge(),Da(),r9(),aR(),oa(),Yn(),BI(),LOt=new Set([`sh`,`bash`,`zsh`,`fish`,`csh`,`tcsh`,`ksh`,`dash`,`cmd`,`cmd.exe`,`powershell`,`powershell.exe`,`pwsh`,`pwsh.exe`,`bash.exe`])}));function zOt(){let e=yl(8).toString(`hex`);return{SINGLE_QUOTE:`__SINGLE_QUOTE_${e}__`,DOUBLE_QUOTE:`__DOUBLE_QUOTE_${e}__`,NEW_LINE:`__NEW_LINE_${e}__`,ESCAPED_OPEN_PAREN:`__ESCAPED_OPEN_PAREN_${e}__`,ESCAPED_CLOSE_PAREN:`__ESCAPED_CLOSE_PAREN_${e}__`}}function BOt(e){return/[\s'"]/.test(e)||e.length===0||e.startsWith(`#`)?!1:!e.startsWith(`!`)&&!e.startsWith(`=`)&&!e.includes(`$`)&&!e.includes("`")&&!e.includes(`*`)&&!e.includes(`?`)&&!e.includes(`[`)&&!e.includes(`{`)&&!e.includes(`~`)&&!e.includes(`(`)&&!e.includes(`<`)&&!e.startsWith(`&`)}function i9(e){let t=[],n=zOt(),{processedCommand:r,heredocs:i}=xU(e),a=r.replace(/\\+\n/g,e=>{let t=e.length-1;return t%2==1?`\\`.repeat(t-1):e}),o=e.replace(/\\+\n/g,e=>{let t=e.length-1;return t%2==1?`\\`.repeat(t-1):e}),s=uc(a.replaceAll(`"`,`"${n.DOUBLE_QUOTE}`).replaceAll(`'`,`'${n.SINGLE_QUOTE}`).replaceAll(`
3392
3392
  `,`\n${n.NEW_LINE}\n`).replaceAll(`\\(`,n.ESCAPED_OPEN_PAREN).replaceAll(`\\)`,n.ESCAPED_CLOSE_PAREN),e=>`$${e}`);if(!s.success)return[o];let c=s.tokens;if(c.length===0)return[];try{for(let e of c){if(typeof e==`string`){if(t.length>0&&typeof t[t.length-1]==`string`){e===n.NEW_LINE?t.push(null):t[t.length-1]+=` ${e}`;continue}}else if(`op`in e&&e.op===`glob`&&t.length>0&&typeof t[t.length-1]==`string`){t[t.length-1]+=` ${e.pattern}`;continue}t.push(e)}return DXe(t.map(e=>e===null?null:typeof e==`string`?e:`comment`in e?`#${e.comment.replaceAll(`"${n.DOUBLE_QUOTE}`,n.DOUBLE_QUOTE).replaceAll(`'${n.SINGLE_QUOTE}`,n.SINGLE_QUOTE)}`:`op`in e&&e.op===`glob`?e.pattern:`op`in e?e.op:null).filter(e=>e!==null).map(e=>e.replaceAll(`${n.SINGLE_QUOTE}`,`'`).replaceAll(`${n.DOUBLE_QUOTE}`,`"`).replaceAll(`\n${n.NEW_LINE}\n`,`
3393
3393
  `).replaceAll(n.ESCAPED_OPEN_PAREN,`\\(`).replaceAll(n.ESCAPED_CLOSE_PAREN,`\\)`)),i)}catch{return[o]}}function VOt(e){return e.filter(e=>!XOt.has(e))}function a9(e){let t=i9(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==void 0&&(n===`>&`||n===`>`||n===`>>`)){let r=t[e-1]?.trim(),i=t[e+1]?.trim(),a=t[e+2]?.trim();if(i===void 0)continue;let o=!1,s=!1,c=i;(n===`>`||n===`>>`)&&i.length>=3&&i.charAt(i.length-2)===` `&&f9.has(i.charAt(i.length-1))&&(a===`>`||a===`>>`||a===`>&`)&&(c=i.slice(0,-2)),n===`>&`&&f9.has(i)?o=!0:n===`>`&&i===`&`&&a!==void 0&&f9.has(a)?(o=!0,s=!0):(n===`>`&&i.startsWith(`&`)&&i.length>1&&f9.has(i.slice(1))||(n===`>`||n===`>>`)&&BOt(c))&&(o=!0),o&&(r&&r.length>=3&&f9.has(r.charAt(r.length-1))&&r.charAt(r.length-2)===` `&&(t[e-1]=r.slice(0,-2)),t[e]=void 0,t[e+1]=void 0,s&&(t[e+2]=void 0))}}return VOt(t.filter(e=>e!==void 0&&e!==``))}function HOt(e){let t=e.trim();if(!t.endsWith(`--help`)||t.includes(`"`)||t.includes(`'`))return!1;let n=uc(t);if(!n.success)return!1;let r=n.tokens,i=!1,a=/^[a-zA-Z0-9]+$/;for(let e of r)if(typeof e==`string`){if(e.startsWith(`-`))if(e===`--help`)i=!0;else return!1;else if(!a.test(e))return!1}return i}function UOt(){p9.cache.clear(),m9.cache.clear()}function WOt(e){let t=zOt(),{processedCommand:n}=xU(e),r=uc(n.replaceAll(`"`,`"${t.DOUBLE_QUOTE}`).replaceAll(`'`,`'${t.SINGLE_QUOTE}`),e=>`$${e}`);if(!r.success)return!1;let i=r.tokens;for(let e=0;e<i.length;e++){let t=i[e],n=i[e+1];if(t!==void 0&&typeof t!=`string`){if(`comment`in t)return!1;if(`op`in t){if(t.op===`glob`||h9.has(t.op))continue;if(t.op===`>&`){if(n!==void 0&&typeof n==`string`&&f9.has(n.trim()))continue}else if(t.op===`>`)continue;else if(t.op===`>>`)continue;return!1}}}return!0}function GOt(e){let{processedCommand:t}=xU(e);return!uc(t,e=>`$${e}`).success||a9(e).length>1&&!WOt(e)}function o9(e){let t=[],n=!1,{processedCommand:r,heredocs:i}=xU(e),a=r.replace(/\\+\n/g,e=>{let t=e.length-1;return t%2==1?`\\`.repeat(t-1):e}),o=uc(a,e=>`$${e}`);if(!o.success)return{commandWithoutRedirections:e,redirections:[],hasDangerousRedirection:!0};let s=o.tokens,c=new Set,l=[];s.forEach((e,t)=>{if(s9(e,`(`)){let e=s[t-1],n=t===0||e&&typeof e==`object`&&`op`in e&&[`&&`,`||`,`;`,`|`].includes(e.op);l.push({index:t,isStart:!!n})}else if(s9(e,`)`)&&l.length>0){let e=l.pop(),n=s[t+1];e.isStart&&(s9(n,`>`)||s9(n,`>>`))&&c.add(e.index).add(t)}});let u=[],d=0;for(let e=0;e<s.length;e++){let r=s[e];if(!r)continue;let[i,a]=[s[e-1],s[e+1]];if(!((s9(r,`(`)||s9(r,`)`))&&c.has(e))){if(s9(r,`(`)&&i&&typeof i==`string`&&i.endsWith(`$`)?d++:s9(r,`)`)&&d>0&&d--,d===0){let{skip:o,dangerous:c}=KOt(r,i,a,s[e+2],s[e+3],t,u);if(c&&(n=!0),o>0){e+=o;continue}}u.push(r)}}return{commandWithoutRedirections:DXe([YOt(u,a)],i)[0],redirections:t,hasDangerousRedirection:n}}function s9(e,t){return typeof e==`object`&&!!e&&`op`in e&&e.op===t}function c9(e){return typeof e!=`string`||e.length===0?!1:!e.startsWith(`!`)&&!e.startsWith(`=`)&&!e.startsWith(`~`)&&!e.includes(`$`)&&!e.includes("`")&&!e.includes(`*`)&&!e.includes(`?`)&&!e.includes(`[`)&&!e.includes(`{`)}function l9(e){return typeof e==`object`&&e&&`op`in e?e.op===`glob`:typeof e!=`string`||e.length===0?!1:e.includes(`$`)||e.includes(`%`)||e.includes("`")||e.includes(`*`)||e.includes(`?`)||e.includes(`[`)||e.includes(`{`)||e.startsWith(`!`)||e.startsWith(`=`)||e.startsWith(`~`)}function KOt(e,t,n,r,i,a,o){let s=e=>typeof e==`string`&&/^\d+$/.test(e.trim());if(s9(e,`>`)||s9(e,`>>`)){let c=e.op;if(s(t)){if(n===`!`&&c9(r))return u9(t.trim(),c,r,a,o,2);if(n===`!`&&l9(r))return{skip:0,dangerous:!0};if(s9(n,`|`)&&c9(r))return u9(t.trim(),c,r,a,o,2);if(s9(n,`|`)&&l9(r))return{skip:0,dangerous:!0};if(typeof n==`string`&&n.startsWith(`!`)&&n.length>1&&n[1]!==`!`&&n[1]!==`-`&&n[1]!==`?`&&!/^!\d/.test(n)){let e=n.substring(1);return l9(e)?{skip:0,dangerous:!0}:u9(t.trim(),c,e,a,o,1)}return u9(t.trim(),c,n,a,o,1)}if(s9(n,`|`)&&c9(r))return a.push({target:r,operator:c}),{skip:2,dangerous:!1};if(s9(n,`|`)&&l9(r))return{skip:0,dangerous:!0};if(n===`!`&&c9(r))return a.push({target:r,operator:c}),{skip:2,dangerous:!1};if(n===`!`&&l9(r))return{skip:0,dangerous:!0};if(typeof n==`string`&&n.startsWith(`!`)&&n.length>1&&n[1]!==`!`&&n[1]!==`-`&&n[1]!==`?`&&!/^!\d/.test(n)){let e=n.substring(1);return l9(e)?{skip:0,dangerous:!0}:(a.push({target:e,operator:c}),{skip:1,dangerous:!1})}if(s9(n,`&`)){if(r===`!`&&c9(i))return a.push({target:i,operator:c}),{skip:3,dangerous:!1};if(r===`!`&&l9(i))return{skip:0,dangerous:!0};if(s9(r,`|`)&&c9(i))return a.push({target:i,operator:c}),{skip:3,dangerous:!1};if(s9(r,`|`)&&l9(i))return{skip:0,dangerous:!0};if(c9(r))return a.push({target:r,operator:c}),{skip:2,dangerous:!1};if(l9(r))return{skip:0,dangerous:!0}}if(c9(n))return a.push({target:n,operator:c}),{skip:1,dangerous:!1};if(l9(n))return{skip:0,dangerous:!0}}if(s9(e,`>&`)){if(s(t)&&s(n))return{skip:0,dangerous:!1};if(s9(n,`|`)&&c9(r))return a.push({target:r,operator:`>`}),{skip:2,dangerous:!1};if(s9(n,`|`)&&l9(r))return{skip:0,dangerous:!0};if(n===`!`&&c9(r))return a.push({target:r,operator:`>`}),{skip:2,dangerous:!1};if(n===`!`&&l9(r))return{skip:0,dangerous:!0};if(c9(n)&&!s(n))return a.push({target:n,operator:`>`}),{skip:1,dangerous:!1};if(!s(n)&&l9(n))return{skip:0,dangerous:!0}}return{skip:0,dangerous:!1}}function u9(e,t,n,r,i,a=1){let o=e===`1`,s=n&&c9(n)&&typeof n==`string`&&!/^\d+$/.test(n),c=typeof n==`string`&&/^\d+$/.test(n.trim());return i.length>0&&i.pop(),!c&&l9(n)?{skip:0,dangerous:!0}:s?(r.push({target:n,operator:t}),o||i.push(e+t,n),{skip:a,dangerous:!1}):!o&&(i.push(e+t),n)?(i.push(n),{skip:1,dangerous:!1}):{skip:0,dangerous:!1}}function qOt(e,t,n){if(!e||typeof e!=`string`)return!1;if(e===`$`)return!0;if(e.endsWith(`$`)){if(e.includes(`=`)&&e.endsWith(`=$`))return!0;let r=1;for(let e=n+1;e<t.length&&r>0;e++)if(s9(t[e],`(`)&&r++,s9(t[e],`)`)&&--r===0){let n=t[e+1];return!!(n&&typeof n==`string`&&!n.startsWith(` `))}}return!1}function JOt(e){return!/^\d+>>?$/.test(e)&&!!(/\s/.test(e)||e.length===1&&`><|&;()`.includes(e))}function d9(e,t,n=!1){return!e||n?e+t:`${e} ${t}`}function YOt(e,t){if(!e.length)return t;let n=``,r=0,i=!1;for(let t=0;t<e.length;t++){let a=e[t],o=e[t-1],s=e[t+1];if(typeof a==`string`){let e=/[|&;]/.test(a)?`"${a}"`:JOt(a)?dc([a]):a;e.endsWith(`$`),s&&typeof s==`object`&&`op`in s&&s.op;let t=n.endsWith(`(`)||o===`$`||typeof o==`object`&&o&&`op`in o&&o.op===`)`;n.endsWith(`<(`)?n+=` ${e}`:n=d9(n,e,t);continue}if(typeof a!=`object`||!a||!(`op`in a))continue;let c=a.op;if(c===`glob`&&`pattern`in a){n=d9(n,a.pattern);continue}if(c===`>&`&&typeof o==`string`&&/^\d+$/.test(o)&&typeof s==`string`&&/^\d+$/.test(s)){let e=n.lastIndexOf(o);n=n.slice(0,e)+o+c+s,t++;continue}if(c===`<`&&s9(s,`<`)){let r=e[t+2];if(r&&typeof r==`string`){n=d9(n,r),t+=2;continue}}if(c===`<<<`){n=d9(n,c);continue}if(c===`(`){if(qOt(o,e,t)||r>0)r++,n.endsWith(` `)&&(n=n.slice(0,-1)),n+=`(`;else if(n.endsWith(`$`))qOt(o,e,t)?(r++,n+=`(`):n=d9(n,`(`);else{let e=n.endsWith(`<(`)||n.endsWith(`(`);n=d9(n,`(`,e)}continue}if(c===`)`){if(i){i=!1,n+=`)`;continue}r>0&&r--,n+=`)`;continue}if(c===`<(`){i=!0,n=d9(n,c);continue}[`&&`,`||`,`|`,`;`,`>`,`>>`,`<`].includes(c)&&(n=d9(n,c))}return n.trim()||t}var f9,p9,m9,h9,XOt,g9=n((()=>{ROt(),jXe(),pc(),f9=new Set([`0`,`1`,`2`]),p9=NOt({toolName:`Bash`,policySpec:`<policy_spec>
3394
3394
  # Work Mate Bash command prefix detection
@@ -3452,6 +3452,6 @@ then the safety system will see that you said "command_injection_detected" and a
3452
3452
 
3453
3453
  Note that not every command has a prefix. If a command has no prefix, return "none".
3454
3454
 
3455
- ONLY return the prefix. Do not return any other text, markdown markers, or other content or formatting.`,eventName:`tengu_bash_prefix`,querySource:`bash_extract_prefix`,preCheck:e=>HOt(e)?{commandPrefix:e}:null}),m9=POt(p9,a9),h9=new Set([`&&`,`||`,`;`,`;;`,`|`]),XOt=new Set([...h9,`>&`,`>`,`>>`])}));function ZOt(e){let t=zr().sandbox?.excludedCommands??[];if(t.length===0)return!1;let n;try{n=a9(e)}catch{n=[e]}for(let e of n){let n=[e.trim()],r=new Set(n),i=0;for(;i<n.length;){let e=n.length;for(let t=i;t<e;t++){let e=n[t],i=u$e(e,x$e);r.has(i)||(n.push(i),r.add(i));let a=OW(e);r.has(a)||(n.push(a),r.add(a))}i=e}for(let e of t){let t=LW(e);for(let e of n)switch(t.type){case`prefix`:if(e===t.prefix||e.startsWith(`${t.prefix} `))return!0;break;case`exact`:if(e===t.command)return!0;break;case`wildcard`:if(EW(t.pattern,e))return!0;break}}}return!1}function _9(e){return!(!Tg.isSandboxingEnabled()||e.dangerouslyDisableSandbox&&Tg.areUnsandboxedCommandsAllowed()||!e.command||ZOt(e.command))}var v9=n((()=>{g9(),Eg(),Vr(),HW()}));function QOt(e){return $Ot.has(e)}var $Ot,ekt=n((()=>{cs(),goe(),os(),Fs(),fs(),ls(),jOe(),zoe(),Hs(),ps(),Xoe(),gse(),ei(),Une(),ms(),is(),zs(),tK(),$Ot=new Set([gs,rs,Us,`LSP`,Vs,Ow,`ReadMcpResourceTool`,hs,as,Koe,ns,rse,rre,fr,Ms,Ooe,ss,ts,eK])}));function tkt(e){return Nre(e)}function y9(e){return k9.flatMap(t=>(e.alwaysAllowRules[t]||[]).map(e=>({source:t,ruleBehavior:`allow`,ruleValue:Er(e)})))}function b9(e,t){if(t){if(t.type===`classifier`)return`Classifier '${t.classifier}' requires approval for this ${e} command: ${t.reason}`;switch(t.type){case`hook`:return t.reason?`Hook '${t.hookName}' blocked this action: ${t.reason}`:`Hook '${t.hookName}' requires approval for this ${e} command`;case`rule`:return`Permission rule '${or(t.rule.ruleValue)}' from ${tkt(t.rule.source)} requires approval for this ${e} command`;case`subcommandResults`:{let n=[];for(let[r,i]of t.reasons)if(i.behavior===`ask`||i.behavior===`passthrough`)if(e===`Bash`){let{commandWithoutRedirections:e,redirections:t}=o9(r),i=t.length>0?e:r;n.push(i)}else n.push(r);if(n.length>0){let t=n.length;return`This ${e} command contains multiple operations. The following ${qa(t,`part`)} ${qa(t,`requires`,`require`)} approval: ${n.join(`, `)}`}return`This ${e} command contains multiple operations that require approval`}case`permissionPromptTool`:return`Tool '${t.permissionPromptToolName}' requires approval for this ${e} command`;case`sandboxOverride`:return`Run outside of the sandbox`;case`workingDir`:return t.reason;case`safetyCheck`:case`other`:return t.reason;case`mode`:return`Current permission mode (${Xne(t.mode)}) requires approval for this ${e} command`;case`asyncAgent`:return t.reason}}return`Claude requested permissions to use ${e}, but you haven't granted it yet.`}function x9(e){return k9.flatMap(t=>(e.alwaysDenyRules[t]||[]).map(e=>({source:t,ruleBehavior:`deny`,ruleValue:Er(e)})))}function S9(e){return k9.flatMap(t=>(e.alwaysAskRules[t]||[]).map(e=>({source:t,ruleBehavior:`ask`,ruleValue:Er(e)})))}function C9(e,t){if(t.ruleValue.ruleContent!==void 0)return!1;let n=Bre(e);if(t.ruleValue.toolName===n)return!0;let r=Fr(t.ruleValue.toolName),i=Fr(n);return r!==null&&i!==null&&(r.toolName===void 0||r.toolName===`*`)&&r.serverName===i.serverName}function nkt(e,t){return y9(e).find(e=>C9(t,e))||null}function w9(e,t){return x9(e).find(e=>C9(t,e))||null}function rkt(e,t){return S9(e).find(e=>C9(t,e))||null}function ikt(e,t,n){return x9(e).find(e=>e.ruleValue.toolName===t&&e.ruleValue.ruleContent===n)||null}function T9(e,t,n){let r=new Set;for(let e of x9(t))e.ruleValue.toolName===n&&e.ruleValue.ruleContent!==void 0&&r.add(e.ruleValue.ruleContent);return e.filter(e=>!r.has(e.agentType))}function E9(e,t,n){return D9(e,Bre(t),n)}function D9(e,t,n){let r=new Map,i=[];switch(n){case`allow`:i=y9(e);break;case`deny`:i=x9(e);break;case`ask`:i=S9(e);break}for(let e of i)e.ruleValue.toolName===t&&e.ruleValue.ruleContent!==void 0&&e.ruleBehavior===n&&r.set(e.ruleValue.ruleContent,e);return r}async function akt(e,t,n,r,i,a){try{for await(let o of xEt(e.name,n,t,r,i,a,r.abortController.signal)){if(!o.permissionRequestResult)continue;let n=o.permissionRequestResult;if(n.behavior===`allow`){let e=n.updatedInput??t;return n.updatedPermissions?.length&&(cVe(n.updatedPermissions),r.setAppState(e=>({...e,toolPermissionContext:xB(e.toolPermissionContext,n.updatedPermissions)}))),{behavior:`allow`,updatedInput:e,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}if(n.behavior===`deny`)return n.interrupt&&(U(`Hook interrupt: tool=${e.name} hookMessage=${n.message}`),r.abortController.abort()),{behavior:`deny`,message:n.message||`Permission denied by hook`,decisionReason:{type:`hook`,hookName:`PermissionRequest`,reason:n.message}}}}catch(e){q(Error(`PermissionRequest hook failed for headless agent`,{cause:jn(e)}))}return null}function O9(e,t){e.localDenialTracking?Object.assign(e.localDenialTracking,t):e.setAppState(e=>e.denialTracking===t?e:{...e,denialTracking:t})}function okt(e,t,n,r,i,a,o){if(!Fmt(e))return null;let s=e.totalDenials>=N1.maxTotal,c=t.toolPermissionContext.shouldAvoidPermissionPrompts,l=e.totalDenials,u=e.consecutiveDenials,d=s?`${l} actions were blocked this session. Please review the transcript before continuing.`:`${u} consecutive actions were blocked. Please review the transcript before continuing.`;if(J(`tengu_auto_mode_denial_limit_exceeded`,{limit:s?`total`:`consecutive`,mode:c?`headless`:`cli`,messageID:r.message.id,consecutiveDenials:u,totalDenials:l,toolName:Dc(i.name)}),c)throw new Sn(`Agent aborted: too many classifier denials in headless mode`);U(`Classifier denial limit exceeded, falling back to prompting: ${d}`,{level:`warn`}),s&&O9(o,{...e,totalDenials:0,consecutiveDenials:0});let f=a.decisionReason?.type===`classifier`?a.decisionReason.classifier:`auto-mode`;return{...a,decisionReason:{type:`classifier`,classifier:f,reason:`${d}\n\nLatest blocked action: ${n}`}}}async function skt(e,t,n){let r=n.getAppState(),i=w9(r.toolPermissionContext,e);if(i)return{behavior:`deny`,decisionReason:{type:`rule`,rule:i},message:`Permission to use ${e.name} has been denied.`};let a=rkt(r.toolPermissionContext,e);if(a&&!(e.name===`Bash`&&Tg.isSandboxingEnabled()&&Tg.isAutoAllowBashIfSandboxedEnabled()&&_9(t)))return{behavior:`ask`,decisionReason:{type:`rule`,rule:a},message:b9(e.name)};let o={behavior:`passthrough`,message:b9(e.name)};try{let r=e.inputSchema.parse(t);o=await e.checkPermissions(r,n)}catch(e){if(e instanceof Sn||e instanceof In)throw e;q(e)}return o?.behavior===`deny`||o?.behavior===`ask`&&o.decisionReason?.type===`rule`&&o.decisionReason.rule.ruleBehavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`safetyCheck`?o:null}async function ckt(e,t,n){if(n.abortController.signal.aborted)throw new Sn;let r=n.getAppState(),i=w9(r.toolPermissionContext,e);if(i)return{behavior:`deny`,decisionReason:{type:`rule`,rule:i},message:`Permission to use ${e.name} has been denied.`};let a=rkt(r.toolPermissionContext,e);if(a&&!(e.name===`Bash`&&Tg.isSandboxingEnabled()&&Tg.isAutoAllowBashIfSandboxedEnabled()&&_9(t)))return{behavior:`ask`,decisionReason:{type:`rule`,rule:a},message:b9(e.name)};let o={behavior:`passthrough`,message:b9(e.name)};try{let r=e.inputSchema.parse(t);o=await e.checkPermissions(r,n)}catch(e){if(e instanceof Sn||e instanceof In)throw e;q(e)}if(o?.behavior===`deny`||e.requiresUserInteraction?.()&&o?.behavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`rule`&&o.decisionReason.rule.ruleBehavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`safetyCheck`)return o;if(r=n.getAppState(),r.toolPermissionContext.mode===`bypassPermissions`||r.toolPermissionContext.mode===`plan`&&r.toolPermissionContext.isBypassPermissionsModeAvailable)return{behavior:`allow`,updatedInput:pkt(o,t),decisionReason:{type:`mode`,mode:r.toolPermissionContext.mode}};let s=nkt(r.toolPermissionContext,e);if(s)return{behavior:`allow`,updatedInput:pkt(o,t),decisionReason:{type:`rule`,rule:s}};let c=o.behavior===`passthrough`?{...o,behavior:`ask`,message:b9(e.name,o.decisionReason)}:o;return c.behavior===`ask`&&c.suggestions&&U(`Permission suggestions for ${e.name}: ${V(c.suggestions,null,2)}`),c}async function lkt({rule:e,initialContext:t,setToolPermissionContext:n}){if(e.source===`policySettings`||e.source===`flagSettings`||e.source===`command`)throw Error(`Cannot delete permission rules from read-only settings`);let r=bB(t,{type:`removeRules`,rules:[e.ruleValue],behavior:e.ruleBehavior,destination:e.source});switch(e.source){case`localSettings`:case`userSettings`:case`projectSettings`:tVe(e);break;case`cliArg`:case`session`:break}n(r)}function ukt(e,t){let n=new Map;for(let t of e){let e=`${t.source}:${t.ruleBehavior}`;n.has(e)||n.set(e,[]),n.get(e).push(t.ruleValue)}let r=[];for(let[e,i]of n){let[n,a]=e.split(`:`);r.push({type:t,rules:i,behavior:a,destination:n})}return r}function dkt(e,t){return xB(e,ukt(t,`addRules`))}function fkt(e,t){let n=e;if(gB()){let e=[`userSettings`,`projectSettings`,`localSettings`,`cliArg`,`session`],t=[`allow`,`deny`,`ask`];for(let r of e)for(let e of t)n=bB(n,{type:`replaceRules`,rules:[],behavior:e,destination:r})}for(let e of[`userSettings`,`projectSettings`,`localSettings`])for(let t of[`allow`,`deny`,`ask`])n=bB(n,{type:`replaceRules`,rules:[],behavior:t,destination:e});let r=ukt(t,`replaceRules`);return xB(n,r)}function pkt(e,t){return(`updatedInput`in e?e.updatedInput:void 0)??t}var k9,A9,j9=n((()=>{Nn(),Ur(),xr(),v9(),bs(),ds(),Dq(),g9(),W(),On(),Qi(),Eg(),qr(),Ja(),gr(),CB(),fi(),vB(),ekt(),cL(),Wt(),Da(),Cc(),GW(),h(),_7(),m3(),Ao(),Yn(),Imt(),tK(),k9=[...Zr,`cliArg`,`command`,`session`],A9=async(e,t,n,r,i)=>{let a=await ckt(e,t,n);if(a.behavior===`allow`){let e=n.getAppState();{let t=n.localDenialTracking??e.denialTracking;e.toolPermissionContext.mode===`auto`&&t&&t.consecutiveDenials>0&&O9(n,M1(t))}return a}if(a.behavior===`ask`){let o=n.getAppState();if(o.toolPermissionContext.mode===`dontAsk`)return{behavior:`deny`,decisionReason:{type:`mode`,mode:`dontAsk`},message:sbt(e.name)};if(o.toolPermissionContext.mode===`auto`||o.toolPermissionContext.mode===`plan`&&iL()){if(a.decisionReason?.type===`safetyCheck`&&!a.decisionReason.classifierApprovable)return o.toolPermissionContext.shouldAvoidPermissionPrompts?{behavior:`deny`,message:a.message,decisionReason:{type:`asyncAgent`,reason:`Safety check requires interactive approval and permission prompts are not available in this context`}}:a;if(e.requiresUserInteraction?.()&&a.behavior===`ask`)return a;let i=n.localDenialTracking??o.denialTracking??Nmt();if(e.name===`PowerShell`)return o.toolPermissionContext.shouldAvoidPermissionPrompts?{behavior:`deny`,message:`PowerShell tool requires interactive approval`,decisionReason:{type:`asyncAgent`,reason:`PowerShell tool requires interactive approval and permission prompts are not available in this context`}}:(U(`Skipping auto mode classifier for ${e.name}: tool requires explicit user permission`),a);if(a.behavior===`ask`&&e.name!==`Agent`&&e.name!==`REPL`)try{let a=e.inputSchema.parse(t),o=await e.checkPermissions(a,{...n,getAppState:()=>{let e=n.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`acceptEdits`}}}});if(o.behavior===`allow`)return O9(n,M1(i)),U(`Skipping auto mode classifier for ${e.name}: would be allowed in acceptEdits mode`),J(`tengu_auto_mode_decision`,{decision:`allowed`,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,confidence:`high`,fastPath:`acceptEdits`}),{behavior:`allow`,updatedInput:o.updatedInput??t,decisionReason:{type:`mode`,mode:`auto`}}}catch(e){if(e instanceof Sn||e instanceof In)throw e}if(QOt(e.name))return O9(n,M1(i)),U(`Skipping auto mode classifier for ${e.name}: tool is on the safe allowlist`),J(`tengu_auto_mode_decision`,{decision:`allowed`,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,confidence:`high`,fastPath:`allowlist`}),{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`auto`}};let s=X2e(e.name,t),c;try{c=await U2e(n.messages,s,n.options.tools,o.toolPermissionContext,n.abortController.signal)}finally{}let l=c.unavailable?`unavailable`:c.shouldBlock?`blocked`:`allowed`,u=c.usage&&c.model?to(c.model,c.usage):void 0;if(J(`tengu_auto_mode_decision`,{decision:l,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,classifierModel:c.model,consecutiveDenials:c.shouldBlock?i.consecutiveDenials+1:0,totalDenials:c.shouldBlock?i.totalDenials+1:i.totalDenials,classifierInputTokens:c.usage?.inputTokens,classifierOutputTokens:c.usage?.outputTokens,classifierCacheReadInputTokens:c.usage?.cacheReadInputTokens,classifierCacheCreationInputTokens:c.usage?.cacheCreationInputTokens,classifierDurationMs:c.durationMs,classifierSystemPromptLength:c.promptLengths?.systemPrompt,classifierToolCallsLength:c.promptLengths?.toolCalls,classifierUserPromptsLength:c.promptLengths?.userPrompts,sessionInputTokens:Lt(),sessionOutputTokens:tn(),sessionCacheReadInputTokens:cte(),sessionCacheCreationInputTokens:pne(),classifierCostUSD:u,classifierStage:c.stage,classifierStage1InputTokens:c.stage1Usage?.inputTokens,classifierStage1OutputTokens:c.stage1Usage?.outputTokens,classifierStage1CacheReadInputTokens:c.stage1Usage?.cacheReadInputTokens,classifierStage1CacheCreationInputTokens:c.stage1Usage?.cacheCreationInputTokens,classifierStage1DurationMs:c.stage1DurationMs,classifierStage1RequestId:c.stage1RequestId,classifierStage1MsgId:c.stage1MsgId,classifierStage1CostUSD:c.stage1Usage&&c.model?to(c.model,c.stage1Usage):void 0,classifierStage2InputTokens:c.stage2Usage?.inputTokens,classifierStage2OutputTokens:c.stage2Usage?.outputTokens,classifierStage2CacheReadInputTokens:c.stage2Usage?.cacheReadInputTokens,classifierStage2CacheCreationInputTokens:c.stage2Usage?.cacheCreationInputTokens,classifierStage2DurationMs:c.stage2DurationMs,classifierStage2RequestId:c.stage2RequestId,classifierStage2MsgId:c.stage2MsgId,classifierStage2CostUSD:c.stage2Usage&&c.model?to(c.model,c.stage2Usage):void 0}),c.durationMs!==void 0&&Qte(c.durationMs),c.shouldBlock){if(c.transcriptTooLong){if(o.toolPermissionContext.shouldAvoidPermissionPrompts)throw new Sn(`Agent aborted: auto mode classifier transcript exceeded context window in headless mode`);return U(`Auto mode classifier transcript too long, falling back to normal permission handling`,{level:`warn`}),{...a,decisionReason:{type:`other`,reason:`Auto mode classifier transcript exceeded context window — falling back to manual approval`}}}if(c.unavailable)return o.toolPermissionContext.shouldAvoidPermissionPrompts?(U(`Auto mode classifier unavailable, denying with retry guidance (fail closed)`,{level:`warn`}),{behavior:`deny`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:`Classifier unavailable`},message:lbt(e.name,c.model)}):(U(`Auto mode classifier unavailable, falling back to prompting with retry guidance (fail closed)`,{level:`warn`}),{behavior:`ask`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:`Classifier unavailable`},message:lbt(e.name,c.model)});let t=Pmt(i);return O9(n,t),U(`Auto mode classifier blocked action: ${c.reason}`,{level:`warn`}),okt(t,o,c.reason,r,e,a,n)||{behavior:`deny`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:c.reason},message:cbt(c.reason)}}return O9(n,M1(i)),{behavior:`allow`,updatedInput:t,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:c.reason}}}if(o.toolPermissionContext.shouldAvoidPermissionPrompts)return await akt(e,t,i,n,o.toolPermissionContext.mode,a.suggestions)||{behavior:`deny`,decisionReason:{type:`asyncAgent`,reason:`Permission prompts are not available in this context`},message:obt(e.name)}}return a}}));async function mkt(e,t){if(!e)return{resultType:`emptyPath`};let n=el(Qr(e));try{if(!(await Nl(n)).isDirectory())return{resultType:`notADirectory`,directoryPath:e,absolutePath:n}}catch(t){let r=Cn(t);if(r===`ENOENT`||r===`ENOTDIR`||r===`EACCES`||r===`EPERM`)return{resultType:`pathNotFound`,directoryPath:e,absolutePath:n};throw t}let r=C8(t);for(let t of r)if(T8(n,t))return{resultType:`alreadyInWorkingDirectory`,directoryPath:e,workingDir:t};return{resultType:`success`,absolutePath:n}}function hkt(e){switch(e.resultType){case`emptyPath`:return`Please provide a directory path.`;case`pathNotFound`:return`Path ${Ue.bold(e.absolutePath)} was not found.`;case`notADirectory`:{let t=qc(e.absolutePath);return`${Ue.bold(e.directoryPath)} is not a directory. Did you mean to add the parent directory ${Ue.bold(t)}?`}case`alreadyInWorkingDirectory`:return`${Ue.bold(e.directoryPath)} is already accessible within the existing working directory ${Ue.bold(e.workingDir)}.`;case`success`:return`Added ${Ue.bold(e.absolutePath)} as a working directory.`}}var gkt=n((()=>{Ge(),On(),Lr(),R8()}));function _kt(e,t){if(e!==`Bash`)return!1;if(t===void 0||t===``)return!0;let n=t.trim().toLowerCase();if(n===`*`)return!0;for(let e of adt){let t=e.toLowerCase();if(n===t||n===`${t}:*`||n===`${t}*`||n===`${t} *`||n.startsWith(`${t} -`)&&n.endsWith(`*`))return!0}return!1}function vkt(e,t){if(e!==`PowerShell`)return!1;if(t===void 0||t===``)return!0;let n=t.trim().toLowerCase();if(n===`*`)return!0;let r=[...E$,`pwsh`,`powershell`,`cmd`,`wsl`,`iex`,`invoke-expression`,`icm`,`invoke-command`,`start-process`,`saps`,`start`,`start-job`,`sajb`,`start-threadjob`,`register-objectevent`,`register-engineevent`,`register-wmievent`,`register-scheduledjob`,`new-pssession`,`nsn`,`enter-pssession`,`etsn`,`add-type`,`new-object`];for(let e of r){if(n===e||n===`${e}:*`||n===`${e}*`||n===`${e} *`||n.startsWith(`${e} -`)&&n.endsWith(`*`))return!0;let t=e.indexOf(` `),r=t===-1?`${e}.exe`:`${e.slice(0,t)}.exe${e.slice(t)}`;if(n===r||n===`${r}:*`||n===`${r}*`||n===`${r} *`||n.startsWith(`${r} -`)&&n.endsWith(`*`))return!0}return!1}function ykt(e,t){return Zn(e)===ur}function bkt(e){if(Zr.includes(e)){let t=ti(e);if(t){let e=$c(yn(),t);return e.length<t.length?e:t}}return e}function xkt(e,t){return _kt(e,t)||vkt(e,t)||ykt(e,t)}function Skt(e,t){let n=[];for(let t of e)if(t.ruleBehavior===`allow`&&xkt(t.ruleValue.toolName,t.ruleValue.ruleContent)){let e=t.ruleValue.ruleContent?`${t.ruleValue.toolName}(${t.ruleValue.ruleContent})`:`${t.ruleValue.toolName}(*)`;n.push({ruleValue:t.ruleValue,source:t.source,ruleDisplay:e,sourceDisplay:bkt(t.source)})}for(let e of t){let t=e.match(/^([^(]+)(?:\(([^)]*)\))?$/);if(t){let r=t[1].trim(),i=t[2]?.trim();xkt(r,i)&&n.push({ruleValue:{toolName:r,ruleContent:i},source:`cliArg`,ruleDisplay:i?e:`${r}(*)`,sourceDisplay:`--allowed-tools`})}}return n}function Ckt(e){return[`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`].includes(e)}function wkt(e,t){let n=new Map;for(let e of t){if(!Ckt(e.source))continue;let t=e.source,r=n.get(t)||[];r.push(e.ruleValue),n.set(t,r)}let r=e;for(let[e,t]of n)r=bB(r,{type:`removeRules`,rules:t,behavior:`allow`,destination:e});return r}function M9(e){let t=[];for(let[n,r]of Object.entries(e.alwaysAllowRules))if(r)for(let e of r){let r=Er(e);t.push({source:n,ruleBehavior:`allow`,ruleValue:r})}let n=Skt(t,[]);if(n.length===0)return{...e,strippedDangerousRules:e.strippedDangerousRules??{}};for(let e of n)U(`Ignoring dangerous permission ${e.ruleDisplay} from ${e.sourceDisplay} (bypasses classifier)`);let r={};for(let e of n){var i;Ckt(e.source)&&(r[i=e.source]??(r[i]=[])).push(or(e.ruleValue))}return{...wkt(e,n),strippedDangerousRules:r}}function N9(e){let t=e.strippedDangerousRules;if(!t)return e;let n=e;for(let[e,r]of Object.entries(t))!r||r.length===0||(n=bB(n,{type:`addRules`,rules:r.map(Er),behavior:`allow`,destination:e}));return{...n,strippedDangerousRules:void 0}}function Tkt(e,t,n){if(e===t)return n;gne(e,t),rte(e,t),e===`plan`&&t!==`plan`&&Gt(!0);{if(t===`plan`&&e!==`plan`)return R9(n);let r=e===`auto`||e===`plan`&&iL(),i=t===`auto`;if(i&&!r){if(!I9())throw Error(`Cannot transition to auto mode: gate is not enabled`);rL(!0),n=M9(n)}else r&&!i&&(rL(!1),Mt(!0),n=N9(n))}return e===`plan`&&t!==`plan`&&n.prePlanMode?{...n,prePlanMode:void 0}:n}function Ekt(e){return Nft(e.join(` `).trim())?Pft():P9(e)}function Dkt({processPwd:e,originalCwd:t}){let{resolvedPath:n,isSymlink:r}=Vn(G(),e);return r?n===el(t):!1}function Okt({permissionModeCli:e,dangerouslySkipPermissions:t}){let n=zr()||{},r=n.permissions?.disableBypassPermissionsMode===`disable`,i=[],a;if(t&&i.push(`bypassPermissions`),e){let t=Hne(e);t===`auto`?i.push(`auto`):i.push(t)}if(n.permissions?.defaultMode){let e=n.permissions.defaultMode;m(process.env.CLAUDE_CODE_REMOTE)&&![`acceptEdits`,`plan`,`default`].includes(e)?(U(`settings defaultMode "${e}" is not supported in CLAUDE_CODE_REMOTE — only acceptEdits and plan are allowed`,{level:`warn`}),J(`tengu_ccr_unsupported_default_mode_ignored`,{mode:e})):e===`auto`?i.push(`auto`):i.push(e)}let o;for(let e of i){if(e===`bypassPermissions`&&r){U(`bypassPermissions mode is disabled by settings`,{level:`warn`}),a=`Bypass permissions mode was disabled by settings`;continue}o={mode:e,notification:a};break}return o||(o={mode:`default`,notification:a}),o||(o={mode:`default`,notification:a}),o.mode===`auto`&&rL(!0),o}function P9(e){if(e.length===0)return[];let t=[];for(let n of e){if(!n)continue;let e=``,r=!1;for(let i of n)switch(i){case`(`:r=!0,e+=i;break;case`)`:r=!1,e+=i;break;case`,`:r?e+=i:(e.trim()&&t.push(e.trim()),e=``);break;case` `:r?e+=i:e.trim()&&(t.push(e.trim()),e=``);break;default:e+=i}e.trim()&&t.push(e.trim())}return t}async function kkt({allowedToolsCli:e,disallowedToolsCli:t,baseToolsCli:n,permissionMode:r,allowDangerouslySkipPermissions:i,addDirs:a}){let o=P9(e).map(e=>or(Er(e))),s=P9(t);if(n&&n.length>0){let e=Ekt(n),t=new Set(e.map(Zn)),r=Pft().filter(e=>!t.has(e));s=[...s,...r]}let c=[],l=new Map,u=process.env.PWD;u&&u!==Xt()&&Dkt({originalCwd:Xt(),processPwd:u})&&l.set(u,{path:u,source:`session`});let d=zr()||{},f=eVe(),p=[],m=[];r===`auto`&&(m=Skt(f,o));let h=dkt({mode:r,additionalWorkingDirectories:l,alwaysAllowRules:{cliArg:o},alwaysDenyRules:{cliArg:s},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0,isAutoModeAvailable:!0},f),g=[...d.permissions?.additionalDirectories||[],...a],_=await Promise.all(g.map(e=>mkt(e,h)));for(let e of _)e.resultType===`success`?h=bB(h,{type:`addDirectories`,directories:[e.absolutePath],destination:`cliArg`}):e.resultType!==`alreadyInWorkingDirectory`&&e.resultType!==`pathNotFound`&&c.push(hkt(e));return{toolPermissionContext:h,warnings:c,dangerousPermissions:m,overlyBroadBashPermissions:p}}function F9(e){let t;switch(e){case`settings`:t=`auto mode disabled by settings`;break;case`circuit-breaker`:t=`auto mode is unavailable for your plan`;break;case`model`:t=`auto mode unavailable for this model`;break}return t}async function Akt(e,t){let n={},r=Nkt(n?.enabled),i=jkt();TFe(r===`disabled`||i);let a=Qo(),o=!!n?.disableFastMode&&!!t,s=_ae(a)&&!o,c=!1;r!==`disabled`&&!i&&s&&(c=r===`enabled`||Pkt());let l=r!==`disabled`&&!i&&s;U(`[auto-mode] verifyAutoModeGateAccess: enabledState=${r} disabledBySettings=${i} model=${a} modelSupported=${s} disableFastModeBreakerFires=${o} carouselAvailable=${c} canEnterAuto=${l}`);let u=wFe(),d=(e,t)=>(e.isAutoModeAvailable!==t&&U(`[auto-mode] verifyAutoModeGateAccess setAvailable: ${e.isAutoModeAvailable} -> ${t}`),e.isAutoModeAvailable===t?e:{...e,isAutoModeAvailable:t});if(l)return{updateContext:e=>d(e,c)};let f;i?(f=`settings`,U(`auto mode disabled: disableAutoMode in settings`,{level:`warn`})):r===`disabled`?(f=`circuit-breaker`,U(`auto mode disabled: tengu_auto_mode_config.enabled === "disabled" (circuit breaker)`,{level:`warn`})):(f=`model`,U(`auto mode disabled: model ${Qo()} does not support auto mode`,{level:`warn`}));let p=F9(f),m=e=>{let t=e.mode===`auto`;U(`[auto-mode] kickOutOfAutoIfNeeded applying: ctx.mode=${e.mode} ctx.prePlanMode=${e.prePlanMode} reason=${f}`);let n=e.mode===`plan`&&(e.prePlanMode===`auto`||!!e.strippedDangerousRules);return!t&&!n?d(e,!1):t?(rL(!1),Mt(!0),{...bB(N9(e),{type:`setMode`,mode:`default`,destination:`session`}),isAutoModeAvailable:!1}):(rL(!1),Mt(!0),{...N9(e),prePlanMode:e.prePlanMode===`auto`?`default`:e.prePlanMode,isAutoModeAvailable:!1})},h=e.mode===`auto`,g=e.mode===`plan`&&(e.prePlanMode===`auto`||!!e.strippedDangerousRules);return h||g||u?h||g?{updateContext:m,notification:p}:{updateContext:m,notification:e.isAutoModeAvailable?p:void 0}:{updateContext:m}}function jkt(){let e=zr()||{};return e.disableAutoMode===`disable`||e.permissions?.disableAutoMode===`disable`}function I9(){return!0}function Mkt(){return jkt()?`settings`:EFe()?`circuit-breaker`:_ae(Qo())?null:`model`}function Nkt(e){return e===`enabled`||e===`disabled`||e===`opt-in`?e:zkt}function Pkt(){return wFe()??!1?!0:Dre()}function L9(){return(zr()||{}).permissions?.disableBypassPermissionsMode===`disable`}function Fkt(e){let t=e;return e.mode===`bypassPermissions`&&(t=bB(e,{type:`setMode`,mode:`default`,destination:`session`})),{...t,isBypassPermissionsModeAvailable:!1}}function Ikt(){return!1}function Lkt(){return Dre()&&I9()&&Pre()}function R9(e){let t=e.mode;if(t===`plan`)return e;{let n=Lkt();if(t===`auto`)return n?{...e,prePlanMode:`auto`}:(rL(!1),Mt(!0),{...N9(e),prePlanMode:`auto`});if(n&&t!==`bypassPermissions`)return rL(!0),{...M9(e),prePlanMode:t}}return U(`[prepareContextForPlanMode] plain plan entry, prePlanMode=${t}`,{level:`info`}),{...e,prePlanMode:t}}function Rkt(e){if(e.mode!==`plan`||e.prePlanMode===`bypassPermissions`)return e;let t=Lkt(),n=iL();return t&&n?M9(e):!t&&!n?e:t?(rL(!0),Mt(!1),M9(e)):(rL(!1),Mt(!0),N9(e))}var zkt,z9=n((()=>{Wt(),vn(),h(),qr(),Vr(),gr(),j9(),vB(),cL(),gkt(),Da(),xr(),bs(),ds(),i1(),Bn(),Uo(),W(),YJ(),No(),odt(),CB(),fi(),zkt=`enabled`}));function B9(e,t=`Custom item`){let n=e.split(`
3455
+ ONLY return the prefix. Do not return any other text, markdown markers, or other content or formatting.`,eventName:`tengu_bash_prefix`,querySource:`bash_extract_prefix`,preCheck:e=>HOt(e)?{commandPrefix:e}:null}),m9=POt(p9,a9),h9=new Set([`&&`,`||`,`;`,`;;`,`|`]),XOt=new Set([...h9,`>&`,`>`,`>>`])}));function ZOt(e){let t=zr().sandbox?.excludedCommands??[];if(t.length===0)return!1;let n;try{n=a9(e)}catch{n=[e]}for(let e of n){let n=[e.trim()],r=new Set(n),i=0;for(;i<n.length;){let e=n.length;for(let t=i;t<e;t++){let e=n[t],i=u$e(e,x$e);r.has(i)||(n.push(i),r.add(i));let a=OW(e);r.has(a)||(n.push(a),r.add(a))}i=e}for(let e of t){let t=LW(e);for(let e of n)switch(t.type){case`prefix`:if(e===t.prefix||e.startsWith(`${t.prefix} `))return!0;break;case`exact`:if(e===t.command)return!0;break;case`wildcard`:if(EW(t.pattern,e))return!0;break}}}return!1}function _9(e){return!(!Tg.isSandboxingEnabled()||e.dangerouslyDisableSandbox&&Tg.areUnsandboxedCommandsAllowed()||!e.command||ZOt(e.command))}var v9=n((()=>{g9(),Eg(),Vr(),HW()}));function QOt(e){return $Ot.has(e)}var $Ot,ekt=n((()=>{cs(),goe(),os(),Fs(),fs(),ls(),jOe(),zoe(),Hs(),ps(),Xoe(),gse(),ei(),Une(),ms(),is(),zs(),tK(),$Ot=new Set([gs,rs,Us,`LSP`,Vs,Ow,`ReadMcpResourceTool`,hs,as,Koe,ns,rse,rre,fr,Ms,Ooe,ss,ts,eK])}));function tkt(e){return Nre(e)}function y9(e){return k9.flatMap(t=>(e.alwaysAllowRules[t]||[]).map(e=>({source:t,ruleBehavior:`allow`,ruleValue:Er(e)})))}function b9(e,t){if(t){if(t.type===`classifier`)return`Classifier '${t.classifier}' requires approval for this ${e} command: ${t.reason}`;switch(t.type){case`hook`:return t.reason?`Hook '${t.hookName}' blocked this action: ${t.reason}`:`Hook '${t.hookName}' requires approval for this ${e} command`;case`rule`:return`Permission rule '${or(t.rule.ruleValue)}' from ${tkt(t.rule.source)} requires approval for this ${e} command`;case`subcommandResults`:{let n=[];for(let[r,i]of t.reasons)if(i.behavior===`ask`||i.behavior===`passthrough`)if(e===`Bash`){let{commandWithoutRedirections:e,redirections:t}=o9(r),i=t.length>0?e:r;n.push(i)}else n.push(r);if(n.length>0){let t=n.length;return`This ${e} command contains multiple operations. The following ${qa(t,`part`)} ${qa(t,`requires`,`require`)} approval: ${n.join(`, `)}`}return`This ${e} command contains multiple operations that require approval`}case`permissionPromptTool`:return`Tool '${t.permissionPromptToolName}' requires approval for this ${e} command`;case`sandboxOverride`:return`Run outside of the sandbox`;case`workingDir`:return t.reason;case`safetyCheck`:case`other`:return t.reason;case`mode`:return`Current permission mode (${Xne(t.mode)}) requires approval for this ${e} command`;case`asyncAgent`:return t.reason}}return`Work Mate requested permissions to use ${e}, but you haven't granted it yet.`}function x9(e){return k9.flatMap(t=>(e.alwaysDenyRules[t]||[]).map(e=>({source:t,ruleBehavior:`deny`,ruleValue:Er(e)})))}function S9(e){return k9.flatMap(t=>(e.alwaysAskRules[t]||[]).map(e=>({source:t,ruleBehavior:`ask`,ruleValue:Er(e)})))}function C9(e,t){if(t.ruleValue.ruleContent!==void 0)return!1;let n=Bre(e);if(t.ruleValue.toolName===n)return!0;let r=Fr(t.ruleValue.toolName),i=Fr(n);return r!==null&&i!==null&&(r.toolName===void 0||r.toolName===`*`)&&r.serverName===i.serverName}function nkt(e,t){return y9(e).find(e=>C9(t,e))||null}function w9(e,t){return x9(e).find(e=>C9(t,e))||null}function rkt(e,t){return S9(e).find(e=>C9(t,e))||null}function ikt(e,t,n){return x9(e).find(e=>e.ruleValue.toolName===t&&e.ruleValue.ruleContent===n)||null}function T9(e,t,n){let r=new Set;for(let e of x9(t))e.ruleValue.toolName===n&&e.ruleValue.ruleContent!==void 0&&r.add(e.ruleValue.ruleContent);return e.filter(e=>!r.has(e.agentType))}function E9(e,t,n){return D9(e,Bre(t),n)}function D9(e,t,n){let r=new Map,i=[];switch(n){case`allow`:i=y9(e);break;case`deny`:i=x9(e);break;case`ask`:i=S9(e);break}for(let e of i)e.ruleValue.toolName===t&&e.ruleValue.ruleContent!==void 0&&e.ruleBehavior===n&&r.set(e.ruleValue.ruleContent,e);return r}async function akt(e,t,n,r,i,a){try{for await(let o of xEt(e.name,n,t,r,i,a,r.abortController.signal)){if(!o.permissionRequestResult)continue;let n=o.permissionRequestResult;if(n.behavior===`allow`){let e=n.updatedInput??t;return n.updatedPermissions?.length&&(cVe(n.updatedPermissions),r.setAppState(e=>({...e,toolPermissionContext:xB(e.toolPermissionContext,n.updatedPermissions)}))),{behavior:`allow`,updatedInput:e,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}if(n.behavior===`deny`)return n.interrupt&&(U(`Hook interrupt: tool=${e.name} hookMessage=${n.message}`),r.abortController.abort()),{behavior:`deny`,message:n.message||`Permission denied by hook`,decisionReason:{type:`hook`,hookName:`PermissionRequest`,reason:n.message}}}}catch(e){q(Error(`PermissionRequest hook failed for headless agent`,{cause:jn(e)}))}return null}function O9(e,t){e.localDenialTracking?Object.assign(e.localDenialTracking,t):e.setAppState(e=>e.denialTracking===t?e:{...e,denialTracking:t})}function okt(e,t,n,r,i,a,o){if(!Fmt(e))return null;let s=e.totalDenials>=N1.maxTotal,c=t.toolPermissionContext.shouldAvoidPermissionPrompts,l=e.totalDenials,u=e.consecutiveDenials,d=s?`${l} actions were blocked this session. Please review the transcript before continuing.`:`${u} consecutive actions were blocked. Please review the transcript before continuing.`;if(J(`tengu_auto_mode_denial_limit_exceeded`,{limit:s?`total`:`consecutive`,mode:c?`headless`:`cli`,messageID:r.message.id,consecutiveDenials:u,totalDenials:l,toolName:Dc(i.name)}),c)throw new Sn(`Agent aborted: too many classifier denials in headless mode`);U(`Classifier denial limit exceeded, falling back to prompting: ${d}`,{level:`warn`}),s&&O9(o,{...e,totalDenials:0,consecutiveDenials:0});let f=a.decisionReason?.type===`classifier`?a.decisionReason.classifier:`auto-mode`;return{...a,decisionReason:{type:`classifier`,classifier:f,reason:`${d}\n\nLatest blocked action: ${n}`}}}async function skt(e,t,n){let r=n.getAppState(),i=w9(r.toolPermissionContext,e);if(i)return{behavior:`deny`,decisionReason:{type:`rule`,rule:i},message:`Permission to use ${e.name} has been denied.`};let a=rkt(r.toolPermissionContext,e);if(a&&!(e.name===`Bash`&&Tg.isSandboxingEnabled()&&Tg.isAutoAllowBashIfSandboxedEnabled()&&_9(t)))return{behavior:`ask`,decisionReason:{type:`rule`,rule:a},message:b9(e.name)};let o={behavior:`passthrough`,message:b9(e.name)};try{let r=e.inputSchema.parse(t);o=await e.checkPermissions(r,n)}catch(e){if(e instanceof Sn||e instanceof In)throw e;q(e)}return o?.behavior===`deny`||o?.behavior===`ask`&&o.decisionReason?.type===`rule`&&o.decisionReason.rule.ruleBehavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`safetyCheck`?o:null}async function ckt(e,t,n){if(n.abortController.signal.aborted)throw new Sn;let r=n.getAppState(),i=w9(r.toolPermissionContext,e);if(i)return{behavior:`deny`,decisionReason:{type:`rule`,rule:i},message:`Permission to use ${e.name} has been denied.`};let a=rkt(r.toolPermissionContext,e);if(a&&!(e.name===`Bash`&&Tg.isSandboxingEnabled()&&Tg.isAutoAllowBashIfSandboxedEnabled()&&_9(t)))return{behavior:`ask`,decisionReason:{type:`rule`,rule:a},message:b9(e.name)};let o={behavior:`passthrough`,message:b9(e.name)};try{let r=e.inputSchema.parse(t);o=await e.checkPermissions(r,n)}catch(e){if(e instanceof Sn||e instanceof In)throw e;q(e)}if(o?.behavior===`deny`||e.requiresUserInteraction?.()&&o?.behavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`rule`&&o.decisionReason.rule.ruleBehavior===`ask`||o?.behavior===`ask`&&o.decisionReason?.type===`safetyCheck`)return o;if(r=n.getAppState(),r.toolPermissionContext.mode===`bypassPermissions`||r.toolPermissionContext.mode===`plan`&&r.toolPermissionContext.isBypassPermissionsModeAvailable)return{behavior:`allow`,updatedInput:pkt(o,t),decisionReason:{type:`mode`,mode:r.toolPermissionContext.mode}};let s=nkt(r.toolPermissionContext,e);if(s)return{behavior:`allow`,updatedInput:pkt(o,t),decisionReason:{type:`rule`,rule:s}};let c=o.behavior===`passthrough`?{...o,behavior:`ask`,message:b9(e.name,o.decisionReason)}:o;return c.behavior===`ask`&&c.suggestions&&U(`Permission suggestions for ${e.name}: ${V(c.suggestions,null,2)}`),c}async function lkt({rule:e,initialContext:t,setToolPermissionContext:n}){if(e.source===`policySettings`||e.source===`flagSettings`||e.source===`command`)throw Error(`Cannot delete permission rules from read-only settings`);let r=bB(t,{type:`removeRules`,rules:[e.ruleValue],behavior:e.ruleBehavior,destination:e.source});switch(e.source){case`localSettings`:case`userSettings`:case`projectSettings`:tVe(e);break;case`cliArg`:case`session`:break}n(r)}function ukt(e,t){let n=new Map;for(let t of e){let e=`${t.source}:${t.ruleBehavior}`;n.has(e)||n.set(e,[]),n.get(e).push(t.ruleValue)}let r=[];for(let[e,i]of n){let[n,a]=e.split(`:`);r.push({type:t,rules:i,behavior:a,destination:n})}return r}function dkt(e,t){return xB(e,ukt(t,`addRules`))}function fkt(e,t){let n=e;if(gB()){let e=[`userSettings`,`projectSettings`,`localSettings`,`cliArg`,`session`],t=[`allow`,`deny`,`ask`];for(let r of e)for(let e of t)n=bB(n,{type:`replaceRules`,rules:[],behavior:e,destination:r})}for(let e of[`userSettings`,`projectSettings`,`localSettings`])for(let t of[`allow`,`deny`,`ask`])n=bB(n,{type:`replaceRules`,rules:[],behavior:t,destination:e});let r=ukt(t,`replaceRules`);return xB(n,r)}function pkt(e,t){return(`updatedInput`in e?e.updatedInput:void 0)??t}var k9,A9,j9=n((()=>{Nn(),Ur(),xr(),v9(),bs(),ds(),Dq(),g9(),W(),On(),Qi(),Eg(),qr(),Ja(),gr(),CB(),fi(),vB(),ekt(),cL(),Wt(),Da(),Cc(),GW(),h(),_7(),m3(),Ao(),Yn(),Imt(),tK(),k9=[...Zr,`cliArg`,`command`,`session`],A9=async(e,t,n,r,i)=>{let a=await ckt(e,t,n);if(a.behavior===`allow`){let e=n.getAppState();{let t=n.localDenialTracking??e.denialTracking;e.toolPermissionContext.mode===`auto`&&t&&t.consecutiveDenials>0&&O9(n,M1(t))}return a}if(a.behavior===`ask`){let o=n.getAppState();if(o.toolPermissionContext.mode===`dontAsk`)return{behavior:`deny`,decisionReason:{type:`mode`,mode:`dontAsk`},message:sbt(e.name)};if(o.toolPermissionContext.mode===`auto`||o.toolPermissionContext.mode===`plan`&&iL()){if(a.decisionReason?.type===`safetyCheck`&&!a.decisionReason.classifierApprovable)return o.toolPermissionContext.shouldAvoidPermissionPrompts?{behavior:`deny`,message:a.message,decisionReason:{type:`asyncAgent`,reason:`Safety check requires interactive approval and permission prompts are not available in this context`}}:a;if(e.requiresUserInteraction?.()&&a.behavior===`ask`)return a;let i=n.localDenialTracking??o.denialTracking??Nmt();if(e.name===`PowerShell`)return o.toolPermissionContext.shouldAvoidPermissionPrompts?{behavior:`deny`,message:`PowerShell tool requires interactive approval`,decisionReason:{type:`asyncAgent`,reason:`PowerShell tool requires interactive approval and permission prompts are not available in this context`}}:(U(`Skipping auto mode classifier for ${e.name}: tool requires explicit user permission`),a);if(a.behavior===`ask`&&e.name!==`Agent`&&e.name!==`REPL`)try{let a=e.inputSchema.parse(t),o=await e.checkPermissions(a,{...n,getAppState:()=>{let e=n.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`acceptEdits`}}}});if(o.behavior===`allow`)return O9(n,M1(i)),U(`Skipping auto mode classifier for ${e.name}: would be allowed in acceptEdits mode`),J(`tengu_auto_mode_decision`,{decision:`allowed`,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,confidence:`high`,fastPath:`acceptEdits`}),{behavior:`allow`,updatedInput:o.updatedInput??t,decisionReason:{type:`mode`,mode:`auto`}}}catch(e){if(e instanceof Sn||e instanceof In)throw e}if(QOt(e.name))return O9(n,M1(i)),U(`Skipping auto mode classifier for ${e.name}: tool is on the safe allowlist`),J(`tengu_auto_mode_decision`,{decision:`allowed`,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,confidence:`high`,fastPath:`allowlist`}),{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`auto`}};let s=X2e(e.name,t),c;try{c=await U2e(n.messages,s,n.options.tools,o.toolPermissionContext,n.abortController.signal)}finally{}let l=c.unavailable?`unavailable`:c.shouldBlock?`blocked`:`allowed`,u=c.usage&&c.model?to(c.model,c.usage):void 0;if(J(`tengu_auto_mode_decision`,{decision:l,toolName:Dc(e.name),inProtectedNamespace:y(),agentMsgId:r.message.id,classifierModel:c.model,consecutiveDenials:c.shouldBlock?i.consecutiveDenials+1:0,totalDenials:c.shouldBlock?i.totalDenials+1:i.totalDenials,classifierInputTokens:c.usage?.inputTokens,classifierOutputTokens:c.usage?.outputTokens,classifierCacheReadInputTokens:c.usage?.cacheReadInputTokens,classifierCacheCreationInputTokens:c.usage?.cacheCreationInputTokens,classifierDurationMs:c.durationMs,classifierSystemPromptLength:c.promptLengths?.systemPrompt,classifierToolCallsLength:c.promptLengths?.toolCalls,classifierUserPromptsLength:c.promptLengths?.userPrompts,sessionInputTokens:Lt(),sessionOutputTokens:tn(),sessionCacheReadInputTokens:cte(),sessionCacheCreationInputTokens:pne(),classifierCostUSD:u,classifierStage:c.stage,classifierStage1InputTokens:c.stage1Usage?.inputTokens,classifierStage1OutputTokens:c.stage1Usage?.outputTokens,classifierStage1CacheReadInputTokens:c.stage1Usage?.cacheReadInputTokens,classifierStage1CacheCreationInputTokens:c.stage1Usage?.cacheCreationInputTokens,classifierStage1DurationMs:c.stage1DurationMs,classifierStage1RequestId:c.stage1RequestId,classifierStage1MsgId:c.stage1MsgId,classifierStage1CostUSD:c.stage1Usage&&c.model?to(c.model,c.stage1Usage):void 0,classifierStage2InputTokens:c.stage2Usage?.inputTokens,classifierStage2OutputTokens:c.stage2Usage?.outputTokens,classifierStage2CacheReadInputTokens:c.stage2Usage?.cacheReadInputTokens,classifierStage2CacheCreationInputTokens:c.stage2Usage?.cacheCreationInputTokens,classifierStage2DurationMs:c.stage2DurationMs,classifierStage2RequestId:c.stage2RequestId,classifierStage2MsgId:c.stage2MsgId,classifierStage2CostUSD:c.stage2Usage&&c.model?to(c.model,c.stage2Usage):void 0}),c.durationMs!==void 0&&Qte(c.durationMs),c.shouldBlock){if(c.transcriptTooLong){if(o.toolPermissionContext.shouldAvoidPermissionPrompts)throw new Sn(`Agent aborted: auto mode classifier transcript exceeded context window in headless mode`);return U(`Auto mode classifier transcript too long, falling back to normal permission handling`,{level:`warn`}),{...a,decisionReason:{type:`other`,reason:`Auto mode classifier transcript exceeded context window — falling back to manual approval`}}}if(c.unavailable)return o.toolPermissionContext.shouldAvoidPermissionPrompts?(U(`Auto mode classifier unavailable, denying with retry guidance (fail closed)`,{level:`warn`}),{behavior:`deny`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:`Classifier unavailable`},message:lbt(e.name,c.model)}):(U(`Auto mode classifier unavailable, falling back to prompting with retry guidance (fail closed)`,{level:`warn`}),{behavior:`ask`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:`Classifier unavailable`},message:lbt(e.name,c.model)});let t=Pmt(i);return O9(n,t),U(`Auto mode classifier blocked action: ${c.reason}`,{level:`warn`}),okt(t,o,c.reason,r,e,a,n)||{behavior:`deny`,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:c.reason},message:cbt(c.reason)}}return O9(n,M1(i)),{behavior:`allow`,updatedInput:t,decisionReason:{type:`classifier`,classifier:`auto-mode`,reason:c.reason}}}if(o.toolPermissionContext.shouldAvoidPermissionPrompts)return await akt(e,t,i,n,o.toolPermissionContext.mode,a.suggestions)||{behavior:`deny`,decisionReason:{type:`asyncAgent`,reason:`Permission prompts are not available in this context`},message:obt(e.name)}}return a}}));async function mkt(e,t){if(!e)return{resultType:`emptyPath`};let n=el(Qr(e));try{if(!(await Nl(n)).isDirectory())return{resultType:`notADirectory`,directoryPath:e,absolutePath:n}}catch(t){let r=Cn(t);if(r===`ENOENT`||r===`ENOTDIR`||r===`EACCES`||r===`EPERM`)return{resultType:`pathNotFound`,directoryPath:e,absolutePath:n};throw t}let r=C8(t);for(let t of r)if(T8(n,t))return{resultType:`alreadyInWorkingDirectory`,directoryPath:e,workingDir:t};return{resultType:`success`,absolutePath:n}}function hkt(e){switch(e.resultType){case`emptyPath`:return`Please provide a directory path.`;case`pathNotFound`:return`Path ${Ue.bold(e.absolutePath)} was not found.`;case`notADirectory`:{let t=qc(e.absolutePath);return`${Ue.bold(e.directoryPath)} is not a directory. Did you mean to add the parent directory ${Ue.bold(t)}?`}case`alreadyInWorkingDirectory`:return`${Ue.bold(e.directoryPath)} is already accessible within the existing working directory ${Ue.bold(e.workingDir)}.`;case`success`:return`Added ${Ue.bold(e.absolutePath)} as a working directory.`}}var gkt=n((()=>{Ge(),On(),Lr(),R8()}));function _kt(e,t){if(e!==`Bash`)return!1;if(t===void 0||t===``)return!0;let n=t.trim().toLowerCase();if(n===`*`)return!0;for(let e of adt){let t=e.toLowerCase();if(n===t||n===`${t}:*`||n===`${t}*`||n===`${t} *`||n.startsWith(`${t} -`)&&n.endsWith(`*`))return!0}return!1}function vkt(e,t){if(e!==`PowerShell`)return!1;if(t===void 0||t===``)return!0;let n=t.trim().toLowerCase();if(n===`*`)return!0;let r=[...E$,`pwsh`,`powershell`,`cmd`,`wsl`,`iex`,`invoke-expression`,`icm`,`invoke-command`,`start-process`,`saps`,`start`,`start-job`,`sajb`,`start-threadjob`,`register-objectevent`,`register-engineevent`,`register-wmievent`,`register-scheduledjob`,`new-pssession`,`nsn`,`enter-pssession`,`etsn`,`add-type`,`new-object`];for(let e of r){if(n===e||n===`${e}:*`||n===`${e}*`||n===`${e} *`||n.startsWith(`${e} -`)&&n.endsWith(`*`))return!0;let t=e.indexOf(` `),r=t===-1?`${e}.exe`:`${e.slice(0,t)}.exe${e.slice(t)}`;if(n===r||n===`${r}:*`||n===`${r}*`||n===`${r} *`||n.startsWith(`${r} -`)&&n.endsWith(`*`))return!0}return!1}function ykt(e,t){return Zn(e)===ur}function bkt(e){if(Zr.includes(e)){let t=ti(e);if(t){let e=$c(yn(),t);return e.length<t.length?e:t}}return e}function xkt(e,t){return _kt(e,t)||vkt(e,t)||ykt(e,t)}function Skt(e,t){let n=[];for(let t of e)if(t.ruleBehavior===`allow`&&xkt(t.ruleValue.toolName,t.ruleValue.ruleContent)){let e=t.ruleValue.ruleContent?`${t.ruleValue.toolName}(${t.ruleValue.ruleContent})`:`${t.ruleValue.toolName}(*)`;n.push({ruleValue:t.ruleValue,source:t.source,ruleDisplay:e,sourceDisplay:bkt(t.source)})}for(let e of t){let t=e.match(/^([^(]+)(?:\(([^)]*)\))?$/);if(t){let r=t[1].trim(),i=t[2]?.trim();xkt(r,i)&&n.push({ruleValue:{toolName:r,ruleContent:i},source:`cliArg`,ruleDisplay:i?e:`${r}(*)`,sourceDisplay:`--allowed-tools`})}}return n}function Ckt(e){return[`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`].includes(e)}function wkt(e,t){let n=new Map;for(let e of t){if(!Ckt(e.source))continue;let t=e.source,r=n.get(t)||[];r.push(e.ruleValue),n.set(t,r)}let r=e;for(let[e,t]of n)r=bB(r,{type:`removeRules`,rules:t,behavior:`allow`,destination:e});return r}function M9(e){let t=[];for(let[n,r]of Object.entries(e.alwaysAllowRules))if(r)for(let e of r){let r=Er(e);t.push({source:n,ruleBehavior:`allow`,ruleValue:r})}let n=Skt(t,[]);if(n.length===0)return{...e,strippedDangerousRules:e.strippedDangerousRules??{}};for(let e of n)U(`Ignoring dangerous permission ${e.ruleDisplay} from ${e.sourceDisplay} (bypasses classifier)`);let r={};for(let e of n){var i;Ckt(e.source)&&(r[i=e.source]??(r[i]=[])).push(or(e.ruleValue))}return{...wkt(e,n),strippedDangerousRules:r}}function N9(e){let t=e.strippedDangerousRules;if(!t)return e;let n=e;for(let[e,r]of Object.entries(t))!r||r.length===0||(n=bB(n,{type:`addRules`,rules:r.map(Er),behavior:`allow`,destination:e}));return{...n,strippedDangerousRules:void 0}}function Tkt(e,t,n){if(e===t)return n;gne(e,t),rte(e,t),e===`plan`&&t!==`plan`&&Gt(!0);{if(t===`plan`&&e!==`plan`)return R9(n);let r=e===`auto`||e===`plan`&&iL(),i=t===`auto`;if(i&&!r){if(!I9())throw Error(`Cannot transition to auto mode: gate is not enabled`);rL(!0),n=M9(n)}else r&&!i&&(rL(!1),Mt(!0),n=N9(n))}return e===`plan`&&t!==`plan`&&n.prePlanMode?{...n,prePlanMode:void 0}:n}function Ekt(e){return Nft(e.join(` `).trim())?Pft():P9(e)}function Dkt({processPwd:e,originalCwd:t}){let{resolvedPath:n,isSymlink:r}=Vn(G(),e);return r?n===el(t):!1}function Okt({permissionModeCli:e,dangerouslySkipPermissions:t}){let n=zr()||{},r=n.permissions?.disableBypassPermissionsMode===`disable`,i=[],a;if(t&&i.push(`bypassPermissions`),e){let t=Hne(e);t===`auto`?i.push(`auto`):i.push(t)}if(n.permissions?.defaultMode){let e=n.permissions.defaultMode;m(process.env.CLAUDE_CODE_REMOTE)&&![`acceptEdits`,`plan`,`default`].includes(e)?(U(`settings defaultMode "${e}" is not supported in CLAUDE_CODE_REMOTE — only acceptEdits and plan are allowed`,{level:`warn`}),J(`tengu_ccr_unsupported_default_mode_ignored`,{mode:e})):e===`auto`?i.push(`auto`):i.push(e)}let o;for(let e of i){if(e===`bypassPermissions`&&r){U(`bypassPermissions mode is disabled by settings`,{level:`warn`}),a=`Bypass permissions mode was disabled by settings`;continue}o={mode:e,notification:a};break}return o||(o={mode:`default`,notification:a}),o||(o={mode:`default`,notification:a}),o.mode===`auto`&&rL(!0),o}function P9(e){if(e.length===0)return[];let t=[];for(let n of e){if(!n)continue;let e=``,r=!1;for(let i of n)switch(i){case`(`:r=!0,e+=i;break;case`)`:r=!1,e+=i;break;case`,`:r?e+=i:(e.trim()&&t.push(e.trim()),e=``);break;case` `:r?e+=i:e.trim()&&(t.push(e.trim()),e=``);break;default:e+=i}e.trim()&&t.push(e.trim())}return t}async function kkt({allowedToolsCli:e,disallowedToolsCli:t,baseToolsCli:n,permissionMode:r,allowDangerouslySkipPermissions:i,addDirs:a}){let o=P9(e).map(e=>or(Er(e))),s=P9(t);if(n&&n.length>0){let e=Ekt(n),t=new Set(e.map(Zn)),r=Pft().filter(e=>!t.has(e));s=[...s,...r]}let c=[],l=new Map,u=process.env.PWD;u&&u!==Xt()&&Dkt({originalCwd:Xt(),processPwd:u})&&l.set(u,{path:u,source:`session`});let d=zr()||{},f=eVe(),p=[],m=[];r===`auto`&&(m=Skt(f,o));let h=dkt({mode:r,additionalWorkingDirectories:l,alwaysAllowRules:{cliArg:o},alwaysDenyRules:{cliArg:s},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0,isAutoModeAvailable:!0},f),g=[...d.permissions?.additionalDirectories||[],...a],_=await Promise.all(g.map(e=>mkt(e,h)));for(let e of _)e.resultType===`success`?h=bB(h,{type:`addDirectories`,directories:[e.absolutePath],destination:`cliArg`}):e.resultType!==`alreadyInWorkingDirectory`&&e.resultType!==`pathNotFound`&&c.push(hkt(e));return{toolPermissionContext:h,warnings:c,dangerousPermissions:m,overlyBroadBashPermissions:p}}function F9(e){let t;switch(e){case`settings`:t=`auto mode disabled by settings`;break;case`circuit-breaker`:t=`auto mode is unavailable for your plan`;break;case`model`:t=`auto mode unavailable for this model`;break}return t}async function Akt(e,t){let n={},r=Nkt(n?.enabled),i=jkt();TFe(r===`disabled`||i);let a=Qo(),o=!!n?.disableFastMode&&!!t,s=_ae(a)&&!o,c=!1;r!==`disabled`&&!i&&s&&(c=r===`enabled`||Pkt());let l=r!==`disabled`&&!i&&s;U(`[auto-mode] verifyAutoModeGateAccess: enabledState=${r} disabledBySettings=${i} model=${a} modelSupported=${s} disableFastModeBreakerFires=${o} carouselAvailable=${c} canEnterAuto=${l}`);let u=wFe(),d=(e,t)=>(e.isAutoModeAvailable!==t&&U(`[auto-mode] verifyAutoModeGateAccess setAvailable: ${e.isAutoModeAvailable} -> ${t}`),e.isAutoModeAvailable===t?e:{...e,isAutoModeAvailable:t});if(l)return{updateContext:e=>d(e,c)};let f;i?(f=`settings`,U(`auto mode disabled: disableAutoMode in settings`,{level:`warn`})):r===`disabled`?(f=`circuit-breaker`,U(`auto mode disabled: tengu_auto_mode_config.enabled === "disabled" (circuit breaker)`,{level:`warn`})):(f=`model`,U(`auto mode disabled: model ${Qo()} does not support auto mode`,{level:`warn`}));let p=F9(f),m=e=>{let t=e.mode===`auto`;U(`[auto-mode] kickOutOfAutoIfNeeded applying: ctx.mode=${e.mode} ctx.prePlanMode=${e.prePlanMode} reason=${f}`);let n=e.mode===`plan`&&(e.prePlanMode===`auto`||!!e.strippedDangerousRules);return!t&&!n?d(e,!1):t?(rL(!1),Mt(!0),{...bB(N9(e),{type:`setMode`,mode:`default`,destination:`session`}),isAutoModeAvailable:!1}):(rL(!1),Mt(!0),{...N9(e),prePlanMode:e.prePlanMode===`auto`?`default`:e.prePlanMode,isAutoModeAvailable:!1})},h=e.mode===`auto`,g=e.mode===`plan`&&(e.prePlanMode===`auto`||!!e.strippedDangerousRules);return h||g||u?h||g?{updateContext:m,notification:p}:{updateContext:m,notification:e.isAutoModeAvailable?p:void 0}:{updateContext:m}}function jkt(){let e=zr()||{};return e.disableAutoMode===`disable`||e.permissions?.disableAutoMode===`disable`}function I9(){return!0}function Mkt(){return jkt()?`settings`:EFe()?`circuit-breaker`:_ae(Qo())?null:`model`}function Nkt(e){return e===`enabled`||e===`disabled`||e===`opt-in`?e:zkt}function Pkt(){return wFe()??!1?!0:Dre()}function L9(){return(zr()||{}).permissions?.disableBypassPermissionsMode===`disable`}function Fkt(e){let t=e;return e.mode===`bypassPermissions`&&(t=bB(e,{type:`setMode`,mode:`default`,destination:`session`})),{...t,isBypassPermissionsModeAvailable:!1}}function Ikt(){return!1}function Lkt(){return Dre()&&I9()&&Pre()}function R9(e){let t=e.mode;if(t===`plan`)return e;{let n=Lkt();if(t===`auto`)return n?{...e,prePlanMode:`auto`}:(rL(!1),Mt(!0),{...N9(e),prePlanMode:`auto`});if(n&&t!==`bypassPermissions`)return rL(!0),{...M9(e),prePlanMode:t}}return U(`[prepareContextForPlanMode] plain plan entry, prePlanMode=${t}`,{level:`info`}),{...e,prePlanMode:t}}function Rkt(e){if(e.mode!==`plan`||e.prePlanMode===`bypassPermissions`)return e;let t=Lkt(),n=iL();return t&&n?M9(e):!t&&!n?e:t?(rL(!0),Mt(!1),M9(e)):(rL(!1),Mt(!0),N9(e))}var zkt,z9=n((()=>{Wt(),vn(),h(),qr(),Vr(),gr(),j9(),vB(),cL(),gkt(),Da(),xr(),bs(),ds(),i1(),Bn(),Uo(),W(),YJ(),No(),odt(),CB(),fi(),zkt=`enabled`}));function B9(e,t=`Custom item`){let n=e.split(`
3456
3456
  `);for(let e of n){let t=e.trim();if(t){let e=t.match(/^#+\s+(.+)$/)?.[1]??t;return e.length>100?`${e.substring(0,97)}...`:e}}return t}function Bkt(e){if(e==null)return null;if(!e)return[];let t=[];if(typeof e==`string`?t=[e]:Array.isArray(e)&&(t=e.filter(e=>typeof e==`string`)),t.length===0)return[];let n=P9(t);return n.includes(`*`)?[`*`]:n}function V9(e){let t=Bkt(e);if(t===null)return e===void 0?void 0:[];if(!t.includes(`*`))return t}function H9(e){let t=Bkt(e);return t===null?[]:t}async function Vkt(e){try{let t=await uue(e,{bigint:!0});return t.dev===0n&&t.ino===0n?null:`${t.dev}:${t.ino}`}catch{return null}}function Hkt(e){let t=Fi(e),n=Fi(en());if(!t||!n)return t;let r=Ni(e);if(r&&_r(r)===_r(n))return t;let i=_r(t),a=_r(n);return i!==a&&i.startsWith(a+tl)?n:t}function U9(e,t){let n=el(Uc()).normalize(`NFC`),r=Hkt(t),i=el(t),a=[];for(;_r(i)!==_r(n);){let t=Y(i,`.workmate`,e);try{Lle(t),a.push(t)}catch(e){if(!Mn(e))throw e}if(r&&_r(i)===_r(r))break;let n=qc(i);if(n===i)break;i=n}return a}async function Ukt(e,t){let n=[],r=new Set;async function i(e){if(!t.aborted){try{let t=await Nl(e,{bigint:!0});if(t.isDirectory()){let n=t.dev!==void 0&&t.ino!==void 0?`${t.dev}:${t.ino}`:await Al(e);if(r.has(n)){U(`Skipping already visited directory (circular symlink): ${e}`);return}r.add(n)}}catch(t){U(`Failed to stat directory ${e}: ${t instanceof Error?t.message:String(t)}`);return}try{let r=await kl(e,{withFileTypes:!0});for(let a of r){if(t.aborted)break;let r=Y(e,a.name);try{if(a.isSymbolicLink())try{let e=await Nl(r);e.isDirectory()?await i(r):e.isFile()&&a.name.endsWith(`.md`)&&n.push(r)}catch(e){U(`Failed to follow symlink ${r}: ${e instanceof Error?e.message:String(e)}`)}else a.isDirectory()?await i(r):a.isFile()&&a.name.endsWith(`.md`)&&n.push(r)}catch(e){U(`Failed to access ${r}: ${e instanceof Error?e.message:String(e)}`)}}}catch(t){U(`Failed to read directory ${e}: ${t instanceof Error?t.message:String(t)}`)}}}return await i(e),n}async function W9(e){let t=m(process.env.CLAUDE_CODE_USE_NATIVE_FILE_SEARCH),n=AbortSignal.timeout(3e3),r;try{r=t?await Ukt(e,n):await gc([`--files`,`--hidden`,`--follow`,`--no-ignore`,`--glob`,`*.md`],e,n)}catch(e){if(Mn(e))return[];throw e}return(await Promise.all(r.map(async e=>{try{let{frontmatter:t,content:n}=od(await Ol(e,{encoding:`utf-8`}),e);return{filePath:e,frontmatter:t,content:n}}catch(t){return U(`Failed to read/parse markdown file: ${e}: ${t instanceof Error?t.message:String(t)}`),null}}))).filter(e=>e!==null)}var Wkt,G9,K9=n((()=>{d(),Da(),Wt(),W(),h(),On(),ci(),gd(),Mi(),z9(),mc(),qr(),Sr(),Hv(),Wkt=[`commands`,`agents`,`output-styles`,`skills`,`workflows`,`templates`],G9=u(async(e,t)=>{let n=Date.now(),r=Y(p(),e),i=Y(kr(),`.workmate`,e),a=U9(e,t),o=Fi(t),s=Ni(t);if(o&&s&&s!==o){let t=_r(Y(o,`.workmate`,e));if(!a.some(e=>_r(e)===t)){let t=Y(s,`.workmate`,e);a.includes(t)||a.push(t)}}let[c,l,u]=await Promise.all([W9(i).then(e=>e.map(e=>({...e,baseDir:i,source:`policySettings`}))),ii(`userSettings`)&&!(e===`agents`&&Bv(`agents`))?W9(r).then(e=>e.map(e=>({...e,baseDir:r,source:`userSettings`}))):Promise.resolve([]),ii(`projectSettings`)&&!(e===`agents`&&Bv(`agents`))?Promise.all(a.map(e=>W9(e).then(t=>t.map(t=>({...t,baseDir:e,source:`projectSettings`}))))):Promise.resolve([])]),d=u.flat(),f=[...c,...l,...d],m=await Promise.all(f.map(e=>Vkt(e.filePath))),h=new Map,g=[];for(let[e,t]of f.entries()){let n=m[e]??null;if(n===null){g.push(t);continue}let r=h.get(n);if(r!==void 0){U(`Skipping duplicate file '${t.filePath}' from ${t.source} (same inode already loaded from ${r})`);continue}h.set(n,t.source),g.push(t)}let _=f.length-g.length;return _>0&&U(`Deduplicated ${_} files in ${e} (same inode via symlinks or hard links)`),J(`tengu_dir_search`,{durationMs:Date.now()-n,managedFilesFound:c.length,userFilesFound:l.length,projectFilesFound:d.length,projectDirsSearched:a.length,subdir:e}),g},(e,t)=>`${e}:${t}`)})),Gkt=n((()=>{gt(),vn(),W(),_t(),Yn(),Jd(),ht(()=>B({updatedAt:L().min(1)})),ht(()=>B({syncedFrom:L().min(1)}))}));function q9(e){return e.source===`built-in`}function Kkt(e){return e.source!==`built-in`&&e.source!==`plugin`}function qkt(e){return e.source===`plugin`}function Jkt(e){let t=e.filter(e=>e.source===`built-in`),n=e.filter(e=>e.source===`plugin`),r=e.filter(e=>e.source===`userSettings`),i=e.filter(e=>e.source===`projectSettings`),a=e.filter(e=>e.source===`policySettings`),o=[t,n,r,i,e.filter(e=>e.source===`flagSettings`),a],s=new Map;for(let e of o)for(let t of e)s.set(t.agentType,t);return Array.from(s.values())}function J9(e,t){return!e.requiredMcpServers||e.requiredMcpServers.length===0||e.requiredMcpServers.every(e=>t.some(t=>t.toLowerCase().includes(e.toLowerCase())))}function Y9(e,t){return e.filter(e=>J9(e,t))}function Ykt(){Q9.cache.clear?.(),G9.cache?.clear?.(),g_t()}function Xkt(e){let t=e.name,n=e.description;return!t||typeof t!=`string`?`Missing required "name" field in frontmatter`:!n||typeof n!=`string`?`Missing required "description" field in frontmatter`:`Unknown parsing error`}function Zkt(e,t){if(!e.hooks)return;let n=nr().safeParse(e.hooks);if(!n.success){U(`Invalid hooks in agent '${t}': ${n.error.message}`);return}return n.data}function Qkt(e,t,n=`flagSettings`){try{let r=Z9().parse(t),i=V9(r.tools);if(_i()&&r.memory&&i!==void 0){let e=new Set(i);for(let t of[ks,ws,gs])e.has(t)||(i=[...i,t])}let a=r.disallowedTools===void 0?void 0:V9(r.disallowedTools),o=r.prompt;return{agentType:e,whenToUse:r.description,...i===void 0?{}:{tools:i},...a===void 0?{}:{disallowedTools:a},getSystemPrompt:()=>_i()&&r.memory?`${o}\n\n${qd(e,r.memory)}`:o,source:n,...r.model?{model:r.model}:{},...r.permissionMode?{permissionMode:r.permissionMode}:{},...r.mcpServers&&r.mcpServers.length>0?{mcpServers:r.mcpServers}:{},...r.hooks?{hooks:r.hooks}:{},...r.maxTurns===void 0?{}:{maxTurns:r.maxTurns},...r.skills&&r.skills.length>0?{skills:r.skills}:{},...r.initialPrompt?{initialPrompt:r.initialPrompt}:{},...r.background?{background:r.background}:{},...r.memory?{memory:r.memory}:{},...r.isolation?{isolation:r.isolation}:{}}}catch(t){return U(`Error parsing agent '${e}' from JSON: ${t instanceof Error?t.message:String(t)}`),q(t),null}}function $kt(e,t=`flagSettings`){try{let n=tAt().parse(e);return Object.entries(n).map(([e,n])=>Qkt(e,n,t)).filter(e=>e!==null)}catch(e){return U(`Error parsing agents from JSON: ${e instanceof Error?e.message:String(e)}`),q(e),[]}}function eAt(e,t,n,r,i){try{let a=n.name,o=n.description;if(!a||typeof a!=`string`)return null;if(!o||typeof o!=`string`)return U(`Agent file ${e} is missing required 'description' in frontmatter`),null;o=o.replace(/\\n/g,`
3457
3457
  `);let s=n.color,c=n.model,l;if(typeof c==`string`&&c.trim().length>0){let e=c.trim();l=e.toLowerCase()===`inherit`?`inherit`:e}let u=n.background;u!==void 0&&u!==`true`&&u!==`false`&&u!==!0&&u!==!1&&U(`Agent file ${e} has invalid background value '${u}'. Must be 'true', 'false', or omitted.`);let d=u===`true`||u===!0||void 0,f=[`user`,`project`,`local`],p=n.memory,m;p!==void 0&&(f.includes(p)?m=p:U(`Agent file ${e} has invalid memory value '${p}'. Valid options: ${f.join(`, `)}`));let h=[`worktree`],g=n.isolation,_;g!==void 0&&(h.includes(g)?_=g:U(`Agent file ${e} has invalid isolation value '${g}'. Valid options: ${h.join(`, `)}`));let v=n.permissionMode,y=v&&$n.includes(v);v&&!y&&U(`Agent file ${e} has invalid permissionMode '${v}'. Valid options: ${$n.join(`, `)}`);let b=n.maxTurns,x=ld(b);b!==void 0&&x===void 0&&U(`Agent file ${e} has invalid maxTurns '${b}'. Must be a positive integer.`);let S=Kc(e,`.md`),C=V9(n.tools);if(_i()&&m&&C!==void 0){let e=new Set(C);for(let t of[ks,ws,gs])e.has(t)||(C=[...C,t])}let w=n.disallowedTools,T=w===void 0?void 0:V9(w),E=H9(n.skills),D=n.initialPrompt,O=typeof D==`string`&&D.trim()?D:void 0,k=n.mcpServers,A;Array.isArray(k)&&(A=k.map(t=>{let n=X9().safeParse(t);return n.success?n.data:(U(`Agent file ${e} has invalid mcpServers item: ${V(t)}. Error: ${n.error.message}`),null)}).filter(e=>e!==null));let ee=Zkt(n,a),te=r.trim();return{baseDir:t,agentType:a,whenToUse:o,...C===void 0?{}:{tools:C},...T===void 0?{}:{disallowedTools:T},...E===void 0?{}:{skills:E},...O===void 0?{}:{initialPrompt:O},...A!==void 0&&A.length>0?{mcpServers:A}:{},...ee===void 0?{}:{hooks:ee},getSystemPrompt:()=>{if(_i()&&m){let e=qd(a,m);return`${te}\n\n${e}`}return te},source:i,filename:S,...s&&typeof s==`string`&&YG.includes(s)?{color:s}:{},...l===void 0?{}:{model:l},...y?{permissionMode:v}:{},...x===void 0?{}:{maxTurns:x},...d?{background:d}:{},...m?{memory:m}:{},..._?{isolation:_}:{}}}catch(t){return U(`Error parsing agent from ${e}: ${t instanceof Error?t.message:String(t)}`),q(t),null}}var X9,Z9,tAt,Q9,$9=n((()=>{d(),gt(),hi(),Da(),xa(),W(),h(),gd(),_t(),Qi(),K9(),gr(),q0(),yr(),Yn(),Ns(),Fs(),vs(),ZG(),Jd(),Gkt(),T4(),X9=ht(()=>lt([L(),rt(L(),Ca())])),Z9=ht(()=>B({description:L().min(1,`Description cannot be empty`),tools:z(L()).optional(),disallowedTools:z(L()).optional(),prompt:L().min(1,`Prompt cannot be empty`),model:L().trim().min(1,`Model cannot be empty`).transform(e=>e.toLowerCase()===`inherit`?`inherit`:e).optional(),permissionMode:dt($n).optional(),mcpServers:z(X9()).optional(),hooks:nr().optional(),maxTurns:R().int().positive().optional(),skills:z(L()).optional(),initialPrompt:L().optional(),memory:dt([`user`,`project`,`local`]).optional(),background:ft().optional(),isolation:dt([`worktree`]).optional()})),tAt=ht(()=>rt(L(),Z9())),Q9=u(async e=>{if(m(process.env.CLAUDE_CODE_SIMPLE)){let e=w4();return{activeAgents:e,allAgents:e}}try{let t=await G9(`agents`,e),n=[],r=t.map(({filePath:e,baseDir:t,frontmatter:r,content:i,source:a})=>{let o=eAt(e,t,r,i,a);if(!o){if(!r.name)return null;let t=Xkt(r);return n.push({path:e,error:t}),U(`Failed to parse agent from ${e}: ${t}`),J(`tengu_agent_parse_error`,{error:t,location:a}),null}return o}).filter(e=>e!==null),i=await K0(),a=[...w4(),...i,...r],o=Jkt(a);for(let e of o)e.color&&JG(e.agentType,e.color);return{activeAgents:o,allAgents:a,failedFiles:n.length>0?n:void 0}}catch(e){let t=e instanceof Error?e.message:String(e);U(`Error loading agent definitions: ${t}`),q(e);let n=w4();return{activeAgents:n,allAgents:n,failedFiles:[{path:`unknown`,error:t}]}}})}));export{$7 as $,Kbe as $C,ex as $S,af as $T,UR as $_,h4 as $a,yE as $b,p$ as $c,YJ as $d,N6e as $f,GBe as $g,cV as $h,y3 as $i,xit as $l,_U as $m,SCt as $n,lvt as $o,f2e as $p,uCt as $r,Gmt as $s,yEt as $t,Ltt as $u,HFe as $v,Jve as $w,zke as $x,lF as $y,Tkt as A,XSe as AC,HS as AS,Qm as AT,JRe as A_,Ebt as Aa,hM as Ab,Vpt as Ac,yet as Ad,tJ as Af,zB as Ag,Eqe as Ah,ZSt as Ai,vQ as Al,Z$e as Am,M8 as An,Bvt as Ao,pK as Ap,QCt as Ar,$ht as As,x7 as At,Wnt as Au,cR as Av,Mye as Aw,TT as Ax,xI as Ay,A9 as B,cxe as BC,KS as BS,sm as BT,az as B_,N4 as Ba,oD as Bb,opt as Bc,met as Bd,I8e as Bf,EB as Bg,CV as Bh,WSt as Bi,cot as Bl,s$e as Bm,UCt as Bn,Wvt as Bo,y4e as Bp,L6 as Br,jht as Bs,o7 as Bt,RX as Bu,vIe as Bv,qg as Bw,oAe as Bx,wF as By,I9 as C,Ky as CC,eDe as CS,ah as CT,Sze as C_,P4 as Ca,fM as Cb,Xpt as Cc,gY as Cd,pJ as Cf,UB as Cg,sJe as Ch,$St as Ci,mQ as Cl,l0e as Cm,yTt as Cn,tyt as Co,$4e as Cp,nCt as Cr,K0 as Cs,HEt as Ct,crt as Cu,xLe as Cv,Vye as Cw,YT as Cx,LI as Cy,R9 as D,zy as DC,zS as DS,eh as DT,bz as D_,J4 as Da,RM as Db,v1 as Dc,Iet as Dd,o7e as Df,RB as Dg,hH as Dh,qSt as Di,pQ as Dl,nG as Dm,W8 as Dn,z2 as Do,hK as Dp,LCt as Dr,H0 as Ds,T7 as Dt,cZ as Du,CR as Dv,r_ as Dw,cAe as Dx,OI as Dy,P9 as E,PSe as EC,RS as ES,nh as ET,Tz as E_,hbt as Ea,zM as Eb,Kpt as Ec,vY as Ed,c7e as Ef,LB as Eg,fH as Eh,KSt as Ei,gQ as El,sG as Em,V8 as En,V2 as Eo,kK as Ep,t6 as Er,E0 as Es,VEt as Et,art as Eu,yR as Ev,a_ as Ew,aAe as Ex,kI as Ey,mkt as F,by as FC,Yx as FS,rme as FT,fz as F_,dbt as Fa,hD as Fb,g1 as Fc,Met as Fd,e5e as Ff,kB as Fg,ZV as Fh,Q3 as Fi,cQ as Fl,D$e as Fm,g8 as Fn,M2 as Fo,lK as Fp,ewt as Fr,Kht as Fs,EEt as Ft,Ent as Fu,BL as Fv,Zg as Fw,kT as Fx,_Pe as Fy,UOt as G,Bv as GC,NS as GS,tm as GT,$R as G_,F4 as Ga,LAe as Gb,Q$ as Gc,tet as Gd,E8e as Gf,CB as Gg,AHe as Gh,bSt as Gi,HZ as Gl,rW as Gm,G6 as Gn,Gvt as Go,XG as Gp,bCt as Gr,oht as Gs,c7 as Gt,hX as Gu,iIe as Gv,Hg as Gw,pT as Gx,yF as Gy,tkt as H,Jv as HC,bS as HS,om as HT,LRe as H_,Abt as Ha,nD as Hb,Rft as Hc,iet as Hd,D8e as Hf,bB as Hg,TV as Hh,B3 as Hi,JZ as Hl,HW as Hm,$6 as Hn,Vvt as Ho,oK as Hp,sCt as Hr,wht as Hs,l7 as Ht,MX as Hu,PL as Hv,Ug as Hw,Zke as Hx,vF as Hy,lkt as I,Wxe as IC,bx as IS,um as IT,uz as I_,Dbt as Ia,eje as Ib,mpt as Ic,Cet as Id,Q8e as If,OB as Ig,QV as Ih,q3 as Ii,jot as Il,KW as Im,w8 as In,F2 as Io,g4e as Ip,Y6 as Ir,d0 as Is,DEt as It,wnt as Iu,xIe as Iv,Eye as Iw,zT as Ix,RF as Iy,a9 as J,hv as JC,yx as JS,Qp as JT,XR as J_,xbt as Ja,UE as Jb,X$ as Jc,aY as Jd,Eq as Jf,oVe as Jg,hV as Jh,aSt as Ji,PZ as Jl,$U as Jm,ZCt as Jn,rvt as Jo,JG as Jp,y6 as Jr,rht as Js,_Et as Jt,Wtt as Ju,GFe as Jv,Ig as Jw,Wke as Jx,$Ne as Jy,o9 as K,Vv as KC,qS as KS,nm as KT,JR as K_,R4 as Ka,jE as Kb,r1 as Kc,Z9e as Kd,Lq as Kf,sVe as Kg,MHe as Kh,vSt as Ki,LZ as Kl,aW as Km,BCt as Kn,g2 as Ko,qG as Kp,xCt as Kr,aht as Ks,lEt as Kt,Ztt as Ku,AL as Kv,sye as Kw,Gke as Kx,jF as Ky,y9 as L,my as LC,GS as LS,bm as LT,dz as L_,m3 as La,pD as Lb,h1 as Lc,vet as Ld,Z8e as Lf,AB as Lg,KV as Lh,e6 as Li,bot as Ll,C$e as Lm,a8 as Ln,b2 as Lo,_4e as Lp,Z6 as Lr,p0 as Ls,wEt as Lt,bnt as Lu,UL as Lv,Jg as Lw,PT as Lx,LF as Ly,Akt as M,Ey as MC,Hx as MS,Vm as MT,lz as M_,W4 as Ma,gM as Mb,Dpt as Mc,get as Md,nJ as Mf,jB as Mg,aH as Mh,G3 as Mi,tst as Ml,B$e as Mm,v8 as Mn,Cvt as Mo,fK as Mp,rwt as Mr,w0 as Ms,Z5 as Mt,YX as Mu,KIe as Mv,t_ as Mw,OT as Mx,bI as My,hkt as N,yy as NC,zx as NS,Om as NT,vz as N_,Obt as Na,pM as Nb,Ept as Nc,wet as Nd,$8e as Nf,SVe as Ng,nH as Nh,JSt as Ni,nst as Nl,A$e as Nm,R8 as Nn,P2 as No,C4e as Np,V6 as Nr,x0 as Ns,u7 as Nt,Rnt as Nu,aR as Nv,$g as Nw,DT as Nx,CI as Ny,N9 as O,Py as OC,tS as OS,th as OT,xz as O_,O4 as Oa,LM as Ob,Upt as Oc,Fet as Od,cJ as Of,AVe as Og,uH as Oh,YSt as Oi,Qot as Ol,Q$e as Om,o5 as On,Xvt as Oo,gK as Op,f6 as Or,zgt as Os,IEt as Ot,Jnt as Ou,xR as Ov,n_ as Ow,xT as Ox,NI as Oy,gkt as P,xy as PC,qx as PS,Dm as PT,hz as P_,Wbt as Pa,aNe as Pb,hpt as Pc,het as Pd,t5e as Pf,vVe as Pg,xqe as Ph,Z3 as Pi,$ot as Pl,O$e as Pm,y8 as Pn,y2 as Po,h4e as Pp,q6 as Pr,Hht as Ps,CEt as Pt,Vnt as Pu,wIe as Pv,Qg as Pw,bT as Px,gPe as Py,Z7 as Q,dv as QC,ax as QS,of as QT,KR as Q_,E4 as Qa,IAe as Qb,mdt as Qc,UJ as Qd,F6e as Qf,hB as Qg,lV as Qh,w3 as Qi,Oit as Ql,gU as Qm,swt as Qn,nvt as Qo,d2e as Qp,gCt as Qr,G1 as Qs,pEt as Qt,iX as Qu,VFe as Qv,Ag as Qw,aT as Qx,nF as Qy,S9 as R,ry as RC,kS as RS,lm as RT,pz as R_,t3 as Ra,mD as Rb,dpt as Rc,Aet as Rd,X8e as Rf,DB as Rg,iqe as Rh,W3 as Ri,oQ as Rl,GW as Rm,yCt as Rn,Evt as Ro,v4e as Rp,H6 as Rr,s0 as Rs,kEt as Rt,UX as Ru,HL as Rv,Xg as Rw,jT as Rx,FF as Ry,kkt as S,Xy as SC,tDe as SS,oh as ST,xze as S_,$ as Sa,ZMe as Sb,cmt as Sc,EY as Sd,mJ as Sf,HVe as Sg,wJe as Sh,QSt as Si,est as Sl,c0e as Sm,STt as Sn,$vt as So,PK as Sp,lCt as Sr,q0 as Ss,k7 as St,Crt as Su,NLe as Sv,l_ as Sw,mAe as Sx,wPe as Sy,Ikt as T,Ly as TC,jS as TS,rh as TT,sze as T_,q4 as Ta,FM as Tb,Gpt as Tc,_Y as Td,hJ as Tf,YVe as Tg,wH as Th,Y3 as Ti,hQ as Tl,tG as Tm,U8 as Tn,nyt as To,L4e as Tp,Q6 as Tr,Xgt as Ts,GEt as Tt,prt as Tu,bLe as Tv,s_ as Tw,_Ae as Tx,wI as Ty,v9 as U,Gv as UC,xx as US,Fpe as UT,WRe as U_,bbt as Ua,VE as Ub,e1 as Uc,oet as Ud,Aq as Uf,xB as Ug,xV as Uh,BSt as Ui,Sat as Ul,SW as Um,s6 as Un,x2 as Uo,o4e as Up,_Ct as Ur,t0 as Us,uEt as Ut,NX as Uu,uIe as Uv,Wg as Uw,fT as Ux,YNe as Uy,j9 as V,sxe as VC,DS as VS,am as VT,URe as V_,ubt as Va,tD as Vb,a1 as Vc,ret as Vd,M8e as Vf,uVe as Vg,mKe as Vh,U3 as Vi,iQ as Vl,wW as Vm,D6 as Vn,Dvt as Vo,a4e as Vp,iCt as Vr,e0 as Vs,xEt as Vt,FX as Vu,LL as Vv,bye as Vw,lAe as Vx,mF as Vy,_9 as W,Hv as WC,FS as WS,im as WT,QR as W_,V4 as Wa,HE as Wb,$$ as Wc,net as Wd,Pq as Wf,yB as Wg,_V as Wh,ASt as Wi,VZ as Wl,CW as Wm,F6 as Wn,Tvt as Wo,YG as Wp,x6 as Wr,sht as Ws,dEt as Wt,ant as Wu,FL as Wv,Vg as Ww,Qke as Wx,DF as Wy,r9 as X,pv as XC,_x as XS,epe as XT,_Re as X_,Ubt as Xa,FAe as Xb,Z$ as Xc,XJ as Xd,Sq as Xf,vB as Xg,mV as Xh,R3 as Xi,tat as Xl,XU as Xm,nwt as Xn,tvt as Xo,KG as Xp,_6 as Xr,W1 as Xs,OEt as Xt,Rtt as Xu,hL as Xv,Zve as Xw,Vke as Xx,iF as Xy,EOt as Y,_v as YC,gx as YS,$fe as YT,ZR as Y_,uxt as Ya,ME as Yb,U$ as Yc,tY as Yd,xq as Yf,_B as Yg,EHe as Yh,iSt as Yi,NZ as Yl,yQe as Ym,r8 as Yn,_vt as Yo,GG as Yp,v6 as Yr,iht as Ys,vEt as Yt,lX as Yu,_L as Yv,Fg as Yw,Bke as Yx,cF as Yy,e9 as Z,fv as ZC,hx as ZS,cf as ZT,GR as Z_,Cbt as Za,NAe as Zb,pdt as Zc,WJ as Zd,k6e as Zf,ZBe as Zg,sV as Zh,gSt as Zi,jZ as Zl,UU as Zm,M6 as Zn,avt as Zo,p2e as Zp,w6 as Zr,tht as Zs,fEt as Zt,sX as Zu,gL as Zv,$ve as Zw,oT as Zx,aF as Zy,G9 as _,sb as _C,id as _E,dDe as _S,dh as _T,Cze as __,nxt as _a,uN as _b,bmt as _c,kY as _d,xJ as _f,ZVe as _g,fYe as _h,pCt as _i,Dst as _l,S0e as _m,Y5 as _n,Y2 as _o,h3e as _p,h6 as _r,Q0 as _s,XEt as _t,Hrt as _u,KLe as _v,N_ as _w,VT as _x,pFe as _y,J9 as a,Mb as aC,tf as aE,zw as aS,Tg as aT,Yz as a_,wxt as aa,cN as ab,P1 as ac,JY as ad,b9e as af,yHe as ag,pU as ah,PCt as ai,Ilt as al,G0e as am,n7 as an,i4 as ao,n6e as ap,K6 as ar,l2 as as,I7 as at,fit as au,IR as av,R_ as aw,wE as ax,QFe as ay,z9 as b,ob as bC,Bue as bE,cDe as bS,ch as bT,jz as b_,ixt as ba,GM as bb,xmt as bc,OY as bd,m7e as bf,ZB as bg,OJe as bh,l6 as bi,yQ as bl,E0e as bm,q5 as bn,J2 as bo,f3e as bp,h8 as br,Y0 as bs,UEt as bt,xrt as bu,OR as bv,P_ as bw,uAe as bx,BI as by,Kkt as c,SCe as cC,Yfe as cE,Aw as cS,Eg as cT,zz as c_,u3 as ca,xNe as cb,Rmt as cc,LY as cd,C9e as cf,mHe as cg,kYe as ch,WCt as ci,Pst as cl,P0e as cm,aEt as cn,d4 as co,t6e as cp,s8 as cr,R_t as cs,dDt as ct,Vrt as cu,GLe as cv,ube as cw,kAe as cx,JFe as cy,eAt as d,yCe as dC,Ud as dE,Tw as dS,mg as dT,Wze as d_,fxt as da,TNe as db,I1 as dc,dtt as dd,EJ as df,QB as dg,QH as dh,R6 as di,Vst as dl,A0e as dm,cEt as dn,o4 as do,$3e as dp,e8 as dr,P_t as ds,YEt as dt,Brt as du,XLe as dv,lbe as dw,pAe as dx,fL as dy,nx as eC,nf as eE,eT as eS,Ng as eT,YBe as e_,d3 as ea,oF as eb,U1 as ec,Att as ed,z9e as ef,wHe as eg,hU as eh,dCt as ei,d$ as el,c2e as em,hEt as en,g4 as eo,gq as ep,X6 as er,h2 as es,mOt as et,bit as eu,VR as ev,uv as ew,AAe as ex,BFe as ey,$kt as f,mb as fC,Rd as fE,Dw as fS,ug as fT,Eze as f_,oxt as fa,ZM as fb,j1 as fc,itt as fd,wJ as ff,uHe as fg,$H as fh,GCt as fi,jst as fl,IG as fm,i7 as fn,lyt as fo,e6e as fp,z6 as fr,F_t as fs,JEt as ft,Krt as fu,FR as fv,B_ as fw,hAe as fx,cL as fy,K9 as g,lb as gC,ad as gE,fDe as gS,Rh as gT,wze as g_,gbt as ga,ENe as gb,ymt as gc,Wet as gd,J7e as gf,tHe as gg,dYe as gh,mCt as gi,CQ as gl,D0e as gm,X5 as gn,uyt as go,E3e as gp,a6 as gr,t2 as gs,KEt as gt,Irt as gu,JLe as gv,ebe as gw,fAe as gx,mFe as gy,U9 as h,ub as hC,od as hE,fOe as hS,Lh as hT,Mz as h_,sxt as ha,DNe as hb,D1 as hc,Ket as hd,X7e as hf,eHe as hg,qH as hh,o6 as hi,Fst as hl,OG as hm,_7 as hn,dyt as ho,T3e as hp,i6 as hr,G_t as hs,WEt as ht,Grt as hu,BLe as hv,tbe as hw,UT as hx,CFe as hy,Q9 as i,Rb as iC,Qfe as iE,Xw as iS,jg as iT,Jz as i_,s3 as ia,dN as ib,qmt as ic,btt as id,d9e as if,xHe as ig,fU as ih,HCt as ii,Flt as il,W0e as im,h7 as in,c4 as io,fq as ip,C6 as ir,q_t as is,H7 as it,sit as iu,tRe as iv,Tbe as iw,dE as ix,yL as iy,Rkt as j,Dy as jC,VS as jS,Lhe as jT,eze as j_,Tbt as ja,BM as jb,Wpt as jc,_et as jd,A5e as jf,MB as jg,rH as jh,XSt as ji,rst as jl,I$e as jm,_8 as jn,Svt as jo,b4e as jp,J6 as jr,Qht as js,s7 as jt,qnt as ju,vR as jv,Fye as jw,AT as jx,yPe as jy,M9 as k,LSe as kC,BS as kS,Zm as kT,mz as k_,n3 as ka,sM as kb,Hpt as kc,ket as kd,aJ as kf,kVe as kg,Dqe as kh,K3 as ki,sst as kl,Y$e as km,kwt as kn,Qvt as ko,mK as kp,t8 as kr,egt as ks,v7 as kt,Znt as ku,SR as kv,i_ as kw,LT as kx,SI as ky,qkt as l,Sb as lC,Jd as lE,jw as lS,fg as lT,Uze as l_,Sbt as la,CN as lb,R1 as lc,zY as ld,m9e as lf,pHe as lg,eU as lh,ICt as li,Nst as ll,M0e as lm,sEt as ln,l4 as lo,a6e as lp,r6 as lr,W_t as ls,lDt as lt,Zrt as lu,ZLe as lv,sbe as lw,OAe as lx,wL as ly,B9 as m,xCe as mC,gd as mE,pOe as mS,uve as mT,Pz as m_,k4 as ma,mN as mb,wmt as mc,qet as md,t9e as mf,WB as mg,VH as mh,eCt as mi,Mst as ml,O0e as mm,p7 as mn,fyt as mo,z3e as mp,W6 as mr,a2 as ms,w7 as mt,Jrt as mu,VLe as mv,V_ as mw,HT as mx,rL as my,Y9 as n,Jb as nC,ff as nE,Yw as nS,kg as nT,XBe as n_,i3 as na,rN as nb,B1 as nc,XY as nd,w9e as nf,CHe as ng,aXe as nh,zCt as ni,n$ as nl,a2e as nm,gEt as nn,v4 as no,j6e as np,RCt as nr,ivt as ns,UDt as nt,TZ as nu,RR as nv,$_ as nw,pE as nx,UFe as ny,$9 as o,jb as oC,Xd as oE,Rw as oS,Wve as oT,Gz as o_,Txt as oa,lN as ob,F1 as oc,ptt as od,AJ as of,hHe as og,lU as oh,NCt as oi,Nlt as ol,H0e as om,iEt as on,t4 as oo,r6e as op,owt as or,o2 as os,V7 as ot,iit as ou,LR as ov,z_ as ow,uE as ox,qFe as oy,Wkt as p,db as pC,md as pE,Sw as pS,lg as pT,Tze as p_,A4 as pa,gN as pb,A1 as pc,PY as pd,Z7e as pf,$Ve as pg,cYe as ph,p6 as pi,Rst as pl,j0e as pm,d7 as pn,Q2 as po,R3e as pp,U6 as pr,I_t as ps,BEt as pt,Urt as pu,qLe as pv,cbe as pw,gAe as px,iL as py,g9 as q,gv as qC,vx as qS,Zp as qT,YR as q_,pbt as qa,PE as qb,i1 as qc,nY as qd,Tq as qf,cVe as qg,gV as qh,hSt as qi,aat as ql,ZU as qm,d6 as qn,xvt as qo,ZG as qp,b6 as qr,pht as qs,bEt as qt,Vtt as qu,YFe as qv,iye as qw,cT as qx,hF as qy,Jkt as r,Z as rC,rf as rE,Rke as rS,Mg as rT,pB as r_,a3 as ra,ANe as rb,Wmt as rc,xtt as rd,RJ as rf,SHe as rg,iXe as rh,VCt as ri,$Q as rl,UG as rm,m7 as rn,a4 as ro,uq as rp,I6 as rr,J_t as rs,HDt as rt,wZ as ru,rRe as rv,rv as rw,gE as rx,EL as ry,q9 as s,Cb as sC,Gd as sE,gke as sS,hg as sT,Vz as s_,Ext as sa,$M as sb,Vmt as sc,htt as sd,S9e as sf,eV as sg,uU as sh,P6 as si,Dlt as sl,B0e as sm,qTt as sn,n4 as so,iq as sp,m6 as sr,z_t as ss,oDt as st,Yrt as su,AR as sv,L_ as sw,fE as sx,tIe as sy,Ykt as t,qb as tC,df as tE,Jw as tS,Dg as tT,JBe as t_,f3 as ta,jNe as tb,Qmt as tc,jtt as td,B9e as tf,THe as tg,mXe as th,vCt as ti,KQ as tl,WG as tm,mEt as tn,_4 as to,A6e as tp,c6 as tr,p2 as ts,W7 as tt,EZ as tu,zR as tv,Pbe as tw,hE as tx,bL as ty,Qkt as u,wb as uC,qd as uE,TOe as uS,pg as uT,Kz as u_,wbt as ua,MNe as ub,Bmt as uc,ltt as ud,TJ as uf,$B as ug,nU as uh,FCt as ui,Ist as ul,AG as um,oEt as un,u4 as uo,o6e as up,n8 as ur,n2 as us,cDt as ut,qrt as uu,YLe as uv,ibe as uw,BT as ux,uL as uy,F9 as v,vCe as vC,ru as vE,pDe as vS,uh as vT,Ez as v_,mbt as va,pNe as vb,Cmt as vc,Net as vd,B7e as vf,lHe as vg,pYe as vh,hCt as vi,fst as vl,x0e as vm,TTt as vn,X2 as vo,g3e as vp,wCt as vr,e2 as vs,LEt as vt,Drt as vu,kR as vv,M_ as vw,SAe as vx,nL as vy,L9 as w,Vy as wC,MS as wS,ih as wT,wz as w_,M4 as wa,uM as wb,tmt as wc,Pet as wd,s7e as wf,VVe as wg,lJe as wh,$3 as wi,ist as wl,_0e as wm,H5 as wn,ryt as wo,zK as wp,B6 as wr,j0 as ws,qEt as wt,mrt as wu,SLe as wv,o_ as ww,GT as wx,zI as wy,Okt as x,eb as xC,zue as xE,YS as xS,sh as xT,Az as x_,j4 as xa,KM as xb,pmt as xc,DY as xd,d7e as xf,BVe as xg,NH as xh,oCt as xi,mst as xl,p0e as xm,G5 as xn,K2 as xo,p3e as xp,n6 as xr,__t as xs,E7 as xt,Ert as xu,jLe as xv,c_ as xw,KT as xx,FI as xy,Mkt as y,ib as yC,cu as yE,XS as yS,lh as yT,Dz as y_,$4 as ya,JM as yb,Smt as yc,Bet as yd,f7e as yf,QVe as yg,NJe as yh,fCt as yi,hst as yl,T0e as ym,K5 as yn,q2 as yo,d3e as yp,CCt as yr,y_t as ys,y7 as yt,Ort as yu,WLe as yv,I_ as yw,dAe as yx,fFe as yy,x9 as z,lxe as zC,PS as zS,fm as zT,sz as z_,H4 as za,rD as zb,u1 as zc,fet as zd,P8e as zf,fVe as zg,qV as zh,H3 as zi,aQ as zl,_$e as zm,E6 as zn,Uvt as zo,uK as zp,OCt as zr,Aht as zs,f7 as zt,mnt as zu,mIe as zv,xye as zw,MT as zx,IF as zy};