@readmagic/workmate 0.0.20 → 0.0.22

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 (509) hide show
  1. package/dist/chunks/AddWorkspaceDirectory-DWgTWJ7R.js +1 -0
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-DCvgQ6n3.js +1 -0
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-s0Orgord.js +1 -0
  4. package/dist/chunks/App-BcEI6U5j.js +1 -0
  5. package/dist/chunks/ApproveApiKey-DegdTXZl.js +1 -0
  6. package/dist/chunks/ApproveApiKey-_VXIMSwY.js +1 -0
  7. package/dist/chunks/BackgroundTasksDialog-CjBt1L0p.js +2 -0
  8. package/dist/chunks/BypassPermissionsModeDialog-D2Gesf-u.js +1 -0
  9. package/dist/chunks/CustomSelect-B46Eh0gU.js +1 -0
  10. package/dist/chunks/DiffDialog-v2IiYyi3.js +6 -0
  11. package/dist/chunks/Doctor-BP0Rqraa.js +1 -0
  12. package/dist/chunks/Doctor-By_y3C2V.js +3 -0
  13. package/dist/chunks/ExitFlow-BasHk1mk.js +2 -0
  14. package/dist/chunks/Grove-C3mhgshv.js +11 -0
  15. package/dist/chunks/InvalidConfigDialog-DYVQK5js.js +1 -0
  16. package/dist/chunks/InvalidSettingsDialog-Dg6OiStR.js +1 -0
  17. package/dist/chunks/KeybindingProviderSetup-Bn1jzN5F.js +1 -0
  18. package/dist/chunks/MCPConnectionManager-ChN4Ayjk.js +1 -0
  19. package/dist/chunks/MCPToolListView-DLSrQHDc.js +1 -0
  20. package/dist/chunks/McpParsingWarnings-DZejAh8b.js +1 -0
  21. package/dist/chunks/MessageSelector-CdDlJE48.js +3 -0
  22. package/dist/chunks/Messages-DuL_r1Or.js +10 -0
  23. package/dist/chunks/Onboarding-CE2GNA-h.js +1 -0
  24. package/dist/chunks/PermissionDialog-BaibiQae.js +1 -0
  25. package/dist/chunks/PressEnterToContinue-DZc_s_pE.js +1 -0
  26. package/dist/chunks/PromptInputFooterSuggestions-lkr_A5jQ.js +1 -0
  27. package/dist/chunks/PromptInputHelpMenu-DaQKKyM5.js +1 -0
  28. package/dist/chunks/QueryEngine-DNNy1UCD.js +1 -0
  29. package/dist/chunks/REPL-CEhW-C41.js +1 -0
  30. package/dist/chunks/REPL-CkSL4C_8.js +124 -0
  31. package/dist/chunks/ResumeConversation-BMCO_3X7.js +1 -0
  32. package/dist/chunks/{SearchBox-CwwV0W-w.js → SearchBox-C9xxQzh1.js} +1 -1
  33. package/dist/chunks/SearchExtraToolsTool-DSy_jDhf.js +1 -0
  34. package/dist/chunks/SelectMulti-CNE06VAN.js +1 -0
  35. package/dist/chunks/Settings-mDykHLok.js +2 -0
  36. package/dist/chunks/Spinner-DwsJJUtn.js +1 -0
  37. package/dist/chunks/SpinnerGlyph-A6G-gloN.js +1 -0
  38. package/dist/chunks/TextInput-7uqPhq9T.js +22 -0
  39. package/dist/chunks/ThemePicker-DT9zVy-0.js +1 -0
  40. package/dist/chunks/TrustDialog-G4jM9IfM.js +1 -0
  41. package/dist/chunks/{ValidationErrorsList-BfZ5gcIv.js → ValidationErrorsList-BLtP647v.js} +1 -1
  42. package/dist/chunks/add-dir-7RfQAC3h.js +1 -0
  43. package/dist/chunks/{agentDisplay-BM4QG_RX.js → agentDisplay-vLQHFrmq.js} +1 -1
  44. package/dist/chunks/agents-BNg_skSm.js +101 -0
  45. package/dist/chunks/{agents-BbDBN5l9.js → agents-DLz0kfsr.js} +1 -1
  46. package/dist/chunks/allErrors-DaztSMrw.js +1 -0
  47. package/dist/chunks/appleTerminalBackup-BYKdf3of.js +1 -0
  48. package/dist/chunks/auth-BTB00dq5.js +10 -0
  49. package/dist/chunks/auth-Bbc0Ny8i.js +1 -0
  50. package/dist/chunks/backgroundHousekeeping-DYz83_8C.js +1 -0
  51. package/dist/chunks/backgroundHousekeeping-bEZtlJSf.js +17 -0
  52. package/dist/chunks/banner-mqZEluky.js +2 -0
  53. package/dist/chunks/branch-exFKkymg.js +2 -0
  54. package/dist/chunks/{break-cache-CcwOjTKt.js → break-cache-BL2gnDLX.js} +2 -2
  55. package/dist/chunks/btw-3l78DYET.js +1 -0
  56. package/dist/chunks/caches-6Nx6tsk9.js +1 -0
  57. package/dist/chunks/caches-ouaWB9bY.js +1 -0
  58. package/dist/chunks/claudeDesktop-D3PEgx3U.js +1 -0
  59. package/dist/chunks/{clear-DmqQBNKg.js → clear-CXfhVRp8.js} +1 -1
  60. package/dist/chunks/client-C01Bnxxv.js +1 -0
  61. package/dist/chunks/client-DYRgRQsr.js +1 -0
  62. package/dist/chunks/{client-C_jBL1yC.js → client-DdenNfkQ.js} +1 -1
  63. package/dist/chunks/client-DvhWKIOx.js +1 -0
  64. package/dist/chunks/commands-BoxOw75F.js +1 -0
  65. package/dist/chunks/compact-BOYr105K.js +2 -0
  66. package/dist/chunks/config-BddEvZZl.js +3 -0
  67. package/dist/chunks/config-GEv9hUzz.js +1 -0
  68. package/dist/chunks/config-kw4xg7Nk.js +1 -0
  69. package/dist/chunks/context-3s9wtn4L.js +1 -0
  70. package/dist/chunks/{context-noninteractive-BzDVMnWC.js → context-noninteractive-CJhUu_4y.js} +9 -9
  71. package/dist/chunks/context-noninteractive-DFvoZ2L9.js +1 -0
  72. package/dist/chunks/conversation-CoGharlH.js +1 -0
  73. package/dist/chunks/conversation-MxEVm54C.js +1 -0
  74. package/dist/chunks/conversationRecovery-Da_8uldZ.js +1 -0
  75. package/dist/chunks/convert-legacy-node-http-options-BZnGSjx2.js +1 -0
  76. package/dist/chunks/crossProjectResume-CzPCHq_K.js +40 -0
  77. package/dist/chunks/cwd-BcO6WHKo.js +1 -0
  78. package/dist/chunks/cwd-CDUelriw.js +1 -0
  79. package/dist/chunks/{datadog-Bc6wkPne.js → datadog-v_mXWncN.js} +1 -1
  80. package/dist/chunks/{debug-D58GQBDG.js → debug-8DCufdSp.js} +4 -4
  81. package/dist/chunks/detectRepository-DfX8xXw2.js +1 -0
  82. package/dist/chunks/{diff-DIg66U_d.js → diff-DJSt7QO6.js} +1 -1
  83. package/dist/chunks/directoryCompletion-CT6YVeg7.js +1 -0
  84. package/dist/chunks/doctor-DWvioSU9.js +1 -0
  85. package/dist/chunks/entry-ex0-RyYV.js +13 -0
  86. package/dist/chunks/esm-0CwQE5CJ.js +10 -0
  87. package/dist/chunks/esm-BCmY8V0C.js +1 -0
  88. package/dist/chunks/esm-BQY8jJNR.js +1 -0
  89. package/dist/chunks/esm-BUJtY-Rb.js +1 -0
  90. package/dist/chunks/esm-BadZVa27.js +1 -0
  91. package/dist/chunks/esm-BbMeEYcz.js +1 -0
  92. package/dist/chunks/esm-sVMjGuep.js +1 -0
  93. package/dist/chunks/execFileNoThrow-BsfuytkN.js +34 -0
  94. package/dist/chunks/exit-BxC_ZEtO.js +1 -0
  95. package/dist/chunks/extraUsage-DYm33Occ.js +1 -0
  96. package/dist/chunks/extractMemories-CzN3Ax2B.js +1 -0
  97. package/dist/chunks/fast-DqUpl_Lr.js +1 -0
  98. package/dist/chunks/fast-NUdUyAaM.js +1 -0
  99. package/dist/chunks/fetchModelList-CqsTAWEN.js +1 -0
  100. package/dist/chunks/fetchModelList-DBMHE6Ng.js +1 -0
  101. package/dist/chunks/fileSuggestions-B-SLfb-o.js +3 -0
  102. package/dist/chunks/firstPartyEventLogger-C0q45h_4.js +3 -0
  103. package/dist/chunks/firstPartyEventLogger-CP8hCBDj.js +1 -0
  104. package/dist/chunks/fpsMetrics-wxj9GAsd.js +1 -0
  105. package/dist/chunks/gemini-BC9kHhwe.js +2 -0
  106. package/dist/chunks/generateSessionName-ChvKBVxB.js +1 -0
  107. package/dist/chunks/{genericProcessUtils-6E7fB1dI.js → genericProcessUtils-BYi0OefF.js} +3 -3
  108. package/dist/chunks/goal-ByyimpVU.js +3 -0
  109. package/dist/chunks/grok-DenjixMl.js +1 -0
  110. package/dist/chunks/grove-Dq8QbQ9o.js +7 -0
  111. package/dist/chunks/help-CK90i4hE.js +1 -0
  112. package/dist/chunks/history-CNQNd6hT.js +1 -0
  113. package/dist/chunks/{hooks-7iyENdDG.js → hooks-BRFDg9DV.js} +2 -2
  114. package/dist/chunks/hooks-BaYwmkxD.js +1 -0
  115. package/dist/chunks/install-ZMll-dAa.js +1 -0
  116. package/dist/chunks/instrumentation-BwVyvRfY.js +21 -0
  117. package/dist/chunks/{job-CXz7SLZp.js → job-G_ukhLc4.js} +1 -1
  118. package/dist/chunks/keybindings-wNxBzDVQ.js +1 -0
  119. package/dist/chunks/launchLocalMemory-BcRlXLm6.js +3 -0
  120. package/dist/chunks/launchOnboarding-CDjQ64RO.js +8 -0
  121. package/dist/chunks/{loadAgentsDir-DaNpxaO-.js → loadAgentsDir-C1LkW7gl.js} +571 -641
  122. package/dist/chunks/loadAgentsDir-DKXap_Om.js +1 -0
  123. package/dist/chunks/loadPluginHooks-DtmHtEiS.js +1 -0
  124. package/dist/chunks/{loader-C33o_5kS.js → loader-C61fB6vU.js} +1 -1
  125. package/dist/chunks/localSearch-BB9x5C2N.js +1 -0
  126. package/dist/chunks/{localSearch-C2SZ9bGW.js → localSearch-DFo_WTMm.js} +1 -1
  127. package/dist/chunks/log-DaILwWJa.js +1 -0
  128. package/dist/chunks/logoUtils-Dj_2SWmO.js +1 -0
  129. package/dist/chunks/{magicDocs-CrTwULyJ.js → magicDocs-DYc9TFmI.js} +2 -2
  130. package/dist/chunks/main-BRg8L_aw.js +346 -0
  131. package/dist/chunks/managedEnv-DsqAYOJ4.js +1 -0
  132. package/dist/chunks/managedEnv-lybrMred.js +1 -0
  133. package/dist/chunks/mcp-Bsw3cMiJ.js +6 -0
  134. package/dist/chunks/mcp-DDdud6Y7.js +1 -0
  135. package/dist/chunks/mcp-DbgTDUt7.js +2 -0
  136. package/dist/chunks/memory-CzwTzihf.js +1 -0
  137. package/dist/chunks/modalContext-DDZdU1J8.js +1 -0
  138. package/dist/chunks/mode-Pan-Q2c4.js +2 -0
  139. package/dist/chunks/model-BYfmXKHf.js +1 -0
  140. package/dist/chunks/model-BwBE0Pt5.js +1 -0
  141. package/dist/chunks/modelOptions-DvNBapgG.js +1 -0
  142. package/dist/chunks/nativeInstaller-DnSNJWIi.js +1 -0
  143. package/dist/chunks/notifications-B0DTaYoy.js +1 -0
  144. package/dist/chunks/omit-Dl1Us_PY.js +1 -0
  145. package/dist/chunks/onChangeAppState-4KOJMN82.js +1 -0
  146. package/dist/chunks/openai-C_6C1_0N.js +10 -0
  147. package/dist/chunks/overlayContext-CMV7nYR9.js +1 -0
  148. package/dist/chunks/panel-D9fGQgln.js +1 -0
  149. package/dist/chunks/parser-BKAVMTyD.js +1 -0
  150. package/dist/chunks/{parser-eVu-cTRs.js → parser-D8slvrJP.js} +1 -1
  151. package/dist/chunks/partition-B504IgAa.js +1 -0
  152. package/dist/chunks/pasteStore-DNV1M5Xd.js +1 -0
  153. package/dist/chunks/permissions-CLFMhdRk.js +3 -0
  154. package/dist/chunks/pidLock-D9do1Afy.js +3 -0
  155. package/dist/chunks/plan-CQLnPLuE.js +1 -0
  156. package/dist/chunks/{platform-DMQxcm4K.js → platform-Dzff1WWw.js} +1 -1
  157. package/dist/chunks/plugin-BYdF7uob.js +17 -0
  158. package/dist/chunks/pluginAutoupdate-BJaAqwTH.js +1 -0
  159. package/dist/chunks/pluginBlocklist-DKKmOnWM.js +1 -0
  160. package/dist/chunks/pluginCliCommands-z8TtJMKH.js +1 -0
  161. package/dist/chunks/{pluginFlagging-DRA0m76J.js → pluginFlagging-DQP8tBi2.js} +1 -1
  162. package/dist/chunks/pluginOperations-BcfJCDco.js +2 -0
  163. package/dist/chunks/{pluginStartupCheck-BF1N4Lih.js → pluginStartupCheck-CfRvCrFg.js} +1 -1
  164. package/dist/chunks/pluginStartupCheck-Cq4PvULa.js +1 -0
  165. package/dist/chunks/plugins-CTM8jpOw.js +4 -0
  166. package/dist/chunks/policyLimits-a7ix6GnU.js +1 -0
  167. package/dist/chunks/poorMode-C11JEH3d.js +1 -0
  168. package/dist/chunks/{poorMode-CKQfWf3S.js → poorMode-J5SYJvoY.js} +1 -1
  169. package/dist/chunks/print-u6MzL5Cr.js +13 -0
  170. package/dist/chunks/processBashCommand-DIwrI2QC.js +1 -0
  171. package/dist/chunks/processSlashCommand-B-Gujpxm.js +5 -0
  172. package/dist/chunks/projectOnboardingState-CJycxw5P.js +1 -0
  173. package/dist/chunks/{prompt-8u06WVES.js → prompt-BGqgPgCU.js} +3 -3
  174. package/dist/chunks/prompt-BPJDGlx5.js +1 -0
  175. package/dist/chunks/prompt-DEdZzkEz.js +1 -0
  176. package/dist/chunks/promptEditor-CmQ9p4oe.js +4 -0
  177. package/dist/chunks/{protocolHandler-DzHVaPl3.js → protocolHandler-CJo9-PfZ.js} +2 -2
  178. package/dist/chunks/{proxy-BhIc7-mj.js → proxy-CB17QimU.js} +2 -2
  179. package/dist/chunks/reconciler-DSKLuOS7.js +1 -0
  180. package/dist/chunks/refresh-BbZFCNpn.js +1 -0
  181. package/dist/chunks/registerProtocol-CLIpzVwF.js +1 -0
  182. package/dist/chunks/reload-plugins-DjugL8jH.js +1 -0
  183. package/dist/chunks/rename-DOtCOtEr.js +1 -0
  184. package/dist/chunks/{renderOptions-D-aQZbzS.js → renderOptions-Zqfm2U1y.js} +1 -1
  185. package/dist/chunks/resume-BB4T4WIV.js +2 -0
  186. package/dist/chunks/ripgrep-BuzOTf1S.js +5 -0
  187. package/dist/chunks/ripgrep-CZ2CqaHb.js +1 -0
  188. package/dist/chunks/{runtimeObserver-DzesbvgI.js → runtimeObserver-CK_iZ6OB.js} +1 -1
  189. package/dist/chunks/{runtimeObserver-L6041elO.js → runtimeObserver-CpP0L9T9.js} +4 -4
  190. package/dist/chunks/sandbox-adapter-DhJJ6WOV.js +1 -0
  191. package/dist/chunks/sandbox-toggle-KOHYvbQT.js +1 -0
  192. package/dist/chunks/searchExtraTools-CdJghGkj.js +1 -0
  193. package/dist/chunks/select-C_KXmqbI.js +1 -0
  194. package/dist/chunks/sessionFileAccessHooks-D7KbWFp7.js +1 -0
  195. package/dist/chunks/sessionObserver-DB-sLv-X.js +1 -0
  196. package/dist/chunks/{sessionObserver-0D8xFoRK.js → sessionObserver-WOYv2n7C.js} +2 -2
  197. package/dist/chunks/sessionStorage-sgOAbDn7.js +1 -0
  198. package/dist/chunks/sessionTracing-yBre24PH.js +11 -0
  199. package/dist/chunks/settings-C-KNkvsM.js +1 -0
  200. package/dist/chunks/settings-DKN4xSpQ.js +24 -0
  201. package/dist/chunks/setup-CN_Pk7AR.js +3 -0
  202. package/dist/chunks/{shadowedRuleDetection-Cy9tsuKc.js → shadowedRuleDetection-Df-kZ_pK.js} +1 -1
  203. package/dist/chunks/{sideQuestion-Ds7Elgs4.js → sideQuestion-CMB8hfgX.js} +3 -3
  204. package/dist/chunks/sinks-BS17vtN0.js +1 -0
  205. package/dist/chunks/sinks-D1EjkHb4.js +1 -0
  206. package/dist/chunks/skillChangeDetector-CBKuGuEi.js +1 -0
  207. package/dist/chunks/{skillGapStore-BxCxKPev.js → skillGapStore-CfmlO6pb.js} +2 -2
  208. package/dist/chunks/{skillLifecycle-CfyNC3sW.js → skillLifecycle-BQ2LMfMx.js} +2 -2
  209. package/dist/chunks/{skillSearchPanel-CMNJFIEC.js → skillSearchPanel-BwYuwLFs.js} +4 -4
  210. package/dist/chunks/skills-BVHPQma0.js +1 -0
  211. package/dist/chunks/src-9vmGsuSI.js +1 -0
  212. package/dist/chunks/{src-CgZmCiiH.js → src-BacxF9BD.js} +2 -2
  213. package/dist/chunks/startupProfiler-B_U4QDtf.js +1 -0
  214. package/dist/chunks/startupProfiler-DTs9w9EN.js +3 -0
  215. package/dist/chunks/{state-D5D6QpTX.js → state-BowF111d.js} +1 -1
  216. package/dist/chunks/state-CGuyDES7.js +1 -0
  217. package/dist/chunks/staticRender-BVWx0IM1.js +1 -0
  218. package/dist/chunks/status-BurdTfyz.js +2 -0
  219. package/dist/chunks/status-DMq1An5h.js +1 -0
  220. package/dist/chunks/statusNoticeHelpers-X75JNlx5.js +1 -0
  221. package/dist/chunks/stringUtils-BQm3OfeJ.js +4 -0
  222. package/dist/chunks/{switcher-DQF5ZNal.js → switcher-Bq1Ct_Sn.js} +1 -1
  223. package/dist/chunks/switcher-DGD4ORVf.js +1 -0
  224. package/dist/chunks/{tasks-C8pb6ftc.js → tasks-0c8Uy04D.js} +1 -1
  225. package/dist/chunks/tempfile-CHO5wXsV.js +1 -0
  226. package/dist/chunks/{templateJobs-DJ4dcfcL.js → templateJobs-BdFzE9XG.js} +1 -1
  227. package/dist/chunks/terminalSetup-Cf_r6pwK.js +32 -0
  228. package/dist/chunks/{terminalSetup-7PdC4fV5.js → terminalSetup-D7J6bxcn.js} +1 -1
  229. package/dist/chunks/theme-Bby4fssR.js +1 -0
  230. package/dist/chunks/tipRegistry-CyRXWWTz.js +2 -0
  231. package/dist/chunks/{toolEventObserver-D2nk8ZbW.js → toolEventObserver-CzFZUIsM.js} +1 -1
  232. package/dist/chunks/toolPool-CnrZcprA.js +1 -0
  233. package/dist/chunks/types-zk5Ltv5q.js +81 -0
  234. package/dist/chunks/udsClient-ftP0yIpe.js +1 -0
  235. package/dist/chunks/use-select-navigation-DMaC_3iw.js +1 -0
  236. package/dist/chunks/useDoublePress-C9xxQzh1.js +1 -0
  237. package/dist/chunks/useExitOnCtrlCDWithKeybindings-CjW3gUOt.js +1 -0
  238. package/dist/chunks/useMainLoopModel-DWscpA9I.js +1 -0
  239. package/dist/chunks/useManagePlugins-CYXVcql2.js +1 -0
  240. package/dist/chunks/useMergedTools-DarmnCEw.js +1 -0
  241. package/dist/chunks/useSearchInput-C2JuUW3g.js +1 -0
  242. package/dist/chunks/useSettingsErrors-DutJBiKZ.js +1 -0
  243. package/dist/chunks/util-Bq5l7FF5.js +1 -0
  244. package/dist/chunks/validatePlugin-DIdEydz_.js +1 -0
  245. package/dist/chunks/{vim-BagKUX4j.js → vim-D8prM2IH.js} +1 -1
  246. package/dist/chunks/worktree-Caqt2WRZ.js +1 -0
  247. package/dist/cli.js +1 -1
  248. package/package.json +3 -21
  249. package/dist/chunks/AddWorkspaceDirectory-BYNvxNrD.js +0 -1
  250. package/dist/chunks/AgentsMdExternalIncludesDialog-BSSz86ER.js +0 -1
  251. package/dist/chunks/AgentsMdExternalIncludesDialog-CMEGV4Md.js +0 -1
  252. package/dist/chunks/App-W_9d1DjK.js +0 -1
  253. package/dist/chunks/ApproveApiKey-Bf1Rb8Ql.js +0 -1
  254. package/dist/chunks/ApproveApiKey-wpdvXpFr.js +0 -1
  255. package/dist/chunks/BackgroundTasksDialog-lGn1Wj1k.js +0 -2
  256. package/dist/chunks/BypassPermissionsModeDialog-CjVjyNf8.js +0 -1
  257. package/dist/chunks/DiffDialog-DCpchgp5.js +0 -6
  258. package/dist/chunks/Doctor-6SjW91rd.js +0 -1
  259. package/dist/chunks/Doctor-FPYTivHw.js +0 -3
  260. package/dist/chunks/ExitFlow-Dy8_1D8J.js +0 -2
  261. package/dist/chunks/Grove-Dd6rjs5P.js +0 -11
  262. package/dist/chunks/HybridTransport-CJVkWa2u.js +0 -2
  263. package/dist/chunks/InvalidConfigDialog-Bisj9ic_.js +0 -1
  264. package/dist/chunks/InvalidSettingsDialog-DyTPNRQR.js +0 -1
  265. package/dist/chunks/MCPConnectionManager-DfyoZaiu.js +0 -1
  266. package/dist/chunks/MCPToolListView-Dioupv8F.js +0 -1
  267. package/dist/chunks/McpParsingWarnings-BUlgpZAF.js +0 -1
  268. package/dist/chunks/MessageSelector-D8fylxPg.js +0 -3
  269. package/dist/chunks/Messages-BZDFMYBT.js +0 -10
  270. package/dist/chunks/Onboarding-BKLomZYo.js +0 -1
  271. package/dist/chunks/PermissionDialog-BPhvs5xH.js +0 -1
  272. package/dist/chunks/PressEnterToContinue-Dwoh6CaW.js +0 -1
  273. package/dist/chunks/PromptInputFooterSuggestions-DCum89fF.js +0 -1
  274. package/dist/chunks/PromptInputHelpMenu-DG2lRqis.js +0 -1
  275. package/dist/chunks/QueryEngine-CyGHpX7M.js +0 -1
  276. package/dist/chunks/REPL-BDsz8KIx.js +0 -1
  277. package/dist/chunks/REPL-CCBNfZfs.js +0 -128
  278. package/dist/chunks/RemoteSessionManager-BfsOv4K6.js +0 -2
  279. package/dist/chunks/ResumeConversation-pC8NLq0F.js +0 -1
  280. package/dist/chunks/SSETransport-B3K6eH9I.js +0 -2
  281. package/dist/chunks/SearchExtraToolsTool-DYoxHo9T.js +0 -1
  282. package/dist/chunks/Settings-CKaGmKg2.js +0 -2
  283. package/dist/chunks/TeleportProgress-CkgSp1cs.js +0 -1
  284. package/dist/chunks/TeleportRepoMismatchDialog-DdO_rECq.js +0 -1
  285. package/dist/chunks/TeleportResumeWrapper-BeG4N-2z.js +0 -1
  286. package/dist/chunks/ThemePicker-iD9ufy99.js +0 -1
  287. package/dist/chunks/TrustDialog-qO5OdQt8.js +0 -1
  288. package/dist/chunks/add-dir-C4eSVlZ6.js +0 -1
  289. package/dist/chunks/agents-D3APE_8d.js +0 -101
  290. package/dist/chunks/allErrors-BkgB7JNK.js +0 -1
  291. package/dist/chunks/api-BHBK9axp.js +0 -1
  292. package/dist/chunks/api-DyUWfg3a.js +0 -1
  293. package/dist/chunks/auth-0rn1U4Eq.js +0 -10
  294. package/dist/chunks/auth-BEoTPSgC.js +0 -1
  295. package/dist/chunks/auth-BPug7U_u.js +0 -1
  296. package/dist/chunks/backgroundHousekeeping-D7xAhUaE.js +0 -1
  297. package/dist/chunks/backgroundHousekeeping-km82qEh0.js +0 -17
  298. package/dist/chunks/banner-BkUdig-T.js +0 -2
  299. package/dist/chunks/bg-tGgpwpYx.js +0 -9
  300. package/dist/chunks/branch-CQ38cx5n.js +0 -2
  301. package/dist/chunks/bridgeConfig-C5L-7KaP.js +0 -1
  302. package/dist/chunks/bridgeConfig-CJMjDoaP.js +0 -1
  303. package/dist/chunks/bridgeMessaging-DVC3qj-C.js +0 -1
  304. package/dist/chunks/bridgePointer-DfTOjgtX.js +0 -1
  305. package/dist/chunks/bridgeStatusUtil-Cex6VowM.js +0 -1
  306. package/dist/chunks/btw-_P96ffHR.js +0 -1
  307. package/dist/chunks/bundledMode--fG1S62b.js +0 -1
  308. package/dist/chunks/caches-DH-q8Fjf.js +0 -1
  309. package/dist/chunks/caches-Dq0pJFDP.js +0 -1
  310. package/dist/chunks/capacityWake-BpP6c7x3.js +0 -3
  311. package/dist/chunks/ccrClient-DO563xlf.js +0 -1
  312. package/dist/chunks/claudeDesktop-DPc_SaVn.js +0 -1
  313. package/dist/chunks/cliLaunch-DDtwAolw.js +0 -1
  314. package/dist/chunks/client-9uHzAmFH.js +0 -1
  315. package/dist/chunks/client-BVal_QII.js +0 -1
  316. package/dist/chunks/client-C19cqYQS.js +0 -1
  317. package/dist/chunks/client-Dd7CKMRX.js +0 -1
  318. package/dist/chunks/commands-BkpqHY9F.js +0 -1
  319. package/dist/chunks/compact-DuVIvqMu.js +0 -2
  320. package/dist/chunks/config-DMP6-Ccr.js +0 -1
  321. package/dist/chunks/config-DRy1I12M.js +0 -3
  322. package/dist/chunks/config-e0Goy478.js +0 -1
  323. package/dist/chunks/context-DjgMzIfe.js +0 -1
  324. package/dist/chunks/context-noninteractive-DV7bIJCm.js +0 -1
  325. package/dist/chunks/controlMessageCompat-IFu4Gc1y.js +0 -1
  326. package/dist/chunks/conversation-BBOE_EoE.js +0 -1
  327. package/dist/chunks/conversation-WxH5pb2z.js +0 -1
  328. package/dist/chunks/createSSHSession-LVGVXHXL.js +0 -5
  329. package/dist/chunks/createSession-BUzna9-E.js +0 -1
  330. package/dist/chunks/createSession-Dgwxk1WA.js +0 -1
  331. package/dist/chunks/crossProjectResume-6B2NYy8a.js +0 -40
  332. package/dist/chunks/cwd-DLK3znO7.js +0 -1
  333. package/dist/chunks/cwd-Nh5IZNKO.js +0 -1
  334. package/dist/chunks/debugUtils-DXBRbwCE.js +0 -1
  335. package/dist/chunks/detached-Biz-xhu0.js +0 -4
  336. package/dist/chunks/detectRepository-CDOJ-M7h.js +0 -1
  337. package/dist/chunks/detectRepository-Cv9-k6dg.js +0 -1
  338. package/dist/chunks/directoryCompletion-BDGcGDuv.js +0 -1
  339. package/dist/chunks/doctor-BhUmhHQU.js +0 -1
  340. package/dist/chunks/entry-B-Y-AYeK.js +0 -13
  341. package/dist/chunks/esm-BYnFh4pG.js +0 -1
  342. package/dist/chunks/esm-Bx6rTxIs.js +0 -1
  343. package/dist/chunks/esm-C367Cyo-.js +0 -1
  344. package/dist/chunks/esm-CXM9jqO_.js +0 -1
  345. package/dist/chunks/esm-CXczu_-W.js +0 -1
  346. package/dist/chunks/esm-CXt5K8Xt.js +0 -1
  347. package/dist/chunks/esm-Cb-L4oAk.js +0 -1
  348. package/dist/chunks/esm-CvHtYRrr.js +0 -1
  349. package/dist/chunks/esm-DhRjocaU.js +0 -1
  350. package/dist/chunks/esm-DklLYEuz.js +0 -1
  351. package/dist/chunks/esm-IYgGg4wR.js +0 -1
  352. package/dist/chunks/esm-lyfry1WB.js +0 -10
  353. package/dist/chunks/execFileNoThrow-Bmb5HEFz.js +0 -34
  354. package/dist/chunks/execSyncWrapper-C3ZFV9od.js +0 -1
  355. package/dist/chunks/exit-CW2eqUrR.js +0 -1
  356. package/dist/chunks/extraUsage-CkTon7ib.js +0 -1
  357. package/dist/chunks/extractMemories-CfmbvayQ.js +0 -1
  358. package/dist/chunks/fast-ByahC7Gw.js +0 -1
  359. package/dist/chunks/fast-xtIP4u4y.js +0 -1
  360. package/dist/chunks/fetchModelList-D9aePIPW.js +0 -1
  361. package/dist/chunks/fetchModelList-Dy-x4h3G.js +0 -1
  362. package/dist/chunks/fileSuggestions-CFkJktgc.js +0 -3
  363. package/dist/chunks/firstPartyEventLogger-Bt9iG9xk.js +0 -1
  364. package/dist/chunks/firstPartyEventLogger-DqGSujCz.js +0 -3
  365. package/dist/chunks/flushGate-BjKW7PFC.js +0 -1
  366. package/dist/chunks/fpsMetrics-Dk_pnSHJ.js +0 -1
  367. package/dist/chunks/gemini-NnmxBoEp.js +0 -1
  368. package/dist/chunks/generateSessionName-EpqGW-T2.js +0 -1
  369. package/dist/chunks/git-By_J4XJL.js +0 -5
  370. package/dist/chunks/git-zJCasBa6.js +0 -1
  371. package/dist/chunks/githubRepoPathMapping-CzgPGOHQ.js +0 -1
  372. package/dist/chunks/goal-DbS8yJfB.js +0 -3
  373. package/dist/chunks/grok-BxZ4vTDw.js +0 -1
  374. package/dist/chunks/grove-CYE1Cfcz.js +0 -7
  375. package/dist/chunks/hash-Tu-My5Vp.js +0 -1
  376. package/dist/chunks/help-DatnwM25.js +0 -1
  377. package/dist/chunks/hooks-DjbqtbUV.js +0 -1
  378. package/dist/chunks/initReplBridge-BEZW5PEY.js +0 -1
  379. package/dist/chunks/install-DJukI-kL.js +0 -1
  380. package/dist/chunks/instrumentation-2HH15DPu.js +0 -21
  381. package/dist/chunks/jwtUtils-C_LG1txt.js +0 -1
  382. package/dist/chunks/keybindings-C9l5il16.js +0 -1
  383. package/dist/chunks/launchLocalMemory-BfGenqj1.js +0 -3
  384. package/dist/chunks/launchOnboarding-DjMmXeQE.js +0 -8
  385. package/dist/chunks/lazySchema-DULtBUCI.js +0 -65
  386. package/dist/chunks/lib-BlVGipXx.js +0 -14
  387. package/dist/chunks/loadAgentsDir-DcI-8FQF.js +0 -1
  388. package/dist/chunks/loadPluginHooks-CGgpcyEC.js +0 -1
  389. package/dist/chunks/localSearch-CTTwYTU1.js +0 -1
  390. package/dist/chunks/log-CZ7ploQm.js +0 -1
  391. package/dist/chunks/logoUtils-CbIqOFrX.js +0 -1
  392. package/dist/chunks/main-Blm02_Js.js +0 -31
  393. package/dist/chunks/main-bJXadFi0.js +0 -356
  394. package/dist/chunks/managedEnv-CUsdYhAI.js +0 -1
  395. package/dist/chunks/managedEnv-DXeaUDSK.js +0 -1
  396. package/dist/chunks/mappers-_B-s9fNz.js +0 -1
  397. package/dist/chunks/mcp-BbbYzWpy.js +0 -6
  398. package/dist/chunks/mcp-D91sH9a8.js +0 -1
  399. package/dist/chunks/mcp-Dx-zgUgu.js +0 -2
  400. package/dist/chunks/memoize-CumjjK2Q.js +0 -1
  401. package/dist/chunks/memory-BeL7ui9m.js +0 -1
  402. package/dist/chunks/modalContext-wY9CeN4G.js +0 -1
  403. package/dist/chunks/mode-D695kgLI.js +0 -2
  404. package/dist/chunks/model-DX0TtzqX.js +0 -1
  405. package/dist/chunks/model-Do0f476p.js +0 -1
  406. package/dist/chunks/model-DpcM8dz5.js +0 -1
  407. package/dist/chunks/modelOptions-B3nis9cC.js +0 -1
  408. package/dist/chunks/nativeInstaller-CymO8TNe.js +0 -1
  409. package/dist/chunks/oauth-D38aRTUb.js +0 -1
  410. package/dist/chunks/oauth-U649LV5H.js +0 -1
  411. package/dist/chunks/omit-DO61BHZu.js +0 -1
  412. package/dist/chunks/onChangeAppState-vKml_lit.js +0 -1
  413. package/dist/chunks/openai-DdupGVdC.js +0 -10
  414. package/dist/chunks/panel-CVd1dzYl.js +0 -1
  415. package/dist/chunks/parser-Cq9X7HMP.js +0 -1
  416. package/dist/chunks/partition-BivH9MBJ.js +0 -1
  417. package/dist/chunks/permissions-C9iqR4_N.js +0 -3
  418. package/dist/chunks/pidLock-DiKz5Tza.js +0 -3
  419. package/dist/chunks/plan-KDN5IGWY.js +0 -1
  420. package/dist/chunks/plugin-D0rzUb8E.js +0 -17
  421. package/dist/chunks/pluginAutoupdate-C2xTKLR_.js +0 -1
  422. package/dist/chunks/pluginBlocklist-xdiUmUpt.js +0 -1
  423. package/dist/chunks/pluginCliCommands-CIDDvVN7.js +0 -1
  424. package/dist/chunks/pluginOperations-BEYsarAn.js +0 -2
  425. package/dist/chunks/pluginStartupCheck-DVkI4pqo.js +0 -1
  426. package/dist/chunks/plugins-CWWU4BKs.js +0 -4
  427. package/dist/chunks/pollConfig-2nFzv6Hy.js +0 -1
  428. package/dist/chunks/poorMode-BTIe8W_H.js +0 -1
  429. package/dist/chunks/print-B5H2xbBS.js +0 -14
  430. package/dist/chunks/processBashCommand-EQ9EWaRV.js +0 -1
  431. package/dist/chunks/processSlashCommand-C4PKNyFT.js +0 -5
  432. package/dist/chunks/prompt-B9sDzLPK.js +0 -1
  433. package/dist/chunks/prompt-WsoTRhoh.js +0 -1
  434. package/dist/chunks/promptEditor-Cr4w-4Bz.js +0 -4
  435. package/dist/chunks/rcDebugLog-DSchf3Hs.js +0 -1
  436. package/dist/chunks/reconciler-RIKmaPg7.js +0 -1
  437. package/dist/chunks/refresh-CCSCAjgz.js +0 -1
  438. package/dist/chunks/registerProtocol-C0IlPEoa.js +0 -1
  439. package/dist/chunks/reload-plugins-DC-tbXVv.js +0 -1
  440. package/dist/chunks/remoteBridgeCore-NGTnhQgw.js +0 -1
  441. package/dist/chunks/remoteManagedSettings-BoOYHzYP.js +0 -1
  442. package/dist/chunks/rename-DS1AmW-F.js +0 -1
  443. package/dist/chunks/resume-Cf5PSoPw.js +0 -2
  444. package/dist/chunks/ripgrep-C3jtZL7k.js +0 -5
  445. package/dist/chunks/ripgrep-CBUbn6Po.js +0 -1
  446. package/dist/chunks/sandbox-adapter-Z4Phj31K.js +0 -1
  447. package/dist/chunks/sandbox-toggle-COZE8Lo4.js +0 -1
  448. package/dist/chunks/searchExtraTools-CvkRbL2m.js +0 -1
  449. package/dist/chunks/session-BvA99K4j.js +0 -2
  450. package/dist/chunks/sessionFileAccessHooks-6XfAf6ke.js +0 -1
  451. package/dist/chunks/sessionIdCompat-Dgp6PW_1.js +0 -1
  452. package/dist/chunks/sessionObserver-CRWUBJEY.js +0 -1
  453. package/dist/chunks/sessionState-CQhbGfmh.js +0 -11
  454. package/dist/chunks/sessionStorage-DqEuxDlb.js +0 -1
  455. package/dist/chunks/sessionStoragePortable-x0Yn02-G.js +0 -3
  456. package/dist/chunks/sessionTracing-BoOZsXU2.js +0 -11
  457. package/dist/chunks/settings-3xZ0fsvE.js +0 -19
  458. package/dist/chunks/settings-Crx1cI1u.js +0 -1
  459. package/dist/chunks/settingsSync-rkWmClKS.js +0 -1
  460. package/dist/chunks/setup-D8L275fT.js +0 -3
  461. package/dist/chunks/shellQuote-Ddgr1vif.js +0 -4
  462. package/dist/chunks/sinks-BXX72cbf.js +0 -1
  463. package/dist/chunks/sinks-DMp6uEzM.js +0 -1
  464. package/dist/chunks/skillChangeDetector-CtithJ4a.js +0 -1
  465. package/dist/chunks/skills-DXMk-498.js +0 -1
  466. package/dist/chunks/src-D3yIF9I42.js +0 -1
  467. package/dist/chunks/src-DQOX_xI1.js +0 -1
  468. package/dist/chunks/src-Dt5IJd3C.js +0 -1
  469. package/dist/chunks/src-Dvp6-vB7.js +0 -19
  470. package/dist/chunks/src-PM8NIIu_.js +0 -1
  471. package/dist/chunks/startupProfiler-CbzxVmbv.js +0 -3
  472. package/dist/chunks/startupProfiler-uHetQush.js +0 -1
  473. package/dist/chunks/state-BStOuCh4.js +0 -1
  474. package/dist/chunks/staticRender-D9AbnQFr.js +0 -1
  475. package/dist/chunks/stats-Ce15gc3E.js +0 -1
  476. package/dist/chunks/status-CFrLuGbf.js +0 -2
  477. package/dist/chunks/status-D5OCkMZG.js +0 -1
  478. package/dist/chunks/statusNoticeHelpers-CZoOse-_.js +0 -1
  479. package/dist/chunks/stringUtils-CKD8qDqx.js +0 -4
  480. package/dist/chunks/subprocessEnv-CNBOhlDV.js +0 -1
  481. package/dist/chunks/subprocessEnv-DtBCqQIo.js +0 -1
  482. package/dist/chunks/switcher-AiMcRzoi.js +0 -1
  483. package/dist/chunks/syncCache-qWJ_VfBo.js +0 -1
  484. package/dist/chunks/teleport-Bi_1VFIZ.js +0 -1
  485. package/dist/chunks/terminalSetup-kWdZRKWq.js +0 -32
  486. package/dist/chunks/theme-CEKOCSLw.js +0 -1
  487. package/dist/chunks/tmux-CpGd0Aca.js +0 -1
  488. package/dist/chunks/toolPool-Df5iUqJ-.js +0 -1
  489. package/dist/chunks/trustedDevice-CB6rNzl-.js +0 -1
  490. package/dist/chunks/trustedDevice-DXGePUAC.js +0 -1
  491. package/dist/chunks/types-APu4OCXJ.js +0 -17
  492. package/dist/chunks/udsClient-U7MEfYj7.js +0 -1
  493. package/dist/chunks/upstreamproxy-CTOuotLO.js +0 -10
  494. package/dist/chunks/useExitOnCtrlCDWithKeybindings-Bw0mlTT9.js +0 -1
  495. package/dist/chunks/useMainLoopModel-CIG2cjS2.js +0 -1
  496. package/dist/chunks/useManagePlugins-MSHw-qHx.js +0 -1
  497. package/dist/chunks/useMergedTools-Bb-INJa2.js +0 -1
  498. package/dist/chunks/useSearchInput-QL_VtdJD.js +0 -1
  499. package/dist/chunks/useSettingsErrors-Dvi6zLCr.js +0 -1
  500. package/dist/chunks/userAgent-i-oGzf40.js +0 -1
  501. package/dist/chunks/util-CLQvtXuD.js +0 -1
  502. package/dist/chunks/validatePlugin-1mTZ3TJR.js +0 -1
  503. package/dist/chunks/which-BxQ1hpjp.js +0 -1
  504. package/dist/chunks/windowsPaths-BdhjMYTm.js +0 -1
  505. package/dist/chunks/windowsPaths-DtGZ83kH.js +0 -1
  506. package/dist/chunks/workSecret-CaM2yIJD.js +0 -1
  507. package/dist/chunks/workerRegistry-BjxoZ12l.js +0 -2
  508. package/dist/chunks/worktree-DpksgxdF.js +0 -1
  509. /package/dist/chunks/{src-DL3w8VPk2.js → src-DL3w8VPk.js} +0 -0
@@ -0,0 +1,13 @@
1
+ import{c as e,l as t,o as n,s as r}from"./envUtils-DcaKZlRU.js";import{n as i,t as a}from"./defineProperty-C-QyHrDq.js";import{$C as o,A as s,A_ as c,Aa as l,B as u,Bg as d,Bo as f,Bs as p,Bt as m,Bu as h,C as g,Cc as _,Cn as ee,Cv as te,Cw as ne,Dd as v,Dg as re,Di as y,Dl as ie,Dw as ae,Eg as oe,Fs as se,Gd as ce,Gm as le,Go as b,Hd as ue,Ho as x,Hp as S,IS as de,Ii as fe,Il as pe,Io as me,Iv as he,J_ as ge,Jd as _e,Jp as ve,KC as C,Kd as ye,Km as be,Kv as xe,LC as Se,La as Ce,Lg as we,Ll as Te,Lo as Ee,Mg as De,Ml as Oe,Mp as ke,Ms as Ae,Na as w,Ng as je,Nl as Me,Ns as Ne,Od as Pe,Og as Fe,Ol as Ie,Ow as Le,Pg as Re,Pi as ze,Qr as T,Qy as Be,Ro as Ve,Ru as He,Sg as Ue,Sm as We,Sn as Ge,Ss as Ke,Sw as qe,Ti as Je,Tw as Ye,Ud as Xe,Um as Ze,Uo as Qe,Up as $e,V as et,Vd as E,Vo as tt,Vt as nt,Wd as rt,Wm as it,Wo as at,Wp as D,X_ as ot,Xd as O,YC as st,Yd as ct,Yp as lt,Yv as ut,Z_ as dt,Zd as ft,Zi as pt,Zn as mt,Zr as ht,_c as gt,_i as k,av as _t,aw as vt,b as yt,bc as bt,bg as xt,bm as St,bn as Ct,bv as wt,cs as Tt,cw as Et,cy as Dt,dc as Ot,dm as kt,do as At,ds as jt,dv as Mt,eb as Nt,ef as Pt,ei as Ft,ep as It,ev as Lt,ew as Rt,f as zt,fg as Bt,fm as Vt,fu as Ht,fv as Ut,gc as Wt,gi as Gt,gm as Kt,go as qt,hb as Jt,hm as Yt,hn as Xt,iw as Zt,iy as Qt,j_ as $t,ja as en,jl as tn,jp as nn,js as rn,k_ as an,ki as on,lC as sn,ls as cn,lv as ln,lw as A,ly as un,mc as dn,ny as fn,o as pn,oo as mn,ov as hn,pc as gn,pg as _n,po as vn,pu as yn,py as bn,qd as xn,qn as Sn,rv as Cn,ry as wn,s as Tn,so as En,sv as Dn,ti as On,tp as kn,uT as An,uc as jn,us as Mn,uv as Nn,v as Pn,vc as Fn,vi as In,vm as Ln,vr as Rn,w as zn,wg as Bn,wn as Vn,ws as Hn,xg as Un,xn as Wn,xv as Gn,y as Kn,yc as qn,yi as Jn,yn as Yn,za as Xn,zo as Zn,zr as Qn,zs as $n}from"./loadAgentsDir-C1LkW7gl.js";import{$ as j,A as M,B as er,F as N,G as P,L as tr,N as nr,P as F,Q as I,S as L,V as R,W as z,Y as B,Z as V,f as rr,j as ir,l as ar,o as or,s as H,x as sr}from"./types-zk5Ltv5q.js";import{A as cr,Bt as lr,K as ur,M as dr,Tn as fr,Yn as pr,cn as mr,fn as hr,qt as gr,ut as U,wn as _r,zn as vr,zt as yr}from"./state-BowF111d.js";import{n as br,t as xr}from"./cwd-BcO6WHKo.js";import{C as W,E as Sr,H as Cr,L as wr,N as G,S as Tr,c as K,et as Er,f as Dr,i as Or,tt as kr,u as Ar,x as jr}from"./debug-8DCufdSp.js";import{Jn as Mr,W as Nr,Xn as Pr,_t as Fr,cr as Ir,d as Lr,h as Rr,ni as zr,or as Br,ri as Vr,rt as Hr,ti as Ur,tt as Wr,u as Gr,ut as Kr}from"./settings-DKN4xSpQ.js";import{P as qr,j as Jr}from"./config-BddEvZZl.js";import{i as Yr,n as Xr,o as Zr}from"./process-gEbdy6uY.js";import{H as Qr,c as $r,i as ei,o as ti,q as ni,s as q}from"./log-DaILwWJa.js";import{n as ri,r as J}from"./analytics-DJobLaWP.js";import{Bn as ii,Cr as ai,Er as oi,Ht as si,K as ci,R as li,Sr as ui,St as di,U as fi,Vn as pi,Vt as mi,W as hi,dr as gi,f as _i,g as vi,lr as yi,nn as bi,ot as xi,q as Si,r as Ci,s as wi,tn as Ti,v as Ei,wr as Di}from"./model-BwBE0Pt5.js";import{_t as Oi,at as ki,bn as Ai,it as ji,tn as Mi,vn as Ni,vt as Pi,yt as Fi}from"./prompt-BGqgPgCU.js";import{n as Ii,t as Li}from"./omit-Dl1Us_PY.js";import{a as Ri,n as zi}from"./grove-Dq8QbQ9o.js";import{i as Bi,r as Vi}from"./auth-BTB00dq5.js";import{t as Hi}from"./pluginBlocklist-DKKmOnWM.js";import{n as Ui,t as Wi}from"./toolPool-CnrZcprA.js";import{n as Gi}from"./conversationRecovery-Da_8uldZ.js";import{a as Ki,i as qi,n as Ji,r as Yi}from"./QueryEngine-DNNy1UCD.js";import{n as Xi,r as Zi}from"./sessionTitle-k4wpUS5l.js";import{n as Qi,r as $i}from"./sideQuestion-CMB8hfgX.js";import{n as ea,r as ta}from"./context-noninteractive-CJhUu_4y.js";import{n as na,r as ra}from"./modelOptions-DvNBapgG.js";import{a as ia,o as aa,t as oa}from"./skillChangeDetector-CBKuGuEi.js";import{n as sa}from"./reconciler-DSKLuOS7.js";import{n as ca,t as la}from"./refresh-BbZFCNpn.js";import{dirname as ua,join as da}from"path";import{randomUUID as Y}from"crypto";import{readFile as fa,stat as pa}from"fs/promises";import{cwd as X}from"process";sr(),or();var ma=H(()=>P({inputTokens:z(),outputTokens:z(),cacheReadInputTokens:z(),cacheCreationInputTokens:z(),webSearchRequests:z(),costUSD:z(),contextWindow:z(),maxOutputTokens:z()})),ha=H(()=>R(`json_schema`));H(()=>P({type:ha()}));var ga=H(()=>P({type:R(`json_schema`),schema:B(V(),j())}));H(()=>ga());var _a=H(()=>M([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>M([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>R(`context-1m-2025-08-07`));var va=H(()=>P({type:R(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),ya=H(()=>P({type:R(`enabled`),budgetTokens:z().optional()}).describe(`Fixed thinking token budget (older models)`)),ba=H(()=>P({type:R(`disabled`)}).describe(`No extended thinking`));H(()=>I([va(),ya(),ba()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var xa=H(()=>P({type:R(`stdio`).optional(),command:V(),args:F(V()).optional(),env:B(V(),V()).optional()})),Sa=H(()=>P({type:R(`sse`),url:V(),headers:B(V(),V()).optional()})),Ca=H(()=>P({type:R(`http`),url:V(),headers:B(V(),V()).optional()})),wa=H(()=>P({type:R(`sdk`),name:V()})),Ta=H(()=>I([xa(),Sa(),Ca(),wa()])),Ea=H(()=>P({type:R(`claudeai-proxy`),url:V(),id:V()})),Da=H(()=>I([Ta(),Ea()])),Oa=H(()=>P({name:V().describe(`Server name as configured`),status:M([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:P({name:V(),version:V()}).optional().describe(`Server information (available when connected)`),error:V().optional().describe(`Error message (available when status is 'failed')`),config:Da().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:V().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:F(P({name:V(),description:V().optional(),annotations:P({readOnly:N().optional(),destructive:N().optional(),openWorld:N().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:P({experimental:B(V(),j()).optional()}).optional().describe(`@internal Server capabilities (available when connected). experimental['claude/channel'] is only present if the server's plugin is on the approved channels allowlist — use its presence to decide whether to show an Enable-channel prompt.`)}).describe(`Status information for an MCP server connection.`));H(()=>P({added:F(V()).describe(`Names of servers that were added`),removed:F(V()).describe(`Names of servers that were removed`),errors:B(V(),V()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var ka=H(()=>M([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),Aa=H(()=>M([`allow`,`deny`,`ask`])),ja=H(()=>P({toolName:V(),ruleContent:V().optional()})),Ma=H(()=>tr(`type`,[P({type:R(`addRules`),rules:F(ja()),behavior:Aa(),destination:ka()}),P({type:R(`replaceRules`),rules:F(ja()),behavior:Aa(),destination:ka()}),P({type:R(`removeRules`),rules:F(ja()),behavior:Aa(),destination:ka()}),P({type:R(`setMode`),mode:er(()=>Pa()),destination:ka()}),P({type:R(`addDirectories`),directories:F(V()),destination:ka()}),P({type:R(`removeDirectories`),directories:F(V()),destination:ka()})])),Na=H(()=>M([`user_temporary`,`user_permanent`,`user_reject`]).describe(`Classification of this permission decision for telemetry. SDK hosts that prompt users (desktop apps, IDEs) should set this to reflect what actually happened: user_temporary for allow-once, user_permanent for always-allow (both the click and later cache hits), user_reject for deny. If unset, the CLI infers conservatively (temporary for allow, reject for deny). The vocabulary matches tool_decision OTel events (monitoring-usage docs).`));H(()=>I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Ma()).optional(),toolUseID:V().optional(),decisionClassification:Na().optional()}),P({behavior:R(`deny`),message:V(),interrupt:N().optional(),toolUseID:V().optional(),decisionClassification:Na().optional()})]));var Pa=H(()=>M([`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`,`auto`]).describe(`Permission mode for controlling how tool executions are handled. 'default' - Standard behavior, prompts for dangerous operations. 'acceptEdits' - Auto-accept file edit operations. 'bypassPermissions' - Bypass all permission checks (requires allowDangerouslySkipPermissions). 'plan' - Planning mode, no actual tool execution. 'dontAsk' - Don't prompt for permissions, deny if not pre-approved. 'auto' - Automatic mode (transcript classifier).`)),Fa=`PreToolUse.PostToolUse.PostToolUseFailure.Notification.UserPromptSubmit.SessionStart.SessionEnd.Stop.StopFailure.SubagentStart.SubagentStop.PreCompact.PostCompact.PermissionRequest.PermissionDenied.Setup.TeammateIdle.TaskCreated.TaskCompleted.Elicitation.ElicitationResult.ConfigChange.WorktreeCreate.WorktreeRemove.InstructionsLoaded.CwdChanged.FileChanged`.split(`.`),Ia=H(()=>M(Fa)),Z=H(()=>P({session_id:V(),transcript_path:V(),cwd:V(),permission_mode:V().optional(),agent_id:V().optional().describe(`Subagent identifier. Present only when the hook fires from within a subagent (e.g., a tool called by an AgentTool worker). Absent for the main thread, even in --agent sessions. Use this field (not agent_type) to distinguish subagent calls from main-thread calls.`),agent_type:V().optional().describe(`Agent type name (e.g., "general-purpose", "code-reviewer"). Present when the hook fires from within a subagent (alongside agent_id), or on the main thread of a session started with --agent (without agent_id).`)})),La=H(()=>Z().and(P({hook_event_name:R(`PreToolUse`),tool_name:V(),tool_input:j(),tool_use_id:V()}))),Ra=H(()=>Z().and(P({hook_event_name:R(`PermissionRequest`),tool_name:V(),tool_input:j(),permission_suggestions:F(Ma()).optional()}))),za=H(()=>Z().and(P({hook_event_name:R(`PostToolUse`),tool_name:V(),tool_input:j(),tool_response:j(),tool_use_id:V()}))),Ba=H(()=>Z().and(P({hook_event_name:R(`PostToolUseFailure`),tool_name:V(),tool_input:j(),tool_use_id:V(),error:V(),is_interrupt:N().optional()}))),Va=H(()=>Z().and(P({hook_event_name:R(`PermissionDenied`),tool_name:V(),tool_input:j(),tool_use_id:V(),reason:V()}))),Ha=H(()=>Z().and(P({hook_event_name:R(`Notification`),message:V(),title:V().optional(),notification_type:V()}))),Ua=H(()=>Z().and(P({hook_event_name:R(`UserPromptSubmit`),prompt:V()}))),Wa=H(()=>Z().and(P({hook_event_name:R(`SessionStart`),source:M([`startup`,`resume`,`clear`,`compact`]),agent_type:V().optional(),model:V().optional()}))),Ga=H(()=>Z().and(P({hook_event_name:R(`Setup`),trigger:M([`init`,`maintenance`])}))),Ka=H(()=>Z().and(P({hook_event_name:R(`Stop`),stop_hook_active:N(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),qa=H(()=>Z().and(P({hook_event_name:R(`StopFailure`),error:Go(),error_details:V().optional(),last_assistant_message:V().optional()}))),Ja=H(()=>Z().and(P({hook_event_name:R(`SubagentStart`),agent_id:V(),agent_type:V()}))),Ya=H(()=>Z().and(P({hook_event_name:R(`SubagentStop`),stop_hook_active:N(),agent_id:V(),agent_transcript_path:V(),agent_type:V(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Xa=H(()=>Z().and(P({hook_event_name:R(`PreCompact`),trigger:M([`manual`,`auto`]),custom_instructions:V().nullable()}))),Za=H(()=>Z().and(P({hook_event_name:R(`PostCompact`),trigger:M([`manual`,`auto`]),compact_summary:V().describe(`The conversation summary produced by compaction`)}))),Qa=H(()=>Z().and(P({hook_event_name:R(`TeammateIdle`),teammate_name:V(),team_name:V()}))),$a=H(()=>Z().and(P({hook_event_name:R(`TaskCreated`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),eo=H(()=>Z().and(P({hook_event_name:R(`TaskCompleted`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),to=H(()=>Z().and(P({hook_event_name:R(`Elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).optional()})).describe(`Hook input for the Elicitation event. Fired when an MCP server requests user input. Hooks can auto-respond (accept/decline) instead of showing the dialog.`)),no=H(()=>Z().and(P({hook_event_name:R(`ElicitationResult`),mcp_server_name:V(),elicitation_id:V().optional(),mode:M([`form`,`url`]).optional(),action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).optional()})).describe(`Hook input for the ElicitationResult event. Fired after the user responds to an MCP elicitation. Hooks can observe or override the response before it is sent to the server.`)),ro=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],io=H(()=>Z().and(P({hook_event_name:R(`ConfigChange`),source:M(ro),file_path:V().optional()}))),ao=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],oo=[`User`,`Project`,`Local`,`Managed`],so=H(()=>Z().and(P({hook_event_name:R(`InstructionsLoaded`),file_path:V(),memory_type:M(oo),load_reason:M(ao),globs:F(V()).optional(),trigger_file_path:V().optional(),parent_file_path:V().optional()}))),co=H(()=>Z().and(P({hook_event_name:R(`WorktreeCreate`),name:V()}))),lo=H(()=>Z().and(P({hook_event_name:R(`WorktreeRemove`),worktree_path:V()}))),uo=H(()=>Z().and(P({hook_event_name:R(`CwdChanged`),old_cwd:V(),new_cwd:V()}))),fo=H(()=>Z().and(P({hook_event_name:R(`FileChanged`),file_path:V(),event:M([`change`,`add`,`unlink`])}))),po=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],mo=H(()=>M(po)),ho=H(()=>Z().and(P({hook_event_name:R(`SessionEnd`),reason:mo()}))),go=H(()=>I([La(),za(),Ba(),Va(),Ha(),Ua(),Wa(),ho(),Ka(),qa(),Ja(),Ya(),Xa(),Za(),Ra(),Ga(),Qa(),$a(),eo(),to(),no(),io(),so(),co(),lo(),uo(),fo()])),_o=H(()=>P({async:R(!0),asyncTimeout:z().optional()})),vo=H(()=>P({hookEventName:R(`PreToolUse`),permissionDecision:Aa().optional(),permissionDecisionReason:V().optional(),updatedInput:B(V(),j()).optional(),additionalContext:V().optional()})),yo=H(()=>P({hookEventName:R(`UserPromptSubmit`),additionalContext:V().optional()})),bo=H(()=>P({hookEventName:R(`SessionStart`),additionalContext:V().optional(),initialUserMessage:V().optional(),watchPaths:F(V()).optional()})),xo=H(()=>P({hookEventName:R(`Setup`),additionalContext:V().optional()})),So=H(()=>P({hookEventName:R(`SubagentStart`),additionalContext:V().optional()})),Co=H(()=>P({hookEventName:R(`PostToolUse`),additionalContext:V().optional(),updatedMCPToolOutput:j().optional()})),wo=H(()=>P({hookEventName:R(`PostToolUseFailure`),additionalContext:V().optional()})),To=H(()=>P({hookEventName:R(`PermissionDenied`),retry:N().optional()})),Eo=H(()=>P({hookEventName:R(`Notification`),additionalContext:V().optional()})),Do=H(()=>P({hookEventName:R(`PermissionRequest`),decision:I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Ma()).optional()}),P({behavior:R(`deny`),message:V().optional(),interrupt:N().optional()})])})),Oo=H(()=>P({hookEventName:R(`CwdChanged`),watchPaths:F(V()).optional()})),ko=H(()=>P({hookEventName:R(`FileChanged`),watchPaths:F(V()).optional()})),Ao=H(()=>P({continue:N().optional(),suppressOutput:N().optional(),stopReason:V().optional(),decision:M([`approve`,`block`]).optional(),systemMessage:V().optional(),reason:V().optional(),hookSpecificOutput:I([vo(),yo(),bo(),xo(),So(),Co(),wo(),To(),Eo(),Do(),jo(),Mo(),Oo(),ko(),No()]).optional()})),jo=H(()=>P({hookEventName:R(`Elicitation`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),Mo=H(()=>P({hookEventName:R(`ElicitationResult`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).optional()}).describe(`Hook-specific output for the ElicitationResult event. Return this to override the action or content before the response is sent to the MCP server.`)),No=H(()=>P({hookEventName:R(`WorktreeCreate`),worktreePath:V()}).describe(`Hook-specific output for the WorktreeCreate event. Provides the absolute path to the created worktree directory. Command hooks print the path on stdout instead.`));H(()=>I([_o(),Ao()]));var Po=H(()=>P({key:V().describe(`Unique key for this option, returned in the response`),label:V().describe(`Display text for this option`),description:V().optional().describe(`Optional description shown below the label`)}));H(()=>P({prompt:V().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:V().describe(`The prompt message to display to the user`),options:F(Po()).describe(`Available options for the user to choose from`)})),H(()=>P({prompt_response:V().describe(`The request ID from the corresponding prompt request`),selected:V().describe(`The key of the selected option`)}));var Fo=H(()=>P({name:V().describe(`Skill name (without the leading slash)`),description:V().describe(`Description of what the skill does`),argumentHint:V().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),Io=H(()=>P({name:V().describe(`Agent type identifier (e.g., "Explore")`),description:V().describe(`Description of when to use this agent`),model:V().optional().describe(`Model alias this agent uses. If omitted, inherits the parent's model`)}).describe(`Information about an available subagent that can be invoked via the Task tool.`)),Lo=H(()=>P({value:V().describe(`Model identifier to use in API calls`),displayName:V().describe(`Human-readable display name`),description:V().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:N().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:N().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:N().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Ro=H(()=>P({email:V().optional(),organization:V().optional(),subscriptionType:V().optional(),tokenSource:V().optional(),apiKeySource:V().optional(),apiProvider:M([`firstParty`,`bedrock`,`vertex`,`foundry`]).optional().describe(`Active API backend. Anthropic OAuth login only applies when "firstParty"; for 3P providers the other fields are absent and auth is external (AWS creds, gcloud ADC, etc.).`)}).describe(`Information about the logged in user's account.`)),zo=H(()=>I([V(),B(V(),Ta())])),Bo=H(()=>P({description:V().describe(`Natural language description of when to use this agent`),tools:F(V()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:F(V()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:V().describe(`The agent's system prompt`),model:V().optional().describe(`Model alias (e.g. 'sonnet', 'opus', 'haiku') or full model ID (e.g. 'claude-opus-4-5'). If omitted or 'inherit', uses the main model`),mcpServers:F(zo()).optional(),criticalSystemReminder_EXPERIMENTAL:V().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:F(V()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:V().optional().describe(`Auto-submitted as the first user turn when this agent is the main thread agent. Slash commands are processed. Prepended to any user-provided prompt.`),maxTurns:z().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:N().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:M([`user`,`project`,`local`]).optional().describe(`Scope for auto-loading agent memory files. 'user' - ~/.workmate/agent-memory/<agentType>/, 'project' - .workmate/agent-memory/<agentType>/, 'local' - .workmate/agent-memory-local/<agentType>/`),permissionMode:Pa().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));H(()=>M([`user`,`project`,`local`]).describe(`Source for loading filesystem-based settings. 'user' - Global user settings (~/.workmate/settings.json). 'project' - Project settings (.workmate/settings.json). 'local' - Local settings (.workmate/settings.local.json).`)),H(()=>P({type:R(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:V().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var Vo=H(()=>j()),Ho=H(()=>j()),Uo=H(()=>j()),Q=H(()=>V()),Wo=H(()=>j()),Go=H(()=>M([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ko=H(()=>I([R(`compacting`),ir()])),qo=H(()=>P({type:R(`user`),message:Vo(),parent_tool_use_id:V().nullable(),isSynthetic:N().optional(),tool_use_result:j().optional(),priority:M([`now`,`next`,`later`]).optional(),timestamp:V().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Jo=H(()=>qo().extend({uuid:Q().optional(),session_id:V().optional()})),Yo=H(()=>qo().extend({uuid:Q(),session_id:V(),isReplay:R(!0)})),Xo=H(()=>P({status:M([`allowed`,`allowed_warning`,`rejected`]),resetsAt:z().optional(),rateLimitType:M([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:z().optional(),overageStatus:M([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:z().optional(),overageDisabledReason:M([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`org_service_zero_credit_limit`,`no_limits_configured`,`unknown`]).optional(),isUsingOverage:N().optional(),surpassedThreshold:z().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),Zo=H(()=>P({type:R(`assistant`),message:Ho(),parent_tool_use_id:V().nullable(),error:Go().optional(),uuid:Q(),session_id:V()})),Qo=H(()=>P({type:R(`rate_limit_event`),rate_limit_info:Xo(),uuid:Q(),session_id:V()}).describe(`Rate limit event emitted when rate limit info changes.`)),$o=H(()=>P({type:R(`streamlined_text`),text:V().describe(`Text content preserved from the assistant message`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),es=H(()=>P({type:R(`streamlined_tool_use_summary`),tool_summary:V().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),ts=H(()=>P({tool_name:V(),tool_use_id:V(),tool_input:B(V(),j())})),ns=H(()=>P({type:R(`result`),subtype:R(`success`),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),result:V(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Wo(),modelUsage:B(V(),ma()),permission_denials:F(ts()),structured_output:j().optional(),fast_mode_state:Es().optional(),uuid:Q(),session_id:V()})),rs=H(()=>P({type:R(`result`),subtype:M([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Wo(),modelUsage:B(V(),ma()),permission_denials:F(ts()),errors:F(V()),fast_mode_state:Es().optional(),uuid:Q(),session_id:V()})),is=H(()=>I([ns(),rs()])),as=H(()=>P({type:R(`system`),subtype:R(`init`),agents:F(V()).optional(),apiKeySource:_a(),betas:F(V()).optional(),claude_code_version:V(),cwd:V(),tools:F(V()),mcp_servers:F(P({name:V(),status:V()})),model:V(),permissionMode:Pa(),slash_commands:F(V()),output_style:V(),skills:F(V()),plugins:F(P({name:V(),path:V(),source:V().optional().describe(`@internal Plugin source identifier in "name\\@marketplace" format. Sentinels: "name\\@inline" for --plugin-dir, "name\\@builtin" for built-in plugins.`)})),fast_mode_state:Es().optional(),uuid:Q(),session_id:V()})),os=H(()=>P({type:R(`stream_event`),event:Uo(),parent_tool_use_id:V().nullable(),uuid:Q(),session_id:V()})),ss=H(()=>P({type:R(`system`),subtype:R(`compact_boundary`),compact_metadata:P({trigger:M([`manual`,`auto`]),pre_tokens:z(),preserved_segment:P({head_uuid:Q(),anchor_uuid:Q(),tail_uuid:Q()}).optional().describe(`Relink info for messagesToKeep. Loaders splice the preserved segment at anchor_uuid (summary for suffix-preserving, boundary for prefix-preserving partial compact) so resume includes preserved content. Unset when compaction summarizes everything (no messagesToKeep).`)}),uuid:Q(),session_id:V()})),cs=H(()=>P({type:R(`system`),subtype:R(`status`),status:Ko(),permissionMode:Pa().optional(),uuid:Q(),session_id:V()})),ls=H(()=>P({type:R(`system`),subtype:R(`post_turn_summary`),summarizes_uuid:V(),status_category:M([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:V(),is_noteworthy:N(),title:V(),description:V(),recent_action:V(),needs_action:V(),artifact_urls:F(V()),uuid:Q(),session_id:V()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),us=H(()=>P({type:R(`system`),subtype:R(`api_retry`),attempt:z(),max_retries:z(),retry_delay_ms:z(),error_status:z().nullable(),error:Go(),uuid:Q(),session_id:V()}).describe(`Emitted when an API request fails with a retryable error and will be retried after a delay. error_status is null for connection errors (e.g. timeouts) that had no HTTP response.`)),ds=H(()=>P({type:R(`system`),subtype:R(`local_command_output`),content:V(),uuid:Q(),session_id:V()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),fs=H(()=>P({type:R(`system`),subtype:R(`hook_started`),hook_id:V(),hook_name:V(),hook_event:V(),uuid:Q(),session_id:V()})),ps=H(()=>P({type:R(`system`),subtype:R(`hook_progress`),hook_id:V(),hook_name:V(),hook_event:V(),stdout:V(),stderr:V(),output:V(),uuid:Q(),session_id:V()})),ms=H(()=>P({type:R(`system`),subtype:R(`hook_response`),hook_id:V(),hook_name:V(),hook_event:V(),output:V(),stdout:V(),stderr:V(),exit_code:z().optional(),outcome:M([`success`,`error`,`cancelled`]),uuid:Q(),session_id:V()})),hs=H(()=>P({type:R(`tool_progress`),tool_use_id:V(),tool_name:V(),parent_tool_use_id:V().nullable(),elapsed_time_seconds:z(),task_id:V().optional(),uuid:Q(),session_id:V()})),gs=H(()=>P({type:R(`auth_status`),isAuthenticating:N(),output:F(V()),error:V().optional(),uuid:Q(),session_id:V()})),_s=H(()=>P({type:R(`system`),subtype:R(`files_persisted`),files:F(P({filename:V(),file_id:V()})),failed:F(P({filename:V(),error:V()})),processed_at:V(),uuid:Q(),session_id:V()})),vs=H(()=>P({type:R(`system`),subtype:R(`task_notification`),task_id:V(),tool_use_id:V().optional(),status:M([`completed`,`failed`,`stopped`]),output_file:V(),summary:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}).optional(),uuid:Q(),session_id:V()})),ys=H(()=>P({type:R(`system`),subtype:R(`task_started`),task_id:V(),tool_use_id:V().optional(),description:V(),task_type:V().optional(),workflow_name:V().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:V().optional(),uuid:Q(),session_id:V()})),bs=H(()=>P({type:R(`system`),subtype:R(`session_state_changed`),state:M([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:V()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),xs=H(()=>P({type:R(`system`),subtype:R(`task_progress`),task_id:V(),tool_use_id:V().optional(),description:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}),last_tool_name:V().optional(),summary:V().optional(),uuid:Q(),session_id:V()})),Ss=H(()=>P({type:R(`tool_use_summary`),summary:V(),preceding_tool_use_ids:F(V()),uuid:Q(),session_id:V()})),Cs=H(()=>P({type:R(`system`),subtype:R(`elicitation_complete`),mcp_server_name:V(),elicitation_id:V(),uuid:Q(),session_id:V()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),ws=H(()=>P({type:R(`prompt_suggestion`),suggestion:V(),uuid:Q(),session_id:V()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>P({sessionId:V().describe(`Unique session identifier (UUID).`),summary:V().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:z().describe(`Last modified time in milliseconds since epoch.`),fileSize:z().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:V().optional().describe(`User-set session title via /rename.`),firstPrompt:V().optional().describe(`First meaningful user prompt in the session.`),gitBranch:V().optional().describe(`Git branch at the end of the session.`),cwd:V().optional().describe(`Working directory for the session.`),tag:V().optional().describe(`User-set session tag.`),createdAt:z().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var Ts=H(()=>I([Zo(),Jo(),Yo(),is(),as(),os(),ss(),cs(),us(),ds(),fs(),ps(),ms(),hs(),gs(),vs(),ys(),xs(),bs(),_s(),Ss(),Qo(),Cs(),ws()])),Es=H(()=>M([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));sr(),or();var Ds=H(()=>j()),Os=H(()=>P({matcher:V().optional(),hookCallbackIds:F(V()),timeout:z().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),ks=H(()=>P({subtype:R(`initialize`),hooks:B(Ia(),F(Os())).optional(),sdkMcpServers:F(V()).optional(),jsonSchema:B(V(),j()).optional(),systemPrompt:V().optional(),appendSystemPrompt:V().optional(),agents:B(V(),Bo()).optional(),promptSuggestions:N().optional(),agentProgressSummaries:N().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>P({commands:F(Fo()),agents:F(Io()),output_style:V(),available_output_styles:F(V()),models:F(Lo()),account:Ro(),pid:z().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:Es().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var As=H(()=>P({subtype:R(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),js=H(()=>P({subtype:R(`can_use_tool`),tool_name:V(),input:B(V(),j()),permission_suggestions:F(Ma()).optional(),blocked_path:V().optional(),decision_reason:V().optional(),title:V().optional(),display_name:V().optional(),tool_use_id:V(),agent_id:V().optional(),description:V().optional()}).describe(`Requests permission to use a tool with the given input.`)),Ms=H(()=>P({subtype:R(`set_permission_mode`),mode:Pa()}).describe(`Sets the permission mode for tool execution handling.`)),Ns=H(()=>P({subtype:R(`set_model`),model:V().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),Ps=H(()=>P({subtype:R(`set_max_thinking_tokens`),max_thinking_tokens:z().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Fs=H(()=>P({subtype:R(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>P({mcpServers:F(Oa())}).describe(`Response containing the current status of all MCP server connections.`));var Is=H(()=>P({subtype:R(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Ls=H(()=>P({name:V(),tokens:z(),color:V(),isDeferred:N().optional()})),Rs=H(()=>P({color:V(),isFilled:N(),categoryName:V(),tokens:z(),percentage:z(),squareFullness:z()}));H(()=>P({categories:F(Ls()),totalTokens:z(),maxTokens:z(),rawMaxTokens:z(),percentage:z(),gridRows:F(F(Rs())),model:V(),memoryFiles:F(P({path:V(),type:V(),tokens:z()})),mcpTools:F(P({name:V(),serverName:V(),tokens:z(),isLoaded:N().optional()})),deferredBuiltinTools:F(P({name:V(),tokens:z(),isLoaded:N()})).optional(),systemTools:F(P({name:V(),tokens:z()})).optional(),systemPromptSections:F(P({name:V(),tokens:z()})).optional(),agents:F(P({agentType:V(),source:V(),tokens:z()})),slashCommands:P({totalCommands:z(),includedCommands:z(),tokens:z()}).optional(),skills:P({totalSkills:z(),includedSkills:z(),tokens:z(),skillFrontmatter:F(P({name:V(),source:V(),tokens:z()}))}).optional(),autoCompactThreshold:z().optional(),isAutoCompactEnabled:N(),messageBreakdown:P({toolCallTokens:z(),toolResultTokens:z(),attachmentTokens:z(),assistantMessageTokens:z(),userMessageTokens:z(),toolCallsByType:F(P({name:V(),callTokens:z(),resultTokens:z()})),attachmentsByType:F(P({name:V(),tokens:z()}))}).optional(),apiUsage:P({input_tokens:z(),output_tokens:z(),cache_creation_input_tokens:z(),cache_read_input_tokens:z()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var zs=H(()=>P({subtype:R(`rewind_files`),user_message_id:V(),dry_run:N().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var Bs=H(()=>P({subtype:R(`cancel_async_message`),message_uuid:V()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>P({cancelled:N()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var Vs=H(()=>P({subtype:R(`seed_read_state`),path:V(),mtime:z()}).describe(`Seeds the readFileState cache with a path+mtime entry. Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read. The mtime lets the CLI detect if the file changed since the seeded Read — same staleness check as the normal path.`)),Hs=H(()=>P({subtype:R(`hook_callback`),callback_id:V(),input:go(),tool_use_id:V().optional()}).describe(`Delivers a hook callback with its input data.`)),Us=H(()=>P({subtype:R(`mcp_message`),server_name:V(),message:Ds()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Ws=H(()=>P({subtype:R(`mcp_set_servers`),servers:B(V(),Ta())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>P({added:F(V()),removed:F(V()),errors:B(V(),V())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Gs=H(()=>P({subtype:R(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>P({commands:F(Fo()),agents:F(Io()),plugins:F(P({name:V(),path:V(),source:V().optional()})),mcpServers:F(Oa()),error_count:z()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Ks=H(()=>P({subtype:R(`mcp_reconnect`),serverName:V()}).describe(`Reconnects a disconnected or failed MCP server.`)),qs=H(()=>P({subtype:R(`mcp_toggle`),serverName:V(),enabled:N()}).describe(`Enables or disables an MCP server.`)),Js=H(()=>P({subtype:R(`stop_task`),task_id:V()}).describe(`Stops a running task.`)),Ys=H(()=>P({subtype:R(`apply_flag_settings`),settings:B(V(),j())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Xs=H(()=>P({subtype:R(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>P({effective:B(V(),j()),sources:F(P({source:M([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:B(V(),j())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:P({model:V()}).optional().describe("Runtime-resolved values after env overrides, session state, and model-specific defaults are applied. Unlike `effective` (disk merge), these reflect what will actually be sent to the API.")}).describe(`Effective merged settings plus raw per-source settings in merge order.`));var Zs=H(()=>P({subtype:R(`elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Qs=H(()=>P({action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),$s=H(()=>I([As(),js(),ks(),Ms(),Ns(),Ps(),Fs(),Is(),Hs(),Us(),zs(),Bs(),Vs(),Ws(),Gs(),Ks(),qs(),Js(),Ys(),Xs(),Zs()])),ec=H(()=>P({type:R(`control_request`),request_id:V(),request:$s()})),tc=H(()=>P({subtype:R(`success`),request_id:V(),response:B(V(),j()).optional()})),nc=H(()=>P({subtype:R(`error`),request_id:V(),error:V(),pending_permission_requests:F(er(()=>ec())).optional()})),rc=H(()=>P({type:R(`control_response`),response:I([tc(),nc()])})),ic=H(()=>P({type:R(`control_cancel_request`),request_id:V()}).describe(`Cancels a currently open control request.`)),ac=H(()=>P({type:R(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),oc=H(()=>P({type:R(`update_environment_variables`),variables:B(V(),V())}).describe(`Updates environment variables at runtime.`));H(()=>I([Ts(),$o(),es(),ls(),rc(),ec(),ic(),ac()])),H(()=>I([Jo(),ec(),rc(),ac(),oc()])),n(),i(),yr(),Er(),wr(),jr(),Dr(),Xr(),Ur(),Ge(),sr(),Or(),or(),St(),ee(),H(()=>L.object({tool_name:L.string().describe(`The name of the tool requesting permission`),input:L.record(L.string(),L.unknown()).describe(`The input for the tool`),tool_use_id:L.string().optional().describe(`The unique tool use request ID`)}));var sc=H(()=>L.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),cc=H(()=>L.object({behavior:L.literal(`allow`),updatedInput:L.record(L.string(),L.unknown()),updatedPermissions:L.array(Vn()).optional().catch(e=>{K(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:L.string().optional(),decisionClassification:sc()})),lc=H(()=>L.object({behavior:L.literal(`deny`),message:L.string(),interrupt:L.boolean().optional(),toolUseID:L.string().optional(),decisionClassification:sc()})),uc=H(()=>L.union([cc(),lc()]));function dc(e,t,n,r){let i={type:`permissionPromptTool`,permissionPromptToolName:t.name,toolResult:e};if(e.behavior===`allow`){let t=e.updatedPermissions;t&&(r.setAppState(e=>({...e,toolPermissionContext:Ln(e.toolPermissionContext,t)})),We(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(K(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}br(),ni(),ti(),Ir(),ar(),Fr(),Hr(),Rr(),oi(),Ni(),gi(),pi(),Ti(),di(),_i(),Mi(),Ye(),o(),st(),Ut(),Re(),Bn(),Vt(),ce(),v(),Ie(),Fn(),Ot(),Mn(),cn(),pt(),ze(),In(),Rn(),Ct(),Xt(),et();var fc=/\u2028|\u2029/g;function pc(e){return e.replace(fc,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function mc(e){return pc(W(e))}Or(),jr(),sr(),St();var hc=`SandboxNetworkAccess`;function gc(e){if(e){if(e.type===`classifier`)return e.reason;switch(e.type){case`rule`:case`mode`:case`subcommandResults`:case`permissionPromptTool`:return;case`hook`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return e.reason}}}function _c(e,t,n,r){let i;try{i=e.getActivityDescription?.(t)??e.getToolUseSummary?.(t)??e.userFacingName(t)}catch{i=e.name}return{tool_name:e.name,action_description:i,tool_use_id:n,request_id:r,input:t}}var vc=1e3,yc=class{constructor(e,t){a(this,`input`,void 0),a(this,`replayUserMessages`,void 0),a(this,`structuredInput`,void 0),a(this,`pendingRequests`,new Map),a(this,`restoredWorkerState`,Promise.resolve(null)),a(this,`inputClosed`,!1),a(this,`unexpectedResponseCallback`,void 0),a(this,`resolvedToolUseIds`,new Set),a(this,`prependedLines`,[]),a(this,`onControlRequestSent`,void 0),a(this,`onControlRequestResolved`,void 0),a(this,`outbound`,new gt),this.input=e,this.replayUserMessages=t,this.input=e,this.structuredInput=this.read()}trackResolvedToolUseId(e){let t=e.request;if(t.subtype===`can_use_tool`&&(this.resolvedToolUseIds.add(t.tool_use_id),this.resolvedToolUseIds.size>vc)){let e=this.resolvedToolUseIds.values().next().value;e!==void 0&&this.resolvedToolUseIds.delete(e)}}flushInternalEvents(){return Promise.resolve()}get internalEventsPending(){return 0}prependUserMessage(e){this.prependedLines.push(`${W({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
2
+ `);if(t===-1)break;let n=e.slice(0,t);e=e.slice(t+1);let r=await this.processLine(n);r&&(zr(`info`,`cli_stdin_message_parsed`,{type:r.type}),yield r)}}.bind(this);yield*t();for await(let n of this.input)e+=n,yield*t();if(e){let t=await this.processLine(e);t&&(yield t)}this.inputClosed=!0;for(let e of this.pendingRequests.values())e.reject(Error(`Tool permission stream closed before response received`))}getPendingPermissionRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request).filter(e=>e.request.subtype===`can_use_tool`)}setUnexpectedResponseCallback(e){this.unexpectedResponseCallback=e}injectControlResponse(e){let t=e.response,n=t?.request_id;if(!n)return;let r=this.pendingRequests.get(n);if(r)if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n),this.write({type:`control_cancel_request`,request_id:n}),t.subtype===`error`)r.reject(Error(t.error));else{let e=t.response;if(r.schema)try{r.resolve(r.schema.parse(e))}catch(e){r.reject(e)}else r.resolve({})}}setOnControlRequestSent(e){this.onControlRequestSent=e}setOnControlRequestResolved(e){this.onControlRequestResolved=e}async processLine(e){if(e)try{let t=Tr(e);if(t.type===`keep_alive`)return;if(t.type===`update_environment_variables`){let e=t.variables??{},n=Object.keys(e);for(let[t,n]of Object.entries(e))process.env[t]=n;K(`[structuredIO] applied update_environment_variables: ${n.join(`, `)}`);return}if(t.type===`control_response`){let e=`uuid`in t&&typeof t.uuid==`string`?t.uuid:void 0;e&&ye(e,`completed`);let n=t.response,r=this.pendingRequests.get(n.request_id);if(!r){let e=(n.subtype===`success`?n.response:void 0)?.toolUseID;if(typeof e==`string`&&this.resolvedToolUseIds.has(e)){K(`Ignoring duplicate control_response for already-resolved toolUseID=${e} request_id=${n.request_id}`);return}this.unexpectedResponseCallback&&await this.unexpectedResponseCallback(t);return}if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n.request_id),r.request.request.subtype===`can_use_tool`&&this.onControlRequestResolved&&this.onControlRequestResolved(n.request_id),n.subtype===`error`){r.reject(Error(n.error??`Unknown error`));return}let i=n.response;if(r.schema)try{r.resolve(r.schema.parse(i))}catch(e){r.reject(e)}else r.resolve({});return this.replayUserMessages?t:void 0}if(t.type!==`user`&&t.type!==`control_request`&&t.type!==`assistant`&&t.type!==`system`){K(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||bc(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&bc(`Error: Expected message role 'user', got '${t.message?.role}'`),t)}catch(t){console.error(`Error parsing streaming input line: ${e}: ${t}`),process.exit(1)}}async write(e){Zr(`${mc(e)}\n`)}async sendRequest(e,t,n,r=Y()){let i={type:`control_request`,request_id:r,request:e};if(this.inputClosed)throw Error(`Stream closed`);if(n?.aborted)throw Error(`Request aborted`);this.outbound.enqueue(i),e.subtype===`can_use_tool`&&this.onControlRequestSent&&this.onControlRequestSent(i);let a=()=>{this.outbound.enqueue({type:`control_cancel_request`,request_id:r});let e=this.pendingRequests.get(r);e&&(this.trackResolvedToolUseId(e.request),e.reject(new Sr))};n&&n.addEventListener(`abort`,a,{once:!0});try{return await new Promise((n,i)=>{this.pendingRequests.set(r,{request:{type:`control_request`,request_id:r,request:e},resolve:e=>{n(e)},reject:i,schema:t})})}finally{n&&n.removeEventListener(`abort`,a),this.pendingRequests.delete(r)}}createCanUseTool(e){return async(t,n,r,i,a,o)=>{let s=o??await u(t,n,r,i,a);if(s.behavior===`allow`||s.behavior===`deny`)return s;let c=new AbortController,l=r.abortController.signal,d=()=>c.abort();l.addEventListener(`abort`,d,{once:!0});try{let i=xc(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=Y();e?.(_c(t,n,a,o));let l=this.sendRequest({subtype:`can_use_tool`,tool_name:t.name,input:n,permission_suggestions:s.suggestions,blocked_path:s.blockedPath,decision_reason:gc(s.decisionReason),tool_use_id:a,agent_id:r.agentId},uc(),c.signal,o).then(e=>({source:`sdk`,result:e})),u=await Promise.race([i,l]);return u.source===`hook`?u.decision?(l.catch(()=>{}),c.abort(),u.decision):dc((await l).result,t,n,r):dc(u.result,t,n,r)}catch(e){return dc({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&Oe(`running`),l.removeEventListener(`abort`,d)}}}createHookCallback(e,t){return{type:`callback`,timeout:t,callback:async(t,n,r)=>{try{return await this.sendRequest({subtype:`hook_callback`,callback_id:e,input:t,tool_use_id:n||void 0},Wn(),r)}catch(t){return console.error(`Error in hook callback ${e}:`,t),{}}}}}async handleElicitation(e,t,n,r,i,a,o){try{return await this.sendRequest({subtype:`elicitation`,mcp_server_name:e,message:t,mode:i,url:a,elicitation_id:o,requested_schema:n},Qs(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:hc,input:{host:e.host},tool_use_id:Y(),description:`Allow network connection to ${e.host}?`},uc())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},P({mcp_response:nr()}))).mcp_response}};function bc(e){console.error(e),process.exit(1)}async function xc(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=nt(e,t,n,r,a,i,r.abortController.signal);for await(let e of o)if(e.permissionRequestResult&&(e.permissionRequestResult.behavior===`allow`||e.permissionRequestResult.behavior===`deny`)){let t=e.permissionRequestResult;if(t.behavior===`allow`){let e=t.updatedInput||n,i=t.updatedPermissions??[];if(i.length>0){We(i);let e=Ln(r.getAppState().toolPermissionContext,i);r.setAppState(t=>t.toolPermissionContext===e?t:{...t,toolPermissionContext:e})}return{behavior:`allow`,updatedInput:e,userModified:!1,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}else return{behavior:`deny`,message:t.message||`Permission denied by PermissionRequest hook`,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}}Oi(),Nr(),Fi(),[...Pi],Or();var Sc=`[stdout-guard]`,Cc=!1,$=``,wc=null;function Tc(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function Ec(){Cc||(Cc=!0,wc=process.stdout.write.bind(process.stdout),process.stdout.write=((e,t,n)=>{let r=typeof e==`string`?e:Buffer.from(e).toString(`utf-8`);$+=r;let i,a=!0;for(;(i=$.indexOf(`
3
+ `))!==-1;){let e=$.slice(0,i);$=$.slice(i+1),Tc(e)?a=wc(`${e}\n`):(process.stderr.write(`${Sc} ${e}\n`),K(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a}),kr(async()=>{$.length>0&&(wc&&Tc($)?wc(`${$}\n`):process.stderr.write(`${Sc} ${$}\n`),$=``),wc&&(process.stdout.write=wc,wc=null),Cc=!1}))}Jr(),Zt(),sn(),Dt(),ut(),c(),ki(),_(),Hn(),Qe(),At(),Ce(),pn(),Wi(),Or(),wr(),br(),wr(),ti(),An(),Or();function Dc(e){let t=process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY,n=t?parseInt(t,10):null,r=n&&!isNaN(n)&&n>0,i=null,a=0;return{start(){i&&(clearTimeout(i),i=null),r&&(a=Date.now(),i=setTimeout(()=>{let t=Date.now()-a;e()&&t>=n&&(K(`Exiting after ${n}ms of idle time`),k())},n))},stop(){i&&(clearTimeout(i),i=null)}}}fi(),Li(),Et(),Bt(),Ze(),ke(),p(),rn(),en(),yt(),Zi(),Qi();function Oc(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(Pe(e))return{sessionId:e,ingressUrl:null,isUrl:!1,jsonlFile:null,isJsonlFile:!1};try{let t=new URL(e);return{sessionId:Y(),ingressUrl:t.href,isUrl:!0,jsonlFile:null,isJsonlFile:!1}}catch{}return null}ui(),Jt(),wt(),Dn(),Cn(),Yt(),lt(),kn(),Pt(),O(),Xe(),He(),gn(),ta(),ra(),Or(),jr();async function kc(){try{let e=await fa(f(),`utf-8`),t=Kr().safeParse(Tr(e));return t.success?t.data:(K(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function Ac(e){await me(f(),W(e,null,2))}async function jc(e,t){let n=Zn();if(!n)return;let r=await Mc(t);r!==null&&await me(da(n,Ve(e)),r)}async function Mc(e){let t=[da(e,`.claude-plugin`,`marketplace.json`),da(e,`marketplace.json`),e];for(let e of t)try{return await fa(e,`utf-8`)}catch{}return null}async function Nc(){let e=await vn();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await jc(t,n.installLocation)}catch(e){K(`Failed to save marketplace JSON for ${t}: ${e}`)}await Ac({...await kc(),...e})}ri(),Er(),Or(),Ur(),ti(),At(),Qe();async function Pc(){let e=b();K(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await qt();t&&(mn(),w(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Ar().mkdir(tt()),await Ar().mkdir(x()));let n=Object.keys(En()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)K(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Vr(`headless_marketplace_reconcile`,()=>sa({skip:e?(e,t)=>!at(t):void 0,onProgress:e=>{e.type===`installed`?K(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&K(`installPluginsForHeadless: failed to install marketplace ${e.name}: ${e.error}`)}}),e=>({installed_count:e.installed.length,updated_count:e.updated.length,failed_count:e.failed.length,skipped_count:e.skipped.length}));t.skipped.length>0&&K(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(mn(),w(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Nc();let t=await Hi();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&w(`headlessPluginInstall: plugins changed`),e&&kr(Ee),i}catch(e){return q(e),!1}finally{J(`tengu_headless_plugin_install`,r)}}Mr(),ri(),Or(),Ur(),ce(),Ie(),ti(),Xr(),v(),In(),Er(),br(),et(),Xt(),pt(),jr(),la(),Ce(),Un(),Ht(),pe(),wr(),mi();var Fc=1e4,Ic=new Set,Lc=[];function Rc(e){if(Ic.has(e))return!1;if(Ic.add(e),Lc.push(e),Lc.length>Fc){let e=Lc.splice(0,Lc.length-Fc);for(let t of e)Ic.delete(t)}return!0}function zc(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Bc(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
4
+ `):e.flatMap(zc)}function Vc(e,t){return t!==void 0&&t.mode===`prompt`&&t.workload===e.workload&&t.isMeta===e.isMeta}async function Hc(e,n,r,i,a,o,s,c){if(Rt.subscribe(e=>{nn(e,r),ci()&&r(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),!ae()&&t(process.env.CLAUDE_CODE_PROACTIVE)&&qe(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),ue(),E(`runHeadless_entry`),await Ri()&&await zi(),E(`after_grove_check`),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
5
+ `),k(1);return}if(c.rewindFiles&&!c.resume){process.stderr.write(`Error: --rewind-files requires --resume
6
+ `),k(1);return}if(c.rewindFiles&&e){process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
7
+ `),k(1);return}let l=Qc(e,c);c.outputFormat===`stream-json`&&Ec();let u=C.getSandboxUnavailableReason();if(u){if(C.isSandboxRequired()){process.stderr.write(`\nError: sandbox required but unavailable: ${u}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),k(1);return}process.stderr.write(`\n⚠ Sandbox disabled: ${u}\n Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.\n\n`)}else if(C.isSandboxingEnabled())try{await C.initialize(l.createSandboxAskCallback())}catch(e){process.stderr.write(`\n❌ Sandbox Error: ${G(e)}\n`),k(1,`other`);return}c.outputFormat===`stream-json`&&c.verbose&&jt(e=>{let t=(()=>{switch(e.type){case`started`:return{type:`system`,subtype:`hook_started`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,uuid:Y(),session_id:U()};case`progress`:return{type:`system`,subtype:`hook_progress`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,stdout:e.stdout,stderr:e.stderr,output:e.output,uuid:Y(),session_id:U()};case`response`:return{type:`system`,subtype:`hook_response`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,output:e.output,stdout:e.stdout,stderr:e.stderr,exit_code:e.exitCode,outcome:e.outcome,uuid:Y(),session_id:U()}}})();l.write(t)}),c.setupTrigger&&await le(c.setupTrigger),E(`before_loadInitialMessages`);let d=n(),{messages:f,turnInterruptionState:p,agentSetting:m}=await Zc(r,{continue:c.continue,resume:c.resume,resumeSessionAt:c.resumeSessionAt,forkSession:c.forkSession,outputFormat:c.outputFormat,sessionStartHooksPromise:c.sessionStartHooksPromise,restoredWorkerState:l.restoredWorkerState}),h=be();if(h&&l.prependUserMessage(h),!c.agent&&!ur()&&m){let{agentDefinition:e}=ia(m,void 0,{activeAgents:s,allAgents:s});if(e){if(r(t=>({...t,agent:e.agentType})),!c.systemPrompt&&!Tn(e)){let t=e.getSystemPrompt();t&&(c.systemPrompt=t)}Ft(e.agentType)}}if(f.length===0&&process.exitCode!==void 0)return;if(c.rewindFiles){if(f.find(e=>e.uuid===c.rewindFiles)?.type!==`user`){process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${c.rewindFiles} is not a user message in this session\n`),k(1);return}let e=n(),t=await qc(c.rewindFiles,e,r,!1);if(!t.canRewind){process.stderr.write(`Error: ${t.error||`Unexpected error`}\n`),k(1);return}process.stdout.write(`Files rewound to state at message ${c.rewindFiles}\n`),k(0);return}let g=typeof c.resume==`string`&&(!!Pe(c.resume)||c.resume.endsWith(`.jsonl`)),_=!!c.sdkUrl;if(!e&&!g&&!_){process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
8
+ `),k(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
9
+ `),k(1);return}let ee=bt(d.mcp.tools,d.toolPermissionContext),te=[...a,...ee],ne=Gc(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>n().mcp.tools,e=>{r(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),Oe(`requires_action`,e)});c.permissionPromptToolName&&(te=te.filter(e=>!Ai(e,c.permissionPromptToolName))),Yr(),E(`after_loadInitialMessages`),await yi(),E(`after_modelStrings`);let v=c.outputFormat===`json`&&c.verbose,re=[],y;E(`before_runHeadlessStreaming`);for await(let e of Uc(l,d.mcp.clients,[...i,...d.mcp.commands],te,f,ne,o,n,r,s,c,p))c.outputFormat===`stream-json`&&c.verbose&&await l.write(e),e.type!==`control_response`&&e.type!==`control_request`&&e.type!==`control_cancel_request`&&!(e.type===`system`&&(e.subtype===`session_state_changed`||e.subtype===`task_notification`||e.subtype===`task_started`||e.subtype===`task_progress`||e.subtype===`post_turn_summary`))&&e.type!==`stream_event`&&e.type!==`keep_alive`&&e.type!==`streamlined_text`&&e.type!==`streamlined_tool_use_summary`&&e.type!==`prompt_suggestion`&&(v&&re.push(e),y=e);switch(c.outputFormat){case`json`:if(y?.type!==`result`)throw Error(`No messages returned`);if(c.verbose){Zr(`${W(re)}\n`);break}Zr(`${W(y)}\n`);break;case`stream-json`:break;default:if(y?.type!==`result`)throw Error(`No messages returned`);switch(y.subtype){case`success`:Zr(y.result.endsWith(`
10
+ `)?y.result:`${y.result}\n`);break;case`error_during_execution`:Zr(`Execution error`);break;case`error_max_turns`:Zr(`Error: Reached max turns (${c.maxTurns}).\nTip: Increase the limit with --max-turns or continue in a new session.`);break;case`error_max_budget_usd`:Zr(`Error: Exceeded USD budget ($${c.maxBudgetUsd}).\nTip: Increase the limit with --max-budget-usd or start a new session to continue.`);break;case`error_max_structured_output_retries`:Zr(`Error: Failed to provide valid structured output after maximum retries.
11
+ Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(rt(),qr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-CzN3Ax2B.js`);await e()}catch{}k(y?.type===`result`&&y?.is_error?1:0)}function Uc(n,i,a,o,s,c,l,u,f,p,g,_){let ee=!1,v,ce=!1,le=null,b,x=n.outbound;process.on(`SIGINT`,()=>{zr(`info`,`shutdown_signal`,{signal:`SIGINT`}),b&&!b.signal.aborted&&b.abort(),Gt(0)}),kr(async()=>{let e={};for(let t of xt(u()))yn(t)&&(e[t.type]=(e[t.type]??0)+1);zr(`info`,`run_state_at_shutdown`,{run_active:ee,run_phase:v,worker_status:ie(),internal_events_pending:n.internalEventsPending,bg_tasks:e})}),Me(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&x.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let S={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},pe;g.enableAuthStatus&&(pe=ii.getInstance().subscribe(e=>{x.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}));let me=e=>{let t=qi(e);t&&x.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};_n.add(me);let ge=s,ve=Ke(s,X(),100),C=an(100),be=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;_&&_.kind!==`none`&&be&&(K(`[print.ts] Auto-resuming interrupted turn (kind: ${_.kind})`),Xc(ge,_.message),Fe({mode:`prompt`,value:_.message.message.content,uuid:Y()}));let Ce=na().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?Ci():Ei(t),r=h(n),i=Si(e.value),a=bi(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),Ee=g.userSpecifiedModel;function ke(e,t){let n=de(e,vi(t));ge.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&x.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:U(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let w=[],Pe=[],Ie=new Set;function Re(e){for(let t of e){if(t.type!==`connected`||Ie.has(t.name)||t.config.type===`sdk`)continue;let e=t.name;try{t.client.setRequestHandler(Be,async(t,r)=>{$r(e,`Elicitation request received in print mode: ${W(t)}`);let i=t.params.mode===`url`?`url`:`form`;J(`tengu_mcp_elicitation_shown`,{mode:i});let a=await ln(e,t.params,r.signal);if(a)return $r(e,`Elicitation resolved by hook: ${W(a)}`),J(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in t.params?t.params.url:void 0,s=`requestedSchema`in t.params?t.params.requestedSchema:void 0,c=`elicitationId`in t.params?t.params.elicitationId:void 0,l=await n.handleElicitation(e,t.params.message,s,r.signal,i,o,c),u=await Nn(e,l,r.signal,i,c);return J(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),t.client.setNotificationHandler(Nt,t=>{let{elicitationId:n}=t.params;$r(e,`Elicitation completion notification: ${n}`),m({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),x.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),Ie.add(e)}catch{}}}async function ze(){let e=new Set(Object.keys(l)),t=new Set(w.map(e=>e.name)),r=Array.from(e).some(e=>!t.has(e)),i=Array.from(t).some(t=>!e.has(t)),a=w.some(e=>e.type===`pending`),o=w.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of w)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await hn(l,(e,t)=>n.sendMcpMessage(e,t));w=r.clients,Pe=r.tools;let i=Pr([...t,...e]);f(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Wr(t)))),...Pe]}})),Kt(w)}}ze();let T={clients:[],tools:[],configs:{}},Ve=e=>{let t=qn(e.toolPermissionContext,e.mcp.tools),n=vt(Ui([...o,...Pe,...T.tools],t,e.toolPermissionContext.mode),`name`);g.permissionPromptToolName&&(n=n.filter(e=>!Ai(e,g.permissionPromptToolName)));let r=dr();if(r&&!g.jsonSchema){let e=ji(r);`tool`in e&&(n=[...n,e.tool])}return n},He=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function We(e){let t=async()=>{let t=new Set(w.map(e=>e.name)),n=await tl(e,{configs:l,clients:w,tools:Pe},T,f);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),w=n.newSdkState.clients,Pe=n.newSdkState.tools,T=n.newDynamicState,n.sdkServersChanged){let e=new Set(w.map(e=>e.name)),n=Pr([...t,...e]);f(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Wr(t)))),...Pe]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return He=He.then(t,t),He}function Ge(){let e=u(),t=e.mcp.clients,n=vt([...e.mcp.tools,...T.tools],`name`),r=new Set([...t.map(e=>e.name),...w.map(e=>e.name)]);return[...t,...w,...T.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers,oauth:e.config.oauth};else if(e.config.type===`claudeai-proxy`)t={type:`claudeai-proxy`,url:e.config.url,id:e.config.id};else if(e.config.type===`stdio`||e.config.type===void 0){let n=e.config;t={type:`stdio`,command:n.command,args:n.args}}let r=e.type===`connected`?xe(n,e.name).map(e=>({name:e.mcpInfo?.toolName??e.name,annotations:{readOnly:e.isReadOnly({})||void 0,destructive:e.isDestructive?.({})||void 0,openWorld:e.isOpenWorld?.({})||void 0}})):void 0;return{name:e.name,status:e.type,serverInfo:e.type===`connected`?e.serverInfo:void 0,error:e.type===`failed`?e.error:void 0,config:t,scope:e.config.scope,tools:r}})}async function Ye(){try{await Pc()&&await tt()}catch(e){q(e)}}let Xe=null;r()||(t(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Xe=Ye():Ye());let Ze=Dc(()=>!ee),Qe=a,$e=p;async function et(){let{agentDefinitions:e}=await ca(f);Qe=await on(X());let t=$e.filter(e=>e.source===`flagSettings`);$e=[...e.allAgents,...t]}async function tt(){let{servers:e}=await wn(),t={};for(let[n,r]of Object.entries(e)){let e=r.type;(e===void 0||e===`stdio`||e===`sse`||e===`http`||e===`sdk`)&&(t[n]=r)}for(let[e,n]of Object.entries(l))n.type===`sdk`&&!(e in t)&&(t[e]=n);let{response:n,sdkServersChanged:r}=await We(t);r&&ze(),K(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let nt=oa.subscribe(()=>{Je(),on(X()).then(e=>{Qe=e})}),it=()=>{setTimeout(()=>{!ae()||Le()||ce||(async()=>{let e=await ft({basePrompt:`<${Qr}>${new Date().toLocaleTimeString()}</${Qr}>`,currentDir:X(),shouldCreate:()=>!ce});if(ce){await xn({commands:e});return}for(let t of e)Fe({...t,uuid:Y()});at()})().catch(e=>{q(e),K(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};d(()=>{b&&De(`now`).length>0&&b.abort(`interrupt`)});let at=async()=>{if(ee)return;if(ee=!0,v=void 0,Oe(`running`),Ze.stop(),E(`run_entry`),await ze(),E(`after_updateSdkMcp`),Xe){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=si(e).then(()=>`timeout`);await Promise.race([Xe,t])===`timeout`&&(q(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),J(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Xe;Xe=null,await et();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-DtmHtEiS.js`);t()}let t=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=oe(t);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;Vc(r,we(t));)i.push(oe(t));let a=await _e(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Bc(i.map(e=>e.value)),uuid:i.findLast(e=>e.uuid)?.uuid??r.uuid});let o=i.map(e=>e.uuid).filter(e=>e!==void 0);if(g.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&x.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:U(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=u(),l=[...s.mcp.clients,...w,...T.clients];Re(l);let d=Ve(s);for(let e of o)ye(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&x.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let p=r.value,m=a.claimedCommands;if(S.abortController?.abort(),S.abortController=null,S.pendingSuggestion=null,S.pendingLastEmittedEntry=null,S.lastEmitted&&r.mode===`prompt`){let e=typeof p==`string`?p:p.find(e=>e.type===`text`)?.text;typeof e==`string`&&Ae(S.lastEmitted.text,e,S.lastEmitted.emittedAt,S.lastEmitted.promptId,S.lastEmitted.generationRequestId),S.lastEmitted=null}b=Mt(),E(`before_ask`),Wt();let h=r,_=!1;try{if(await ai(h.workload??g.workload,async()=>{for await(let e of Ji({commands:vt([...Qe,...s.mcp.commands],`name`),prompt:p,promptUuid:h.uuid,isMeta:h.isMeta,cwd:X(),tools:d,verbose:g.verbose,mcpClients:l,thinkingConfig:g.thinkingConfig,maxTurns:g.maxTurns,maxBudgetUsd:g.maxBudgetUsd,taskBudget:g.taskBudget,canUseTool:c,userSpecifiedModel:Ee,fallbackModel:g.fallbackModel,jsonSchema:dr()??g.jsonSchema,mutableMessages:ge,getReadFileCache:()=>C.size===0?ve:$t(ve,C),setReadFileCache:e=>{ve=e;for(let[e,t]of C.entries()){let n=ve.get(e);(!n||t.timestamp>n.timestamp)&&ve.set(e,t)}C.clear()},customSystemPrompt:g.systemPrompt,appendSystemPrompt:g.appendSystemPrompt,getAppState:u,setAppState:f,abortController:b,replayUserMessages:g.replayUserMessages,includePartialMessages:g.includePartialMessages,handleElicitation:(e,t,r)=>n.handleElicitation(e,t.message,void 0,r,t.mode,t.url,`elicitationId`in t?t.elicitationId:void 0),agents:$e,orphanedPermission:h.orphanedPermission,setSDKStatus:e=>{x.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(e.type===`result`){_=!!e.is_error;for(let e of Ue())x.enqueue(e);xt(u()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&yn(e))?le=e:(le=null,x.enqueue(e))}else{for(let e of Ue())x.enqueue(e);x.enqueue(e)}}),_)await ct({commands:m,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:h.workload??g.workload});else{let e=await ct({commands:m,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:h.workload??g.workload});for(let t of e)Fe({...t,uuid:Y()})}}catch(e){throw await ct({commands:m,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:h.workload??g.workload}),e}for(let e of o)ye(e,`completed`);if(g.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){S.abortController?.abort();let e=new AbortController;S.abortController=e;let t=$n();if(!t)Ne(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await se(e,ge,u,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:Y(),session_id:U()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};le?(S.pendingSuggestion=r,S.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(S.lastEmitted=i,x.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Ne(`aborted`,void 0,void 0,`sdk`);return}q(Cr(e))}finally{S.inflightPromise===n.promise&&(S.inflightPromise=null)}})(),S.inflightPromise=n.promise}}rt(),dn(),ue()}};do{for(let e of Ue())x.enqueue(e);v=`draining_commands`,await a(),i=!1;{let e=xt(u()).some(e=>yn(e)),n=we(t)!==void 0;(e||n)&&(i=!0,n||(v=`waiting_for_agents`,await si(100)))}}while(i);le&&(x.enqueue(le),le=null,S.pendingSuggestion&&(x.enqueue(S.pendingSuggestion),S.pendingLastEmittedEntry&&(S.lastEmitted={...S.pendingLastEmittedEntry,emittedAt:Date.now()},S.pendingLastEmittedEntry=null),S.pendingSuggestion=null))}catch(e){try{await n.write({type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:U(),total_cost_usd:0,usage:Se,modelUsage:{},permission_denials:[],uuid:Y(),errors:[G(e),...ei().map(e=>e.error)]})}catch{}S.abortController?.abort(),k(1);return}finally{if(v=`finally_flush`,await n.flushInternalEvents(),v=`finally_post_flush`,!Jn()){Oe(`idle`);for(let e of Ue())x.enqueue(e)}ee=!1,Ze.start()}if(ae()&&!Le()&&we(t)===void 0&&!ce){it();return}if(we(t)!==void 0){at();return}ce&&(S.inflightPromise&&await Promise.race([S.inflightPromise,si(5e3)]),S.abortController?.abort(),S.abortController=null,await Tt(),nt(),pe?.(),_n.delete(me),x.done())},D=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},O=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},st=new Set;n.setUnexpectedResponseCallback(async e=>{await $c({message:e,setAppState:f,handledToolUseIds:st,onEnqueued:()=>{at()}})});let lt=new Map,ut=new Map,dt=new Set,pt=new Map,mt=null;return(async()=>{let e=!1;zr(`info`,`cli_message_loop_started`);for await(let t of n.structuredInput){let r=`uuid`in t?t.uuid:void 0;if(r&&t.type!==`user`&&t.type!==`control_response`&&ye(r,`completed`),t.type===`control_request`){let r=t,o=r.request;if(r.request.subtype===`interrupt`)f(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),b&&b.abort(),S.abortController?.abort(),S.abortController=null,S.lastEmitted=null,S.pendingSuggestion=null,D(r);else if(o.subtype===`end_session`){K(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),b&&b.abort(),S.abortController?.abort(),S.abortController=null,S.lastEmitted=null,S.pendingSuggestion=null,D(r);break}else if(r.request.subtype===`initialize`){if(r.request.sdkMcpServers&&r.request.sdkMcpServers.length>0)for(let e of r.request.sdkMcpServers)l[e]={type:`sdk`,name:e};await Kc(r.request,r.request_id,e,x,a,Ce,n,!!g.enableAuthStatus,g,p,u),r.request.promptSuggestions&&f(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),r.request.agentProgressSummaries&&vr(!0),e=!0,je()&&at()}else if(r.request.subtype===`set_permission_mode`){let e=r.request;f(t=>({...t,toolPermissionContext:Jc(e,r.request_id,t.toolPermissionContext,x)}))}else if(r.request.subtype===`set_model`){let e=r.request.model??`default`,t=e==="default"?Ci():e;Ee=t,_r(t),tn({model:t}),ke(e,t),D(r)}else if(r.request.subtype===`set_max_thinking_tokens`)r.request.max_thinking_tokens===null?g.thinkingConfig=void 0:r.request.max_thinking_tokens===0?g.thinkingConfig={type:`disabled`}:g.thinkingConfig={type:`enabled`,budgetTokens:r.request.max_thinking_tokens},D(r);else if(r.request.subtype===`mcp_status`)D(r,{mcpServers:Ge()});else if(r.request.subtype===`get_context_usage`)try{let e=u(),t=await ea({messages:ge,getAppState:u,options:{mainLoopModel:wi(),tools:Ve(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:g.systemPrompt,appendSystemPrompt:g.appendSystemPrompt}});D(r,{...t})}catch(e){O(r,G(e))}else if(r.request.subtype===`mcp_message`){let e=r.request,t=w.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),D(r)}else if(r.request.subtype===`rewind_files`){let e=u(),t=await qc(r.request.user_message_id,e,f,r.request.dry_run??!1);t.canRewind||r.request.dry_run?D(r,t):O(r,t.error??`Unexpected error`)}else if(r.request.subtype===`cancel_async_message`){let e=r.request.message_uuid,t=re(t=>t.uuid===e);D(r,{cancelled:t.length>0})}else if(r.request.subtype===`seed_read_state`){try{let e=Br(r.request.path),t=Math.floor((await pa(e)).mtimeMs);if(t<=r.request.mtime){let n=await fa(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
12
+ `,`
13
+ `);C.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}D(r)}else if(r.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await We(r.request.servers);D(r,e),t&&ze()}else if(r.request.subtype===`reload_plugins`)try{let e=await ca(f),t=$e.filter(e=>e.source===`flagSettings`);$e=[...e.agentDefinitions.allAgents,...t];let n=[],[i,a,o]=await Promise.allSettled([on(X()),tt(),Xn()]);i.status===`fulfilled`?Qe=i.value:q(i.reason),a.status===`rejected`&&q(a.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):q(o.reason),D(r,{commands:Qe.filter(e=>e.userInvocable!==!1).map(e=>({name:fe(e),description:y(e),argumentHint:e.argumentHint||``})),agents:$e.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Ge(),error_count:e.error_count})}catch(e){O(r,G(e))}else if(r.request.subtype===`mcp_reconnect`){let e=u(),{serverName:t}=r.request;Ie.delete(t);let n=Qt(t)??i.find(e=>e.name===t)?.config??w.find(e=>e.name===t)?.config??T.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)O(r,`Server not found: ${t}`);else{let e=await _t(t,n),i=Wr(t);if(f(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...A(n.mcp.tools,e=>e.name?.startsWith(i)),...e.tools],commands:[...A(n.mcp.commands,e=>he(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:Ii(n.mcp.resources,t)}})),T={...T,clients:[...T.clients.filter(e=>e.name!==t),e.client],tools:[...T.tools.filter(e=>!e.name?.startsWith(i)),...e.tools]},e.client.type===`connected`)Re([e.client]),D(r);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(r,t)}}}else if(r.request.subtype===`mcp_toggle`){let e=u(),{serverName:t,enabled:n}=r.request;Ie.delete(t);let a=Qt(t)??i.find(e=>e.name===t)?.config??w.find(e=>e.name===t)?.config??T.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)O(r,`Server not found: ${t}`);else if(n){bn(t,!0);let e=await _t(t,a),n=Wr(t);if(f(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...A(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...A(r.mcp.commands,e=>he(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:Ii(r.mcp.resources,t)}})),e.client.type===`connected`)Re([e.client]),D(r);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(r,t)}}else{bn(t,!1);let n=[...i,...w,...T.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await ot(t,a);let o=Wr(t);f(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:a}:e),tools:A(e.mcp.tools,e=>e.name?.startsWith(o)),commands:A(e.mcp.commands,e=>he(e,t)),resources:Ii(e.mcp.resources,t)}})),D(r)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=u(),n=Qt(e)??i.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)O(r,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)O(r,`Server type "${n.type}" does not support OAuth authentication`);else try{lt.get(e)?.abort();let t=new AbortController;lt.set(e,t);let i,a=new Promise(e=>{i=e}),o=Gn(e,n,e=>i(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{ut.set(e,t)}}),s=await Promise.race([a,o.then(()=>null)]);s?D(r,{authUrl:s,requiresUserAction:!0}):D(r,{requiresUserAction:!1}),pt.set(e,o),o.then(async()=>{if(un(e)||dt.has(e))return;let t=await _t(e,n),r=Wr(e);f(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...A(n.mcp.tools,e=>e.name?.startsWith(r)),...t.tools],commands:[...A(n.mcp.commands,t=>he(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:Ii(n.mcp.resources,e)}})),T={...T,clients:[...T.clients.filter(t=>t.name!==e),t.client],tools:[...T.tools.filter(e=>!e.name?.startsWith(r)),...t.tools]}}).catch(t=>{K(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{lt.get(e)===t&&(lt.delete(e),ut.delete(e),dt.delete(e),pt.delete(e))})}catch(e){O(r,G(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=ut.get(e);if(n){let i=!1;try{let e=new URL(t);i=e.searchParams.has(`code`)||e.searchParams.has(`error`)}catch{}if(!i)O(r,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{dt.add(e),n(t);let i=pt.get(e);if(i)try{await i,D(r)}catch(e){O(r,e instanceof Error?e.message:`OAuth authentication failed`)}else D(r)}}else O(r,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;mt?.service.cleanup(),J(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Bi,n,i=new Promise(e=>{n=e}),a=t.startOAuthFlow(async(e,t)=>{n({manualUrl:e,automaticUrl:t})},{loginWithClaudeAi:e??!0,skipBrowserOpen:!0}).then(async t=>{await Vi(t),J(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),mt?.service===t&&(mt=null)});mt={service:t,flow:a},a.catch(e=>K(`claude_authenticate flow ended: ${e}`,{level:`info`}));try{let{manualUrl:e,automaticUrl:t}=await Promise.race([i,a.then(()=>{throw Error(`OAuth flow completed without producing auth URLs`)})]);D(r,{manualUrl:e,automaticUrl:t})}catch(e){O(r,G(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!mt)O(r,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&mt.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=mt;e.then(()=>{let e=xi();D(r,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:Di()}})},e=>O(r,G(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=u(),n=Qt(e)??i.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)O(r,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)O(r,`Cannot clear auth for server type "${n.type}"`);else{await te(e,n);let t=await _t(e,n),i=Wr(e);f(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...A(n.mcp.tools,e=>e.name?.startsWith(i)),...t.tools],commands:[...A(n.mcp.commands,t=>he(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:Ii(n.mcp.resources,e)}})),D(r,{})}}else if(r.request.subtype===`apply_flag_settings`){let e=wi(),t=cr()??{},n=r.request.settings,i={...t,...n};for(let e of Object.keys(i))i[e]===null&&delete i[e];mr(i),Rt.notifyChange(`flagSettings`),`model`in n&&(n.model==null?_r(void 0):_r(String(n.model)));let a=wi();if(a!==e){Ee=a;let e=n.model?String(n.model):`default`;tn({model:a}),ke(e,a)}D(r)}else if(r.request.subtype===`get_settings`){let e=wi();D(r,{...Gr(),applied:{model:e}})}else if(r.request.subtype===`stop_task`){let{task_id:e}=r.request;try{await Te(e,{getAppState:u,setAppState:f}),D(r,{})}catch(e){O(r,G(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(b&&!b.signal.aborted?b:Mt()).signal;(async()=>{try{let i=await Xi(e,n);if(i&&t)try{On(U(),i)}catch(e){q(e)}D(r,{title:i})}catch(e){O(r,G(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=$n(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:Mt()}}:await Ki({tools:Ve(u()),commands:Qe,mcpClients:[...u().mcp.clients,...w,...T.clients],messages:ge,readFileState:ve,getAppState:u,setAppState:f,customSystemPrompt:g.systemPrompt,appendSystemPrompt:g.appendSystemPrompt,thinkingConfig:g.thinkingConfig,agents:$e}),i=await $i({question:e,cacheSafeParams:n});D(r,{response:i.response})}catch(e){O(r,G(e))}})()}else r.request.subtype===`set_proactive`?(r.request.enabled?ae()||(qe(`command`),it()):ne(),D(r)):O(r,`Unsupported control request subtype: ${r.request.subtype}`);continue}else if(t.type===`control_response`){g.replayUserMessages&&x.enqueue(t);continue}else if(t.type===`keep_alive`)continue;else if(t.type===`update_environment_variables`)continue;else if(t.type===`assistant`||t.type===`system`){let e=Yi([t]);ge.push(...e),t.type===`assistant`&&g.replayUserMessages&&x.enqueue(t);continue}if(t.type!==`user`)continue;let o=t;if(e=!0,o.uuid){let e=U(),t=await Sn(e,o.uuid);if(t||Ic.has(o.uuid)){K(`Skipping duplicate user message: ${o.uuid}`),g.replayUserMessages&&(K(`Sending acknowledgment for duplicate user message: ${o.uuid}`),x.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&ye(o.uuid,`completed`);continue}Rc(o.uuid)}Fe({mode:`prompt`,value:o.message.content,uuid:o.uuid,priority:o.priority}),f(e=>({...e,attribution:It(e.attribution,e=>{Qn(e).catch(e=>{K(`Attribution: Failed to save snapshot: ${e}`)})})})),at()}ce=!0,ee||(S.inflightPromise&&await Promise.race([S.inflightPromise,si(5e3)]),S.abortController?.abort(),S.abortController=null,await Tt(),nt(),pe?.(),_n.delete(me),x.done())})(),x}function Wc(e){let t=async(n,r,i,a,o,s)=>{let c=s??await u(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:d}=Yn(i.abortController.signal);if(l.aborted)return d(),{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let f=new Promise(e=>{l.addEventListener(`abort`,()=>e(`aborted`),{once:!0})}),p=e.call({tool_name:n.name,input:r,tool_use_id:o},i,t,a),m=await Promise.race([p,f]);if(d(),m===`aborted`||l.aborted)return{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let h=m,g=e.mapToolResultToToolResultBlockParam(h.data,`1`);if(!g.content||!Array.isArray(g.content)||!g.content[0]||g.content[0].type!==`text`||typeof g.content[0].text!=`string`)throw Error(`Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.`);return dc(uc().parse(rr(g.content[0].text)),e,r,i)};return t}function Gc(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await u(e,t,n,r,i);let i=null;return async(t,r,a,o,s,c)=>{if(!i){let t=n(),r=t.find(t=>Ai(t,e));if(!r){let n=`Error: MCP tool ${e} (passed via --permission-prompt-tool) not found. Available MCP tools: ${t.map(e=>e.name).join(`, `)||`none`}`;throw process.stderr.write(`${n}\n`),k(1),Error(n)}if(!r.inputJSONSchema){let t=`Error: tool ${e} (passed via --permission-prompt-tool) must be an MCP tool`;throw process.stderr.write(`${t}\n`),k(1),Error(t)}i=Wc(r)}return i(t,r,a,o,s,c)}}async function Kc(e,t,n,r,i,a,o,s,c,u,d){if(n){r.enqueue({type:`control_response`,response:{subtype:`error`,error:`Already initialized`,request_id:t,pending_permission_requests:o.getPendingPermissionRequests()}});return}if(e.systemPrompt!==void 0&&(c.systemPrompt=e.systemPrompt),e.appendSystemPrompt!==void 0&&(c.appendSystemPrompt=e.appendSystemPrompt),e.promptSuggestions!==void 0&&(c.promptSuggestions=e.promptSuggestions),e.agents){let t=zt(e.agents,`flagSettings`);u.push(...t)}if(c.agent){let e=ur()===c.agent,t=u.find(e=>e.agentType===c.agent);if(t&&!e){if(fr(t.agentType),!c.systemPrompt&&!Tn(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&_r(Ei(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let f=Lr()?.outputStyle||`default`,p=await l(xr()),m=xi();if(e.hooks){let t={};for(let[n,r]of Object.entries(e.hooks))t[n]=r.map(e=>{let t=e.hookCallbackIds.map(t=>o.createHookCallback(t,e.timeout));return{matcher:e.matcher,hooks:t}});gr(t)}e.jsonSchema&&hr(e.jsonSchema);let h={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:fe(e),description:y(e),argumentHint:e.argumentHint||``})),agents:u.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:f,available_output_styles:Object.keys(p),models:a,account:{email:m?.email,organization:m?.organization,subscriptionType:m?.subscription,tokenSource:m?.tokenSource,apiKeySource:m?.apiKeySource,apiProvider:Di()},pid:process.pid};if(ci()&&hi()){let e=d();h.fast_mode_state=li(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:h}}),s){let e=ii.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}}async function qc(e,t,n,r){if(!$e())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!S(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await D(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await ve(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${G(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Jc(e,t,n,r){if(e.mode===`bypassPermissions`){if(zn())return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:`Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration`}}),n;if(!n.isBypassPermissionsModeAvailable)return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:`Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions`}}),n}if(e.mode===`auto`&&!g()){let e=Kn();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${Pn(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...s(n.mode,e.mode,n),mode:e.mode}}function Yc(e,t){if(t===`stream-json`){let t={type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:U(),total_cost_usd:0,usage:Se,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(`${W(t)}\n`)}else process.stderr.write(`${e}\n`)}function Xc(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function Zc(e,t){let n=!lr();if(t.continue)try{J(`tengu_continue_print`,{});let r=await Gi(void 0,void 0);if(r)return t.forkSession||r.sessionId&&(pr(kt(r.sessionId),r.fullPath?ua(r.fullPath):null),n&&await ht()),aa(r,e),T(t.forkSession?{...r,worktreeSession:void 0}:r),{messages:r.messages,turnInterruptionState:r.turnInterruptionState,agentSetting:r.agentSetting}}catch(e){return q(e),k(1),{messages:[]}}if(t.resume)try{J(`tengu_resume_print`,{});let r=Oc(typeof t.resume==`string`?t.resume:``);if(!r){let e=`Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>`;return typeof t.resume==`string`&&(e+=`. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${t.resume}" is not a valid UUID`),Yc(e,t.outputFormat),k(1),{messages:[]}}let i=await Gi(r.sessionId,r.jsonlFile||void 0);if(!i||i.messages.length===0)return Yc(`No conversation found with session ID: ${r.sessionId}`,t.outputFormat),k(1),{messages:[]};if(t.resumeSessionAt){let e=i.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return Yc(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),k(1),{messages:[]};i.messages=e>=0?i.messages.slice(0,e+1):[]}return!t.forkSession&&i.sessionId&&(pr(kt(i.sessionId),i.fullPath?ua(i.fullPath):null),n&&await ht()),aa(i,e),T(t.forkSession?{...i,worktreeSession:void 0}:i),{messages:i.messages,turnInterruptionState:i.turnInterruptionState,agentSetting:i.agentSetting}}catch(e){return q(e),Yc(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),k(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??it(`startup`))}}function Qc(e,t){let n;return n=typeof e==`string`?e.trim()===``?jn([]):jn([W({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,new yc(n,t.replayUserMessages)}async function $c({message:e,setAppState:t,onEnqueued:n,handledToolUseIds:r}){let i=e.response;if(i?.subtype===`success`&&i.response?.toolUseID&&typeof i.response.toolUseID==`string`){let e=i.response,t=e.toolUseID;if(!t)return!1;if(K(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return K(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await mt(t);return a?(r.add(t),K(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),Fe({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(K(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function el(e){return{...e,scope:`dynamic`}}async function tl(e,t,n,r){let{allowed:i,blocked:a}=fn(e),o={};for(let e of a)o[e]=`Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)`;let s={},c={};for(let[e,t]of Object.entries(i))t.type===`sdk`?s[e]=t:c[e]=t;let l=new Set(Object.keys(t.configs)),u=new Set(Object.keys(s)),d=[],f=[],p={...t.configs},m=[...t.clients],h=[...t.tools];for(let e of l)if(!u.has(e)){let t=m.find(t=>t.name===e);t&&t.type===`connected`&&await t.cleanup(),m=m.filter(t=>t.name!==e);let n=`mcp__${e}__`;h=h.filter(e=>!e.name.startsWith(n)),delete p[e],f.push(e)}for(let[e,t]of Object.entries(s))if(!l.has(e)){p[e]=t;let n={type:`pending`,name:e,config:{...t,scope:`dynamic`}};m=[...m,n],d.push(e)}let g=await nl(c,n,r);return{response:{added:[...d,...g.response.added],removed:[...f,...g.response.removed],errors:{...o,...g.response.errors}},newSdkState:{configs:p,clients:m,tools:h},newDynamicState:g.newState,sdkServersChanged:d.length>0||f.length>0}}async function nl(e,t,n){let r=new Set(Object.keys(t.configs)),i=new Set(Object.keys(e)),a=[...r].filter(e=>!i.has(e)),o=[...i].filter(e=>!r.has(e)),s=[...r].filter(e=>i.has(e)).filter(n=>{let r=t.configs[n],i=e[n];return!r||!i||!ge(r,el(i))}),c=[],l=[],u={},d=[...t.clients],f=[...t.tools];for(let e of[...a,...s]){let n=d.find(t=>t.name===e),r=t.configs[e];if(n&&r){if(n.type===`connected`)try{await n.cleanup()}catch(e){q(e)}await ot(e,r)}let i=`mcp__${e}__`;f=f.filter(e=>!e.name.startsWith(i)),d=d.filter(t=>t.name!==e),a.includes(e)&&c.push(e)}for(let t of[...o,...s]){let n=e[t];if(!n)continue;let r=el(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await dt(t,r);if(d.push(e),e.type===`connected`){let t=await Lt(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Cr(e);u[t]=n.message,q(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=el(n))}let m={clients:d,tools:f,configs:p};return n(e=>{let n=new Set([...Object.keys(t.configs),...Object.keys(p)]),r=e.mcp.tools.filter(e=>{for(let t of n)if(e.name.startsWith(`mcp__${t}__`))return!1;return!0}),i=e.mcp.clients.filter(e=>!n.has(e.name));return{...e,mcp:{...e.mcp,tools:[...r,...f],clients:[...i,...d]}}}),{response:{added:l,removed:c,errors:u},newState:m}}export{Hc as runHeadless};
@@ -0,0 +1 @@
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Ec as t,GS as n,Gu as r,HS as i,RS as a,Sf as o,Tc as s,VS as c,Wu as l,Zi as u,bf as d,mm as f,nx as p,pm as m,tx as h,xf as g,yf as _}from"./loadAgentsDir-C1LkW7gl.js";import{I as v,t as y}from"./src-DL3w8VPk.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";import{A as x,L as S,N as C}from"./debug-8DCufdSp.js";import{h as w,t as T}from"./settings-DKN4xSpQ.js";import{n as E,r as D}from"./analytics-DJobLaWP.js";import{bt as O,yt as k}from"./prompt-BGqgPgCU.js";import{randomUUID as A}from"crypto";y(),d(),r(),o();var j=b();function M({input:e,progress:t,verbose:n}){return(0,j.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,j.jsx)(l,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),t?(0,j.jsx)(g,{fullOutput:t.fullOutput,output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,verbose:n}):_.renderToolUseProgressMessage?.([],{verbose:n,tools:[],terminalSize:void 0})]})}S(),E(),h(),u(),w();function N(){return T().defaultShell??`bash`}d(),k(),f();async function P(r,o,l,u,d){let f=O()&&N()===`powershell`;D(`tengu_input_bash`,{powershell:f});let h=i({content:n({inputString:`<bash-input>${r}</bash-input>`,precedingInputBlocks:o})}),g;d({jsx:(0,j.jsx)(M,{input:r,progress:null,verbose:u.options.verbose}),shouldHidePromptInput:!1});try{let n={...u,setToolJSX:e=>{g=e?.jsx}},o=e=>{d({jsx:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(M,{input:r,progress:e.data,verbose:u.options.verbose}),g]}),shouldHidePromptInput:!1,showSpinner:!1})},c=null;f&&(c=(t(),e(s)).PowerShellTool);let v=c??_,y=(c?await c.call({command:r,dangerouslyDisableSandbox:!0},n,void 0,void 0,o):await _.call({command:r,dangerouslyDisableSandbox:!0},n,void 0,void 0,o)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await p(v,{...y,stderr:``},A()),S=typeof x.content==`string`?x.content:m(y.stdout);return{messages:[a(),h,...l,i({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${m(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof x?e.interrupted?{messages:[a(),h,c({toolUse:!1}),...l],shouldQuery:!1}:{messages:[a(),h,...l,i({content:`<bash-stdout>${m(e.stdout)}</bash-stdout><bash-stderr>${m(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[a(),h,...l,i({content:`<bash-stderr>Command failed: ${m(C(e))}</bash-stderr>`})],shouldQuery:!1}}finally{d(null)}}export{P as processBashCommand};
@@ -0,0 +1,5 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{ct as t,ot as n}from"./esm-BQY8jJNR.js";import{$d as r,$h as i,$o as a,AS as o,Ah as s,B as c,Bs as l,Ci as u,Cx as d,Dd as f,E as p,Ea as m,Ed as h,Ei as g,FS as _,GS as v,HS as y,Ii as b,KS as x,Lm as S,Ni as C,Og as w,Oh as T,Oi as E,Pg as D,Pi as O,Qd as k,Ql as A,RS as j,Rs as M,Sx as N,US as ee,V as te,VS as ne,Vs as re,Xl as ie,Zi as ae,Zl as oe,au as se,b as ce,bp as le,cd as ue,dc as de,dv as fe,ef as pe,es as me,fS as he,fa as ge,fc as _e,fv as P,iu as F,kg as I,ld as ve,mS as L,ng as ye,ns as be,od as xe,pS as R,qS as Se,sd as z,tu as Ce,ud as we,xx as Te,yp as Ee,zS as De,zm as Oe}from"./loadAgentsDir-C1LkW7gl.js";import{Ln as ke,t as Ae,ut as je,zt as Me}from"./state-BowF111d.js";import{E as Ne,L as Pe,c as B,f as Fe,i as V,k as H,u as Ie}from"./debug-8DCufdSp.js";import{Dt as Le,Et as Re}from"./settings-DKN4xSpQ.js";import{D as U,O as W,o as G,q as ze,s as K}from"./log-DaILwWJa.js";import{n as Be,r as q}from"./analytics-DJobLaWP.js";import{Ht as Ve,Sr as He,Vt as Ue,xr as We}from"./model-BwBE0Pt5.js";import{E as Ge,T as Ke,w as qe}from"./sessionTracing-yBre24PH.js";import{randomUUID as J}from"crypto";function Je(e,t,n,r,i){let a=0;for(let o of Le){let s=n[o];if(s)for(let n of s)for(let s of n.hooks){let c=s.once?()=>{B(`Removing one-shot hook for event ${o} in skill '${r}'`),we(e,t,o,s)}:void 0;ue(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Ye=e((()=>{Re(),V(),ve()}));function Xe(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.slice(1).split(` `);if(!n[0])return null;let r=n[0],i=!1,a=1;n.length>1&&n[1]===`(MCP)`&&(r=`${r} (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Ze=e((()=>{}));function Qe(){return!1}function $e(){if(!Qe())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,n,a,o,s,c){let l=h(),u=e.pluginInfo?L(e.pluginInfo.repository).marketplace:void 0;q(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...u&&{_PROTO_marketplace_name:u},...A(e.pluginInfo)}});let{skillContent:d,modifiedGetAppState:f,baseAgent:p,promptMessages:m}=await re(e,t,n);B(`Executing forked slash command /${e.name} with agent ${p.agentType}`);let g=n.options.allowBackgroundForkedSlashCommands===!0;if(g&&$e(),g){let t=fe(),i=b(e),a=We(),o=e=>I({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:a}),u=async()=>{if(!c?.runId)return;let e=await k({runId:c.runId,rootDir:c.rootDir,priority:`later`,workload:a});for(let t of e)w(t)},d=async e=>{c?.runId&&await r({runId:c.runId,rootDir:c.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let r=Date.now()+$;for(;Date.now()<r&&n.getAppState().mcp.clients.some(e=>e.type===`pending`);)await Ve(Q);let a=n.options.refreshTools?.()??n.options.tools,c=[];for await(let r of z({agentDefinition:p,promptMessages:m,toolUseContext:{...n,getAppState:f,abortController:t},canUseTool:s,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:a,override:{agentId:l}}))c.push(r);let d=M(c,`Command completed`);B(`Background forked command /${i} completed (agent ${l})`),o(`<scheduled-task-result command="/${i}">\n${d}\n</scheduled-task-result>`);try{await u()}catch(e){K(e)}})().catch(async e=>{K(e),o(`<scheduled-task-result command="/${i}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await d(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!c?.runId}}let _=[],x=[],S=`forked-command-${e.name}`,C=0,T=e=>(C++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:d,agentId:l},parentToolUseID:S,toolUseID:`${S}-${C}`,timestamp:new Date().toISOString(),uuid:J()}),E=()=>{o({jsx:se(x,{tools:n.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};E();try{for await(let t of z({agentDefinition:p,promptMessages:m,toolUseContext:{...n,getAppState:f},canUseTool:s,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:n.options.tools})){_.push(t);let e=ge([t]);if(t.type===`assistant`){let r=i(t);r>0&&n.setResponseLength(e=>e+r);let a=e[0];a&&a.type===`assistant`&&(x.push(T(t)),E())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(x.push(T(t)),E())}}}finally{o(null)}let D=M(_,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${l}`),{messages:[y({content:v({inputString:`/${b(e)} ${t}`.trim(),precedingInputBlocks:a})}),y({content:`<local-command-stdout>\n${D}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:D}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,r,i,a,s,c,l,d){let f=Xe(e);if(!f){q(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[j(),...r,y({content:v({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:p,args:h,isMcp:g}=f,_=g?`mcp`:u().has(p)?p:`custom`;if(!C(p,i.options.commands)){let n=!1;try{await Ie().stat(`/${p}`),n=!0}catch{}if(tt(p)&&!n){q(`tengu_input_slash_invalid`,{input:p});let e=`Unknown skill: ${p}`;return{messages:[j(),...r,y({content:v({inputString:e,precedingInputBlocks:t})}),...h?[De(`Args from unknown skill: ${h}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let i=J();return ke(i),q(`tengu_input_prompt`,{}),Ke(`user_prompt`,{prompt_length:String(e.length),prompt:Ge(e),"prompt.id":i}),{messages:[y({content:v({inputString:e,precedingInputBlocks:t}),uuid:s}),...r],shouldQuery:!0}}let{messages:b,shouldQuery:x,allowedTools:S,model:w,command:T,resultText:E,nextInput:D,submitNextInput:O,deferAutonomyCompletion:k}=await rt(p,h,a,i,t,n,c,l,s,d);if(b.length===0){let e={input:_};if(T.type===`prompt`&&T.pluginInfo){let{pluginManifest:t,repository:n}=T.pluginInfo,{marketplace:r}=L(n),i=R(r);e._PROTO_plugin_name=t.name,r&&(e._PROTO_marketplace_name=r),e.plugin_repository=i?n:`third-party`,e.plugin_name=i?t.name:`third-party`,i&&t.version&&(e.plugin_version=t.version),Object.assign(e,A(T.pluginInfo))}return q(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:w,nextInput:D,submitNextInput:O,deferAutonomyCompletion:k}}if(b.length===2&&b[1].type===`user`&&typeof b[1].message.content==`string`&&b[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||q(`tengu_input_slash_invalid`,{input:p}),{messages:[j(),...b],shouldQuery:x,allowedTools:S,model:w};let M={input:_};if(T.type===`prompt`&&T.pluginInfo){let{pluginManifest:e,repository:t}=T.pluginInfo,{marketplace:n}=L(t),r=R(n);M._PROTO_plugin_name=e.name,n&&(M._PROTO_marketplace_name=n),M.plugin_repository=r?t:`third-party`,M.plugin_name=r?e.name:`third-party`,r&&e.version&&(M.plugin_version=e.version),Object.assign(M,A(T.pluginInfo))}q(`tengu_input_command`,{...M,invocation_trigger:`user-slash`});let N=b.length>0&&b[0]&&o(b[0]);return{messages:x||b.every(m)||N?b:[j(),...b],shouldQuery:x,allowedTools:S,model:w,resultText:E,nextInput:D,submitNextInput:O,deferAutonomyCompletion:k}}async function rt(e,t,n,r,i,a,o,l,u,d){let f=E(e,r.options.commands);if(f.type===`prompt`&&f.userInvocable!==!1&&oe(e),f.userInvocable===!1)return{messages:[y({content:v({inputString:`/${e}`,precedingInputBlocks:i})}),y({content:`This skill can only be invoked by Work Mate, not directly by users. Ask Work Mate to use the "${e}" skill for you.`})],shouldQuery:!1,command:f};try{switch(f.type){case`local-jsx`:return new Promise(e=>{let a=!1,o=(n,r)=>{if(a=!0,r?.display===`skip`){e({messages:[],shouldQuery:!1,command:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>y({content:e,isMeta:!0})),s=le()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[_(Y(f,c)),_(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[y({content:v({inputString:Y(f,c),precedingInputBlocks:i})}),y(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${x}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};f.load().then(e=>e.call(o,{...r,canUseTool:l},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:f});return}a||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:f.immediate===!0})}}).catch(t=>{K(t),!a&&(a=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:f}))})});case`local`:{let e=y({content:v({inputString:Y(f,f.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:i})});try{let n=j(),i=await(await f.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:f};if(i.type===`compact`){let t=[n,e,...i.displayText?[y({content:`<local-command-stdout>${i.displayText}</local-command-stdout>`,timestamp:new Date(Date.now()+100).toISOString()})]:[]],r={...i.compactionResult,messagesToKeep:[...i.compactionResult.messagesToKeep??[],...t]};return s(),{messages:S(r),shouldQuery:!1,command:f}}return{messages:[e,_(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:f,resultText:i.value}}catch(t){return K(t),{messages:[e,_(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:f}}}case`prompt`:try{return f.context===`fork`?await et(f,t,r,i,n,l??c,d):await Z(f,t,r,i,a,u)}catch(e){return e instanceof Ne?{messages:[y({content:v({inputString:Y(f,t),precedingInputBlocks:i})}),ne({toolUse:!1})],shouldQuery:!1,command:f}:{messages:[y({content:v({inputString:Y(f,t),precedingInputBlocks:i})}),y({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:f}}}}catch(e){if(e instanceof H)return{messages:[y({content:v({inputString:e.message,precedingInputBlocks:i})})],shouldQuery:!1,command:f};throw e}}function Y(e,t){return ee(b(e),t)}function X(e,t=`loading`){return[`<${U}>${e}</${U}>`,`<${W}>${e}</${W}>`,`<skill-format>true</skill-format>`].join(`
2
+ `)}function it(e,t){return[`<${U}>${e}</${U}>`,`<${W}>/${e}</${W}>`,t?`<command-args>${t}</command-args>`:null].filter(Boolean).join(`
3
+ `)}function at(e,t){return e.userInvocable===!1&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`mcp`)?X(e.name,e.progressMessage):it(e.name,t)}async function ot(e,t,n,r,i=[]){let a=g(e,n);if(!a)throw new H(`Unknown command: ${e}`);if(a.type!==`prompt`)throw Error(`Unexpected ${a.type} command. Expected 'prompt' command. Use /${e} directly in the main conversation.`);return Z(a,t,r,[],i)}async function Z(e,t,r,i=[],o=[],s){let c=await e.getPromptForCommand(t,r),l=!N(`hooks`)||d(e.source);if(e.hooks&&l){let t=je();Je(r.setAppState,t,e.hooks,e.name,e.type===`prompt`?e.skillRoot:void 0)}let u=e.source?`${e.source}:${e.name}`:e.name,f=c.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
+
5
+ `);Ae(e.name,u,f,n()?.agentId??null);let m=at(e,t),h=p(e.allowedTools??[]),g=o.length>0||i.length>0?[...o,...i,...c]:c,_=await _e(me(c.filter(e=>e.type===`text`).map(e=>e.text).join(` `),r,null,[],r.messages,`repl_main_thread`,{skipSkillDiscovery:!0}));return{messages:[y({content:m,uuid:s}),y({content:g,isMeta:!0}),..._,a({type:`command_permissions`,allowedTools:h,model:e.model})],shouldQuery:!0,allowedTools:h,model:e.model,command:e}}var Q,$;e((()=>{Me(),O(),Se(),ze(),Be(),Oe(),T(),xe(),F(),P(),t(),be(),V(),Pe(),l(),Fe(),Ee(),de(),Ye(),G(),D(),ae(),ce(),te(),he(),Te(),Ze(),Ue(),ie(),qe(),Ce(),ye(),f(),pe(),He(),Q=200,$=1e4}))();export{X as formatSkillLoadingMetadata,ot as processPromptSlashCommand,nt as processSlashCommand};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{n as r,t as i}from"./cwd-BcO6WHKo.js";import{f as a,u as o}from"./debug-8DCufdSp.js";import{An as s,Mn as c}from"./settings-DKN4xSpQ.js";import{_ as l,m as u,o as d}from"./config-BddEvZZl.js";import{join as f}from"path";function p(){let e=o().existsSync(f(i(),`AGENTS.md`)),t=c(i());return[{key:`workspace`,text:`Ask Work Mate to create a new app or clone a repository`,isComplete:!1,isCompletable:!0,isEnabled:t},{key:`agentsmd`,text:`Run /init to create a AGENTS.md file with instructions for Work Mate`,isComplete:e,isCompletable:!0,isEnabled:!t}]}function m(){return p().filter(({isCompletable:e,isEnabled:t})=>e&&t).every(({isComplete:e})=>e)}function h(){d().hasCompletedProjectOnboarding||m()&&l(e=>({...e,hasCompletedProjectOnboarding:!0}))}function g(){l(e=>({...e,projectOnboardingSeenCount:e.projectOnboardingSeenCount+1}))}var _,v=e((()=>{n(),u(),r(),s(),a(),_=t(()=>{let e=d();return e.hasCompletedProjectOnboarding||e.projectOnboardingSeenCount>=4||process.env.IS_DEMO?!1:!m()})}));export{_ as a,h as i,g as n,v as r,p as t};
@@ -1,4 +1,4 @@
1
- import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-DcaKZlRU.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{D as l,E as u,F as d,N as f,n as p,r as m,t as h}from"./lazySchema-DULtBUCI.js";import{C as g,R as _,j as v,x as y}from"./debug-D58GQBDG.js";import{G as b,K as x,U as S,W as C,Z as w,q as T}from"./settings-3xZ0fsvE.js";import{H as E,q as D}from"./log-CZ7ploQm.js";import{i as O,o as k}from"./platform-DMQxcm4K.js";import{_ as A,u as j}from"./model-Do0f476p.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e,t){return{tool_use_id:e,type:`tool_result`,content:t}}function oe(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function se(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function ce(e,t){return e.find(e=>se(e,t))}function le(e){return{...de,userFacingName:()=>e.name,...e}}var ue,de,fe=t((()=>{ue=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),de={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),pe,me,he,ge,_e=t((()=>{pe=`Edit`,me=`/.workmate/**`,he=`~/.workmate/**`,ge=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function ve(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ye(){return!j().toLowerCase().includes(`claude-3-haiku`)}function be(e){let t=e.startsWith(`.`)?e.slice(1):e;return xe.has(t.toLowerCase())}var xe,Se=t((()=>{A(),xe=new Set([`pdf`])})),R,Ce=t((()=>{R=`Bash`}));function we(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
1
+ import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-DcaKZlRU.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{$ as l,G as u,W as d,Z as f,o as p,s as m,x as h}from"./types-zk5Ltv5q.js";import{C as g,L as _,j as v,x as y}from"./debug-8DCufdSp.js";import{G as b,K as x,U as S,W as C,Z as w,q as T}from"./settings-DKN4xSpQ.js";import{H as E,q as D}from"./log-DaILwWJa.js";import{i as O,o as k}from"./platform-Dzff1WWw.js";import{f as A,s as j}from"./model-BwBE0Pt5.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e,t){return{tool_use_id:e,type:`tool_result`,content:t}}function oe(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function se(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function ce(e,t){return e.find(e=>se(e,t))}function le(e){return{...de,userFacingName:()=>e.name,...e}}var ue,de,fe=t((()=>{ue=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),de={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),pe,me,he,ge,_e=t((()=>{pe=`Edit`,me=`/.workmate/**`,he=`~/.workmate/**`,ge=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function ve(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ye(){return!j().toLowerCase().includes(`claude-3-haiku`)}function be(e){let t=e.startsWith(`.`)?e.slice(1):e;return xe.has(t.toLowerCase())}var xe,Se=t((()=>{A(),xe=new Set([`pdf`])})),R,Ce=t((()=>{R=`Bash`}));function we(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
2
2
  Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
3
3
 
4
4
  Usage:
@@ -67,7 +67,7 @@ Usage:
67
67
  - This tool will overwrite the existing file if there is one at the provided path.${An()}
68
68
  - Prefer the Edit tool for modifying existing files \u2014 it only sends the diff. Only use this tool to create new files or for complete rewrites.
69
69
  - NEVER create documentation files (*.md) or README files unless explicitly requested by the User.
70
- - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`}var Mn,Nn=t((()=>{je(),Mn=`Write`})),Pn,Fn=t((()=>{Pn=`NotebookEdit`})),In,Ln=t((()=>{In=`TaskGet`})),Rn,zn=t((()=>{Rn=`TaskList`})),Bn,Vn=t((()=>{Bn=`SearchExtraTools`}));function Hn(e){return e.isNonInteractiveSession}function Un(e){let t=Yn.get(e);if(t)return t;let n=Wn(e);return Yn.set(e,n),n}function Wn(e){try{let t=new Gn.Ajv({allErrors:!0});if(!t.validateSchema(e))return{error:t.errorsText(t.errors)};let n=t.compile(e);return{tool:{...Jn,inputJSONSchema:e,async call(e){if(!n(e)){let e=n.errors?.map(e=>`${e.instancePath||`root`}: ${e.message}`).join(`, `);throw new v(`Output does not match required schema: ${e}`,`StructuredOutput schema mismatch: ${(e??``).slice(0,150)}`)}return{data:`Structured output provided successfully`,structured_output:e}}}}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}var Gn,Kn,qn,K,Jn,Yn,Xn=t((()=>{Gn=n(fn(),1),m(),fe(),_(),h(),y(),Kn=p(()=>l({}).passthrough()),qn=p(()=>f().describe(`Structured output tool result`)),K=`StructuredOutput`,Jn=le({isMcp:!1,isEnabled(){return!0},isConcurrencySafe(){return!0},isReadOnly(){return!0},isOpenWorld(){return!1},name:K,searchHint:`return the final response as structured JSON`,maxResultSizeChars:1e5,async description(){return`Return structured output in the requested format`},async prompt(){return`Use this tool to return your final response in the requested structured format. You MUST call this tool exactly once at the end of your response to provide the structured output.`},get inputSchema(){return Kn()},get outputSchema(){return qn()},async call(e){return{data:`Structured output provided successfully`,structured_output:e}},async checkPermissions(e){return{behavior:`allow`,updatedInput:e}},renderToolUseMessage(e){let t=Object.keys(e);return t.length===0?null:t.length<=3?t.map(t=>`${t}: ${g(e[t])}`).join(`, `):`${t.length} fields: ${t.slice(0,3).join(`, `)}…`},renderToolUseRejectedMessage(){return`Structured output rejected`},renderToolUseErrorMessage(){return`Structured output error`},renderToolUseProgressMessage(){return null},renderToolResultMessage(e){return e},mapToolResultToToolResultBlockParam(e,t){return{tool_use_id:t,type:`tool_result`,content:e}}}),Yn=new WeakMap})),Zn,Qn,$n,er=t((()=>{D(),Zn=`Sleep`,Qn=`Wait for a specified duration`,$n=`Wait for a specified duration. The user can interrupt the sleep at any time.
70
+ - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`}var Mn,Nn=t((()=>{je(),Mn=`Write`})),Pn,Fn=t((()=>{Pn=`NotebookEdit`})),In,Ln=t((()=>{In=`TaskGet`})),Rn,zn=t((()=>{Rn=`TaskList`})),Bn,Vn=t((()=>{Bn=`SearchExtraTools`}));function Hn(e){return e.isNonInteractiveSession}function Un(e){let t=Yn.get(e);if(t)return t;let n=Wn(e);return Yn.set(e,n),n}function Wn(e){try{let t=new Gn.Ajv({allErrors:!0});if(!t.validateSchema(e))return{error:t.errorsText(t.errors)};let n=t.compile(e);return{tool:{...Jn,inputJSONSchema:e,async call(e){if(!n(e)){let e=n.errors?.map(e=>`${e.instancePath||`root`}: ${e.message}`).join(`, `);throw new v(`Output does not match required schema: ${e}`,`StructuredOutput schema mismatch: ${(e??``).slice(0,150)}`)}return{data:`Structured output provided successfully`,structured_output:e}}}}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}var Gn,Kn,qn,K,Jn,Yn,Xn=t((()=>{Gn=n(fn(),1),h(),fe(),_(),p(),y(),Kn=m(()=>u({}).passthrough()),qn=m(()=>f().describe(`Structured output tool result`)),K=`StructuredOutput`,Jn=le({isMcp:!1,isEnabled(){return!0},isConcurrencySafe(){return!0},isReadOnly(){return!0},isOpenWorld(){return!1},name:K,searchHint:`return the final response as structured JSON`,maxResultSizeChars:1e5,async description(){return`Return structured output in the requested format`},async prompt(){return`Use this tool to return your final response in the requested structured format. You MUST call this tool exactly once at the end of your response to provide the structured output.`},get inputSchema(){return Kn()},get outputSchema(){return qn()},async call(e){return{data:`Structured output provided successfully`,structured_output:e}},async checkPermissions(e){return{behavior:`allow`,updatedInput:e}},renderToolUseMessage(e){let t=Object.keys(e);return t.length===0?null:t.length<=3?t.map(t=>`${t}: ${g(e[t])}`).join(`, `):`${t.length} fields: ${t.slice(0,3).join(`, `)}…`},renderToolUseRejectedMessage(){return`Structured output rejected`},renderToolUseErrorMessage(){return`Structured output error`},renderToolUseProgressMessage(){return null},renderToolResultMessage(e){return e},mapToolResultToToolResultBlockParam(e,t){return{tool_use_id:t,type:`tool_result`,content:e}}}),Yn=new WeakMap})),Zn,Qn,$n,er=t((()=>{D(),Zn=`Sleep`,Qn=`Wait for a specified duration`,$n=`Wait for a specified duration. The user can interrupt the sleep at any time.
71
71
 
72
72
  Use this when the user tells you to sleep or rest, when you have nothing to do, or when you're waiting for something.
73
73
 
@@ -97,7 +97,7 @@ All operations require:
97
97
 
98
98
  Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.`})),rr,ir=t((()=>{rr=`VerifyPlanExecution`})),ar,or=t((()=>{ar=`ExecuteExtraTool`})),sr,cr=t((()=>{sr=`EnterWorktree`})),lr,ur=t((()=>{lr=`ExitWorktree`})),dr=t((()=>{})),q,J,fr,pr,mr,hr,Y=t((()=>{q=`Workflow`,J=`.workmate/workflows`,fr=`.workmate/workflow-runs`,pr=[`.ts`,`.js`,`.mjs`],mr=1e3,hr=4096}));function gr(e){return{[vr]:e}}function _r(e){return e[vr]}var vr,yr=t((()=>{vr=Symbol(`workflow.hostHandle`)}));function br(e,t){return e.kind===`agentType`?t.agentType===e.agentType:e.kind===`model`?typeof t.model==`string`&&t.model.startsWith(e.pattern):e.match(t)}var xr,Sr,Cr=t((()=>{s(),xr=class extends Error{constructor(e){super(e),this.name=`AdapterNotFoundError`}},Sr=class{constructor(){c(this,`adapters`,new Map),c(this,`rules`,[]),c(this,`defaultId`,null)}register(e){return this.adapters.set(e.id,e),this}default(e){return this.defaultId=e,this}route(e){return this.rules.push(e),this}has(e){return this.adapters.has(e)}get(e){return this.adapters.get(e)}resolve(e){for(let t of this.rules)if(br(t,e)){let e=this.adapters.get(t.adapter);if(e)return e}if(this.defaultId){let e=this.adapters.get(this.defaultId);if(e)return e}throw new xr(`No adapter matched (rules=${this.rules.length}, default=${this.defaultId??`none`})`)}async initializeAll(){for(let e of this.adapters.values())await e.initialize?.()}async disposeAll(){for(let e of this.adapters.values())await e.dispose?.()}}}));function wr(e){return e===void 0||Number.isNaN(e)?3:Math.max(1,Math.min(Math.trunc(e),16))}var Tr,Er=t((()=>{Y(),s(),Tr=class{constructor(e){c(this,`available`,void 0),c(this,`waiters`,[]),this.available=Math.max(1,Math.floor(e))}async acquire(e){if(e?.aborted)throw Error(`Semaphore.acquire aborted (signal already aborted)`);return this.available>0?(--this.available,()=>this.release()):new Promise((t,n)=>{let r=()=>{let e=this.waiters.indexOf(i);e>=0&&this.waiters.splice(e,1),n(Error(`Semaphore.acquire aborted`))},i={wake:()=>{e?.removeEventListener(`abort`,r),t(()=>this.release())},cleanup:()=>e?.removeEventListener(`abort`,r)};e?.addEventListener(`abort`,r,{once:!0}),this.waiters.push(i)})}release(){let e=this.waiters.shift();e?e.wake():this.available+=1}}}));function Dr(e){let t=Nr.exec(e);if(!t)return{meta:null,body:e};let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`{`)throw new X("meta must be an object literal `{ ... }`");let r=0,i=n,a=null;for(;n<e.length;n++){let t=e[n];if(a){if(t===`\\`){n++;continue}t===a&&(a=null);continue}if(t===`"`||t===`'`||t==="`"){a=t;continue}if(t===`{`)r++;else if(t===`}`&&(r--,r===0)){n++;break}}if(r!==0)throw new X(`meta literal braces are not closed`);let o=e.slice(i,n),s;try{s=Function(`return (${o})`)()}catch(e){throw new X(`meta must be a plain literal (no variable/function calls/interpolation): ${e.message}`)}return{meta:Or(s),body:e.slice(0,t.index)+e.slice(n).replace(/^[ \t]*;[ \t]*\n/,`
99
99
  `)}}function Or(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new X(`meta must be an object`);let t=e;if(typeof t.name!=`string`||typeof t.description!=`string`)throw new X(`meta must include string name and description`);return t}function kr(){function e(...e){if(e.length===0)throw new Z(`Date.now()/new Date()`);return new Date(...e)}let t=e;return t.now=()=>{throw new Z(`Date.now()`)},t.parse=Date.parse,t.UTC=Date.UTC,t}function Ar(){return new Proxy(Math,{get(e,t,n){return t===`random`?()=>{throw new Z(`Math.random()`)}:Reflect.get(e,t,n)}})}function jr(e){if(/^\s*import\b/m.test(e))throw new X(`workflow scripts are the body of new AsyncFunction (not ESM modules); import is not supported. agent / parallel / pipeline / phase / log / workflow / args / budget are injected as parameters — use them directly.`);if(/\bimport\s*\(/m.test(e))throw new X(`dynamic import(...) is forbidden in workflow scripts: it bypasses the Date/Math sandbox and breaks resume determinism. The sandbox does not guarantee security (same trust level as the LLM), but explicit escapes are prohibited. Inject external dependencies via args.`);if(/^\s*export\b/m.test(e))throw new X(`workflow scripts allow only one export const meta = {...} (already extracted by the engine). Remove other export / export default statements; use top-level return for the result.`)}function Mr(e){let{meta:t,body:n}=Dr(e);jr(n);let r;try{r=new Pr(`agent`,`parallel`,`pipeline`,`phase`,`log`,`workflow`,`args`,`budget`,`Date`,`Math`,n)}catch(e){throw new X(`Script syntax error: ${e.message}`)}let i=kr(),a=Ar();return{meta:t,async execute(e,t,n){return r(e.agent,e.parallel,e.pipeline,e.phase,e.log,e.workflow,t,n,i,a)}}}var X,Nr,Z,Pr,Fr=t((()=>{X=class extends Error{constructor(e){super(e),this.name=`ScriptError`}},Nr=/export\s+const\s+meta\s*=\s*/,Z=class extends Error{constructor(e){super(`${e} is not available in workflow scripts (would break resume determinism). Pass timestamps/random seeds via args.`),this.name=`NonDeterministicError`}},Pr=Object.getPrototypeOf(async()=>{}).constructor}));function Ir(e){let{label:t,phase:n,...r}=e,i=Object.keys(r).sort(),a={};for(let e of i)a[e]=r[e];return JSON.stringify(a)}function Lr(e,t){return F(`sha256`).update(`${e}\n${Ir(t)}`).digest(`hex`)}function Rr(e){let t=t=>M(e,t,`journal.jsonl`);return{async read(e){try{return(await L(t(e),`utf-8`)).split(`
100
- `).filter(e=>e.trim().length>0).map(e=>JSON.parse(e)).sort((e,t)=>(e.seq??0)-(t.seq??0))}catch{return[]}},async append(n,r){await te(M(e,n),{recursive:!0}),await I(t(n),`${JSON.stringify(r)}\n`,`utf-8`)},async truncate(t){await re(M(e,t),{recursive:!0,force:!0})}}}var zr=t((()=>{})),Br,Vr,Hr=t((()=>{s(),Br=class extends Error{constructor(){super(`workflow token budget exhausted (budget.total reached the cap)`),this.name=`BudgetExhaustedError`}},Vr=class{constructor(e){c(this,`total`,void 0),c(this,`spentTokens`,0),this.total=e}spent(){return this.spentTokens}remaining(){return this.total==null?1/0:Math.max(0,this.total-this.spentTokens)}addOutputTokens(e){e>0&&(this.spentTokens+=e)}assertCanSpend(){if(this.total!=null&&this.spentTokens>=this.total)throw new Br}}})),Ur=t((()=>{}));function Wr(e,t){let n=P(e),r=P(n,t);return r===n||r.startsWith(n+ee)}function Gr(e){return typeof e!=`string`||e.length===0||e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e===`.`||e===`..`?null:e}var Kr=t((()=>{}));function qr(e){return pr.includes(e.toLowerCase())}async function Jr(e,t){for(let n of pr){let r=P(e,t+n);if(!Wr(e,r))return null;try{return{path:r,content:await L(r,`utf-8`)}}catch{}}return null}async function Yr(e){let t;try{t=await ne(e)}catch{return[]}return t.filter(e=>qr(N(e).ext)).map(e=>N(e).name).sort()}var Xr=t((()=>{Y(),Kr()})),Q,$,Zr=t((()=>{Q=class extends Error{constructor(e){super(e),this.name=`WorkflowError`}},$=class extends Error{constructor(){super(`workflow has been aborted`),this.name=`WorkflowAbortedError`}}}));function Qr(e,t){return{semaphore:new Tr(wr(t)),budget:new Vr(e),agentCountBox:{value:0},agentIdSeq:{value:0},depth:0}}function $r(e){let t=Qr(e.budgetTotal,e.maxConcurrency);return{ports:e.ports,host:e.host,signal:e.signal,runId:e.runId,workflowName:e.workflowName,cwd:e.cwd,resources:t,journal:e.journal?[...e.journal]:[],journalIndex:0,journalInvalidated:!1,currentPhase:null}}var ei=t((()=>{Hr(),Er()}));function ti(e,t){let n=t=>{e.ports.progressEmitter.emit({runId:e.runId,...t})};return{agent:async(t,r={})=>{let i=e.resources;if(i.agentCountBox.value>=1e3)throw new Q(`workflow exceeds total agent cap (${mr})`);let a=i.agentIdSeq.value++,o={prompt:t,...r},s=Lr(t,o),c=r.label,l=r.phase??e.currentPhase??void 0;if(!e.journalInvalidated&&e.journalIndex<e.journal.length){let t=e.journal[e.journalIndex];if(t.key===s)return e.journalIndex++,n({type:`agent_done`,agentId:a,label:c,phase:l,result:t.result}),ni(t.result);e.journalInvalidated=!0,e.journal=e.journal.slice(0,e.journalIndex),await e.ports.journalStore.truncate(e.runId)}let u;try{u=await e.resources.semaphore.acquire(e.signal)}catch{throw new $}try{if(e.signal.aborted)throw new $;if(i.budget.assertCanSpend(),e.ports.taskRegistrar.pendingAction(e.runId)?.kind===`skip`)return n({type:`agent_done`,agentId:a,label:c,phase:l,result:{kind:`skipped`}}),null;e.resources.agentCountBox.value++,n({type:`agent_started`,agentId:a,label:c,phase:l});let t=e.ports.agentAdapterRegistry,r=t?{host:e.host,signal:e.signal,runId:e.runId,agentId:a,onProgress:e=>{n({type:`agent_progress`,agentId:a,label:c,phase:l,...e})},...e.ports.taskRegistrar.registerAgentAbort?{registerAgentAbort:(t,n)=>{e.ports.taskRegistrar.registerAgentAbort?.(e.runId,t,n)}}:{},...e.ports.taskRegistrar.unregisterAgentAbort?{unregisterAgentAbort:t=>{e.ports.taskRegistrar.unregisterAgentAbort?.(e.runId,t)}}:{}}:null,u=t?t.resolve(o):null,d=()=>u?u.run(o,r):e.ports.agentRunner.runAgentToResult(o,e.host),f;try{if(f=await d(),f.kind===`dead`){let t=typeof f.detail==`string`?f.detail:``;e.ports.logger.warn?.(`agent "${c??`#${a}`}" returned dead`+(f.reason?` (${f.reason})`:``)+(t?`: ${t.slice(0,150)}`:``)+`; retrying once`),f=await d()}}catch(t){if(t instanceof $)throw t;let n=t instanceof Error?t.message:String(t);e.ports.logger.warn?.(`agent "${c??`#${a}`}" threw (${n}); retrying once`);try{f=await d()}catch(e){if(e instanceof $)throw e;f={kind:`dead`,reason:`runagent-threw`,detail:e instanceof Error?e.message:String(e)}}}f.kind===`ok`&&e.resources.budget.addOutputTokens(f.usage.outputTokens),n({type:`agent_done`,agentId:a,label:c,phase:l,result:f});let p={key:s,seq:a,result:f};return e.journal.push(p),e.journalIndex++,await e.ports.journalStore.append(e.runId,p),ni(f)}finally{u()}},parallel:async t=>{if(t.length>4096)throw new Q(`parallel exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,n)=>{try{return await t()}catch(t){return e.ports.logger.warn?.(`parallel thunk #${n} failed: ${t.message}`),null}}))},pipeline:async(t,...n)=>{if(t.length>4096)throw new Q(`pipeline exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,r)=>{try{let e=t;for(let i of n)e=await i(e,t,r);return e}catch(t){return e.ports.logger.warn?.(`pipeline item #${r} failed: ${t.message}`),null}}))},phase:t=>{e.currentPhase&&n({type:`phase_done`,phase:e.currentPhase}),e.currentPhase=t,n({type:`phase_started`,phase:t})},log:e=>{n({type:`log`,message:e})},workflow:async(n,r)=>{if(e.resources.depth>=1)throw new Q(`workflow() nesting allows only one level`);return t({...typeof n==`string`?{name:n}:{scriptPath:n.scriptPath},args:r})}}}function ni(e){return e.kind===`ok`?e.output:null}var ri=t((()=>{Y(),Zr(),zr()}));async function ii(e){let{ports:t}=e,n;try{n=Mr(e.script)}catch(n){let r=n.message;return t.progressEmitter.emit({type:`run_done`,runId:e.runId,status:`failed`,error:r}),{status:`failed`,error:r}}let r=e.workflowName??n.meta?.name??`workflow`,i=[],a=!1;e.resume&&!e.scriptChanged?i=await t.journalStore.read(e.runId):e.scriptChanged&&(await t.journalStore.truncate(e.runId),a=!0);let o=$r({ports:t,host:e.host,signal:e.signal,runId:e.runId,workflowName:r,cwd:e.cwd,budgetTotal:e.budgetTotal,maxConcurrency:e.maxConcurrency,journal:i});a&&(o.journalInvalidated=!0),t.progressEmitter.emit({type:`run_started`,runId:e.runId,workflowName:r,meta:n.meta});let s=async t=>{let n=await ai(t,e.cwd),r;try{r=Mr(n)}catch(e){throw new Q(`Sub-workflow script error: ${e.message}`)}let i=o.resources.depth;o.resources.depth+=1;try{let e=ti(o,s);return await r.execute(e,t.args,o.resources.budget)}finally{o.resources.depth=i}},c=ti(o,s),l=()=>{o.currentPhase&&t.progressEmitter.emit({type:`phase_done`,runId:e.runId,phase:o.currentPhase})},u;try{u={status:`completed`,returnValue:await n.execute(c,e.args,o.resources.budget)}}catch(e){u=e instanceof $?{status:`killed`}:{status:`failed`,error:e.message}}return l(),t.progressEmitter.emit({type:`run_done`,runId:e.runId,...u}),u}async function ai(e,t){if(e.script)return e.script;if(e.scriptPath)return await L(e.scriptPath,`utf-8`);if(e.name){let n=await Jr(M(t,J),e.name);if(!n)throw new Q(`Sub-workflow "${e.name}" not found`);return n.content}throw new Q(`workflow() requires name or scriptPath`)}var oi=t((()=>{Y(),ei(),Zr(),ri(),Xr(),Fr()})),si=t((()=>{})),ci,li=t((()=>{m(),ci=l({script:f().optional().describe(`Self-contained workflow script source (inline)`),name:f().optional().describe(`Named workflow, resolved to .workmate/workflows/<name>.ts|js|mjs`),scriptPath:f().optional().describe(`Absolute path to an existing script file`),args:d().optional().describe(`The args global variable passed through to the script. Pass a real JSON value (object/array/string), not a JSON string.`),resumeFromRunId:f().optional().describe(`Resume the specified run, replaying the journal`),description:f().optional().describe(`A short description of this invocation (3-5 words)`),title:f().optional().describe(`Progress viewer title`),maxConcurrency:u().int().min(1).max(16).optional().describe(`Concurrency cap for agent(). Defaults to 3 (max 16). When the workflow contains heavy parallel/pipeline fan-out, you may confirm the desired concurrency with the user via AskUserQuestion before launching.`)})}));async function ui(e,t,n){let r=M(n,fr,t);await te(r,{recursive:!0});let i=M(r,`script.js`);return await ie(i,e,`utf-8`),i}var di=t((()=>{Y()}));function fi(e){return{name:q,inputSchema:ci,isEnabled:()=>!0,isReadOnly:()=>!1,async description(){return`Execute a workflow script that orchestrates multiple subagents to complete a task`},async prompt(){return _i},renderToolUseMessage(e){return e.resumeFromRunId?`Workflow resume: ${e.resumeFromRunId}`:`Workflow: ${e.name??e.scriptPath??(e.script?`inline`:`unknown`)}`},async call(t,n,r,i){let a=e.hostFactory({context:n,canUseTool:r,parentMessage:i}),o,s;try{let e=await gi(t,a.cwd);o=e.script,s=e.workflowFile}catch(e){return{data:{output:`Error: ${e.message}`}}}try{Mr(o)}catch(e){return{data:{output:`Error: script validation failed: ${e.message}`}}}let c=t.name??t.title??`workflow`,{runId:l,signal:u}=e.taskRegistrar.register({workflowName:c,...s?{workflowFile:s}:{},...t.description?{summary:t.description}:{},...a.toolUseId?{toolUseId:a.toolUseId}:{},...t.resumeFromRunId?{runId:t.resumeFromRunId}:{}},a.handle);if(!s&&t.script)try{s=await ui(t.script,l,a.cwd)}catch(t){e.logger.warn?.(`inline script persist failed: ${t.message}`)}ii({script:o,...t.args===void 0?{}:{args:hi(t.args)},runId:l,workflowName:c,ports:e,host:a.handle,signal:u,cwd:a.cwd,budgetTotal:a.budgetTotal,...t.maxConcurrency===void 0?{}:{maxConcurrency:t.maxConcurrency},...t.resumeFromRunId?{resume:!0}:{}}).then(t=>pi(e,t,l)).catch(t=>e.taskRegistrar.fail(l,t.message));let d=s??`<inline run ${l}>`;return{data:{output:[`Workflow started (running in the background).`,`run_id: ${l}`,`workflow: ${c}`,`script: ${d}`,``,`You will be notified on completion. Use /workflows to view live progress.`].join(`
100
+ `).filter(e=>e.trim().length>0).map(e=>JSON.parse(e)).sort((e,t)=>(e.seq??0)-(t.seq??0))}catch{return[]}},async append(n,r){await te(M(e,n),{recursive:!0}),await I(t(n),`${JSON.stringify(r)}\n`,`utf-8`)},async truncate(t){await re(M(e,t),{recursive:!0,force:!0})}}}var zr=t((()=>{})),Br,Vr,Hr=t((()=>{s(),Br=class extends Error{constructor(){super(`workflow token budget exhausted (budget.total reached the cap)`),this.name=`BudgetExhaustedError`}},Vr=class{constructor(e){c(this,`total`,void 0),c(this,`spentTokens`,0),this.total=e}spent(){return this.spentTokens}remaining(){return this.total==null?1/0:Math.max(0,this.total-this.spentTokens)}addOutputTokens(e){e>0&&(this.spentTokens+=e)}assertCanSpend(){if(this.total!=null&&this.spentTokens>=this.total)throw new Br}}})),Ur=t((()=>{}));function Wr(e,t){let n=P(e),r=P(n,t);return r===n||r.startsWith(n+ee)}function Gr(e){return typeof e!=`string`||e.length===0||e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e===`.`||e===`..`?null:e}var Kr=t((()=>{}));function qr(e){return pr.includes(e.toLowerCase())}async function Jr(e,t){for(let n of pr){let r=P(e,t+n);if(!Wr(e,r))return null;try{return{path:r,content:await L(r,`utf-8`)}}catch{}}return null}async function Yr(e){let t;try{t=await ne(e)}catch{return[]}return t.filter(e=>qr(N(e).ext)).map(e=>N(e).name).sort()}var Xr=t((()=>{Y(),Kr()})),Q,$,Zr=t((()=>{Q=class extends Error{constructor(e){super(e),this.name=`WorkflowError`}},$=class extends Error{constructor(){super(`workflow has been aborted`),this.name=`WorkflowAbortedError`}}}));function Qr(e,t){return{semaphore:new Tr(wr(t)),budget:new Vr(e),agentCountBox:{value:0},agentIdSeq:{value:0},depth:0}}function $r(e){let t=Qr(e.budgetTotal,e.maxConcurrency);return{ports:e.ports,host:e.host,signal:e.signal,runId:e.runId,workflowName:e.workflowName,cwd:e.cwd,resources:t,journal:e.journal?[...e.journal]:[],journalIndex:0,journalInvalidated:!1,currentPhase:null}}var ei=t((()=>{Hr(),Er()}));function ti(e,t){let n=t=>{e.ports.progressEmitter.emit({runId:e.runId,...t})};return{agent:async(t,r={})=>{let i=e.resources;if(i.agentCountBox.value>=1e3)throw new Q(`workflow exceeds total agent cap (${mr})`);let a=i.agentIdSeq.value++,o={prompt:t,...r},s=Lr(t,o),c=r.label,l=r.phase??e.currentPhase??void 0;if(!e.journalInvalidated&&e.journalIndex<e.journal.length){let t=e.journal[e.journalIndex];if(t.key===s)return e.journalIndex++,n({type:`agent_done`,agentId:a,label:c,phase:l,result:t.result}),ni(t.result);e.journalInvalidated=!0,e.journal=e.journal.slice(0,e.journalIndex),await e.ports.journalStore.truncate(e.runId)}let u;try{u=await e.resources.semaphore.acquire(e.signal)}catch{throw new $}try{if(e.signal.aborted)throw new $;if(i.budget.assertCanSpend(),e.ports.taskRegistrar.pendingAction(e.runId)?.kind===`skip`)return n({type:`agent_done`,agentId:a,label:c,phase:l,result:{kind:`skipped`}}),null;e.resources.agentCountBox.value++,n({type:`agent_started`,agentId:a,label:c,phase:l});let t=e.ports.agentAdapterRegistry,r=t?{host:e.host,signal:e.signal,runId:e.runId,agentId:a,onProgress:e=>{n({type:`agent_progress`,agentId:a,label:c,phase:l,...e})},...e.ports.taskRegistrar.registerAgentAbort?{registerAgentAbort:(t,n)=>{e.ports.taskRegistrar.registerAgentAbort?.(e.runId,t,n)}}:{},...e.ports.taskRegistrar.unregisterAgentAbort?{unregisterAgentAbort:t=>{e.ports.taskRegistrar.unregisterAgentAbort?.(e.runId,t)}}:{}}:null,u=t?t.resolve(o):null,d=()=>u?u.run(o,r):e.ports.agentRunner.runAgentToResult(o,e.host),f;try{if(f=await d(),f.kind===`dead`){let t=typeof f.detail==`string`?f.detail:``;e.ports.logger.warn?.(`agent "${c??`#${a}`}" returned dead`+(f.reason?` (${f.reason})`:``)+(t?`: ${t.slice(0,150)}`:``)+`; retrying once`),f=await d()}}catch(t){if(t instanceof $)throw t;let n=t instanceof Error?t.message:String(t);e.ports.logger.warn?.(`agent "${c??`#${a}`}" threw (${n}); retrying once`);try{f=await d()}catch(e){if(e instanceof $)throw e;f={kind:`dead`,reason:`runagent-threw`,detail:e instanceof Error?e.message:String(e)}}}f.kind===`ok`&&e.resources.budget.addOutputTokens(f.usage.outputTokens),n({type:`agent_done`,agentId:a,label:c,phase:l,result:f});let p={key:s,seq:a,result:f};return e.journal.push(p),e.journalIndex++,await e.ports.journalStore.append(e.runId,p),ni(f)}finally{u()}},parallel:async t=>{if(t.length>4096)throw new Q(`parallel exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,n)=>{try{return await t()}catch(t){return e.ports.logger.warn?.(`parallel thunk #${n} failed: ${t.message}`),null}}))},pipeline:async(t,...n)=>{if(t.length>4096)throw new Q(`pipeline exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,r)=>{try{let e=t;for(let i of n)e=await i(e,t,r);return e}catch(t){return e.ports.logger.warn?.(`pipeline item #${r} failed: ${t.message}`),null}}))},phase:t=>{e.currentPhase&&n({type:`phase_done`,phase:e.currentPhase}),e.currentPhase=t,n({type:`phase_started`,phase:t})},log:e=>{n({type:`log`,message:e})},workflow:async(n,r)=>{if(e.resources.depth>=1)throw new Q(`workflow() nesting allows only one level`);return t({...typeof n==`string`?{name:n}:{scriptPath:n.scriptPath},args:r})}}}function ni(e){return e.kind===`ok`?e.output:null}var ri=t((()=>{Y(),Zr(),zr()}));async function ii(e){let{ports:t}=e,n;try{n=Mr(e.script)}catch(n){let r=n.message;return t.progressEmitter.emit({type:`run_done`,runId:e.runId,status:`failed`,error:r}),{status:`failed`,error:r}}let r=e.workflowName??n.meta?.name??`workflow`,i=[],a=!1;e.resume&&!e.scriptChanged?i=await t.journalStore.read(e.runId):e.scriptChanged&&(await t.journalStore.truncate(e.runId),a=!0);let o=$r({ports:t,host:e.host,signal:e.signal,runId:e.runId,workflowName:r,cwd:e.cwd,budgetTotal:e.budgetTotal,maxConcurrency:e.maxConcurrency,journal:i});a&&(o.journalInvalidated=!0),t.progressEmitter.emit({type:`run_started`,runId:e.runId,workflowName:r,meta:n.meta});let s=async t=>{let n=await ai(t,e.cwd),r;try{r=Mr(n)}catch(e){throw new Q(`Sub-workflow script error: ${e.message}`)}let i=o.resources.depth;o.resources.depth+=1;try{let e=ti(o,s);return await r.execute(e,t.args,o.resources.budget)}finally{o.resources.depth=i}},c=ti(o,s),l=()=>{o.currentPhase&&t.progressEmitter.emit({type:`phase_done`,runId:e.runId,phase:o.currentPhase})},u;try{u={status:`completed`,returnValue:await n.execute(c,e.args,o.resources.budget)}}catch(e){u=e instanceof $?{status:`killed`}:{status:`failed`,error:e.message}}return l(),t.progressEmitter.emit({type:`run_done`,runId:e.runId,...u}),u}async function ai(e,t){if(e.script)return e.script;if(e.scriptPath)return await L(e.scriptPath,`utf-8`);if(e.name){let n=await Jr(M(t,J),e.name);if(!n)throw new Q(`Sub-workflow "${e.name}" not found`);return n.content}throw new Q(`workflow() requires name or scriptPath`)}var oi=t((()=>{Y(),ei(),Zr(),ri(),Xr(),Fr()})),si=t((()=>{})),ci,li=t((()=>{h(),ci=u({script:f().optional().describe(`Self-contained workflow script source (inline)`),name:f().optional().describe(`Named workflow, resolved to .workmate/workflows/<name>.ts|js|mjs`),scriptPath:f().optional().describe(`Absolute path to an existing script file`),args:l().optional().describe(`The args global variable passed through to the script. Pass a real JSON value (object/array/string), not a JSON string.`),resumeFromRunId:f().optional().describe(`Resume the specified run, replaying the journal`),description:f().optional().describe(`A short description of this invocation (3-5 words)`),title:f().optional().describe(`Progress viewer title`),maxConcurrency:d().int().min(1).max(16).optional().describe(`Concurrency cap for agent(). Defaults to 3 (max 16). When the workflow contains heavy parallel/pipeline fan-out, you may confirm the desired concurrency with the user via AskUserQuestion before launching.`)})}));async function ui(e,t,n){let r=M(n,fr,t);await te(r,{recursive:!0});let i=M(r,`script.js`);return await ie(i,e,`utf-8`),i}var di=t((()=>{Y()}));function fi(e){return{name:q,inputSchema:ci,isEnabled:()=>!0,isReadOnly:()=>!1,async description(){return`Execute a workflow script that orchestrates multiple subagents to complete a task`},async prompt(){return _i},renderToolUseMessage(e){return e.resumeFromRunId?`Workflow resume: ${e.resumeFromRunId}`:`Workflow: ${e.name??e.scriptPath??(e.script?`inline`:`unknown`)}`},async call(t,n,r,i){let a=e.hostFactory({context:n,canUseTool:r,parentMessage:i}),o,s;try{let e=await gi(t,a.cwd);o=e.script,s=e.workflowFile}catch(e){return{data:{output:`Error: ${e.message}`}}}try{Mr(o)}catch(e){return{data:{output:`Error: script validation failed: ${e.message}`}}}let c=t.name??t.title??`workflow`,{runId:l,signal:u}=e.taskRegistrar.register({workflowName:c,...s?{workflowFile:s}:{},...t.description?{summary:t.description}:{},...a.toolUseId?{toolUseId:a.toolUseId}:{},...t.resumeFromRunId?{runId:t.resumeFromRunId}:{}},a.handle);if(!s&&t.script)try{s=await ui(t.script,l,a.cwd)}catch(t){e.logger.warn?.(`inline script persist failed: ${t.message}`)}ii({script:o,...t.args===void 0?{}:{args:hi(t.args)},runId:l,workflowName:c,ports:e,host:a.handle,signal:u,cwd:a.cwd,budgetTotal:a.budgetTotal,...t.maxConcurrency===void 0?{}:{maxConcurrency:t.maxConcurrency},...t.resumeFromRunId?{resume:!0}:{}}).then(t=>pi(e,t,l)).catch(t=>e.taskRegistrar.fail(l,t.message));let d=s??`<inline run ${l}>`;return{data:{output:[`Workflow started (running in the background).`,`run_id: ${l}`,`workflow: ${c}`,`script: ${d}`,``,`You will be notified on completion. Use /workflows to view live progress.`].join(`
101
101
  `)}}},mapToolResultToToolResultBlockParam(e,t){return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:e.output}]}}}}function pi(e,t,n){if(t.status===`completed`){let r=t.returnValue==null?`(no return value)`:mi(t.returnValue);e.taskRegistrar.complete(n,r)}else t.status===`failed`?e.taskRegistrar.fail(n,t.error??`workflow failed`):e.taskRegistrar.kill(n)}function mi(e){if(typeof e==`string`)return e.slice(0,500);try{return JSON.stringify(e).slice(0,500)}catch{return String(e)}}function hi(e){if(typeof e!=`string`)return e;try{let t=JSON.parse(e);return typeof t==`object`&&t?t:e}catch{return e}}async function gi(e,t){if(e.script)return{script:e.script};if(e.scriptPath){let n=P(t,e.scriptPath);if(!Wr(t,n))throw Error(`scriptPath "${e.scriptPath}" is out of bounds (after resolve, ${n} is not within cwd ${t})`);return{script:await L(n,`utf-8`),workflowFile:n}}if(e.name){if(Gr(e.name)===null)throw Error(`Named workflow name "${e.name}" is invalid (contains path separators or is . / ..)`);let n=await Jr(M(t,J),e.name);if(!n)throw Error(`Named workflow "${e.name}" not found (looked in ${J}/)`);return{script:n.content,workflowFile:n.path}}throw Error(`One of script, name, or scriptPath must be provided`)}var _i,vi=t((()=>{Y(),Xr(),oi(),Fr(),Kr(),li(),di(),_i='Use the Workflow tool to execute a workflow script that orchestrates multiple subagents deterministically. The script runs in the background; you receive a run_id immediately and are notified on completion.\n\nProvide the script inline via "script", or reference a named workflow via "name" (resolved from .workmate/workflows/), or an existing file via "scriptPath". Pass "args" as a real JSON value (object/array/string), not a stringified string.\n\nUse "resumeFromRunId" to resume a prior run — completed agent() calls replay from the journal instantly.\n\nConcurrency: default is 3 (hard ceiling 16). OMIT maxConcurrency to use 3. To set maxConcurrency to ANY value other than 3, you MUST first ask the user via AskUserQuestion — propose 3 / 6 / 9 (or other tiers matching the fan-out width) with 3 marked "(Recommended)". The ONLY exception: the user has ALREADY specified a concurrency number in this session ("use 6", "maxConcurrency 9") — then honor it without re-asking. Never silently raise concurrency above 3 just because the workflow fans out; 3 is the recommended default.\n\nScript execution model (common pitfalls — getting these wrong is the #1 cause of script errors): the script is the body of `new AsyncFunction` — NOT an ESM module, and TypeScript is NOT transpiled. Therefore:\n- Do NOT use `import` — `agent`, `parallel`, `pipeline`, `phase`, `log`, `workflow`, `args`, and `budget` are injected as parameters; reference them directly.\n- Do NOT use TS type annotations, `interface`, `enum`, `as`, or generics — the engine does not transpile, so even a .ts file with type syntax fails to parse.\n- Keep EXACTLY ONE `export const meta = {...}` (plain literal) and remove every other `export` / `export default`.\n- Return the result with a top-level `return`.\nPrefer .js / .mjs. See /ultracode for the full playbook and quality patterns.'})),yi=t((()=>{dr(),Y(),yr(),Cr(),Er(),Fr(),zr(),Hr(),Ur(),Xr(),Zr(),ei(),ri(),oi(),si(),vi(),li(),di()})),bi,xi,Si,Ci,wi,Ti,Ei=t((()=>{bi=`LocalMemoryRecall`,xi=100*1024,Si=2*1024,Ci=50*1024,wi=4*1024,Ti=8*1024})),Di,Oi,ki,Ai,ji=t((()=>{x(),Me(),mn(),w(),yn(),C(),je(),Pe(),xn(),wn(),kn(),_e(),Nn(),Fn(),Be(),Ie(),Ln(),zn(),Re(),Vn(),Xn(),er(),nr(),ir(),or(),cr(),ur(),yi(),Ei(),Di=new Set([b,B,pn,T,hn,S,q,bi]),Oi=new Set([...Di]),ki=new Set([z,Ne,G,Sn,...On,pe,Mn,Pn,ze,K,Bn,ar,sr,lr]),Ai=new Set([...On,z,pe,Mn,Sn,G,Pn,T,hn,b,S,Fe,In,Rn,Le,Ne,pn,B,rr,`LSP`,ze,q,Zn,Bn,ar,K])}));function Mi(){return`Deferred tools appear by name in <available-deferred-tools> messages.`}function Ni(e){return!(e.alwaysLoad===!0||Ai.has(e.name))}function Pi(e){return e.name}function Fi(){return Ii+Mi()+Li}var Ii,Li,Ri=t((()=>{ji(),Vn(),Ii=`Search for deferred tools by name or keyword. LOW PRIORITY — only use this tool when no core tool can accomplish the task. Core tools (Read, Edit, Write, Bash, Glob, Grep, Agent, WebFetch, WebSearch, Skill) are always available and should be used directly. This tool is for discovering additional capabilities like MCP tools, worktree management, agent teams (TeamCreate, TeamDelete, SendMessage), etc.
102
102
 
103
103
  `,Li=` Returns matching tool names.
@@ -0,0 +1 @@
1
+ import{Vx as e,qx as t}from"./loadAgentsDir-C1LkW7gl.js";t();export{e as clearPromptCache};
@@ -0,0 +1 @@
1
+ import{i as e,r as t}from"./prompt-BGqgPgCU.js";t();export{e as isDeferredTool};
@@ -0,0 +1,4 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{R_ as r,U_ as i}from"./loadAgentsDir-C1LkW7gl.js";import{Rn as a,t as o}from"./src-DL3w8VPk.js";import{T as s,c,f as l,i as u,u as d,x as f}from"./debug-8DCufdSp.js";import{_ as p,b as m,x as h,y as g}from"./stringUtils-BQm3OfeJ.js";import{i as _,n as v,o as y,s as b}from"./history-CNQNd6hT.js";import{n as x,t as S}from"./tempfile-CHO5wXsV.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!g(e)}function D(e){let t=C(e.split(` `)[0]??``);return A.find(e=>t.includes(e))}function O(e,t,n){return n?M.has(e)?[`-g`,`${t}:${n}`]:e===`subl`?[`${t}:${n}`]:[t]:[t]}function k(e,t){let n=N();if(!n)return!1;let r=n.split(` `),i=r[0]??n,o=r.slice(1),s=D(n);if(s){let r=O(s,e,t),a={detached:!0,stdio:`ignore`},l;return l=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...a,shell:!0}):w(i,[...o,...r],a),l.on(`error`,e=>c(`editor spawn failed: ${e}`,{level:`error`})),l.unref(),!0}let l=a.get(process.stdout);if(!l)return!1;let u=t&&j.test(C(i));l.enterAlternateScreen();try{let r={stdio:`inherit`},a;return a=process.platform===`win32`?T(`${n} ${u?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...o,...u?[`+${t}`,e]:[e]],r),a.error?(c(`editor spawn failed: ${a.error}`,{level:`error`}),!1):!0}finally{l.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),o(),u(),p(),A=[`code`,`cursor`,`windsurf`,`codium`,`subl`,`atom`,`gedit`,`notepad++`,`notepad`],j=/\b(vi|vim|nvim|nano|emacs|pico|micro|helix|hx)\b/,M=new Set([`code`,`cursor`,`windsurf`,`codium`]),N=t(()=>process.env.VISUAL?.trim()?process.env.VISUAL.trim():process.env.EDITOR?.trim()?process.env.EDITOR.trim():process.platform===`win32`?`start /wait notepad`:[`code`,`vi`,`nano`].find(e=>E(e)))}));function F(e){return D(e)!==void 0}function I(e){let t=d(),n=a.get(process.stdout);if(!n)throw Error(`Ink instance not found - cannot pause rendering`);let r=N();if(!r)return{content:null};try{t.statSync(e)}catch{return{content:null}}let o=!F(r);o?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return m(`${z[r]??r} "${e}"`,{stdio:`inherit`}),{content:t.readFileSync(e,{encoding:`utf-8`})}}catch(e){if(typeof e==`object`&&e&&`status`in e&&typeof e.status==`number`){let t=e.status;if(t!==0)return{content:null,error:`${i(r)} exited with code ${t}`}}return{content:null}}finally{o?n.exitAlternateScreen():(n.resumeStdin(),n.resume())}}function L(e,t,n){let r=e;for(let[e,t]of Object.entries(n))if(t.type===`text`){let n=parseInt(e,10),i=t.content,a=r.indexOf(i);if(a!==-1){let e=_(n,y(i));r=r.slice(0,a)+e+r.slice(a+i.length)}}return r}function R(e,t){let n=d(),r=S();try{s(r,t?v(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(r);if(n.content===null)return n;let i=n.content;return i.endsWith(`
2
+ `)&&!i.endsWith(`
3
+
4
+ `)&&(i=i.slice(0,-1)),t&&(i=L(i,e,t)),{content:i}}finally{try{n.unlinkSync(r)}catch{}}}var z,B=e((()=>{b(),o(),P(),h(),l(),r(),f(),x(),z={code:`code -w`,subl:`subl --wait`}}));export{P as a,N as i,R as n,k as o,B as r,I as t};
@@ -1,4 +1,4 @@
1
- import{C as e,c as t,i as n,x as r}from"./debug-D58GQBDG.js";import{c as i,h as a}from"./config-DRy1I12M.js";import{r as o,t as s}from"./execFileNoThrow-Bmb5HEFz.js";import{n as c,t as l}from"./which-BxQ1hpjp.js";import{n as u,t as d}from"./githubRepoPathMapping-CzgPGOHQ.js";import{n as f}from"./banner-BkUdig-T.js";import{r as p}from"./registerProtocol-C0IlPEoa.js";import{homedir as m}from"os";import{basename as h}from"path";import{spawn as g}from"child_process";r(),a(),n(),o(),l();var _=[{name:`iTerm2`,bundleId:`com.googlecode.iterm2`,app:`iTerm`},{name:`Ghostty`,bundleId:`com.mitchellh.ghostty`,app:`Ghostty`},{name:`Kitty`,bundleId:`net.kovidgoyal.kitty`,app:`kitty`},{name:`Alacritty`,bundleId:`org.alacritty`,app:`Alacritty`},{name:`WezTerm`,bundleId:`com.github.wez.wezterm`,app:`WezTerm`},{name:`Terminal.app`,bundleId:`com.apple.Terminal`,app:`Terminal`}],v=[`ghostty`,`kitty`,`alacritty`,`wezterm`,`gnome-terminal`,`konsole`,`xfce4-terminal`,`mate-terminal`,`tilix`,`xterm`];async function y(){let e=i().deepLinkTerminal;if(e){let t=_.find(t=>t.app===e);if(t)return{name:t.name,command:t.app}}let t=process.env.TERM_PROGRAM;if(t){let e=t.replace(/\.app$/i,``).toLowerCase(),n=_.find(t=>t.app.toLowerCase()===e||t.name.toLowerCase()===e);if(n)return{name:n.name,command:n.app}}for(let e of _){let{code:t,stdout:n}=await s(`mdfind`,[`kMDItemCFBundleIdentifier == "${e.bundleId}"`],{timeout:5e3,useCwd:!1});if(t===0&&n.trim().length>0)return{name:e.name,command:e.app}}for(let e of _){let{code:t}=await s(`ls`,[`/Applications/${e.app}.app`],{timeout:1e3,useCwd:!1});if(t===0)return{name:e.name,command:e.app}}return{name:`Terminal.app`,command:`Terminal`}}async function b(){let e=process.env.TERMINAL;if(e){let t=await c(e);if(t)return{name:h(e),command:t}}let t=await c(`x-terminal-emulator`);if(t)return{name:`x-terminal-emulator`,command:t};for(let e of v){let t=await c(e);if(t)return{name:e,command:t}}return null}async function x(){let e=await c(`wt.exe`);if(e)return{name:`Windows Terminal`,command:e};let t=await c(`pwsh.exe`);if(t)return{name:`PowerShell`,command:t};let n=await c(`powershell.exe`);return n?{name:`PowerShell`,command:n}:{name:`Command Prompt`,command:`cmd.exe`}}async function S(){switch(process.platform){case`darwin`:return y();case`linux`:return b();case`win32`:return x();default:return null}}async function C(e,n){let r=await S();if(!r)return t(`No terminal emulator detected`,{level:`error`}),!1;t(`Launching in terminal: ${r.name} (${r.command})`);let i=[`--deep-link-origin`];switch(n.repo&&(i.push(`--deep-link-repo`,n.repo),n.lastFetchMs!==void 0&&i.push(`--deep-link-last-fetch`,String(n.lastFetchMs))),n.query&&i.push(`--prefill`,n.query),process.platform){case`darwin`:return w(r,e,i,n.cwd);case`linux`:return T(r,e,i,n.cwd);case`win32`:return E(r,e,i,n.cwd);default:return!1}}async function w(e,n,r,i){switch(e.command){case`iTerm`:{let{code:e}=await s(`osascript`,[`-e`,`tell application "iTerm"
1
+ import{C as e,c as t,i as n,x as r}from"./debug-8DCufdSp.js";import{c as i,m as a}from"./config-BddEvZZl.js";import{i as o,t as s}from"./execFileNoThrow-BsfuytkN.js";import{_ as c,v as l}from"./stringUtils-BQm3OfeJ.js";import{i as u,n as d,r as f}from"./banner-mqZEluky.js";import{r as p}from"./registerProtocol-CLIpzVwF.js";import{homedir as m}from"os";import{basename as h}from"path";import{spawn as g}from"child_process";r(),a(),n(),o(),c();var _=[{name:`iTerm2`,bundleId:`com.googlecode.iterm2`,app:`iTerm`},{name:`Ghostty`,bundleId:`com.mitchellh.ghostty`,app:`Ghostty`},{name:`Kitty`,bundleId:`net.kovidgoyal.kitty`,app:`kitty`},{name:`Alacritty`,bundleId:`org.alacritty`,app:`Alacritty`},{name:`WezTerm`,bundleId:`com.github.wez.wezterm`,app:`WezTerm`},{name:`Terminal.app`,bundleId:`com.apple.Terminal`,app:`Terminal`}],v=[`ghostty`,`kitty`,`alacritty`,`wezterm`,`gnome-terminal`,`konsole`,`xfce4-terminal`,`mate-terminal`,`tilix`,`xterm`];async function y(){let e=i().deepLinkTerminal;if(e){let t=_.find(t=>t.app===e);if(t)return{name:t.name,command:t.app}}let t=process.env.TERM_PROGRAM;if(t){let e=t.replace(/\.app$/i,``).toLowerCase(),n=_.find(t=>t.app.toLowerCase()===e||t.name.toLowerCase()===e);if(n)return{name:n.name,command:n.app}}for(let e of _){let{code:t,stdout:n}=await s(`mdfind`,[`kMDItemCFBundleIdentifier == "${e.bundleId}"`],{timeout:5e3,useCwd:!1});if(t===0&&n.trim().length>0)return{name:e.name,command:e.app}}for(let e of _){let{code:t}=await s(`ls`,[`/Applications/${e.app}.app`],{timeout:1e3,useCwd:!1});if(t===0)return{name:e.name,command:e.app}}return{name:`Terminal.app`,command:`Terminal`}}async function b(){let e=process.env.TERMINAL;if(e){let t=await l(e);if(t)return{name:h(e),command:t}}let t=await l(`x-terminal-emulator`);if(t)return{name:`x-terminal-emulator`,command:t};for(let e of v){let t=await l(e);if(t)return{name:e,command:t}}return null}async function x(){let e=await l(`wt.exe`);if(e)return{name:`Windows Terminal`,command:e};let t=await l(`pwsh.exe`);if(t)return{name:`PowerShell`,command:t};let n=await l(`powershell.exe`);return n?{name:`PowerShell`,command:n}:{name:`Command Prompt`,command:`cmd.exe`}}async function S(){switch(process.platform){case`darwin`:return y();case`linux`:return b();case`win32`:return x();default:return null}}async function C(e,n){let r=await S();if(!r)return t(`No terminal emulator detected`,{level:`error`}),!1;t(`Launching in terminal: ${r.name} (${r.command})`);let i=[`--deep-link-origin`];switch(n.repo&&(i.push(`--deep-link-repo`,n.repo),n.lastFetchMs!==void 0&&i.push(`--deep-link-last-fetch`,String(n.lastFetchMs))),n.query&&i.push(`--prefill`,n.query),process.platform){case`darwin`:return w(r,e,i,n.cwd);case`linux`:return T(r,e,i,n.cwd);case`win32`:return E(r,e,i,n.cwd);default:return!1}}async function w(e,n,r,i){switch(e.command){case`iTerm`:{let{code:e}=await s(`osascript`,[`-e`,`tell application "iTerm"
2
2
  if running then
3
3
  create window with default profile
4
4
  else
@@ -10,4 +10,4 @@ import{C as e,c as t,i as n,x as r}from"./debug-D58GQBDG.js";import{c as i,h as
10
10
  end tell`],{useCwd:!1});if(e===0)return!0;break}case`Terminal`:{let{code:e}=await s(`osascript`,[`-e`,`tell application "Terminal"
11
11
  do script ${A(O(n,r,i))}
12
12
  activate
13
- end tell`],{useCwd:!1});return e===0}case`Ghostty`:{let t=[`-na`,e.command,`--args`,`--window-save-state=never`];i&&t.push(`--working-directory=${i}`),t.push(`-e`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`Alacritty`:{let t=[`-na`,e.command,`--args`];i&&t.push(`--working-directory`,i),t.push(`-e`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`kitty`:{let t=[`-na`,e.command,`--args`];i&&t.push(`--directory`,i),t.push(n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`WezTerm`:{let t=[`-na`,e.command,`--args`,`start`];i&&t.push(`--cwd`,i),t.push(`--`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}}return t(`Failed to launch ${e.name}, falling back to Terminal.app`),w({name:`Terminal.app`,command:`Terminal`},n,r,i)}async function T(e,t,n,r){let i,a;switch(e.name){case`gnome-terminal`:i=r?[`--working-directory=${r}`,`--`]:[`--`],i.push(t,...n);break;case`konsole`:i=r?[`--workdir`,r,`-e`]:[`-e`],i.push(t,...n);break;case`kitty`:i=r?[`--directory`,r]:[],i.push(t,...n);break;case`wezterm`:i=r?[`start`,`--cwd`,r,`--`]:[`start`,`--`],i.push(t,...n);break;case`alacritty`:i=r?[`--working-directory`,r,`-e`]:[`-e`],i.push(t,...n);break;case`ghostty`:i=r?[`--working-directory=${r}`,`-e`]:[`-e`],i.push(t,...n);break;case`xfce4-terminal`:case`mate-terminal`:i=r?[`--working-directory=${r}`,`-x`]:[`-x`],i.push(t,...n);break;case`tilix`:i=r?[`--working-directory=${r}`,`-e`]:[`-e`],i.push(t,...n);break;default:i=[`-e`,t,...n],a=r;break}return D(e.command,i,{cwd:a})}async function E(e,t,n,r){let i=[];switch(e.name){case`Windows Terminal`:r&&i.push(`-d`,r),i.push(`--`,t,...n);break;case`PowerShell`:{let e=r?`Set-Location ${j(r)}; `:``;i.push(`-NoExit`,`-Command`,`${e}& ${j(t)} ${n.map(j).join(` `)}`);break}default:{let e=r?`cd /d ${M(r)} && `:``;i.push(`/k`,`${e}${M(t)} ${n.map(e=>M(e)).join(` `)}`);break}}return D(e.command,i,{windowsVerbatimArguments:e.name===`Command Prompt`})}function D(e,n,r={}){return new Promise(i=>{let a=g(e,n,{detached:!0,stdio:`ignore`,cwd:r.cwd,windowsVerbatimArguments:r.windowsVerbatimArguments});a.once(`error`,n=>{t(`Failed to spawn ${e}: ${n.message}`,{level:`error`}),i(!1)}),a.once(`spawn`,()=>{a.unref(),i(!0)})})}function O(e,t,n){return`${n?`cd ${k(n)} && `:``}${[e,...t].map(k).join(` `)}`}function k(e){return`'${e.replace(/'/g,`'\\''`)}'`}function A(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function j(e){return`'${e.replace(/'/g,`''`)}'`}function M(e){return`"${e.replace(/"/g,``).replace(/%/g,`%%`).replace(/(\\+)$/,`$1$1`)}"`}n();async function N(n){t(`Handling deep link URI: ${n}`);let r;try{r=p(n)}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`Deep link error: ${t}`),1}t(`Parsed deep link action: ${e(r)}`);let{cwd:i,resolvedRepo:a}=await F(r),o=a?await f(i):void 0;return await C(process.execPath,{query:r.query,cwd:i,repo:a,lastFetchMs:o?.getTime()})?0:(console.error(`Failed to open a terminal. Make sure a supported terminal emulator is installed.`),1)}async function P(){if(process.env.__CFBundleIdentifier!==`com.anthropic.claude-code-url-handler`)return null;try{let{waitForUrlEvent:e}=await import(`./urlHandler-DLz3FZm1.js`),t=await e(5e3);return t?await N(t):null}catch{return null}}async function F(e){if(e.cwd)return{cwd:e.cwd};if(e.repo){let n=await d(u(e.repo));if(n[0])return t(`Resolved repo ${e.repo} → ${n[0]}`),{cwd:n[0],resolvedRepo:e.repo};t(`No local clone found for repo ${e.repo}, falling back to home`)}return{cwd:m()}}export{N as handleDeepLinkUri,P as handleUrlSchemeLaunch};
13
+ end tell`],{useCwd:!1});return e===0}case`Ghostty`:{let t=[`-na`,e.command,`--args`,`--window-save-state=never`];i&&t.push(`--working-directory=${i}`),t.push(`-e`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`Alacritty`:{let t=[`-na`,e.command,`--args`];i&&t.push(`--working-directory`,i),t.push(`-e`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`kitty`:{let t=[`-na`,e.command,`--args`];i&&t.push(`--directory`,i),t.push(n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}case`WezTerm`:{let t=[`-na`,e.command,`--args`,`start`];i&&t.push(`--cwd`,i),t.push(`--`,n,...r);let{code:a}=await s(`open`,t,{useCwd:!1});if(a===0)return!0;break}}return t(`Failed to launch ${e.name}, falling back to Terminal.app`),w({name:`Terminal.app`,command:`Terminal`},n,r,i)}async function T(e,t,n,r){let i,a;switch(e.name){case`gnome-terminal`:i=r?[`--working-directory=${r}`,`--`]:[`--`],i.push(t,...n);break;case`konsole`:i=r?[`--workdir`,r,`-e`]:[`-e`],i.push(t,...n);break;case`kitty`:i=r?[`--directory`,r]:[],i.push(t,...n);break;case`wezterm`:i=r?[`start`,`--cwd`,r,`--`]:[`start`,`--`],i.push(t,...n);break;case`alacritty`:i=r?[`--working-directory`,r,`-e`]:[`-e`],i.push(t,...n);break;case`ghostty`:i=r?[`--working-directory=${r}`,`-e`]:[`-e`],i.push(t,...n);break;case`xfce4-terminal`:case`mate-terminal`:i=r?[`--working-directory=${r}`,`-x`]:[`-x`],i.push(t,...n);break;case`tilix`:i=r?[`--working-directory=${r}`,`-e`]:[`-e`],i.push(t,...n);break;default:i=[`-e`,t,...n],a=r;break}return D(e.command,i,{cwd:a})}async function E(e,t,n,r){let i=[];switch(e.name){case`Windows Terminal`:r&&i.push(`-d`,r),i.push(`--`,t,...n);break;case`PowerShell`:{let e=r?`Set-Location ${j(r)}; `:``;i.push(`-NoExit`,`-Command`,`${e}& ${j(t)} ${n.map(j).join(` `)}`);break}default:{let e=r?`cd /d ${M(r)} && `:``;i.push(`/k`,`${e}${M(t)} ${n.map(e=>M(e)).join(` `)}`);break}}return D(e.command,i,{windowsVerbatimArguments:e.name===`Command Prompt`})}function D(e,n,r={}){return new Promise(i=>{let a=g(e,n,{detached:!0,stdio:`ignore`,cwd:r.cwd,windowsVerbatimArguments:r.windowsVerbatimArguments});a.once(`error`,n=>{t(`Failed to spawn ${e}: ${n.message}`,{level:`error`}),i(!1)}),a.once(`spawn`,()=>{a.unref(),i(!0)})})}function O(e,t,n){return`${n?`cd ${k(n)} && `:``}${[e,...t].map(k).join(` `)}`}function k(e){return`'${e.replace(/'/g,`'\\''`)}'`}function A(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function j(e){return`'${e.replace(/'/g,`''`)}'`}function M(e){return`"${e.replace(/"/g,``).replace(/%/g,`%%`).replace(/(\\+)$/,`$1$1`)}"`}n();async function N(n){t(`Handling deep link URI: ${n}`);let r;try{r=p(n)}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`Deep link error: ${t}`),1}t(`Parsed deep link action: ${e(r)}`);let{cwd:i,resolvedRepo:a}=await F(r),o=a?await d(i):void 0;return await C(process.execPath,{query:r.query,cwd:i,repo:a,lastFetchMs:o?.getTime()})?0:(console.error(`Failed to open a terminal. Make sure a supported terminal emulator is installed.`),1)}async function P(){if(process.env.__CFBundleIdentifier!==`com.anthropic.claude-code-url-handler`)return null;try{let{waitForUrlEvent:e}=await import(`./urlHandler-DLz3FZm1.js`),t=await e(5e3);return t?await N(t):null}catch{return null}}async function F(e){if(e.cwd)return{cwd:e.cwd};if(e.repo){let n=await f(u(e.repo));if(n[0])return t(`Resolved repo ${e.repo} → ${n[0]}`),{cwd:n[0],resolvedRepo:e.repo};t(`No local clone found for repo ${e.repo}, falling back to home`)}return{cwd:m()}}export{N as handleDeepLinkUri,P as handleUrlSchemeLaunch};