@readmagic/workmate 0.0.19 → 0.0.20

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 (256) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-9FcHMKgX.js → AddWorkspaceDirectory-BYNvxNrD.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-BSSz86ER.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-DLnj3JQO.js → AgentsMdExternalIncludesDialog-CMEGV4Md.js} +1 -1
  4. package/dist/chunks/{App-NkBqbDbC.js → App-W_9d1DjK.js} +1 -1
  5. package/dist/chunks/{ApproveApiKey-rgB6AsYD.js → ApproveApiKey-Bf1Rb8Ql.js} +1 -1
  6. package/dist/chunks/ApproveApiKey-wpdvXpFr.js +1 -0
  7. package/dist/chunks/{BackgroundTasksDialog-CcViruUO.js → BackgroundTasksDialog-lGn1Wj1k.js} +1 -1
  8. package/dist/chunks/{BypassPermissionsModeDialog-D254L98G.js → BypassPermissionsModeDialog-CjVjyNf8.js} +1 -1
  9. package/dist/chunks/{DiffDialog-6Srcz3NW.js → DiffDialog-DCpchgp5.js} +1 -1
  10. package/dist/chunks/Doctor-6SjW91rd.js +1 -0
  11. package/dist/chunks/{Doctor-DiNxlXfC.js → Doctor-FPYTivHw.js} +1 -1
  12. package/dist/chunks/{ExitFlow-Bt2De110.js → ExitFlow-Dy8_1D8J.js} +1 -1
  13. package/dist/chunks/{Grove-DC4jyxeB.js → Grove-Dd6rjs5P.js} +1 -1
  14. package/dist/chunks/{HybridTransport-DArmWb1V.js → HybridTransport-CJVkWa2u.js} +1 -1
  15. package/dist/chunks/{InvalidConfigDialog-DFiB0Kzc.js → InvalidConfigDialog-Bisj9ic_.js} +1 -1
  16. package/dist/chunks/{InvalidSettingsDialog-BHNo2__T.js → InvalidSettingsDialog-DyTPNRQR.js} +1 -1
  17. package/dist/chunks/{MCPConnectionManager-CdpO2Tj9.js → MCPConnectionManager-DfyoZaiu.js} +1 -1
  18. package/dist/chunks/{MCPToolListView-Ch4jOk_x.js → MCPToolListView-Dioupv8F.js} +1 -1
  19. package/dist/chunks/{McpParsingWarnings-D4UQ8Q2e.js → McpParsingWarnings-BUlgpZAF.js} +1 -1
  20. package/dist/chunks/{MessageSelector-BgsrdJur.js → MessageSelector-D8fylxPg.js} +1 -1
  21. package/dist/chunks/{Messages-DB1pmDY_.js → Messages-BZDFMYBT.js} +1 -1
  22. package/dist/chunks/{Onboarding-BnjdTwci.js → Onboarding-BKLomZYo.js} +1 -1
  23. package/dist/chunks/{PromptInputFooterSuggestions-Chg9U-BC.js → PromptInputFooterSuggestions-DCum89fF.js} +1 -1
  24. package/dist/chunks/{PromptInputHelpMenu-C0ZSo12s.js → PromptInputHelpMenu-DG2lRqis.js} +1 -1
  25. package/dist/chunks/{QueryEngine-bKlupZpA.js → QueryEngine-CyGHpX7M.js} +1 -1
  26. package/dist/chunks/REPL-BDsz8KIx.js +1 -0
  27. package/dist/chunks/{REPL-Cg8UXYpX.js → REPL-CCBNfZfs.js} +5 -5
  28. package/dist/chunks/{RemoteSessionManager-CRWOHvKf.js → RemoteSessionManager-BfsOv4K6.js} +1 -1
  29. package/dist/chunks/{ResumeConversation-Ld7tYLKO.js → ResumeConversation-pC8NLq0F.js} +1 -1
  30. package/dist/chunks/{SSETransport-pPrlSZNF.js → SSETransport-B3K6eH9I.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-DYoxHo9T.js +1 -0
  32. package/dist/chunks/{Settings-CsOlPcIW.js → Settings-CKaGmKg2.js} +2 -2
  33. package/dist/chunks/{TeleportProgress-Di-PMey7.js → TeleportProgress-CkgSp1cs.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-CDv1cbo-.js → TeleportRepoMismatchDialog-DdO_rECq.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-Bmf13tGU.js → TeleportResumeWrapper-BeG4N-2z.js} +1 -1
  36. package/dist/chunks/{ThemePicker-B3AO3_jA.js → ThemePicker-iD9ufy99.js} +1 -1
  37. package/dist/chunks/{TrustDialog-C0aiR_LU.js → TrustDialog-qO5OdQt8.js} +1 -1
  38. package/dist/chunks/{add-dir-w1Ay3861.js → add-dir-C4eSVlZ6.js} +1 -1
  39. package/dist/chunks/{agentDisplay-D01ZlnVX.js → agentDisplay-BM4QG_RX.js} +1 -1
  40. package/dist/chunks/{agents-Bxenhf8S.js → agents-BbDBN5l9.js} +1 -1
  41. package/dist/chunks/{agents-B_hUgPnR.js → agents-D3APE_8d.js} +1 -1
  42. package/dist/chunks/{allErrors-C_iHQOlK.js → allErrors-BkgB7JNK.js} +1 -1
  43. package/dist/chunks/api-BHBK9axp.js +1 -0
  44. package/dist/chunks/{api-C5ULzZny.js → api-DyUWfg3a.js} +1 -1
  45. package/dist/chunks/{auth-DvcZHXGk.js → auth-0rn1U4Eq.js} +1 -1
  46. package/dist/chunks/auth-BEoTPSgC.js +1 -0
  47. package/dist/chunks/auth-BPug7U_u.js +1 -0
  48. package/dist/chunks/backgroundHousekeeping-D7xAhUaE.js +1 -0
  49. package/dist/chunks/{backgroundHousekeeping-BGKR5cdA.js → backgroundHousekeeping-km82qEh0.js} +2 -2
  50. package/dist/chunks/{branch-CqQxCSHG.js → branch-CQ38cx5n.js} +1 -1
  51. package/dist/chunks/{bridgeConfig-MxsnEEPx.js → bridgeConfig-C5L-7KaP.js} +1 -1
  52. package/dist/chunks/bridgeConfig-CJMjDoaP.js +1 -0
  53. package/dist/chunks/{bridgeMessaging-Bx5pkkkx.js → bridgeMessaging-DVC3qj-C.js} +1 -1
  54. package/dist/chunks/{bridgeStatusUtil-B9EcQksI.js → bridgeStatusUtil-Cex6VowM.js} +1 -1
  55. package/dist/chunks/{btw-DeznoRrw.js → btw-_P96ffHR.js} +1 -1
  56. package/dist/chunks/caches-DH-q8Fjf.js +1 -0
  57. package/dist/chunks/caches-Dq0pJFDP.js +1 -0
  58. package/dist/chunks/{ccrClient-CimQTd0b.js → ccrClient-DO563xlf.js} +1 -1
  59. package/dist/chunks/{clear-KvoD-lFN.js → clear-DmqQBNKg.js} +1 -1
  60. package/dist/chunks/client-C19cqYQS.js +1 -0
  61. package/dist/chunks/commands-BkpqHY9F.js +1 -0
  62. package/dist/chunks/{compact-Dgzve3dI.js → compact-DuVIvqMu.js} +1 -1
  63. package/dist/chunks/config-DMP6-Ccr.js +1 -0
  64. package/dist/chunks/{context-Dz-bbYCw.js → context-DjgMzIfe.js} +1 -1
  65. package/dist/chunks/{context-noninteractive-ApbVPU86.js → context-noninteractive-BzDVMnWC.js} +1 -1
  66. package/dist/chunks/context-noninteractive-DV7bIJCm.js +1 -0
  67. package/dist/chunks/{conversation-CJ-d0O-U.js → conversation-BBOE_EoE.js} +1 -1
  68. package/dist/chunks/conversation-WxH5pb2z.js +1 -0
  69. package/dist/chunks/{createSSHSession-DOz_Ox1_.js → createSSHSession-LVGVXHXL.js} +1 -1
  70. package/dist/chunks/createSession-BUzna9-E.js +1 -0
  71. package/dist/chunks/{createSession-yR87Rhiv.js → createSession-Dgwxk1WA.js} +1 -1
  72. package/dist/chunks/{crossProjectResume-DNnZo3gU.js → crossProjectResume-6B2NYy8a.js} +1 -1
  73. package/dist/chunks/{datadog-DBgIEaEd.js → datadog-Bc6wkPne.js} +1 -1
  74. package/dist/chunks/{diff-qOom_T1G.js → diff-DIg66U_d.js} +1 -1
  75. package/dist/chunks/doctor-BhUmhHQU.js +1 -0
  76. package/dist/chunks/{entry-EmOA7oWN.js → entry-B-Y-AYeK.js} +1 -1
  77. package/dist/chunks/{esm-DBMVQDVv.js → esm-CvHtYRrr.js} +1 -1
  78. package/dist/chunks/{exit-DDrAFCzE.js → exit-CW2eqUrR.js} +1 -1
  79. package/dist/chunks/{extraUsage-DylXI7Fc.js → extraUsage-CkTon7ib.js} +1 -1
  80. package/dist/chunks/extractMemories-CfmbvayQ.js +1 -0
  81. package/dist/chunks/fast-ByahC7Gw.js +1 -0
  82. package/dist/chunks/{fast-BCkhj9Dq.js → fast-xtIP4u4y.js} +1 -1
  83. package/dist/chunks/fetchModelList-D9aePIPW.js +1 -0
  84. package/dist/chunks/{fetchModelList-BbjuFHQT.js → fetchModelList-Dy-x4h3G.js} +1 -1
  85. package/dist/chunks/{fileSuggestions-Ct7vKEpR.js → fileSuggestions-CFkJktgc.js} +1 -1
  86. package/dist/chunks/firstPartyEventLogger-Bt9iG9xk.js +1 -0
  87. package/dist/chunks/{firstPartyEventLogger-CxUuXQhL.js → firstPartyEventLogger-DqGSujCz.js} +2 -2
  88. package/dist/chunks/{flushGate-BZe_QwEz.js → flushGate-BjKW7PFC.js} +1 -1
  89. package/dist/chunks/{gemini-8sSwOtEf.js → gemini-NnmxBoEp.js} +1 -1
  90. package/dist/chunks/{generateSessionName-vT1khubt.js → generateSessionName-EpqGW-T2.js} +1 -1
  91. package/dist/chunks/{goal-CznQA1n1.js → goal-DbS8yJfB.js} +1 -1
  92. package/dist/chunks/{grok-cEzUsG-s.js → grok-BxZ4vTDw.js} +1 -1
  93. package/dist/chunks/{grove--HtQL4QZ.js → grove-CYE1Cfcz.js} +1 -1
  94. package/dist/chunks/{help-B6A_kDQA.js → help-DatnwM25.js} +1 -1
  95. package/dist/chunks/{hooks-CN5hLrhi.js → hooks-7iyENdDG.js} +1 -1
  96. package/dist/chunks/hooks-DjbqtbUV.js +1 -0
  97. package/dist/chunks/{initReplBridge-BJhmlcVt.js → initReplBridge-BEZW5PEY.js} +1 -1
  98. package/dist/chunks/{install-DUOtI2Hq.js → install-DJukI-kL.js} +1 -1
  99. package/dist/chunks/{instrumentation-DpgB3GFx.js → instrumentation-2HH15DPu.js} +3 -3
  100. package/dist/chunks/{job-DDoX1iFe.js → job-CXz7SLZp.js} +1 -1
  101. package/dist/chunks/{keybindings-BGTuYfk-.js → keybindings-C9l5il16.js} +1 -1
  102. package/dist/chunks/{launchLocalMemory-CoWeLNeP.js → launchLocalMemory-BfGenqj1.js} +1 -1
  103. package/dist/chunks/{launchOnboarding-CTIBGSLV.js → launchOnboarding-DjMmXeQE.js} +1 -1
  104. package/dist/chunks/{loadAgentsDir-DXOkUcW3.js → loadAgentsDir-DaNpxaO-.js} +587 -612
  105. package/dist/chunks/loadAgentsDir-DcI-8FQF.js +1 -0
  106. package/dist/chunks/{loadPluginHooks-DrNVtTBq.js → loadPluginHooks-CGgpcyEC.js} +1 -1
  107. package/dist/chunks/{localSearch-DnT21UkF.js → localSearch-C2SZ9bGW.js} +1 -1
  108. package/dist/chunks/localSearch-CTTwYTU1.js +1 -0
  109. package/dist/chunks/{logoUtils-YwL3izJt.js → logoUtils-CbIqOFrX.js} +1 -1
  110. package/dist/chunks/{magicDocs-rxv0rR8E.js → magicDocs-CrTwULyJ.js} +1 -1
  111. package/dist/chunks/{main-BOvY4O6D.js → main-bJXadFi0.js} +10 -10
  112. package/dist/chunks/{managedEnv-CpgCYISH.js → managedEnv-CUsdYhAI.js} +1 -1
  113. package/dist/chunks/managedEnv-DXeaUDSK.js +1 -0
  114. package/dist/chunks/{mappers-DYtq2XVS.js → mappers-_B-s9fNz.js} +1 -1
  115. package/dist/chunks/{mcp-BoU3TNFs.js → mcp-BbbYzWpy.js} +2 -2
  116. package/dist/chunks/{mcp-BPvcoKDY.js → mcp-D91sH9a8.js} +1 -1
  117. package/dist/chunks/{mcp-BfqsHRx0.js → mcp-Dx-zgUgu.js} +1 -1
  118. package/dist/chunks/{memory-BPKRdkBb.js → memory-BeL7ui9m.js} +1 -1
  119. package/dist/chunks/{mode-CXpXux2s.js → mode-D695kgLI.js} +1 -1
  120. package/dist/chunks/model-DX0TtzqX.js +1 -0
  121. package/dist/chunks/{model-Cxx3suBa.js → model-Do0f476p.js} +1 -1
  122. package/dist/chunks/{model-CxPYKiW1.js → model-DpcM8dz5.js} +1 -1
  123. package/dist/chunks/{modelOptions-BqBHEyiR.js → modelOptions-B3nis9cC.js} +1 -1
  124. package/dist/chunks/{src-l6_O0K-a.js → modifiersNative-BYHdmWw1.js} +1 -1
  125. package/dist/chunks/modifiersNative-D7nm70eq.js +1 -0
  126. package/dist/chunks/{nativeInstaller-CaXwRpoR.js → nativeInstaller-CymO8TNe.js} +1 -1
  127. package/dist/chunks/{omit-DZUxsClb.js → omit-DO61BHZu.js} +1 -1
  128. package/dist/chunks/{onChangeAppState-qHXqufwy.js → onChangeAppState-vKml_lit.js} +1 -1
  129. package/dist/chunks/{openai-_FQ9EhuR.js → openai-DdupGVdC.js} +1 -1
  130. package/dist/chunks/{partition-BgwHlPsO.js → partition-BivH9MBJ.js} +1 -1
  131. package/dist/chunks/{permissions-Dv5d5Nu3.js → permissions-C9iqR4_N.js} +1 -1
  132. package/dist/chunks/{pidLock-CEhbTkBE.js → pidLock-DiKz5Tza.js} +2 -2
  133. package/dist/chunks/{plan-DVPBW5OS.js → plan-KDN5IGWY.js} +1 -1
  134. package/dist/chunks/{plugin-Bh2eBwLW.js → plugin-D0rzUb8E.js} +1 -1
  135. package/dist/chunks/{pluginAutoupdate-C2YbEHrP.js → pluginAutoupdate-C2xTKLR_.js} +1 -1
  136. package/dist/chunks/{pluginBlocklist-B2NAKaB9.js → pluginBlocklist-xdiUmUpt.js} +1 -1
  137. package/dist/chunks/{pluginCliCommands-Cw5TrYYb.js → pluginCliCommands-CIDDvVN7.js} +1 -1
  138. package/dist/chunks/{pluginFlagging-BDTgCYuC.js → pluginFlagging-DRA0m76J.js} +1 -1
  139. package/dist/chunks/{pluginOperations-BBwGEdfC.js → pluginOperations-BEYsarAn.js} +1 -1
  140. package/dist/chunks/{pluginStartupCheck-DhhMk3dA.js → pluginStartupCheck-BF1N4Lih.js} +1 -1
  141. package/dist/chunks/pluginStartupCheck-DVkI4pqo.js +1 -0
  142. package/dist/chunks/{plugins-r0h93GT_.js → plugins-CWWU4BKs.js} +1 -1
  143. package/dist/chunks/{print-CDzhHi2F.js → print-B5H2xbBS.js} +3 -3
  144. package/dist/chunks/{processBashCommand-DmdCAWOR.js → processBashCommand-EQ9EWaRV.js} +1 -1
  145. package/dist/chunks/{processSlashCommand-B43TkiaI.js → processSlashCommand-C4PKNyFT.js} +1 -1
  146. package/dist/chunks/{prompt-DEioJrx_.js → prompt-8u06WVES.js} +1 -1
  147. package/dist/chunks/prompt-B9sDzLPK.js +1 -0
  148. package/dist/chunks/prompt-WsoTRhoh.js +1 -0
  149. package/dist/chunks/{promptEditor-eJzbtNn4.js → promptEditor-Cr4w-4Bz.js} +1 -1
  150. package/dist/chunks/{protocolHandler-C-CFTcUJ.js → protocolHandler-DzHVaPl3.js} +2 -2
  151. package/dist/chunks/{reconciler-DZP4dJJG.js → reconciler-RIKmaPg7.js} +1 -1
  152. package/dist/chunks/{refresh-vaY-Sr80.js → refresh-CCSCAjgz.js} +1 -1
  153. package/dist/chunks/registerProtocol-C0IlPEoa.js +1 -0
  154. package/dist/chunks/{reload-plugins-m9CzoIxu.js → reload-plugins-DC-tbXVv.js} +1 -1
  155. package/dist/chunks/{remoteBridgeCore-C4vSr1gp.js → remoteBridgeCore-NGTnhQgw.js} +1 -1
  156. package/dist/chunks/{remoteManagedSettings-6RAHPt_g.js → remoteManagedSettings-BoOYHzYP.js} +1 -1
  157. package/dist/chunks/{rename-DmauGVBX.js → rename-DS1AmW-F.js} +1 -1
  158. package/dist/chunks/{resume-ut_pBrLN.js → resume-Cf5PSoPw.js} +1 -1
  159. package/dist/chunks/{runtimeObserver-CSroopId.js → runtimeObserver-DzesbvgI.js} +1 -1
  160. package/dist/chunks/{runtimeObserver-C2vjqtCE.js → runtimeObserver-L6041elO.js} +2 -2
  161. package/dist/chunks/sandbox-adapter-Z4Phj31K.js +1 -0
  162. package/dist/chunks/{sandbox-toggle-BJKd1ZYk.js → sandbox-toggle-COZE8Lo4.js} +1 -1
  163. package/dist/chunks/sanitization-DV-94a9Z.js +1 -0
  164. package/dist/chunks/searchExtraTools-CvkRbL2m.js +1 -0
  165. package/dist/chunks/{session-DTin6hOR.js → session-BvA99K4j.js} +1 -1
  166. package/dist/chunks/sessionFileAccessHooks-6XfAf6ke.js +1 -0
  167. package/dist/chunks/{sessionObserver-iAJLH92a.js → sessionObserver-0D8xFoRK.js} +1 -1
  168. package/dist/chunks/sessionObserver-CRWUBJEY.js +1 -0
  169. package/dist/chunks/{sessionState-DAcub-HK.js → sessionState-CQhbGfmh.js} +1 -1
  170. package/dist/chunks/sessionStorage-DqEuxDlb.js +1 -0
  171. package/dist/chunks/{sessionTracing-Dvi520eN.js → sessionTracing-BoOZsXU2.js} +1 -1
  172. package/dist/chunks/{settingsSync-aHn3p-6J.js → settingsSync-rkWmClKS.js} +1 -1
  173. package/dist/chunks/{setup-CK3ybjjM.js → setup-D8L275fT.js} +2 -2
  174. package/dist/chunks/{shadowedRuleDetection-BL7dEv-u.js → shadowedRuleDetection-Cy9tsuKc.js} +1 -1
  175. package/dist/chunks/{sideQuestion-Ct87yvOR.js → sideQuestion-Ds7Elgs4.js} +1 -1
  176. package/dist/chunks/{sinks-Bmn3li0M.js → sinks-BXX72cbf.js} +1 -1
  177. package/dist/chunks/sinks-DMp6uEzM.js +1 -0
  178. package/dist/chunks/{skillChangeDetector-Bco3UoeW.js → skillChangeDetector-CtithJ4a.js} +1 -1
  179. package/dist/chunks/{skillGapStore-MtlRyYmT.js → skillGapStore-BxCxKPev.js} +2 -2
  180. package/dist/chunks/{skillLifecycle-Drs6gEv9.js → skillLifecycle-CfyNC3sW.js} +2 -2
  181. package/dist/chunks/{skillSearchPanel-DkvmjNaw.js → skillSearchPanel-CMNJFIEC.js} +2 -2
  182. package/dist/chunks/{skills-axToWEo0.js → skills-DXMk-498.js} +1 -1
  183. package/dist/chunks/{status-CGp4uRlH.js → status-CFrLuGbf.js} +1 -1
  184. package/dist/chunks/status-D5OCkMZG.js +1 -0
  185. package/dist/chunks/{statusNoticeHelpers-BrN_2q7H.js → statusNoticeHelpers-CZoOse-_.js} +1 -1
  186. package/dist/chunks/switcher-AiMcRzoi.js +1 -0
  187. package/dist/chunks/{switcher-99gm2vpe.js → switcher-DQF5ZNal.js} +1 -1
  188. package/dist/chunks/{syncCache-B3OVvp8K.js → syncCache-qWJ_VfBo.js} +1 -1
  189. package/dist/chunks/{tasks-t5zT_D32.js → tasks-C8pb6ftc.js} +1 -1
  190. package/dist/chunks/{teleport-CvX_nUjQ.js → teleport-Bi_1VFIZ.js} +1 -1
  191. package/dist/chunks/{templateJobs-Bm8bovHx.js → templateJobs-DJ4dcfcL.js} +1 -1
  192. package/dist/chunks/{theme-DzaSXOpQ.js → theme-CEKOCSLw.js} +1 -1
  193. package/dist/chunks/{toolEventObserver-C_nHI27x.js → toolEventObserver-D2nk8ZbW.js} +1 -1
  194. package/dist/chunks/{toolPool-CgKK0K8f.js → toolPool-Df5iUqJ-.js} +1 -1
  195. package/dist/chunks/{trustedDevice-Bb7O8_tj.js → trustedDevice-CB6rNzl-.js} +1 -1
  196. package/dist/chunks/trustedDevice-DXGePUAC.js +1 -0
  197. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-D0uqGxGw.js → useExitOnCtrlCDWithKeybindings-Bw0mlTT9.js} +1 -1
  198. package/dist/chunks/useMainLoopModel-CIG2cjS2.js +1 -0
  199. package/dist/chunks/{useManagePlugins-ITVFO9dz.js → useManagePlugins-MSHw-qHx.js} +1 -1
  200. package/dist/chunks/{useMergedTools-rQ19rFvH.js → useMergedTools-Bb-INJa2.js} +1 -1
  201. package/dist/chunks/{useSearchInput-CXTa-leH.js → useSearchInput-QL_VtdJD.js} +1 -1
  202. package/dist/chunks/{useSettingsErrors-Xc6RYjYF.js → useSettingsErrors-Dvi6zLCr.js} +1 -1
  203. package/dist/chunks/{userAgent-CJ5Rp9kc.js → userAgent-i-oGzf40.js} +1 -1
  204. package/dist/chunks/{util-CD3ar4of.js → util-CLQvtXuD.js} +1 -1
  205. package/dist/chunks/{validatePlugin-CxrlCKc1.js → validatePlugin-1mTZ3TJR.js} +1 -1
  206. package/dist/chunks/{workerRegistry-BGJtgrko.js → workerRegistry-BjxoZ12l.js} +2 -2
  207. package/dist/chunks/worktree-DpksgxdF.js +1 -0
  208. package/dist/cli.js +1 -1
  209. package/package.json +1 -5
  210. package/dist/chunks/AgentsMdExternalIncludesDialog-Bny8WDwC.js +0 -1
  211. package/dist/chunks/ApproveApiKey-BKzkEkW-.js +0 -1
  212. package/dist/chunks/Doctor-DYEdLRxR.js +0 -1
  213. package/dist/chunks/REPL-yzvMFfaU.js +0 -1
  214. package/dist/chunks/SearchExtraToolsTool-CdgQlm--.js +0 -1
  215. package/dist/chunks/api-CB3e0De0.js +0 -1
  216. package/dist/chunks/attributionHooks-C0aXyx9L.js +0 -1
  217. package/dist/chunks/auth-CsYEYXBO.js +0 -1
  218. package/dist/chunks/auth-CubXYcRl.js +0 -1
  219. package/dist/chunks/backgroundHousekeeping-CykbtljP.js +0 -1
  220. package/dist/chunks/bridgeConfig-Cp2x_wtE.js +0 -1
  221. package/dist/chunks/caches-BiVRgePi.js +0 -1
  222. package/dist/chunks/caches-CGzKSWiP.js +0 -1
  223. package/dist/chunks/client-CmnPWgLq.js +0 -1
  224. package/dist/chunks/commands-CrzVgHxp.js +0 -1
  225. package/dist/chunks/config-Df8jooTW.js +0 -1
  226. package/dist/chunks/context-noninteractive-m4O3VtG7.js +0 -1
  227. package/dist/chunks/conversation-BYBX07j8.js +0 -1
  228. package/dist/chunks/createSession-C_-ZEQT5.js +0 -1
  229. package/dist/chunks/doctor-CflXjqVK.js +0 -1
  230. package/dist/chunks/extractMemories-B_8wZpXA.js +0 -1
  231. package/dist/chunks/fast-4ajfJv-M.js +0 -1
  232. package/dist/chunks/fetchModelList-V8_e2O1N.js +0 -1
  233. package/dist/chunks/firstPartyEventLogger-YQm0DoVu.js +0 -1
  234. package/dist/chunks/hooks-CJY5Vfy6.js +0 -1
  235. package/dist/chunks/loadAgentsDir-Dxz1vp3F.js +0 -1
  236. package/dist/chunks/localSearch-CCs5fOd_.js +0 -1
  237. package/dist/chunks/managedEnv-CrnBYTtQ.js +0 -1
  238. package/dist/chunks/model-aEJ54cMA.js +0 -1
  239. package/dist/chunks/pluginStartupCheck-CHx379_R.js +0 -1
  240. package/dist/chunks/postCommitAttribution-DoSP9wZD.js +0 -1
  241. package/dist/chunks/prompt-C50mDqWv.js +0 -1
  242. package/dist/chunks/prompt-WGH9CcXh.js +0 -1
  243. package/dist/chunks/registerProtocol-Xsq4ldwg.js +0 -1
  244. package/dist/chunks/sandbox-adapter-CL0qdcxn.js +0 -1
  245. package/dist/chunks/searchExtraTools-ByWuNCGo.js +0 -1
  246. package/dist/chunks/sessionFileAccessHooks-DorzHolr.js +0 -1
  247. package/dist/chunks/sessionObserver-Dy6NFlzL.js +0 -1
  248. package/dist/chunks/sessionStorage-DItJMkwx.js +0 -1
  249. package/dist/chunks/sinks-QQ_6Op7q.js +0 -1
  250. package/dist/chunks/src-DPUAq5Ty.js +0 -1
  251. package/dist/chunks/status-3uevwSMo.js +0 -1
  252. package/dist/chunks/switcher-DJDxjLPQ.js +0 -1
  253. package/dist/chunks/trustedDevice-C2gnF9Lc.js +0 -1
  254. package/dist/chunks/useMainLoopModel-BGPOmBkl.js +0 -1
  255. package/dist/chunks/worktree-CanG5GhE.js +0 -1
  256. /package/dist/chunks/{src-DLz3FZm1.js → urlHandler-DLz3FZm1.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{c as e,i as t,l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{n as a,t as o}from"./defineProperty-C-QyHrDq.js";import{n as s,t as c}from"./axios-DaWTGg7G.js";import{$T as l,$d as u,$l as d,$y as f,A as p,Ab as m,Ai as h,B as g,Bc as ee,Bg as _,Bt as te,C as ne,Cb as re,Cn as v,Di as y,Dx as ie,ES as ae,Eb as b,Ex as oe,Fb as x,Fc as se,Gg as ce,Gs as le,Gv as ue,Hc as S,If as de,Ig as fe,Io as pe,Ix as me,Jn as he,Jv as ge,Kb as _e,Kv as ve,La as ye,Lc as be,Lf as xe,Lg as C,Li as Se,Lv as Ce,Mb as we,Mi as Te,Mo as Ee,Ms as De,Mx as Oe,Nb as ke,Ns as w,Ob as Ae,Pb as je,Pc as Me,Ps as T,QC as Ne,Qd as E,Qn as Pe,Qw as Fe,Qy as Ie,Rc as Le,Ro as Re,Rv as ze,Sn as Be,Th as Ve,Tu as He,Tx as Ue,Ub as We,Uc as Ge,Ug as D,Ur as Ke,V as qe,VS as Je,Vc as Ye,Vg as Xe,Vo as Ze,Vt as Qe,Wb as $e,Wc as O,Xp as k,Xv as et,Yv as tt,ZC as nt,Zd as rt,Zp as it,__ as at,_b as ot,_i as st,_m as ct,aT as lt,af as ut,ai as dt,ax as ft,b as pt,bb as mt,bg as ht,bm as gt,bn as _t,br as vt,cc as yt,co as bt,cs as xt,dT as St,dm as Ct,ds as wt,eb as Tt,ec as Et,ef as Dt,eg as Ot,eu as kt,f as At,fm as jt,fs as Mt,g_ as Nt,ga as Pt,gi as Ft,gm as It,gs as Lt,hT as A,h_ as Rt,hg as zt,hm as Bt,hn as Vt,hs as Ht,hx as Ut,ic as Wt,ii as Gt,io as Kt,jo as qt,js as Jt,jx as Yt,kb as Xt,lc as Zt,lp as Qt,ls as $t,ly as en,mT as tn,m_ as nn,mg as rn,mm as an,ms as on,nc as sn,ni as cn,no as ln,ny as un,o as dn,oS as fn,oT as pn,oy as mn,pg as hn,pm as gn,ps as _n,qc as vn,qg as yn,qs as bn,rf as xn,ry as Sn,s as Cn,sS as wn,sp as Tn,ss as En,tT as Dn,tc as On,tg as kn,ti as An,to as jn,ty as Mn,uT as Nn,um as Pn,uo as Fn,us as In,v as Ln,vm as Rn,vr as zn,vx as Bn,w as Vn,wS as Hn,wh as Un,wm as Wn,wn as Gn,wu as Kn,xm as qn,xn as Jn,xu as Yn,y as Xn,yb as Zn,yg as Qn,ym as $n,yn as er,yr as tr,zi as nr}from"./loadAgentsDir-DXOkUcW3.js";import{C as j,D as M,E as N,F as P,N as F,P as I,S as rr,_ as L,f as R,g as z,h as ir,i as B,j as V,n as H,p as ar,r as or,t as sr,y as cr}from"./lazySchema-DULtBUCI.js";import{J as lr,Kn as ur,Mn as dr,N as fr,Qt as pr,Ut as mr,Wt as hr,ar as gr,ft as U,j as _r,jn as vr,mn as yr,vn as br}from"./state-D5D6QpTX.js";import{n as xr,t as Sr}from"./cwd-Nh5IZNKO.js";import{C as Cr,E as wr,P as W,R as Tr,S as Er,U as Dr,a as Or,c as G,f as kr,i as Ar,nt as jr,tt as Mr,u as Nr,x as Pr}from"./debug-D58GQBDG.js";import{Ln as Fr,W as Ir,_t as Lr,ar as Rr,d as zr,h as Br,rt as Vr,sr as Hr,tt as Ur,u as Wr,ut as Gr,zn as Kr}from"./settings-3xZ0fsvE.js";import{F as qr,M as Jr}from"./config-DRy1I12M.js";import{i as Yr,n as Xr,o as K}from"./process-gEbdy6uY.js";import{A as Zr,O as Qr,k as $r}from"./git-By_J4XJL.js";import{H as ei,c as ti,i as ni,o as ri,q as ii,s as q}from"./log-CZ7ploQm.js";import{s as ai,u as oi}from"./types-APu4OCXJ.js";import{n as si,r as J}from"./analytics-DJobLaWP.js";import{$r as ci,Br as li,C as ui,En as di,J as fi,Pt as pi,Q as mi,Qr as hi,Rr as gi,Tn as _i,U as vi,Y as yi,Z as bi,Zr as xi,_ as Si,dn as Ci,dr as wi,fn as Ti,mt as Ei,o as Di,ti as Oi,u as ki,ur as Ai,x as ji}from"./model-Cxx3suBa.js";import{_t as Mi,at as Ni,bn as Pi,it as Fi,tn as Ii,vn as Li,vt as Ri,yt as zi}from"./prompt-DEioJrx_.js";import{C as Bi,S as Vi,T as Hi,_ as Ui,a as Wi,at as Gi,b as Ki,c as qi,ct as Ji,et as Yi,l as Xi,n as Zi,nt as Qi,o as $i,rt as ea,s as ta,st as na,t as ra}from"./sessionState-DAcub-HK.js";import{n as ia,t as aa}from"./omit-DZUxsClb.js";import{a as oa,n as sa,t as ca}from"./bridgeConfig-MxsnEEPx.js";import{i as la,n as ua,s as da}from"./mappers-DYtq2XVS.js";import{n as fa,r as pa}from"./sessionTitle-k4wpUS5l.js";import{t as ma}from"./pollConfig-2nFzv6Hy.js";import{t as ha}from"./controlMessageCompat-IFu4Gc1y.js";import{n as ga,t as _a}from"./ccrClient-CimQTd0b.js";import{n as va,t as ya}from"./HybridTransport-DArmWb1V.js";import{n as ba,t as xa}from"./SSETransport-pPrlSZNF.js";import{a as Sa,n as Ca}from"./grove--HtQL4QZ.js";import{o as wa}from"./remoteManagedSettings-6RAHPt_g.js";import{i as Ta,r as Ea}from"./auth-DvcZHXGk.js";import{t as Da}from"./pluginBlocklist-B2NAKaB9.js";import{t as Oa}from"./settingsSync-aHn3p-6J.js";import{n as ka,t as Aa}from"./toolPool-CgKK0K8f.js";import{t as ja}from"./onChangeAppState-qHXqufwy.js";import{n as Ma,r as Na}from"./QueryEngine-bKlupZpA.js";import{r as Pa}from"./bridgeStatusUtil-B9EcQksI.js";import{n as Fa,r as Ia}from"./sideQuestion-Ct87yvOR.js";import{n as La,r as Ra}from"./context-noninteractive-ApbVPU86.js";import{n as za,r as Ba}from"./modelOptions-BqBHEyiR.js";import{a as Va,o as Ha,t as Ua}from"./skillChangeDetector-Bco3UoeW.js";import{n as Wa}from"./reconciler-DZP4dJJG.js";import{n as Ga,t as Ka}from"./refresh-vaY-Sr80.js";import{basename as qa,dirname as Ja,join as Ya}from"path";import{PassThrough as Xa}from"stream";import{randomUUID as Y}from"crypto";import{mkdir as Za,readFile as Qa,stat as $a,writeFile as eo}from"fs/promises";import{URL as to}from"url";import{cwd as X}from"process";r(),a(),c(),mr(),Mr(),Tr(),Pr(),kr(),Xr(),Ar(),Qr(),ii(),ri(),Fr(),ai(),Br(),Oi(),li(),wi(),_i(),Ci(),pi(),Si(),Oa(),or(),sr();var no=H(()=>M({inputTokens:N(),outputTokens:N(),cacheReadInputTokens:N(),cacheCreationInputTokens:N(),webSearchRequests:N(),costUSD:N(),contextWindow:N(),maxOutputTokens:N()})),ro=H(()=>j(`json_schema`));H(()=>M({type:ro()}));var io=H(()=>M({type:j(`json_schema`),schema:V(F(),P())}));H(()=>io());var ao=H(()=>R([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>R([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>j(`context-1m-2025-08-07`));var oo=H(()=>M({type:j(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),so=H(()=>M({type:j(`enabled`),budgetTokens:N().optional()}).describe(`Fixed thinking token budget (older models)`)),co=H(()=>M({type:j(`disabled`)}).describe(`No extended thinking`));H(()=>I([oo(),so(),co()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var lo=H(()=>M({type:j(`stdio`).optional(),command:F(),args:z(F()).optional(),env:V(F(),F()).optional()})),uo=H(()=>M({type:j(`sse`),url:F(),headers:V(F(),F()).optional()})),fo=H(()=>M({type:j(`http`),url:F(),headers:V(F(),F()).optional()})),po=H(()=>M({type:j(`sdk`),name:F()})),mo=H(()=>I([lo(),uo(),fo(),po()])),ho=H(()=>M({type:j(`claudeai-proxy`),url:F(),id:F()})),go=H(()=>I([mo(),ho()])),_o=H(()=>M({name:F().describe(`Server name as configured`),status:R([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:M({name:F(),version:F()}).optional().describe(`Server information (available when connected)`),error:F().optional().describe(`Error message (available when status is 'failed')`),config:go().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:F().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:z(M({name:F(),description:F().optional(),annotations:M({readOnly:L().optional(),destructive:L().optional(),openWorld:L().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:M({experimental:V(F(),P()).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(()=>M({added:z(F()).describe(`Names of servers that were added`),removed:z(F()).describe(`Names of servers that were removed`),errors:V(F(),F()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var vo=H(()=>R([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),yo=H(()=>R([`allow`,`deny`,`ask`])),bo=H(()=>M({toolName:F(),ruleContent:F().optional()})),xo=H(()=>cr(`type`,[M({type:j(`addRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`replaceRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`removeRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`setMode`),mode:rr(()=>Co()),destination:vo()}),M({type:j(`addDirectories`),directories:z(F()),destination:vo()}),M({type:j(`removeDirectories`),directories:z(F()),destination:vo()})])),So=H(()=>R([`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([M({behavior:j(`allow`),updatedInput:V(F(),P()).optional(),updatedPermissions:z(xo()).optional(),toolUseID:F().optional(),decisionClassification:So().optional()}),M({behavior:j(`deny`),message:F(),interrupt:L().optional(),toolUseID:F().optional(),decisionClassification:So().optional()})]));var Co=H(()=>R([`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).`)),wo=`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(`.`),To=H(()=>R(wo)),Z=H(()=>M({session_id:F(),transcript_path:F(),cwd:F(),permission_mode:F().optional(),agent_id:F().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:F().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).`)})),Eo=H(()=>Z().and(M({hook_event_name:j(`PreToolUse`),tool_name:F(),tool_input:P(),tool_use_id:F()}))),Do=H(()=>Z().and(M({hook_event_name:j(`PermissionRequest`),tool_name:F(),tool_input:P(),permission_suggestions:z(xo()).optional()}))),Oo=H(()=>Z().and(M({hook_event_name:j(`PostToolUse`),tool_name:F(),tool_input:P(),tool_response:P(),tool_use_id:F()}))),ko=H(()=>Z().and(M({hook_event_name:j(`PostToolUseFailure`),tool_name:F(),tool_input:P(),tool_use_id:F(),error:F(),is_interrupt:L().optional()}))),Ao=H(()=>Z().and(M({hook_event_name:j(`PermissionDenied`),tool_name:F(),tool_input:P(),tool_use_id:F(),reason:F()}))),jo=H(()=>Z().and(M({hook_event_name:j(`Notification`),message:F(),title:F().optional(),notification_type:F()}))),Mo=H(()=>Z().and(M({hook_event_name:j(`UserPromptSubmit`),prompt:F()}))),No=H(()=>Z().and(M({hook_event_name:j(`SessionStart`),source:R([`startup`,`resume`,`clear`,`compact`]),agent_type:F().optional(),model:F().optional()}))),Po=H(()=>Z().and(M({hook_event_name:j(`Setup`),trigger:R([`init`,`maintenance`])}))),Fo=H(()=>Z().and(M({hook_event_name:j(`Stop`),stop_hook_active:L(),last_assistant_message:F().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Io=H(()=>Z().and(M({hook_event_name:j(`StopFailure`),error:Ns(),error_details:F().optional(),last_assistant_message:F().optional()}))),Lo=H(()=>Z().and(M({hook_event_name:j(`SubagentStart`),agent_id:F(),agent_type:F()}))),Ro=H(()=>Z().and(M({hook_event_name:j(`SubagentStop`),stop_hook_active:L(),agent_id:F(),agent_transcript_path:F(),agent_type:F(),last_assistant_message:F().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),zo=H(()=>Z().and(M({hook_event_name:j(`PreCompact`),trigger:R([`manual`,`auto`]),custom_instructions:F().nullable()}))),Bo=H(()=>Z().and(M({hook_event_name:j(`PostCompact`),trigger:R([`manual`,`auto`]),compact_summary:F().describe(`The conversation summary produced by compaction`)}))),Vo=H(()=>Z().and(M({hook_event_name:j(`TeammateIdle`),teammate_name:F(),team_name:F()}))),Ho=H(()=>Z().and(M({hook_event_name:j(`TaskCreated`),task_id:F(),task_subject:F(),task_description:F().optional(),teammate_name:F().optional(),team_name:F().optional()}))),Uo=H(()=>Z().and(M({hook_event_name:j(`TaskCompleted`),task_id:F(),task_subject:F(),task_description:F().optional(),teammate_name:F().optional(),team_name:F().optional()}))),Wo=H(()=>Z().and(M({hook_event_name:j(`Elicitation`),mcp_server_name:F(),message:F(),mode:R([`form`,`url`]).optional(),url:F().optional(),elicitation_id:F().optional(),requested_schema:V(F(),P()).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.`)),Go=H(()=>Z().and(M({hook_event_name:j(`ElicitationResult`),mcp_server_name:F(),elicitation_id:F().optional(),mode:R([`form`,`url`]).optional(),action:R([`accept`,`decline`,`cancel`]),content:V(F(),P()).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.`)),Ko=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],qo=H(()=>Z().and(M({hook_event_name:j(`ConfigChange`),source:R(Ko),file_path:F().optional()}))),Jo=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Yo=[`User`,`Project`,`Local`,`Managed`],Xo=H(()=>Z().and(M({hook_event_name:j(`InstructionsLoaded`),file_path:F(),memory_type:R(Yo),load_reason:R(Jo),globs:z(F()).optional(),trigger_file_path:F().optional(),parent_file_path:F().optional()}))),Zo=H(()=>Z().and(M({hook_event_name:j(`WorktreeCreate`),name:F()}))),Qo=H(()=>Z().and(M({hook_event_name:j(`WorktreeRemove`),worktree_path:F()}))),$o=H(()=>Z().and(M({hook_event_name:j(`CwdChanged`),old_cwd:F(),new_cwd:F()}))),es=H(()=>Z().and(M({hook_event_name:j(`FileChanged`),file_path:F(),event:R([`change`,`add`,`unlink`])}))),ts=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ns=H(()=>R(ts)),rs=H(()=>Z().and(M({hook_event_name:j(`SessionEnd`),reason:ns()}))),is=H(()=>I([Eo(),Oo(),ko(),Ao(),jo(),Mo(),No(),rs(),Fo(),Io(),Lo(),Ro(),zo(),Bo(),Do(),Po(),Vo(),Ho(),Uo(),Wo(),Go(),qo(),Xo(),Zo(),Qo(),$o(),es()])),as=H(()=>M({async:j(!0),asyncTimeout:N().optional()})),os=H(()=>M({hookEventName:j(`PreToolUse`),permissionDecision:yo().optional(),permissionDecisionReason:F().optional(),updatedInput:V(F(),P()).optional(),additionalContext:F().optional()})),ss=H(()=>M({hookEventName:j(`UserPromptSubmit`),additionalContext:F().optional()})),cs=H(()=>M({hookEventName:j(`SessionStart`),additionalContext:F().optional(),initialUserMessage:F().optional(),watchPaths:z(F()).optional()})),ls=H(()=>M({hookEventName:j(`Setup`),additionalContext:F().optional()})),us=H(()=>M({hookEventName:j(`SubagentStart`),additionalContext:F().optional()})),ds=H(()=>M({hookEventName:j(`PostToolUse`),additionalContext:F().optional(),updatedMCPToolOutput:P().optional()})),fs=H(()=>M({hookEventName:j(`PostToolUseFailure`),additionalContext:F().optional()})),ps=H(()=>M({hookEventName:j(`PermissionDenied`),retry:L().optional()})),ms=H(()=>M({hookEventName:j(`Notification`),additionalContext:F().optional()})),hs=H(()=>M({hookEventName:j(`PermissionRequest`),decision:I([M({behavior:j(`allow`),updatedInput:V(F(),P()).optional(),updatedPermissions:z(xo()).optional()}),M({behavior:j(`deny`),message:F().optional(),interrupt:L().optional()})])})),gs=H(()=>M({hookEventName:j(`CwdChanged`),watchPaths:z(F()).optional()})),_s=H(()=>M({hookEventName:j(`FileChanged`),watchPaths:z(F()).optional()})),vs=H(()=>M({continue:L().optional(),suppressOutput:L().optional(),stopReason:F().optional(),decision:R([`approve`,`block`]).optional(),systemMessage:F().optional(),reason:F().optional(),hookSpecificOutput:I([os(),ss(),cs(),ls(),us(),ds(),fs(),ps(),ms(),hs(),ys(),bs(),gs(),_s(),xs()]).optional()})),ys=H(()=>M({hookEventName:j(`Elicitation`),action:R([`accept`,`decline`,`cancel`]).optional(),content:V(F(),P()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),bs=H(()=>M({hookEventName:j(`ElicitationResult`),action:R([`accept`,`decline`,`cancel`]).optional(),content:V(F(),P()).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.`)),xs=H(()=>M({hookEventName:j(`WorktreeCreate`),worktreePath:F()}).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([as(),vs()]));var Ss=H(()=>M({key:F().describe(`Unique key for this option, returned in the response`),label:F().describe(`Display text for this option`),description:F().optional().describe(`Optional description shown below the label`)}));H(()=>M({prompt:F().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:F().describe(`The prompt message to display to the user`),options:z(Ss()).describe(`Available options for the user to choose from`)})),H(()=>M({prompt_response:F().describe(`The request ID from the corresponding prompt request`),selected:F().describe(`The key of the selected option`)}));var Cs=H(()=>M({name:F().describe(`Skill name (without the leading slash)`),description:F().describe(`Description of what the skill does`),argumentHint:F().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),ws=H(()=>M({name:F().describe(`Agent type identifier (e.g., "Explore")`),description:F().describe(`Description of when to use this agent`),model:F().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.`)),Ts=H(()=>M({value:F().describe(`Model identifier to use in API calls`),displayName:F().describe(`Human-readable display name`),description:F().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:L().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:L().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:L().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Es=H(()=>M({email:F().optional(),organization:F().optional(),subscriptionType:F().optional(),tokenSource:F().optional(),apiKeySource:F().optional(),apiProvider:R([`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.`)),Ds=H(()=>I([F(),V(F(),mo())])),Os=H(()=>M({description:F().describe(`Natural language description of when to use this agent`),tools:z(F()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:z(F()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:F().describe(`The agent's system prompt`),model:F().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:z(Ds()).optional(),criticalSystemReminder_EXPERIMENTAL:F().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:z(F()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:F().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:N().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:L().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:R([`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:Co().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(()=>R([`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(()=>M({type:j(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:F().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>M({canRewind:L(),error:F().optional(),filesChanged:z(F()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var ks=H(()=>P()),As=H(()=>P()),js=H(()=>P()),Q=H(()=>F()),Ms=H(()=>P()),Ns=H(()=>R([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ps=H(()=>I([j(`compacting`),ar()])),Fs=H(()=>M({type:j(`user`),message:ks(),parent_tool_use_id:F().nullable(),isSynthetic:L().optional(),tool_use_result:P().optional(),priority:R([`now`,`next`,`later`]).optional(),timestamp:F().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Is=H(()=>Fs().extend({uuid:Q().optional(),session_id:F().optional()})),Ls=H(()=>Fs().extend({uuid:Q(),session_id:F(),isReplay:j(!0)})),Rs=H(()=>M({status:R([`allowed`,`allowed_warning`,`rejected`]),resetsAt:N().optional(),rateLimitType:R([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:N().optional(),overageStatus:R([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:N().optional(),overageDisabledReason:R([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`org_service_zero_credit_limit`,`no_limits_configured`,`unknown`]).optional(),isUsingOverage:L().optional(),surpassedThreshold:N().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),zs=H(()=>M({type:j(`assistant`),message:As(),parent_tool_use_id:F().nullable(),error:Ns().optional(),uuid:Q(),session_id:F()})),Bs=H(()=>M({type:j(`rate_limit_event`),rate_limit_info:Rs(),uuid:Q(),session_id:F()}).describe(`Rate limit event emitted when rate limit info changes.`)),Vs=H(()=>M({type:j(`streamlined_text`),text:F().describe(`Text content preserved from the assistant message`),session_id:F(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Hs=H(()=>M({type:j(`streamlined_tool_use_summary`),tool_summary:F().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:F(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Us=H(()=>M({tool_name:F(),tool_use_id:F(),tool_input:V(F(),P())})),Ws=H(()=>M({type:j(`result`),subtype:j(`success`),duration_ms:N(),duration_api_ms:N(),is_error:L(),num_turns:N(),result:F(),stop_reason:F().nullable(),total_cost_usd:N(),usage:Ms(),modelUsage:V(F(),no()),permission_denials:z(Us()),structured_output:P().optional(),fast_mode_state:mc().optional(),uuid:Q(),session_id:F()})),Gs=H(()=>M({type:j(`result`),subtype:R([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:N(),duration_api_ms:N(),is_error:L(),num_turns:N(),stop_reason:F().nullable(),total_cost_usd:N(),usage:Ms(),modelUsage:V(F(),no()),permission_denials:z(Us()),errors:z(F()),fast_mode_state:mc().optional(),uuid:Q(),session_id:F()})),Ks=H(()=>I([Ws(),Gs()])),qs=H(()=>M({type:j(`system`),subtype:j(`init`),agents:z(F()).optional(),apiKeySource:ao(),betas:z(F()).optional(),claude_code_version:F(),cwd:F(),tools:z(F()),mcp_servers:z(M({name:F(),status:F()})),model:F(),permissionMode:Co(),slash_commands:z(F()),output_style:F(),skills:z(F()),plugins:z(M({name:F(),path:F(),source:F().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:mc().optional(),uuid:Q(),session_id:F()})),Js=H(()=>M({type:j(`stream_event`),event:js(),parent_tool_use_id:F().nullable(),uuid:Q(),session_id:F()})),Ys=H(()=>M({type:j(`system`),subtype:j(`compact_boundary`),compact_metadata:M({trigger:R([`manual`,`auto`]),pre_tokens:N(),preserved_segment:M({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:F()})),Xs=H(()=>M({type:j(`system`),subtype:j(`status`),status:Ps(),permissionMode:Co().optional(),uuid:Q(),session_id:F()})),Zs=H(()=>M({type:j(`system`),subtype:j(`post_turn_summary`),summarizes_uuid:F(),status_category:R([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:F(),is_noteworthy:L(),title:F(),description:F(),recent_action:F(),needs_action:F(),artifact_urls:z(F()),uuid:Q(),session_id:F()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),Qs=H(()=>M({type:j(`system`),subtype:j(`api_retry`),attempt:N(),max_retries:N(),retry_delay_ms:N(),error_status:N().nullable(),error:Ns(),uuid:Q(),session_id:F()}).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.`)),$s=H(()=>M({type:j(`system`),subtype:j(`local_command_output`),content:F(),uuid:Q(),session_id:F()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),ec=H(()=>M({type:j(`system`),subtype:j(`hook_started`),hook_id:F(),hook_name:F(),hook_event:F(),uuid:Q(),session_id:F()})),tc=H(()=>M({type:j(`system`),subtype:j(`hook_progress`),hook_id:F(),hook_name:F(),hook_event:F(),stdout:F(),stderr:F(),output:F(),uuid:Q(),session_id:F()})),nc=H(()=>M({type:j(`system`),subtype:j(`hook_response`),hook_id:F(),hook_name:F(),hook_event:F(),output:F(),stdout:F(),stderr:F(),exit_code:N().optional(),outcome:R([`success`,`error`,`cancelled`]),uuid:Q(),session_id:F()})),rc=H(()=>M({type:j(`tool_progress`),tool_use_id:F(),tool_name:F(),parent_tool_use_id:F().nullable(),elapsed_time_seconds:N(),task_id:F().optional(),uuid:Q(),session_id:F()})),ic=H(()=>M({type:j(`auth_status`),isAuthenticating:L(),output:z(F()),error:F().optional(),uuid:Q(),session_id:F()})),ac=H(()=>M({type:j(`system`),subtype:j(`files_persisted`),files:z(M({filename:F(),file_id:F()})),failed:z(M({filename:F(),error:F()})),processed_at:F(),uuid:Q(),session_id:F()})),oc=H(()=>M({type:j(`system`),subtype:j(`task_notification`),task_id:F(),tool_use_id:F().optional(),status:R([`completed`,`failed`,`stopped`]),output_file:F(),summary:F(),usage:M({total_tokens:N(),tool_uses:N(),duration_ms:N()}).optional(),uuid:Q(),session_id:F()})),sc=H(()=>M({type:j(`system`),subtype:j(`task_started`),task_id:F(),tool_use_id:F().optional(),description:F(),task_type:F().optional(),workflow_name:F().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:F().optional(),uuid:Q(),session_id:F()})),cc=H(()=>M({type:j(`system`),subtype:j(`session_state_changed`),state:R([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:F()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),lc=H(()=>M({type:j(`system`),subtype:j(`task_progress`),task_id:F(),tool_use_id:F().optional(),description:F(),usage:M({total_tokens:N(),tool_uses:N(),duration_ms:N()}),last_tool_name:F().optional(),summary:F().optional(),uuid:Q(),session_id:F()})),uc=H(()=>M({type:j(`tool_use_summary`),summary:F(),preceding_tool_use_ids:z(F()),uuid:Q(),session_id:F()})),dc=H(()=>M({type:j(`system`),subtype:j(`elicitation_complete`),mcp_server_name:F(),elicitation_id:F(),uuid:Q(),session_id:F()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),fc=H(()=>M({type:j(`prompt_suggestion`),suggestion:F(),uuid:Q(),session_id:F()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>M({sessionId:F().describe(`Unique session identifier (UUID).`),summary:F().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:N().describe(`Last modified time in milliseconds since epoch.`),fileSize:N().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:F().optional().describe(`User-set session title via /rename.`),firstPrompt:F().optional().describe(`First meaningful user prompt in the session.`),gitBranch:F().optional().describe(`Git branch at the end of the session.`),cwd:F().optional().describe(`Working directory for the session.`),tag:F().optional().describe(`User-set session tag.`),createdAt:N().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var pc=H(()=>I([zs(),Is(),Ls(),Ks(),qs(),Js(),Ys(),Xs(),Qs(),$s(),ec(),tc(),nc(),rc(),ic(),oc(),sc(),lc(),cc(),ac(),uc(),Bs(),dc(),fc()])),mc=H(()=>R([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));or(),sr();var hc=H(()=>P()),gc=H(()=>M({matcher:F().optional(),hookCallbackIds:z(F()),timeout:N().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),_c=H(()=>M({subtype:j(`initialize`),hooks:V(To(),z(gc())).optional(),sdkMcpServers:z(F()).optional(),jsonSchema:V(F(),P()).optional(),systemPrompt:F().optional(),appendSystemPrompt:F().optional(),agents:V(F(),Os()).optional(),promptSuggestions:L().optional(),agentProgressSummaries:L().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>M({commands:z(Cs()),agents:z(ws()),output_style:F(),available_output_styles:z(F()),models:z(Ts()),account:Es(),pid:N().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:mc().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var vc=H(()=>M({subtype:j(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),yc=H(()=>M({subtype:j(`can_use_tool`),tool_name:F(),input:V(F(),P()),permission_suggestions:z(xo()).optional(),blocked_path:F().optional(),decision_reason:F().optional(),title:F().optional(),display_name:F().optional(),tool_use_id:F(),agent_id:F().optional(),description:F().optional()}).describe(`Requests permission to use a tool with the given input.`)),bc=H(()=>M({subtype:j(`set_permission_mode`),mode:Co()}).describe(`Sets the permission mode for tool execution handling.`)),xc=H(()=>M({subtype:j(`set_model`),model:F().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),Sc=H(()=>M({subtype:j(`set_max_thinking_tokens`),max_thinking_tokens:N().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Cc=H(()=>M({subtype:j(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>M({mcpServers:z(_o())}).describe(`Response containing the current status of all MCP server connections.`));var wc=H(()=>M({subtype:j(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Tc=H(()=>M({name:F(),tokens:N(),color:F(),isDeferred:L().optional()})),Ec=H(()=>M({color:F(),isFilled:L(),categoryName:F(),tokens:N(),percentage:N(),squareFullness:N()}));H(()=>M({categories:z(Tc()),totalTokens:N(),maxTokens:N(),rawMaxTokens:N(),percentage:N(),gridRows:z(z(Ec())),model:F(),memoryFiles:z(M({path:F(),type:F(),tokens:N()})),mcpTools:z(M({name:F(),serverName:F(),tokens:N(),isLoaded:L().optional()})),deferredBuiltinTools:z(M({name:F(),tokens:N(),isLoaded:L()})).optional(),systemTools:z(M({name:F(),tokens:N()})).optional(),systemPromptSections:z(M({name:F(),tokens:N()})).optional(),agents:z(M({agentType:F(),source:F(),tokens:N()})),slashCommands:M({totalCommands:N(),includedCommands:N(),tokens:N()}).optional(),skills:M({totalSkills:N(),includedSkills:N(),tokens:N(),skillFrontmatter:z(M({name:F(),source:F(),tokens:N()}))}).optional(),autoCompactThreshold:N().optional(),isAutoCompactEnabled:L(),messageBreakdown:M({toolCallTokens:N(),toolResultTokens:N(),attachmentTokens:N(),assistantMessageTokens:N(),userMessageTokens:N(),toolCallsByType:z(M({name:F(),callTokens:N(),resultTokens:N()})),attachmentsByType:z(M({name:F(),tokens:N()}))}).optional(),apiUsage:M({input_tokens:N(),output_tokens:N(),cache_creation_input_tokens:N(),cache_read_input_tokens:N()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var Dc=H(()=>M({subtype:j(`rewind_files`),user_message_id:F(),dry_run:L().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>M({canRewind:L(),error:F().optional(),filesChanged:z(F()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var Oc=H(()=>M({subtype:j(`cancel_async_message`),message_uuid:F()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>M({cancelled:L()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var kc=H(()=>M({subtype:j(`seed_read_state`),path:F(),mtime:N()}).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.`)),Ac=H(()=>M({subtype:j(`hook_callback`),callback_id:F(),input:is(),tool_use_id:F().optional()}).describe(`Delivers a hook callback with its input data.`)),jc=H(()=>M({subtype:j(`mcp_message`),server_name:F(),message:hc()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Mc=H(()=>M({subtype:j(`mcp_set_servers`),servers:V(F(),mo())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>M({added:z(F()),removed:z(F()),errors:V(F(),F())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Nc=H(()=>M({subtype:j(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>M({commands:z(Cs()),agents:z(ws()),plugins:z(M({name:F(),path:F(),source:F().optional()})),mcpServers:z(_o()),error_count:N()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Pc=H(()=>M({subtype:j(`mcp_reconnect`),serverName:F()}).describe(`Reconnects a disconnected or failed MCP server.`)),Fc=H(()=>M({subtype:j(`mcp_toggle`),serverName:F(),enabled:L()}).describe(`Enables or disables an MCP server.`)),Ic=H(()=>M({subtype:j(`stop_task`),task_id:F()}).describe(`Stops a running task.`)),Lc=H(()=>M({subtype:j(`apply_flag_settings`),settings:V(F(),P())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Rc=H(()=>M({subtype:j(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>M({effective:V(F(),P()),sources:z(M({source:R([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:V(F(),P())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:M({model:F()}).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 zc=H(()=>M({subtype:j(`elicitation`),mcp_server_name:F(),message:F(),mode:R([`form`,`url`]).optional(),url:F().optional(),elicitation_id:F().optional(),requested_schema:V(F(),P()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Bc=H(()=>M({action:R([`accept`,`decline`,`cancel`]),content:V(F(),P()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Vc=H(()=>I([vc(),yc(),_c(),bc(),xc(),Sc(),Cc(),wc(),Ac(),jc(),Dc(),Oc(),kc(),Mc(),Nc(),Pc(),Fc(),Ic(),Lc(),Rc(),zc()])),Hc=H(()=>M({type:j(`control_request`),request_id:F(),request:Vc()})),Uc=H(()=>M({subtype:j(`success`),request_id:F(),response:V(F(),P()).optional()})),Wc=H(()=>M({subtype:j(`error`),request_id:F(),error:F(),pending_permission_requests:z(rr(()=>Hc())).optional()})),Gc=H(()=>M({type:j(`control_response`),response:I([Uc(),Wc()])})),Kc=H(()=>M({type:j(`control_cancel_request`),request_id:F()}).describe(`Cancels a currently open control request.`)),qc=H(()=>M({type:j(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Jc=H(()=>M({type:j(`update_environment_variables`),variables:V(F(),F())}).describe(`Updates environment variables at runtime.`));H(()=>I([pc(),Vs(),Hs(),Zs(),Gc(),Hc(),Kc(),qc()])),H(()=>I([Is(),Hc(),Gc(),qc(),Jc()])),Be(),or(),sr(),ce(),v(),H(()=>B.object({tool_name:B.string().describe(`The name of the tool requesting permission`),input:B.record(B.string(),B.unknown()).describe(`The input for the tool`),tool_use_id:B.string().optional().describe(`The unique tool use request ID`)}));var Yc=H(()=>B.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Xc=H(()=>B.object({behavior:B.literal(`allow`),updatedInput:B.record(B.string(),B.unknown()),updatedPermissions:B.array(Gn()).optional().catch(e=>{G(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:B.string().optional(),decisionClassification:Yc()})),Zc=H(()=>B.object({behavior:B.literal(`deny`),message:B.string(),interrupt:B.boolean().optional(),toolUseID:B.string().optional(),decisionClassification:Yc()})),Qc=H(()=>B.union([Xc(),Zc()]));function $c(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:D(e.toolPermissionContext,t)})),yn(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(G(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}xr(),Hr(),Lr(),Vr(),Li(),Ii(),Gi(),lt(),Dn(),x(),Sn(),Ki(),C(),an(),k(),u(),Zi(),S(),se(),w(),De(),ln(),ye(),Se(),vt(),_t(),Vt(),qe();var el=/\u2028|\u2029/g;function tl(e){return e.replace(el,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function nl(e){return tl(Cr(e))}Ar(),Pr(),or(),ce();var rl=`SandboxNetworkAccess`;function il(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 al(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 ol=1e3,sl=class{constructor(e,t){o(this,`input`,void 0),o(this,`replayUserMessages`,void 0),o(this,`structuredInput`,void 0),o(this,`pendingRequests`,new Map),o(this,`restoredWorkerState`,Promise.resolve(null)),o(this,`inputClosed`,!1),o(this,`unexpectedResponseCallback`,void 0),o(this,`resolvedToolUseIds`,new Set),o(this,`prependedLines`,[]),o(this,`onControlRequestSent`,void 0),o(this,`onControlRequestResolved`,void 0),o(this,`outbound`,new Ye),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>ol)){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(`${Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
1
+ import{c as e,i as t,l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{n as a,t as o}from"./defineProperty-C-QyHrDq.js";import{n as s,t as c}from"./axios-DaWTGg7G.js";import{$T as l,$d as u,$l as d,$y as f,A as p,Ab as m,Ai as h,B as g,Bc as ee,Bg as _,Bt as te,C as ne,Cb as re,Cn as v,Di as y,Dx as ie,ES as ae,Eb as b,Ex as oe,Fb as x,Fc as se,Gg as ce,Gs as le,Gv as ue,Hc as S,If as de,Ig as fe,Io as pe,Ix as me,Jn as he,Jv as ge,Kb as _e,Kv as ve,La as ye,Lc as be,Lf as xe,Lg as C,Li as Se,Lv as Ce,Mb as we,Mi as Te,Mo as Ee,Ms as De,Mx as Oe,Nb as ke,Ns as w,Ob as Ae,Pb as je,Pc as Me,Ps as T,QC as Ne,Qd as E,Qn as Pe,Qw as Fe,Qy as Ie,Rc as Le,Ro as Re,Rv as ze,Sn as Be,Th as Ve,Tu as He,Tx as Ue,Ub as We,Uc as Ge,Ug as D,Ur as Ke,V as qe,VS as Je,Vc as Ye,Vg as Xe,Vo as Ze,Vt as Qe,Wb as $e,Wc as O,Xp as k,Xv as et,Yv as tt,ZC as nt,Zd as rt,Zp as it,__ as at,_b as ot,_i as st,_m as ct,aT as lt,af as ut,ai as dt,ax as ft,b as pt,bb as mt,bg as ht,bm as gt,bn as _t,br as vt,cc as yt,co as bt,cs as xt,dT as St,dm as Ct,ds as wt,eb as Tt,ec as Et,ef as Dt,eg as Ot,eu as kt,f as At,fm as jt,fs as Mt,g_ as Nt,ga as Pt,gi as Ft,gm as It,gs as Lt,hT as A,h_ as Rt,hg as zt,hm as Bt,hn as Vt,hs as Ht,hx as Ut,ic as Wt,ii as Gt,io as Kt,jo as qt,js as Jt,jx as Yt,kb as Xt,lc as Zt,lp as Qt,ls as $t,ly as en,mT as tn,m_ as nn,mg as rn,mm as an,ms as on,nc as sn,ni as cn,no as ln,ny as un,o as dn,oS as fn,oT as pn,oy as mn,pg as hn,pm as gn,ps as _n,qc as vn,qg as yn,qs as bn,rf as xn,ry as Sn,s as Cn,sS as wn,sp as Tn,ss as En,tT as Dn,tc as On,tg as kn,ti as An,to as jn,ty as Mn,uT as Nn,um as Pn,uo as Fn,us as In,v as Ln,vm as Rn,vr as zn,vx as Bn,w as Vn,wS as Hn,wh as Un,wm as Wn,wn as Gn,wu as Kn,xm as qn,xn as Jn,xu as Yn,y as Xn,yb as Zn,yg as Qn,ym as $n,yn as er,yr as tr,zi as nr}from"./loadAgentsDir-DaNpxaO-.js";import{C as j,D as M,E as N,F as P,N as F,P as I,S as rr,_ as L,f as R,g as z,h as ir,i as B,j as V,n as H,p as ar,r as or,t as sr,y as cr}from"./lazySchema-DULtBUCI.js";import{J as lr,Kn as ur,Mn as dr,N as fr,Qt as pr,Ut as mr,Wt as hr,ar as gr,ft as U,j as _r,jn as vr,mn as yr,vn as br}from"./state-D5D6QpTX.js";import{n as xr,t as Sr}from"./cwd-Nh5IZNKO.js";import{C as Cr,E as wr,P as W,R as Tr,S as Er,U as Dr,a as Or,c as G,f as kr,i as Ar,nt as jr,tt as Mr,u as Nr,x as Pr}from"./debug-D58GQBDG.js";import{Ln as Fr,W as Ir,_t as Lr,ar as Rr,d as zr,h as Br,rt as Vr,sr as Hr,tt as Ur,u as Wr,ut as Gr,zn as Kr}from"./settings-3xZ0fsvE.js";import{F as qr,M as Jr}from"./config-DRy1I12M.js";import{i as Yr,n as Xr,o as K}from"./process-gEbdy6uY.js";import{A as Zr,O as Qr,k as $r}from"./git-By_J4XJL.js";import{H as ei,c as ti,i as ni,o as ri,q as ii,s as q}from"./log-CZ7ploQm.js";import{s as ai,u as oi}from"./types-APu4OCXJ.js";import{n as si,r as J}from"./analytics-DJobLaWP.js";import{$r as ci,Br as li,C as ui,En as di,J as fi,Pt as pi,Q as mi,Qr as hi,Rr as gi,Tn as _i,U as vi,Y as yi,Z as bi,Zr as xi,_ as Si,dn as Ci,dr as wi,fn as Ti,mt as Ei,o as Di,ti as Oi,u as ki,ur as Ai,x as ji}from"./model-Do0f476p.js";import{_t as Mi,at as Ni,bn as Pi,it as Fi,tn as Ii,vn as Li,vt as Ri,yt as zi}from"./prompt-8u06WVES.js";import{C as Bi,S as Vi,T as Hi,_ as Ui,a as Wi,at as Gi,b as Ki,c as qi,ct as Ji,et as Yi,l as Xi,n as Zi,nt as Qi,o as $i,rt as ea,s as ta,st as na,t as ra}from"./sessionState-CQhbGfmh.js";import{n as ia,t as aa}from"./omit-DO61BHZu.js";import{a as oa,n as sa,t as ca}from"./bridgeConfig-C5L-7KaP.js";import{i as la,n as ua,s as da}from"./mappers-_B-s9fNz.js";import{n as fa,r as pa}from"./sessionTitle-k4wpUS5l.js";import{t as ma}from"./pollConfig-2nFzv6Hy.js";import{t as ha}from"./controlMessageCompat-IFu4Gc1y.js";import{n as ga,t as _a}from"./ccrClient-DO563xlf.js";import{n as va,t as ya}from"./HybridTransport-CJVkWa2u.js";import{n as ba,t as xa}from"./SSETransport-B3K6eH9I.js";import{a as Sa,n as Ca}from"./grove-CYE1Cfcz.js";import{o as wa}from"./remoteManagedSettings-BoOYHzYP.js";import{i as Ta,r as Ea}from"./auth-0rn1U4Eq.js";import{t as Da}from"./pluginBlocklist-xdiUmUpt.js";import{t as Oa}from"./settingsSync-rkWmClKS.js";import{n as ka,t as Aa}from"./toolPool-Df5iUqJ-.js";import{t as ja}from"./onChangeAppState-vKml_lit.js";import{n as Ma,r as Na}from"./QueryEngine-CyGHpX7M.js";import{r as Pa}from"./bridgeStatusUtil-Cex6VowM.js";import{n as Fa,r as Ia}from"./sideQuestion-Ds7Elgs4.js";import{n as La,r as Ra}from"./context-noninteractive-BzDVMnWC.js";import{n as za,r as Ba}from"./modelOptions-B3nis9cC.js";import{a as Va,o as Ha,t as Ua}from"./skillChangeDetector-CtithJ4a.js";import{n as Wa}from"./reconciler-RIKmaPg7.js";import{n as Ga,t as Ka}from"./refresh-CCSCAjgz.js";import{basename as qa,dirname as Ja,join as Ya}from"path";import{PassThrough as Xa}from"stream";import{randomUUID as Y}from"crypto";import{mkdir as Za,readFile as Qa,stat as $a,writeFile as eo}from"fs/promises";import{URL as to}from"url";import{cwd as X}from"process";r(),a(),c(),mr(),Mr(),Tr(),Pr(),kr(),Xr(),Ar(),Qr(),ii(),ri(),Fr(),ai(),Br(),Oi(),li(),wi(),_i(),Ci(),pi(),Si(),Oa(),or(),sr();var no=H(()=>M({inputTokens:N(),outputTokens:N(),cacheReadInputTokens:N(),cacheCreationInputTokens:N(),webSearchRequests:N(),costUSD:N(),contextWindow:N(),maxOutputTokens:N()})),ro=H(()=>j(`json_schema`));H(()=>M({type:ro()}));var io=H(()=>M({type:j(`json_schema`),schema:V(F(),P())}));H(()=>io());var ao=H(()=>R([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>R([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>j(`context-1m-2025-08-07`));var oo=H(()=>M({type:j(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),so=H(()=>M({type:j(`enabled`),budgetTokens:N().optional()}).describe(`Fixed thinking token budget (older models)`)),co=H(()=>M({type:j(`disabled`)}).describe(`No extended thinking`));H(()=>I([oo(),so(),co()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var lo=H(()=>M({type:j(`stdio`).optional(),command:F(),args:z(F()).optional(),env:V(F(),F()).optional()})),uo=H(()=>M({type:j(`sse`),url:F(),headers:V(F(),F()).optional()})),fo=H(()=>M({type:j(`http`),url:F(),headers:V(F(),F()).optional()})),po=H(()=>M({type:j(`sdk`),name:F()})),mo=H(()=>I([lo(),uo(),fo(),po()])),ho=H(()=>M({type:j(`claudeai-proxy`),url:F(),id:F()})),go=H(()=>I([mo(),ho()])),_o=H(()=>M({name:F().describe(`Server name as configured`),status:R([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:M({name:F(),version:F()}).optional().describe(`Server information (available when connected)`),error:F().optional().describe(`Error message (available when status is 'failed')`),config:go().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:F().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:z(M({name:F(),description:F().optional(),annotations:M({readOnly:L().optional(),destructive:L().optional(),openWorld:L().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:M({experimental:V(F(),P()).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(()=>M({added:z(F()).describe(`Names of servers that were added`),removed:z(F()).describe(`Names of servers that were removed`),errors:V(F(),F()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var vo=H(()=>R([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),yo=H(()=>R([`allow`,`deny`,`ask`])),bo=H(()=>M({toolName:F(),ruleContent:F().optional()})),xo=H(()=>cr(`type`,[M({type:j(`addRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`replaceRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`removeRules`),rules:z(bo()),behavior:yo(),destination:vo()}),M({type:j(`setMode`),mode:rr(()=>Co()),destination:vo()}),M({type:j(`addDirectories`),directories:z(F()),destination:vo()}),M({type:j(`removeDirectories`),directories:z(F()),destination:vo()})])),So=H(()=>R([`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([M({behavior:j(`allow`),updatedInput:V(F(),P()).optional(),updatedPermissions:z(xo()).optional(),toolUseID:F().optional(),decisionClassification:So().optional()}),M({behavior:j(`deny`),message:F(),interrupt:L().optional(),toolUseID:F().optional(),decisionClassification:So().optional()})]));var Co=H(()=>R([`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).`)),wo=`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(`.`),To=H(()=>R(wo)),Z=H(()=>M({session_id:F(),transcript_path:F(),cwd:F(),permission_mode:F().optional(),agent_id:F().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:F().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).`)})),Eo=H(()=>Z().and(M({hook_event_name:j(`PreToolUse`),tool_name:F(),tool_input:P(),tool_use_id:F()}))),Do=H(()=>Z().and(M({hook_event_name:j(`PermissionRequest`),tool_name:F(),tool_input:P(),permission_suggestions:z(xo()).optional()}))),Oo=H(()=>Z().and(M({hook_event_name:j(`PostToolUse`),tool_name:F(),tool_input:P(),tool_response:P(),tool_use_id:F()}))),ko=H(()=>Z().and(M({hook_event_name:j(`PostToolUseFailure`),tool_name:F(),tool_input:P(),tool_use_id:F(),error:F(),is_interrupt:L().optional()}))),Ao=H(()=>Z().and(M({hook_event_name:j(`PermissionDenied`),tool_name:F(),tool_input:P(),tool_use_id:F(),reason:F()}))),jo=H(()=>Z().and(M({hook_event_name:j(`Notification`),message:F(),title:F().optional(),notification_type:F()}))),Mo=H(()=>Z().and(M({hook_event_name:j(`UserPromptSubmit`),prompt:F()}))),No=H(()=>Z().and(M({hook_event_name:j(`SessionStart`),source:R([`startup`,`resume`,`clear`,`compact`]),agent_type:F().optional(),model:F().optional()}))),Po=H(()=>Z().and(M({hook_event_name:j(`Setup`),trigger:R([`init`,`maintenance`])}))),Fo=H(()=>Z().and(M({hook_event_name:j(`Stop`),stop_hook_active:L(),last_assistant_message:F().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Io=H(()=>Z().and(M({hook_event_name:j(`StopFailure`),error:Ns(),error_details:F().optional(),last_assistant_message:F().optional()}))),Lo=H(()=>Z().and(M({hook_event_name:j(`SubagentStart`),agent_id:F(),agent_type:F()}))),Ro=H(()=>Z().and(M({hook_event_name:j(`SubagentStop`),stop_hook_active:L(),agent_id:F(),agent_transcript_path:F(),agent_type:F(),last_assistant_message:F().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),zo=H(()=>Z().and(M({hook_event_name:j(`PreCompact`),trigger:R([`manual`,`auto`]),custom_instructions:F().nullable()}))),Bo=H(()=>Z().and(M({hook_event_name:j(`PostCompact`),trigger:R([`manual`,`auto`]),compact_summary:F().describe(`The conversation summary produced by compaction`)}))),Vo=H(()=>Z().and(M({hook_event_name:j(`TeammateIdle`),teammate_name:F(),team_name:F()}))),Ho=H(()=>Z().and(M({hook_event_name:j(`TaskCreated`),task_id:F(),task_subject:F(),task_description:F().optional(),teammate_name:F().optional(),team_name:F().optional()}))),Uo=H(()=>Z().and(M({hook_event_name:j(`TaskCompleted`),task_id:F(),task_subject:F(),task_description:F().optional(),teammate_name:F().optional(),team_name:F().optional()}))),Wo=H(()=>Z().and(M({hook_event_name:j(`Elicitation`),mcp_server_name:F(),message:F(),mode:R([`form`,`url`]).optional(),url:F().optional(),elicitation_id:F().optional(),requested_schema:V(F(),P()).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.`)),Go=H(()=>Z().and(M({hook_event_name:j(`ElicitationResult`),mcp_server_name:F(),elicitation_id:F().optional(),mode:R([`form`,`url`]).optional(),action:R([`accept`,`decline`,`cancel`]),content:V(F(),P()).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.`)),Ko=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],qo=H(()=>Z().and(M({hook_event_name:j(`ConfigChange`),source:R(Ko),file_path:F().optional()}))),Jo=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Yo=[`User`,`Project`,`Local`,`Managed`],Xo=H(()=>Z().and(M({hook_event_name:j(`InstructionsLoaded`),file_path:F(),memory_type:R(Yo),load_reason:R(Jo),globs:z(F()).optional(),trigger_file_path:F().optional(),parent_file_path:F().optional()}))),Zo=H(()=>Z().and(M({hook_event_name:j(`WorktreeCreate`),name:F()}))),Qo=H(()=>Z().and(M({hook_event_name:j(`WorktreeRemove`),worktree_path:F()}))),$o=H(()=>Z().and(M({hook_event_name:j(`CwdChanged`),old_cwd:F(),new_cwd:F()}))),es=H(()=>Z().and(M({hook_event_name:j(`FileChanged`),file_path:F(),event:R([`change`,`add`,`unlink`])}))),ts=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ns=H(()=>R(ts)),rs=H(()=>Z().and(M({hook_event_name:j(`SessionEnd`),reason:ns()}))),is=H(()=>I([Eo(),Oo(),ko(),Ao(),jo(),Mo(),No(),rs(),Fo(),Io(),Lo(),Ro(),zo(),Bo(),Do(),Po(),Vo(),Ho(),Uo(),Wo(),Go(),qo(),Xo(),Zo(),Qo(),$o(),es()])),as=H(()=>M({async:j(!0),asyncTimeout:N().optional()})),os=H(()=>M({hookEventName:j(`PreToolUse`),permissionDecision:yo().optional(),permissionDecisionReason:F().optional(),updatedInput:V(F(),P()).optional(),additionalContext:F().optional()})),ss=H(()=>M({hookEventName:j(`UserPromptSubmit`),additionalContext:F().optional()})),cs=H(()=>M({hookEventName:j(`SessionStart`),additionalContext:F().optional(),initialUserMessage:F().optional(),watchPaths:z(F()).optional()})),ls=H(()=>M({hookEventName:j(`Setup`),additionalContext:F().optional()})),us=H(()=>M({hookEventName:j(`SubagentStart`),additionalContext:F().optional()})),ds=H(()=>M({hookEventName:j(`PostToolUse`),additionalContext:F().optional(),updatedMCPToolOutput:P().optional()})),fs=H(()=>M({hookEventName:j(`PostToolUseFailure`),additionalContext:F().optional()})),ps=H(()=>M({hookEventName:j(`PermissionDenied`),retry:L().optional()})),ms=H(()=>M({hookEventName:j(`Notification`),additionalContext:F().optional()})),hs=H(()=>M({hookEventName:j(`PermissionRequest`),decision:I([M({behavior:j(`allow`),updatedInput:V(F(),P()).optional(),updatedPermissions:z(xo()).optional()}),M({behavior:j(`deny`),message:F().optional(),interrupt:L().optional()})])})),gs=H(()=>M({hookEventName:j(`CwdChanged`),watchPaths:z(F()).optional()})),_s=H(()=>M({hookEventName:j(`FileChanged`),watchPaths:z(F()).optional()})),vs=H(()=>M({continue:L().optional(),suppressOutput:L().optional(),stopReason:F().optional(),decision:R([`approve`,`block`]).optional(),systemMessage:F().optional(),reason:F().optional(),hookSpecificOutput:I([os(),ss(),cs(),ls(),us(),ds(),fs(),ps(),ms(),hs(),ys(),bs(),gs(),_s(),xs()]).optional()})),ys=H(()=>M({hookEventName:j(`Elicitation`),action:R([`accept`,`decline`,`cancel`]).optional(),content:V(F(),P()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),bs=H(()=>M({hookEventName:j(`ElicitationResult`),action:R([`accept`,`decline`,`cancel`]).optional(),content:V(F(),P()).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.`)),xs=H(()=>M({hookEventName:j(`WorktreeCreate`),worktreePath:F()}).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([as(),vs()]));var Ss=H(()=>M({key:F().describe(`Unique key for this option, returned in the response`),label:F().describe(`Display text for this option`),description:F().optional().describe(`Optional description shown below the label`)}));H(()=>M({prompt:F().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:F().describe(`The prompt message to display to the user`),options:z(Ss()).describe(`Available options for the user to choose from`)})),H(()=>M({prompt_response:F().describe(`The request ID from the corresponding prompt request`),selected:F().describe(`The key of the selected option`)}));var Cs=H(()=>M({name:F().describe(`Skill name (without the leading slash)`),description:F().describe(`Description of what the skill does`),argumentHint:F().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),ws=H(()=>M({name:F().describe(`Agent type identifier (e.g., "Explore")`),description:F().describe(`Description of when to use this agent`),model:F().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.`)),Ts=H(()=>M({value:F().describe(`Model identifier to use in API calls`),displayName:F().describe(`Human-readable display name`),description:F().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:L().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:L().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:L().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Es=H(()=>M({email:F().optional(),organization:F().optional(),subscriptionType:F().optional(),tokenSource:F().optional(),apiKeySource:F().optional(),apiProvider:R([`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.`)),Ds=H(()=>I([F(),V(F(),mo())])),Os=H(()=>M({description:F().describe(`Natural language description of when to use this agent`),tools:z(F()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:z(F()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:F().describe(`The agent's system prompt`),model:F().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:z(Ds()).optional(),criticalSystemReminder_EXPERIMENTAL:F().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:z(F()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:F().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:N().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:L().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:R([`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:Co().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(()=>R([`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(()=>M({type:j(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:F().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>M({canRewind:L(),error:F().optional(),filesChanged:z(F()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var ks=H(()=>P()),As=H(()=>P()),js=H(()=>P()),Q=H(()=>F()),Ms=H(()=>P()),Ns=H(()=>R([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ps=H(()=>I([j(`compacting`),ar()])),Fs=H(()=>M({type:j(`user`),message:ks(),parent_tool_use_id:F().nullable(),isSynthetic:L().optional(),tool_use_result:P().optional(),priority:R([`now`,`next`,`later`]).optional(),timestamp:F().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Is=H(()=>Fs().extend({uuid:Q().optional(),session_id:F().optional()})),Ls=H(()=>Fs().extend({uuid:Q(),session_id:F(),isReplay:j(!0)})),Rs=H(()=>M({status:R([`allowed`,`allowed_warning`,`rejected`]),resetsAt:N().optional(),rateLimitType:R([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:N().optional(),overageStatus:R([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:N().optional(),overageDisabledReason:R([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`org_service_zero_credit_limit`,`no_limits_configured`,`unknown`]).optional(),isUsingOverage:L().optional(),surpassedThreshold:N().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),zs=H(()=>M({type:j(`assistant`),message:As(),parent_tool_use_id:F().nullable(),error:Ns().optional(),uuid:Q(),session_id:F()})),Bs=H(()=>M({type:j(`rate_limit_event`),rate_limit_info:Rs(),uuid:Q(),session_id:F()}).describe(`Rate limit event emitted when rate limit info changes.`)),Vs=H(()=>M({type:j(`streamlined_text`),text:F().describe(`Text content preserved from the assistant message`),session_id:F(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Hs=H(()=>M({type:j(`streamlined_tool_use_summary`),tool_summary:F().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:F(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Us=H(()=>M({tool_name:F(),tool_use_id:F(),tool_input:V(F(),P())})),Ws=H(()=>M({type:j(`result`),subtype:j(`success`),duration_ms:N(),duration_api_ms:N(),is_error:L(),num_turns:N(),result:F(),stop_reason:F().nullable(),total_cost_usd:N(),usage:Ms(),modelUsage:V(F(),no()),permission_denials:z(Us()),structured_output:P().optional(),fast_mode_state:mc().optional(),uuid:Q(),session_id:F()})),Gs=H(()=>M({type:j(`result`),subtype:R([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:N(),duration_api_ms:N(),is_error:L(),num_turns:N(),stop_reason:F().nullable(),total_cost_usd:N(),usage:Ms(),modelUsage:V(F(),no()),permission_denials:z(Us()),errors:z(F()),fast_mode_state:mc().optional(),uuid:Q(),session_id:F()})),Ks=H(()=>I([Ws(),Gs()])),qs=H(()=>M({type:j(`system`),subtype:j(`init`),agents:z(F()).optional(),apiKeySource:ao(),betas:z(F()).optional(),claude_code_version:F(),cwd:F(),tools:z(F()),mcp_servers:z(M({name:F(),status:F()})),model:F(),permissionMode:Co(),slash_commands:z(F()),output_style:F(),skills:z(F()),plugins:z(M({name:F(),path:F(),source:F().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:mc().optional(),uuid:Q(),session_id:F()})),Js=H(()=>M({type:j(`stream_event`),event:js(),parent_tool_use_id:F().nullable(),uuid:Q(),session_id:F()})),Ys=H(()=>M({type:j(`system`),subtype:j(`compact_boundary`),compact_metadata:M({trigger:R([`manual`,`auto`]),pre_tokens:N(),preserved_segment:M({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:F()})),Xs=H(()=>M({type:j(`system`),subtype:j(`status`),status:Ps(),permissionMode:Co().optional(),uuid:Q(),session_id:F()})),Zs=H(()=>M({type:j(`system`),subtype:j(`post_turn_summary`),summarizes_uuid:F(),status_category:R([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:F(),is_noteworthy:L(),title:F(),description:F(),recent_action:F(),needs_action:F(),artifact_urls:z(F()),uuid:Q(),session_id:F()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),Qs=H(()=>M({type:j(`system`),subtype:j(`api_retry`),attempt:N(),max_retries:N(),retry_delay_ms:N(),error_status:N().nullable(),error:Ns(),uuid:Q(),session_id:F()}).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.`)),$s=H(()=>M({type:j(`system`),subtype:j(`local_command_output`),content:F(),uuid:Q(),session_id:F()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),ec=H(()=>M({type:j(`system`),subtype:j(`hook_started`),hook_id:F(),hook_name:F(),hook_event:F(),uuid:Q(),session_id:F()})),tc=H(()=>M({type:j(`system`),subtype:j(`hook_progress`),hook_id:F(),hook_name:F(),hook_event:F(),stdout:F(),stderr:F(),output:F(),uuid:Q(),session_id:F()})),nc=H(()=>M({type:j(`system`),subtype:j(`hook_response`),hook_id:F(),hook_name:F(),hook_event:F(),output:F(),stdout:F(),stderr:F(),exit_code:N().optional(),outcome:R([`success`,`error`,`cancelled`]),uuid:Q(),session_id:F()})),rc=H(()=>M({type:j(`tool_progress`),tool_use_id:F(),tool_name:F(),parent_tool_use_id:F().nullable(),elapsed_time_seconds:N(),task_id:F().optional(),uuid:Q(),session_id:F()})),ic=H(()=>M({type:j(`auth_status`),isAuthenticating:L(),output:z(F()),error:F().optional(),uuid:Q(),session_id:F()})),ac=H(()=>M({type:j(`system`),subtype:j(`files_persisted`),files:z(M({filename:F(),file_id:F()})),failed:z(M({filename:F(),error:F()})),processed_at:F(),uuid:Q(),session_id:F()})),oc=H(()=>M({type:j(`system`),subtype:j(`task_notification`),task_id:F(),tool_use_id:F().optional(),status:R([`completed`,`failed`,`stopped`]),output_file:F(),summary:F(),usage:M({total_tokens:N(),tool_uses:N(),duration_ms:N()}).optional(),uuid:Q(),session_id:F()})),sc=H(()=>M({type:j(`system`),subtype:j(`task_started`),task_id:F(),tool_use_id:F().optional(),description:F(),task_type:F().optional(),workflow_name:F().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:F().optional(),uuid:Q(),session_id:F()})),cc=H(()=>M({type:j(`system`),subtype:j(`session_state_changed`),state:R([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:F()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),lc=H(()=>M({type:j(`system`),subtype:j(`task_progress`),task_id:F(),tool_use_id:F().optional(),description:F(),usage:M({total_tokens:N(),tool_uses:N(),duration_ms:N()}),last_tool_name:F().optional(),summary:F().optional(),uuid:Q(),session_id:F()})),uc=H(()=>M({type:j(`tool_use_summary`),summary:F(),preceding_tool_use_ids:z(F()),uuid:Q(),session_id:F()})),dc=H(()=>M({type:j(`system`),subtype:j(`elicitation_complete`),mcp_server_name:F(),elicitation_id:F(),uuid:Q(),session_id:F()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),fc=H(()=>M({type:j(`prompt_suggestion`),suggestion:F(),uuid:Q(),session_id:F()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>M({sessionId:F().describe(`Unique session identifier (UUID).`),summary:F().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:N().describe(`Last modified time in milliseconds since epoch.`),fileSize:N().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:F().optional().describe(`User-set session title via /rename.`),firstPrompt:F().optional().describe(`First meaningful user prompt in the session.`),gitBranch:F().optional().describe(`Git branch at the end of the session.`),cwd:F().optional().describe(`Working directory for the session.`),tag:F().optional().describe(`User-set session tag.`),createdAt:N().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var pc=H(()=>I([zs(),Is(),Ls(),Ks(),qs(),Js(),Ys(),Xs(),Qs(),$s(),ec(),tc(),nc(),rc(),ic(),oc(),sc(),lc(),cc(),ac(),uc(),Bs(),dc(),fc()])),mc=H(()=>R([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));or(),sr();var hc=H(()=>P()),gc=H(()=>M({matcher:F().optional(),hookCallbackIds:z(F()),timeout:N().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),_c=H(()=>M({subtype:j(`initialize`),hooks:V(To(),z(gc())).optional(),sdkMcpServers:z(F()).optional(),jsonSchema:V(F(),P()).optional(),systemPrompt:F().optional(),appendSystemPrompt:F().optional(),agents:V(F(),Os()).optional(),promptSuggestions:L().optional(),agentProgressSummaries:L().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>M({commands:z(Cs()),agents:z(ws()),output_style:F(),available_output_styles:z(F()),models:z(Ts()),account:Es(),pid:N().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:mc().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var vc=H(()=>M({subtype:j(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),yc=H(()=>M({subtype:j(`can_use_tool`),tool_name:F(),input:V(F(),P()),permission_suggestions:z(xo()).optional(),blocked_path:F().optional(),decision_reason:F().optional(),title:F().optional(),display_name:F().optional(),tool_use_id:F(),agent_id:F().optional(),description:F().optional()}).describe(`Requests permission to use a tool with the given input.`)),bc=H(()=>M({subtype:j(`set_permission_mode`),mode:Co()}).describe(`Sets the permission mode for tool execution handling.`)),xc=H(()=>M({subtype:j(`set_model`),model:F().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),Sc=H(()=>M({subtype:j(`set_max_thinking_tokens`),max_thinking_tokens:N().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Cc=H(()=>M({subtype:j(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>M({mcpServers:z(_o())}).describe(`Response containing the current status of all MCP server connections.`));var wc=H(()=>M({subtype:j(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Tc=H(()=>M({name:F(),tokens:N(),color:F(),isDeferred:L().optional()})),Ec=H(()=>M({color:F(),isFilled:L(),categoryName:F(),tokens:N(),percentage:N(),squareFullness:N()}));H(()=>M({categories:z(Tc()),totalTokens:N(),maxTokens:N(),rawMaxTokens:N(),percentage:N(),gridRows:z(z(Ec())),model:F(),memoryFiles:z(M({path:F(),type:F(),tokens:N()})),mcpTools:z(M({name:F(),serverName:F(),tokens:N(),isLoaded:L().optional()})),deferredBuiltinTools:z(M({name:F(),tokens:N(),isLoaded:L()})).optional(),systemTools:z(M({name:F(),tokens:N()})).optional(),systemPromptSections:z(M({name:F(),tokens:N()})).optional(),agents:z(M({agentType:F(),source:F(),tokens:N()})),slashCommands:M({totalCommands:N(),includedCommands:N(),tokens:N()}).optional(),skills:M({totalSkills:N(),includedSkills:N(),tokens:N(),skillFrontmatter:z(M({name:F(),source:F(),tokens:N()}))}).optional(),autoCompactThreshold:N().optional(),isAutoCompactEnabled:L(),messageBreakdown:M({toolCallTokens:N(),toolResultTokens:N(),attachmentTokens:N(),assistantMessageTokens:N(),userMessageTokens:N(),toolCallsByType:z(M({name:F(),callTokens:N(),resultTokens:N()})),attachmentsByType:z(M({name:F(),tokens:N()}))}).optional(),apiUsage:M({input_tokens:N(),output_tokens:N(),cache_creation_input_tokens:N(),cache_read_input_tokens:N()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var Dc=H(()=>M({subtype:j(`rewind_files`),user_message_id:F(),dry_run:L().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>M({canRewind:L(),error:F().optional(),filesChanged:z(F()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var Oc=H(()=>M({subtype:j(`cancel_async_message`),message_uuid:F()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>M({cancelled:L()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var kc=H(()=>M({subtype:j(`seed_read_state`),path:F(),mtime:N()}).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.`)),Ac=H(()=>M({subtype:j(`hook_callback`),callback_id:F(),input:is(),tool_use_id:F().optional()}).describe(`Delivers a hook callback with its input data.`)),jc=H(()=>M({subtype:j(`mcp_message`),server_name:F(),message:hc()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Mc=H(()=>M({subtype:j(`mcp_set_servers`),servers:V(F(),mo())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>M({added:z(F()),removed:z(F()),errors:V(F(),F())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Nc=H(()=>M({subtype:j(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>M({commands:z(Cs()),agents:z(ws()),plugins:z(M({name:F(),path:F(),source:F().optional()})),mcpServers:z(_o()),error_count:N()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Pc=H(()=>M({subtype:j(`mcp_reconnect`),serverName:F()}).describe(`Reconnects a disconnected or failed MCP server.`)),Fc=H(()=>M({subtype:j(`mcp_toggle`),serverName:F(),enabled:L()}).describe(`Enables or disables an MCP server.`)),Ic=H(()=>M({subtype:j(`stop_task`),task_id:F()}).describe(`Stops a running task.`)),Lc=H(()=>M({subtype:j(`apply_flag_settings`),settings:V(F(),P())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Rc=H(()=>M({subtype:j(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>M({effective:V(F(),P()),sources:z(M({source:R([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:V(F(),P())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:M({model:F()}).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 zc=H(()=>M({subtype:j(`elicitation`),mcp_server_name:F(),message:F(),mode:R([`form`,`url`]).optional(),url:F().optional(),elicitation_id:F().optional(),requested_schema:V(F(),P()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Bc=H(()=>M({action:R([`accept`,`decline`,`cancel`]),content:V(F(),P()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Vc=H(()=>I([vc(),yc(),_c(),bc(),xc(),Sc(),Cc(),wc(),Ac(),jc(),Dc(),Oc(),kc(),Mc(),Nc(),Pc(),Fc(),Ic(),Lc(),Rc(),zc()])),Hc=H(()=>M({type:j(`control_request`),request_id:F(),request:Vc()})),Uc=H(()=>M({subtype:j(`success`),request_id:F(),response:V(F(),P()).optional()})),Wc=H(()=>M({subtype:j(`error`),request_id:F(),error:F(),pending_permission_requests:z(rr(()=>Hc())).optional()})),Gc=H(()=>M({type:j(`control_response`),response:I([Uc(),Wc()])})),Kc=H(()=>M({type:j(`control_cancel_request`),request_id:F()}).describe(`Cancels a currently open control request.`)),qc=H(()=>M({type:j(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Jc=H(()=>M({type:j(`update_environment_variables`),variables:V(F(),F())}).describe(`Updates environment variables at runtime.`));H(()=>I([pc(),Vs(),Hs(),Zs(),Gc(),Hc(),Kc(),qc()])),H(()=>I([Is(),Hc(),Gc(),qc(),Jc()])),Be(),or(),sr(),ce(),v(),H(()=>B.object({tool_name:B.string().describe(`The name of the tool requesting permission`),input:B.record(B.string(),B.unknown()).describe(`The input for the tool`),tool_use_id:B.string().optional().describe(`The unique tool use request ID`)}));var Yc=H(()=>B.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Xc=H(()=>B.object({behavior:B.literal(`allow`),updatedInput:B.record(B.string(),B.unknown()),updatedPermissions:B.array(Gn()).optional().catch(e=>{G(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:B.string().optional(),decisionClassification:Yc()})),Zc=H(()=>B.object({behavior:B.literal(`deny`),message:B.string(),interrupt:B.boolean().optional(),toolUseID:B.string().optional(),decisionClassification:Yc()})),Qc=H(()=>B.union([Xc(),Zc()]));function $c(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:D(e.toolPermissionContext,t)})),yn(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(G(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}xr(),Hr(),Lr(),Vr(),Li(),Ii(),Gi(),lt(),Dn(),x(),Sn(),Ki(),C(),an(),k(),u(),Zi(),S(),se(),w(),De(),ln(),ye(),Se(),vt(),_t(),Vt(),qe();var el=/\u2028|\u2029/g;function tl(e){return e.replace(el,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function nl(e){return tl(Cr(e))}Ar(),Pr(),or(),ce();var rl=`SandboxNetworkAccess`;function il(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 al(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 ol=1e3,sl=class{constructor(e,t){o(this,`input`,void 0),o(this,`replayUserMessages`,void 0),o(this,`structuredInput`,void 0),o(this,`pendingRequests`,new Map),o(this,`restoredWorkerState`,Promise.resolve(null)),o(this,`inputClosed`,!1),o(this,`unexpectedResponseCallback`,void 0),o(this,`resolvedToolUseIds`,new Set),o(this,`prependedLines`,[]),o(this,`onControlRequestSent`,void 0),o(this,`onControlRequestResolved`,void 0),o(this,`outbound`,new Ye),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>ol)){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(`${Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
2
2
  `);if(t===-1)break;let n=e.slice(0,t);e=e.slice(t+1);let r=await this.processLine(n);r&&($r(`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=ha(Er(e));if(t.type===`keep_alive`)return;if(t.type===`update_environment_variables`){let e=t.variables??{},n=Object.keys(e);for(let[t,n]of Object.entries(e))process.env[t]=n;G(`[structuredIO] applied update_environment_variables: ${n.join(`, `)}`);return}if(t.type===`control_response`){let e=`uuid`in t&&typeof t.uuid==`string`?t.uuid:void 0;e&&Bt(e,`completed`);let n=t.response,r=this.pendingRequests.get(n.request_id);if(!r){let e=(n.subtype===`success`?n.response:void 0)?.toolUseID;if(typeof e==`string`&&this.resolvedToolUseIds.has(e)){G(`Ignoring duplicate control_response for already-resolved toolUseID=${e} request_id=${n.request_id}`);return}this.unexpectedResponseCallback&&await this.unexpectedResponseCallback(t);return}if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n.request_id),r.request.request.subtype===`can_use_tool`&&this.onControlRequestResolved&&this.onControlRequestResolved(n.request_id),n.subtype===`error`){r.reject(Error(n.error??`Unknown error`));return}let i=n.response;if(r.schema)try{r.resolve(r.schema.parse(i))}catch(e){r.reject(e)}else r.resolve({});return this.replayUserMessages?t:void 0}if(t.type!==`user`&&t.type!==`control_request`&&t.type!==`assistant`&&t.type!==`system`){G(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||cl(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&cl(`Error: Expected message role 'user', got '${t.message?.role}'`),t)}catch(t){console.error(`Error parsing streaming input line: ${e}: ${t}`),process.exit(1)}}async write(e){K(`${nl(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 wr))};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 g(t,n,r,i,a);if(s.behavior===`allow`||s.behavior===`deny`)return s;let c=new AbortController,l=r.abortController.signal,u=()=>c.abort();l.addEventListener(`abort`,u,{once:!0});try{let i=ll(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=Y();e?.(al(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:il(s.decisionReason),tool_use_id:a,agent_id:r.agentId},Qc(),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):$c((await l).result,t,n,r):$c(u.result,t,n,r)}catch(e){return $c({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&$i(`running`),l.removeEventListener(`abort`,u)}}}createHookCallback(e,t){return{type:`callback`,timeout:t,callback:async(t,n,r)=>{try{return await this.sendRequest({subtype:`hook_callback`,callback_id:e,input:t,tool_use_id:n||void 0},Jn(),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},Bc(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:rl,input:{host:e.host},tool_use_id:Y(),description:`Allow network connection to ${e.host}?`},Qc())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},M({mcp_response:ir()}))).mcp_response}};function cl(e){console.error(e),process.exit(1)}async function ll(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=Qe(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){yn(i);let e=D(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`}}}}Bi(),ba();function ul(e,t={},r,i){if(n(process.env.CLAUDE_CODE_USE_CCR_V2)){let n=new to(e.href);return n.protocol===`wss:`?n.protocol=`https:`:n.protocol===`ws:`&&(n.protocol=`http:`),n.pathname=`${n.pathname.replace(/\/$/,``)}/worker/events/stream`,new xa(n,t,r,i)}if(e.protocol===`ws:`||e.protocol===`wss:`)return n(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)?new ya(e,t,r,i):new va(e,t,r,i);throw Error(`Unsupported protocol: ${e.protocol}`)}an(),Ar(),Qr(),r(),Tr(),Xr(),Zi(),ba(),a();var dl=class extends sl{constructor(e,t,r){let i=new Xa({encoding:`utf8`});super(i,r),o(this,`url`,void 0),o(this,`transport`,void 0),o(this,`inputStream`,void 0),o(this,`isBridge`,!1),o(this,`isDebug`,!1),o(this,`ccrClient`,null),o(this,`keepAliveTimer`,null),this.inputStream=i,this.url=new to(e);let a={},s=Vi();s?a.Authorization=`Bearer ${s}`:G(`[remote-io] No session ingress token available`,{level:`error`});let c=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;c&&(a[`x-environment-runner-version`]=c);let l=()=>{let e={},t=Vi();t&&(e.Authorization=`Bearer ${t}`);let n=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;return n&&(e[`x-environment-runner-version`]=n),e};if(this.transport=ul(this.url,a,U(),l),this.isBridge=process.env.CLAUDE_CODE_ENVIRONMENT_KIND===`bridge`,this.isDebug=Or(),this.transport.setOnData(e=>{this.inputStream.write(e),this.isBridge&&this.isDebug&&K(e.endsWith(`
3
3
  `)?e:`${e}\n`)}),this.transport.setOnClose(()=>{this.inputStream.end()}),n(process.env.CLAUDE_CODE_USE_CCR_V2)){if(!(this.transport instanceof xa))throw Error(`CCR v2 requires SSETransport; check getTransportForUrl`);this.ccrClient=new _a(this.transport,this.url);let e=this.ccrClient.initialize();this.restoredWorkerState=e.catch(()=>null),e.catch(e=>{$r(`error`,`cli_worker_lifecycle_init_failed`,{reason:e instanceof ga?e.reason:`unknown`}),q(Error(`CCRClient initialization failed: ${W(e)}`)),rt(1,`other`)}),jr(async()=>this.ccrClient?.close()),st((e,t,n)=>this.ccrClient.writeInternalEvent(e,t,n)),Ft(()=>this.ccrClient.readInternalEvents(),()=>this.ccrClient.readSubagentInternalEvents());let t={started:`processing`,completed:`processed`};It((e,n)=>{this.ccrClient?.reportDelivery(e,t[n])}),Xi((e,t)=>{this.ccrClient?.reportState(e,t)}),qi(e=>{this.ccrClient?.reportMetadata(e)},{replayCurrent:!0})}this.transport.connect();let u=ma().session_keepalive_interval_v2_ms;if(this.isBridge&&u>0&&(this.keepAliveTimer=setInterval(()=>{G(`[remote-io] keep_alive sent`),this.write({type:`keep_alive`}).catch(e=>{G(`[remote-io] keep_alive write failed: ${W(e)}`)})},u),this.keepAliveTimer.unref?.()),jr(async()=>this.close()),t){let e=this.inputStream;(async()=>{for await(let n of t)e.write(`${String(n).replace(/\n$/,``)}\n`)})()}}flushInternalEvents(){return this.ccrClient?.flushInternalEvents()??Promise.resolve()}get internalEventsPending(){return this.ccrClient?.internalEventsPending??0}async write(e){this.ccrClient?await this.ccrClient.writeEvent(e):await this.transport.write(e),this.isBridge&&(e.type===`control_request`||this.isDebug)&&K(`${nl(e)}\n`)}close(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=null),this.transport.close(),this.inputStream.end()}};Mi(),Ir(),zi(),[...Ri],Mr(),Ar();var fl=`[stdout-guard]`,pl=!1,$=``,ml=null;function hl(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function gl(){pl||(pl=!0,ml=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(`
4
4
  `))!==-1;){let e=$.slice(0,i);$=$.slice(i+1),hl(e)?a=ml(`${e}\n`):(process.stderr.write(`${fl} ${e}\n`),G(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a}),jr(async()=>{$.length>0&&(ml&&hl($)?ml(`${$}\n`):process.stderr.write(`${fl} ${$}\n`),$=``),ml&&(process.stdout.write=ml,ml=null),pl=!1}))}Jr(),Nn(),Hi(),Yt(),Bn(),f(),Ni(),nn(),_(),ht(),Kn(),vn(),bn(),on(),pe(),bt(),dn(),Aa(),Yn(),Tr(),ri(),Bi(),l(),Ar(),u();function _l(e){let t=process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY,n=t?parseInt(t,10):null,r=n&&!isNaN(n)&&n>0,i=null,a=0;return{start(){i&&(clearTimeout(i),i=null),r&&(a=Date.now(),i=setTimeout(()=>{let t=Date.now()-a;e()&&t>=n&&(G(`Exiting after ${n}ms of idle time`),E())},n))},stop(){i&&(clearTimeout(i),i=null)}}}aa(),tn(),wn(),xn(),Ne();function vl(e){if(e.type!==`user`)return;let t=e.message?.content;if(!t||Array.isArray(t)&&t.length===0)return;let n=`uuid`in e&&typeof e.uuid==`string`?e.uuid:void 0;return{content:Array.isArray(t)?yl(t):t,uuid:n}}function yl(e){return e.some(bl)?e.map(e=>{if(!bl(e))return e;let t=e.source,n=typeof t.mediaType==`string`&&t.mediaType?t.mediaType:nt(e.source.data);return{...e,source:{type:`base64`,media_type:n,data:e.source.data}}}):e}function bl(e){return e.type!==`image`||e.source?.type!==`base64`?!1:!e.source.media_type}or(),mr(),Ar(),r(),sr(),oa();var xl=3e4;function Sl(e){G(`[bridge:inbound-attach] ${e}`)}var Cl=H(()=>M({file_uuid:F(),file_name:F()})),wl=H(()=>z(Cl()));function Tl(e){if(typeof e!=`object`||!e||!(`file_attachments`in e))return[];let t=wl().safeParse(e.file_attachments);return t.success?t.data:[]}function El(e){return qa(e).replace(/[^a-zA-Z0-9._-]/g,`_`)||`attachment`}function Dl(){return Ya(t(),`uploads`,U())}async function Ol(e){let t=ca();if(!t){Sl(`skip: no oauth token`);return}let n;try{let r=`${sa()}/api/oauth/files/${encodeURIComponent(e.file_uuid)}/content`,i=await s.get(r,{headers:{Authorization:`Bearer ${t}`},responseType:`arraybuffer`,timeout:xl,validateStatus:()=>!0});if(i.status!==200){Sl(`fetch ${e.file_uuid} failed: status=${i.status}`);return}n=Buffer.from(i.data)}catch(t){Sl(`fetch ${e.file_uuid} threw: ${t}`);return}let r=El(e.file_name),i=(e.file_uuid.slice(0,8)||Y().slice(0,8)).replace(/[^a-zA-Z0-9_-]/g,`_`),a=Dl(),o=Ya(a,`${i}-${r}`);try{await Za(a,{recursive:!0}),await eo(o,n)}catch(e){Sl(`write ${o} failed: ${e}`);return}return Sl(`resolved ${e.file_uuid} → ${o} (${n.length} bytes)`),o}async function kl(e){if(e.length===0)return``;Sl(`resolving ${e.length} attachment(s)`);let t=(await Promise.all(e.map(Ol))).filter(e=>e!==void 0);return t.length===0?``:`${t.map(e=>`@"${e}"`).join(` `)} `}function Al(e,t){if(!t)return e;if(typeof e==`string`)return t+e;let n=e.findLastIndex(e=>e.type===`text`);if(n!==-1){let r=e[n];if(r.type===`text`)return[...e.slice(0,n),{...r,text:t+r.text},...e.slice(n+1)]}return[...e,{type:`text`,text:t.trimEnd()}]}async function jl(e,t){let n=Tl(e);return n.length===0?t:Al(t,await kl(n))}fi(),Ce(),kn(),Zt(),Et(),pt(),pa(),Fa();function Ml(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(it(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}xi(),Je(),We(),m(),b(),Ve(),Wn(),gt(),jt(),Tn(),be(),ua(),Ra(),Ba(),Ar(),Pr();async function Nl(){try{let e=await Qa(wt(),`utf-8`),t=Gr().safeParse(Er(e));return t.success?t.data:(G(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function Pl(e){await En(wt(),Cr(e,null,2))}async function Fl(e,t){let n=In();if(!n)return;let r=await Il(t);r!==null&&await En(Ya(n,$t(e)),r)}async function Il(e){let t=[Ya(e,`.claude-plugin`,`marketplace.json`),Ya(e,`marketplace.json`),e];for(let e of t)try{return await Qa(e,`utf-8`)}catch{}return null}async function Ll(){let e=await Re();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await Fl(t,n.installLocation)}catch(e){G(`Failed to save marketplace JSON for ${t}: ${e}`)}await Pl({...await Nl(),...e})}si(),Mr(),Ar(),Qr(),ri(),pe(),on();async function Rl(){let e=Lt();G(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await Ze();t&&(qt(),Kt(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Nr().mkdir(Mt()),await Nr().mkdir(_n()));let n=Object.keys(Ee()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)G(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Zr(`headless_marketplace_reconcile`,()=>Wa({skip:e?(e,t)=>!Ht(t):void 0,onProgress:e=>{e.type===`installed`?G(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&G(`installPluginsForHeadless: failed to install marketplace ${e.name}: ${e.error}`)}}),e=>({installed_count:e.installed.length,updated_count:e.updated.length,failed_count:e.failed.length,skipped_count:e.skipped.length}));t.skipped.length>0&&G(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(qt(),Kt(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Ll();let t=await Da();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&Kt(`headlessPluginInstall: plugins changed`),e&&jr(xt),i}catch(e){return q(e),!1}finally{J(`tengu_headless_plugin_install`,r)}}si(),Ar(),Qr(),an(),Zi(),ri(),Xr(),k(),u(),Mr(),xr(),qe(),mr(),vt(),Vt(),ye(),Pr(),r(),Ka(),bt(),ve(),de(),d(),Tr();var zl=1e4,Bl=new Set,Vl=[];function Hl(e){if(Bl.has(e))return!1;if(Bl.add(e),Vl.push(e),Vl.length>zl){let e=Vl.splice(0,Vl.length-zl);for(let t of e)Bl.delete(t)}return!0}function Ul(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Wl(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
@@ -9,6 +9,6 @@ import{c as e,i as t,l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{n
9
9
  `),E(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
10
10
  `),E(1);return}let _=O(d.mcp.tools,d.toolPermissionContext),te=[...a,..._],ne=Yl(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>t().mcp.tools,e=>{r(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),$i(`requires_action`,e)});c.permissionPromptToolName&&(te=te.filter(e=>!Pi(e,c.permissionPromptToolName))),Yr(),Pn(`after_loadInitialMessages`),await gi(),Pn(`after_modelStrings`);let re=c.outputFormat===`json`&&c.verbose,v=[],y;Pn(`before_runHeadlessStreaming`);for await(let e of ql(l,d.mcp.clients,[...i,...d.mcp.commands],te,f,ne,o,t,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`&&(re&&v.push(e),y=e);switch(c.outputFormat){case`json`:if(y?.type!==`result`)throw Error(`No messages returned`);if(c.verbose){K(`${Cr(v)}\n`);break}K(`${Cr(y)}\n`);break;case`stream-json`:break;default:if(y?.type!==`result`)throw Error(`No messages returned`);switch(y.subtype){case`success`:K(y.result.endsWith(`
11
11
  `)?y.result:`${y.result}\n`);break;case`error_during_execution`:K(`Execution error`);break;case`error_max_turns`:K(`Error: Reached max turns (${c.maxTurns}).\nTip: Increase the limit with --max-turns or continue in a new session.`);break;case`error_max_budget_usd`:K(`Error: Exceeded USD budget ($${c.maxBudgetUsd}).\nTip: Increase the limit with --max-budget-usd or start a new session to continue.`);break;case`error_max_structured_output_retries`:K(`Error: Failed to provide valid structured output after maximum retries.
12
- Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(gn(),qr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-B_8wZpXA.js`);await e()}catch{}E(y?.type===`result`&&y?.is_error?1:0)}function ql(t,r,a,o,s,c,l,u,d,f,p,m){let g=!1,_,ne=!1,re=null,v,b=t.outbound;process.on(`SIGINT`,()=>{$r(`info`,`shutdown_signal`,{signal:`SIGINT`}),v&&!v.signal.aborted&&v.abort(),rt(0)}),jr(async()=>{let e={};for(let t of ue(u()))xe(t)&&(e[t.type]=(e[t.type]??0)+1);$r(`info`,`run_state_at_shutdown`,{run_active:g,run_phase:_,worker_status:ra(),internal_events_pending:t.internalEventsPending,bg_tasks:e})}),ta(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&b.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let x={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},se;p.enableAuthStatus&&(se=Ai.getInstance().subscribe(e=>{b.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}));let ce=e=>{let t=da(e);t&&b.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};ze.add(ce);let S=s,de=le(s,X(),100),fe=Ie(100),pe=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;m&&m.kind!==`none`&&pe&&(G(`[print.ts] Auto-resuming interrupted turn (kind: ${m.kind})`),eu(S,m.message),et({mode:`prompt`,value:m.message.message.content,uuid:Y()}));let ve=za().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?Di():ui(t),r=Qt(n),i=mi(e.value),a=di(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),ye=p.userSpecifiedModel;function be(e,t){let n=Pt(e,ji(t));S.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&b.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:U(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let C=[],Se=[],Ce=new Set;function Ee(e){for(let n of e){if(n.type!==`connected`||Ce.has(n.name)||n.config.type===`sdk`)continue;let e=n.name;try{n.client.setRequestHandler(Hn,async(n,r)=>{ti(e,`Elicitation request received in print mode: ${Cr(n)}`);let i=n.params.mode===`url`?`url`:`form`;J(`tengu_mcp_elicitation_shown`,{mode:i});let a=await we(e,n.params,r.signal);if(a)return ti(e,`Elicitation resolved by hook: ${Cr(a)}`),J(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in n.params?n.params.url:void 0,s=`requestedSchema`in n.params?n.params.requestedSchema:void 0,c=`elicitationId`in n.params?n.params.elicitationId:void 0,l=await t.handleElicitation(e,n.params.message,s,r.signal,i,o,c),u=await ke(e,l,r.signal,i,c);return J(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),n.client.setNotificationHandler(ae,t=>{let{elicitationId:n}=t.params;ti(e,`Elicitation completion notification: ${n}`),te({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),b.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),Ce.add(e)}catch{}}}async function De(){let e=new Set(Object.keys(l)),n=new Set(C.map(e=>e.name)),r=Array.from(e).some(e=>!n.has(e)),i=Array.from(n).some(t=>!e.has(t)),a=C.some(e=>e.type===`pending`),o=C.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of C)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await Xt(l,(e,n)=>t.sendMcpMessage(e,n));C=r.clients,Se=r.tools;let i=Kr([...n,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Ur(t)))),...Se]}})),Xe(C)}}De();let w={clients:[],tools:[],configs:{}},Me=e=>{let t=Ge(e.toolPermissionContext,e.mcp.tools),n=St(ka([...o,...Se,...w.tools],t,e.toolPermissionContext.mode),`name`);p.permissionPromptToolName&&(n=n.filter(e=>!Pi(e,p.permissionPromptToolName)));let r=fr();if(r&&!p.jsonSchema){let e=Fi(r);`tool`in e&&(n=[...n,e.tool])}return n},T=null,Ne=0;function Pe(){if(!T)return;let e=Math.min(Ne,S.length),t=S.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);Ne=S.length,t.length>0&&T.writeMessages(t)}let Fe=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Re(e){let t=async()=>{let t=new Set(C.map(e=>e.name)),n=await au(e,{configs:l,clients:C,tools:Se},w,d);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),C=n.newSdkState.clients,Se=n.newSdkState.tools,w=n.newDynamicState,n.sdkServersChanged){let e=new Set(C.map(e=>e.name)),n=Kr([...t,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Ur(t)))),...Se]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Fe=Fe.then(t,t),Fe}function Be(){let e=u(),t=e.mcp.clients,n=St([...e.mcp.tools,...w.tools],`name`),r=new Set([...t.map(e=>e.name),...C.map(e=>e.name)]);return[...t,...C,...w.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers,oauth:e.config.oauth};else if(e.config.type===`claudeai-proxy`)t={type:`claudeai-proxy`,url:e.config.url,id:e.config.id};else if(e.config.type===`stdio`||e.config.type===void 0){let n=e.config;t={type:`stdio`,command:n.command,args:n.args}}let r=e.type===`connected`?Ut(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 Ve(){try{await Promise.all([Promise.resolve(),Zr(`headless_managed_settings_wait`,()=>wa())]),await Rl()&&await Je()}catch(e){q(e)}}let He=null;i()||(n(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?He=Ve():Ve());let Ue=_l(()=>!g),We=a,D=f;async function qe(){let{agentDefinitions:e}=await Ga(d);We=await Te(X());let t=D.filter(e=>e.source===`flagSettings`);D=[...e.allAgents,...t]}async function Je(){let{servers:e}=await oe(),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 Re(t);r&&De(),G(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Ye=Ua.subscribe(()=>{y(),Te(X()).then(e=>{We=e})}),Ze=()=>{setTimeout(()=>{!na()||Ji()||ne||(async()=>{let e=await qn({basePrompt:`<${ei}>${new Date().toLocaleTimeString()}</${ei}>`,currentDir:X(),shouldCreate:()=>!ne});if(ne){await ct({commands:e});return}for(let t of e)et({...t,uuid:Y()});Qe()})().catch(e=>{q(e),G(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};en(()=>{v&&Mn(`now`).length>0&&v.abort(`interrupt`)});let Qe=async()=>{if(g)return;if(g=!0,_=void 0,$i(`running`),Ue.stop(),Pn(`run_entry`),await De(),Pn(`after_updateSdkMcp`),He){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Ti(e).then(()=>`timeout`);await Promise.race([He,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 He;He=null,await qe();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-DrNVtTBq.js`);t()}let n=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=ge(n);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;Gl(r,mn(n));)i.push(ge(n));let a=await Rn(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Wl(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(p.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&b.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:U(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=u(),l=[...s.mcp.clients,...C,...w.clients];Ee(l);let f=Me(s);for(let e of o)Bt(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&b.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let m=r.value,h=a.claimedCommands;if(t instanceof dl&&r.mode===`prompt`&&J(`tengu_bridge_message_received`,{is_repl:!1}),x.abortController?.abort(),x.abortController=null,x.pendingSuggestion=null,x.pendingLastEmittedEntry=null,x.lastEmitted&&r.mode===`prompt`){let e=typeof m==`string`?m:m.find(e=>e.type===`text`)?.text;typeof e==`string`&&On(x.lastEmitted.text,e,x.lastEmitted.emittedAt,x.lastEmitted.promptId,x.lastEmitted.generationRequestId),x.lastEmitted=null}v=je(),Pn(`before_ask`),ee();let g=r,_=!1;try{if(await hi(g.workload??p.workload,async()=>{for await(let e of Ma({commands:St([...We,...s.mcp.commands],`name`),prompt:m,promptUuid:g.uuid,isMeta:g.isMeta,cwd:X(),tools:f,verbose:p.verbose,mcpClients:l,thinkingConfig:p.thinkingConfig,maxTurns:p.maxTurns,maxBudgetUsd:p.maxBudgetUsd,taskBudget:p.taskBudget,canUseTool:c,userSpecifiedModel:ye,fallbackModel:p.fallbackModel,jsonSchema:fr()??p.jsonSchema,mutableMessages:S,getReadFileCache:()=>fe.size===0?de:Tt(de,fe),setReadFileCache:e=>{de=e;for(let[e,t]of fe.entries()){let n=de.get(e);(!n||t.timestamp>n.timestamp)&&de.set(e,t)}fe.clear()},customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,getAppState:u,setAppState:d,abortController:v,replayUserMessages:p.replayUserMessages,includePartialMessages:p.includePartialMessages,handleElicitation:(e,n,r)=>t.handleElicitation(e,n.message,void 0,r,n.mode,n.url,`elicitationId`in n?n.elicitationId:void 0),agents:D,orphanedPermission:g.orphanedPermission,setSDKStatus:e=>{b.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(Pe(),e.type===`result`){_=!!e.is_error;for(let e of Ui())b.enqueue(e);ue(u()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&xe(e))?re=e:(re=null,b.enqueue(e))}else{for(let e of Ui())b.enqueue(e);b.enqueue(e)}}),_)await $n({commands:h,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:g.workload??p.workload});else{let e=await $n({commands:h,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:g.workload??p.workload});for(let t of e)et({...t,uuid:Y()})}}catch(e){throw await $n({commands:h,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:g.workload??p.workload}),e}for(let e of o)Bt(e,`completed`);if(Pe(),T?.sendResult(),p.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){x.abortController?.abort();let e=new AbortController;x.abortController=e;let t=yt();if(!t)sn(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await Wt(e,S,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};re?(x.pendingSuggestion=r,x.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(x.lastEmitted=i,b.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){sn(`aborted`,void 0,void 0,`sdk`);return}q(Dr(e))}finally{x.inflightPromise===n.promise&&(x.inflightPromise=null)}})(),x.inflightPromise=n.promise}}gn(),Le(),Ct()}};do{for(let e of Ui())b.enqueue(e);_=`draining_commands`,await a(),i=!1;{let e=ue(u()).some(e=>xe(e)),t=mn(n)!==void 0;(e||t)&&(i=!0,t||(_=`waiting_for_agents`,await Ti(100)))}}while(i);re&&(b.enqueue(re),re=null,x.pendingSuggestion&&(b.enqueue(x.pendingSuggestion),x.pendingLastEmittedEntry&&(x.lastEmitted={...x.pendingLastEmittedEntry,emittedAt:Date.now()},x.pendingLastEmittedEntry=null),x.pendingSuggestion=null))}catch(e){try{await t.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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[W(e),...ni().map(e=>e.error)]})}catch{}x.abortController?.abort(),E(1);return}finally{if(_=`finally_flush`,await t.flushInternalEvents(),_=`finally_post_flush`,!Dt()){$i(`idle`);for(let e of Ui())b.enqueue(e)}g=!1,Ue.start()}if(na()&&!Ji()&&mn(n)===void 0&&!ne){Ze();return}if(mn(n)!==void 0){Qe();return}ne&&(x.inflightPromise&&await Promise.race([x.inflightPromise,Ti(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ye(),se?.(),ze.delete(ce),b.done())},O=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},k=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},nt=new Set;t.setUnexpectedResponseCallback(async e=>{await ru({message:e,setAppState:d,handledToolUseIds:nt,onEnqueued:()=>{Qe()}})});let it=new Map,at=new Map,ot=new Set,st=new Map,lt=null;return(async()=>{let e=!1;$r(`info`,`cli_message_loop_started`);for await(let n of t.structuredInput){let i=`uuid`in n?n.uuid:void 0;if(i&&n.type!==`user`&&n.type!==`control_response`&&Bt(i,`completed`),n.type===`control_request`){let i=n,o=i.request;if(i.request.subtype===`interrupt`)d(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,O(i);else if(o.subtype===`end_session`){G(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,O(i);break}else if(i.request.subtype===`initialize`){if(i.request.sdkMcpServers&&i.request.sdkMcpServers.length>0)for(let e of i.request.sdkMcpServers)l[e]={type:`sdk`,name:e};await Xl(i.request,i.request_id,e,b,a,ve,t,!!p.enableAuthStatus,p,f,u),i.request.promptSuggestions&&d(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),i.request.agentProgressSummaries&&ur(!0),e=!0,un()&&Qe()}else if(i.request.subtype===`set_permission_mode`){let e=i.request;d(t=>({...t,toolPermissionContext:Ql(e,i.request_id,t.toolPermissionContext,b)}))}else if(i.request.subtype===`set_model`){let e=i.request.model??`default`,t=e==="default"?Di():e;ye=t,vr(t),Wi({model:t}),be(e,t),O(i)}else if(i.request.subtype===`set_max_thinking_tokens`)i.request.max_thinking_tokens===null?p.thinkingConfig=void 0:i.request.max_thinking_tokens===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:i.request.max_thinking_tokens},O(i);else if(i.request.subtype===`mcp_status`)O(i,{mcpServers:Be()});else if(i.request.subtype===`get_context_usage`)try{let e=u(),t=await La({messages:S,getAppState:u,options:{mainLoopModel:ki(),tools:Me(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt}});O(i,{...t})}catch(e){k(i,W(e))}else if(i.request.subtype===`mcp_message`){let e=i.request,t=C.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),O(i)}else if(i.request.subtype===`rewind_files`){let e=u(),t=await Zl(i.request.user_message_id,e,d,i.request.dry_run??!1);t.canRewind||i.request.dry_run?O(i,t):k(i,t.error??`Unexpected error`)}else if(i.request.subtype===`cancel_async_message`){let e=i.request.message_uuid,t=tt(t=>t.uuid===e);O(i,{cancelled:t.length>0})}else if(i.request.subtype===`seed_read_state`){try{let e=Rr(i.request.path),t=Math.floor((await $a(e)).mtimeMs);if(t<=i.request.mtime){let n=await Qa(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
12
+ Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(gn(),qr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-CfmbvayQ.js`);await e()}catch{}E(y?.type===`result`&&y?.is_error?1:0)}function ql(t,r,a,o,s,c,l,u,d,f,p,m){let g=!1,_,ne=!1,re=null,v,b=t.outbound;process.on(`SIGINT`,()=>{$r(`info`,`shutdown_signal`,{signal:`SIGINT`}),v&&!v.signal.aborted&&v.abort(),rt(0)}),jr(async()=>{let e={};for(let t of ue(u()))xe(t)&&(e[t.type]=(e[t.type]??0)+1);$r(`info`,`run_state_at_shutdown`,{run_active:g,run_phase:_,worker_status:ra(),internal_events_pending:t.internalEventsPending,bg_tasks:e})}),ta(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&b.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let x={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},se;p.enableAuthStatus&&(se=Ai.getInstance().subscribe(e=>{b.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}));let ce=e=>{let t=da(e);t&&b.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};ze.add(ce);let S=s,de=le(s,X(),100),fe=Ie(100),pe=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;m&&m.kind!==`none`&&pe&&(G(`[print.ts] Auto-resuming interrupted turn (kind: ${m.kind})`),eu(S,m.message),et({mode:`prompt`,value:m.message.message.content,uuid:Y()}));let ve=za().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?Di():ui(t),r=Qt(n),i=mi(e.value),a=di(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),ye=p.userSpecifiedModel;function be(e,t){let n=Pt(e,ji(t));S.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&b.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:U(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let C=[],Se=[],Ce=new Set;function Ee(e){for(let n of e){if(n.type!==`connected`||Ce.has(n.name)||n.config.type===`sdk`)continue;let e=n.name;try{n.client.setRequestHandler(Hn,async(n,r)=>{ti(e,`Elicitation request received in print mode: ${Cr(n)}`);let i=n.params.mode===`url`?`url`:`form`;J(`tengu_mcp_elicitation_shown`,{mode:i});let a=await we(e,n.params,r.signal);if(a)return ti(e,`Elicitation resolved by hook: ${Cr(a)}`),J(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in n.params?n.params.url:void 0,s=`requestedSchema`in n.params?n.params.requestedSchema:void 0,c=`elicitationId`in n.params?n.params.elicitationId:void 0,l=await t.handleElicitation(e,n.params.message,s,r.signal,i,o,c),u=await ke(e,l,r.signal,i,c);return J(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),n.client.setNotificationHandler(ae,t=>{let{elicitationId:n}=t.params;ti(e,`Elicitation completion notification: ${n}`),te({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),b.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),Ce.add(e)}catch{}}}async function De(){let e=new Set(Object.keys(l)),n=new Set(C.map(e=>e.name)),r=Array.from(e).some(e=>!n.has(e)),i=Array.from(n).some(t=>!e.has(t)),a=C.some(e=>e.type===`pending`),o=C.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of C)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await Xt(l,(e,n)=>t.sendMcpMessage(e,n));C=r.clients,Se=r.tools;let i=Kr([...n,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Ur(t)))),...Se]}})),Xe(C)}}De();let w={clients:[],tools:[],configs:{}},Me=e=>{let t=Ge(e.toolPermissionContext,e.mcp.tools),n=St(ka([...o,...Se,...w.tools],t,e.toolPermissionContext.mode),`name`);p.permissionPromptToolName&&(n=n.filter(e=>!Pi(e,p.permissionPromptToolName)));let r=fr();if(r&&!p.jsonSchema){let e=Fi(r);`tool`in e&&(n=[...n,e.tool])}return n},T=null,Ne=0;function Pe(){if(!T)return;let e=Math.min(Ne,S.length),t=S.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);Ne=S.length,t.length>0&&T.writeMessages(t)}let Fe=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Re(e){let t=async()=>{let t=new Set(C.map(e=>e.name)),n=await au(e,{configs:l,clients:C,tools:Se},w,d);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),C=n.newSdkState.clients,Se=n.newSdkState.tools,w=n.newDynamicState,n.sdkServersChanged){let e=new Set(C.map(e=>e.name)),n=Kr([...t,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Ur(t)))),...Se]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Fe=Fe.then(t,t),Fe}function Be(){let e=u(),t=e.mcp.clients,n=St([...e.mcp.tools,...w.tools],`name`),r=new Set([...t.map(e=>e.name),...C.map(e=>e.name)]);return[...t,...C,...w.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers,oauth:e.config.oauth};else if(e.config.type===`claudeai-proxy`)t={type:`claudeai-proxy`,url:e.config.url,id:e.config.id};else if(e.config.type===`stdio`||e.config.type===void 0){let n=e.config;t={type:`stdio`,command:n.command,args:n.args}}let r=e.type===`connected`?Ut(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 Ve(){try{await Promise.all([Promise.resolve(),Zr(`headless_managed_settings_wait`,()=>wa())]),await Rl()&&await Je()}catch(e){q(e)}}let He=null;i()||(n(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?He=Ve():Ve());let Ue=_l(()=>!g),We=a,D=f;async function qe(){let{agentDefinitions:e}=await Ga(d);We=await Te(X());let t=D.filter(e=>e.source===`flagSettings`);D=[...e.allAgents,...t]}async function Je(){let{servers:e}=await oe(),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 Re(t);r&&De(),G(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Ye=Ua.subscribe(()=>{y(),Te(X()).then(e=>{We=e})}),Ze=()=>{setTimeout(()=>{!na()||Ji()||ne||(async()=>{let e=await qn({basePrompt:`<${ei}>${new Date().toLocaleTimeString()}</${ei}>`,currentDir:X(),shouldCreate:()=>!ne});if(ne){await ct({commands:e});return}for(let t of e)et({...t,uuid:Y()});Qe()})().catch(e=>{q(e),G(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};en(()=>{v&&Mn(`now`).length>0&&v.abort(`interrupt`)});let Qe=async()=>{if(g)return;if(g=!0,_=void 0,$i(`running`),Ue.stop(),Pn(`run_entry`),await De(),Pn(`after_updateSdkMcp`),He){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Ti(e).then(()=>`timeout`);await Promise.race([He,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 He;He=null,await qe();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-CGgpcyEC.js`);t()}let n=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=ge(n);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;Gl(r,mn(n));)i.push(ge(n));let a=await Rn(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Wl(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(p.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&b.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:U(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=u(),l=[...s.mcp.clients,...C,...w.clients];Ee(l);let f=Me(s);for(let e of o)Bt(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&b.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let m=r.value,h=a.claimedCommands;if(t instanceof dl&&r.mode===`prompt`&&J(`tengu_bridge_message_received`,{is_repl:!1}),x.abortController?.abort(),x.abortController=null,x.pendingSuggestion=null,x.pendingLastEmittedEntry=null,x.lastEmitted&&r.mode===`prompt`){let e=typeof m==`string`?m:m.find(e=>e.type===`text`)?.text;typeof e==`string`&&On(x.lastEmitted.text,e,x.lastEmitted.emittedAt,x.lastEmitted.promptId,x.lastEmitted.generationRequestId),x.lastEmitted=null}v=je(),Pn(`before_ask`),ee();let g=r,_=!1;try{if(await hi(g.workload??p.workload,async()=>{for await(let e of Ma({commands:St([...We,...s.mcp.commands],`name`),prompt:m,promptUuid:g.uuid,isMeta:g.isMeta,cwd:X(),tools:f,verbose:p.verbose,mcpClients:l,thinkingConfig:p.thinkingConfig,maxTurns:p.maxTurns,maxBudgetUsd:p.maxBudgetUsd,taskBudget:p.taskBudget,canUseTool:c,userSpecifiedModel:ye,fallbackModel:p.fallbackModel,jsonSchema:fr()??p.jsonSchema,mutableMessages:S,getReadFileCache:()=>fe.size===0?de:Tt(de,fe),setReadFileCache:e=>{de=e;for(let[e,t]of fe.entries()){let n=de.get(e);(!n||t.timestamp>n.timestamp)&&de.set(e,t)}fe.clear()},customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,getAppState:u,setAppState:d,abortController:v,replayUserMessages:p.replayUserMessages,includePartialMessages:p.includePartialMessages,handleElicitation:(e,n,r)=>t.handleElicitation(e,n.message,void 0,r,n.mode,n.url,`elicitationId`in n?n.elicitationId:void 0),agents:D,orphanedPermission:g.orphanedPermission,setSDKStatus:e=>{b.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(Pe(),e.type===`result`){_=!!e.is_error;for(let e of Ui())b.enqueue(e);ue(u()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&xe(e))?re=e:(re=null,b.enqueue(e))}else{for(let e of Ui())b.enqueue(e);b.enqueue(e)}}),_)await $n({commands:h,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:g.workload??p.workload});else{let e=await $n({commands:h,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:g.workload??p.workload});for(let t of e)et({...t,uuid:Y()})}}catch(e){throw await $n({commands:h,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:g.workload??p.workload}),e}for(let e of o)Bt(e,`completed`);if(Pe(),T?.sendResult(),p.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){x.abortController?.abort();let e=new AbortController;x.abortController=e;let t=yt();if(!t)sn(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await Wt(e,S,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};re?(x.pendingSuggestion=r,x.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(x.lastEmitted=i,b.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){sn(`aborted`,void 0,void 0,`sdk`);return}q(Dr(e))}finally{x.inflightPromise===n.promise&&(x.inflightPromise=null)}})(),x.inflightPromise=n.promise}}gn(),Le(),Ct()}};do{for(let e of Ui())b.enqueue(e);_=`draining_commands`,await a(),i=!1;{let e=ue(u()).some(e=>xe(e)),t=mn(n)!==void 0;(e||t)&&(i=!0,t||(_=`waiting_for_agents`,await Ti(100)))}}while(i);re&&(b.enqueue(re),re=null,x.pendingSuggestion&&(b.enqueue(x.pendingSuggestion),x.pendingLastEmittedEntry&&(x.lastEmitted={...x.pendingLastEmittedEntry,emittedAt:Date.now()},x.pendingLastEmittedEntry=null),x.pendingSuggestion=null))}catch(e){try{await t.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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[W(e),...ni().map(e=>e.error)]})}catch{}x.abortController?.abort(),E(1);return}finally{if(_=`finally_flush`,await t.flushInternalEvents(),_=`finally_post_flush`,!Dt()){$i(`idle`);for(let e of Ui())b.enqueue(e)}g=!1,Ue.start()}if(na()&&!Ji()&&mn(n)===void 0&&!ne){Ze();return}if(mn(n)!==void 0){Qe();return}ne&&(x.inflightPromise&&await Promise.race([x.inflightPromise,Ti(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ye(),se?.(),ze.delete(ce),b.done())},O=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},k=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},nt=new Set;t.setUnexpectedResponseCallback(async e=>{await ru({message:e,setAppState:d,handledToolUseIds:nt,onEnqueued:()=>{Qe()}})});let it=new Map,at=new Map,ot=new Set,st=new Map,lt=null;return(async()=>{let e=!1;$r(`info`,`cli_message_loop_started`);for await(let n of t.structuredInput){let i=`uuid`in n?n.uuid:void 0;if(i&&n.type!==`user`&&n.type!==`control_response`&&Bt(i,`completed`),n.type===`control_request`){let i=n,o=i.request;if(i.request.subtype===`interrupt`)d(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,O(i);else if(o.subtype===`end_session`){G(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,O(i);break}else if(i.request.subtype===`initialize`){if(i.request.sdkMcpServers&&i.request.sdkMcpServers.length>0)for(let e of i.request.sdkMcpServers)l[e]={type:`sdk`,name:e};await Xl(i.request,i.request_id,e,b,a,ve,t,!!p.enableAuthStatus,p,f,u),i.request.promptSuggestions&&d(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),i.request.agentProgressSummaries&&ur(!0),e=!0,un()&&Qe()}else if(i.request.subtype===`set_permission_mode`){let e=i.request;d(t=>({...t,toolPermissionContext:Ql(e,i.request_id,t.toolPermissionContext,b)}))}else if(i.request.subtype===`set_model`){let e=i.request.model??`default`,t=e==="default"?Di():e;ye=t,vr(t),Wi({model:t}),be(e,t),O(i)}else if(i.request.subtype===`set_max_thinking_tokens`)i.request.max_thinking_tokens===null?p.thinkingConfig=void 0:i.request.max_thinking_tokens===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:i.request.max_thinking_tokens},O(i);else if(i.request.subtype===`mcp_status`)O(i,{mcpServers:Be()});else if(i.request.subtype===`get_context_usage`)try{let e=u(),t=await La({messages:S,getAppState:u,options:{mainLoopModel:ki(),tools:Me(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt}});O(i,{...t})}catch(e){k(i,W(e))}else if(i.request.subtype===`mcp_message`){let e=i.request,t=C.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),O(i)}else if(i.request.subtype===`rewind_files`){let e=u(),t=await Zl(i.request.user_message_id,e,d,i.request.dry_run??!1);t.canRewind||i.request.dry_run?O(i,t):k(i,t.error??`Unexpected error`)}else if(i.request.subtype===`cancel_async_message`){let e=i.request.message_uuid,t=tt(t=>t.uuid===e);O(i,{cancelled:t.length>0})}else if(i.request.subtype===`seed_read_state`){try{let e=Rr(i.request.path),t=Math.floor((await $a(e)).mtimeMs);if(t<=i.request.mtime){let n=await Qa(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
13
13
  `,`
14
- `);fe.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}O(i)}else if(i.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Re(i.request.servers);O(i,e),t&&De()}else if(i.request.subtype===`reload_plugins`)try{let e=await Ga(d),t=D.filter(e=>e.source===`flagSettings`);D=[...e.agentDefinitions.allAgents,...t];let n=[],[r,a,o]=await Promise.allSettled([Te(X()),Je(),Fn()]);r.status===`fulfilled`?We=r.value:q(r.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),O(i,{commands:We.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:h(e),argumentHint:e.argumentHint||``})),agents:D.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Be(),error_count:e.error_count})}catch(e){k(i,W(e))}else if(i.request.subtype===`mcp_reconnect`){let e=u(),{serverName:t}=i.request;Ce.delete(t);let n=ie(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)k(i,`Server not found: ${t}`);else{let e=await Ae(t,n),r=Ur(t);if(d(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(r)),...e.tools],commands:[...A(n.mcp.commands,e=>ft(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:ia(n.mcp.resources,t)}})),w={...w,clients:[...w.clients.filter(e=>e.name!==t),e.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...e.tools]},e.client.type===`connected`)Ee([e.client]),O(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;k(i,t)}}}else if(i.request.subtype===`mcp_toggle`){let e=u(),{serverName:t,enabled:n}=i.request;Ce.delete(t);let a=ie(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)k(i,`Server not found: ${t}`);else if(n){me(t,!0);let e=await Ae(t,a),n=Ur(t);if(d(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=>ft(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:ia(r.mcp.resources,t)}})),e.client.type===`connected`)Ee([e.client]),O(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;k(i,t)}}else{me(t,!1);let n=[...r,...C,...w.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await Zn(t,a);let o=Ur(t);d(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=>ft(e,t)),resources:ia(e.mcp.resources,t)}})),O(i)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=u(),n=ie(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)k(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)k(i,`Server type "${n.type}" does not support OAuth authentication`);else try{it.get(e)?.abort();let t=new AbortController;it.set(e,t);let r,a=new Promise(e=>{r=e}),o=$e(e,n,e=>r(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{at.set(e,t)}}),s=await Promise.race([a,o.then(()=>null)]);s?O(i,{authUrl:s,requiresUserAction:!0}):O(i,{requiresUserAction:!1}),st.set(e,o),o.then(async()=>{if(Oe(e)||ot.has(e))return;let t=await Ae(e,n),r=Ur(e);d(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=>ft(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),w={...w,clients:[...w.clients.filter(t=>t.name!==e),t.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...t.tools]}}).catch(t=>{G(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{it.get(e)===t&&(it.delete(e),at.delete(e),ot.delete(e),st.delete(e))})}catch(e){k(i,W(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=at.get(e);if(n){let r=!1;try{let e=new URL(t);r=e.searchParams.has(`code`)||e.searchParams.has(`error`)}catch{}if(!r)k(i,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{ot.add(e),n(t);let r=st.get(e);if(r)try{await r,O(i)}catch(e){k(i,e instanceof Error?e.message:`OAuth authentication failed`)}else O(i)}}else k(i,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;lt?.service.cleanup(),J(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Ta,n,r=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 Ea(t),J(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),lt?.service===t&&(lt=null)});lt={service:t,flow:a},a.catch(e=>G(`claude_authenticate flow ended: ${e}`,{level:`info`}));try{let{manualUrl:e,automaticUrl:t}=await Promise.race([r,a.then(()=>{throw Error(`OAuth flow completed without producing auth URLs`)})]);O(i,{manualUrl:e,automaticUrl:t})}catch(e){k(i,W(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!lt)k(i,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&lt.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=lt;e.then(()=>{let e=Ei();O(i,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:ci()}})},e=>k(i,W(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=u(),n=ie(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)k(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)k(i,`Cannot clear auth for server type "${n.type}"`);else{await _e(e,n);let t=await Ae(e,n),r=Ur(e);d(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=>ft(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),O(i,{})}}else if(i.request.subtype===`apply_flag_settings`){let e=ki(),t=_r()??{},n=i.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];yr(r),pn.notifyChange(`flagSettings`),`model`in n&&(n.model==null?vr(void 0):vr(String(n.model)));let a=ki();if(a!==e){ye=a;let e=n.model?String(n.model):`default`;Wi({model:a}),be(e,a)}O(i)}else if(i.request.subtype===`get_settings`){let e=ki();O(i,{...Wr(),applied:{model:e}})}else if(i.request.subtype===`stop_task`){let{task_id:e}=i.request;try{await kt(e,{getAppState:u,setAppState:d}),O(i,{})}catch(e){k(i,W(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(v&&!v.signal.aborted?v:je()).signal;(async()=>{try{let r=await fa(e,n);if(r&&t)try{dt(U(),r)}catch(e){q(e)}O(i,{title:r})}catch(e){k(i,W(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=yt(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:je()}}:await Na({tools:Me(u()),commands:We,mcpClients:[...u().mcp.clients,...C,...w.clients],messages:S,readFileState:de,getAppState:u,setAppState:d,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,thinkingConfig:p.thinkingConfig,agents:D}),r=await Ia({question:e,cacheSafeParams:n});O(i,{response:r.response})}catch(e){k(i,W(e))}})()}else if(i.request.subtype===`set_proactive`)i.request.enabled?na()||(Qi(`command`),Ze()):ea(),O(i);else if(o.subtype===`remote_control`)if(o.enabled)if(T)O(i,{session_url:fn(T.bridgeSessionId,T.sessionIngressUrl),connect_url:Pa(T.environmentId,T.sessionIngressUrl),environment_id:T.environmentId});else{let e;try{let{initReplBridge:n}=await import(`./initReplBridge-BJhmlcVt.js`),r=await n({onInboundMessage(e){let t=vl(e);if(!t)return;let{content:n,uuid:r}=t;et({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),Qe()},onPermissionResponse(e){t.injectControlResponse(e)},onInterrupt(){v?.abort()},onSetModel(e){let t=e==="default"?Di():e;ye=t,vr(t)},onSetMaxThinkingTokens(e){e===null?p.thinkingConfig=void 0:e===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(t,n){t===`failed`&&(e=n),G(`[bridge:sdk] State change: ${t}${n?` — ${n}`:``}`),b.enqueue({type:`system`,subtype:`bridge_state`,state:t,detail:n,uuid:Y(),session_id:U()})},initialMessages:S.length>0?S:void 0});r?(T=r,Ne=S.length,t.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),t.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),O(i,{session_url:fn(r.bridgeSessionId,r.sessionIngressUrl),connect_url:Pa(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):k(i,e??`Remote Control initialization failed`)}catch(e){k(i,W(e))}}else T&&(t.setOnControlRequestSent(void 0),t.setOnControlRequestResolved(void 0),await T.teardown(),T=null),O(i);else k(i,`Unsupported control request subtype: ${i.request.subtype}`);continue}else if(n.type===`control_response`){p.replayUserMessages&&b.enqueue(n);continue}else if(n.type===`keep_alive`)continue;else if(n.type===`update_environment_variables`)continue;else if(n.type===`assistant`||n.type===`system`){let e=la([n]);S.push(...e),n.type===`assistant`&&p.replayUserMessages&&b.enqueue(n);continue}if(n.type!==`user`)continue;let o=n;if(e=!0,o.uuid){let e=U(),t=await he(e,o.uuid);if(t||Bl.has(o.uuid)){G(`Skipping duplicate user message: ${o.uuid}`),p.replayUserMessages&&(G(`Sending acknowledgment for duplicate user message: ${o.uuid}`),b.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&Bt(o.uuid,`completed`);continue}Hl(o.uuid)}et({mode:`prompt`,value:await jl(o,o.message.content),uuid:o.uuid,priority:o.priority}),d(e=>({...e,attribution:Un(e.attribution,e=>{Ke(e).catch(e=>{G(`Attribution: Failed to save snapshot: ${e}`)})})})),Qe()}ne=!0,g||(x.inflightPromise&&await Promise.race([x.inflightPromise,Ti(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ye(),se?.(),ze.delete(ce),b.done())})(),b}function Jl(e){let t=async(n,r,i,a,o,s)=>{let c=s??await g(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=er(i.abortController.signal);if(l.aborted)return u(),{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let d=new Promise(e=>{l.addEventListener(`abort`,()=>e(`aborted`),{once:!0})}),f=e.call({tool_name:n.name,input:r,tool_use_id:o},i,t,a),p=await Promise.race([f,d]);if(u(),p===`aborted`||l.aborted)return{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let m=p,h=e.mapToolResultToToolResultBlockParam(m.data,`1`);if(!h.content||!Array.isArray(h.content)||!h.content[0]||h.content[0].type!==`text`||typeof h.content[0].text!=`string`)throw Error(`Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.`);return $c(Qc().parse(oi(h.content[0].text)),e,r,i)};return t}function Yl(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await g(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=>Pi(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`),E(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`),E(1),Error(t)}i=Jl(r)}return i(t,r,a,o,s,c)}}async function Xl(e,t,n,r,i,a,o,s,c,l,u){if(n){r.enqueue({type:`control_response`,response:{subtype:`error`,error:`Already initialized`,request_id:t,pending_permission_requests:o.getPendingPermissionRequests()}});return}if(e.systemPrompt!==void 0&&(c.systemPrompt=e.systemPrompt),e.appendSystemPrompt!==void 0&&(c.appendSystemPrompt=e.appendSystemPrompt),e.promptSuggestions!==void 0&&(c.promptSuggestions=e.promptSuggestions),e.agents){let t=At(e.agents,`flagSettings`);l.push(...t)}if(c.agent){let e=lr()===c.agent,t=l.find(e=>e.agentType===c.agent);if(t&&!e){if(dr(t.agentType),!c.systemPrompt&&!Cn(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&vr(ui(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let d=zr()?.outputStyle||`default`,f=await jn(Sr()),p=Ei();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}});pr(t)}e.jsonSchema&&br(e.jsonSchema);let m={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:h(e),argumentHint:e.argumentHint||``})),agents:l.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:d,available_output_styles:Object.keys(f),models:a,account:{email:p?.email,organization:p?.organization,subscriptionType:p?.subscription,tokenSource:p?.tokenSource,apiKeySource:p?.apiKeySource,apiProvider:ci()},pid:process.pid};if(bi()&&yi()){let e=u();m.fast_mode_state=vi(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:m}}),s){let e=Ai.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}}async function Zl(e,t,n,r){if(!rn())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!hn(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await zt(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await Qn(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${W(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Ql(e,t,n,r){if(e.mode===`bypassPermissions`){if(Vn())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`&&!ne()){let e=Xn();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${Ln(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...p(n.mode,e.mode,n),mode:e.mode}}function $l(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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(`${Cr(t)}\n`)}else process.stderr.write(`${e}\n`)}function eu(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function tu(e,t){let r=!hr();if(t.continue)try{J(`tengu_continue_print`,{});let n=await He(void 0,void 0);if(n)return t.forkSession||n.sessionId&&(gr(fe(n.sessionId),n.fullPath?Ja(n.fullPath):null),r&&await An()),Ha(n,e),cn(t.forkSession?{...n,worktreeSession:void 0}:n),{messages:n.messages,turnInterruptionState:n.turnInterruptionState,agentSetting:n.agentSetting}}catch(e){return q(e),E(1),{messages:[]}}if(t.teleport)try{if(!ut(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(J(`tengu_teleport_print`,{}),typeof t.teleport!=`string`)throw Error(`No session ID provided for teleport`);let{checkOutTeleportedSessionBranch:e,processMessagesForTeleportResume:n,teleportResumeCodeSession:r,validateGitState:i}=await import(`./teleport-CvX_nUjQ.js`);await i();let a=await r(t.teleport),{branchError:o}=await e(a.branch);return{messages:n(a.log,o)}}catch(e){return q(e),E(1),{messages:[]}}if(t.resume)try{J(`tengu_resume_print`,{});let i=Ml(typeof t.resume==`string`?t.resume:``);if(!i){let e=`Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>`;return typeof t.resume==`string`&&(e+=`. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${t.resume}" is not a valid UUID`),$l(e,t.outputFormat),E(1),{messages:[]}}if(n(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,n]=await Promise.all([zn(i.sessionId),t.restoredWorkerState]);n&&(e(ja(n)),typeof n.model==`string`&&vr(n.model))}else i.isUrl&&i.ingressUrl&&n(process.env.ENABLE_SESSION_PERSISTENCE)&&await tr(i.sessionId,i.ingressUrl);let a=await He(i.sessionId,i.jsonlFile||void 0);if(!a||a.messages.length===0)return i.isUrl||n(process.env.CLAUDE_CODE_USE_CCR_V2)?{messages:await(t.sessionStartHooksPromise??Rt(`startup`))}:($l(`No conversation found with session ID: ${i.sessionId}`,t.outputFormat),E(1),{messages:[]});if(t.resumeSessionAt){let e=a.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return $l(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),E(1),{messages:[]};a.messages=e>=0?a.messages.slice(0,e+1):[]}return!t.forkSession&&a.sessionId&&(gr(fe(a.sessionId),a.fullPath?Ja(a.fullPath):null),r&&await An()),Ha(a,e),cn(t.forkSession?{...a,worktreeSession:void 0}:a),{messages:a.messages,turnInterruptionState:a.turnInterruptionState,agentSetting:a.agentSetting}}catch(e){return q(e),$l(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),E(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??Rt(`startup`))}}function nu(e,t){let n;return n=typeof e==`string`?e.trim()===``?Me([]):Me([Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new dl(t.sdkUrl,n,t.replayUserMessages):new sl(n,t.replayUserMessages)}async function ru({message:e,setAppState:t,onEnqueued:n,handledToolUseIds:r}){let i=e.response;if(i?.subtype===`success`&&i.response?.toolUseID&&typeof i.response.toolUseID==`string`){let e=i.response,t=e.toolUseID;if(!t)return!1;if(G(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return G(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await Pe(t);return a?(r.add(t),G(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),et({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(G(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function iu(e){return{...e,scope:`dynamic`}}async function au(e,t,n,r){let{allowed:i,blocked:a}=Ue(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 ou(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 ou(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||!ot(r,iu(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 Zn(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=iu(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await mt(t,r);if(d.push(e),e.type===`connected`){let t=await re(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Dr(e);u[t]=n.message,q(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=iu(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{Kl as runHeadless};
14
+ `);fe.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}O(i)}else if(i.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Re(i.request.servers);O(i,e),t&&De()}else if(i.request.subtype===`reload_plugins`)try{let e=await Ga(d),t=D.filter(e=>e.source===`flagSettings`);D=[...e.agentDefinitions.allAgents,...t];let n=[],[r,a,o]=await Promise.allSettled([Te(X()),Je(),Fn()]);r.status===`fulfilled`?We=r.value:q(r.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),O(i,{commands:We.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:h(e),argumentHint:e.argumentHint||``})),agents:D.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Be(),error_count:e.error_count})}catch(e){k(i,W(e))}else if(i.request.subtype===`mcp_reconnect`){let e=u(),{serverName:t}=i.request;Ce.delete(t);let n=ie(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)k(i,`Server not found: ${t}`);else{let e=await Ae(t,n),r=Ur(t);if(d(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(r)),...e.tools],commands:[...A(n.mcp.commands,e=>ft(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:ia(n.mcp.resources,t)}})),w={...w,clients:[...w.clients.filter(e=>e.name!==t),e.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...e.tools]},e.client.type===`connected`)Ee([e.client]),O(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;k(i,t)}}}else if(i.request.subtype===`mcp_toggle`){let e=u(),{serverName:t,enabled:n}=i.request;Ce.delete(t);let a=ie(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)k(i,`Server not found: ${t}`);else if(n){me(t,!0);let e=await Ae(t,a),n=Ur(t);if(d(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=>ft(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:ia(r.mcp.resources,t)}})),e.client.type===`connected`)Ee([e.client]),O(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;k(i,t)}}else{me(t,!1);let n=[...r,...C,...w.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await Zn(t,a);let o=Ur(t);d(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=>ft(e,t)),resources:ia(e.mcp.resources,t)}})),O(i)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=u(),n=ie(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)k(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)k(i,`Server type "${n.type}" does not support OAuth authentication`);else try{it.get(e)?.abort();let t=new AbortController;it.set(e,t);let r,a=new Promise(e=>{r=e}),o=$e(e,n,e=>r(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{at.set(e,t)}}),s=await Promise.race([a,o.then(()=>null)]);s?O(i,{authUrl:s,requiresUserAction:!0}):O(i,{requiresUserAction:!1}),st.set(e,o),o.then(async()=>{if(Oe(e)||ot.has(e))return;let t=await Ae(e,n),r=Ur(e);d(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=>ft(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),w={...w,clients:[...w.clients.filter(t=>t.name!==e),t.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...t.tools]}}).catch(t=>{G(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{it.get(e)===t&&(it.delete(e),at.delete(e),ot.delete(e),st.delete(e))})}catch(e){k(i,W(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=at.get(e);if(n){let r=!1;try{let e=new URL(t);r=e.searchParams.has(`code`)||e.searchParams.has(`error`)}catch{}if(!r)k(i,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{ot.add(e),n(t);let r=st.get(e);if(r)try{await r,O(i)}catch(e){k(i,e instanceof Error?e.message:`OAuth authentication failed`)}else O(i)}}else k(i,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;lt?.service.cleanup(),J(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Ta,n,r=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 Ea(t),J(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),lt?.service===t&&(lt=null)});lt={service:t,flow:a},a.catch(e=>G(`claude_authenticate flow ended: ${e}`,{level:`info`}));try{let{manualUrl:e,automaticUrl:t}=await Promise.race([r,a.then(()=>{throw Error(`OAuth flow completed without producing auth URLs`)})]);O(i,{manualUrl:e,automaticUrl:t})}catch(e){k(i,W(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!lt)k(i,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&lt.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=lt;e.then(()=>{let e=Ei();O(i,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:ci()}})},e=>k(i,W(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=u(),n=ie(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)k(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)k(i,`Cannot clear auth for server type "${n.type}"`);else{await _e(e,n);let t=await Ae(e,n),r=Ur(e);d(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=>ft(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),O(i,{})}}else if(i.request.subtype===`apply_flag_settings`){let e=ki(),t=_r()??{},n=i.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];yr(r),pn.notifyChange(`flagSettings`),`model`in n&&(n.model==null?vr(void 0):vr(String(n.model)));let a=ki();if(a!==e){ye=a;let e=n.model?String(n.model):`default`;Wi({model:a}),be(e,a)}O(i)}else if(i.request.subtype===`get_settings`){let e=ki();O(i,{...Wr(),applied:{model:e}})}else if(i.request.subtype===`stop_task`){let{task_id:e}=i.request;try{await kt(e,{getAppState:u,setAppState:d}),O(i,{})}catch(e){k(i,W(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(v&&!v.signal.aborted?v:je()).signal;(async()=>{try{let r=await fa(e,n);if(r&&t)try{dt(U(),r)}catch(e){q(e)}O(i,{title:r})}catch(e){k(i,W(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=yt(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:je()}}:await Na({tools:Me(u()),commands:We,mcpClients:[...u().mcp.clients,...C,...w.clients],messages:S,readFileState:de,getAppState:u,setAppState:d,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,thinkingConfig:p.thinkingConfig,agents:D}),r=await Ia({question:e,cacheSafeParams:n});O(i,{response:r.response})}catch(e){k(i,W(e))}})()}else if(i.request.subtype===`set_proactive`)i.request.enabled?na()||(Qi(`command`),Ze()):ea(),O(i);else if(o.subtype===`remote_control`)if(o.enabled)if(T)O(i,{session_url:fn(T.bridgeSessionId,T.sessionIngressUrl),connect_url:Pa(T.environmentId,T.sessionIngressUrl),environment_id:T.environmentId});else{let e;try{let{initReplBridge:n}=await import(`./initReplBridge-BEZW5PEY.js`),r=await n({onInboundMessage(e){let t=vl(e);if(!t)return;let{content:n,uuid:r}=t;et({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),Qe()},onPermissionResponse(e){t.injectControlResponse(e)},onInterrupt(){v?.abort()},onSetModel(e){let t=e==="default"?Di():e;ye=t,vr(t)},onSetMaxThinkingTokens(e){e===null?p.thinkingConfig=void 0:e===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(t,n){t===`failed`&&(e=n),G(`[bridge:sdk] State change: ${t}${n?` — ${n}`:``}`),b.enqueue({type:`system`,subtype:`bridge_state`,state:t,detail:n,uuid:Y(),session_id:U()})},initialMessages:S.length>0?S:void 0});r?(T=r,Ne=S.length,t.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),t.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),O(i,{session_url:fn(r.bridgeSessionId,r.sessionIngressUrl),connect_url:Pa(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):k(i,e??`Remote Control initialization failed`)}catch(e){k(i,W(e))}}else T&&(t.setOnControlRequestSent(void 0),t.setOnControlRequestResolved(void 0),await T.teardown(),T=null),O(i);else k(i,`Unsupported control request subtype: ${i.request.subtype}`);continue}else if(n.type===`control_response`){p.replayUserMessages&&b.enqueue(n);continue}else if(n.type===`keep_alive`)continue;else if(n.type===`update_environment_variables`)continue;else if(n.type===`assistant`||n.type===`system`){let e=la([n]);S.push(...e),n.type===`assistant`&&p.replayUserMessages&&b.enqueue(n);continue}if(n.type!==`user`)continue;let o=n;if(e=!0,o.uuid){let e=U(),t=await he(e,o.uuid);if(t||Bl.has(o.uuid)){G(`Skipping duplicate user message: ${o.uuid}`),p.replayUserMessages&&(G(`Sending acknowledgment for duplicate user message: ${o.uuid}`),b.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&Bt(o.uuid,`completed`);continue}Hl(o.uuid)}et({mode:`prompt`,value:await jl(o,o.message.content),uuid:o.uuid,priority:o.priority}),d(e=>({...e,attribution:Un(e.attribution,e=>{Ke(e).catch(e=>{G(`Attribution: Failed to save snapshot: ${e}`)})})})),Qe()}ne=!0,g||(x.inflightPromise&&await Promise.race([x.inflightPromise,Ti(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ye(),se?.(),ze.delete(ce),b.done())})(),b}function Jl(e){let t=async(n,r,i,a,o,s)=>{let c=s??await g(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=er(i.abortController.signal);if(l.aborted)return u(),{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let d=new Promise(e=>{l.addEventListener(`abort`,()=>e(`aborted`),{once:!0})}),f=e.call({tool_name:n.name,input:r,tool_use_id:o},i,t,a),p=await Promise.race([f,d]);if(u(),p===`aborted`||l.aborted)return{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let m=p,h=e.mapToolResultToToolResultBlockParam(m.data,`1`);if(!h.content||!Array.isArray(h.content)||!h.content[0]||h.content[0].type!==`text`||typeof h.content[0].text!=`string`)throw Error(`Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.`);return $c(Qc().parse(oi(h.content[0].text)),e,r,i)};return t}function Yl(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await g(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=>Pi(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`),E(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`),E(1),Error(t)}i=Jl(r)}return i(t,r,a,o,s,c)}}async function Xl(e,t,n,r,i,a,o,s,c,l,u){if(n){r.enqueue({type:`control_response`,response:{subtype:`error`,error:`Already initialized`,request_id:t,pending_permission_requests:o.getPendingPermissionRequests()}});return}if(e.systemPrompt!==void 0&&(c.systemPrompt=e.systemPrompt),e.appendSystemPrompt!==void 0&&(c.appendSystemPrompt=e.appendSystemPrompt),e.promptSuggestions!==void 0&&(c.promptSuggestions=e.promptSuggestions),e.agents){let t=At(e.agents,`flagSettings`);l.push(...t)}if(c.agent){let e=lr()===c.agent,t=l.find(e=>e.agentType===c.agent);if(t&&!e){if(dr(t.agentType),!c.systemPrompt&&!Cn(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&vr(ui(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let d=zr()?.outputStyle||`default`,f=await jn(Sr()),p=Ei();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}});pr(t)}e.jsonSchema&&br(e.jsonSchema);let m={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:h(e),argumentHint:e.argumentHint||``})),agents:l.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:d,available_output_styles:Object.keys(f),models:a,account:{email:p?.email,organization:p?.organization,subscriptionType:p?.subscription,tokenSource:p?.tokenSource,apiKeySource:p?.apiKeySource,apiProvider:ci()},pid:process.pid};if(bi()&&yi()){let e=u();m.fast_mode_state=vi(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:m}}),s){let e=Ai.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}}async function Zl(e,t,n,r){if(!rn())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!hn(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await zt(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await Qn(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${W(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Ql(e,t,n,r){if(e.mode===`bypassPermissions`){if(Vn())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`&&!ne()){let e=Xn();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${Ln(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...p(n.mode,e.mode,n),mode:e.mode}}function $l(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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(`${Cr(t)}\n`)}else process.stderr.write(`${e}\n`)}function eu(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function tu(e,t){let r=!hr();if(t.continue)try{J(`tengu_continue_print`,{});let n=await He(void 0,void 0);if(n)return t.forkSession||n.sessionId&&(gr(fe(n.sessionId),n.fullPath?Ja(n.fullPath):null),r&&await An()),Ha(n,e),cn(t.forkSession?{...n,worktreeSession:void 0}:n),{messages:n.messages,turnInterruptionState:n.turnInterruptionState,agentSetting:n.agentSetting}}catch(e){return q(e),E(1),{messages:[]}}if(t.teleport)try{if(!ut(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(J(`tengu_teleport_print`,{}),typeof t.teleport!=`string`)throw Error(`No session ID provided for teleport`);let{checkOutTeleportedSessionBranch:e,processMessagesForTeleportResume:n,teleportResumeCodeSession:r,validateGitState:i}=await import(`./teleport-Bi_1VFIZ.js`);await i();let a=await r(t.teleport),{branchError:o}=await e(a.branch);return{messages:n(a.log,o)}}catch(e){return q(e),E(1),{messages:[]}}if(t.resume)try{J(`tengu_resume_print`,{});let i=Ml(typeof t.resume==`string`?t.resume:``);if(!i){let e=`Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>`;return typeof t.resume==`string`&&(e+=`. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${t.resume}" is not a valid UUID`),$l(e,t.outputFormat),E(1),{messages:[]}}if(n(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,n]=await Promise.all([zn(i.sessionId),t.restoredWorkerState]);n&&(e(ja(n)),typeof n.model==`string`&&vr(n.model))}else i.isUrl&&i.ingressUrl&&n(process.env.ENABLE_SESSION_PERSISTENCE)&&await tr(i.sessionId,i.ingressUrl);let a=await He(i.sessionId,i.jsonlFile||void 0);if(!a||a.messages.length===0)return i.isUrl||n(process.env.CLAUDE_CODE_USE_CCR_V2)?{messages:await(t.sessionStartHooksPromise??Rt(`startup`))}:($l(`No conversation found with session ID: ${i.sessionId}`,t.outputFormat),E(1),{messages:[]});if(t.resumeSessionAt){let e=a.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return $l(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),E(1),{messages:[]};a.messages=e>=0?a.messages.slice(0,e+1):[]}return!t.forkSession&&a.sessionId&&(gr(fe(a.sessionId),a.fullPath?Ja(a.fullPath):null),r&&await An()),Ha(a,e),cn(t.forkSession?{...a,worktreeSession:void 0}:a),{messages:a.messages,turnInterruptionState:a.turnInterruptionState,agentSetting:a.agentSetting}}catch(e){return q(e),$l(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),E(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??Rt(`startup`))}}function nu(e,t){let n;return n=typeof e==`string`?e.trim()===``?Me([]):Me([Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new dl(t.sdkUrl,n,t.replayUserMessages):new sl(n,t.replayUserMessages)}async function ru({message:e,setAppState:t,onEnqueued:n,handledToolUseIds:r}){let i=e.response;if(i?.subtype===`success`&&i.response?.toolUseID&&typeof i.response.toolUseID==`string`){let e=i.response,t=e.toolUseID;if(!t)return!1;if(G(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return G(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await Pe(t);return a?(r.add(t),G(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),et({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(G(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function iu(e){return{...e,scope:`dynamic`}}async function au(e,t,n,r){let{allowed:i,blocked:a}=Ue(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 ou(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 ou(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||!ot(r,iu(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 Zn(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=iu(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await mt(t,r);if(d.push(e),e.type===`connected`){let t=await re(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Dr(e);u[t]=n.message,q(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=iu(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{Kl as runHeadless};
@@ -1 +1 @@
1
- import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{CC as t,Gm as n,Km as r,La as i,Rg as a,SC as o,Sa as s,Um as c,Wm as l,Xc as u,Yc as d,mp as f,pp as p,qa as m,va as h,xa as g,zg as _}from"./loadAgentsDir-DXOkUcW3.js";import{I as v,t as y}from"./src-DL3w8VPk2.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";import{A as x,P as S,R as C}from"./debug-D58GQBDG.js";import{h as w,t as T}from"./settings-3xZ0fsvE.js";import{n as E,r as D}from"./analytics-DJobLaWP.js";import{bt as O,yt as k}from"./prompt-DEioJrx_.js";import{randomUUID as A}from"crypto";y(),l(),f(),r();var j=b();function M({input:e,progress:t,verbose:r}){return(0,j.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,j.jsx)(p,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),t?(0,j.jsx)(n,{fullOutput:t.fullOutput,output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,verbose:r}):c.renderToolUseProgressMessage?.([],{verbose:r,tools:[],terminalSize:void 0})]})}C(),E(),o(),i(),w();function N(){return T().defaultShell??`bash`}l(),k(),_();async function P(n,r,i,o,l){let f=O()&&N()===`powershell`;D(`tengu_input_bash`,{powershell:f});let p=s({content:m({inputString:`<bash-input>${n}</bash-input>`,precedingInputBlocks:r})}),_;l({jsx:(0,j.jsx)(M,{input:n,progress:null,verbose:o.options.verbose}),shouldHidePromptInput:!1});try{let r={...o,setToolJSX:e=>{_=e?.jsx}},m=e=>{l({jsx:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(M,{input:n,progress:e.data,verbose:o.options.verbose}),_]}),shouldHidePromptInput:!1,showSpinner:!1})},g=null;f&&(g=(u(),e(d)).PowerShellTool);let v=g??c,y=(g?await g.call({command:n,dangerouslyDisableSandbox:!0},r,void 0,void 0,m):await c.call({command:n,dangerouslyDisableSandbox:!0},r,void 0,void 0,m)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await t(v,{...y,stderr:``},A()),S=typeof x.content==`string`?x.content:a(y.stdout);return{messages:[h(),p,...i,s({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${a(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof x?e.interrupted?{messages:[h(),p,g({toolUse:!1}),...i],shouldQuery:!1}:{messages:[h(),p,...i,s({content:`<bash-stdout>${a(e.stdout)}</bash-stdout><bash-stderr>${a(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[h(),p,...i,s({content:`<bash-stderr>Command failed: ${a(S(e))}</bash-stderr>`})],shouldQuery:!1}}finally{l(null)}}export{P as processBashCommand};
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{CC as t,Gm as n,Km as r,La as i,Rg as a,SC as o,Sa as s,Um as c,Wm as l,Xc as u,Yc as d,mp as f,pp as p,qa as m,va as h,xa as g,zg as _}from"./loadAgentsDir-DaNpxaO-.js";import{I as v,t as y}from"./src-DL3w8VPk2.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";import{A as x,P as S,R as C}from"./debug-D58GQBDG.js";import{h as w,t as T}from"./settings-3xZ0fsvE.js";import{n as E,r as D}from"./analytics-DJobLaWP.js";import{bt as O,yt as k}from"./prompt-8u06WVES.js";import{randomUUID as A}from"crypto";y(),l(),f(),r();var j=b();function M({input:e,progress:t,verbose:r}){return(0,j.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,j.jsx)(p,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),t?(0,j.jsx)(n,{fullOutput:t.fullOutput,output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,verbose:r}):c.renderToolUseProgressMessage?.([],{verbose:r,tools:[],terminalSize:void 0})]})}C(),E(),o(),i(),w();function N(){return T().defaultShell??`bash`}l(),k(),_();async function P(n,r,i,o,l){let f=O()&&N()===`powershell`;D(`tengu_input_bash`,{powershell:f});let p=s({content:m({inputString:`<bash-input>${n}</bash-input>`,precedingInputBlocks:r})}),_;l({jsx:(0,j.jsx)(M,{input:n,progress:null,verbose:o.options.verbose}),shouldHidePromptInput:!1});try{let r={...o,setToolJSX:e=>{_=e?.jsx}},m=e=>{l({jsx:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(M,{input:n,progress:e.data,verbose:o.options.verbose}),_]}),shouldHidePromptInput:!1,showSpinner:!1})},g=null;f&&(g=(u(),e(d)).PowerShellTool);let v=g??c,y=(g?await g.call({command:n,dangerouslyDisableSandbox:!0},r,void 0,void 0,m):await c.call({command:n,dangerouslyDisableSandbox:!0},r,void 0,void 0,m)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await t(v,{...y,stderr:``},A()),S=typeof x.content==`string`?x.content:a(y.stdout);return{messages:[h(),p,...i,s({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${a(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof x?e.interrupted?{messages:[h(),p,g({toolUse:!1}),...i],shouldQuery:!1}:{messages:[h(),p,...i,s({content:`<bash-stdout>${a(e.stdout)}</bash-stdout><bash-stderr>${a(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[h(),p,...i,s({content:`<bash-stderr>Command failed: ${a(S(e))}</bash-stderr>`})],shouldQuery:!1}}finally{l(null)}}export{P as processBashCommand};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$_ as t,Ap as n,Aw as r,B as i,BC as a,Bw as o,Cm as s,Ds as c,Dv as l,E as u,Ea as d,Fb as f,Fc as p,Ga as m,Ha as h,Ic as g,Ii as _,La as v,Li as y,Mp as b,Np as x,Of as S,Ow as C,Pb as w,Ra as T,Sa as E,Sf as D,Sm as O,Tf as k,Ti as ee,Ts as A,Uh as j,V as te,VC as ne,Wh as M,Xp as re,Xv as ie,Yp as ae,Zv as oe,b as se,bf as ce,c_ as le,ha as N,ji as ue,jp as de,kf as fe,ki as pe,kp as me,kw as P,lc as he,qa as F,ry as ge,sc as I,tv as L,u_ as _e,uc as ve,va as R,wm as ye,ws as be,wv as xe,xa as Se,xf as Ce,ya as we,zC as Te,zi as z,zw as Ee}from"./loadAgentsDir-DXOkUcW3.js";import{Ut as De,Wn as Oe,ft as ke,t as Ae}from"./state-D5D6QpTX.js";import{E as je,R as Me,c as B,f as Ne,i as V,k as H,u as Pe}from"./debug-D58GQBDG.js";import{Dt as Fe,Et as Ie}from"./settings-3xZ0fsvE.js";import{T as U,o as Le,q as Re,s as W,w as G}from"./log-CZ7ploQm.js";import{n as ze,r as K}from"./analytics-DJobLaWP.js";import{Xr as Be,Zr as Ve,dn as He,fn as Ue}from"./model-Cxx3suBa.js";import{ct as We,ot as Ge}from"./esm-DBMVQDVv.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-Dvi520eN.js";import{randomUUID as q}from"crypto";function Ye(e,t,n,r,i){let a=0;for(let o of Fe){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}'`),x(e,t,o,s)}:void 0;de(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Ie(),V(),b()}));function Ze(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.slice(1).split(` `);if(!n[0])return null;let r=n[0],i=!1,a=1;n.length>1&&n[1]===`(MCP)`&&(r=`${r} (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Qe=e((()=>{}));function $e(){return!1}function J(){if(!$e())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,i,a,o,c,l){let u=ae(),d=e.pluginInfo?r(e.pluginInfo.repository).marketplace:void 0;K(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...d&&{_PROTO_marketplace_name:d},...D(e.pluginInfo)}});let{skillContent:f,modifiedGetAppState:p,baseAgent:h,promptMessages:g}=await ve(e,t,i);B(`Executing forked slash command /${e.name} with agent ${h.agentType}`);let _=i.options.allowBackgroundForkedSlashCommands===!0;if(_&&J(),_){let t=w(),r=z(e),a=Be(),o=e=>oe({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:a}),d=async()=>{if(!l?.runId)return;let e=await O({runId:l.runId,rootDir:l.rootDir,priority:`later`,workload:a});for(let t of e)ie(t)},f=async e=>{l?.runId&&await s({runId:l.runId,rootDir:l.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let a=Date.now()+$;for(;Date.now()<a&&i.getAppState().mcp.clients.some(e=>e.type===`pending`);)await Ue(Q);let s=i.options.refreshTools?.()??i.options.tools,l=[];for await(let r of n({agentDefinition:h,promptMessages:g,toolUseContext:{...i,getAppState:p,abortController:t},canUseTool:c,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:s,override:{agentId:u}}))l.push(r);let f=I(l,`Command completed`);B(`Background forked command /${r} completed (agent ${u})`),o(`<scheduled-task-result command="/${r}">\n${f}\n</scheduled-task-result>`);try{await d()}catch(e){W(e)}})().catch(async e=>{W(e),o(`<scheduled-task-result command="/${r}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await f(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!l?.runId}}let v=[],y=[],b=`forked-command-${e.name}`,x=0,S=e=>(x++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:f,agentId:u},parentToolUseID:b,toolUseID:`${b}-${x}`,timestamp:new Date().toISOString(),uuid:q()}),C=()=>{o({jsx:fe(y,{tools:i.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};C();try{for await(let t of n({agentDefinition:h,promptMessages:g,toolUseContext:{...i,getAppState:p},canUseTool:c,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:i.options.tools})){v.push(t);let e=m([t]);if(t.type===`assistant`){let n=xe(t);n>0&&i.setResponseLength(e=>e+n);let r=e[0];r&&r.type===`assistant`&&(y.push(S(t)),C())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(y.push(S(t)),C())}}}finally{o(null)}let T=I(v,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${u}`),{messages:[E({content:F({inputString:`/${z(e)} ${t}`.trim(),precedingInputBlocks:a})}),E({content:`<local-command-stdout>\n${T}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:T}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,i,a,o,s,c,l,u){let d=Ze(e);if(!d){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[R(),...i,E({content:F({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:f,args:p,isMcp:m}=d,g=m?`mcp`:ee().has(f)?f:`custom`;if(!_(f,a.options.commands)){let n=!1;try{await Pe().stat(`/${f}`),n=!0}catch{}if(tt(f)&&!n){K(`tengu_input_slash_invalid`,{input:f});let e=`Unknown skill: ${f}`;return{messages:[R(),...i,E({content:F({inputString:e,precedingInputBlocks:t})}),...p?[we(`Args from unknown skill: ${p}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let r=q();return Oe(r),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":r}),{messages:[E({content:F({inputString:e,precedingInputBlocks:t}),uuid:s}),...i],shouldQuery:!0}}let{messages:v,shouldQuery:y,allowedTools:b,model:x,command:S,resultText:C,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}=await rt(f,p,o,a,t,n,c,l,s,u);if(v.length===0){let e={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:t,repository:n}=S.pluginInfo,{marketplace:i}=r(n),a=P(i);e._PROTO_plugin_name=t.name,i&&(e._PROTO_marketplace_name=i),e.plugin_repository=a?n:`third-party`,e.plugin_name=a?t.name:`third-party`,a&&t.version&&(e.plugin_version=t.version),Object.assign(e,D(S.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:x,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}}if(v.length===2&&v[1].type===`user`&&typeof v[1].message.content==`string`&&v[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:f}),{messages:[R(),...v],shouldQuery:y,allowedTools:b,model:x};let A={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:e,repository:t}=S.pluginInfo,{marketplace:n}=r(t),i=P(n);A._PROTO_plugin_name=e.name,n&&(A._PROTO_marketplace_name=n),A.plugin_repository=i?t:`third-party`,A.plugin_name=i?e.name:`third-party`,i&&e.version&&(A.plugin_version=e.version),Object.assign(A,D(S.pluginInfo))}K(`tengu_input_command`,{...A,invocation_trigger:`user-slash`});let j=v.length>0&&v[0]&&T(v[0]);return{messages:y||v.every(h)||j?v:[R(),...v],shouldQuery:y,allowedTools:b,model:x,resultText:C,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}}async function rt(e,t,n,r,a,o,s,c,l,u){let d=ue(e,r.options.commands);if(d.type===`prompt`&&d.userInvocable!==!1&&Ce(e),d.userInvocable===!1)return{messages:[E({content:F({inputString:`/${e}`,precedingInputBlocks:a})}),E({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:d};try{switch(d.type){case`local-jsx`:return new Promise(e=>{let i=!1,o=(n,r)=>{if(i=!0,r?.display===`skip`){e({messages:[],shouldQuery:!1,command:d,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>E({content:e,isMeta:!0})),s=M()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[N(Y(d,c)),N(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[E({content:F({inputString:Y(d,c),precedingInputBlocks:a})}),E(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${Ee}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:d,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};d.load().then(e=>e.call(o,{...r,canUseTool:c},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:d});return}i||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:d.immediate===!0})}}).catch(t=>{W(t),!i&&(i=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:d}))})});case`local`:{let e=E({content:F({inputString:Y(d,d.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:a})});try{let n=R(),i=await(await d.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:d};if(i.type===`compact`){let t=[n,e,...i.displayText?[E({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 L(),{messages:le(r),shouldQuery:!1,command:d}}return{messages:[e,N(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:d,resultText:i.value}}catch(t){return W(t),{messages:[e,N(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:d}}}case`prompt`:try{return d.context===`fork`?await et(d,t,r,a,n,c??i,u):await Z(d,t,r,a,o,l)}catch(e){return e instanceof je?{messages:[E({content:F({inputString:Y(d,t),precedingInputBlocks:a})}),Se({toolUse:!1})],shouldQuery:!1,command:d}:{messages:[E({content:F({inputString:Y(d,t),precedingInputBlocks:a})}),E({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:d}}}}catch(e){if(e instanceof H)return{messages:[E({content:F({inputString:e.message,precedingInputBlocks:a})})],shouldQuery:!1,command:d};throw e}}function Y(e,t){return d(z(e),t)}function X(e,t=`loading`){return[`<${G}>${e}</${G}>`,`<${U}>${e}</${U}>`,`<skill-format>true</skill-format>`].join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$_ as t,Ap as n,Aw as r,B as i,BC as a,Bw as o,Cm as s,Ds as c,Dv as l,E as u,Ea as d,Fb as f,Fc as p,Ga as m,Ha as h,Ic as g,Ii as _,La as v,Li as y,Mp as b,Np as x,Of as S,Ow as C,Pb as w,Ra as T,Sa as E,Sf as D,Sm as O,Tf as k,Ti as ee,Ts as A,Uh as j,V as te,VC as ne,Wh as M,Xp as re,Xv as ie,Yp as ae,Zv as oe,b as se,bf as ce,c_ as le,ha as N,ji as ue,jp as de,kf as fe,ki as pe,kp as me,kw as P,lc as he,qa as F,ry as ge,sc as I,tv as L,u_ as _e,uc as ve,va as R,wm as ye,ws as be,wv as xe,xa as Se,xf as Ce,ya as we,zC as Te,zi as z,zw as Ee}from"./loadAgentsDir-DaNpxaO-.js";import{Ut as De,Wn as Oe,ft as ke,t as Ae}from"./state-D5D6QpTX.js";import{E as je,R as Me,c as B,f as Ne,i as V,k as H,u as Pe}from"./debug-D58GQBDG.js";import{Dt as Fe,Et as Ie}from"./settings-3xZ0fsvE.js";import{T as U,o as Le,q as Re,s as W,w as G}from"./log-CZ7ploQm.js";import{n as ze,r as K}from"./analytics-DJobLaWP.js";import{Xr as Be,Zr as Ve,dn as He,fn as Ue}from"./model-Do0f476p.js";import{ct as We,ot as Ge}from"./esm-CvHtYRrr.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-BoOZsXU2.js";import{randomUUID as q}from"crypto";function Ye(e,t,n,r,i){let a=0;for(let o of Fe){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}'`),x(e,t,o,s)}:void 0;de(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Ie(),V(),b()}));function Ze(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.slice(1).split(` `);if(!n[0])return null;let r=n[0],i=!1,a=1;n.length>1&&n[1]===`(MCP)`&&(r=`${r} (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Qe=e((()=>{}));function $e(){return!1}function J(){if(!$e())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,i,a,o,c,l){let u=ae(),d=e.pluginInfo?r(e.pluginInfo.repository).marketplace:void 0;K(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...d&&{_PROTO_marketplace_name:d},...D(e.pluginInfo)}});let{skillContent:f,modifiedGetAppState:p,baseAgent:h,promptMessages:g}=await ve(e,t,i);B(`Executing forked slash command /${e.name} with agent ${h.agentType}`);let _=i.options.allowBackgroundForkedSlashCommands===!0;if(_&&J(),_){let t=w(),r=z(e),a=Be(),o=e=>oe({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:a}),d=async()=>{if(!l?.runId)return;let e=await O({runId:l.runId,rootDir:l.rootDir,priority:`later`,workload:a});for(let t of e)ie(t)},f=async e=>{l?.runId&&await s({runId:l.runId,rootDir:l.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let a=Date.now()+$;for(;Date.now()<a&&i.getAppState().mcp.clients.some(e=>e.type===`pending`);)await Ue(Q);let s=i.options.refreshTools?.()??i.options.tools,l=[];for await(let r of n({agentDefinition:h,promptMessages:g,toolUseContext:{...i,getAppState:p,abortController:t},canUseTool:c,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:s,override:{agentId:u}}))l.push(r);let f=I(l,`Command completed`);B(`Background forked command /${r} completed (agent ${u})`),o(`<scheduled-task-result command="/${r}">\n${f}\n</scheduled-task-result>`);try{await d()}catch(e){W(e)}})().catch(async e=>{W(e),o(`<scheduled-task-result command="/${r}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await f(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!l?.runId}}let v=[],y=[],b=`forked-command-${e.name}`,x=0,S=e=>(x++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:f,agentId:u},parentToolUseID:b,toolUseID:`${b}-${x}`,timestamp:new Date().toISOString(),uuid:q()}),C=()=>{o({jsx:fe(y,{tools:i.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};C();try{for await(let t of n({agentDefinition:h,promptMessages:g,toolUseContext:{...i,getAppState:p},canUseTool:c,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:i.options.tools})){v.push(t);let e=m([t]);if(t.type===`assistant`){let n=xe(t);n>0&&i.setResponseLength(e=>e+n);let r=e[0];r&&r.type===`assistant`&&(y.push(S(t)),C())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(y.push(S(t)),C())}}}finally{o(null)}let T=I(v,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${u}`),{messages:[E({content:F({inputString:`/${z(e)} ${t}`.trim(),precedingInputBlocks:a})}),E({content:`<local-command-stdout>\n${T}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:T}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,i,a,o,s,c,l,u){let d=Ze(e);if(!d){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[R(),...i,E({content:F({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:f,args:p,isMcp:m}=d,g=m?`mcp`:ee().has(f)?f:`custom`;if(!_(f,a.options.commands)){let n=!1;try{await Pe().stat(`/${f}`),n=!0}catch{}if(tt(f)&&!n){K(`tengu_input_slash_invalid`,{input:f});let e=`Unknown skill: ${f}`;return{messages:[R(),...i,E({content:F({inputString:e,precedingInputBlocks:t})}),...p?[we(`Args from unknown skill: ${p}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let r=q();return Oe(r),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":r}),{messages:[E({content:F({inputString:e,precedingInputBlocks:t}),uuid:s}),...i],shouldQuery:!0}}let{messages:v,shouldQuery:y,allowedTools:b,model:x,command:S,resultText:C,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}=await rt(f,p,o,a,t,n,c,l,s,u);if(v.length===0){let e={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:t,repository:n}=S.pluginInfo,{marketplace:i}=r(n),a=P(i);e._PROTO_plugin_name=t.name,i&&(e._PROTO_marketplace_name=i),e.plugin_repository=a?n:`third-party`,e.plugin_name=a?t.name:`third-party`,a&&t.version&&(e.plugin_version=t.version),Object.assign(e,D(S.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:x,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}}if(v.length===2&&v[1].type===`user`&&typeof v[1].message.content==`string`&&v[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:f}),{messages:[R(),...v],shouldQuery:y,allowedTools:b,model:x};let A={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:e,repository:t}=S.pluginInfo,{marketplace:n}=r(t),i=P(n);A._PROTO_plugin_name=e.name,n&&(A._PROTO_marketplace_name=n),A.plugin_repository=i?t:`third-party`,A.plugin_name=i?e.name:`third-party`,i&&e.version&&(A.plugin_version=e.version),Object.assign(A,D(S.pluginInfo))}K(`tengu_input_command`,{...A,invocation_trigger:`user-slash`});let j=v.length>0&&v[0]&&T(v[0]);return{messages:y||v.every(h)||j?v:[R(),...v],shouldQuery:y,allowedTools:b,model:x,resultText:C,nextInput:w,submitNextInput:O,deferAutonomyCompletion:k}}async function rt(e,t,n,r,a,o,s,c,l,u){let d=ue(e,r.options.commands);if(d.type===`prompt`&&d.userInvocable!==!1&&Ce(e),d.userInvocable===!1)return{messages:[E({content:F({inputString:`/${e}`,precedingInputBlocks:a})}),E({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:d};try{switch(d.type){case`local-jsx`:return new Promise(e=>{let i=!1,o=(n,r)=>{if(i=!0,r?.display===`skip`){e({messages:[],shouldQuery:!1,command:d,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>E({content:e,isMeta:!0})),s=M()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[N(Y(d,c)),N(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[E({content:F({inputString:Y(d,c),precedingInputBlocks:a})}),E(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${Ee}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:d,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};d.load().then(e=>e.call(o,{...r,canUseTool:c},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:d});return}i||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:d.immediate===!0})}}).catch(t=>{W(t),!i&&(i=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:d}))})});case`local`:{let e=E({content:F({inputString:Y(d,d.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:a})});try{let n=R(),i=await(await d.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:d};if(i.type===`compact`){let t=[n,e,...i.displayText?[E({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 L(),{messages:le(r),shouldQuery:!1,command:d}}return{messages:[e,N(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:d,resultText:i.value}}catch(t){return W(t),{messages:[e,N(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:d}}}case`prompt`:try{return d.context===`fork`?await et(d,t,r,a,n,c??i,u):await Z(d,t,r,a,o,l)}catch(e){return e instanceof je?{messages:[E({content:F({inputString:Y(d,t),precedingInputBlocks:a})}),Se({toolUse:!1})],shouldQuery:!1,command:d}:{messages:[E({content:F({inputString:Y(d,t),precedingInputBlocks:a})}),E({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:d}}}}catch(e){if(e instanceof H)return{messages:[E({content:F({inputString:e.message,precedingInputBlocks:a})})],shouldQuery:!1,command:d};throw e}}function Y(e,t){return d(z(e),t)}function X(e,t=`loading`){return[`<${G}>${e}</${G}>`,`<${U}>${e}</${U}>`,`<skill-format>true</skill-format>`].join(`
2
2
  `)}function it(e,t){return[`<${G}>${e}</${G}>`,`<${U}>/${e}</${U}>`,t?`<command-args>${t}</command-args>`:null].filter(Boolean).join(`
3
3
  `)}function at(e,t){return e.userInvocable===!1&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`mcp`)?X(e.name,e.progressMessage):it(e.name,t)}async function ot(e,t,n,r,i=[]){let a=pe(e,n);if(!a)throw new H(`Unknown command: ${e}`);if(a.type!==`prompt`)throw Error(`Unexpected ${a.type} command. Expected 'prompt' command. Use /${e} directly in the main conversation.`);return Z(a,t,r,[],i)}async function Z(e,t,n,r=[],i=[],o){let s=await e.getPromptForCommand(t,n),c=!a(`hooks`)||ne(e.source);if(e.hooks&&c){let t=ke();Ye(n.setAppState,t,e.hooks,e.name,e.type===`prompt`?e.skillRoot:void 0)}let l=e.source?`${e.source}:${e.name}`:e.name,d=s.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
4
 
@@ -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-Cxx3suBa.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{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.
2
2
  Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
3
3
 
4
4
  Usage:
@@ -0,0 +1 @@
1
+ import{i as e,r as t}from"./prompt-8u06WVES.js";t();export{e as isDeferredTool};
@@ -0,0 +1 @@
1
+ import{lw as e,rw as t}from"./loadAgentsDir-DaNpxaO-.js";e();export{t as clearPromptCache};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{Ad as r,Fd as i,Md as a,Pd as o,fb as s,sb as c,vu as l,yu as u}from"./loadAgentsDir-DXOkUcW3.js";import{Rn as d,t as f}from"./src-DL3w8VPk2.js";import{T as p,c as m,f as h,i as g,u as _,x as v}from"./debug-D58GQBDG.js";import{n as y,t as b}from"./execSyncWrapper-C3ZFV9od.js";import{r as x,t as S}from"./which-BxQ1hpjp.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!x(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,a=r.slice(1),o=D(n);if(o){let r=O(o,e,t),s={detached:!0,stdio:`ignore`},c;return c=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...s,shell:!0}):w(i,[...a,...r],s),c.on(`error`,e=>m(`editor spawn failed: ${e}`,{level:`error`})),c.unref(),!0}let s=d.get(process.stdout);if(!s)return!1;let c=t&&j.test(C(i));s.enterAlternateScreen();try{let r={stdio:`inherit`},o;return o=process.platform===`win32`?T(`${n} ${c?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...a,...c?[`+${t}`,e]:[e]],r),o.error?(m(`editor spawn failed: ${o.error}`,{level:`error`}),!1):!0}finally{s.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),f(),g(),S(),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=_(),n=d.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 i=!F(r);i?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return b(`${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:`${s(r)} exited with code ${t}`}}return{content:null}}finally{i?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,s=r.indexOf(i);if(s!==-1){let e=a(n,o(i));r=r.slice(0,s)+e+r.slice(s+i.length)}}return r}function R(e,t){let n=_(),i=l();try{p(i,t?r(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(i);if(n.content===null)return n;let a=n.content;return a.endsWith(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{Ad as r,Fd as i,Md as a,Pd as o,fb as s,sb as c,vu as l,yu as u}from"./loadAgentsDir-DaNpxaO-.js";import{Rn as d,t as f}from"./src-DL3w8VPk2.js";import{T as p,c as m,f as h,i as g,u as _,x as v}from"./debug-D58GQBDG.js";import{n as y,t as b}from"./execSyncWrapper-C3ZFV9od.js";import{r as x,t as S}from"./which-BxQ1hpjp.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!x(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,a=r.slice(1),o=D(n);if(o){let r=O(o,e,t),s={detached:!0,stdio:`ignore`},c;return c=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...s,shell:!0}):w(i,[...a,...r],s),c.on(`error`,e=>m(`editor spawn failed: ${e}`,{level:`error`})),c.unref(),!0}let s=d.get(process.stdout);if(!s)return!1;let c=t&&j.test(C(i));s.enterAlternateScreen();try{let r={stdio:`inherit`},o;return o=process.platform===`win32`?T(`${n} ${c?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...a,...c?[`+${t}`,e]:[e]],r),o.error?(m(`editor spawn failed: ${o.error}`,{level:`error`}),!1):!0}finally{s.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),f(),g(),S(),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=_(),n=d.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 i=!F(r);i?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return b(`${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:`${s(r)} exited with code ${t}`}}return{content:null}}finally{i?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,s=r.indexOf(i);if(s!==-1){let e=a(n,o(i));r=r.slice(0,s)+e+r.slice(s+i.length)}}return r}function R(e,t){let n=_(),i=l();try{p(i,t?r(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(i);if(n.content===null)return n;let a=n.content;return a.endsWith(`
2
2
  `)&&!a.endsWith(`
3
3
 
4
4
  `)&&(a=a.slice(0,-1)),t&&(a=L(a,e,t)),{content:a}}finally{try{n.unlinkSync(i)}catch{}}}var z,B=e((()=>{i(),f(),P(),y(),h(),c(),v(),u(),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};