@readmagic/workmate 0.0.20 → 0.0.21

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 (420) hide show
  1. package/dist/chunks/AddWorkspaceDirectory-DgAxYgBY.js +1 -0
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-DGMRVexR.js +1 -0
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-Dp6CwZyI.js +1 -0
  4. package/dist/chunks/App-VWyPd524.js +1 -0
  5. package/dist/chunks/ApproveApiKey-Bolw0sPs.js +1 -0
  6. package/dist/chunks/ApproveApiKey-CyNPMd6g.js +1 -0
  7. package/dist/chunks/BackgroundTasksDialog-DxagIOOw.js +2 -0
  8. package/dist/chunks/BypassPermissionsModeDialog-OS2S66zQ.js +1 -0
  9. package/dist/chunks/{DiffDialog-DCpchgp5.js → DiffDialog-CMtml9iw.js} +3 -3
  10. package/dist/chunks/Doctor-Bk9P37mU.js +1 -0
  11. package/dist/chunks/Doctor-D9F3tKsr.js +3 -0
  12. package/dist/chunks/ExitFlow-DhRv5JPj.js +2 -0
  13. package/dist/chunks/{Grove-Dd6rjs5P.js → Grove-Bbh8PpH0.js} +1 -1
  14. package/dist/chunks/{HybridTransport-CJVkWa2u.js → HybridTransport-P1vEUwhv.js} +1 -1
  15. package/dist/chunks/InvalidConfigDialog-xAYpE-20.js +1 -0
  16. package/dist/chunks/InvalidSettingsDialog-CXFSISy3.js +1 -0
  17. package/dist/chunks/MCPConnectionManager-CoId-C__.js +1 -0
  18. package/dist/chunks/MCPToolListView-BQkQ-hyF.js +1 -0
  19. package/dist/chunks/McpParsingWarnings-6ENzOklf.js +1 -0
  20. package/dist/chunks/MessageSelector-BvRVrfg6.js +3 -0
  21. package/dist/chunks/Messages-Cykztq1O.js +10 -0
  22. package/dist/chunks/Onboarding-CfeRwPNQ.js +1 -0
  23. package/dist/chunks/PermissionDialog-BaibiQae.js +1 -0
  24. package/dist/chunks/PressEnterToContinue-DZc_s_pE.js +1 -0
  25. package/dist/chunks/PromptInputFooterSuggestions-Blzgj5yW.js +1 -0
  26. package/dist/chunks/PromptInputHelpMenu-Ckp0k8E3.js +1 -0
  27. package/dist/chunks/QueryEngine-DduzztIG.js +1 -0
  28. package/dist/chunks/REPL-B8e5UU3H.js +128 -0
  29. package/dist/chunks/REPL-C4mbOhyL.js +1 -0
  30. package/dist/chunks/{RemoteSessionManager-BfsOv4K6.js → RemoteSessionManager-BPESC6Wu.js} +2 -2
  31. package/dist/chunks/ResumeConversation-DG1sLryB.js +1 -0
  32. package/dist/chunks/{SSETransport-B3K6eH9I.js → SSETransport-CDNP2PlK.js} +1 -1
  33. package/dist/chunks/{SearchBox-CwwV0W-w.js → SearchBox-C9xxQzh1.js} +1 -1
  34. package/dist/chunks/SearchExtraToolsTool-vK2PP628.js +1 -0
  35. package/dist/chunks/Settings-B7n_dfP-.js +2 -0
  36. package/dist/chunks/TeleportProgress-QL3ibQfK.js +1 -0
  37. package/dist/chunks/TeleportRepoMismatchDialog-f-xl7biD.js +1 -0
  38. package/dist/chunks/TeleportResumeWrapper-DzVcrFuP.js +1 -0
  39. package/dist/chunks/ThemePicker-CIFKZza0.js +1 -0
  40. package/dist/chunks/TrustDialog-C0HEwZPk.js +1 -0
  41. package/dist/chunks/{ValidationErrorsList-BfZ5gcIv.js → ValidationErrorsList-2QWIs_6h.js} +1 -1
  42. package/dist/chunks/add-dir-DmEhPnvj.js +1 -0
  43. package/dist/chunks/{agentDisplay-BM4QG_RX.js → agentDisplay-1Y-N-gqz.js} +1 -1
  44. package/dist/chunks/{agents-BbDBN5l9.js → agents-CvW8XjoJ.js} +1 -1
  45. package/dist/chunks/agents-D96ng5I9.js +101 -0
  46. package/dist/chunks/allErrors-CT2dbBF3.js +1 -0
  47. package/dist/chunks/{api-DyUWfg3a.js → api-DTyrmy1O.js} +1 -1
  48. package/dist/chunks/api-DumFOErN.js +1 -0
  49. package/dist/chunks/{auth-0rn1U4Eq.js → auth-CZ4EsFWF.js} +1 -1
  50. package/dist/chunks/auth-QvonHoG9.js +1 -0
  51. package/dist/chunks/auth-jV5THRH8.js +1 -0
  52. package/dist/chunks/backgroundHousekeeping-C72oPgfD.js +17 -0
  53. package/dist/chunks/backgroundHousekeeping-D9PScHES.js +1 -0
  54. package/dist/chunks/{banner-BkUdig-T.js → banner-ChT5Ri7Q.js} +1 -1
  55. package/dist/chunks/{bg-tGgpwpYx.js → bg-qG2osBbP.js} +2 -2
  56. package/dist/chunks/{branch-CQ38cx5n.js → branch-K8X6jx0i.js} +1 -1
  57. package/dist/chunks/{break-cache-CcwOjTKt.js → break-cache-BZ_UMtEL.js} +1 -1
  58. package/dist/chunks/{bridgeConfig-C5L-7KaP.js → bridgeConfig-C-bI-slm.js} +1 -1
  59. package/dist/chunks/bridgeConfig-_xpxhGB5.js +1 -0
  60. package/dist/chunks/{bridgeMessaging-DVC3qj-C.js → bridgeMessaging-DSJlYarJ.js} +1 -1
  61. package/dist/chunks/{bridgeStatusUtil-Cex6VowM.js → bridgeStatusUtil-DaEq5c69.js} +1 -1
  62. package/dist/chunks/btw-BNs5OX7x.js +1 -0
  63. package/dist/chunks/caches-CC5NHwAz.js +1 -0
  64. package/dist/chunks/caches-nHxJWXgO.js +1 -0
  65. package/dist/chunks/{ccrClient-DO563xlf.js → ccrClient-JnhF5b3z.js} +1 -1
  66. package/dist/chunks/{clear-DmqQBNKg.js → clear-D2KRoibg.js} +1 -1
  67. package/dist/chunks/client-BtTkq0YS.js +1 -0
  68. package/dist/chunks/commands-C_rYjyQZ.js +1 -0
  69. package/dist/chunks/compact-Cqd6vKpn.js +2 -0
  70. package/dist/chunks/config-Be0BkAAr.js +1 -0
  71. package/dist/chunks/{config-DRy1I12M.js → config-DUTgj3js.js} +1 -1
  72. package/dist/chunks/{config-e0Goy478.js → config-DoEDgAfv.js} +1 -1
  73. package/dist/chunks/context-Db9tH1VF.js +1 -0
  74. package/dist/chunks/{context-noninteractive-BzDVMnWC.js → context-noninteractive-CacA9VlT.js} +2 -2
  75. package/dist/chunks/context-noninteractive-D9tJYwi7.js +1 -0
  76. package/dist/chunks/conversation-DWfE4KGH.js +1 -0
  77. package/dist/chunks/conversation-Tvo4EDpQ.js +1 -0
  78. package/dist/chunks/convert-legacy-node-http-options-BZnGSjx2.js +1 -0
  79. package/dist/chunks/{createSSHSession-LVGVXHXL.js → createSSHSession-BQ83MMtr.js} +1 -1
  80. package/dist/chunks/createSession-CqHnHhCR.js +1 -0
  81. package/dist/chunks/{createSession-Dgwxk1WA.js → createSession-DqTtBycR.js} +1 -1
  82. package/dist/chunks/crossProjectResume-DIXtiODF.js +40 -0
  83. package/dist/chunks/{datadog-Bc6wkPne.js → datadog-BuElf2EQ.js} +1 -1
  84. package/dist/chunks/detectRepository-DUJBh5s2.js +1 -0
  85. package/dist/chunks/{detectRepository-CDOJ-M7h.js → detectRepository-pRAVv8SH.js} +1 -1
  86. package/dist/chunks/{diff-DIg66U_d.js → diff-yA6v_dpP.js} +1 -1
  87. package/dist/chunks/{directoryCompletion-BDGcGDuv.js → directoryCompletion-CuA3_YIT.js} +1 -1
  88. package/dist/chunks/doctor-eNAm6OiS.js +1 -0
  89. package/dist/chunks/{entry-B-Y-AYeK.js → entry-DidpiR-D.js} +5 -5
  90. package/dist/chunks/esm-0CwQE5CJ.js +10 -0
  91. package/dist/chunks/esm-BCUC71kt.js +1 -0
  92. package/dist/chunks/esm-BCmY8V0C.js +1 -0
  93. package/dist/chunks/esm-BUJtY-Rb.js +1 -0
  94. package/dist/chunks/esm-BadZVa27.js +1 -0
  95. package/dist/chunks/esm-BbMeEYcz.js +1 -0
  96. package/dist/chunks/esm-sVMjGuep.js +1 -0
  97. package/dist/chunks/execFileNoThrow-B_KRY4cT.js +34 -0
  98. package/dist/chunks/exit-DywUeiYd.js +1 -0
  99. package/dist/chunks/extraUsage-DiAirtuk.js +1 -0
  100. package/dist/chunks/extractMemories-_xiTnX95.js +1 -0
  101. package/dist/chunks/fast-DCXZACT9.js +1 -0
  102. package/dist/chunks/fast-Qo4WVqiW.js +1 -0
  103. package/dist/chunks/{fetchModelList-Dy-x4h3G.js → fetchModelList-fQDsmR3E.js} +1 -1
  104. package/dist/chunks/fetchModelList-woVzIVde.js +1 -0
  105. package/dist/chunks/{fileSuggestions-CFkJktgc.js → fileSuggestions-CRx1D6uk.js} +3 -3
  106. package/dist/chunks/firstPartyEventLogger-B261Wksn.js +3 -0
  107. package/dist/chunks/firstPartyEventLogger-DtFTeHy-.js +1 -0
  108. package/dist/chunks/{flushGate-BjKW7PFC.js → flushGate-BA8dSr0i.js} +1 -1
  109. package/dist/chunks/fpsMetrics-wxj9GAsd.js +1 -0
  110. package/dist/chunks/{gemini-NnmxBoEp.js → gemini-BXAyy1JN.js} +1 -1
  111. package/dist/chunks/generateSessionName-Cwmk2N3F.js +1 -0
  112. package/dist/chunks/{genericProcessUtils-6E7fB1dI.js → genericProcessUtils-Cnyun_Wr.js} +3 -3
  113. package/dist/chunks/{git-By_J4XJL.js → git-Wid-XppW.js} +1 -1
  114. package/dist/chunks/git-hO-TMvXc.js +1 -0
  115. package/dist/chunks/{githubRepoPathMapping-CzgPGOHQ.js → githubRepoPathMapping-OV8U1VFK.js} +1 -1
  116. package/dist/chunks/goal-C9clrwEH.js +3 -0
  117. package/dist/chunks/{grok-BxZ4vTDw.js → grok-CjeCecsZ.js} +1 -1
  118. package/dist/chunks/{grove-CYE1Cfcz.js → grove-DqTnK9nn.js} +2 -2
  119. package/dist/chunks/help-Bb6LdzXK.js +1 -0
  120. package/dist/chunks/{hooks-7iyENdDG.js → hooks-BDgToO1Z.js} +2 -2
  121. package/dist/chunks/hooks-BX2s7aoL.js +1 -0
  122. package/dist/chunks/{initReplBridge-BEZW5PEY.js → initReplBridge-D7cuY_os.js} +1 -1
  123. package/dist/chunks/install-eCA8UACi.js +1 -0
  124. package/dist/chunks/{instrumentation-2HH15DPu.js → instrumentation-BaRKojJh.js} +6 -6
  125. package/dist/chunks/{job-CXz7SLZp.js → job-DYMfSglZ.js} +1 -1
  126. package/dist/chunks/{jwtUtils-C_LG1txt.js → jwtUtils-JE2okZ70.js} +1 -1
  127. package/dist/chunks/keybindings-iBqc1KHL.js +1 -0
  128. package/dist/chunks/launchLocalMemory-IZPGEzMk.js +3 -0
  129. package/dist/chunks/launchOnboarding-BeNf51Ig.js +8 -0
  130. package/dist/chunks/loadAgentsDir-Bpke9CtB.js +1 -0
  131. package/dist/chunks/{loadAgentsDir-DaNpxaO-.js → loadAgentsDir-C96o6gCj.js} +576 -576
  132. package/dist/chunks/loadPluginHooks-0nGlugZ4.js +1 -0
  133. package/dist/chunks/{localSearch-C2SZ9bGW.js → localSearch-DLz5IGGu.js} +1 -1
  134. package/dist/chunks/localSearch-dodgnjGn.js +1 -0
  135. package/dist/chunks/logoUtils-Cg_6QV1Z.js +1 -0
  136. package/dist/chunks/{magicDocs-CrTwULyJ.js → magicDocs-DmPNMnNY.js} +2 -2
  137. package/dist/chunks/{main-Blm02_Js.js → main-7ssnA9Yb.js} +2 -2
  138. package/dist/chunks/{main-bJXadFi0.js → main-BEv6MqMX.js} +34 -34
  139. package/dist/chunks/{managedEnv-CUsdYhAI.js → managedEnv-CHYvwXBH.js} +1 -1
  140. package/dist/chunks/managedEnv-CbjOQmEe.js +1 -0
  141. package/dist/chunks/mappers-D8VLUZ2N.js +1 -0
  142. package/dist/chunks/mcp-BUn3yqsT.js +1 -0
  143. package/dist/chunks/mcp-BskLq9iP.js +2 -0
  144. package/dist/chunks/mcp-C-0DMaXx.js +6 -0
  145. package/dist/chunks/memory-vDkJM58W.js +1 -0
  146. package/dist/chunks/modalContext-DDZdU1J8.js +1 -0
  147. package/dist/chunks/mode-Dbh21H2Y.js +2 -0
  148. package/dist/chunks/model-BaMclMXn.js +1 -0
  149. package/dist/chunks/model-atn3_JBi.js +1 -0
  150. package/dist/chunks/model-vS1Iewyq.js +1 -0
  151. package/dist/chunks/{modelOptions-B3nis9cC.js → modelOptions-Cw1ThINb.js} +1 -1
  152. package/dist/chunks/nativeInstaller-CfZ5uNTh.js +1 -0
  153. package/dist/chunks/omit-B7eQ9q0x.js +1 -0
  154. package/dist/chunks/{onChangeAppState-vKml_lit.js → onChangeAppState-kEAt8nxV.js} +1 -1
  155. package/dist/chunks/{openai-DdupGVdC.js → openai-wh8AX5iz.js} +3 -3
  156. package/dist/chunks/panel-Cm23FDVt.js +1 -0
  157. package/dist/chunks/{partition-BivH9MBJ.js → partition-CENvOfiS.js} +1 -1
  158. package/dist/chunks/permissions-ChuIx-d4.js +3 -0
  159. package/dist/chunks/{pidLock-DiKz5Tza.js → pidLock-C1hmh3YQ.js} +2 -2
  160. package/dist/chunks/plan-s228H7IU.js +1 -0
  161. package/dist/chunks/plugin-DVBEWwMP.js +17 -0
  162. package/dist/chunks/{pluginAutoupdate-C2xTKLR_.js → pluginAutoupdate-aLXhSUVD.js} +1 -1
  163. package/dist/chunks/pluginBlocklist-BprCv0En.js +1 -0
  164. package/dist/chunks/pluginCliCommands-WzzqR1Sr.js +1 -0
  165. package/dist/chunks/{pluginFlagging-DRA0m76J.js → pluginFlagging-BSLuTk3M.js} +1 -1
  166. package/dist/chunks/pluginOperations-Ca9Lup5G.js +2 -0
  167. package/dist/chunks/pluginStartupCheck-DdtxcNwH.js +1 -0
  168. package/dist/chunks/{pluginStartupCheck-BF1N4Lih.js → pluginStartupCheck-xQbHZ5gf.js} +1 -1
  169. package/dist/chunks/plugins-DdIaXpNb.js +4 -0
  170. package/dist/chunks/{poorMode-CKQfWf3S.js → poorMode-Bt_A2arj.js} +1 -1
  171. package/dist/chunks/poorMode-ZIq2oz7q.js +1 -0
  172. package/dist/chunks/print-vxrRE1O2.js +14 -0
  173. package/dist/chunks/processBashCommand-ISucgwpi.js +1 -0
  174. package/dist/chunks/processSlashCommand-BnpXO_fI.js +5 -0
  175. package/dist/chunks/prompt-2AA5W7EH.js +1 -0
  176. package/dist/chunks/prompt-AXiS2LoO.js +1 -0
  177. package/dist/chunks/{prompt-8u06WVES.js → prompt-BNNE5tsG.js} +1 -1
  178. package/dist/chunks/promptEditor-DT6egmcb.js +4 -0
  179. package/dist/chunks/{protocolHandler-DzHVaPl3.js → protocolHandler-DukQ6b4Q.js} +1 -1
  180. package/dist/chunks/{reconciler-RIKmaPg7.js → reconciler-D3zyJCnV.js} +1 -1
  181. package/dist/chunks/refresh-BSG0t4cf.js +1 -0
  182. package/dist/chunks/{registerProtocol-C0IlPEoa.js → registerProtocol-BOEYaX-X.js} +1 -1
  183. package/dist/chunks/{reload-plugins-DC-tbXVv.js → reload-plugins-BFMRhbv8.js} +1 -1
  184. package/dist/chunks/{remoteBridgeCore-NGTnhQgw.js → remoteBridgeCore-D5OwvmAz.js} +1 -1
  185. package/dist/chunks/{remoteManagedSettings-BoOYHzYP.js → remoteManagedSettings-DyGVvvcW.js} +1 -1
  186. package/dist/chunks/rename-BrEwj3Xw.js +1 -0
  187. package/dist/chunks/resume-DR5JbICs.js +2 -0
  188. package/dist/chunks/{ripgrep-C3jtZL7k.js → ripgrep-Dt4a91S5.js} +1 -1
  189. package/dist/chunks/ripgrep-KTOU5s9J.js +1 -0
  190. package/dist/chunks/{runtimeObserver-L6041elO.js → runtimeObserver-CsZw5XBt.js} +2 -2
  191. package/dist/chunks/{runtimeObserver-DzesbvgI.js → runtimeObserver-DS1PK6We.js} +1 -1
  192. package/dist/chunks/sandbox-adapter-BqDyWcol.js +1 -0
  193. package/dist/chunks/sandbox-toggle-B9f_0NQI.js +1 -0
  194. package/dist/chunks/searchExtraTools-2pIT2C8u.js +1 -0
  195. package/dist/chunks/session-wkRTfdo8.js +2 -0
  196. package/dist/chunks/sessionFileAccessHooks-DV22q9JO.js +1 -0
  197. package/dist/chunks/sessionObserver-BLJg0qm_.js +1 -0
  198. package/dist/chunks/{sessionObserver-0D8xFoRK.js → sessionObserver-N7fORFdL.js} +2 -2
  199. package/dist/chunks/{sessionState-CQhbGfmh.js → sessionState-8jutEorw.js} +1 -1
  200. package/dist/chunks/sessionStorage-DRV7IhZF.js +1 -0
  201. package/dist/chunks/sessionTracing-fIp8g04N.js +11 -0
  202. package/dist/chunks/{settings-3xZ0fsvE.js → settings-BowI3jp-.js} +2 -2
  203. package/dist/chunks/settings-CHn0gJCG.js +1 -0
  204. package/dist/chunks/settingsSync-DF4JgSNc.js +1 -0
  205. package/dist/chunks/setup-UiEO9i7F.js +3 -0
  206. package/dist/chunks/{shadowedRuleDetection-Cy9tsuKc.js → shadowedRuleDetection-DEo1hvGi.js} +1 -1
  207. package/dist/chunks/{sideQuestion-Ds7Elgs4.js → sideQuestion-C11KgNGL.js} +3 -3
  208. package/dist/chunks/sinks-DnLqRPEC.js +1 -0
  209. package/dist/chunks/{sinks-BXX72cbf.js → sinks-mGBiINp8.js} +1 -1
  210. package/dist/chunks/skillChangeDetector-Dc6YZXJE.js +1 -0
  211. package/dist/chunks/{skillGapStore-BxCxKPev.js → skillGapStore-H4MkUFUY.js} +2 -2
  212. package/dist/chunks/{skillLifecycle-CfyNC3sW.js → skillLifecycle-ADUTDK7D.js} +2 -2
  213. package/dist/chunks/{skillSearchPanel-CMNJFIEC.js → skillSearchPanel-PpfVDMGR.js} +2 -2
  214. package/dist/chunks/skills-DKtN17ch.js +1 -0
  215. package/dist/chunks/src-9vmGsuSI.js +1 -0
  216. package/dist/chunks/{src-CgZmCiiH.js → src-BacxF9BD.js} +2 -2
  217. package/dist/chunks/{startupProfiler-CbzxVmbv.js → startupProfiler-B90b5vuq.js} +1 -1
  218. package/dist/chunks/startupProfiler-DG2TN5R_.js +1 -0
  219. package/dist/chunks/staticRender-BVWx0IM1.js +1 -0
  220. package/dist/chunks/stats-D4LEtkrw.js +1 -0
  221. package/dist/chunks/status-0ZBx6Ls0.js +2 -0
  222. package/dist/chunks/status-BUJ4-omB.js +1 -0
  223. package/dist/chunks/{statusNoticeHelpers-CZoOse-_.js → statusNoticeHelpers-BrpQWj0l.js} +1 -1
  224. package/dist/chunks/{stringUtils-CKD8qDqx.js → stringUtils-D7oJIyY2.js} +1 -1
  225. package/dist/chunks/switcher-D7Ey5uIi.js +1 -0
  226. package/dist/chunks/{switcher-DQF5ZNal.js → switcher-DWfKi17X.js} +1 -1
  227. package/dist/chunks/{syncCache-qWJ_VfBo.js → syncCache-DUhciJLz.js} +1 -1
  228. package/dist/chunks/{tasks-C8pb6ftc.js → tasks-BwSsj2vI.js} +1 -1
  229. package/dist/chunks/teleport-DwZMevmQ.js +1 -0
  230. package/dist/chunks/{templateJobs-DJ4dcfcL.js → templateJobs-fiKuu4DK.js} +1 -1
  231. package/dist/chunks/{terminalSetup-7PdC4fV5.js → terminalSetup-Cte5a4hM.js} +1 -1
  232. package/dist/chunks/{terminalSetup-kWdZRKWq.js → terminalSetup-a7-BNS4T.js} +1 -1
  233. package/dist/chunks/theme-CAoGjf2D.js +1 -0
  234. package/dist/chunks/{tmux-CpGd0Aca.js → tmux-DA06aewY.js} +1 -1
  235. package/dist/chunks/{toolEventObserver-D2nk8ZbW.js → toolEventObserver-Cq_ZV7x9.js} +1 -1
  236. package/dist/chunks/toolPool-mdsxlKWR.js +1 -0
  237. package/dist/chunks/{trustedDevice-CB6rNzl-.js → trustedDevice-C1m--Yjw.js} +1 -1
  238. package/dist/chunks/trustedDevice-CeDIk_ln.js +1 -0
  239. package/dist/chunks/{udsClient-U7MEfYj7.js → udsClient-BcwsY0XE.js} +1 -1
  240. package/dist/chunks/useExitOnCtrlCDWithKeybindings-L5idX6Kz.js +1 -0
  241. package/dist/chunks/useMainLoopModel-VXeS2EC6.js +1 -0
  242. package/dist/chunks/useManagePlugins-CAXp5CfH.js +1 -0
  243. package/dist/chunks/useMergedTools-DYXrPTIA.js +1 -0
  244. package/dist/chunks/useSearchInput-Bxl4wGcZ.js +1 -0
  245. package/dist/chunks/useSettingsErrors-sbjsaT7k.js +1 -0
  246. package/dist/chunks/{userAgent-i-oGzf40.js → userAgent-NbKd-hN7.js} +1 -1
  247. package/dist/chunks/util-DU63xTwZ.js +1 -0
  248. package/dist/chunks/validatePlugin-DQ_9OCpP.js +1 -0
  249. package/dist/chunks/{vim-BagKUX4j.js → vim-xruiCyUd.js} +1 -1
  250. package/dist/chunks/which-B8rchd8P.js +1 -0
  251. package/dist/chunks/{workerRegistry-BjxoZ12l.js → workerRegistry-BBgquE8F.js} +2 -2
  252. package/dist/chunks/worktree-C28I8mFB.js +1 -0
  253. package/dist/cli.js +1 -1
  254. package/package.json +3 -21
  255. package/dist/chunks/AddWorkspaceDirectory-BYNvxNrD.js +0 -1
  256. package/dist/chunks/AgentsMdExternalIncludesDialog-BSSz86ER.js +0 -1
  257. package/dist/chunks/AgentsMdExternalIncludesDialog-CMEGV4Md.js +0 -1
  258. package/dist/chunks/App-W_9d1DjK.js +0 -1
  259. package/dist/chunks/ApproveApiKey-Bf1Rb8Ql.js +0 -1
  260. package/dist/chunks/ApproveApiKey-wpdvXpFr.js +0 -1
  261. package/dist/chunks/BackgroundTasksDialog-lGn1Wj1k.js +0 -2
  262. package/dist/chunks/BypassPermissionsModeDialog-CjVjyNf8.js +0 -1
  263. package/dist/chunks/Doctor-6SjW91rd.js +0 -1
  264. package/dist/chunks/Doctor-FPYTivHw.js +0 -3
  265. package/dist/chunks/ExitFlow-Dy8_1D8J.js +0 -2
  266. package/dist/chunks/InvalidConfigDialog-Bisj9ic_.js +0 -1
  267. package/dist/chunks/InvalidSettingsDialog-DyTPNRQR.js +0 -1
  268. package/dist/chunks/MCPConnectionManager-DfyoZaiu.js +0 -1
  269. package/dist/chunks/MCPToolListView-Dioupv8F.js +0 -1
  270. package/dist/chunks/McpParsingWarnings-BUlgpZAF.js +0 -1
  271. package/dist/chunks/MessageSelector-D8fylxPg.js +0 -3
  272. package/dist/chunks/Messages-BZDFMYBT.js +0 -10
  273. package/dist/chunks/Onboarding-BKLomZYo.js +0 -1
  274. package/dist/chunks/PermissionDialog-BPhvs5xH.js +0 -1
  275. package/dist/chunks/PressEnterToContinue-Dwoh6CaW.js +0 -1
  276. package/dist/chunks/PromptInputFooterSuggestions-DCum89fF.js +0 -1
  277. package/dist/chunks/PromptInputHelpMenu-DG2lRqis.js +0 -1
  278. package/dist/chunks/QueryEngine-CyGHpX7M.js +0 -1
  279. package/dist/chunks/REPL-BDsz8KIx.js +0 -1
  280. package/dist/chunks/REPL-CCBNfZfs.js +0 -128
  281. package/dist/chunks/ResumeConversation-pC8NLq0F.js +0 -1
  282. package/dist/chunks/SearchExtraToolsTool-DYoxHo9T.js +0 -1
  283. package/dist/chunks/Settings-CKaGmKg2.js +0 -2
  284. package/dist/chunks/TeleportProgress-CkgSp1cs.js +0 -1
  285. package/dist/chunks/TeleportRepoMismatchDialog-DdO_rECq.js +0 -1
  286. package/dist/chunks/TeleportResumeWrapper-BeG4N-2z.js +0 -1
  287. package/dist/chunks/ThemePicker-iD9ufy99.js +0 -1
  288. package/dist/chunks/TrustDialog-qO5OdQt8.js +0 -1
  289. package/dist/chunks/add-dir-C4eSVlZ6.js +0 -1
  290. package/dist/chunks/agents-D3APE_8d.js +0 -101
  291. package/dist/chunks/allErrors-BkgB7JNK.js +0 -1
  292. package/dist/chunks/api-BHBK9axp.js +0 -1
  293. package/dist/chunks/auth-BEoTPSgC.js +0 -1
  294. package/dist/chunks/auth-BPug7U_u.js +0 -1
  295. package/dist/chunks/backgroundHousekeeping-D7xAhUaE.js +0 -1
  296. package/dist/chunks/backgroundHousekeeping-km82qEh0.js +0 -17
  297. package/dist/chunks/bridgeConfig-CJMjDoaP.js +0 -1
  298. package/dist/chunks/btw-_P96ffHR.js +0 -1
  299. package/dist/chunks/caches-DH-q8Fjf.js +0 -1
  300. package/dist/chunks/caches-Dq0pJFDP.js +0 -1
  301. package/dist/chunks/client-C19cqYQS.js +0 -1
  302. package/dist/chunks/commands-BkpqHY9F.js +0 -1
  303. package/dist/chunks/compact-DuVIvqMu.js +0 -2
  304. package/dist/chunks/config-DMP6-Ccr.js +0 -1
  305. package/dist/chunks/context-DjgMzIfe.js +0 -1
  306. package/dist/chunks/context-noninteractive-DV7bIJCm.js +0 -1
  307. package/dist/chunks/conversation-BBOE_EoE.js +0 -1
  308. package/dist/chunks/conversation-WxH5pb2z.js +0 -1
  309. package/dist/chunks/createSession-BUzna9-E.js +0 -1
  310. package/dist/chunks/crossProjectResume-6B2NYy8a.js +0 -40
  311. package/dist/chunks/detectRepository-Cv9-k6dg.js +0 -1
  312. package/dist/chunks/doctor-BhUmhHQU.js +0 -1
  313. package/dist/chunks/esm-BYnFh4pG.js +0 -1
  314. package/dist/chunks/esm-Bx6rTxIs.js +0 -1
  315. package/dist/chunks/esm-C367Cyo-.js +0 -1
  316. package/dist/chunks/esm-CXM9jqO_.js +0 -1
  317. package/dist/chunks/esm-CXczu_-W.js +0 -1
  318. package/dist/chunks/esm-CXt5K8Xt.js +0 -1
  319. package/dist/chunks/esm-Cb-L4oAk.js +0 -1
  320. package/dist/chunks/esm-CvHtYRrr.js +0 -1
  321. package/dist/chunks/esm-DhRjocaU.js +0 -1
  322. package/dist/chunks/esm-DklLYEuz.js +0 -1
  323. package/dist/chunks/esm-IYgGg4wR.js +0 -1
  324. package/dist/chunks/esm-lyfry1WB.js +0 -10
  325. package/dist/chunks/execFileNoThrow-Bmb5HEFz.js +0 -34
  326. package/dist/chunks/exit-CW2eqUrR.js +0 -1
  327. package/dist/chunks/extraUsage-CkTon7ib.js +0 -1
  328. package/dist/chunks/extractMemories-CfmbvayQ.js +0 -1
  329. package/dist/chunks/fast-ByahC7Gw.js +0 -1
  330. package/dist/chunks/fast-xtIP4u4y.js +0 -1
  331. package/dist/chunks/fetchModelList-D9aePIPW.js +0 -1
  332. package/dist/chunks/firstPartyEventLogger-Bt9iG9xk.js +0 -1
  333. package/dist/chunks/firstPartyEventLogger-DqGSujCz.js +0 -3
  334. package/dist/chunks/fpsMetrics-Dk_pnSHJ.js +0 -1
  335. package/dist/chunks/generateSessionName-EpqGW-T2.js +0 -1
  336. package/dist/chunks/git-zJCasBa6.js +0 -1
  337. package/dist/chunks/goal-DbS8yJfB.js +0 -3
  338. package/dist/chunks/help-DatnwM25.js +0 -1
  339. package/dist/chunks/hooks-DjbqtbUV.js +0 -1
  340. package/dist/chunks/install-DJukI-kL.js +0 -1
  341. package/dist/chunks/keybindings-C9l5il16.js +0 -1
  342. package/dist/chunks/launchLocalMemory-BfGenqj1.js +0 -3
  343. package/dist/chunks/launchOnboarding-DjMmXeQE.js +0 -8
  344. package/dist/chunks/loadAgentsDir-DcI-8FQF.js +0 -1
  345. package/dist/chunks/loadPluginHooks-CGgpcyEC.js +0 -1
  346. package/dist/chunks/localSearch-CTTwYTU1.js +0 -1
  347. package/dist/chunks/logoUtils-CbIqOFrX.js +0 -1
  348. package/dist/chunks/managedEnv-DXeaUDSK.js +0 -1
  349. package/dist/chunks/mappers-_B-s9fNz.js +0 -1
  350. package/dist/chunks/mcp-BbbYzWpy.js +0 -6
  351. package/dist/chunks/mcp-D91sH9a8.js +0 -1
  352. package/dist/chunks/mcp-Dx-zgUgu.js +0 -2
  353. package/dist/chunks/memory-BeL7ui9m.js +0 -1
  354. package/dist/chunks/modalContext-wY9CeN4G.js +0 -1
  355. package/dist/chunks/mode-D695kgLI.js +0 -2
  356. package/dist/chunks/model-DX0TtzqX.js +0 -1
  357. package/dist/chunks/model-Do0f476p.js +0 -1
  358. package/dist/chunks/model-DpcM8dz5.js +0 -1
  359. package/dist/chunks/nativeInstaller-CymO8TNe.js +0 -1
  360. package/dist/chunks/omit-DO61BHZu.js +0 -1
  361. package/dist/chunks/panel-CVd1dzYl.js +0 -1
  362. package/dist/chunks/permissions-C9iqR4_N.js +0 -3
  363. package/dist/chunks/plan-KDN5IGWY.js +0 -1
  364. package/dist/chunks/plugin-D0rzUb8E.js +0 -17
  365. package/dist/chunks/pluginBlocklist-xdiUmUpt.js +0 -1
  366. package/dist/chunks/pluginCliCommands-CIDDvVN7.js +0 -1
  367. package/dist/chunks/pluginOperations-BEYsarAn.js +0 -2
  368. package/dist/chunks/pluginStartupCheck-DVkI4pqo.js +0 -1
  369. package/dist/chunks/plugins-CWWU4BKs.js +0 -4
  370. package/dist/chunks/poorMode-BTIe8W_H.js +0 -1
  371. package/dist/chunks/print-B5H2xbBS.js +0 -14
  372. package/dist/chunks/processBashCommand-EQ9EWaRV.js +0 -1
  373. package/dist/chunks/processSlashCommand-C4PKNyFT.js +0 -5
  374. package/dist/chunks/prompt-B9sDzLPK.js +0 -1
  375. package/dist/chunks/prompt-WsoTRhoh.js +0 -1
  376. package/dist/chunks/promptEditor-Cr4w-4Bz.js +0 -4
  377. package/dist/chunks/refresh-CCSCAjgz.js +0 -1
  378. package/dist/chunks/rename-DS1AmW-F.js +0 -1
  379. package/dist/chunks/resume-Cf5PSoPw.js +0 -2
  380. package/dist/chunks/ripgrep-CBUbn6Po.js +0 -1
  381. package/dist/chunks/sandbox-adapter-Z4Phj31K.js +0 -1
  382. package/dist/chunks/sandbox-toggle-COZE8Lo4.js +0 -1
  383. package/dist/chunks/searchExtraTools-CvkRbL2m.js +0 -1
  384. package/dist/chunks/session-BvA99K4j.js +0 -2
  385. package/dist/chunks/sessionFileAccessHooks-6XfAf6ke.js +0 -1
  386. package/dist/chunks/sessionObserver-CRWUBJEY.js +0 -1
  387. package/dist/chunks/sessionStorage-DqEuxDlb.js +0 -1
  388. package/dist/chunks/sessionTracing-BoOZsXU2.js +0 -11
  389. package/dist/chunks/settings-Crx1cI1u.js +0 -1
  390. package/dist/chunks/settingsSync-rkWmClKS.js +0 -1
  391. package/dist/chunks/setup-D8L275fT.js +0 -3
  392. package/dist/chunks/sinks-DMp6uEzM.js +0 -1
  393. package/dist/chunks/skillChangeDetector-CtithJ4a.js +0 -1
  394. package/dist/chunks/skills-DXMk-498.js +0 -1
  395. package/dist/chunks/src-D3yIF9I42.js +0 -1
  396. package/dist/chunks/src-DQOX_xI1.js +0 -1
  397. package/dist/chunks/src-Dt5IJd3C.js +0 -1
  398. package/dist/chunks/src-Dvp6-vB7.js +0 -19
  399. package/dist/chunks/src-PM8NIIu_.js +0 -1
  400. package/dist/chunks/startupProfiler-uHetQush.js +0 -1
  401. package/dist/chunks/staticRender-D9AbnQFr.js +0 -1
  402. package/dist/chunks/stats-Ce15gc3E.js +0 -1
  403. package/dist/chunks/status-CFrLuGbf.js +0 -2
  404. package/dist/chunks/status-D5OCkMZG.js +0 -1
  405. package/dist/chunks/switcher-AiMcRzoi.js +0 -1
  406. package/dist/chunks/teleport-Bi_1VFIZ.js +0 -1
  407. package/dist/chunks/theme-CEKOCSLw.js +0 -1
  408. package/dist/chunks/toolPool-Df5iUqJ-.js +0 -1
  409. package/dist/chunks/trustedDevice-DXGePUAC.js +0 -1
  410. package/dist/chunks/useExitOnCtrlCDWithKeybindings-Bw0mlTT9.js +0 -1
  411. package/dist/chunks/useMainLoopModel-CIG2cjS2.js +0 -1
  412. package/dist/chunks/useManagePlugins-MSHw-qHx.js +0 -1
  413. package/dist/chunks/useMergedTools-Bb-INJa2.js +0 -1
  414. package/dist/chunks/useSearchInput-QL_VtdJD.js +0 -1
  415. package/dist/chunks/useSettingsErrors-Dvi6zLCr.js +0 -1
  416. package/dist/chunks/util-CLQvtXuD.js +0 -1
  417. package/dist/chunks/validatePlugin-1mTZ3TJR.js +0 -1
  418. package/dist/chunks/which-BxQ1hpjp.js +0 -1
  419. package/dist/chunks/worktree-DpksgxdF.js +0 -1
  420. /package/dist/chunks/{src-DL3w8VPk2.js → src-DL3w8VPk.js} +0 -0
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{P as t,R as n,c as r,i}from"./debug-D58GQBDG.js";import{i as a,t as o}from"./sessionIdCompat-Dgp6PW_1.js";import{i as s,o as c}from"./debugUtils-DXBRbwCE.js";async function l({environmentId:e,title:n,events:i,gitRepoUrl:a,branch:o,signal:c,baseUrl:l,getAccessToken:u,permissionMode:d}){let{getClaudeAIOAuthTokens:f}=await import(`./auth-BEoTPSgC.js`),{getOrganizationUUID:p}=await import(`./client-C19cqYQS.js`),{getOauthConfig:m}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:h}=await import(`./api-BHBK9axp.js`),{parseGitHubRepository:g}=await import(`./detectRepository-Cv9-k6dg.js`),{getDefaultBranch:_}=await import(`./git-zJCasBa6.js`),{getMainLoopModel:v}=await import(`./model-DX0TtzqX.js`),{default:y}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:b}=await import(`./bridgeConfig-CJMjDoaP.js`),x=u?.()??f()?.accessToken;if(!x)return r(`[bridge] No access token for session creation`),null;let S=b()?`self-hosted`:await p();if(!S)return r(`[bridge] No org UUID for session creation`),null;let C=null,w=null;if(a){let{parseGitRemote:e}=await import(`./detectRepository-Cv9-k6dg.js`),t=e(a);if(t){let{host:e,owner:n,name:r}=t,i=o||await _()||void 0;C={type:`git_repository`,url:`https://${e}/${n}/${r}`,revision:i},w={type:`git_repository`,git_info:{type:`github`,repo:`${n}/${r}`,branches:[`claude/${o||`task`}`]}}}else{let e=g(a);if(e){let[t,n]=e.split(`/`);if(t&&n){let e=o||await _()||void 0;C={type:`git_repository`,url:`https://github.com/${t}/${n}`,revision:e},w={type:`git_repository`,git_info:{type:`github`,repo:`${t}/${n}`,branches:[`claude/${o||`task`}`]}}}}}}let T={...n!==void 0&&{title:n},events:i,session_context:{sources:C?[C]:[],outcomes:w?[w]:[],model:v()},environment_id:e,source:`remote-control`,...d&&{permission_mode:d}},E={...h(x),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":S},D=`${l??m().BASE_API_URL}/v1/sessions`,O;try{O=await y.post(D,T,{headers:E,signal:c,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session creation request failed: ${t(e)}`),null}if(!(O.status===200||O.status===201)){let e=s(O.data);return r(`[bridge] Session creation failed with status ${O.status}${e?`: ${e}`:``}`),null}let k=O.data;return!k||typeof k!=`object`||!(`id`in k)||typeof k.id!=`string`?(r(`[bridge] No session ID in response`),null):k.id}async function u(e,n){let{getClaudeAIOAuthTokens:i}=await import(`./auth-BEoTPSgC.js`),{getOrganizationUUID:a}=await import(`./client-C19cqYQS.js`),{getOauthConfig:o}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:c}=await import(`./api-BHBK9axp.js`),{default:l}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:u}=await import(`./bridgeConfig-CJMjDoaP.js`),d=n?.getAccessToken?.()??i()?.accessToken;if(!d)return r(`[bridge] No access token for session fetch`),null;let f=u()?`self-hosted`:await a();if(!f)return r(`[bridge] No org UUID for session fetch`),null;let p={...c(d),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":f},m=`${n?.baseUrl??o().BASE_API_URL}/v1/sessions/${e}`;r(`[bridge] Fetching session ${e}`);let h;try{h=await l.get(m,{headers:p,timeout:1e4,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session fetch request failed: ${t(e)}`),null}if(h.status!==200){let e=s(h.data);return r(`[bridge] Session fetch failed with status ${h.status}${e?`: ${e}`:``}`),null}return h.data}async function d(e,t){let{getClaudeAIOAuthTokens:n}=await import(`./auth-BEoTPSgC.js`),{getOrganizationUUID:i}=await import(`./client-C19cqYQS.js`),{getOauthConfig:a}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:o}=await import(`./api-BHBK9axp.js`),{default:c}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:l}=await import(`./bridgeConfig-CJMjDoaP.js`),u=t?.getAccessToken?.()??n()?.accessToken;if(!u){r(`[bridge] No access token for session archive`);return}let d=l()?`self-hosted`:await i();if(!d){r(`[bridge] No org UUID for session archive`);return}let f={...o(u),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":d},p=`${t?.baseUrl??a().BASE_API_URL}/v1/sessions/${e}/archive`;r(`[bridge] Archiving session ${e}`);let m=await c.post(p,{},{headers:f,timeout:t?.timeoutMs??1e4,validateStatus:e=>e<500});if(m.status===200)r(`[bridge] Session ${e} archived successfully`);else{let e=s(m.data);r(`[bridge] Session archive failed with status ${m.status}${e?`: ${e}`:``}`)}}async function f(e,n,i){let{getClaudeAIOAuthTokens:o}=await import(`./auth-BEoTPSgC.js`),{getOrganizationUUID:c}=await import(`./client-C19cqYQS.js`),{getOauthConfig:l}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:u}=await import(`./api-BHBK9axp.js`),{default:d}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:f}=await import(`./bridgeConfig-CJMjDoaP.js`),p=i?.getAccessToken?.()??o()?.accessToken;if(!p){r(`[bridge] No access token for session title update`);return}let m=f()?`self-hosted`:await c();if(!m){r(`[bridge] No org UUID for session title update`);return}let h={...u(p),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":m},g=a(e),_=`${i?.baseUrl??l().BASE_API_URL}/v1/sessions/${g}`;r(`[bridge] Updating session title: ${g} → ${n}`);try{let e=await d.patch(_,{title:n},{headers:h,timeout:1e4,validateStatus:e=>e<500});if(e.status===200)r(`[bridge] Session title updated successfully`);else{let t=s(e.data);r(`[bridge] Session title update failed with status ${e.status}${t?`: ${t}`:``}`)}}catch(e){r(`[bridge] Session title update request failed: ${t(e)}`)}}var p=e((()=>{i(),n(),c(),o()}));export{f as a,p as i,l as n,u as r,d as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{P as t,R as n,c as r,i}from"./debug-D58GQBDG.js";import{i as a,t as o}from"./sessionIdCompat-Dgp6PW_1.js";import{i as s,o as c}from"./debugUtils-DXBRbwCE.js";async function l({environmentId:e,title:n,events:i,gitRepoUrl:a,branch:o,signal:c,baseUrl:l,getAccessToken:u,permissionMode:d}){let{getClaudeAIOAuthTokens:f}=await import(`./auth-jV5THRH8.js`),{getOrganizationUUID:p}=await import(`./client-BtTkq0YS.js`),{getOauthConfig:m}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:h}=await import(`./api-DumFOErN.js`),{parseGitHubRepository:g}=await import(`./detectRepository-DUJBh5s2.js`),{getDefaultBranch:_}=await import(`./git-hO-TMvXc.js`),{getMainLoopModel:v}=await import(`./model-atn3_JBi.js`),{default:y}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:b}=await import(`./bridgeConfig-_xpxhGB5.js`),x=u?.()??f()?.accessToken;if(!x)return r(`[bridge] No access token for session creation`),null;let S=b()?`self-hosted`:await p();if(!S)return r(`[bridge] No org UUID for session creation`),null;let C=null,w=null;if(a){let{parseGitRemote:e}=await import(`./detectRepository-DUJBh5s2.js`),t=e(a);if(t){let{host:e,owner:n,name:r}=t,i=o||await _()||void 0;C={type:`git_repository`,url:`https://${e}/${n}/${r}`,revision:i},w={type:`git_repository`,git_info:{type:`github`,repo:`${n}/${r}`,branches:[`claude/${o||`task`}`]}}}else{let e=g(a);if(e){let[t,n]=e.split(`/`);if(t&&n){let e=o||await _()||void 0;C={type:`git_repository`,url:`https://github.com/${t}/${n}`,revision:e},w={type:`git_repository`,git_info:{type:`github`,repo:`${t}/${n}`,branches:[`claude/${o||`task`}`]}}}}}}let T={...n!==void 0&&{title:n},events:i,session_context:{sources:C?[C]:[],outcomes:w?[w]:[],model:v()},environment_id:e,source:`remote-control`,...d&&{permission_mode:d}},E={...h(x),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":S},D=`${l??m().BASE_API_URL}/v1/sessions`,O;try{O=await y.post(D,T,{headers:E,signal:c,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session creation request failed: ${t(e)}`),null}if(!(O.status===200||O.status===201)){let e=s(O.data);return r(`[bridge] Session creation failed with status ${O.status}${e?`: ${e}`:``}`),null}let k=O.data;return!k||typeof k!=`object`||!(`id`in k)||typeof k.id!=`string`?(r(`[bridge] No session ID in response`),null):k.id}async function u(e,n){let{getClaudeAIOAuthTokens:i}=await import(`./auth-jV5THRH8.js`),{getOrganizationUUID:a}=await import(`./client-BtTkq0YS.js`),{getOauthConfig:o}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:c}=await import(`./api-DumFOErN.js`),{default:l}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:u}=await import(`./bridgeConfig-_xpxhGB5.js`),d=n?.getAccessToken?.()??i()?.accessToken;if(!d)return r(`[bridge] No access token for session fetch`),null;let f=u()?`self-hosted`:await a();if(!f)return r(`[bridge] No org UUID for session fetch`),null;let p={...c(d),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":f},m=`${n?.baseUrl??o().BASE_API_URL}/v1/sessions/${e}`;r(`[bridge] Fetching session ${e}`);let h;try{h=await l.get(m,{headers:p,timeout:1e4,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session fetch request failed: ${t(e)}`),null}if(h.status!==200){let e=s(h.data);return r(`[bridge] Session fetch failed with status ${h.status}${e?`: ${e}`:``}`),null}return h.data}async function d(e,t){let{getClaudeAIOAuthTokens:n}=await import(`./auth-jV5THRH8.js`),{getOrganizationUUID:i}=await import(`./client-BtTkq0YS.js`),{getOauthConfig:a}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:o}=await import(`./api-DumFOErN.js`),{default:c}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:l}=await import(`./bridgeConfig-_xpxhGB5.js`),u=t?.getAccessToken?.()??n()?.accessToken;if(!u){r(`[bridge] No access token for session archive`);return}let d=l()?`self-hosted`:await i();if(!d){r(`[bridge] No org UUID for session archive`);return}let f={...o(u),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":d},p=`${t?.baseUrl??a().BASE_API_URL}/v1/sessions/${e}/archive`;r(`[bridge] Archiving session ${e}`);let m=await c.post(p,{},{headers:f,timeout:t?.timeoutMs??1e4,validateStatus:e=>e<500});if(m.status===200)r(`[bridge] Session ${e} archived successfully`);else{let e=s(m.data);r(`[bridge] Session archive failed with status ${m.status}${e?`: ${e}`:``}`)}}async function f(e,n,i){let{getClaudeAIOAuthTokens:o}=await import(`./auth-jV5THRH8.js`),{getOrganizationUUID:c}=await import(`./client-BtTkq0YS.js`),{getOauthConfig:l}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:u}=await import(`./api-DumFOErN.js`),{default:d}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:f}=await import(`./bridgeConfig-_xpxhGB5.js`),p=i?.getAccessToken?.()??o()?.accessToken;if(!p){r(`[bridge] No access token for session title update`);return}let m=f()?`self-hosted`:await c();if(!m){r(`[bridge] No org UUID for session title update`);return}let h={...u(p),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":m},g=a(e),_=`${i?.baseUrl??l().BASE_API_URL}/v1/sessions/${g}`;r(`[bridge] Updating session title: ${g} → ${n}`);try{let e=await d.patch(_,{title:n},{headers:h,timeout:1e4,validateStatus:e=>e<500});if(e.status===200)r(`[bridge] Session title updated successfully`);else{let t=s(e.data);r(`[bridge] Session title update failed with status ${e.status}${t?`: ${t}`:``}`)}}catch(e){r(`[bridge] Session title update request failed: ${t(e)}`)}}var p=e((()=>{i(),n(),c(),o()}));export{f as a,p as i,l as n,u as r,d as t};
@@ -0,0 +1,40 @@
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Ci as n,Du as r,GS as i,Lu as a,Nr as o,Ou as s,Qw as c,Ru as l,Sc as u,Si as d,Sr as f,Zw as p,_u as ee,bc as m,br as h,fr as g,ir as te,lu as ne,np as _,oi as v,rp as re,su as ie,vu as ae,wr as y,zS as oe}from"./loadAgentsDir-C96o6gCj.js";import{C as se,D as b,Gr as x,H as ce,I as S,P as C,T as w,Wt as le,Xn as ue,ai as T,di as E,fi as de,hn as fe,k as pe,oi as me,ot as he,p as D,t as ge}from"./src-DL3w8VPk.js";import{t as O}from"./jsx-runtime-Bb4Xn-E0.js";import{$ as _e,Ut as ve,ft as ye}from"./state-D5D6QpTX.js";import{S as be,c as k,i as xe,x as Se}from"./debug-D58GQBDG.js";import{In as A,Ln as Ce}from"./settings-BowI3jp-.js";import{i as we,m as Te}from"./git-Wid-XppW.js";import{a as j,o as Ee,s as De}from"./log-CZ7ploQm.js";import{n as Oe,r as M}from"./analytics-DJobLaWP.js";import{C as N,d as ke,m as Ae,v as je}from"./startupProfiler-B90b5vuq.js";import{_ as P,h as F}from"./model-BaMclMXn.js";import{i as Me,r as Ne}from"./shellQuote-Ddgr1vif.js";import{n as Pe,t as Fe}from"./useExitOnCtrlCDWithKeybindings-L5idX6Kz.js";import{t as Ie}from"./SearchBox-C9xxQzh1.js";import{n as Le,t as Re}from"./useSearchInput-Bxl4wGcZ.js";import{n as I,t as ze}from"./Messages-Cykztq1O.js";function Be({log:e,onExit:t,onSelect:n}){let[r,i]=L.useState(null);L.useEffect(()=>{i(null),y(e)&&o(e).then(i)},[e]);let a=y(e)&&r===null,s=r??e,c=g(s)||``,l=m();return le(`confirm:no`,t,{context:`Confirmation`}),le(`confirm:yes`,(0,L.useCallback)(()=>{n(r??e)},[n,r,e]),{context:`Confirmation`}),a?(0,R.jsxs)(S,{flexDirection:`column`,padding:1,children:[(0,R.jsx)(D,{message:`Loading session…`}),(0,R.jsx)(C,{dimColor:!0,children:(0,R.jsx)(w,{children:(0,R.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})})})]}):(0,R.jsxs)(S,{flexDirection:`column`,children:[(0,R.jsx)(ze,{messages:s.messages,tools:l,commands:[],verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:new Set,isMessageSelectorVisible:!1,conversationId:c,screen:`transcript`,streamingToolUses:[],showAllInTranscript:!0,isLoading:!1}),(0,R.jsxs)(S,{flexShrink:0,flexDirection:`column`,borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,paddingLeft:2,children:[(0,R.jsxs)(C,{children:[Ae(s.modified),` · `,s.messageCount,` messages`,s.gitBranch?` · ${s.gitBranch}`:``]}),(0,R.jsx)(C,{dimColor:!0,children:(0,R.jsxs)(w,{children:[(0,R.jsx)(b,{shortcut:`Enter`,action:`resume`}),(0,R.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})]})]})}var L,R,Ve=e((()=>{L=t(T(),1),ge(),oe(),u(),je(),h(),re(),I(),R=O()}));function z(e,t){if(e===V)return 5;let n=x(e),r=t?Math.min(n,t-H-U):n;return Math.max(0,r)+H+U}function He(e,t){let n=t-H-U;return x(e)<=n?e:n<=1?e.charAt(0):N(e,n)}function Ue({tabs:e,selectedIndex:t,availableWidth:n,showAllProjects:r=!1}){let i=r?`Resume (All Projects)`:`Resume`,a=i.length+1,o=Math.max(Je,G),s=n-a-o-2,c=Math.max(0,Math.min(t,e.length-1)),l=Math.max(20,Math.floor(s/2)),u=e.map(e=>z(e,l)),d=0,f=e.length;if(u.reduce((e,t,n)=>e+t+ +(n<u.length-1),0)>s){let t=s-qe,n=u[c]??0;for(d=c,f=c+1;d>0||f<e.length;){let r=d>0,i=f<e.length;if(r){let e=(u[d-1]??0)+1;if(n+e<=t){d--,n+=e;continue}}if(i){let e=(u[f]??0)+1;if(n+e<=t){f++,n+=e;continue}}break}}let p=d,ee=e.length-f,m=e.slice(d,f),h=m.map((e,t)=>d+t);return(0,B.jsxs)(S,{flexDirection:`row`,gap:1,children:[(0,B.jsx)(C,{color:`suggestion`,children:i}),p>0&&(0,B.jsxs)(C,{dimColor:!0,children:[W,p]}),m.map((e,t)=>{let n=h[t]===c,r=e===V?e:`#${He(e,l-H)}`;return(0,B.jsxs)(C,{backgroundColor:n?`suggestion`:void 0,color:n?`inverseText`:void 0,bold:n,children:[` `,r,` `]},e)}),ee>0?(0,B.jsxs)(C,{dimColor:!0,children:[We,ee,Ge]}):(0,B.jsx)(C,{dimColor:!0,children:Ke})]})}var B,V,H,U,W,We,Ge,Ke,qe,Je,G,K=e((()=>{ge(),je(),B=O(),V=`All`,H=2,U=1,W=`← `,We=`→`,Ge=` (tab to cycle)`,Ke=`(tab to cycle)`,qe=5,Je=18,G=14}));function Ye({nodes:e,onSelect:t,onCancel:n,onFocus:i,focusNodeId:a,visibleOptionCount:o,layout:s=`expanded`,isDisabled:c=!1,hideIndexes:l=!1,isNodeExpanded:u,onExpand:d,onCollapse:f,getParentPrefix:p,getChildPrefix:ee,onUpFromFirstItem:m}){let[h,g]=q.useState(new Set),te=q.useRef(!1),ne=q.useRef(null),_=q.useCallback(e=>u?u(e):h.has(e),[u,h]),v=q.useMemo(()=>{let t=[];function n(e,r,i){let a=!!e.children&&e.children.length>0,o=_(e.id);if(t.push({node:e,depth:r,isExpanded:o,hasChildren:a,parentId:i}),a&&o&&e.children)for(let t of e.children)n(t,r+1,e.id)}for(let t of e)n(t,0);return t},[e,_]),re=q.useCallback(e=>e?`▼ `:`▶ `,[]),ie=q.useCallback(e=>` ▸ `,[]),ae=p??re,y=ee??ie,oe=q.useCallback(e=>{let t=``;return e.hasChildren?t=ae(e.isExpanded):e.depth>0&&(t=y(e.depth)),t+e.node.label},[ae,y]),se=q.useMemo(()=>v.map(e=>({label:oe(e),description:e.node.description,dimDescription:e.node.dimDescription??!0,value:e.node.id})),[v,oe]),b=q.useMemo(()=>{let e=new Map;return v.forEach(t=>e.set(t.node.id,t.node)),e},[v]),x=q.useCallback(e=>v.find(t=>t.node.id===e),[v]),ce=q.useCallback((e,t)=>{x(e)?.hasChildren&&(t?d?d(e):g(t=>new Set(t).add(e)):f?f(e):g(t=>{let n=new Set(t);return n.delete(e),n}))},[x,d,f]);return(0,Xe.jsx)(S,{tabIndex:0,autoFocus:!0,onKeyDown:e=>{if(!a||c)return;let t=x(a);if(t){if(e.key===`right`&&t.hasChildren)e.preventDefault(),ce(a,!0);else if(e.key===`left`){if(t.hasChildren&&t.isExpanded)e.preventDefault(),ce(a,!1);else if(t.parentId!==void 0&&(e.preventDefault(),te.current=!0,ce(t.parentId,!1),i)){let e=b.get(t.parentId);e&&i(e)}}}},children:(0,Xe.jsx)(r,{options:se,onChange:q.useCallback(e=>{let n=b.get(e);n&&t(n)},[b,t]),onFocus:q.useCallback(e=>{if(te.current){te.current=!1;return}if(ne.current!==e&&(ne.current=e,i)){let t=b.get(e);t&&i(t)}},[i,b]),onCancel:n,defaultFocusValue:a,visibleOptionCount:o,layout:s,isDisabled:c,hideIndexes:l,onUpFromFirstItem:m})})}var q,Xe,Ze=e((()=>{q=t(T(),1),ge(),s(),Xe=O()}));function Qe(e,t){return N(e.replace(/\s+/g,` `).trim(),t)}function $e({before:e,match:t,after:n},r){return E.dim(e)+r(t)+E.dim(n)}function et(e,t,n){let r=e.toLowerCase().indexOf(t.toLowerCase());if(r===-1)return null;let i=r+t.length,a=Math.max(0,r-n),o=Math.min(e.length,i+n),s=e.slice(a,r),c=e.slice(r,i),l=e.slice(i,o);return{before:(a>0?`…`:``)+s.replace(/\s+/g,` `).trimStart(),match:c.trim(),after:l.replace(/\s+/g,` `).trimEnd()+(o<e.length?`…`:``)}}function tt(e,t,n){let{isGroupHeader:r=!1,isChild:i=!1,forkCount:a=0}=n||{},o=r&&a>0?ct:i?lt:0,s=r&&a>0?` (+${a} other ${a===1?`session`:`sessions`})`:``,c=e.isSidechain?` (sidechain)`:``,l=t-o-c.length-s.length;return`${Qe(j(e),l)}${c}${s}`}function nt(e,t){let{isChild:n=!1,showProjectPath:r=!1}=t||{},i=n?` `:``,a=ke(e),o=r&&e.projectPath?` · ${e.projectPath}`:``;return i+a+o}function rt({logs:e,maxHeight:t=1/0,forceWidth:n,onCancel:i,onSelect:o,onLogsChanged:s,onLoadMore:c,initialSearchQuery:l,showAllProjects:u=!1,onToggleAllProjects:p,onAgenticSearch:m}){let h=he(),ne=n===void 0?h.columns:n,re=Pe(i),ae=ue(),y=f(),[oe]=ce(),x=ee(oe),T=J.useMemo(()=>e=>me(e,x.warning),[x.warning]),[E,de]=J.useState(null),[D,ge]=J.useState(!1),[O,ve]=J.useState(!1),[be,k]=J.useState(!1),xe=J.useMemo(()=>_e(),[]),[Se,A]=J.useState(``),[Ce,Te]=J.useState(0),[Ee,De]=J.useState(new Set),[Oe,N]=J.useState(null),[Ae,je]=J.useState(1),[P,F]=J.useState(`list`),[Me,Ne]=J.useState(null),Fe=J.useRef(null),[Ie,Re]=J.useState(0),[I,ze]=J.useState({status:`idle`}),[L,R]=J.useState(!1),Ve=J.useRef(null),{query:z,setQuery:He,cursorOffset:B}=Le({isActive:P===`search`&&I.status!==`searching`,onExit:()=>{F(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},onExitUp:()=>{F(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},passthroughCtrlKeys:[`n`],initialQuery:l||``}),V=J.useDeferredValue(z),[H,U]=J.useState(``);J.useEffect(()=>{if(!V){U(``);return}let e=setTimeout(U,300,V);return()=>clearTimeout(e)},[V]);let[W,We]=J.useState(null),[Ge,Ke]=J.useState(!1);J.useEffect(()=>{we().then(e=>de(e)),d(xe).then(e=>{k(e.length>1)})},[xe]);let qe=J.useMemo(()=>new Map(e.map(e=>[e,at(e)])),[e]),Je=J.useMemo(()=>null,[e,qe,!1]),G=J.useMemo(()=>st(e),[e]),K=G.length>0,q=J.useMemo(()=>K?[`All`,...G]:[],[K,G]),Xe=q.length>0&&Ie<q.length?Ie:0,Ze=q[Xe],rt=Ze===`All`?void 0:Ze,it=+!!K,ct=J.useMemo(()=>{let t=e;return y&&(t=e.filter(e=>{let t=ye(),n=g(e);return!!(t&&n===t||e.customTitle||te(e.messages)||e.firstPrompt||e.customTitle)})),rt!==void 0&&(t=t.filter(e=>e.tag===rt)),D&&E&&(t=t.filter(e=>e.gitBranch===E)),be&&!O&&(t=t.filter(e=>e.projectPath===xe)),t},[e,y,rt,D,E,be,O,xe]),lt=J.useMemo(()=>{if(!z)return ct;let e=z.toLowerCase();return ct.filter(t=>{let n=j(t).toLowerCase(),r=(t.gitBranch||``).toLowerCase(),i=(t.tag||``).toLowerCase(),a=t.prNumber?`pr #${t.prNumber} ${t.prRepository||``}`.toLowerCase():``;return n.includes(e)||r.includes(e)||i.includes(e)||a.includes(e)})},[ct,z]);J.useEffect(()=>{},[V,H,!1]),J.useEffect(()=>{We(null),Ke(!1)},[H,Je,!1]);let{filteredLogs:ut,snippets:X}=J.useMemo(()=>{let e=new Map,t=lt;if(W&&H&&W.query===H){for(let t of W.results)if(t.searchableText){let n=et(t.searchableText,H,dt);n&&e.set(t.log,n)}let n=new Set(t.map(e=>e.messages[0]?.uuid)),r=W.results.map(e=>e.log).filter(e=>!n.has(e.messages[0]?.uuid));t=[...t,...r]}return{filteredLogs:t,snippets:e}},[lt,W,H]),Z=J.useMemo(()=>I.status===`results`&&I.results.length>0?I.results:ut,[I,ut]),Q=Math.max(30,ne-4),ft=J.useMemo(()=>{if(!y)return[];let e=ot(Z);return Array.from(e.entries()).map(([e,t])=>{let n=t[0],r=Z.indexOf(n),i=X.get(n),a=i?$e(i,T):null;if(t.length===1){let t=nt(n,{showProjectPath:u});return{id:`log:${e}:0`,value:{log:n,indexInFiltered:r},label:tt(n,Q),description:a?`${t}\n ${a}`:t,dimDescription:!0}}let o=t.length-1,s=t.slice(1).map((t,n)=>{let r=Z.indexOf(t),i=X.get(t),a=i?$e(i,T):null,o=nt(t,{isChild:!0,showProjectPath:u});return{id:`log:${e}:${n+1}`,value:{log:t,indexInFiltered:r},label:tt(t,Q,{isChild:!0}),description:a?`${o}\n ${a}`:o,dimDescription:!0}}),c=nt(n,{showProjectPath:u});return{id:`group:${e}`,value:{log:n,indexInFiltered:r},label:tt(n,Q,{isGroupHeader:!0,forkCount:o}),description:a?`${c}\n ${a}`:c,dimDescription:!0,children:s}})},[y,Z,Q,u,X,T]),pt=J.useMemo(()=>y?[]:Z.map((e,t)=>{let n=Qe(j(e)+(e.isSidechain?` (sidechain)`:``),Q),r=ke(e),i=u&&e.projectPath?` · ${e.projectPath}`:``,a=X.get(e),o=a?$e(a,T):null;return{label:n,description:o?`${r}${i}\n ${o}`:r+i,dimDescription:!0,value:t.toString()}}),[y,Z,T,Q,u,X]),$=Oe?.value.log??null,mt=()=>{if(!y||!$)return``;let e=g($);if(!e)return``;let t=Z.filter(t=>g(t)===e);if(!(t.length>1))return``;let n=Ee.has(e);return t.indexOf($)>0||n?`← to collapse`:`→ to expand`},ht=J.useCallback(async()=>{let e=$?g($):void 0;if(!$||!e){F(`list`),A(``);return}Se.trim()&&(await v(e,Se.trim(),$.fullPath),y&&s&&s()),F(`list`),A(``)},[$,Se,s,y]),gt=J.useCallback(()=>{F(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},[]),_t=J.useCallback(()=>{F(`search`),M(`tengu_session_search_toggled`,{enabled:!0})},[]),vt=J.useCallback(async()=>{if(!z.trim()||!m||!0)return;Ve.current?.abort();let t=new AbortController;Ve.current=t,ze({status:`searching`}),M(`tengu_agentic_search_started`,{query_length:z.length});try{let n=await m(z,e,t.signal);if(t.signal.aborted)return;ze({status:`results`,results:n,query:z}),M(`tengu_agentic_search_completed`,{query_length:z.length,results_count:n.length})}catch(e){if(t.signal.aborted)return;ze({status:`error`,message:e instanceof Error?e.message:`Search failed`}),M(`tengu_agentic_search_error`,{query_length:z.length})}},[z,m,!1,e]);J.useEffect(()=>{I.status!==`idle`&&I.status!==`searching`&&(I.status===`results`&&I.query!==z||I.status===`error`)&&ze({status:`idle`})},[z,I]),J.useEffect(()=>()=>{Ve.current?.abort()},[]);let yt=J.useRef(I.status);J.useEffect(()=>{let e=yt.current;if(yt.current=I.status,e===`searching`&&I.status===`results`){if(y&&ft.length>0)N(ft[0]);else if(!y&&Z.length>0){let e=Z[0];N({id:`0`,value:{log:e,indexInFiltered:0},label:``})}}},[I.status,y,ft,Z]);let bt=J.useCallback(e=>{let t=parseInt(e,10),n=Z[t];!n||Fe.current===t.toString()||(Fe.current=t.toString(),N({id:t.toString(),value:{log:n,indexInFiltered:t},label:``}),je(t+1))},[Z]),xt=J.useCallback(e=>{N(e);let t=Z.findIndex(t=>g(t)===g(e.value.log));t>=0&&je(t+1)},[Z]);le(`confirm:no`,()=>{Ve.current?.abort(),ze({status:`idle`}),M(`tengu_agentic_search_cancelled`,{})},{context:`Confirmation`,isActive:P!==`preview`&&I.status===`searching`}),le(`confirm:no`,()=>{F(`list`),A(``)},{context:`Settings`,isActive:P===`rename`&&I.status!==`searching`}),le(`confirm:no`,()=>{He(``),R(!1),i?.()},{context:`Confirmation`,isActive:P!==`preview`&&P!==`rename`&&P!==`search`&&L&&I.status!==`searching`}),fe((e,t)=>{if(P!==`preview`&&I.status!==`searching`&&P!==`rename`)if(P===`search`)e.toLowerCase()===`n`&&t.ctrl?gt():(t.return||t.downArrow)&&z.trim();else{if(L){if(t.return){vt(),R(!1);return}else if(t.downArrow){R(!1);return}else if(t.upArrow){F(`search`),R(!1);return}}if(K&&t.tab){let e=t.shift?-1:1;Re(t=>{let n=((t<q.length?t:0)+q.length+e)%q.length,r=q[n];return M(`tengu_session_tag_filter_changed`,{is_all:r===`All`,tag_count:G.length}),n});return}let n=!t.ctrl&&!t.meta,r=e.toLowerCase();if(r===`a`&&t.ctrl&&p)p(),M(`tengu_session_all_projects_toggled`,{enabled:!u});else if(r===`b`&&t.ctrl){let e=!D;ge(e),M(`tengu_session_branch_filter_toggled`,{enabled:e})}else if(r===`w`&&t.ctrl&&be){let e=!O;ve(e),M(`tengu_session_worktree_filter_toggled`,{enabled:e})}else r===`/`&&n?(F(`search`),M(`tengu_session_search_toggled`,{enabled:!0})):r===`r`&&t.ctrl&&$?(F(`rename`),A(``),M(`tengu_session_rename_started`,{})):r===`v`&&t.ctrl&&$?(Ne($),F(`preview`),M(`tengu_session_preview_opened`,{messageCount:$.messageCount})):$&&n&&e.length>0&&!/^\s+$/.test(e)&&(F(`search`),He(e),M(`tengu_session_search_toggled`,{enabled:!0}))}},{isActive:!0});let St=[];D&&E&&St.push(E),be&&!O&&St.push(`current worktree`);let Ct=8+ +(St.length>0&&P!==`search`)+it,wt=Math.max(1,Math.floor((t-Ct-2)/3));return J.useEffect(()=>{if(!c)return;let e=wt*2;Ae+e>=Z.length&&c(wt*3)},[Ae,wt,Z.length,c]),e.length===0?null:P===`preview`&&Me&&y?(0,Y.jsx)(Be,{log:Me,onExit:()=>{F(`list`),Ne(null)},onSelect:o}):(0,Y.jsxs)(S,{flexDirection:`column`,height:t-1,children:[(0,Y.jsx)(S,{flexShrink:0,children:(0,Y.jsx)(se,{color:`suggestion`})}),(0,Y.jsx)(S,{flexShrink:0,children:(0,Y.jsx)(C,{children:` `})}),K?(0,Y.jsx)(Ue,{tabs:q,selectedIndex:Xe,availableWidth:ne,showAllProjects:u}):(0,Y.jsx)(S,{flexShrink:0,children:(0,Y.jsxs)(C,{bold:!0,color:`suggestion`,children:[`Resume Session`,P===`list`&&Z.length>wt&&(0,Y.jsxs)(C,{dimColor:!0,children:[` `,`(`,Ae,` of `,Z.length,`)`]})]})}),(0,Y.jsx)(pe,{query:z,isFocused:P===`search`,isTerminalFocused:ae,cursorOffset:B}),St.length>0&&P!==`search`&&(0,Y.jsx)(S,{flexShrink:0,paddingLeft:2,children:(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsx)(w,{children:St})})}),(0,Y.jsx)(S,{flexShrink:0,children:(0,Y.jsx)(C,{children:` `})}),I.status===`searching`&&(0,Y.jsxs)(S,{paddingLeft:1,flexShrink:0,children:[(0,Y.jsx)(ie,{}),(0,Y.jsx)(C,{children:` Searching…`})]}),I.status===`results`&&I.results.length>0&&(0,Y.jsx)(S,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(C,{dimColor:!0,italic:!0,children:`Work Mate found these results:`})}),I.status===`results`&&I.results.length===0&&ut.length===0&&(0,Y.jsx)(S,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(C,{dimColor:!0,italic:!0,children:`No matching sessions found.`})}),I.status===`error`&&ut.length===0&&(0,Y.jsx)(S,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(C,{dimColor:!0,italic:!0,children:`No matching sessions found.`})}),!!z.trim()&&m&&!1,I.status===`searching`?null:P===`rename`&&$?(0,Y.jsxs)(S,{paddingLeft:2,flexDirection:`column`,children:[(0,Y.jsx)(C,{bold:!0,children:`Rename session:`}),(0,Y.jsx)(S,{paddingTop:1,children:(0,Y.jsx)(a,{value:Se,onChange:A,onSubmit:ht,placeholder:j($,`Enter new session name`),columns:ne,cursorOffset:Ce,onChangeCursorOffset:Te,showCursor:!0})})]}):y?(0,Y.jsx)(Ye,{nodes:ft,onSelect:e=>{o(e.value.log)},onFocus:xt,onCancel:i,focusNodeId:Oe?.id,visibleOptionCount:wt,layout:`expanded`,isDisabled:P===`search`||L,hideIndexes:!1,isNodeExpanded:e=>{if(P===`search`||D)return!0;let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;return t?Ee.has(t):!1},onExpand:e=>{let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;t&&(De(e=>new Set(e).add(t)),M(`tengu_session_group_expanded`,{}))},onCollapse:e=>{let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;t&&De(e=>{let n=new Set(e);return n.delete(t),n})},onUpFromFirstItem:_t}):(0,Y.jsx)(r,{options:pt,onChange:e=>{let t=Z[parseInt(e,10)];t&&o(t)},visibleOptionCount:wt,onCancel:i,onFocus:bt,defaultFocusValue:Oe?.id.toString(),layout:`expanded`,isDisabled:P===`search`||L,onUpFromFirstItem:_t}),(0,Y.jsx)(S,{paddingLeft:2,children:re.pending?(0,Y.jsxs)(C,{dimColor:!0,children:[`Press `,re.keyName,` again to exit`]}):P===`rename`?(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsxs)(w,{children:[(0,Y.jsx)(b,{shortcut:`Enter`,action:`save`}),(0,Y.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):I.status===`searching`?(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsxs)(w,{children:[(0,Y.jsx)(C,{children:`Searching with Work Mate…`}),(0,Y.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):L?(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsxs)(w,{children:[(0,Y.jsx)(b,{shortcut:`Enter`,action:`search`}),(0,Y.jsx)(b,{shortcut:`↓`,action:`skip`}),(0,Y.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):P===`search`?(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsxs)(w,{children:[(0,Y.jsx)(C,{children:`Type to Search`}),(0,Y.jsx)(b,{shortcut:`Enter`,action:`select`}),(0,Y.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`clear`})]})}):(0,Y.jsx)(C,{dimColor:!0,children:(0,Y.jsxs)(w,{children:[p&&(0,Y.jsx)(b,{shortcut:`Ctrl+A`,action:`show ${u?`current dir`:`all projects`}`}),E&&(0,Y.jsx)(b,{shortcut:`Ctrl+B`,action:`toggle branch`}),be&&(0,Y.jsx)(b,{shortcut:`Ctrl+W`,action:`show ${O?`current worktree`:`all worktrees`}`}),(0,Y.jsx)(b,{shortcut:`Ctrl+V`,action:`preview`}),(0,Y.jsx)(b,{shortcut:`Ctrl+R`,action:`rename`}),(0,Y.jsx)(C,{children:`Type to search`}),(0,Y.jsx)(_,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`}),mt()&&(0,Y.jsx)(C,{children:mt()})]})})})]})}function it(e){if(e.type!==`user`&&e.type!==`assistant`)return``;let t=`message`in e?e.message?.content:void 0;return t?typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(` `):``:``}function at(e){let t=(e.messages.length<=ut?e.messages:[...e.messages.slice(0,X),...e.messages.slice(-1e3)]).map(it).filter(Boolean).join(` `),n=`${[e.customTitle,e.summary,e.firstPrompt,e.gitBranch,e.tag,e.prNumber?`PR #${e.prNumber}`:void 0,e.prRepository].filter(Boolean).join(` `)} ${t}`.trim();return n.length>Z?n.slice(0,Z):n}function ot(e){let t=new Map;for(let n of e){let e=g(n);if(e){let r=t.get(e);r?r.push(n):t.set(e,[n])}}return t.forEach(e=>e.sort((e,t)=>new Date(t.modified).getTime()-new Date(e.modified).getTime())),t}function st(e){let t=new Set;for(let n of e)n.tag&&t.add(n.tag);return Array.from(t).sort((e,t)=>e.localeCompare(t))}var J,Y,ct,lt,ut,X,Z,dt,Q=e((()=>{de(),J=t(T(),1),ve(),Fe(),Re(),i(),ge(),oe(),Oe(),je(),n(),Te(),Ee(),h(),ae(),re(),s(),Ie(),Ve(),ne(),K(),l(),Ze(),Y=O(),ct=2,lt=4,ut=2e3,X=1e3,Z=5e4,dt=50}));function ft(e){if(e.type!==`user`&&e.type!==`assistant`)return``;let t=`message`in e?e.message?.content:void 0;return t?typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(` `):``:``}function pt(e){if(e.length===0)return``;let t=(e.length<=gt?e:[...e.slice(0,gt/2),...e.slice(-100/2)]).map(ft).filter(Boolean).join(` `).replace(/\s+/g,` `).trim();return t.length>ht?`${t.slice(0,ht)}…`:t}function $(e,t){return!!(j(e).toLowerCase().includes(t)||e.customTitle?.toLowerCase().includes(t)||e.tag?.toLowerCase().includes(t)||e.gitBranch?.toLowerCase().includes(t)||e.summary?.toLowerCase().includes(t)||e.firstPrompt?.toLowerCase().includes(t)||e.messages&&e.messages.length>0&&pt(e.messages).toLowerCase().includes(t))}async function mt(e,t,n){if(!e.trim()||t.length===0)return[];let r=e.toLowerCase(),i=t.filter(e=>$(e,r)),a;if(i.length>=_t)a=i.slice(0,_t);else{let e=t.filter(e=>!$(e,r)),n=_t-i.length;a=[...i,...e.slice(0,n)]}k(`Agentic search: ${a.length}/${t.length} logs, query="${e}", matching: ${i.length}, with messages: ${A(a,e=>e.messages?.length>0)}`);let s=a.map(async e=>{if(y(e))try{return await o(e)}catch(t){return De(t),e}return e}),l=await Promise.all(s);k(`Agentic search: loaded ${A(l,e=>e.messages?.length>0)}/${a.length} logs with transcripts`);let u=`Sessions:
2
+ ${l.map((e,t)=>{let n=[`${t}:`],r=j(e);if(n.push(r),e.customTitle&&e.customTitle!==r&&n.push(`[custom title: ${e.customTitle}]`),e.tag&&n.push(`[tag: ${e.tag}]`),e.gitBranch&&n.push(`[branch: ${e.gitBranch}]`),e.summary&&n.push(`- Summary: ${e.summary}`),e.firstPrompt&&e.firstPrompt!==`No prompt`&&n.push(`- First message: ${e.firstPrompt.slice(0,300)}`),e.messages&&e.messages.length>0){let t=pt(e.messages);t&&n.push(`- Transcript: ${t}`)}return n.join(` `)}).join(`
3
+ `)}
4
+
5
+ Search query: "${e}"
6
+
7
+ Find the sessions that are most relevant to this query.`;k(`Agentic search prompt (first 500 chars): ${u.slice(0,500)}...`);try{let e=F();k(`Agentic search using model: ${e}`);let t=(await c({model:e,system:vt,messages:[{role:`user`,content:u}],signal:n,querySource:`session_search`})).content.find(e=>e.type===`text`);if(t?.type!==`text`)return k(`No text content in agentic search response`),[];k(`Agentic search response: ${t.text}`);let r=t.text.match(/\{[\s\S]*\}/);if(!r)return k(`Could not find JSON in agentic search response`),[];let i=(be(r[0]).relevant_indices||[]).filter(e=>e>=0&&e<l.length).map(e=>l[e]);return k(`Agentic search found ${i.length} relevant sessions`),i}catch(e){return De(e),k(`Agentic search error: ${e}`),[]}}var ht,gt,_t,vt,yt=e((()=>{Ce(),xe(),Ee(),P(),h(),p(),Se(),ht=2e3,gt=100,_t=100,vt=`Your goal is to find relevant sessions based on a user's search query.
8
+
9
+ You will be given a list of sessions with their metadata and a search query. Identify which sessions are most relevant to the query.
10
+
11
+ Each session may include:
12
+ - Title (display name or custom title)
13
+ - Tag (user-assigned category, shown as [tag: name] - users tag sessions with /tag command to categorize them)
14
+ - Branch (git branch name, shown as [branch: name])
15
+ - Summary (AI-generated summary)
16
+ - First message (beginning of the conversation)
17
+ - Transcript (excerpt of conversation content)
18
+
19
+ IMPORTANT: Tags are user-assigned labels that indicate the session's topic or category. If the query matches a tag exactly or partially, those sessions should be highly prioritized.
20
+
21
+ For each session, consider (in order of priority):
22
+ 1. Exact tag matches (highest priority - user explicitly categorized this session)
23
+ 2. Partial tag matches or tag-related terms
24
+ 3. Title matches (custom titles or first message content)
25
+ 4. Branch name matches
26
+ 5. Summary and transcript content matches
27
+ 6. Semantic similarity and related concepts
28
+
29
+ CRITICAL: Be VERY inclusive in your matching. Include sessions that:
30
+ - Contain the query term anywhere in any field
31
+ - Are semantically related to the query (e.g., "testing" matches sessions about "tests", "unit tests", "QA", etc.)
32
+ - Discuss topics that could be related to the query
33
+ - Have transcripts that mention the concept even in passing
34
+
35
+ When in doubt, INCLUDE the session. It's better to return too many results than too few. The user can easily scan through results, but missing relevant sessions is frustrating.
36
+
37
+ Return sessions ordered by relevance (most relevant first). If truly no sessions have ANY connection to the query, return an empty array - but this should be rare.
38
+
39
+ Respond with ONLY the JSON object, no markdown formatting:
40
+ {"relevant_indices": [2, 5, 0]}`}));function bt(e,t){let n=_e();if(!t||!e.projectPath||e.projectPath===n)return{isCrossProject:!1};let r=g(e);return{isCrossProject:!0,isSameRepoWorktree:!1,command:`cd ${Me([e.projectPath])} && claude --resume ${r}`,projectPath:e.projectPath}}var xt=e((()=>{ve(),Ne(),h()}));export{rt as a,yt as i,xt as n,Q as o,mt as r,bt as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{n as r,t as i}from"./axios-DaWTGg7G.js";import{d as a,h as o}from"./config-DRy1I12M.js";import{o as s,s as c}from"./log-CZ7ploQm.js";import{$r as l,N as u,R as d,_ as f,r as p,ti as m}from"./model-Do0f476p.js";import{Z as h,et as g}from"./esm-CvHtYRrr.js";import{f as _,p as v}from"./firstPartyEventLogger-DqGSujCz.js";import{createHash as y}from"crypto";function b(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}async function x(){if(N.length===0)return;let e=N;N=[];try{await r.post(E,e,{headers:{"Content-Type":`application/json`,"DD-API-KEY":D},timeout:A})}catch(e){c(e)}}function S(){P||(P=setTimeout(()=>{P=null,x()},T()).unref())}async function C(){P&&(clearTimeout(P),P=null),await x()}async function w(e,t){if(l()!==`firstParty`)return;let n=F;if(n===null&&(n=await I()),!(!n||!j.has(e)))try{let{envContext:n,...r}=await h({model:t.model,betas:t.betas}),i={...r,...n,...t,userBucket:R()};if(typeof i.toolName==`string`&&i.toolName.startsWith(`mcp__`)&&(i.toolName=`mcp`),typeof i.model==`string`){let e=p(i.model.replace(/\[1m]$/i,``));i.model=e in u?e:`other`}if(typeof i.version==`string`&&(i.version=i.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,`$1`)),i.status!==void 0&&i.status!==null){let e=String(i.status);i.http_status=e;let t=e.charAt(0);t>=`1`&&t<=`5`&&(i.http_status_range=`${t}xx`),delete i.status}let a=i,o={ddsource:`nodejs`,ddtags:[`event:${e}`,...M.filter(e=>a[e]!==void 0&&a[e]!==null).map(e=>`${b(e)}:${a[e]}`)].join(`,`),message:e,service:`workmate`,hostname:`workmate`,env:process.env.USER_TYPE};for(let[e,t]of Object.entries(i))t!=null&&(o[b(e)]=t);N.push(o),N.length>=k?(P&&(clearTimeout(P),P=null),x()):S()}catch(e){c(e)}}function T(){return parseInt(process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||``,10)||O}var E,D,O,k,A,j,M,N,P,F,I,L,R,z=e((()=>{i(),n(),o(),s(),f(),m(),d(),_(),g(),E=process.env.DATADOG_LOGS_ENDPOINT??``,D=process.env.DATADOG_API_KEY??``,O=15e3,k=100,A=5e3,j=new Set(`tengu_api_error.tengu_api_success.tengu_cancel.tengu_compact_failed.tengu_exit.tengu_flicker.tengu_init.tengu_model_fallback_triggered.tengu_oauth_error.tengu_oauth_success.tengu_oauth_token_refresh_failure.tengu_oauth_token_refresh_success.tengu_oauth_token_refresh_lock_acquiring.tengu_oauth_token_refresh_lock_acquired.tengu_oauth_token_refresh_starting.tengu_oauth_token_refresh_completed.tengu_oauth_token_refresh_lock_releasing.tengu_oauth_token_refresh_lock_released.tengu_query_error.tengu_session_file_read.tengu_started.tengu_tool_use_error.tengu_tool_use_granted_in_prompt_permanent.tengu_tool_use_granted_in_prompt_temporary.tengu_tool_use_rejected_in_prompt.tengu_tool_use_success.tengu_uncaught_exception.tengu_unhandled_rejection.tengu_voice_recording_started.tengu_voice_toggled.tengu_team_mem_sync_pull.tengu_team_mem_sync_push.tengu_team_mem_sync_started.tengu_team_mem_entries_capped`.split(`.`)),M=[`arch`,`clientType`,`errorType`,`http_status_range`,`http_status`,`model`,`platform`,`provider`,`skillMode`,`subscriptionType`,`toolName`,`userBucket`,`userType`,`version`,`versionBase`],N=[],P=null,F=null,I=t(async()=>{if(v()||!E||!D)return F=!1,!1;try{return F=!0,!0}catch(e){return c(e),F=!1,!1}}),L=30,R=t(()=>{let e=a(),t=y(`sha256`).update(e).digest(`hex`);return parseInt(t.slice(0,8),16)%L})}));export{C as n,w as r,z as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{Z as r,et as i}from"./esm-BCUC71kt.js";import{n as a,t as o}from"./axios-DaWTGg7G.js";import{d as s,h as c}from"./config-DUTgj3js.js";import{o as l,s as u}from"./log-CZ7ploQm.js";import{$r as d,N as f,R as p,_ as m,r as h,ti as g}from"./model-BaMclMXn.js";import{f as _,p as v}from"./firstPartyEventLogger-B261Wksn.js";import{createHash as y}from"crypto";function b(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}async function x(){if(N.length===0)return;let e=N;N=[];try{await a.post(E,e,{headers:{"Content-Type":`application/json`,"DD-API-KEY":D},timeout:A})}catch(e){u(e)}}function S(){P||(P=setTimeout(()=>{P=null,x()},T()).unref())}async function C(){P&&(clearTimeout(P),P=null),await x()}async function w(e,t){if(d()!==`firstParty`)return;let n=F;if(n===null&&(n=await I()),!(!n||!j.has(e)))try{let{envContext:n,...i}=await r({model:t.model,betas:t.betas}),a={...i,...n,...t,userBucket:R()};if(typeof a.toolName==`string`&&a.toolName.startsWith(`mcp__`)&&(a.toolName=`mcp`),typeof a.model==`string`){let e=h(a.model.replace(/\[1m]$/i,``));a.model=e in f?e:`other`}if(typeof a.version==`string`&&(a.version=a.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,`$1`)),a.status!==void 0&&a.status!==null){let e=String(a.status);a.http_status=e;let t=e.charAt(0);t>=`1`&&t<=`5`&&(a.http_status_range=`${t}xx`),delete a.status}let o=a,s={ddsource:`nodejs`,ddtags:[`event:${e}`,...M.filter(e=>o[e]!==void 0&&o[e]!==null).map(e=>`${b(e)}:${o[e]}`)].join(`,`),message:e,service:`workmate`,hostname:`workmate`,env:process.env.USER_TYPE};for(let[e,t]of Object.entries(a))t!=null&&(s[b(e)]=t);N.push(s),N.length>=k?(P&&(clearTimeout(P),P=null),x()):S()}catch(e){u(e)}}function T(){return parseInt(process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||``,10)||O}var E,D,O,k,A,j,M,N,P,F,I,L,R,z=e((()=>{o(),n(),c(),l(),m(),g(),p(),_(),i(),E=process.env.DATADOG_LOGS_ENDPOINT??``,D=process.env.DATADOG_API_KEY??``,O=15e3,k=100,A=5e3,j=new Set(`tengu_api_error.tengu_api_success.tengu_cancel.tengu_compact_failed.tengu_exit.tengu_flicker.tengu_init.tengu_model_fallback_triggered.tengu_oauth_error.tengu_oauth_success.tengu_oauth_token_refresh_failure.tengu_oauth_token_refresh_success.tengu_oauth_token_refresh_lock_acquiring.tengu_oauth_token_refresh_lock_acquired.tengu_oauth_token_refresh_starting.tengu_oauth_token_refresh_completed.tengu_oauth_token_refresh_lock_releasing.tengu_oauth_token_refresh_lock_released.tengu_query_error.tengu_session_file_read.tengu_started.tengu_tool_use_error.tengu_tool_use_granted_in_prompt_permanent.tengu_tool_use_granted_in_prompt_temporary.tengu_tool_use_rejected_in_prompt.tengu_tool_use_success.tengu_uncaught_exception.tengu_unhandled_rejection.tengu_voice_recording_started.tengu_voice_toggled.tengu_team_mem_sync_pull.tengu_team_mem_sync_push.tengu_team_mem_sync_started.tengu_team_mem_entries_capped`.split(`.`)),M=[`arch`,`clientType`,`errorType`,`http_status_range`,`http_status`,`model`,`platform`,`provider`,`skillMode`,`subscriptionType`,`toolName`,`userBucket`,`userType`,`version`,`versionBase`],N=[],P=null,F=null,I=t(async()=>{if(v()||!E||!D)return F=!1,!1;try{return F=!0,!0}catch(e){return u(e),F=!1,!1}}),L=30,R=t(()=>{let e=s(),t=y(`sha256`).update(e).digest(`hex`);return parseInt(t.slice(0,8),16)%L})}));export{C as n,w as r,z as t};
@@ -0,0 +1 @@
1
+ import{a as e,i as t,o as n}from"./detectRepository-pRAVv8SH.js";t();export{e as parseGitHubRepository,n as parseGitRemote};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./cwd-Nh5IZNKO.js";import{c as r,i}from"./debug-D58GQBDG.js";import{m as a,u as o}from"./git-By_J4XJL.js";function s(){p.clear()}async function c(){let e=await l();return!e||e.host!==`github.com`?null:`${e.owner}/${e.name}`}async function l(){let e=n();if(p.has(e))return p.get(e)??null;try{let t=await o();if(r(`Git remote URL: ${t}`),!t)return r(`No git remote URL found`),p.set(e,null),null;let n=u(t);return r(`Parsed repository: ${n?`${n.host}/${n.owner}/${n.name}`:null} from URL: ${t}`),p.set(e,n),n}catch(t){return r(`Error detecting repository: ${t}`),p.set(e,null),null}}function u(e){let t=e.trim(),n=t.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/);if(n?.[1]&&n[2]&&n[3])return f(n[1])?{host:n[1],owner:n[2],name:n[3]}:null;let r=t.match(/^(https?|ssh|git):\/\/(?:[^@]+@)?([^/:]+(?::\d+)?)\/([^/]+)\/([^/]+?)(?:\.git)?$/);if(r?.[1]&&r[2]&&r[3]&&r[4]){let e=r[1],t=r[2],n=t.split(`:`)[0]??``;return f(n)?{host:e===`https`||e===`http`?t:n,owner:r[3],name:r[4]}:null}return null}function d(e){let t=e.trim(),n=u(t);if(n)return n.host===`github.com`?`${n.owner}/${n.name}`:null;if(!t.includes(`://`)&&!t.includes(`@`)&&t.includes(`/`)){let e=t.split(`/`);if(e.length===2&&e[0]&&e[1]){let t=e[1].replace(/\.git$/,``);return`${e[0]}/${t}`}}return r(`Could not parse repository from: ${t}`),null}function f(e){if(!e.includes(`.`))return!1;let t=e.split(`.`).pop();return t?/^[a-zA-Z]+$/.test(t):!1}var p,m=e((()=>{t(),i(),a(),p=new Map}));export{d as a,m as i,c as n,u as o,l as r,s as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./cwd-Nh5IZNKO.js";import{c as r,i}from"./debug-D58GQBDG.js";import{m as a,u as o}from"./git-Wid-XppW.js";function s(){p.clear()}async function c(){let e=await l();return!e||e.host!==`github.com`?null:`${e.owner}/${e.name}`}async function l(){let e=n();if(p.has(e))return p.get(e)??null;try{let t=await o();if(r(`Git remote URL: ${t}`),!t)return r(`No git remote URL found`),p.set(e,null),null;let n=u(t);return r(`Parsed repository: ${n?`${n.host}/${n.owner}/${n.name}`:null} from URL: ${t}`),p.set(e,n),n}catch(t){return r(`Error detecting repository: ${t}`),p.set(e,null),null}}function u(e){let t=e.trim(),n=t.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/);if(n?.[1]&&n[2]&&n[3])return f(n[1])?{host:n[1],owner:n[2],name:n[3]}:null;let r=t.match(/^(https?|ssh|git):\/\/(?:[^@]+@)?([^/:]+(?::\d+)?)\/([^/]+)\/([^/]+?)(?:\.git)?$/);if(r?.[1]&&r[2]&&r[3]&&r[4]){let e=r[1],t=r[2],n=t.split(`:`)[0]??``;return f(n)?{host:e===`https`||e===`http`?t:n,owner:r[3],name:r[4]}:null}return null}function d(e){let t=e.trim(),n=u(t);if(n)return n.host===`github.com`?`${n.owner}/${n.name}`:null;if(!t.includes(`://`)&&!t.includes(`@`)&&t.includes(`/`)){let e=t.split(`/`);if(e.length===2&&e[0]&&e[1]){let t=e[1].replace(/\.git$/,``);return`${e[0]}/${t}`}}return r(`Could not parse repository from: ${t}`),null}function f(e){if(!e.includes(`.`))return!1;let t=e.split(`.`).pop();return t?/^[a-zA-Z]+$/.test(t):!1}var p,m=e((()=>{t(),i(),a(),p=new Map}));export{d as a,m as i,c as n,u as o,l as r,s as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";var n,r;e((()=>{n=t(),r=async(e,t)=>{let{DiffDialog:r}=await import(`./DiffDialog-DCpchgp5.js`);return(0,n.jsx)(r,{messages:t.messages,onDone:e})}}))();export{r as call};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";var n,r;e((()=>{n=t(),r=async(e,t)=>{let{DiffDialog:r}=await import(`./DiffDialog-CMtml9iw.js`);return(0,n.jsx)(r,{messages:t.messages,onDone:e})}}))();export{r as call};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./cwd-Nh5IZNKO.js";import{f as r,u as i}from"./debug-D58GQBDG.js";import{ar as a,sr as o}from"./settings-3xZ0fsvE.js";import{o as s,s as c}from"./log-CZ7ploQm.js";import{a as l,i as u}from"./memoize-CumjjK2Q.js";import{basename as d,dirname as f,join as p,sep as m}from"path";function h(e,t){if(!e)return{directory:t||n(),prefix:``};let r=a(e,t);return e.endsWith(`/`)||e.endsWith(m)?{directory:r,prefix:``}:{directory:f(r),prefix:d(e)}}async function g(e){let t=C.get(e);if(t)return t;try{let t=(await i().readdir(e)).filter(e=>e.isDirectory()&&!e.name.startsWith(`.`)).map(t=>({name:t.name,path:p(e,t.name),type:`directory`})).slice(0,100);return C.set(e,t),t}catch(e){return c(e),[]}}async function _(e,t={}){let{basePath:r=n(),maxResults:i=10}=t,{directory:a,prefix:o}=h(e,r),s=await g(a),c=o.toLowerCase();return s.filter(e=>e.name.toLowerCase().startsWith(c)).slice(0,i).map(e=>({id:e.path,displayText:`${e.name}/`,description:`directory`,metadata:{type:`directory`}}))}function v(e){return e.startsWith(`~/`)||e.startsWith(`/`)||e.startsWith(`./`)||e.startsWith(`../`)||e===`~`||e===`.`||e===`..`}async function y(e,t=!1){let n=`${e}:${t}`,r=w.get(n);if(r)return r;try{let r=(await i().readdir(e)).filter(e=>t||!e.name.startsWith(`.`)).map(t=>({name:t.name,path:p(e,t.name),type:t.isDirectory()?`directory`:`file`})).sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name)).slice(0,100);return w.set(n,r),r}catch(e){return c(e),[]}}async function b(e,t={}){let{basePath:r=n(),maxResults:i=10,includeFiles:a=!0,includeHidden:o=!1}=t,{directory:s,prefix:c}=h(e,r),l=await y(s,o),u=c.toLowerCase(),d=l.filter(e=>!a&&e.type===`file`?!1:e.name.toLowerCase().startsWith(u)).slice(0,i),f=e.includes(`/`)||e.includes(m),p=``;if(f){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(m),r=Math.max(t,n);p=e.substring(0,r+1)}return(p.startsWith(`./`)||p.startsWith(`.${m}`))&&(p=p.slice(2)),d.map(e=>{let t=p+e.name;return{id:t,displayText:e.type===`directory`?`${t}/`:t,metadata:{type:e.type}}})}var x,S,C,w,T=e((()=>{l(),t(),r(),s(),o(),x=500,S=300*1e3,C=new u({max:x,ttl:S}),w=new u({max:x,ttl:S})}));export{v as i,b as n,T as r,_ as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./cwd-Nh5IZNKO.js";import{f as r,u as i}from"./debug-D58GQBDG.js";import{ar as a,sr as o}from"./settings-BowI3jp-.js";import{o as s,s as c}from"./log-CZ7ploQm.js";import{a as l,i as u}from"./memoize-CumjjK2Q.js";import{basename as d,dirname as f,join as p,sep as m}from"path";function h(e,t){if(!e)return{directory:t||n(),prefix:``};let r=a(e,t);return e.endsWith(`/`)||e.endsWith(m)?{directory:r,prefix:``}:{directory:f(r),prefix:d(e)}}async function g(e){let t=C.get(e);if(t)return t;try{let t=(await i().readdir(e)).filter(e=>e.isDirectory()&&!e.name.startsWith(`.`)).map(t=>({name:t.name,path:p(e,t.name),type:`directory`})).slice(0,100);return C.set(e,t),t}catch(e){return c(e),[]}}async function _(e,t={}){let{basePath:r=n(),maxResults:i=10}=t,{directory:a,prefix:o}=h(e,r),s=await g(a),c=o.toLowerCase();return s.filter(e=>e.name.toLowerCase().startsWith(c)).slice(0,i).map(e=>({id:e.path,displayText:`${e.name}/`,description:`directory`,metadata:{type:`directory`}}))}function v(e){return e.startsWith(`~/`)||e.startsWith(`/`)||e.startsWith(`./`)||e.startsWith(`../`)||e===`~`||e===`.`||e===`..`}async function y(e,t=!1){let n=`${e}:${t}`,r=w.get(n);if(r)return r;try{let r=(await i().readdir(e)).filter(e=>t||!e.name.startsWith(`.`)).map(t=>({name:t.name,path:p(e,t.name),type:t.isDirectory()?`directory`:`file`})).sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name)).slice(0,100);return w.set(n,r),r}catch(e){return c(e),[]}}async function b(e,t={}){let{basePath:r=n(),maxResults:i=10,includeFiles:a=!0,includeHidden:o=!1}=t,{directory:s,prefix:c}=h(e,r),l=await y(s,o),u=c.toLowerCase(),d=l.filter(e=>!a&&e.type===`file`?!1:e.name.toLowerCase().startsWith(u)).slice(0,i),f=e.includes(`/`)||e.includes(m),p=``;if(f){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(m),r=Math.max(t,n);p=e.substring(0,r+1)}return(p.startsWith(`./`)||p.startsWith(`.${m}`))&&(p=p.slice(2)),d.map(e=>{let t=p+e.name;return{id:t,displayText:e.type===`directory`?`${t}/`:t,metadata:{type:e.type}}})}var x,S,C,w,T=e((()=>{l(),t(),r(),s(),o(),x=500,S=300*1e3,C=new u({max:x,ttl:S}),w=new u({max:x,ttl:S})}));export{v as i,b as n,T as r,_ as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Doctor-D9F3tKsr.js";var i,a;e((()=>{n(),i=t(),a=(e,t,n)=>Promise.resolve((0,i.jsx)(r,{onDone:e}))}))();export{a as call};
@@ -1,13 +1,13 @@
1
- import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{$y as n,B as r,Cu as i,Kc as a,Li as o,Mi as s,Qs as c,V as l,Yy as u,Zs as d,ar as f,br as p,gf as m,hf as h,i as g,o as _,qc as v,wu as y}from"./loadAgentsDir-DaNpxaO-.js";import{C as b,D as x,E as S,F as C,L as w,N as T,P as E,_ as D,f as ee,g as O,j as k,r as te,x as A}from"./lazySchema-DULtBUCI.js";import{$ as ne,Ut as j,ar as M,gr as re,hr as ie,mt as ae,zn as oe}from"./state-D5D6QpTX.js";import{d as se,h as ce}from"./settings-3xZ0fsvE.js";import{h as le,r as ue}from"./config-DRy1I12M.js";import{l as de,p as fe,r as pe}from"./sessionStoragePortable-x0Yn02-G.js";import{_ as me,u as he}from"./model-Do0f476p.js";import{_n as ge,vn as _e}from"./prompt-8u06WVES.js";import{n as ve,r as ye}from"./managedEnv-CUsdYhAI.js";import{t as be}from"./QueryEngine-CyGHpX7M.js";import{n as xe,r as Se}from"./modelOptions-B3nis9cC.js";import{dirname as Ce}from"node:path";import{randomUUID as N}from"node:crypto";import{Readable as we,Writable as Te}from"node:stream";import{unlink as Ee}from"node:fs/promises";import*as P from"node:path/posix";import{isAbsolute as De,resolve as Oe}from"node:path/posix";te();var F={authenticate:`authenticate`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_focus:`document/didFocus`,document_did_open:`document/didOpen`,document_did_save:`document/didSave`,initialize:`initialize`,logout:`logout`,nes_accept:`nes/accept`,nes_close:`nes/close`,nes_reject:`nes/reject`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,session_cancel:`session/cancel`,session_close:`session/close`,session_fork:`session/fork`,session_list:`session/list`,session_load:`session/load`,session_new:`session/new`,session_prompt:`session/prompt`,session_resume:`session/resume`,session_set_config_option:`session/set_config_option`,session_set_mode:`session/set_mode`,session_set_model:`session/set_model`},I={elicitation_complete:`elicitation/complete`,elicitation_create:`elicitation/create`,fs_read_text_file:`fs/read_text_file`,fs_write_text_file:`fs/write_text_file`,session_request_permission:`session/request_permission`,session_update:`session/update`,terminal_create:`terminal/create`,terminal_kill:`terminal/kill`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`},ke=x({_meta:k(T(),C()).nullish(),terminal:D().optional().default(!1)}),Ae=x({_meta:k(T(),C()).nullish(),label:T().nullish(),name:T(),optional:D().optional().default(!1),secret:D().optional().default(!0)}),je=x({_meta:k(T(),C()).nullish(),description:T().nullish(),id:T(),name:T()}),Me=x({_meta:k(T(),C()).nullish(),description:T().nullish(),id:T(),link:T().nullish(),name:T(),vars:O(Ae)}),Ne=x({_meta:k(T(),C()).nullish(),args:O(T()).optional(),description:T().nullish(),env:k(T(),T()).optional(),id:T(),name:T()}),Pe=E([Me.and(x({type:b(`env_var`)})),Ne.and(x({type:b(`terminal`)})),je]),Fe=x({_meta:k(T(),C()).nullish(),methodId:T()}),Ie=x({_meta:k(T(),C()).nullish()}),Le=x({_meta:k(T(),C()).nullish(),blob:T(),mimeType:T().nullish(),uri:T()}),Re=x({default:D().nullish(),description:T().nullish(),title:T().nullish()}),ze=x({_meta:k(T(),C()).nullish()}),Be=x({_meta:k(T(),C()).nullish()}),Ve=x({amount:S(),currency:T()}),He=x({_meta:k(T(),C()).nullish(),terminalId:T()}),Ue=x({_meta:k(T(),C()).nullish(),newText:T(),oldText:T().nullish(),path:T()}),We=E([T(),S(),S(),D(),O(T())]),Ge=A(E([x({content:k(T(),We).nullish()}).and(x({action:b(`accept`)})),x({action:b(`decline`)}),x({action:b(`cancel`)})]),x({_meta:k(T(),C()).nullish()})),Ke=x({_meta:k(T(),C()).nullish()}),qe=T(),Je=x({_meta:k(T(),C()).nullish(),elicitationId:qe}),Ye=b(`object`),Xe=b(`string`),Ze=x({_meta:k(T(),C()).nullish()}),Qe=x({_meta:k(T(),C()).nullish(),form:Ke.nullish(),url:Ze.nullish()}),$e=x({const:T(),title:T()}),et=x({_meta:k(T(),C()).nullish(),name:T(),value:T()}),tt=x({code:E([b(-32700),b(-32600),b(-32601),b(-32602),b(-32603),b(-32800),b(-32e3),b(-32002),b(-32042),S().int().min(-2147483648,{message:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{message:`Invalid value: Expected int32 to be <= 2147483647`})]),data:C().optional(),message:T()}),nt=C(),rt=C(),it=C(),at=x({_meta:k(T(),C()).nullish(),readTextFile:D().optional().default(!1),writeTextFile:D().optional().default(!1)}),ot=x({_meta:k(T(),C()).nullish(),name:T(),value:T()}),st=x({_meta:k(T(),C()).nullish(),name:T(),title:T().nullish(),version:T()}),ct=x({default:S().nullish(),description:T().nullish(),maximum:S().nullish(),minimum:S().nullish(),title:T().nullish()}),lt=x({_meta:k(T(),C()).nullish()}),ut=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cursor:T().nullish(),cwd:T().nullish()}),dt=x({_meta:k(T(),C()).nullish()}),ft=x({_meta:k(T(),C()).nullish(),logout:dt.nullish()}),pt=x({_meta:k(T(),C()).nullish()}),mt=x({_meta:k(T(),C()).nullish()}),ht=x({_meta:k(T(),C()).nullish(),http:D().optional().default(!1),sse:D().optional().default(!1)}),gt=x({_meta:k(T(),C()).nullish(),headers:O(ot),name:T(),url:T()}),_t=x({_meta:k(T(),C()).nullish(),headers:O(ot),name:T(),url:T()}),vt=x({_meta:k(T(),C()).nullish(),args:O(T()),command:T(),env:O(et),name:T()}),L=E([gt.and(x({type:b(`http`)})),_t.and(x({type:b(`sse`)})),vt]),yt=T(),bt=x({_meta:k(T(),C()).nullish(),description:T().nullish(),modelId:yt,name:T()}),xt=E([b(`error`),b(`warning`),b(`information`),b(`hint`)]),St=x({_meta:k(T(),C()).nullish()}),Ct=x({_meta:k(T(),C()).nullish()}),wt=x({_meta:k(T(),C()).nullish()}),Tt=x({_meta:k(T(),C()).nullish()}),Et=x({_meta:k(T(),C()).nullish()}),Dt=x({_meta:k(T(),C()).nullish(),maxCount:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),Ot=x({diff:T(),uri:T()}),kt=x({endLine:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),startLine:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),text:T()}),At=x({_meta:k(T(),C()).nullish()}),jt=x({_meta:k(T(),C()).nullish()}),Mt=x({languageId:T(),text:T(),uri:T()}),Nt=x({_meta:k(T(),C()).nullish(),maxCount:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),Pt=E([b(`rejected`),b(`ignored`),b(`replaced`),b(`cancelled`)]),Ft=x({excerpts:O(kt),uri:T()}),It=x({_meta:k(T(),C()).nullish()}),Lt=x({_meta:k(T(),C()).nullish()}),Rt=x({name:T(),owner:T(),remoteUrl:T()}),zt=x({_meta:k(T(),C()).nullish()}),Bt=x({_meta:k(T(),C()).nullish(),jump:At.nullish(),rename:Lt.nullish(),searchAndReplace:zt.nullish()}),Vt=x({id:T(),isRegex:D().nullish(),replace:T(),search:T(),uri:T()}),Ht=E([b(`automatic`),b(`diagnostic`),b(`manual`)]),Ut=x({_meta:k(T(),C()).nullish(),maxCount:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),Wt=x({_meta:k(T(),C()).nullish(),diagnostics:St.nullish(),editHistory:Dt.nullish(),openFiles:jt.nullish(),recentFiles:Nt.nullish(),relatedSnippets:It.nullish(),userActions:Ut.nullish()}),Gt=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cwd:T(),mcpServers:O(L)}),Kt=x({default:S().nullish(),description:T().nullish(),maximum:S().nullish(),minimum:S().nullish(),title:T().nullish()}),qt=T(),Jt=E([b(`allow_once`),b(`allow_always`),b(`reject_once`),b(`reject_always`)]),Yt=x({_meta:k(T(),C()).nullish(),kind:Jt,name:T(),optionId:qt}),Xt=E([b(`high`),b(`medium`),b(`low`)]),Zt=E([b(`pending`),b(`in_progress`),b(`completed`)]),Qt=x({_meta:k(T(),C()).nullish(),content:T(),priority:Xt,status:Zt}),$t=x({_meta:k(T(),C()).nullish(),entries:O(Qt)}),R=x({character:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),line:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`})}),en=x({id:T(),position:R,uri:T()}),tn=x({id:T(),newName:T(),position:R,uri:T()}),nn=x({action:T(),position:R,timestampMs:S(),uri:T()}),rn=E([b(`utf-16`),b(`utf-32`),b(`utf-8`)]),an=x({_meta:k(T(),C()).nullish(),auth:ke.optional().default({terminal:!1}),elicitation:Qe.nullish(),fs:at.optional().default({readTextFile:!1,writeTextFile:!1}),nes:Bt.nullish(),positionEncodings:O(rn).optional(),terminal:D().optional().default(!1)}),on=x({_meta:k(T(),C()).nullish(),audio:D().optional().default(!1),embeddedContext:D().optional().default(!1),image:D().optional().default(!1)}),sn=S().int().gte(0).lte(65535),cn=x({_meta:k(T(),C()).nullish(),clientCapabilities:an.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:st.nullish(),protocolVersion:sn}),z=x({end:R,start:R}),ln=x({message:T(),range:z,severity:xt,uri:T()}),un=x({languageId:T(),lastFocusedMs:S().nullish(),uri:T(),visibleRange:z.nullish()}),dn=x({_meta:k(T(),C()).nullish(),diagnostics:O(ln).nullish(),editHistory:O(Ot).nullish(),openFiles:O(un).nullish(),recentFiles:O(Mt).nullish(),relatedSnippets:O(Ft).nullish(),userActions:O(nn).nullish()}),fn=x({newText:T(),range:z}),pn=E([x({cursorPosition:R.nullish(),edits:O(fn),id:T(),uri:T()}).and(x({kind:b(`edit`)})),en.and(x({kind:b(`jump`)})),tn.and(x({kind:b(`rename`)})),Vt.and(x({kind:b(`searchAndReplace`)}))]),mn=x({_meta:k(T(),C()).nullish(),content:T()}),hn=x({_meta:k(T(),C()).nullish()}),B=E([S(),T()]).nullable();x({_meta:k(T(),C()).nullish(),requestId:B});var gn=x({requestId:B}),_n=ee([`assistant`,`user`]),V=x({_meta:k(T(),C()).nullish(),audience:O(_n).nullish(),lastModified:T().nullish(),priority:S().nullish()}),vn=x({_meta:k(T(),C()).nullish(),annotations:V.nullish(),data:T(),mimeType:T()}),yn=x({_meta:k(T(),C()).nullish(),annotations:V.nullish(),data:T(),mimeType:T(),uri:T().nullish()}),bn=x({_meta:k(T(),C()).nullish(),annotations:V.nullish(),description:T().nullish(),mimeType:T().nullish(),name:T(),size:S().nullish(),title:T().nullish(),uri:T()}),xn=x({_meta:k(T(),C()).nullish(),optionId:qt}),Sn=E([x({outcome:b(`cancelled`)}),xn.and(x({outcome:b(`selected`)}))]),Cn=x({_meta:k(T(),C()).nullish(),outcome:Sn}),wn=x({_meta:k(T(),C()).nullish()}),Tn=x({_meta:k(T(),C()).nullish()}),En=x({currentValue:D()}),Dn=T(),On=T(),kn=E([b(`mode`),b(`model`),b(`thought_level`),T()]),An=T(),jn=x({_meta:k(T(),C()).nullish(),description:T().nullish(),name:T(),value:An}),Mn=x({_meta:k(T(),C()).nullish(),group:Dn,name:T(),options:O(jn)}),H=A(E([x({currentValue:An,options:E([O(jn),O(Mn)])}).and(x({type:b(`select`)})),En.and(x({type:b(`boolean`)}))]),x({_meta:k(T(),C()).nullish(),category:kn.nullish(),description:T().nullish(),id:On,name:T()})),Nn=x({_meta:k(T(),C()).nullish(),configOptions:O(H)}),Pn=x({_meta:k(T(),C()).nullish()}),U=T(),Fn=x({_meta:k(T(),C()).nullish(),id:T(),sessionId:U}),In=x({_meta:k(T(),C()).nullish(),sessionId:U}),Ln=x({_meta:k(T(),C()).nullish(),sessionId:U}),Rn=x({_meta:k(T(),C()).nullish(),sessionId:U}),zn=x({_meta:k(T(),C()).nullish(),args:O(T()).optional(),command:T(),cwd:T().nullish(),env:O(et).optional(),outputByteLimit:S().nullish(),sessionId:U}),Bn=x({_meta:k(T(),C()).nullish(),sessionId:U,uri:T()}),Vn=x({_meta:k(T(),C()).nullish(),position:R,sessionId:U,uri:T(),version:S(),visibleRange:z}),Hn=x({_meta:k(T(),C()).nullish(),languageId:T(),sessionId:U,text:T(),uri:T(),version:S()}),Un=x({_meta:k(T(),C()).nullish(),sessionId:U,uri:T()}),Wn=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cwd:T(),mcpServers:O(L).optional(),sessionId:U}),Gn=x({_meta:k(T(),C()).nullish(),sessionId:U,terminalId:T()}),Kn=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cwd:T(),mcpServers:O(L),sessionId:U}),qn=x({_meta:k(T(),C()).nullish(),limit:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),line:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:T(),sessionId:U}),Jn=x({_meta:k(T(),C()).nullish(),id:T(),reason:Pt.nullish(),sessionId:U}),Yn=x({_meta:k(T(),C()).nullish(),sessionId:U,terminalId:T()}),Xn=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cwd:T(),mcpServers:O(L).optional(),sessionId:U}),Zn=x({_meta:k(T(),C()).nullish(),additionalDirectories:O(T()).optional(),cwd:T(),sessionId:U,title:T().nullish(),updatedAt:T().nullish()}),Qn=x({_meta:k(T(),C()).nullish(),nextCursor:T().nullish(),sessions:O(Zn)}),$n=x({_meta:k(T(),C()).nullish(),title:T().nullish(),updatedAt:T().nullish()}),er=x({_meta:k(T(),C()).nullish()}),W=T(),tr=x({_meta:k(T(),C()).nullish(),currentModeId:W}),nr=x({_meta:k(T(),C()).nullish(),description:T().nullish(),id:W,name:T()}),G=x({_meta:k(T(),C()).nullish(),availableModes:O(nr),currentModeId:W}),K=x({_meta:k(T(),C()).nullish(),availableModels:O(bt),currentModelId:yt}),rr=x({_meta:k(T(),C()).nullish(),configOptions:O(H).nullish(),models:K.nullish(),modes:G.nullish(),sessionId:U}),ir=x({_meta:k(T(),C()).nullish(),configOptions:O(H).nullish(),models:K.nullish(),modes:G.nullish()}),ar=x({_meta:k(T(),C()).nullish(),configOptions:O(H).nullish(),models:K.nullish(),modes:G.nullish(),sessionId:U}),or=x({_meta:k(T(),C()).nullish(),configOptions:O(H).nullish(),models:K.nullish(),modes:G.nullish()}),sr=x({_meta:k(T(),C()).nullish()}),cr=x({_meta:k(T(),C()).nullish(),additionalDirectories:wn.nullish(),close:Tn.nullish(),fork:Pn.nullish(),list:er.nullish(),resume:sr.nullish()}),lr=A(E([x({type:b(`boolean`),value:D()}),x({value:An})]),x({_meta:k(T(),C()).nullish(),configId:On,sessionId:U})),ur=x({_meta:k(T(),C()).nullish(),configOptions:O(H)}),dr=x({_meta:k(T(),C()).nullish(),modeId:W,sessionId:U}),fr=x({_meta:k(T(),C()).nullish()}),pr=x({_meta:k(T(),C()).nullish(),modelId:yt,sessionId:U}),mr=x({_meta:k(T(),C()).nullish()}),hr=x({_meta:k(T(),C()).nullish(),sessionId:U}),gr=E([b(`end_turn`),b(`max_tokens`),b(`max_turn_requests`),b(`refusal`),b(`cancelled`)]),_r=E([b(`email`),b(`uri`),b(`date`),b(`date-time`)]),vr=x({default:T().nullish(),description:T().nullish(),enum:O(T()).nullish(),format:_r.nullish(),maxLength:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),minLength:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),oneOf:O($e).nullish(),pattern:T().nullish(),title:T().nullish()}),yr=x({_meta:k(T(),C()).nullish(),context:dn.nullish(),position:R,selection:z.nullish(),sessionId:U,triggerKind:Ht,uri:T(),version:S()}),br=x({_meta:k(T(),C()).nullish(),suggestions:O(pn)}),xr=x({_meta:k(T(),C()).nullish(),terminalId:T()}),Sr=x({_meta:k(T(),C()).nullish(),exitCode:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:T().nullish()}),Cr=x({_meta:k(T(),C()).nullish(),sessionId:U,terminalId:T()}),wr=x({_meta:k(T(),C()).nullish(),exitStatus:Sr.nullish(),output:T(),truncated:D()}),Tr=x({_meta:k(T(),C()).nullish(),annotations:V.nullish(),text:T()}),Er=x({range:z.nullish(),text:T()}),Dr=x({_meta:k(T(),C()).nullish(),contentChanges:O(Er),sessionId:U,uri:T(),version:S()});x({method:T(),params:E([In,Hn,Dr,Bn,Un,Vn,Fn,Jn,nt]).nullish()});var Or=E([b(`full`),b(`incremental`)]),kr=x({_meta:k(T(),C()).nullish(),syncKind:Or}),Ar=x({_meta:k(T(),C()).nullish(),didChange:kr.nullish(),didClose:Ct.nullish(),didFocus:wt.nullish(),didOpen:Tt.nullish(),didSave:Et.nullish()}),jr=x({_meta:k(T(),C()).nullish(),document:Ar.nullish()}),Mr=x({_meta:k(T(),C()).nullish(),context:Wt.nullish(),events:jr.nullish()}),Nr=x({_meta:k(T(),C()).nullish(),auth:ft.optional().default({}),loadSession:D().optional().default(!1),mcpCapabilities:ht.optional().default({http:!1,sse:!1}),nes:Mr.nullish(),positionEncoding:rn.nullish(),promptCapabilities:on.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:cr.optional().default({})}),Pr=x({_meta:k(T(),C()).nullish(),agentCapabilities:Nr.optional().default({auth:{},loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:st.nullish(),authMethods:O(Pe).optional().default([]),protocolVersion:sn}),Fr=E([x({_meta:k(T(),C()).nullish(),mimeType:T().nullish(),text:T(),uri:T()}),Le]),Ir=x({_meta:k(T(),C()).nullish(),annotations:V.nullish(),resource:Fr}),Lr=E([Tr.and(x({type:b(`text`)})),yn.and(x({type:b(`image`)})),vn.and(x({type:b(`audio`)})),bn.and(x({type:b(`resource_link`)})),Ir.and(x({type:b(`resource`)}))]),Rr=x({_meta:k(T(),C()).nullish(),content:Lr}),zr=x({_meta:k(T(),C()).nullish(),content:Lr,messageId:T().nullish()}),Br=x({_meta:k(T(),C()).nullish(),messageId:T().nullish(),prompt:O(Lr),sessionId:U}),Vr=x({anyOf:O($e)}),Hr=E([Rr.and(x({type:b(`content`)})),Ue.and(x({type:b(`diff`)})),xr.and(x({type:b(`terminal`)}))]),Ur=T(),Wr=x({sessionId:U,toolCallId:Ur.nullish()}),Gr=A(E([Wr,gn]),x({elicitationId:qe,url:T().url()})),Kr=x({_meta:k(T(),C()).nullish(),line:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:T()}),qr=E([b(`pending`),b(`in_progress`),b(`completed`),b(`failed`)]),Jr=E([b(`read`),b(`edit`),b(`delete`),b(`move`),b(`search`),b(`execute`),b(`think`),b(`fetch`),b(`switch_mode`),b(`other`)]),Yr=x({_meta:k(T(),C()).nullish(),content:O(Hr).optional(),kind:Jr.optional(),locations:O(Kr).optional(),rawInput:C().optional(),rawOutput:C().optional(),status:qr.optional(),title:T(),toolCallId:Ur}),Xr=x({_meta:k(T(),C()).nullish(),content:O(Hr).nullish(),kind:Jr.nullish(),locations:O(Kr).nullish(),rawInput:C().optional(),rawOutput:C().optional(),status:qr.nullish(),title:T().nullish(),toolCallId:Ur}),Zr=x({_meta:k(T(),C()).nullish(),options:O(Yt),sessionId:U,toolCall:Xr}),Qr=x({_meta:k(T(),C()).nullish(),hint:T()}),$r=x({_meta:k(T(),C()).nullish(),description:T(),input:Qr.nullish(),name:T()}),ei=x({_meta:k(T(),C()).nullish(),availableCommands:O($r)}),ti=E([x({enum:O(T()),type:Xe}),Vr]),ni=x({default:O(T()).nullish(),description:T().nullish(),items:ti,maxItems:S().nullish(),minItems:S().nullish(),title:T().nullish()}),ri=E([vr.and(x({type:b(`string`)})),Kt.and(x({type:b(`number`)})),ct.and(x({type:b(`integer`)})),Re.and(x({type:b(`boolean`)})),ni.and(x({type:b(`array`)}))]),ii=x({description:T().nullish(),properties:k(T(),ri).optional().default({}),required:O(T()).nullish(),title:T().nullish(),type:Ye.optional().default(`object`)}),ai=A(E([A(E([Wr,gn]),x({requestedSchema:ii})).and(x({mode:b(`form`)})),Gr.and(x({mode:b(`url`)}))]),x({_meta:k(T(),C()).nullish(),message:T()})),oi=x({cachedReadTokens:S().nullish(),cachedWriteTokens:S().nullish(),inputTokens:S(),outputTokens:S(),thoughtTokens:S().nullish(),totalTokens:S()});E([x({id:B,result:E([Pr,Ie,mt,ar,ir,Qn,rr,or,Be,fr,ur,x({_meta:k(T(),C()).nullish(),stopReason:gr,usage:oi.nullish(),userMessageId:T().nullish()}),mr,hr,br,ze,it])}),x({error:tt,id:B})]);var si=x({_meta:k(T(),C()).nullish(),cost:Ve.nullish(),size:S(),used:S()}),ci=E([zr.and(x({sessionUpdate:b(`user_message_chunk`)})),zr.and(x({sessionUpdate:b(`agent_message_chunk`)})),zr.and(x({sessionUpdate:b(`agent_thought_chunk`)})),Yr.and(x({sessionUpdate:b(`tool_call`)})),Xr.and(x({sessionUpdate:b(`tool_call_update`)})),$t.and(x({sessionUpdate:b(`plan`)})),ei.and(x({sessionUpdate:b(`available_commands_update`)})),tr.and(x({sessionUpdate:b(`current_mode_update`)})),Nn.and(x({sessionUpdate:b(`config_option_update`)})),$n.and(x({sessionUpdate:b(`session_info_update`)})),si.and(x({sessionUpdate:b(`usage_update`)}))]),li=x({_meta:k(T(),C()).nullish(),sessionId:U,update:ci});x({method:T(),params:E([li,Je,nt]).nullish()});var ui=x({_meta:k(T(),C()).nullish(),sessionId:U,terminalId:T()}),di=x({_meta:k(T(),C()).nullish(),exitCode:S().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:T().nullish()}),fi=x({name:T(),uri:T()}),pi=x({_meta:k(T(),C()).nullish(),repository:Rt.nullish(),workspaceFolders:O(fi).nullish(),workspaceUri:T().nullish()});x({id:B,method:T(),params:E([cn,Fe,pt,Gt,Kn,ut,Wn,Xn,Rn,dr,lr,Br,pr,pi,yr,Ln,rt]).nullish()});var mi=x({_meta:k(T(),C()).nullish(),content:T(),path:T(),sessionId:U});x({id:B,method:T(),params:E([mi,qn,Zr,zn,Cr,Yn,ui,Gn,ai,rt]).nullish()}),E([x({id:B,result:E([x({_meta:k(T(),C()).nullish()}),mn,Cn,He,wr,hn,di,lt,Ge,it])}),x({error:tt,id:B})]),e();function hi(e,t){let n=new TextEncoder,r=new TextDecoder;return{readable:new ReadableStream({async start(e){let n=``,i=t.getReader();try{for(;;){let{value:t,done:a}=await i.read();if(a){n+=r.decode();break}if(!t)continue;n+=r.decode(t,{stream:!0});let o=n.split(`
1
+ import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{$l as n,B as r,Ds as i,Es as a,Gd as o,Li as s,Mi as c,Oy as l,Ql as u,Sc as d,V as f,Wd as p,ar as m,br as h,i as g,o as _,wy as ee,xc as te}from"./loadAgentsDir-C96o6gCj.js";import{C as v,D as y,E as b,F as x,L as S,N as C,P as w,_ as T,f as ne,g as E,j as D,r as re,x as O}from"./lazySchema-DULtBUCI.js";import{$ as ie,Ut as k,ar as A,gr as ae,hr as oe,mt as se,zn as ce}from"./state-D5D6QpTX.js";import{d as le,h as ue}from"./settings-BowI3jp-.js";import{h as de,r as fe}from"./config-DUTgj3js.js";import{l as pe,p as me,r as he}from"./sessionStoragePortable-x0Yn02-G.js";import{_ as ge,u as _e}from"./model-BaMclMXn.js";import{_n as ve,vn as ye}from"./prompt-BNNE5tsG.js";import{n as be,r as xe}from"./managedEnv-CHYvwXBH.js";import{t as Se}from"./QueryEngine-DduzztIG.js";import{n as Ce,r as we}from"./modelOptions-Cw1ThINb.js";import{dirname as Te}from"node:path";import{randomUUID as j}from"node:crypto";import{Readable as Ee,Writable as De}from"node:stream";import{unlink as Oe}from"node:fs/promises";import*as M from"node:path/posix";import{isAbsolute as ke,resolve as Ae}from"node:path/posix";re();var N={authenticate:`authenticate`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_focus:`document/didFocus`,document_did_open:`document/didOpen`,document_did_save:`document/didSave`,initialize:`initialize`,logout:`logout`,nes_accept:`nes/accept`,nes_close:`nes/close`,nes_reject:`nes/reject`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,session_cancel:`session/cancel`,session_close:`session/close`,session_fork:`session/fork`,session_list:`session/list`,session_load:`session/load`,session_new:`session/new`,session_prompt:`session/prompt`,session_resume:`session/resume`,session_set_config_option:`session/set_config_option`,session_set_mode:`session/set_mode`,session_set_model:`session/set_model`},P={elicitation_complete:`elicitation/complete`,elicitation_create:`elicitation/create`,fs_read_text_file:`fs/read_text_file`,fs_write_text_file:`fs/write_text_file`,session_request_permission:`session/request_permission`,session_update:`session/update`,terminal_create:`terminal/create`,terminal_kill:`terminal/kill`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`},je=y({_meta:D(C(),x()).nullish(),terminal:T().optional().default(!1)}),Me=y({_meta:D(C(),x()).nullish(),label:C().nullish(),name:C(),optional:T().optional().default(!1),secret:T().optional().default(!0)}),Ne=y({_meta:D(C(),x()).nullish(),description:C().nullish(),id:C(),name:C()}),Pe=y({_meta:D(C(),x()).nullish(),description:C().nullish(),id:C(),link:C().nullish(),name:C(),vars:E(Me)}),Fe=y({_meta:D(C(),x()).nullish(),args:E(C()).optional(),description:C().nullish(),env:D(C(),C()).optional(),id:C(),name:C()}),Ie=w([Pe.and(y({type:v(`env_var`)})),Fe.and(y({type:v(`terminal`)})),Ne]),Le=y({_meta:D(C(),x()).nullish(),methodId:C()}),Re=y({_meta:D(C(),x()).nullish()}),ze=y({_meta:D(C(),x()).nullish(),blob:C(),mimeType:C().nullish(),uri:C()}),Be=y({default:T().nullish(),description:C().nullish(),title:C().nullish()}),Ve=y({_meta:D(C(),x()).nullish()}),He=y({_meta:D(C(),x()).nullish()}),Ue=y({amount:b(),currency:C()}),We=y({_meta:D(C(),x()).nullish(),terminalId:C()}),Ge=y({_meta:D(C(),x()).nullish(),newText:C(),oldText:C().nullish(),path:C()}),Ke=w([C(),b(),b(),T(),E(C())]),qe=O(w([y({content:D(C(),Ke).nullish()}).and(y({action:v(`accept`)})),y({action:v(`decline`)}),y({action:v(`cancel`)})]),y({_meta:D(C(),x()).nullish()})),Je=y({_meta:D(C(),x()).nullish()}),Ye=C(),Xe=y({_meta:D(C(),x()).nullish(),elicitationId:Ye}),Ze=v(`object`),Qe=v(`string`),$e=y({_meta:D(C(),x()).nullish()}),et=y({_meta:D(C(),x()).nullish(),form:Je.nullish(),url:$e.nullish()}),tt=y({const:C(),title:C()}),nt=y({_meta:D(C(),x()).nullish(),name:C(),value:C()}),rt=y({code:w([v(-32700),v(-32600),v(-32601),v(-32602),v(-32603),v(-32800),v(-32e3),v(-32002),v(-32042),b().int().min(-2147483648,{message:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{message:`Invalid value: Expected int32 to be <= 2147483647`})]),data:x().optional(),message:C()}),it=x(),at=x(),ot=x(),st=y({_meta:D(C(),x()).nullish(),readTextFile:T().optional().default(!1),writeTextFile:T().optional().default(!1)}),ct=y({_meta:D(C(),x()).nullish(),name:C(),value:C()}),lt=y({_meta:D(C(),x()).nullish(),name:C(),title:C().nullish(),version:C()}),ut=y({default:b().nullish(),description:C().nullish(),maximum:b().nullish(),minimum:b().nullish(),title:C().nullish()}),dt=y({_meta:D(C(),x()).nullish()}),ft=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cursor:C().nullish(),cwd:C().nullish()}),pt=y({_meta:D(C(),x()).nullish()}),mt=y({_meta:D(C(),x()).nullish(),logout:pt.nullish()}),ht=y({_meta:D(C(),x()).nullish()}),gt=y({_meta:D(C(),x()).nullish()}),_t=y({_meta:D(C(),x()).nullish(),http:T().optional().default(!1),sse:T().optional().default(!1)}),vt=y({_meta:D(C(),x()).nullish(),headers:E(ct),name:C(),url:C()}),yt=y({_meta:D(C(),x()).nullish(),headers:E(ct),name:C(),url:C()}),bt=y({_meta:D(C(),x()).nullish(),args:E(C()),command:C(),env:E(nt),name:C()}),F=w([vt.and(y({type:v(`http`)})),yt.and(y({type:v(`sse`)})),bt]),xt=C(),St=y({_meta:D(C(),x()).nullish(),description:C().nullish(),modelId:xt,name:C()}),Ct=w([v(`error`),v(`warning`),v(`information`),v(`hint`)]),wt=y({_meta:D(C(),x()).nullish()}),Tt=y({_meta:D(C(),x()).nullish()}),Et=y({_meta:D(C(),x()).nullish()}),Dt=y({_meta:D(C(),x()).nullish()}),Ot=y({_meta:D(C(),x()).nullish()}),kt=y({_meta:D(C(),x()).nullish(),maxCount:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),At=y({diff:C(),uri:C()}),jt=y({endLine:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),startLine:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),text:C()}),Mt=y({_meta:D(C(),x()).nullish()}),Nt=y({_meta:D(C(),x()).nullish()}),Pt=y({languageId:C(),text:C(),uri:C()}),Ft=y({_meta:D(C(),x()).nullish(),maxCount:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),It=w([v(`rejected`),v(`ignored`),v(`replaced`),v(`cancelled`)]),Lt=y({excerpts:E(jt),uri:C()}),Rt=y({_meta:D(C(),x()).nullish()}),zt=y({_meta:D(C(),x()).nullish()}),Bt=y({name:C(),owner:C(),remoteUrl:C()}),Vt=y({_meta:D(C(),x()).nullish()}),Ht=y({_meta:D(C(),x()).nullish(),jump:Mt.nullish(),rename:zt.nullish(),searchAndReplace:Vt.nullish()}),Ut=y({id:C(),isRegex:T().nullish(),replace:C(),search:C(),uri:C()}),Wt=w([v(`automatic`),v(`diagnostic`),v(`manual`)]),Gt=y({_meta:D(C(),x()).nullish(),maxCount:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish()}),Kt=y({_meta:D(C(),x()).nullish(),diagnostics:wt.nullish(),editHistory:kt.nullish(),openFiles:Nt.nullish(),recentFiles:Ft.nullish(),relatedSnippets:Rt.nullish(),userActions:Gt.nullish()}),qt=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cwd:C(),mcpServers:E(F)}),Jt=y({default:b().nullish(),description:C().nullish(),maximum:b().nullish(),minimum:b().nullish(),title:C().nullish()}),Yt=C(),Xt=w([v(`allow_once`),v(`allow_always`),v(`reject_once`),v(`reject_always`)]),Zt=y({_meta:D(C(),x()).nullish(),kind:Xt,name:C(),optionId:Yt}),Qt=w([v(`high`),v(`medium`),v(`low`)]),$t=w([v(`pending`),v(`in_progress`),v(`completed`)]),en=y({_meta:D(C(),x()).nullish(),content:C(),priority:Qt,status:$t}),tn=y({_meta:D(C(),x()).nullish(),entries:E(en)}),I=y({character:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}),line:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`})}),nn=y({id:C(),position:I,uri:C()}),rn=y({id:C(),newName:C(),position:I,uri:C()}),an=y({action:C(),position:I,timestampMs:b(),uri:C()}),on=w([v(`utf-16`),v(`utf-32`),v(`utf-8`)]),sn=y({_meta:D(C(),x()).nullish(),auth:je.optional().default({terminal:!1}),elicitation:et.nullish(),fs:st.optional().default({readTextFile:!1,writeTextFile:!1}),nes:Ht.nullish(),positionEncodings:E(on).optional(),terminal:T().optional().default(!1)}),cn=y({_meta:D(C(),x()).nullish(),audio:T().optional().default(!1),embeddedContext:T().optional().default(!1),image:T().optional().default(!1)}),ln=b().int().gte(0).lte(65535),un=y({_meta:D(C(),x()).nullish(),clientCapabilities:sn.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:lt.nullish(),protocolVersion:ln}),L=y({end:I,start:I}),dn=y({message:C(),range:L,severity:Ct,uri:C()}),fn=y({languageId:C(),lastFocusedMs:b().nullish(),uri:C(),visibleRange:L.nullish()}),pn=y({_meta:D(C(),x()).nullish(),diagnostics:E(dn).nullish(),editHistory:E(At).nullish(),openFiles:E(fn).nullish(),recentFiles:E(Pt).nullish(),relatedSnippets:E(Lt).nullish(),userActions:E(an).nullish()}),mn=y({newText:C(),range:L}),hn=w([y({cursorPosition:I.nullish(),edits:E(mn),id:C(),uri:C()}).and(y({kind:v(`edit`)})),nn.and(y({kind:v(`jump`)})),rn.and(y({kind:v(`rename`)})),Ut.and(y({kind:v(`searchAndReplace`)}))]),gn=y({_meta:D(C(),x()).nullish(),content:C()}),_n=y({_meta:D(C(),x()).nullish()}),R=w([b(),C()]).nullable();y({_meta:D(C(),x()).nullish(),requestId:R});var vn=y({requestId:R}),yn=ne([`assistant`,`user`]),z=y({_meta:D(C(),x()).nullish(),audience:E(yn).nullish(),lastModified:C().nullish(),priority:b().nullish()}),bn=y({_meta:D(C(),x()).nullish(),annotations:z.nullish(),data:C(),mimeType:C()}),xn=y({_meta:D(C(),x()).nullish(),annotations:z.nullish(),data:C(),mimeType:C(),uri:C().nullish()}),Sn=y({_meta:D(C(),x()).nullish(),annotations:z.nullish(),description:C().nullish(),mimeType:C().nullish(),name:C(),size:b().nullish(),title:C().nullish(),uri:C()}),Cn=y({_meta:D(C(),x()).nullish(),optionId:Yt}),wn=w([y({outcome:v(`cancelled`)}),Cn.and(y({outcome:v(`selected`)}))]),Tn=y({_meta:D(C(),x()).nullish(),outcome:wn}),En=y({_meta:D(C(),x()).nullish()}),Dn=y({_meta:D(C(),x()).nullish()}),On=y({currentValue:T()}),kn=C(),An=C(),jn=w([v(`mode`),v(`model`),v(`thought_level`),C()]),B=C(),Mn=y({_meta:D(C(),x()).nullish(),description:C().nullish(),name:C(),value:B}),Nn=y({_meta:D(C(),x()).nullish(),group:kn,name:C(),options:E(Mn)}),V=O(w([y({currentValue:B,options:w([E(Mn),E(Nn)])}).and(y({type:v(`select`)})),On.and(y({type:v(`boolean`)}))]),y({_meta:D(C(),x()).nullish(),category:jn.nullish(),description:C().nullish(),id:An,name:C()})),Pn=y({_meta:D(C(),x()).nullish(),configOptions:E(V)}),Fn=y({_meta:D(C(),x()).nullish()}),H=C(),In=y({_meta:D(C(),x()).nullish(),id:C(),sessionId:H}),Ln=y({_meta:D(C(),x()).nullish(),sessionId:H}),Rn=y({_meta:D(C(),x()).nullish(),sessionId:H}),zn=y({_meta:D(C(),x()).nullish(),sessionId:H}),Bn=y({_meta:D(C(),x()).nullish(),args:E(C()).optional(),command:C(),cwd:C().nullish(),env:E(nt).optional(),outputByteLimit:b().nullish(),sessionId:H}),Vn=y({_meta:D(C(),x()).nullish(),sessionId:H,uri:C()}),Hn=y({_meta:D(C(),x()).nullish(),position:I,sessionId:H,uri:C(),version:b(),visibleRange:L}),Un=y({_meta:D(C(),x()).nullish(),languageId:C(),sessionId:H,text:C(),uri:C(),version:b()}),Wn=y({_meta:D(C(),x()).nullish(),sessionId:H,uri:C()}),Gn=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cwd:C(),mcpServers:E(F).optional(),sessionId:H}),Kn=y({_meta:D(C(),x()).nullish(),sessionId:H,terminalId:C()}),qn=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cwd:C(),mcpServers:E(F),sessionId:H}),Jn=y({_meta:D(C(),x()).nullish(),limit:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),line:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:C(),sessionId:H}),Yn=y({_meta:D(C(),x()).nullish(),id:C(),reason:It.nullish(),sessionId:H}),Xn=y({_meta:D(C(),x()).nullish(),sessionId:H,terminalId:C()}),Zn=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cwd:C(),mcpServers:E(F).optional(),sessionId:H}),Qn=y({_meta:D(C(),x()).nullish(),additionalDirectories:E(C()).optional(),cwd:C(),sessionId:H,title:C().nullish(),updatedAt:C().nullish()}),$n=y({_meta:D(C(),x()).nullish(),nextCursor:C().nullish(),sessions:E(Qn)}),er=y({_meta:D(C(),x()).nullish(),title:C().nullish(),updatedAt:C().nullish()}),tr=y({_meta:D(C(),x()).nullish()}),U=C(),nr=y({_meta:D(C(),x()).nullish(),currentModeId:U}),rr=y({_meta:D(C(),x()).nullish(),description:C().nullish(),id:U,name:C()}),W=y({_meta:D(C(),x()).nullish(),availableModes:E(rr),currentModeId:U}),G=y({_meta:D(C(),x()).nullish(),availableModels:E(St),currentModelId:xt}),ir=y({_meta:D(C(),x()).nullish(),configOptions:E(V).nullish(),models:G.nullish(),modes:W.nullish(),sessionId:H}),ar=y({_meta:D(C(),x()).nullish(),configOptions:E(V).nullish(),models:G.nullish(),modes:W.nullish()}),or=y({_meta:D(C(),x()).nullish(),configOptions:E(V).nullish(),models:G.nullish(),modes:W.nullish(),sessionId:H}),sr=y({_meta:D(C(),x()).nullish(),configOptions:E(V).nullish(),models:G.nullish(),modes:W.nullish()}),cr=y({_meta:D(C(),x()).nullish()}),lr=y({_meta:D(C(),x()).nullish(),additionalDirectories:En.nullish(),close:Dn.nullish(),fork:Fn.nullish(),list:tr.nullish(),resume:cr.nullish()}),ur=O(w([y({type:v(`boolean`),value:T()}),y({value:B})]),y({_meta:D(C(),x()).nullish(),configId:An,sessionId:H})),dr=y({_meta:D(C(),x()).nullish(),configOptions:E(V)}),fr=y({_meta:D(C(),x()).nullish(),modeId:U,sessionId:H}),pr=y({_meta:D(C(),x()).nullish()}),mr=y({_meta:D(C(),x()).nullish(),modelId:xt,sessionId:H}),hr=y({_meta:D(C(),x()).nullish()}),gr=y({_meta:D(C(),x()).nullish(),sessionId:H}),_r=w([v(`end_turn`),v(`max_tokens`),v(`max_turn_requests`),v(`refusal`),v(`cancelled`)]),vr=w([v(`email`),v(`uri`),v(`date`),v(`date-time`)]),yr=y({default:C().nullish(),description:C().nullish(),enum:E(C()).nullish(),format:vr.nullish(),maxLength:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),minLength:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),oneOf:E(tt).nullish(),pattern:C().nullish(),title:C().nullish()}),br=y({_meta:D(C(),x()).nullish(),context:pn.nullish(),position:I,selection:L.nullish(),sessionId:H,triggerKind:Wt,uri:C(),version:b()}),xr=y({_meta:D(C(),x()).nullish(),suggestions:E(hn)}),Sr=y({_meta:D(C(),x()).nullish(),terminalId:C()}),Cr=y({_meta:D(C(),x()).nullish(),exitCode:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:C().nullish()}),wr=y({_meta:D(C(),x()).nullish(),sessionId:H,terminalId:C()}),Tr=y({_meta:D(C(),x()).nullish(),exitStatus:Cr.nullish(),output:C(),truncated:T()}),Er=y({_meta:D(C(),x()).nullish(),annotations:z.nullish(),text:C()}),Dr=y({range:L.nullish(),text:C()}),Or=y({_meta:D(C(),x()).nullish(),contentChanges:E(Dr),sessionId:H,uri:C(),version:b()});y({method:C(),params:w([Ln,Un,Or,Vn,Wn,Hn,In,Yn,it]).nullish()});var kr=w([v(`full`),v(`incremental`)]),Ar=y({_meta:D(C(),x()).nullish(),syncKind:kr}),jr=y({_meta:D(C(),x()).nullish(),didChange:Ar.nullish(),didClose:Tt.nullish(),didFocus:Et.nullish(),didOpen:Dt.nullish(),didSave:Ot.nullish()}),Mr=y({_meta:D(C(),x()).nullish(),document:jr.nullish()}),Nr=y({_meta:D(C(),x()).nullish(),context:Kt.nullish(),events:Mr.nullish()}),Pr=y({_meta:D(C(),x()).nullish(),auth:mt.optional().default({}),loadSession:T().optional().default(!1),mcpCapabilities:_t.optional().default({http:!1,sse:!1}),nes:Nr.nullish(),positionEncoding:on.nullish(),promptCapabilities:cn.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:lr.optional().default({})}),Fr=y({_meta:D(C(),x()).nullish(),agentCapabilities:Pr.optional().default({auth:{},loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:lt.nullish(),authMethods:E(Ie).optional().default([]),protocolVersion:ln}),Ir=w([y({_meta:D(C(),x()).nullish(),mimeType:C().nullish(),text:C(),uri:C()}),ze]),Lr=y({_meta:D(C(),x()).nullish(),annotations:z.nullish(),resource:Ir}),K=w([Er.and(y({type:v(`text`)})),xn.and(y({type:v(`image`)})),bn.and(y({type:v(`audio`)})),Sn.and(y({type:v(`resource_link`)})),Lr.and(y({type:v(`resource`)}))]),Rr=y({_meta:D(C(),x()).nullish(),content:K}),zr=y({_meta:D(C(),x()).nullish(),content:K,messageId:C().nullish()}),Br=y({_meta:D(C(),x()).nullish(),messageId:C().nullish(),prompt:E(K),sessionId:H}),Vr=y({anyOf:E(tt)}),Hr=w([Rr.and(y({type:v(`content`)})),Ge.and(y({type:v(`diff`)})),Sr.and(y({type:v(`terminal`)}))]),Ur=C(),Wr=y({sessionId:H,toolCallId:Ur.nullish()}),Gr=O(w([Wr,vn]),y({elicitationId:Ye,url:C().url()})),Kr=y({_meta:D(C(),x()).nullish(),line:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:C()}),qr=w([v(`pending`),v(`in_progress`),v(`completed`),v(`failed`)]),Jr=w([v(`read`),v(`edit`),v(`delete`),v(`move`),v(`search`),v(`execute`),v(`think`),v(`fetch`),v(`switch_mode`),v(`other`)]),Yr=y({_meta:D(C(),x()).nullish(),content:E(Hr).optional(),kind:Jr.optional(),locations:E(Kr).optional(),rawInput:x().optional(),rawOutput:x().optional(),status:qr.optional(),title:C(),toolCallId:Ur}),Xr=y({_meta:D(C(),x()).nullish(),content:E(Hr).nullish(),kind:Jr.nullish(),locations:E(Kr).nullish(),rawInput:x().optional(),rawOutput:x().optional(),status:qr.nullish(),title:C().nullish(),toolCallId:Ur}),Zr=y({_meta:D(C(),x()).nullish(),options:E(Zt),sessionId:H,toolCall:Xr}),Qr=y({_meta:D(C(),x()).nullish(),hint:C()}),$r=y({_meta:D(C(),x()).nullish(),description:C(),input:Qr.nullish(),name:C()}),ei=y({_meta:D(C(),x()).nullish(),availableCommands:E($r)}),ti=w([y({enum:E(C()),type:Qe}),Vr]),ni=y({default:E(C()).nullish(),description:C().nullish(),items:ti,maxItems:b().nullish(),minItems:b().nullish(),title:C().nullish()}),ri=w([yr.and(y({type:v(`string`)})),Jt.and(y({type:v(`number`)})),ut.and(y({type:v(`integer`)})),Be.and(y({type:v(`boolean`)})),ni.and(y({type:v(`array`)}))]),ii=y({description:C().nullish(),properties:D(C(),ri).optional().default({}),required:E(C()).nullish(),title:C().nullish(),type:Ze.optional().default(`object`)}),ai=O(w([O(w([Wr,vn]),y({requestedSchema:ii})).and(y({mode:v(`form`)})),Gr.and(y({mode:v(`url`)}))]),y({_meta:D(C(),x()).nullish(),message:C()})),oi=y({cachedReadTokens:b().nullish(),cachedWriteTokens:b().nullish(),inputTokens:b(),outputTokens:b(),thoughtTokens:b().nullish(),totalTokens:b()});w([y({id:R,result:w([Fr,Re,gt,or,ar,$n,ir,sr,He,pr,dr,y({_meta:D(C(),x()).nullish(),stopReason:_r,usage:oi.nullish(),userMessageId:C().nullish()}),hr,gr,xr,Ve,ot])}),y({error:rt,id:R})]);var si=y({_meta:D(C(),x()).nullish(),cost:Ue.nullish(),size:b(),used:b()}),ci=w([zr.and(y({sessionUpdate:v(`user_message_chunk`)})),zr.and(y({sessionUpdate:v(`agent_message_chunk`)})),zr.and(y({sessionUpdate:v(`agent_thought_chunk`)})),Yr.and(y({sessionUpdate:v(`tool_call`)})),Xr.and(y({sessionUpdate:v(`tool_call_update`)})),tn.and(y({sessionUpdate:v(`plan`)})),ei.and(y({sessionUpdate:v(`available_commands_update`)})),nr.and(y({sessionUpdate:v(`current_mode_update`)})),Pn.and(y({sessionUpdate:v(`config_option_update`)})),er.and(y({sessionUpdate:v(`session_info_update`)})),si.and(y({sessionUpdate:v(`usage_update`)}))]),li=y({_meta:D(C(),x()).nullish(),sessionId:H,update:ci});y({method:C(),params:w([li,Xe,it]).nullish()});var ui=y({_meta:D(C(),x()).nullish(),sessionId:H,terminalId:C()}),di=y({_meta:D(C(),x()).nullish(),exitCode:b().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:C().nullish()}),fi=y({name:C(),uri:C()}),pi=y({_meta:D(C(),x()).nullish(),repository:Bt.nullish(),workspaceFolders:E(fi).nullish(),workspaceUri:C().nullish()});y({id:R,method:C(),params:w([un,Le,ht,qt,qn,ft,Gn,Zn,zn,fr,ur,Br,mr,pi,br,Rn,at]).nullish()});var mi=y({_meta:D(C(),x()).nullish(),content:C(),path:C(),sessionId:H});y({id:R,method:C(),params:w([mi,Jn,Zr,Bn,wr,Xn,ui,Kn,ai,at]).nullish()}),w([y({id:R,result:w([y({_meta:D(C(),x()).nullish()}),gn,Tn,We,Tr,_n,di,dt,qe,ot])}),y({error:rt,id:R})]),e();function hi(e,t){let n=new TextEncoder,r=new TextDecoder;return{readable:new ReadableStream({async start(e){let n=``,i=t.getReader();try{for(;;){let{value:t,done:a}=await i.read();if(a){n+=r.decode();break}if(!t)continue;n+=r.decode(t,{stream:!0});let o=n.split(`
2
2
  `);n=o.pop()||``;for(let t of o){let n=t.trim();if(n)try{let t=JSON.parse(n);e.enqueue(t)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}}}let t=n.trim();if(t)try{let n=JSON.parse(t);e.enqueue(n)}catch(e){console.error(`Failed to parse JSON message:`,t,e)}}catch(t){e.error(t);return}finally{i.releaseLock()}e.close()}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
3
- `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}te();var gi,_i=class{constructor(e,n){t(this,`connection`,void 0);let r=e(this),i=async(e,t)=>{switch(e){case F.initialize:{let e=cn.parse(t);return r.initialize(e)}case F.session_new:{let e=Gt.parse(t);return r.newSession(e)}case F.session_load:{if(!r.loadSession)throw q.methodNotFound(e);let n=Kn.parse(t);return r.loadSession(n)}case F.session_list:{if(!r.listSessions)throw q.methodNotFound(e);let n=ut.parse(t);return r.listSessions(n)}case F.session_fork:{if(!r.unstable_forkSession)throw q.methodNotFound(e);let n=Wn.parse(t);return r.unstable_forkSession(n)}case F.session_resume:{if(!r.unstable_resumeSession)throw q.methodNotFound(e);let n=Xn.parse(t);return r.unstable_resumeSession(n)}case F.session_close:{if(!r.unstable_closeSession)throw q.methodNotFound(e);let n=Rn.parse(t);return r.unstable_closeSession(n)}case F.session_set_mode:{if(!r.setSessionMode)throw q.methodNotFound(e);let n=dr.parse(t);return await r.setSessionMode(n)??{}}case F.authenticate:{let e=Fe.parse(t);return await r.authenticate(e)??{}}case F.logout:{if(!r.unstable_logout)throw q.methodNotFound(e);let n=pt.parse(t);return await r.unstable_logout(n)??{}}case F.session_prompt:{let e=Br.parse(t);return r.prompt(e)}case F.session_set_model:{if(!r.unstable_setSessionModel)throw q.methodNotFound(e);let n=pr.parse(t);return await r.unstable_setSessionModel(n)??{}}case F.session_set_config_option:{if(!r.setSessionConfigOption)throw q.methodNotFound(e);let n=lr.parse(t);return r.setSessionConfigOption(n)}case F.nes_start:{if(!r.unstable_startNes)throw q.methodNotFound(e);let n=pi.parse(t);return r.unstable_startNes(n)}case F.nes_suggest:{if(!r.unstable_suggestNes)throw q.methodNotFound(e);let n=yr.parse(t);return r.unstable_suggestNes(n)}case F.nes_close:{if(!r.unstable_closeNes)throw q.methodNotFound(e);let n=Ln.parse(t);return await r.unstable_closeNes(n)??{}}default:if(r.extMethod)return r.extMethod(e,t);throw q.methodNotFound(e)}},a=async(e,t)=>{switch(e){case F.session_cancel:{let e=In.parse(t);return r.cancel(e)}case F.document_did_open:{if(!r.unstable_didOpenDocument)return;let e=Hn.parse(t);return r.unstable_didOpenDocument(e)}case F.document_did_change:{if(!r.unstable_didChangeDocument)return;let e=Dr.parse(t);return r.unstable_didChangeDocument(e)}case F.document_did_close:{if(!r.unstable_didCloseDocument)return;let e=Bn.parse(t);return r.unstable_didCloseDocument(e)}case F.document_did_save:{if(!r.unstable_didSaveDocument)return;let e=Un.parse(t);return r.unstable_didSaveDocument(e)}case F.document_did_focus:{if(!r.unstable_didFocusDocument)return;let e=Vn.parse(t);return r.unstable_didFocusDocument(e)}case F.nes_accept:{if(!r.unstable_acceptNes)return;let e=Fn.parse(t);return r.unstable_acceptNes(e)}case F.nes_reject:{if(!r.unstable_rejectNes)return;let e=Jn.parse(t);return r.unstable_rejectNes(e)}default:if(r.extNotification)return r.extNotification(e,t);throw q.methodNotFound(e)}};this.connection=new yi(i,a,n)}async sessionUpdate(e){return await this.connection.sendNotification(I.session_update,e)}async requestPermission(e){return await this.connection.sendRequest(I.session_request_permission,e)}async readTextFile(e){return await this.connection.sendRequest(I.fs_read_text_file,e)}async writeTextFile(e){return await this.connection.sendRequest(I.fs_write_text_file,e)??{}}async createTerminal(e){return new vi((await this.connection.sendRequest(I.terminal_create,e)).terminalId,e.sessionId,this.connection)}async unstable_createElicitation(e){return await this.connection.sendRequest(I.elicitation_create,e)}async unstable_completeElicitation(e){return await this.connection.sendNotification(I.elicitation_complete,e)}async extMethod(e,t){return await this.connection.sendRequest(e,t)}async extNotification(e,t){return await this.connection.sendNotification(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}};gi=Symbol.asyncDispose;var vi=class{constructor(e,n,r){t(this,`id`,void 0),t(this,`sessionId`,void 0),t(this,`connection`,void 0),this.id=e,this.sessionId=n,this.connection=r}async currentOutput(){return await this.connection.sendRequest(I.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}async waitForExit(){return await this.connection.sendRequest(I.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}async kill(){return await this.connection.sendRequest(I.terminal_kill,{sessionId:this.sessionId,terminalId:this.id})??{}}async release(){return await this.connection.sendRequest(I.terminal_release,{sessionId:this.sessionId,terminalId:this.id})??{}}async[gi](){await this.release()}},yi=class{constructor(e,n,r){t(this,`pendingResponses`,new Map),t(this,`nextRequestId`,0),t(this,`requestHandler`,void 0),t(this,`notificationHandler`,void 0),t(this,`stream`,void 0),t(this,`writeQueue`,Promise.resolve()),t(this,`abortController`,new AbortController),t(this,`closedPromise`,void 0),this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let e=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(n)break;if(t)try{this.processMessage(t)}catch(e){console.error(`Unexpected error during message processing:`,t,e),`id`in t&&t.id!==void 0&&this.sendMessage({jsonrpc:`2.0`,id:t.id,error:{code:-32700,message:`Parse error`}})}}}finally{e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);for(let e of this.pendingResponses.values())e.reject(t);this.pendingResponses.clear(),this.abortController.abort(t)}async processMessage(e){if(`method`in e&&`id`in e){let t=await this.tryCallRequestHandler(e.method,e.params);`error`in t&&console.error(`Error handling request`,e,t.error),await this.sendMessage({jsonrpc:`2.0`,id:e.id,...t})}else if(`method`in e){let t=await this.tryCallNotificationHandler(e.method,e.params);`error`in t&&console.error(`Error handling notification`,e,t.error)}else`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}async tryCallRequestHandler(e,t){try{return{result:await this.requestHandler(e,t)??null}}catch(e){if(e instanceof q)return e.toResult();if(e instanceof w)return q.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return q.internalError(t?JSON.parse(t):{}).toResult()}catch{return q.internalError({details:t}).toResult()}}}async tryCallNotificationHandler(e,t){try{return await this.notificationHandler(e,t),{result:null}}catch(e){if(e instanceof q)return e.toResult();if(e instanceof w)return q.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return q.internalError(t?JSON.parse(t):{}).toResult()}catch{return q.internalError({details:t}).toResult()}}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t){if(`result`in e)t.resolve(e.result);else if(`error`in e){let{code:n,message:r,data:i}=e.error;t.reject(new q(n,r,i))}this.pendingResponses.delete(e.id)}else console.error(`Got response to unknown request`,e.id)}sendRequest(e,t){this.throwIfClosed();let n=this.nextRequestId++,r=new Promise((e,t)=>{this.pendingResponses.set(n,{resolve:e,reject:t})});return r.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:n,method:e,params:t}),r}async sendNotification(e,t){this.throwIfClosed(),await this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}throwIfClosed(){if(this.abortController.signal.aborted)throw this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{this.close(e)}),this.writeQueue}},q=class e extends Error{constructor(e,n,r){super(n),t(this,`code`,void 0),t(this,`data`,void 0),this.code=e,this.name=`RequestError`,this.data=r}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};ie(),j(),ce(),_e(),le(),n(),v(),c(),o(),l(),_(),ye();function J(e,t){if(e)return t?De(e)?e:Oe(t,e):e}var bi=!(typeof process.geteuid==`function`?process.geteuid()===0:typeof process.getuid==`function`&&process.getuid()===0)||!!process.env.IS_SANDBOX,xi={auto:`auto`,default:`default`,acceptedits:`acceptEdits`,dontask:`dontAsk`,plan:`plan`,bypasspermissions:`bypassPermissions`,bypass:`bypassPermissions`};function Si(e,t=`permissions.defaultMode`){if(e===void 0)return`default`;if(typeof e!=`string`)throw Error(`Invalid ${t}: expected a string.`);let n=e.trim().toLowerCase();if(n===``)throw Error(`Invalid ${t}: expected a non-empty string.`);let r=xi[n];if(!r)throw Error(`Invalid ${t}: ${e}.`);if(r===`bypassPermissions`&&!bi)throw Error(`Invalid ${t}: bypassPermissions is not available when running as root.`);return r}function Ci(e){let t=[...e.mcpServers??[]].sort((e,t)=>e.name.localeCompare(t.name));return JSON.stringify({cwd:e.cwd,mcpServers:t})}var wi=256;function Ti(e){let t=e.replace(/[\r\n]+/g,` `).replace(/\s+/g,` `).trim();return t.length<=wi?t:`${t.slice(0,wi-1)}…`}function Ei(e,t){if(!t)return e;let n=P.resolve(t),r=P.resolve(e);return r.startsWith(n+P.sep)||r===n?P.relative(n,r):e}function Di(e){let t="```";for(let n of e.matchAll(/^```+/gm)??[])for(;n[0].length>=t.length;)t+="`";return`${t}\n${e}${e.endsWith(`
3
+ `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}re();var gi,_i=class{constructor(e,n){t(this,`connection`,void 0);let r=e(this),i=async(e,t)=>{switch(e){case N.initialize:{let e=un.parse(t);return r.initialize(e)}case N.session_new:{let e=qt.parse(t);return r.newSession(e)}case N.session_load:{if(!r.loadSession)throw q.methodNotFound(e);let n=qn.parse(t);return r.loadSession(n)}case N.session_list:{if(!r.listSessions)throw q.methodNotFound(e);let n=ft.parse(t);return r.listSessions(n)}case N.session_fork:{if(!r.unstable_forkSession)throw q.methodNotFound(e);let n=Gn.parse(t);return r.unstable_forkSession(n)}case N.session_resume:{if(!r.unstable_resumeSession)throw q.methodNotFound(e);let n=Zn.parse(t);return r.unstable_resumeSession(n)}case N.session_close:{if(!r.unstable_closeSession)throw q.methodNotFound(e);let n=zn.parse(t);return r.unstable_closeSession(n)}case N.session_set_mode:{if(!r.setSessionMode)throw q.methodNotFound(e);let n=fr.parse(t);return await r.setSessionMode(n)??{}}case N.authenticate:{let e=Le.parse(t);return await r.authenticate(e)??{}}case N.logout:{if(!r.unstable_logout)throw q.methodNotFound(e);let n=ht.parse(t);return await r.unstable_logout(n)??{}}case N.session_prompt:{let e=Br.parse(t);return r.prompt(e)}case N.session_set_model:{if(!r.unstable_setSessionModel)throw q.methodNotFound(e);let n=mr.parse(t);return await r.unstable_setSessionModel(n)??{}}case N.session_set_config_option:{if(!r.setSessionConfigOption)throw q.methodNotFound(e);let n=ur.parse(t);return r.setSessionConfigOption(n)}case N.nes_start:{if(!r.unstable_startNes)throw q.methodNotFound(e);let n=pi.parse(t);return r.unstable_startNes(n)}case N.nes_suggest:{if(!r.unstable_suggestNes)throw q.methodNotFound(e);let n=br.parse(t);return r.unstable_suggestNes(n)}case N.nes_close:{if(!r.unstable_closeNes)throw q.methodNotFound(e);let n=Rn.parse(t);return await r.unstable_closeNes(n)??{}}default:if(r.extMethod)return r.extMethod(e,t);throw q.methodNotFound(e)}},a=async(e,t)=>{switch(e){case N.session_cancel:{let e=Ln.parse(t);return r.cancel(e)}case N.document_did_open:{if(!r.unstable_didOpenDocument)return;let e=Un.parse(t);return r.unstable_didOpenDocument(e)}case N.document_did_change:{if(!r.unstable_didChangeDocument)return;let e=Or.parse(t);return r.unstable_didChangeDocument(e)}case N.document_did_close:{if(!r.unstable_didCloseDocument)return;let e=Vn.parse(t);return r.unstable_didCloseDocument(e)}case N.document_did_save:{if(!r.unstable_didSaveDocument)return;let e=Wn.parse(t);return r.unstable_didSaveDocument(e)}case N.document_did_focus:{if(!r.unstable_didFocusDocument)return;let e=Hn.parse(t);return r.unstable_didFocusDocument(e)}case N.nes_accept:{if(!r.unstable_acceptNes)return;let e=In.parse(t);return r.unstable_acceptNes(e)}case N.nes_reject:{if(!r.unstable_rejectNes)return;let e=Yn.parse(t);return r.unstable_rejectNes(e)}default:if(r.extNotification)return r.extNotification(e,t);throw q.methodNotFound(e)}};this.connection=new yi(i,a,n)}async sessionUpdate(e){return await this.connection.sendNotification(P.session_update,e)}async requestPermission(e){return await this.connection.sendRequest(P.session_request_permission,e)}async readTextFile(e){return await this.connection.sendRequest(P.fs_read_text_file,e)}async writeTextFile(e){return await this.connection.sendRequest(P.fs_write_text_file,e)??{}}async createTerminal(e){return new vi((await this.connection.sendRequest(P.terminal_create,e)).terminalId,e.sessionId,this.connection)}async unstable_createElicitation(e){return await this.connection.sendRequest(P.elicitation_create,e)}async unstable_completeElicitation(e){return await this.connection.sendNotification(P.elicitation_complete,e)}async extMethod(e,t){return await this.connection.sendRequest(e,t)}async extNotification(e,t){return await this.connection.sendNotification(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}};gi=Symbol.asyncDispose;var vi=class{constructor(e,n,r){t(this,`id`,void 0),t(this,`sessionId`,void 0),t(this,`connection`,void 0),this.id=e,this.sessionId=n,this.connection=r}async currentOutput(){return await this.connection.sendRequest(P.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}async waitForExit(){return await this.connection.sendRequest(P.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}async kill(){return await this.connection.sendRequest(P.terminal_kill,{sessionId:this.sessionId,terminalId:this.id})??{}}async release(){return await this.connection.sendRequest(P.terminal_release,{sessionId:this.sessionId,terminalId:this.id})??{}}async[gi](){await this.release()}},yi=class{constructor(e,n,r){t(this,`pendingResponses`,new Map),t(this,`nextRequestId`,0),t(this,`requestHandler`,void 0),t(this,`notificationHandler`,void 0),t(this,`stream`,void 0),t(this,`writeQueue`,Promise.resolve()),t(this,`abortController`,new AbortController),t(this,`closedPromise`,void 0),this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let e=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(n)break;if(t)try{this.processMessage(t)}catch(e){console.error(`Unexpected error during message processing:`,t,e),`id`in t&&t.id!==void 0&&this.sendMessage({jsonrpc:`2.0`,id:t.id,error:{code:-32700,message:`Parse error`}})}}}finally{e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);for(let e of this.pendingResponses.values())e.reject(t);this.pendingResponses.clear(),this.abortController.abort(t)}async processMessage(e){if(`method`in e&&`id`in e){let t=await this.tryCallRequestHandler(e.method,e.params);`error`in t&&console.error(`Error handling request`,e,t.error),await this.sendMessage({jsonrpc:`2.0`,id:e.id,...t})}else if(`method`in e){let t=await this.tryCallNotificationHandler(e.method,e.params);`error`in t&&console.error(`Error handling notification`,e,t.error)}else`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}async tryCallRequestHandler(e,t){try{return{result:await this.requestHandler(e,t)??null}}catch(e){if(e instanceof q)return e.toResult();if(e instanceof S)return q.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return q.internalError(t?JSON.parse(t):{}).toResult()}catch{return q.internalError({details:t}).toResult()}}}async tryCallNotificationHandler(e,t){try{return await this.notificationHandler(e,t),{result:null}}catch(e){if(e instanceof q)return e.toResult();if(e instanceof S)return q.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return q.internalError(t?JSON.parse(t):{}).toResult()}catch{return q.internalError({details:t}).toResult()}}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t){if(`result`in e)t.resolve(e.result);else if(`error`in e){let{code:n,message:r,data:i}=e.error;t.reject(new q(n,r,i))}this.pendingResponses.delete(e.id)}else console.error(`Got response to unknown request`,e.id)}sendRequest(e,t){this.throwIfClosed();let n=this.nextRequestId++,r=new Promise((e,t)=>{this.pendingResponses.set(n,{resolve:e,reject:t})});return r.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:n,method:e,params:t}),r}async sendNotification(e,t){this.throwIfClosed(),await this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}throwIfClosed(){if(this.abortController.signal.aborted)throw this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{this.close(e)}),this.writeQueue}},q=class e extends Error{constructor(e,n,r){super(n),t(this,`code`,void 0),t(this,`data`,void 0),this.code=e,this.name=`RequestError`,this.data=r}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};oe(),k(),ue(),ye(),de(),l(),d(),i(),s(),f(),_(),xe();function J(e,t){if(e)return t?ke(e)?e:Ae(t,e):e}var bi=!(typeof process.geteuid==`function`?process.geteuid()===0:typeof process.getuid==`function`&&process.getuid()===0)||!!process.env.IS_SANDBOX,xi={auto:`auto`,default:`default`,acceptedits:`acceptEdits`,dontask:`dontAsk`,plan:`plan`,bypasspermissions:`bypassPermissions`,bypass:`bypassPermissions`};function Si(e,t=`permissions.defaultMode`){if(e===void 0)return`default`;if(typeof e!=`string`)throw Error(`Invalid ${t}: expected a string.`);let n=e.trim().toLowerCase();if(n===``)throw Error(`Invalid ${t}: expected a non-empty string.`);let r=xi[n];if(!r)throw Error(`Invalid ${t}: ${e}.`);if(r===`bypassPermissions`&&!bi)throw Error(`Invalid ${t}: bypassPermissions is not available when running as root.`);return r}function Ci(e){let t=[...e.mcpServers??[]].sort((e,t)=>e.name.localeCompare(t.name));return JSON.stringify({cwd:e.cwd,mcpServers:t})}var wi=256;function Ti(e){let t=e.replace(/[\r\n]+/g,` `).replace(/\s+/g,` `).trim();return t.length<=wi?t:`${t.slice(0,wi-1)}…`}function Ei(e,t){if(!t)return e;let n=M.resolve(t),r=M.resolve(e);return r.startsWith(n+M.sep)||r===n?M.relative(n,r):e}function Di(e){let t="```";for(let n of e.matchAll(/^```+/gm)??[])for(;n[0].length>=t.length;)t+="`";return`${t}\n${e}${e.endsWith(`
4
4
  `)?``:`
5
5
  `}${t}`}function Y(e,t=!1,n){let r=e.name,i=e.input;switch(r){case`Agent`:case`Task`:{let e=i?.description??`Task`,t=i?.prompt;return{title:e,kind:`think`,content:t?[{type:`content`,content:{type:`text`,text:t}}]:[]}}case`Bash`:{let e=i?.command??`Terminal`,t=i?.description;return{title:e,kind:`execute`,content:t?[{type:`content`,content:{type:`text`,text:t}}]:[]}}case`Read`:{let e=i?.file_path,t=e??`File`,r=i?.offset,a=i?.limit,o=``;a&&a>0?o=` (${r??1} - ${(r??1)+a-1})`:r&&(o=` (from line ${r})`);let s=t?Ei(t,n):`File`,c=J(e,n);return{title:`Read ${s}${o}`,kind:`read`,locations:c?[{path:c,line:r??1}]:[],content:[]}}case`Write`:{let e=i?.file_path??``,t=i?.content??``,r=e?Ei(e,n):void 0,a=J(e,n);return{title:r?`Write ${r}`:`Write`,kind:`edit`,content:a?[{type:`diff`,path:a,oldText:null,newText:t}]:[{type:`content`,content:{type:`text`,text:t}}],locations:a?[{path:a}]:[]}}case`Edit`:{let e=i?.file_path??``,t=i?.old_string??``,r=i?.new_string??``,a=e?Ei(e,n):void 0,o=J(e,n);return{title:a?`Edit ${a}`:`Edit`,kind:`edit`,content:o?[{type:`diff`,path:o,oldText:t||null,newText:r}]:[],locations:o?[{path:o}]:[]}}case`Glob`:{let e=i?.path??``,t=i?.pattern??``,r=J(e,n),a=`Find`;return e&&(a+=` \`${e}\``),t&&(a+=` \`${t}\``),{title:a,kind:`search`,content:[],locations:r?[{path:r}]:[]}}case`Grep`:{let e=i?.pattern??``,t=i?.path??``,n=`grep`;return i?.[`-i`]&&(n+=` -i`),i?.[`-n`]&&(n+=` -n`),i?.[`-A`]!==void 0&&(n+=` -A ${i[`-A`]}`),i?.[`-B`]!==void 0&&(n+=` -B ${i[`-B`]}`),i?.[`-C`]!==void 0&&(n+=` -C ${i[`-C`]}`),i?.output_mode===`files_with_matches`?n+=` -l`:i?.output_mode===`count`&&(n+=` -c`),i?.head_limit!==void 0&&(n+=` | head -${i.head_limit}`),i?.glob&&(n+=` --include="${i.glob}"`),i?.type&&(n+=` --type=${i.type}`),i?.multiline&&(n+=` -P`),e&&(n+=` "${e}"`),t&&(n+=` ${t}`),{title:n,kind:`search`,content:[]}}case`TodoWrite`:{let e=i?.todos;return{title:Array.isArray(e)?`Update TODOs: ${e.map(e=>e.content).join(`, `)}`:`Update TODOs`,kind:`think`,content:[]}}case`ExitPlanMode`:{let e=i?.plan;return{title:`Ready to code?`,kind:`switch_mode`,content:e?[{type:`content`,content:{type:`text`,text:e}}]:[]}}default:return{title:r||`Unknown Tool`,kind:`other`,content:[]}}}function Oi(e,t){return Array.isArray(e)&&e.length>0?{content:e.map(e=>({type:`content`,content:ki(e,t)}))}:typeof e==`string`&&e.length>0?{content:[{type:`content`,content:{type:`text`,text:t?`\`\`\`\n${e}\n\`\`\``:e}}]}:{}}function ki(e,t){let n=e=>({type:`text`,text:t?`\`\`\`\n${e}\n\`\`\``:e});switch(e.type){case`text`:{let n=e.text;return{type:`text`,text:t?`\`\`\`\n${n}\n\`\`\``:n}}case`image`:{let t=e.source;return t?.type===`base64`?{type:`image`,data:t.data,mimeType:t.media_type}:n(t?.type===`url`?`[image: ${t.url}]`:`[image: file reference]`)}case`resource_link`:{let t=e.uri;return{type:`resource_link`,uri:t,name:e.name??t,mimeType:e.mimeType}}case`resource`:{let t=e.resource;return{type:`resource`,resource:{uri:t?.uri??``,mimeType:t?.mimeType,...typeof t?.text==`string`?{text:t.text}:{},...typeof t?.blob==`string`?{blob:t.blob}:{}}}}case`tool_reference`:return n(`Tool: ${e.tool_name}`);case`tool_search_tool_search_result`:{let t=e.tool_references;return n(`Tools found: ${t?.map(e=>e.tool_name).join(`, `)||`none`}`)}case`tool_search_tool_result_error`:return n(`Error: ${e.error_code}${e.error_message?` - ${e.error_message}`:``}`);case`web_fetch_result`:return n(`Fetched: ${e.url}`);case`web_fetch_tool_result_error`:return n(`Error: ${e.error_code}`);case`code_execution_result`:case`bash_code_execution_result`:return n(`Output: ${e.stdout||e.stderr||``}`);case`code_execution_tool_result_error`:case`bash_code_execution_tool_result_error`:return n(`Error: ${e.error_code}`);case`text_editor_code_execution_view_result`:return n(e.content);case`text_editor_code_execution_create_result`:return n(e.is_file_update?`File updated`:`File created`);case`text_editor_code_execution_str_replace_result`:{let t=e.lines;return n(t?.join(`
6
6
  `)||``)}case`text_editor_code_execution_tool_result_error`:return n(`Error: ${e.error_code}${e.error_message?` - ${e.error_message}`:``}`);default:try{return{type:`text`,text:JSON.stringify(e)}}catch{return{type:`text`,text:`[content]`}}}}function Ai(e,t,n=!1){if(!t)return{};let r=e.is_error===!0,i=e.content;if(r&&i)return Oi(i,!0);switch(t.name){case`Read`:return typeof i==`string`&&i.length>0?{content:[{type:`content`,content:{type:`text`,text:Di(i)}}]}:Array.isArray(i)&&i.length>0?{content:i.map(e=>({type:`content`,content:e.type===`text`?{type:`text`,text:Di(e.text)}:ki(e,!1)}))}:{};case`Bash`:{let e=``;if(i&&typeof i==`object`&&!Array.isArray(i)&&i.type===`bash_code_execution_result`){let t=i;e=[t.stdout,t.stderr].filter(Boolean).join(`
7
7
  `)}else typeof i==`string`?e=i:Array.isArray(i)&&i.length>0&&(e=i.map(e=>e.type===`text`?e.text:``).join(`
8
8
  `));return e.trim()?{content:[{type:`content`,content:{type:`text`,text:`\`\`\`console\n${e.trimEnd()}\n\`\`\``}}]}:{}}case`Edit`:case`Write`:return{};case`ExitPlanMode`:return{title:`Exited Plan Mode`};default:return Oi(i??``,r)}}function ji(e){return e===`in_progress`?`in_progress`:e===`completed`?`completed`:`pending`}function X(e,t,n,r,i,a,o){let s=[];for(let i of e){let e=i.type,a=null;switch(e){case`text`:case`text_delta`:{let e=i.text??``;a={sessionUpdate:t===`assistant`?`agent_message_chunk`:`user_message_chunk`,...o?.messageId?{messageId:o.messageId}:{},content:{type:`text`,text:e}};break}case`thinking`:case`thinking_delta`:{let e=i.thinking??``;a={sessionUpdate:`agent_thought_chunk`,...o?.messageId?{messageId:o.messageId}:{},content:{type:`text`,text:e}};break}case`image`:{let e=i.source;e?.type===`base64`&&(a={sessionUpdate:t===`assistant`?`agent_message_chunk`:`user_message_chunk`,...o?.messageId?{messageId:o.messageId}:{},content:{type:`image`,data:e.data,mimeType:e.media_type}});break}case`tool_use`:case`server_tool_use`:case`mcp_tool_use`:{let t=i.id??``,n=i.name??`unknown`,s=i.input,c=t in r;if(r[t]={type:e,id:t,name:n,input:s},n===`TodoWrite`){let e=s?.todos;Array.isArray(e)&&(a={sessionUpdate:`plan`,entries:e.map(e=>({content:e.content,status:ji(e.status),priority:`medium`}))})}else{let e=s?{...s}:{};a=c?{_meta:{claudeCode:{toolName:n}},toolCallId:t,sessionUpdate:`tool_call_update`,status:`in_progress`,rawInput:e,...Y({name:n,id:t,input:s??{}},!1,o?.cwd)}:{_meta:{claudeCode:{toolName:n}},toolCallId:t,sessionUpdate:`tool_call`,rawInput:e,status:`pending`,...Y({name:n,id:t,input:s??{}},!1,o?.cwd)}}break}case`tool_result`:case`mcp_tool_result`:{let e=i.tool_use_id??``,t=r[e];if(!t)break;if(t.name!==`TodoWrite`){let n=Ai(i,{name:t.name,id:t.id},!1);a={_meta:{claudeCode:{toolName:t.name}},toolCallId:e,sessionUpdate:`tool_call_update`,status:i.is_error===!0?`failed`:`completed`,rawOutput:i.content,...n}}break}case`redacted_thinking`:case`input_json_delta`:case`citations_delta`:case`signature_delta`:case`container_upload`:case`compaction`:case`compaction_delta`:break}if(a){if(o?.parentToolUseId){let e=a._meta;a._meta={...e,claudeCode:{...e?.claudeCode??{},parentToolUseId:o.parentToolUseId}}}s.push({sessionId:n,update:a})}}return s}function Mi(e,t,n,r,i){let a=e.message;if(!a)return[];let o=a.content;if(!o)return[];if(typeof o==`string`)return[{sessionId:t,update:{sessionUpdate:`agent_message_chunk`,...i?.messageId?{messageId:i.messageId}:{},content:{type:`text`,text:o}}}];let s=i?.streamingActive?o.filter(e=>e.type!==`text`&&e.type!==`thinking`):o;return s.length===0?[]:X(s,`assistant`,t,n,r,void 0,i)}function Ni(e,t,n,r,i){let a=e.event;if(!a)return[];switch(a.type){case`content_block_start`:{let o=a.content_block;return o?X([o],`assistant`,t,n,r,void 0,{clientCapabilities:i?.clientCapabilities,parentToolUseId:e.parent_tool_use_id,cwd:i?.cwd,messageId:i?.messageId}):[]}case`content_block_delta`:{let o=a.delta;return o?X([o],`assistant`,t,n,r,void 0,{clientCapabilities:i?.clientCapabilities,parentToolUseId:e.parent_tool_use_id,cwd:i?.cwd,messageId:i?.messageId}):[]}case`message_start`:case`message_delta`:case`message_stop`:case`content_block_stop`:return[];default:return[]}}function Pi(e,t){let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n}function Fi(e,t){let n=null,r=0;for(let i of Object.keys(e)){let e=Pi(i,t);e>r&&(r=e,n=i)}return n?e[n]??null:null}var Ii=console;function Li(e,t){if(t.aborted)return Promise.resolve({done:!0,value:void 0});let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});return Promise.race([e.next(),r]).finally(()=>{n&&t.removeEventListener(`abort`,n)})}async function Ri(e,t,n,r,i,a,o,s){let c=`end_turn`,l={inputTokens:0,outputTokens:0,cachedReadTokens:0,cachedWriteTokens:0},u=null,d=null,f=2e5,p=!1,m=null;try{for(;!r.aborted;){let s=await Li(t,r);if(s.done||r.aborted)break;let h=s.value;if(h==null)continue;let g=h;switch(g.type){case`system`:g.subtype===`compact_boundary`&&(u=0,await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:`
9
9
 
10
- Compacting completed.`}}}));break;case`result`:{let t=g.usage;t&&(l.inputTokens+=t.input_tokens??0,l.outputTokens+=t.output_tokens??0,l.cachedReadTokens+=t.cache_read_input_tokens??0,l.cachedWriteTokens+=t.cache_creation_input_tokens??0);let i=g.modelUsage;if(i&&d){let e=Fi(i,d);e?.contextWindow&&(f=e.contextWindow)}u!==null&&await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`usage_update`,used:u,size:f}});let a=g.subtype,o=g.is_error;if(r.aborted){c=`cancelled`;break}switch(a){case`success`:{let e=g.stop_reason;c=e===`max_tokens`?`max_tokens`:e===`refusal`?`refusal`:`end_turn`,o&&(c=`end_turn`);break}case`error_during_execution`:c=g.stop_reason===`max_tokens`?`max_tokens`:`end_turn`;break;case`error_max_budget_usd`:case`error_max_turns`:case`error_max_structured_output_retries`:c=`max_turn_requests`;break}break}case`stream_event`:{let t=g.parent_tool_use_id;t===null&&m===null&&(m=N());let r=Ni(g,e,i,n,{clientCapabilities:a,cwd:o,messageId:t===null?m??void 0:void 0});for(let e of r)await n.sessionUpdate(e);p=!0;break}case`assistant`:{let t=g.message,r=g.parent_tool_use_id;if(t?.usage&&r===null){let e=t.usage;u=(typeof e.input_tokens==`number`?e.input_tokens:0)+(typeof e.output_tokens==`number`?e.output_tokens:0)+(typeof e.cache_read_input_tokens==`number`?e.cache_read_input_tokens:0)+(typeof e.cache_creation_input_tokens==`number`?e.cache_creation_input_tokens:0)}r===null&&t?.model&&t.model!==`<synthetic>`&&(d=t.model);let s;r===null&&(m===null&&(m=N()),s=m);let c=Mi(g,e,i,n,{clientCapabilities:a,cwd:o,parentToolUseId:r,streamingActive:p,messageId:s});for(let e of c)await n.sessionUpdate(e);r===null&&(m=null);break}case`user`:break;case`progress`:{let t=g.data;if(!t)break;let r=t.type;if(r===`agent_progress`||r===`skill_progress`){let r=t.message;if(r){let t=r.content;if(t)for(let r of t)r.type===`text`&&await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:r.text}}})}}break}case`tool_use_summary`:break;case`attachment`:break;case`compact_boundary`:u=0,await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:`
10
+ Compacting completed.`}}}));break;case`result`:{let t=g.usage;t&&(l.inputTokens+=t.input_tokens??0,l.outputTokens+=t.output_tokens??0,l.cachedReadTokens+=t.cache_read_input_tokens??0,l.cachedWriteTokens+=t.cache_creation_input_tokens??0);let i=g.modelUsage;if(i&&d){let e=Fi(i,d);e?.contextWindow&&(f=e.contextWindow)}u!==null&&await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`usage_update`,used:u,size:f}});let a=g.subtype,o=g.is_error;if(r.aborted){c=`cancelled`;break}switch(a){case`success`:{let e=g.stop_reason;c=e===`max_tokens`?`max_tokens`:e===`refusal`?`refusal`:`end_turn`,o&&(c=`end_turn`);break}case`error_during_execution`:c=g.stop_reason===`max_tokens`?`max_tokens`:`end_turn`;break;case`error_max_budget_usd`:case`error_max_turns`:case`error_max_structured_output_retries`:c=`max_turn_requests`;break}break}case`stream_event`:{let t=g.parent_tool_use_id;t===null&&m===null&&(m=j());let r=Ni(g,e,i,n,{clientCapabilities:a,cwd:o,messageId:t===null?m??void 0:void 0});for(let e of r)await n.sessionUpdate(e);p=!0;break}case`assistant`:{let t=g.message,r=g.parent_tool_use_id;if(t?.usage&&r===null){let e=t.usage;u=(typeof e.input_tokens==`number`?e.input_tokens:0)+(typeof e.output_tokens==`number`?e.output_tokens:0)+(typeof e.cache_read_input_tokens==`number`?e.cache_read_input_tokens:0)+(typeof e.cache_creation_input_tokens==`number`?e.cache_creation_input_tokens:0)}r===null&&t?.model&&t.model!==`<synthetic>`&&(d=t.model);let s;r===null&&(m===null&&(m=j()),s=m);let c=Mi(g,e,i,n,{clientCapabilities:a,cwd:o,parentToolUseId:r,streamingActive:p,messageId:s});for(let e of c)await n.sessionUpdate(e);r===null&&(m=null);break}case`user`:break;case`progress`:{let t=g.data;if(!t)break;let r=t.type;if(r===`agent_progress`||r===`skill_progress`){let r=t.message;if(r){let t=r.content;if(t)for(let r of t)r.type===`text`&&await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:r.text}}})}}break}case`tool_use_summary`:break;case`attachment`:break;case`compact_boundary`:u=0,await n.sessionUpdate({sessionId:e,update:{sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:`
11
11
 
12
- Compacting completed.`}}});break;default:Ii.debug(`Ignoring unknown SDK message type`);break}}if(r.aborted||s?.())return{stopReason:`cancelled`,usage:l}}catch(e){if(r.aborted)return{stopReason:`cancelled`,usage:l};throw e}return{stopReason:c,usage:l}}async function zi(e,t,n,r,i,a){for(let o of t){let t=o;if(t.type!==`user`&&t.type!==`assistant`){Ii.debug(`Ignoring unknown SDK message type`);continue}if(t.isMeta===!0)continue;let s=t.message?.content;if(!s)continue;let c=t.type===`assistant`?`assistant`:`user`;if(typeof s==`string`){if(!s.trim())continue;let t=N();await n.sessionUpdate({sessionId:e,update:{sessionUpdate:c===`assistant`?`agent_message_chunk`:`user_message_chunk`,...t?{messageId:t}:{},content:{type:`text`,text:s}}});continue}if(Array.isArray(s)){let t=X(s,c,e,r,n,void 0,{clientCapabilities:i,cwd:a,messageId:N()});for(let e of t)await n.sessionUpdate(e)}}}function Bi(e,t,n,i,a,o,s,c){return async(n,l,u,d,f,p)=>{let m=Hi(i);if(n.name===`ExitPlanMode`)return Vi(e,t,f,l,m,a,o,s,c);if(p!==void 0)return p;try{let e=await r(n,l,u,d,f);if(e.behavior===`allow`||e.behavior===`deny`)return e}catch(e){return console.error(`[ACP Permissions] Pipeline error:`,e),{behavior:`deny`,message:`Permission pipeline failed`,decisionReason:{type:`other`,reason:`Permission pipeline failed`},toolUseID:f}}let h=Y({name:n.name,id:f,input:l},m,a),g={toolCallId:f,title:h.title,kind:h.kind,status:`pending`,rawInput:l},_=[{kind:`allow_always`,name:`Always Allow`,optionId:`allow_always`},{kind:`allow_once`,name:`Allow`,optionId:`allow`},{kind:`reject_once`,name:`Reject`,optionId:`reject`},{kind:`reject_always`,name:`Always Reject`,optionId:`reject_always`}];try{let n=await e.requestPermission({sessionId:t,toolCall:g,options:_});if(n.outcome.outcome===`cancelled`)return c?.(),{behavior:`deny`,message:`Permission request cancelled by client`,decisionReason:{type:`mode`,mode:`default`},toolUseID:f};if(n.outcome.outcome===`selected`&&`optionId`in n.outcome&&n.outcome.optionId!==void 0){let e=n.outcome.optionId;if(e===`allow`||e===`allow_always`)return{behavior:`allow`,updatedInput:l}}return{behavior:`deny`,message:`Permission denied by client`,decisionReason:{type:`mode`,mode:`default`}}}catch(e){return console.error(`[ACP Permissions] Client request error:`,e),{behavior:`deny`,message:`Permission request failed`,decisionReason:{type:`mode`,mode:`default`}}}}}async function Vi(e,t,n,r,i,a,o,s,c){let l=[{kind:`allow_always`,name:`Yes, and use "auto" mode`,optionId:`auto`},{kind:`allow_always`,name:`Yes, and auto-accept edits`,optionId:`acceptEdits`},{kind:`allow_once`,name:`Yes, and manually approve edits`,optionId:`default`},{kind:`reject_once`,name:`No, keep planning`,optionId:`plan`}];s?.()===!0&&l.unshift({kind:`allow_always`,name:`Yes, and bypass permissions`,optionId:`bypassPermissions`});let u=Y({name:`ExitPlanMode`,id:n,input:r},i,a),d={toolCallId:n,title:u.title,kind:u.kind,status:`pending`,rawInput:r},f=await e.requestPermission({sessionId:t,toolCall:d,options:l});if(f.outcome.outcome===`cancelled`)return c?.(),{behavior:`deny`,message:`Tool use aborted`,decisionReason:{type:`mode`,mode:`default`}};if(f.outcome.outcome===`selected`&&`optionId`in f.outcome&&f.outcome.optionId!==void 0){let n=f.outcome.optionId;if(l.some(e=>e.optionId===n)&&(n==="default"||n===`acceptEdits`||n===`auto`||n===`bypassPermissions`))return o?.(n),await e.sessionUpdate({sessionId:t,update:{sessionUpdate:`current_mode_update`,currentModeId:n}}),{behavior:`allow`,updatedInput:r}}return{behavior:`deny`,message:`User rejected request to exit plan mode.`,decisionReason:{type:`mode`,mode:`plan`}}}function Hi(e){if(!e)return!1;if(e.terminal===!0)return!0;let t=e._meta;return!t||typeof t!=`object`?!1:t.terminal_output===!0}me(),Se(),h(),de(),e(),y(),p();var Z=class{constructor(e){t(this,`conn`,void 0),t(this,`sessions`,new Map),t(this,`clientCapabilities`,void 0),this.conn=e}async initialize(e){return this.clientCapabilities=e.clientCapabilities,{protocolVersion:1,authMethods:[],agentInfo:{name:`workmate`,title:`Work Mate`,version:typeof globalThis.MACRO==`object`&&globalThis.MACRO!==null?String(globalThis.MACRO.VERSION??`0.0.0`):`0.0.0`},agentCapabilities:{_meta:{claudeCode:{promptQueueing:!0,forkSession:!0}},promptCapabilities:{image:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{list:{},resume:{},close:{},delete:{}}}}}async authenticate(e){return{}}async newSession(e){let t=await this.createSession(e);return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async unstable_resumeSession(e){let t=await this.getOrCreateSession({...e,replay:!1});return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async loadSession(e){let t=await this.getOrCreateSession(e);return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async listSessions(e){if(e.cursor!==void 0&&e.cursor!==null)throw Error(`Pagination cursor not supported: listSessions returns all results in a single page.`);let t=e.cwd||ne(),n=await pe(t),r=await m({dir:t}),i=[];for(let e of r){if(!e.cwd||await pe(e.cwd)!==n)continue;let t=Ti(e.summary??``);i.push({sessionId:e.sessionId,cwd:e.cwd,...t?{title:t}:{},updatedAt:new Date(e.lastModified).toISOString()})}return{sessions:i}}async unstable_forkSession(e){let{initialMessages:t}=await Ui(e.sessionId),n=await this.createSession({cwd:e.cwd,mcpServers:e.mcpServers??[],_meta:e._meta},{initialMessages:t});return this.scheduleAvailableCommandsUpdate(n.sessionId),n}async unstable_closeSession(e){if(!this.sessions.get(e.sessionId))throw Error(`Session not found`);return await this.teardownSession(e.sessionId),{}}async unstable_deleteSession(e){let t=await fe(e.sessionId);if(t)try{await Ee(t.filePath)}catch(e){if(e.code!==`ENOENT`)throw e}return this.sessions.has(e.sessionId)&&await this.teardownSession(e.sessionId),{}}async extMethod(e,t){if(e===`session/delete`){let e=t.sessionId;if(typeof e!=`string`||e.length===0)throw Error(`session/delete requires a non-empty sessionId`);return this.unstable_deleteSession({sessionId:e})}throw q.methodNotFound(e)}async cancel(e){let t=this.sessions.get(e.sessionId);if(t){t.cancelled=!0,t.cancelGeneration+=1;for(let[,e]of t.pendingMessages)e.resolve(!0);t.pendingMessages.clear(),t.pendingQueue=[],t.pendingQueueHead=0,t.queryEngine.interrupt()}}async setSessionMode(e){if(!this.sessions.get(e.sessionId))throw Error(`Session not found`);return this.applySessionMode(e.sessionId,e.modeId),await this.conn.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:`current_mode_update`,currentModeId:e.modeId}}),await this.updateConfigOption(e.sessionId,`mode`,e.modeId),{}}async unstable_setSessionModel(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session not found`);return t.queryEngine.setModel(e.modelId),await this.updateConfigOption(e.sessionId,`model`,e.modelId),{}}async sendAvailableCommandsUpdate(e){let t=this.sessions.get(e);if(!t)return;let n=t.commands.filter(e=>e.type===`prompt`&&!e.isHidden&&e.userInvocable!==!1).map(e=>({name:e.name,description:e.description,input:e.argumentHint?{hint:e.argumentHint}:void 0}));await this.conn.sessionUpdate({sessionId:e,update:{sessionUpdate:`available_commands_update`,availableCommands:n}})}scheduleAvailableCommandsUpdate(e){setTimeout(()=>{this.sendAvailableCommandsUpdate(e).catch(e=>{console.error(`[ACP] Failed to send available commands update:`,e)})},0)}};async function Ui(e){let t;try{let n=await f(e);n&&n.messages.length>0&&(t=i(n.messages))}catch(e){console.error(`[ACP] fork source load failed:`,e)}return{initialMessages:t}}var Wi=[`auto`,`default`,`acceptEdits`,`bypassPermissions`,`dontAsk`,`plan`];function Gi(e){return Wi.includes(e)}function Ki(e,t,n){if(t){let t=qi(e,`_meta.permissionMode`);if(t===`bypassPermissions`&&!Xi())throw Error(`Mode not available: bypassPermissions cannot run as root (start the agent as a non-root user, or set IS_SANDBOX=1).`);return t}return Ji(n)??`default`}function qi(e,t){if(e==null)throw Error(`Invalid ${t}: expected a string.`);return Si(e,t)}function Ji(e){if(e!=null)try{return Si(e,`permissions.defaultMode`)}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[ACP] Invalid permissions.defaultMode, using default:`,t);return}}function Yi(e,t){return!!e&&Object.hasOwn(e,t)}function Xi(){return Zi()}function Zi(){return process.env.IS_SANDBOX?!0:typeof process.geteuid==`function`?process.geteuid()!==0:typeof process.getuid!=`function`||process.getuid()!==0}function Qi(e,t){return[{id:`mode`,name:`Mode`,description:`Session permission mode`,category:`mode`,type:`select`,currentValue:e.currentModeId,options:e.availableModes.map(e=>({value:e.id,name:e.name,description:e.description}))},{id:`model`,name:`Model`,description:`AI model to use`,category:`model`,type:`select`,currentValue:t.currentModelId,options:t.availableModels.map(e=>({value:e.modelId,name:e.name,description:e.description??void 0}))}]}function $i(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;if(Array.isArray(e.options))for(let n of e.options)n&&typeof n==`object`&&typeof n.value==`string`&&t.push(n.value);else typeof n.value==`string`&&t.push(n.value)}return t}function Q(e){return e.conn}function $(e){return e.clientCapabilities}function ea(e,t,n,r){n===`mode`?t.modes={...t.modes,currentModeId:r}:n===`model`&&(t.models={...t.models,currentModelId:r})}j();function ta(){return se().permissions?.defaultMode}async function na(e,t={}){ue();let n=t.sessionId??N(),r=e.cwd;M(n,ae()),oe(r);let i=process.cwd(),o=!1;try{process.chdir(r),o=!0}catch{}re(),ve();try{let i=ge(),o=a(i),c=e._meta,l=Yi(c,`permissionMode`),f=Ki(l?c?.permissionMode:void 0,l,ta()),p=$(this),m=this.conn,h=Bi(m,n,()=>this.sessions.get(n)?.modes.currentModeId??`default`,p,r,e=>{this.applySessionMode(n,e)},()=>this.sessions.get(n)?.appState.toolPermissionContext.isBypassPermissionsModeAvailable??!1),_=Xi(),v={...d(),toolPermissionContext:{...i,mode:f,isBypassPermissionsModeAvailable:_}},[y,b]=await Promise.all([s(r),g(r)]);v.agentDefinitions=b;let x=new be({cwd:r,tools:o,commands:y,mcpClients:[],agents:b.activeAgents,canUseTool:h,getAppState:()=>v,setAppState:e=>{let t=e(v);Object.assign(v,t)},readFileCache:new u(500,50*1024*1024),includePartialMessages:!0,replayUserMessages:!0,initialMessages:t.initialMessages}),S={currentModeId:f,availableModes:[{id:`default`,name:`Default`,description:`Standard behavior, prompts for dangerous operations`},{id:`acceptEdits`,name:`Accept Edits`,description:`Auto-accept file edit operations`},{id:`plan`,name:`Plan Mode`,description:`Planning mode, no actual tool execution`},{id:`auto`,name:`Auto`,description:`Use a model classifier to approve/deny permission prompts.`},..._?[{id:`bypassPermissions`,name:`Bypass Permissions`,description:`Skip all permission checks`}]:[],{id:`dontAsk`,name:`Don't Ask`,description:`Don't prompt for permissions, deny if not pre-approved`}]},C=xe(),w=he(),T={availableModels:C.map(e=>({modelId:String(e.value??``),name:e.label??String(e.value??``),description:e.description??void 0})),currentModelId:w};x.setModel(w);let E=Qi(S,T),D={queryEngine:x,cancelled:!1,cancelGeneration:0,cwd:r,modes:S,models:T,configOptions:E,promptRunning:!1,pendingMessages:new Map,pendingQueue:[],pendingQueueHead:0,toolUseCache:{},clientCapabilities:p,appState:v,commands:y,sessionFingerprint:Ci({cwd:r,mcpServers:e.mcpServers})};return this.sessions.set(n,D),{sessionId:n,modes:S,models:T,configOptions:E}}finally{o&&process.chdir(i)}}Object.assign(Z.prototype,{createSession:na}),y(),p(),j(),de();async function ra(e){let t=e.replay!==!1,n=this.sessions.get(e.sessionId);if(n){if(Ci({cwd:e.cwd,mcpServers:e.mcpServers})===n.sessionFingerprint){let r=await fe(e.sessionId,e.cwd);return M(e.sessionId,r?Ce(r.filePath):null),oe(e.cwd),t&&await this.replaySessionHistory(e),{sessionId:e.sessionId,modes:n.modes,models:n.models,configOptions:n.configOptions}}await this.teardownSession(e.sessionId)}let r=await fe(e.sessionId,e.cwd),a=r?Ce(r.filePath):null;M(e.sessionId,a),oe(e.cwd);let o;if(r)try{let t=await f(e.sessionId);t&&t.messages.length>0&&(o=i(t.messages))}catch(e){console.error(`[ACP] Failed to load session history:`,e)}let s=await this.createSession({cwd:e.cwd,mcpServers:e.mcpServers??[],_meta:e._meta},{sessionId:e.sessionId,initialMessages:o});if(t&&o&&o.length>0){let t=this.sessions.get(e.sessionId);t&&await zi(e.sessionId,o,Q(this),t.toolUseCache,$(this),t.cwd)}return{sessionId:s.sessionId,modes:s.modes,models:s.models,configOptions:s.configOptions}}async function ia(e){this.sessions.get(e)&&(await this.cancel({sessionId:e}),this.sessions.delete(e))}async function aa(e){try{let t=await f(e.sessionId);if(!t||t.messages.length===0)return;let n=i(t.messages);if(n.length===0)return;let r=this.sessions.get(e.sessionId);if(!r)return;await zi(e.sessionId,n,Q(this),r.toolUseCache,$(this),r.cwd)}catch(e){console.error(`[ACP] Failed to replay session history:`,e)}}function oa(e,t){if(!Gi(t))throw Error(`Invalid mode: ${t}`);let n=this.sessions.get(e);if(n){if(t===`bypassPermissions`&&!n.appState.toolPermissionContext.isBypassPermissionsModeAvailable||!n.modes.availableModes.some(e=>e.id===t))throw Error(`Mode not available: ${t}`);n.modes={...n.modes,currentModeId:t},n.appState.toolPermissionContext={...n.appState.toolPermissionContext,mode:t}}}async function sa(e,t,n){let r=this.sessions.get(e);r&&(ea(this,r,t,n),r.configOptions=r.configOptions.map(e=>e.id===t&&typeof e.currentValue==`string`?{...e,currentValue:n}:e),await Q(this).sessionUpdate({sessionId:e,update:{sessionUpdate:`config_option_update`,configOptions:r.configOptions}}))}Object.assign(Z.prototype,{getOrCreateSession:ra,teardownSession:ia,replaySessionHistory:aa,applySessionMode:oa,updateConfigOption:sa});function ca(e){if(!e||e.length===0)return``;let t=[];for(let n of e){let e=n;if(e.type===`text`)t.push(String(e.text??``));else if(e.type===`resource_link`){let n=typeof e.name==`string`?e.name:void 0,r=typeof e.uri==`string`?e.uri:void 0;t.push(la(n,r))}else if(e.type===`resource`){let n=e.resource;if(n&&typeof n.text==`string`)t.push(n.text);else if(n&&typeof n.blob==`string`){let e=typeof n.mimeType==`string`?n.mimeType:`application/octet-stream`,r=typeof n.uri==`string`?n.uri:`(unknown uri)`;t.push(`Embedded resource: ${r} (${e}, base64 blob, ${n.blob.length} chars)`)}}}return t.filter(e=>e.length>0).join(`
13
- `)}function la(e,t){let n=[];return e&&e.length>0&&n.push(`name=${e}`),t&&t.length>0&&n.push(`uri=${t}`),n.length>0?`Resource link: ${n.join(`, `)}`:`Resource link`}function ua(e){for(;e.pendingQueueHead<e.pendingQueue.length;){let t=e.pendingQueue[e.pendingQueueHead++];if(!t)continue;let n=e.pendingMessages.get(t);if(n)return e.pendingMessages.delete(t),da(e),n}da(e)}function da(e){if(e.pendingQueueHead!==0){if(e.pendingQueueHead>=e.pendingQueue.length){e.pendingQueue=[],e.pendingQueueHead=0;return}e.pendingQueueHead>1024&&e.pendingQueueHead*2>e.pendingQueue.length&&(e.pendingQueue=e.pendingQueue.slice(e.pendingQueueHead),e.pendingQueueHead=0)}}j();async function fa(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session ${e.sessionId} not found`);let n=e.messageId??void 0,r=ca(e.prompt);if(!r.trim())throw Error(`Prompt content is empty`);let i=t.cancelGeneration;if(t.promptRunning){let e=N();if(await new Promise(n=>{t.pendingQueue.push(e),t.pendingMessages.set(e,{resolve:n})}))return{stopReason:`cancelled`}}if(t.cancelGeneration!==i)return{stopReason:`cancelled`};t.cancelled=!1,t.promptRunning=!0;try{t.queryEngine.resetAbortController(),M(e.sessionId,ae());let i=t.queryEngine.submitMessage(r),{stopReason:a,usage:o}=await Ri(e.sessionId,i,Q(this),t.queryEngine.getAbortSignal(),t.toolUseCache,$(this),t.cwd,()=>t.cancelled);if(t.cancelled)return{stopReason:`cancelled`};if(await ma(this,e.sessionId,r),o){let e={inputTokens:o.inputTokens,outputTokens:o.outputTokens,cachedReadTokens:o.cachedReadTokens,cachedWriteTokens:o.cachedWriteTokens,thoughtTokens:0,totalTokens:o.inputTokens+o.outputTokens+o.cachedReadTokens+o.cachedWriteTokens+0};return{stopReason:a,usage:e,...n?{userMessageId:n}:{},_meta:{claudeCode:{usage:e}}}}return{stopReason:a,...n?{userMessageId:n}:{}}}catch(n){let r=n instanceof Error&&(n.name===`AbortError`||/abort|cancelled|interrupt/i.test(n.message));if(t.cancelled||r)return{stopReason:`cancelled`};throw n instanceof Error&&(n.message.includes(`terminated`)||n.message.includes(`process exited`))?(await this.teardownSession(e.sessionId),Error(`The Work Mate Agent process exited unexpectedly. Please start a new session.`)):n}finally{let e=ua(t);e?(t.promptRunning=!0,e.resolve(!1)):t.promptRunning=!1}}async function pa(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session not found`);if(typeof e.value!=`string`)throw Error(`Invalid value for config option ${e.configId}: ${String(e.value)}`);let n=t.configOptions.find(t=>t.id===e.configId);if(!n)throw Error(`Unknown config option: ${e.configId}`);if(n.type===`select`){let t=$i(n.options);if(!t.includes(e.value))throw Error(`Invalid value '${e.value}' for config option ${e.configId}; must be one of: ${t.join(`, `)}`)}let r=e.value;return e.configId===`mode`?(this.applySessionMode(e.sessionId,r),await Q(this).sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:`current_mode_update`,currentModeId:r}})):e.configId===`model`&&t.queryEngine.setModel(r),ea(this,t,e.configId,r),t.configOptions=t.configOptions.map(t=>t.id===e.configId&&typeof t.currentValue==`string`?{...t,currentValue:r}:t),{configOptions:t.configOptions}}async function ma(e,t,n){let r=e.sessions.get(t);if(!r)return;let i=r.toolUseCache;if(i.__sessionInfoTitleSent)return;i.__sessionInfoTitleSent=!0;let a=Ti(n).slice(0,100);try{await Q(e).sessionUpdate({sessionId:t,update:{sessionUpdate:`session_info_update`,...a?{title:a}:{},updatedAt:new Date().toISOString()}})}catch(e){console.error(`[ACP] Failed to send session_info_update:`,e)}}Object.assign(Z.prototype,{prompt:fa,setSessionConfigOption:pa}),le(),ye();function ha(e,t){let n=we.toWeb(e);return hi(Te.toWeb(t),n)}async function ga(){ue(),ve();let e=ha(process.stdin,process.stdout),t,n=new _i(e=>(t=new Z(e),t),e);console.log=console.error,console.info=console.error,console.warn=console.error,console.debug=console.error;async function r(){for(let[e]of t.sessions)try{await t.unstable_closeSession({sessionId:e})}catch{}process.exit(0)}n.closed.then(r).catch(r),process.on(`SIGTERM`,r),process.on(`SIGINT`,r),process.on(`unhandledRejection`,(e,t)=>{console.error(`Unhandled Rejection at:`,t,`reason:`,e)}),process.stdin.resume()}export{ga as runAcpAgent};
12
+ Compacting completed.`}}});break;default:Ii.debug(`Ignoring unknown SDK message type`);break}}if(r.aborted||s?.())return{stopReason:`cancelled`,usage:l}}catch(e){if(r.aborted)return{stopReason:`cancelled`,usage:l};throw e}return{stopReason:c,usage:l}}async function zi(e,t,n,r,i,a){for(let o of t){let t=o;if(t.type!==`user`&&t.type!==`assistant`){Ii.debug(`Ignoring unknown SDK message type`);continue}if(t.isMeta===!0)continue;let s=t.message?.content;if(!s)continue;let c=t.type===`assistant`?`assistant`:`user`;if(typeof s==`string`){if(!s.trim())continue;let t=j();await n.sessionUpdate({sessionId:e,update:{sessionUpdate:c===`assistant`?`agent_message_chunk`:`user_message_chunk`,...t?{messageId:t}:{},content:{type:`text`,text:s}}});continue}if(Array.isArray(s)){let t=X(s,c,e,r,n,void 0,{clientCapabilities:i,cwd:a,messageId:j()});for(let e of t)await n.sessionUpdate(e)}}}function Bi(e,t,n,i,a,o,s,c){return async(n,l,u,d,f,p)=>{let m=Hi(i);if(n.name===`ExitPlanMode`)return Vi(e,t,f,l,m,a,o,s,c);if(p!==void 0)return p;try{let e=await r(n,l,u,d,f);if(e.behavior===`allow`||e.behavior===`deny`)return e}catch(e){return console.error(`[ACP Permissions] Pipeline error:`,e),{behavior:`deny`,message:`Permission pipeline failed`,decisionReason:{type:`other`,reason:`Permission pipeline failed`},toolUseID:f}}let h=Y({name:n.name,id:f,input:l},m,a),g={toolCallId:f,title:h.title,kind:h.kind,status:`pending`,rawInput:l},_=[{kind:`allow_always`,name:`Always Allow`,optionId:`allow_always`},{kind:`allow_once`,name:`Allow`,optionId:`allow`},{kind:`reject_once`,name:`Reject`,optionId:`reject`},{kind:`reject_always`,name:`Always Reject`,optionId:`reject_always`}];try{let n=await e.requestPermission({sessionId:t,toolCall:g,options:_});if(n.outcome.outcome===`cancelled`)return c?.(),{behavior:`deny`,message:`Permission request cancelled by client`,decisionReason:{type:`mode`,mode:`default`},toolUseID:f};if(n.outcome.outcome===`selected`&&`optionId`in n.outcome&&n.outcome.optionId!==void 0){let e=n.outcome.optionId;if(e===`allow`||e===`allow_always`)return{behavior:`allow`,updatedInput:l}}return{behavior:`deny`,message:`Permission denied by client`,decisionReason:{type:`mode`,mode:`default`}}}catch(e){return console.error(`[ACP Permissions] Client request error:`,e),{behavior:`deny`,message:`Permission request failed`,decisionReason:{type:`mode`,mode:`default`}}}}}async function Vi(e,t,n,r,i,a,o,s,c){let l=[{kind:`allow_always`,name:`Yes, and use "auto" mode`,optionId:`auto`},{kind:`allow_always`,name:`Yes, and auto-accept edits`,optionId:`acceptEdits`},{kind:`allow_once`,name:`Yes, and manually approve edits`,optionId:`default`},{kind:`reject_once`,name:`No, keep planning`,optionId:`plan`}];s?.()===!0&&l.unshift({kind:`allow_always`,name:`Yes, and bypass permissions`,optionId:`bypassPermissions`});let u=Y({name:`ExitPlanMode`,id:n,input:r},i,a),d={toolCallId:n,title:u.title,kind:u.kind,status:`pending`,rawInput:r},f=await e.requestPermission({sessionId:t,toolCall:d,options:l});if(f.outcome.outcome===`cancelled`)return c?.(),{behavior:`deny`,message:`Tool use aborted`,decisionReason:{type:`mode`,mode:`default`}};if(f.outcome.outcome===`selected`&&`optionId`in f.outcome&&f.outcome.optionId!==void 0){let n=f.outcome.optionId;if(l.some(e=>e.optionId===n)&&(n==="default"||n===`acceptEdits`||n===`auto`||n===`bypassPermissions`))return o?.(n),await e.sessionUpdate({sessionId:t,update:{sessionUpdate:`current_mode_update`,currentModeId:n}}),{behavior:`allow`,updatedInput:r}}return{behavior:`deny`,message:`User rejected request to exit plan mode.`,decisionReason:{type:`mode`,mode:`plan`}}}function Hi(e){if(!e)return!1;if(e.terminal===!0)return!0;let t=e._meta;return!t||typeof t!=`object`?!1:t.terminal_output===!0}ge(),we(),p(),pe(),e(),n(),h();var Z=class{constructor(e){t(this,`conn`,void 0),t(this,`sessions`,new Map),t(this,`clientCapabilities`,void 0),this.conn=e}async initialize(e){return this.clientCapabilities=e.clientCapabilities,{protocolVersion:1,authMethods:[],agentInfo:{name:`workmate`,title:`Work Mate`,version:typeof globalThis.MACRO==`object`&&globalThis.MACRO!==null?String(globalThis.MACRO.VERSION??`0.0.0`):`0.0.0`},agentCapabilities:{_meta:{claudeCode:{promptQueueing:!0,forkSession:!0}},promptCapabilities:{image:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{list:{},resume:{},close:{},delete:{}}}}}async authenticate(e){return{}}async newSession(e){let t=await this.createSession(e);return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async unstable_resumeSession(e){let t=await this.getOrCreateSession({...e,replay:!1});return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async loadSession(e){let t=await this.getOrCreateSession(e);return this.scheduleAvailableCommandsUpdate(t.sessionId),t}async listSessions(e){if(e.cursor!==void 0&&e.cursor!==null)throw Error(`Pagination cursor not supported: listSessions returns all results in a single page.`);let t=e.cwd||ie(),n=await he(t),r=await o({dir:t}),i=[];for(let e of r){if(!e.cwd||await he(e.cwd)!==n)continue;let t=Ti(e.summary??``);i.push({sessionId:e.sessionId,cwd:e.cwd,...t?{title:t}:{},updatedAt:new Date(e.lastModified).toISOString()})}return{sessions:i}}async unstable_forkSession(e){let{initialMessages:t}=await Ui(e.sessionId),n=await this.createSession({cwd:e.cwd,mcpServers:e.mcpServers??[],_meta:e._meta},{initialMessages:t});return this.scheduleAvailableCommandsUpdate(n.sessionId),n}async unstable_closeSession(e){if(!this.sessions.get(e.sessionId))throw Error(`Session not found`);return await this.teardownSession(e.sessionId),{}}async unstable_deleteSession(e){let t=await me(e.sessionId);if(t)try{await Oe(t.filePath)}catch(e){if(e.code!==`ENOENT`)throw e}return this.sessions.has(e.sessionId)&&await this.teardownSession(e.sessionId),{}}async extMethod(e,t){if(e===`session/delete`){let e=t.sessionId;if(typeof e!=`string`||e.length===0)throw Error(`session/delete requires a non-empty sessionId`);return this.unstable_deleteSession({sessionId:e})}throw q.methodNotFound(e)}async cancel(e){let t=this.sessions.get(e.sessionId);if(t){t.cancelled=!0,t.cancelGeneration+=1;for(let[,e]of t.pendingMessages)e.resolve(!0);t.pendingMessages.clear(),t.pendingQueue=[],t.pendingQueueHead=0,t.queryEngine.interrupt()}}async setSessionMode(e){if(!this.sessions.get(e.sessionId))throw Error(`Session not found`);return this.applySessionMode(e.sessionId,e.modeId),await this.conn.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:`current_mode_update`,currentModeId:e.modeId}}),await this.updateConfigOption(e.sessionId,`mode`,e.modeId),{}}async unstable_setSessionModel(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session not found`);return t.queryEngine.setModel(e.modelId),await this.updateConfigOption(e.sessionId,`model`,e.modelId),{}}async sendAvailableCommandsUpdate(e){let t=this.sessions.get(e);if(!t)return;let n=t.commands.filter(e=>e.type===`prompt`&&!e.isHidden&&e.userInvocable!==!1).map(e=>({name:e.name,description:e.description,input:e.argumentHint?{hint:e.argumentHint}:void 0}));await this.conn.sessionUpdate({sessionId:e,update:{sessionUpdate:`available_commands_update`,availableCommands:n}})}scheduleAvailableCommandsUpdate(e){setTimeout(()=>{this.sendAvailableCommandsUpdate(e).catch(e=>{console.error(`[ACP] Failed to send available commands update:`,e)})},0)}};async function Ui(e){let t;try{let n=await m(e);n&&n.messages.length>0&&(t=u(n.messages))}catch(e){console.error(`[ACP] fork source load failed:`,e)}return{initialMessages:t}}var Wi=[`auto`,`default`,`acceptEdits`,`bypassPermissions`,`dontAsk`,`plan`];function Gi(e){return Wi.includes(e)}function Ki(e,t,n){if(t){let t=qi(e,`_meta.permissionMode`);if(t===`bypassPermissions`&&!Xi())throw Error(`Mode not available: bypassPermissions cannot run as root (start the agent as a non-root user, or set IS_SANDBOX=1).`);return t}return Ji(n)??`default`}function qi(e,t){if(e==null)throw Error(`Invalid ${t}: expected a string.`);return Si(e,t)}function Ji(e){if(e!=null)try{return Si(e,`permissions.defaultMode`)}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[ACP] Invalid permissions.defaultMode, using default:`,t);return}}function Yi(e,t){return!!e&&Object.hasOwn(e,t)}function Xi(){return Zi()}function Zi(){return process.env.IS_SANDBOX?!0:typeof process.geteuid==`function`?process.geteuid()!==0:typeof process.getuid!=`function`||process.getuid()!==0}function Qi(e,t){return[{id:`mode`,name:`Mode`,description:`Session permission mode`,category:`mode`,type:`select`,currentValue:e.currentModeId,options:e.availableModes.map(e=>({value:e.id,name:e.name,description:e.description}))},{id:`model`,name:`Model`,description:`AI model to use`,category:`model`,type:`select`,currentValue:t.currentModelId,options:t.availableModels.map(e=>({value:e.modelId,name:e.name,description:e.description??void 0}))}]}function $i(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;if(Array.isArray(e.options))for(let n of e.options)n&&typeof n==`object`&&typeof n.value==`string`&&t.push(n.value);else typeof n.value==`string`&&t.push(n.value)}return t}function Q(e){return e.conn}function $(e){return e.clientCapabilities}function ea(e,t,n,r){n===`mode`?t.modes={...t.modes,currentModeId:r}:n===`model`&&(t.models={...t.models,currentModelId:r})}k();function ta(){return le().permissions?.defaultMode}async function na(e,t={}){fe();let n=t.sessionId??j(),r=e.cwd;A(n,se()),ce(r);let i=process.cwd(),o=!1;try{process.chdir(r),o=!0}catch{}ae(),be();try{let i=ve(),o=te(i),s=e._meta,l=Yi(s,`permissionMode`),u=Ki(l?s?.permissionMode:void 0,l,ta()),d=$(this),f=this.conn,p=Bi(f,n,()=>this.sessions.get(n)?.modes.currentModeId??`default`,d,r,e=>{this.applySessionMode(n,e)},()=>this.sessions.get(n)?.appState.toolPermissionContext.isBypassPermissionsModeAvailable??!1),m=Xi(),h={...a(),toolPermissionContext:{...i,mode:u,isBypassPermissionsModeAvailable:m}},[_,v]=await Promise.all([c(r),g(r)]);h.agentDefinitions=v;let y=new Se({cwd:r,tools:o,commands:_,mcpClients:[],agents:v.activeAgents,canUseTool:p,getAppState:()=>h,setAppState:e=>{let t=e(h);Object.assign(h,t)},readFileCache:new ee(500,50*1024*1024),includePartialMessages:!0,replayUserMessages:!0,initialMessages:t.initialMessages}),b={currentModeId:u,availableModes:[{id:`default`,name:`Default`,description:`Standard behavior, prompts for dangerous operations`},{id:`acceptEdits`,name:`Accept Edits`,description:`Auto-accept file edit operations`},{id:`plan`,name:`Plan Mode`,description:`Planning mode, no actual tool execution`},{id:`auto`,name:`Auto`,description:`Use a model classifier to approve/deny permission prompts.`},...m?[{id:`bypassPermissions`,name:`Bypass Permissions`,description:`Skip all permission checks`}]:[],{id:`dontAsk`,name:`Don't Ask`,description:`Don't prompt for permissions, deny if not pre-approved`}]},x=Ce(),S=_e(),C={availableModels:x.map(e=>({modelId:String(e.value??``),name:e.label??String(e.value??``),description:e.description??void 0})),currentModelId:S};y.setModel(S);let w=Qi(b,C),T={queryEngine:y,cancelled:!1,cancelGeneration:0,cwd:r,modes:b,models:C,configOptions:w,promptRunning:!1,pendingMessages:new Map,pendingQueue:[],pendingQueueHead:0,toolUseCache:{},clientCapabilities:d,appState:h,commands:_,sessionFingerprint:Ci({cwd:r,mcpServers:e.mcpServers})};return this.sessions.set(n,T),{sessionId:n,modes:b,models:C,configOptions:w}}finally{o&&process.chdir(i)}}Object.assign(Z.prototype,{createSession:na}),n(),h(),k(),pe();async function ra(e){let t=e.replay!==!1,n=this.sessions.get(e.sessionId);if(n){if(Ci({cwd:e.cwd,mcpServers:e.mcpServers})===n.sessionFingerprint){let r=await me(e.sessionId,e.cwd);return A(e.sessionId,r?Te(r.filePath):null),ce(e.cwd),t&&await this.replaySessionHistory(e),{sessionId:e.sessionId,modes:n.modes,models:n.models,configOptions:n.configOptions}}await this.teardownSession(e.sessionId)}let r=await me(e.sessionId,e.cwd),i=r?Te(r.filePath):null;A(e.sessionId,i),ce(e.cwd);let a;if(r)try{let t=await m(e.sessionId);t&&t.messages.length>0&&(a=u(t.messages))}catch(e){console.error(`[ACP] Failed to load session history:`,e)}let o=await this.createSession({cwd:e.cwd,mcpServers:e.mcpServers??[],_meta:e._meta},{sessionId:e.sessionId,initialMessages:a});if(t&&a&&a.length>0){let t=this.sessions.get(e.sessionId);t&&await zi(e.sessionId,a,Q(this),t.toolUseCache,$(this),t.cwd)}return{sessionId:o.sessionId,modes:o.modes,models:o.models,configOptions:o.configOptions}}async function ia(e){this.sessions.get(e)&&(await this.cancel({sessionId:e}),this.sessions.delete(e))}async function aa(e){try{let t=await m(e.sessionId);if(!t||t.messages.length===0)return;let n=u(t.messages);if(n.length===0)return;let r=this.sessions.get(e.sessionId);if(!r)return;await zi(e.sessionId,n,Q(this),r.toolUseCache,$(this),r.cwd)}catch(e){console.error(`[ACP] Failed to replay session history:`,e)}}function oa(e,t){if(!Gi(t))throw Error(`Invalid mode: ${t}`);let n=this.sessions.get(e);if(n){if(t===`bypassPermissions`&&!n.appState.toolPermissionContext.isBypassPermissionsModeAvailable||!n.modes.availableModes.some(e=>e.id===t))throw Error(`Mode not available: ${t}`);n.modes={...n.modes,currentModeId:t},n.appState.toolPermissionContext={...n.appState.toolPermissionContext,mode:t}}}async function sa(e,t,n){let r=this.sessions.get(e);r&&(ea(this,r,t,n),r.configOptions=r.configOptions.map(e=>e.id===t&&typeof e.currentValue==`string`?{...e,currentValue:n}:e),await Q(this).sessionUpdate({sessionId:e,update:{sessionUpdate:`config_option_update`,configOptions:r.configOptions}}))}Object.assign(Z.prototype,{getOrCreateSession:ra,teardownSession:ia,replaySessionHistory:aa,applySessionMode:oa,updateConfigOption:sa});function ca(e){if(!e||e.length===0)return``;let t=[];for(let n of e){let e=n;if(e.type===`text`)t.push(String(e.text??``));else if(e.type===`resource_link`){let n=typeof e.name==`string`?e.name:void 0,r=typeof e.uri==`string`?e.uri:void 0;t.push(la(n,r))}else if(e.type===`resource`){let n=e.resource;if(n&&typeof n.text==`string`)t.push(n.text);else if(n&&typeof n.blob==`string`){let e=typeof n.mimeType==`string`?n.mimeType:`application/octet-stream`,r=typeof n.uri==`string`?n.uri:`(unknown uri)`;t.push(`Embedded resource: ${r} (${e}, base64 blob, ${n.blob.length} chars)`)}}}return t.filter(e=>e.length>0).join(`
13
+ `)}function la(e,t){let n=[];return e&&e.length>0&&n.push(`name=${e}`),t&&t.length>0&&n.push(`uri=${t}`),n.length>0?`Resource link: ${n.join(`, `)}`:`Resource link`}function ua(e){for(;e.pendingQueueHead<e.pendingQueue.length;){let t=e.pendingQueue[e.pendingQueueHead++];if(!t)continue;let n=e.pendingMessages.get(t);if(n)return e.pendingMessages.delete(t),da(e),n}da(e)}function da(e){if(e.pendingQueueHead!==0){if(e.pendingQueueHead>=e.pendingQueue.length){e.pendingQueue=[],e.pendingQueueHead=0;return}e.pendingQueueHead>1024&&e.pendingQueueHead*2>e.pendingQueue.length&&(e.pendingQueue=e.pendingQueue.slice(e.pendingQueueHead),e.pendingQueueHead=0)}}k();async function fa(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session ${e.sessionId} not found`);let n=e.messageId??void 0,r=ca(e.prompt);if(!r.trim())throw Error(`Prompt content is empty`);let i=t.cancelGeneration;if(t.promptRunning){let e=j();if(await new Promise(n=>{t.pendingQueue.push(e),t.pendingMessages.set(e,{resolve:n})}))return{stopReason:`cancelled`}}if(t.cancelGeneration!==i)return{stopReason:`cancelled`};t.cancelled=!1,t.promptRunning=!0;try{t.queryEngine.resetAbortController(),A(e.sessionId,se());let i=t.queryEngine.submitMessage(r),{stopReason:a,usage:o}=await Ri(e.sessionId,i,Q(this),t.queryEngine.getAbortSignal(),t.toolUseCache,$(this),t.cwd,()=>t.cancelled);if(t.cancelled)return{stopReason:`cancelled`};if(await ma(this,e.sessionId,r),o){let e={inputTokens:o.inputTokens,outputTokens:o.outputTokens,cachedReadTokens:o.cachedReadTokens,cachedWriteTokens:o.cachedWriteTokens,thoughtTokens:0,totalTokens:o.inputTokens+o.outputTokens+o.cachedReadTokens+o.cachedWriteTokens+0};return{stopReason:a,usage:e,...n?{userMessageId:n}:{},_meta:{claudeCode:{usage:e}}}}return{stopReason:a,...n?{userMessageId:n}:{}}}catch(n){let r=n instanceof Error&&(n.name===`AbortError`||/abort|cancelled|interrupt/i.test(n.message));if(t.cancelled||r)return{stopReason:`cancelled`};throw n instanceof Error&&(n.message.includes(`terminated`)||n.message.includes(`process exited`))?(await this.teardownSession(e.sessionId),Error(`The Work Mate Agent process exited unexpectedly. Please start a new session.`)):n}finally{let e=ua(t);e?(t.promptRunning=!0,e.resolve(!1)):t.promptRunning=!1}}async function pa(e){let t=this.sessions.get(e.sessionId);if(!t)throw Error(`Session not found`);if(typeof e.value!=`string`)throw Error(`Invalid value for config option ${e.configId}: ${String(e.value)}`);let n=t.configOptions.find(t=>t.id===e.configId);if(!n)throw Error(`Unknown config option: ${e.configId}`);if(n.type===`select`){let t=$i(n.options);if(!t.includes(e.value))throw Error(`Invalid value '${e.value}' for config option ${e.configId}; must be one of: ${t.join(`, `)}`)}let r=e.value;return e.configId===`mode`?(this.applySessionMode(e.sessionId,r),await Q(this).sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:`current_mode_update`,currentModeId:r}})):e.configId===`model`&&t.queryEngine.setModel(r),ea(this,t,e.configId,r),t.configOptions=t.configOptions.map(t=>t.id===e.configId&&typeof t.currentValue==`string`?{...t,currentValue:r}:t),{configOptions:t.configOptions}}async function ma(e,t,n){let r=e.sessions.get(t);if(!r)return;let i=r.toolUseCache;if(i.__sessionInfoTitleSent)return;i.__sessionInfoTitleSent=!0;let a=Ti(n).slice(0,100);try{await Q(e).sessionUpdate({sessionId:t,update:{sessionUpdate:`session_info_update`,...a?{title:a}:{},updatedAt:new Date().toISOString()}})}catch(e){console.error(`[ACP] Failed to send session_info_update:`,e)}}Object.assign(Z.prototype,{prompt:fa,setSessionConfigOption:pa}),de(),xe();function ha(e,t){let n=Ee.toWeb(e);return hi(De.toWeb(t),n)}async function ga(){fe(),be();let e=ha(process.stdin,process.stdout),t,n=new _i(e=>(t=new Z(e),t),e);console.log=console.error,console.info=console.error,console.warn=console.error,console.debug=console.error;async function r(){for(let[e]of t.sessions)try{await t.unstable_closeSession({sessionId:e})}catch{}process.exit(0)}n.closed.then(r).catch(r),process.on(`SIGTERM`,r),process.on(`SIGINT`,r),process.on(`unhandledRejection`,(e,t)=>{console.error(`Unhandled Rejection at:`,t,`reason:`,e)}),process.stdin.resume()}export{ga as runAcpAgent};
@@ -0,0 +1,10 @@
1
+ import{n as e,r as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{E as i,l as a,n as o,s,w as c}from"./esm-lWlUmoUA.js";import{F as ee,c as l,n as u,p as d,r as te,u as f}from"./esm-BbMeEYcz.js";import{n as ne,t as re}from"./esm-sVMjGuep.js";var p,m=e((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(p||(p={}))})),h,g,_=e((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(h||(h={})),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(g||(g={}))}));function ie(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function ae(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function v(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new y(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function oe(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function se(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}function ce(e,t){return e.toLowerCase()===t.toLowerCase()}var y,b=e((()=>{y=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),x,S=e((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(x||(x={}))})),le,ue=e((()=>{S(),n(),le=class{constructor(){r(this,`kind`,x.DROP)}createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function de(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var C,fe,pe=e((()=>{S(),_(),b(),n(),C=class{constructor(e,t,n=!0,i=de(t)){r(this,`startTime`,void 0),r(this,`_boundaries`,void 0),r(this,`_recordMinMax`,void 0),r(this,`_current`,void 0),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=i}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=se(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},fe=class{constructor(e,t){r(this,`kind`,x.HISTOGRAM),r(this,`_boundaries`,void 0),r(this,`_recordMinMax`,void 0),this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new C(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]+a[e];let s=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(s=Math.min(n.min,r.min),c=Math.max(n.max,r.max)):n.hasMinMax?(s=n.min,c=n.max):r.hasMinMax&&(s=r.min,c=r.max)),new C(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:s,max:c})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=a[e]-i[e];return new C(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:g.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===h.GAUGE||e.type===h.UP_DOWN_COUNTER||e.type===h.OBSERVABLE_GAUGE||e.type===h.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}})),w,me,he=e((()=>{n(),w=class e{constructor(e=new me,t=0,n=0,i=0){r(this,`backing`,void 0),r(this,`indexBase`,void 0),r(this,`indexStart`,void 0),r(this,`indexEnd`,void 0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=i}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}},me=class e{constructor(e=[0]){r(this,`_counts`,void 0),this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}}));function ge(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&ve)>>20)-be}function _e(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),r=t.getUint32(4);return(n&ye)*2**32+r}var ve,ye,be,xe,Se,T,Ce=e((()=>{ve=2146435072,ye=1048575,be=1023,xe=-1022,Se=be,T=2**-1022}));function E(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function we(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var D=e((()=>{})),O,Te=e((()=>{O=class extends Error{}})),Ee,De=e((()=>{Ce(),D(),Te(),n(),Ee=class{constructor(e){r(this,`_shift`,void 0),this._shift=-e}mapToIndex(e){return e<T?this._minNormalLowerBoundaryIndex():ge(e)+this._rightShift(_e(e)-1,52)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new O(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new O(`overflow: ${e} is > maximum lower boundary: ${n}`);return E(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=xe>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Se>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),Oe,ke=e((()=>{Ce(),D(),Te(),n(),Oe=class{constructor(e){r(this,`_scale`,void 0),r(this,`_scaleFactor`,void 0),r(this,`_inverseFactor`,void 0),this._scale=e,this._scaleFactor=E(Math.LOG2E,e),this._inverseFactor=E(Math.LN2,-e)}mapToIndex(e){if(e<=T)return this._minNormalLowerBoundaryIndex()-1;if(_e(e)===0)return(ge(e)<<this._scale)-1;let t=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return t>=n?n:t}lowerBoundary(e){let t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new O(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return T;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new O(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return xe<<this._scale}_maxNormalLowerBoundaryIndex(){return(Se+1<<this._scale)-1}}}));function Ae(e){if(e>Me||e<je)throw new O(`expected scale >= ${je} && <= ${Me}, got: ${e}`);return Ne[e+10]}var je,Me,Ne,Pe=e((()=>{De(),ke(),Te(),je=-10,Me=20,Ne=Array.from({length:31},(e,t)=>t>10?new Oe(t-10):new Ee(t-10))})),k,Fe,Ie,A,Le,Re,ze=e((()=>{S(),_(),o(),he(),Pe(),D(),n(),k=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}constructor(e,t){r(this,`low`,void 0),r(this,`high`,void 0),this.low=e,this.high=t}},Fe=20,Ie=160,A=2,Le=class e{constructor(e,t=Ie,n=!0,i=0,a=0,o=0,c=1/0,ee=-1/0,l=new w,u=new w,d=Ae(Fe)){r(this,`startTime`,void 0),r(this,`_maxSize`,void 0),r(this,`_recordMinMax`,void 0),r(this,`_sum`,void 0),r(this,`_count`,void 0),r(this,`_zeroCount`,void 0),r(this,`_min`,void 0),r(this,`_max`,void 0),r(this,`_positive`,void 0),r(this,`_negative`,void 0),r(this,`_mapping`,void 0),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=i,this._count=a,this._zeroCount=o,this._min=c,this._max=ee,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<A&&(s.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
2
+ changing to the minimum size of: ${A}`),this._maxSize=A)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new e(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,n){let r=this._mapping.mapToIndex(t),i=!1,a=0,o=0;if(e.length===0?(e.indexStart=r,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):r<e.indexStart&&e.indexEnd-r>=this._maxSize?(i=!0,o=r,a=e.indexEnd):r>e.indexEnd&&r-e.indexStart>=this._maxSize&&(i=!0,o=e.indexStart,a=r),i){let e=this._changeScale(a,o);this._downscale(e),r=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,r,n)}_incrementIndexBy(e,t,n){if(n===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){let n=e.indexEnd-t;n>=e.backing.length&&this._grow(e,n+1),e.indexStart=t}else if(t>e.indexEnd){let n=t-e.indexStart;n>=e.backing.length&&this._grow(e,n+1),e.indexEnd=t}let r=t-e.indexBase;r<0&&(r+=e.backing.length),e.incrementBucket(r,n)}_grow(e,t){let n=e.backing.length,r=e.indexBase-e.indexStart,i=n-r,a=we(t);a>this._maxSize&&(a=this._maxSize);let o=a-r;e.backing.growTo(a,i,o)}_changeScale(e,t){let n=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n}_downscale(e){if(e===0)return;if(e<0)throw Error(`impossible change of scale: ${this.scale}`);let t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Ae(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=k.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=k.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(r.high,r.low))}_highLowAtScale(e,t,n){if(e.length===0)return new k(0,-1);let r=t-n;return new k(e.indexStart>>r,e.indexEnd>>r)}_mergeBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++)this._incrementIndexBy(e,i+t>>a,n.at(t))}_diffBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++){let r=(i+t>>a)-e.indexBase;r<0&&(r+=e.backing.length),e.decrementBucket(r,n.at(t))}e.trim()}},Re=class{constructor(e,t){r(this,`kind`,x.EXPONENTIAL_HISTOGRAM),r(this,`_maxSize`,void 0),r(this,`_recordMinMax`,void 0),this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new Le(e,this._maxSize,this._recordMinMax)}merge(e,t){let n=t.clone();return n.merge(e),n}diff(e,t){let n=t.clone();return n.diff(e),n}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:g.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===h.GAUGE||e.type===h.UP_DOWN_COUNTER||e.type===h.OBSERVABLE_GAUGE||e.type===h.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}})),j,Be,Ve=e((()=>{S(),u(),_(),n(),j=class{constructor(e,t=0,n=[0,0]){r(this,`startTime`,void 0),r(this,`_current`,void 0),r(this,`sampleTime`,void 0),this.startTime=e,this._current=t,this.sampleTime=n}record(e){this._current=e,this.sampleTime=d(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Be=class{constructor(){r(this,`kind`,x.LAST_VALUE)}createAccumulation(e){return new j(e)}merge(e,t){let n=f(t.sampleTime)>=f(e.sampleTime)?t:e;return new j(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=f(t.sampleTime)>=f(e.sampleTime)?t:e;return new j(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:g.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),M,He,Ue=e((()=>{S(),_(),n(),M=class{constructor(e,t,n=0,i=!1){r(this,`startTime`,void 0),r(this,`monotonic`,void 0),r(this,`_current`,void 0),r(this,`reset`,void 0),this.startTime=e,this.monotonic=t,this._current=n,this.reset=i}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},He=class{constructor(e){r(this,`kind`,x.SUM),r(this,`monotonic`,void 0),this.monotonic=e}createAccumulation(e){return new M(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new M(t.startTime,this.monotonic,r,t.reset):new M(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new M(t.startTime,this.monotonic,r,!0):new M(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:g.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),We=e((()=>{ue(),pe(),ze(),Ve(),Ue()})),N,P,F,I,L,R,Ge,z,B,V,H,Ke,qe=e((()=>{o(),We(),_(),n(),N=class e{createAggregator(t){return e.DEFAULT_INSTANCE}},r(N,`DEFAULT_INSTANCE`,new le),P=class e{createAggregator(t){switch(t.type){case h.COUNTER:case h.OBSERVABLE_COUNTER:case h.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},r(P,`MONOTONIC_INSTANCE`,new He(!0)),r(P,`NON_MONOTONIC_INSTANCE`,new He(!1)),F=class e{createAggregator(t){return e.DEFAULT_INSTANCE}},r(F,`DEFAULT_INSTANCE`,new Be),I=class e{createAggregator(t){return e.DEFAULT_INSTANCE}},r(I,`DEFAULT_INSTANCE`,new fe([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0)),L=class{constructor(e,t=!0){if(r(this,`_boundaries`,void 0),r(this,`_recordMinMax`,void 0),e==null)throw Error(`ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array`);e=e.concat(),e=e.sort((e,t)=>e-t);let n=e.lastIndexOf(-1/0),i=e.indexOf(1/0);i===-1&&(i=void 0),this._boundaries=e.slice(n+1,i),this._recordMinMax=t}createAggregator(e){return new fe(this._boundaries,this._recordMinMax)}},R=class{constructor(e=160,t=!0){r(this,`_maxSize`,void 0),r(this,`_recordMinMax`,void 0),this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new Re(this._maxSize,this._recordMinMax)}},Ge=class{_resolve(e){switch(e.type){case h.COUNTER:case h.UP_DOWN_COUNTER:case h.OBSERVABLE_COUNTER:case h.OBSERVABLE_UP_DOWN_COUNTER:return B;case h.GAUGE:case h.OBSERVABLE_GAUGE:return V;case h.HISTOGRAM:return e.advice.explicitBucketBoundaries?new L(e.advice.explicitBucketBoundaries):H}return s.warn(`Unable to recognize instrument type: ${e.type}`),z}createAggregator(e){return this._resolve(e).createAggregator(e)}},z=new N,B=new P,V=new F,H=new I,new R,Ke=new Ge}));function Je(e){switch(e.type){case U.DEFAULT:return Ke;case U.DROP:return z;case U.SUM:return B;case U.LAST_VALUE:return V;case U.EXPONENTIAL_HISTOGRAM:{let t=e;return new R(t.options?.maxSize,t.options?.recordMinMax)}case U.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?H:new L(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var U,W=e((()=>{qe(),(function(e){e[e.DEFAULT=0]=`DEFAULT`,e[e.DROP=1]=`DROP`,e[e.SUM=2]=`SUM`,e[e.LAST_VALUE=3]=`LAST_VALUE`,e[e.EXPLICIT_BUCKET_HISTOGRAM=4]=`EXPLICIT_BUCKET_HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=5]=`EXPONENTIAL_HISTOGRAM`})(U||(U={}))})),Ye,G,Xe=e((()=>{m(),W(),Ye=e=>({type:U.DEFAULT}),G=e=>p.CUMULATIVE})),Ze,Qe=e((()=>{o(),b(),Xe(),n(),Ze=class{constructor(e){r(this,`_shutdown`,!1),r(this,`_metricProducers`,void 0),r(this,`_sdkMetricProducer`,void 0),r(this,`_aggregationTemporalitySelector`,void 0),r(this,`_aggregationSelector`,void 0),r(this,`_cardinalitySelector`,void 0),this._aggregationSelector=e?.aggregationSelector??Ye,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??G,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw Error(`MetricReader is not bound to a MetricProducer`);if(this._shutdown)throw Error(`MetricReader is shutdown`);let[t,...n]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),r=t.errors.concat(n.flatMap(e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(n.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:r}}async shutdown(e){if(this._shutdown){s.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await v(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){s.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await v(this.onForceFlush(),e.timeoutMillis)}}})),$e,et=e((()=>{o(),u(),Qe(),b(),_(),n(),$e=class extends Ze{constructor(e){let{exporter:t,exportIntervalMillis:n=6e4,metricProducers:i,cardinalityLimits:a}=e,{exportTimeoutMillis:o=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),metricProducers:i,cardinalitySelector:e=>{let t={default:2e3,...a};switch(e){case h.COUNTER:return t.counter??t.default;case h.GAUGE:return t.gauge??t.default;case h.HISTOGRAM:return t.histogram??t.default;case h.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case h.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case h.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case h.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),r(this,`_interval`,void 0),r(this,`_exporter`,void 0),r(this,`_exportInterval`,void 0),r(this,`_exportTimeout`,void 0),n<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(o<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(n<o){if(`exportIntervalMillis`in e&&`exportTimeoutMillis`in e)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);s.info(`Timeout of ${o} exceeds the interval of ${n}. Clamping timeout to interval duration.`),o=n}this._exportInterval=n,this._exportTimeout=o,this._exporter=t}async _runOnce(){try{await v(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof y){s.error(`Export took longer than %s milliseconds and timed out.`,this._exportTimeout);return}ee(e)}}async _doRun(){let{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&s.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){s.debug(`Error while resolving async portion of resource: `,e),ee(e)}if(e.scopeMetrics.length===0)return;let n=await te._export(this._exporter,e);if(n.code!==l.SUCCESS)throw Error(`PeriodicExportingMetricReader: metrics export failed (error ${n.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!=`number`&&this._interval.unref()}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}})),tt,nt=e((()=>{u(),n(),tt=class{constructor(e){r(this,`_shutdown`,!1),r(this,`_aggregationTemporality`,void 0),r(this,`_metrics`,[]),this._aggregationTemporality=e}export(e,t){if(this._shutdown){setTimeout(()=>t({code:l.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>t({code:l.SUCCESS}),0)}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}})),rt,it=e((()=>{u(),Xe(),n(),rt=class e{constructor(e){r(this,`_shutdown`,!1),r(this,`_temporalitySelector`,void 0),this._temporalitySelector=e?.temporalitySelector??G}export(t,n){if(this._shutdown){n({code:l.FAILED});return}return e._sendMetrics(t,n)}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(let t of e.scopeMetrics)for(let e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:l.SUCCESS})}}})),at,ot=e((()=>{n(),at=class{constructor(){r(this,`_registeredViews`,[])}addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(n=>this._matchInstrument(n.instrumentSelector,e)&&this._matchMeter(n.meterSelector,t))}_matchInstrument(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))}}}));function K(e,t,n){return lt(e)||s.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:n?.description??``,unit:n?.unit??``,valueType:n?.valueType??c.DOUBLE,advice:n?.advice??{}}}function st(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function ct(e,t){return ce(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function lt(e){return ut.test(e)}var ut,q=e((()=>{o(),b(),ut=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function dt(e){return e instanceof Y}var J,ft,pt,mt,ht,Y,gt,_t,vt,yt=e((()=>{o(),u(),n(),J=class{constructor(e,t){r(this,`_writableMetricStorage`,void 0),r(this,`_descriptor`,void 0),this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n=a.active()){if(typeof e!=`number`){s.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===c.INT&&!Number.isInteger(e)&&(s.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,d(Date.now()))}},ft=class extends J{add(e,t,n){this._record(e,t,n)}},pt=class extends J{add(e,t,n){if(e<0){s.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},mt=class extends J{record(e,t,n){this._record(e,t,n)}},ht=class extends J{record(e,t,n){if(e<0){s.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},Y=class{constructor(e,t,n){r(this,`_metricStorages`,void 0),r(this,`_descriptor`,void 0),r(this,`_observableRegistry`,void 0),this._descriptor=e,this._metricStorages=t,this._observableRegistry=n}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}},gt=class extends Y{},_t=class extends Y{},vt=class extends Y{}})),bt,xt=e((()=>{q(),yt(),_(),n(),bt=class{constructor(e){r(this,`_meterSharedState`,void 0),this._meterSharedState=e}createGauge(e,t){let n=K(e,h.GAUGE,t);return new mt(this._meterSharedState.registerMetricStorage(n),n)}createHistogram(e,t){let n=K(e,h.HISTOGRAM,t);return new ht(this._meterSharedState.registerMetricStorage(n),n)}createCounter(e,t){let n=K(e,h.COUNTER,t);return new pt(this._meterSharedState.registerMetricStorage(n),n)}createUpDownCounter(e,t){let n=K(e,h.UP_DOWN_COUNTER,t);return new ft(this._meterSharedState.registerMetricStorage(n),n)}createObservableGauge(e,t){let n=K(e,h.OBSERVABLE_GAUGE,t);return new _t(n,this._meterSharedState.registerAsyncMetricStorage(n),this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=K(e,h.OBSERVABLE_COUNTER,t);return new gt(n,this._meterSharedState.registerAsyncMetricStorage(n),this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=K(e,h.OBSERVABLE_UP_DOWN_COUNTER,t);return new vt(n,this._meterSharedState.registerAsyncMetricStorage(n),this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),X,St=e((()=>{q(),n(),X=class{constructor(e){r(this,`_instrumentDescriptor`,void 0),this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=K(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),Ct,Z,Q=e((()=>{b(),n(),Ct=class{constructor(e){r(this,`_valueMap`,new Map),r(this,`_keyMap`,new Map),r(this,`_hash`,void 0),this._hash=e}get(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)}getOrDefault(e,t){let n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);let r=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r),r}set(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)}has(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)}*keys(){let e=this._keyMap.entries(),t=e.next();for(;t.done!==!0;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){let e=this._valueMap.entries(),t=e.next();for(;t.done!==!0;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}},Z=class extends Ct{constructor(){super(ie)}}})),wt,Tt=e((()=>{b(),Q(),n(),wt=class{constructor(e,t){r(this,`_activeCollectionStorage`,new Z),r(this,`_cumulativeMemoStorage`,new Z),r(this,`_cardinalityLimit`,void 0),r(this,`_overflowAttributes`,{"otel.metric.overflow":!0}),r(this,`_overflowHashCode`,void 0),r(this,`_aggregator`,void 0),this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=ie(this._overflowAttributes)}record(e,t,n,r){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(r))?.record(e);return}i=this._aggregator.createAccumulation(r),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,n,r])=>{let i=this._aggregator.createAccumulation(t);i?.record(n);let a=i;if(this._cumulativeMemoStorage.has(e,r)){let t=this._cumulativeMemoStorage.get(e,r);a=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,r=this._overflowHashCode,this._cumulativeMemoStorage.has(e,r))){let t=this._cumulativeMemoStorage.get(e,r);a=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,r)){let t=this._activeCollectionStorage.get(e,r);a=this._aggregator.merge(t,a)}this._cumulativeMemoStorage.set(e,i,r),this._activeCollectionStorage.set(e,a,r)})}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new Z,e}}}));function Et(e){return Array.from(e.entries())}var Dt,Ot=e((()=>{m(),Q(),n(),Dt=class e{constructor(e,t){r(this,`_aggregator`,void 0),r(this,`_unreportedAccumulations`,new Map),r(this,`_reportHistory`,new Map),this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(t,n,r,i){this._stashAccumulations(r);let a=this._getMergedUnreportedAccumulations(t),o=a,s;if(this._reportHistory.has(t)){let n=this._reportHistory.get(t),r=n.collectionTime;s=n.aggregationTemporality,o=s===p.CUMULATIVE?e.merge(n.accumulations,a,this._aggregator):e.calibrateStartTime(n.accumulations,a,r)}else s=t.selectAggregationTemporality(n.type);this._reportHistory.set(t,{accumulations:o,collectionTime:i,aggregationTemporality:s});let c=Et(o);if(c.length!==0)return this._aggregator.toMetricData(n,s,c,i)}_stashAccumulations(e){let t=this._unreportedAccumulations.keys();for(let n of t){let t=this._unreportedAccumulations.get(n);t===void 0&&(t=[],this._unreportedAccumulations.set(n,t)),t.push(e)}}_getMergedUnreportedAccumulations(t){let n=new Z,r=this._unreportedAccumulations.get(t);if(this._unreportedAccumulations.set(t,[]),r===void 0)return n;for(let t of r)n=e.merge(n,t,this._aggregator);return n}static merge(e,t,n){let r=e,i=t.entries(),a=i.next();for(;a.done!==!0;){let[t,o,s]=a.value;if(e.has(t,s)){let i=e.get(t,s),a=n.merge(i,o);r.set(t,a,s)}else r.set(t,o,s);a=i.next()}return r}static calibrateStartTime(e,t,n){for(let[r,i]of e.keys())t.get(r,i)?.setStartTime(n);return t}}})),kt,At=e((()=>{St(),Tt(),Ot(),Q(),n(),kt=class extends X{constructor(e,t,n,i,a){super(e),r(this,`_aggregationCardinalityLimit`,void 0),r(this,`_deltaMetricStorage`,void 0),r(this,`_temporalMetricStorage`,void 0),r(this,`_attributesProcessor`,void 0),this._aggregationCardinalityLimit=a,this._deltaMetricStorage=new wt(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Dt(t,i),this._attributesProcessor=n}record(e,t){let n=new Z;Array.from(e.entries()).forEach(([e,t])=>{n.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(n,t)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}}));function jt(e,t){let n=``;return e.unit!==t.unit&&(n+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(n+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(n+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(n+=`\t- Description '${e.description}' does not match '${t.description}'\n`),n}function Mt(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function Nt(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function Pt(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'`}function Ft(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'
3
+ \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${r}
4
+ \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${r}`}function It(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:Ft(e,t):Pt(e,t):Nt(e,t):Mt(e,t)}var Lt=e((()=>{})),Rt,zt=e((()=>{q(),o(),Lt(),n(),Rt=class e{constructor(){r(this,`_sharedRegistry`,new Map),r(this,`_perCollectorRegistry`,new Map)}static create(){return new e}getStorages(e){let t=[];for(let e of this._sharedRegistry.values())t=t.concat(e);let n=this._perCollectorRegistry.get(e);if(n!=null)for(let e of n.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let n=this._perCollectorRegistry.get(e);n??(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)}findOrUpdateCompatibleStorage(e){let t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){let n=this._perCollectorRegistry.get(e);if(n===void 0)return null;let r=n.get(t.name);return r===void 0?null:this._findOrUpdateCompatibleStorage(t,r)}_registerStorage(e,t){let n=e.getInstrumentDescriptor(),r=t.get(n.name);if(r===void 0){t.set(n.name,[e]);return}r.push(e)}_findOrUpdateCompatibleStorage(e,t){let n=null;for(let r of t){let t=r.getInstrumentDescriptor();ct(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),s.warn(`A view or instrument with the name `,e.name,` has already been registered, but has a different description and is incompatible with another registered view.
5
+ `,`Details:
6
+ `,jt(t,e),`The longer description will be used.
7
+ To resolve the conflict:`,It(t,e))),n=r):s.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
8
+ `,`Details:
9
+ `,jt(t,e),`To resolve the conflict:
10
+ `,It(t,e))}return n}}})),Bt,Vt=e((()=>{n(),Bt=class{constructor(e){r(this,`_backingStorages`,void 0),this._backingStorages=e}record(e,t,n,r){this._backingStorages.forEach(i=>{i.record(e,t,n,r)})}}})),Ht,Ut,Wt=e((()=>{o(),Q(),yt(),n(),Ht=class{constructor(e,t){r(this,`_buffer`,new Z),r(this,`_instrumentName`,void 0),r(this,`_valueType`,void 0),this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){s.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===c.INT&&!Number.isInteger(e)&&(s.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)}},Ut=class{constructor(){r(this,`_buffer`,new Map)}observe(e,t,n={}){if(!dt(e))return;let r=this._buffer.get(e);if(r??(r=new Z,this._buffer.set(e,r)),typeof t!=`number`){s.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===c.INT&&!Number.isInteger(t)&&(s.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||r.set(n,t)}}})),Gt,Kt=e((()=>{o(),yt(),Wt(),b(),n(),Gt=class{constructor(){r(this,`_callbacks`,[]),r(this,`_batchCallbacks`,[])}addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(dt));if(n.size===0){s.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(dt)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new Ht(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=v(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Ut,a=Promise.resolve(n(i));t!=null&&(a=v(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&oe(n.instruments,t))}}})),qt,Jt=e((()=>{St(),Tt(),Ot(),n(),qt=class extends X{constructor(e,t,n,i,a){super(e),r(this,`_aggregationCardinalityLimit`,void 0),r(this,`_deltaMetricStorage`,void 0),r(this,`_temporalMetricStorage`,void 0),r(this,`_attributesProcessor`,void 0),this._aggregationCardinalityLimit=a,this._deltaMetricStorage=new wt(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Dt(t,i),this._attributesProcessor=n}record(e,t,n,r){t=this._attributesProcessor.process(t,n),this._deltaMetricStorage.record(e,t,n,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}}));function Yt(){return rn}function Xt(e){return new en(e)}function Zt(e){return new tn(e)}function Qt(e){return new nn(e)}var $t,en,tn,nn,rn,an=e((()=>{n(),$t=class{process(e,t){return e}},en=class{constructor(e){r(this,`_processors`,void 0),this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},tn=class{constructor(e){r(this,`_allowedAttributeNames`,void 0),this._allowedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(n[t]=e[t])}),n}},nn=class{constructor(e){r(this,`_deniedAttributeNames`,void 0),this._deniedAttributeNames=e}process(e,t){let n={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(n[t]=e[t])}),n}},rn=new $t})),on,sn=e((()=>{q(),xt(),At(),zt(),Vt(),Kt(),Jt(),an(),n(),on=class{constructor(e,t){r(this,`metricStorageRegistry`,new Rt),r(this,`observableRegistry`,new Gt),r(this,`meter`,void 0),r(this,`_meterProviderSharedState`,void 0),r(this,`_instrumentationScope`,void 0),this.meter=new bt(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,qt);return t.length===1?t[0]:new Bt(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,kt)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=st(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,Yt(),[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}}})),cn,ln=e((()=>{b(),ot(),sn(),W(),n(),cn=class{constructor(e){r(this,`viewRegistry`,new at),r(this,`metricCollectors`,[]),r(this,`meterSharedStates`,new Map),r(this,`resource`,void 0),this.resource=e}getMeterSharedState(e){let t=ae(e),n=this.meterSharedStates.get(t);return n??(n=new on(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Je(n.selectAggregation(e))]);return t}}})),un,dn=e((()=>{u(),n(),un=class{constructor(e,t){r(this,`_sharedState`,void 0),r(this,`_metricReader`,void 0),this._sharedState=e,this._metricReader=t}async collect(e){let t=d(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),fn,pn,$,mn=e((()=>{n(),fn=/[\^$\\.+?()[\]{}|]/g,pn=class e{constructor(t){r(this,`_matchAll`,void 0),r(this,`_regexp`,void 0),t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(fn,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},$=class{constructor(e){r(this,`_matchAll`,void 0),r(this,`_pattern`,void 0),this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),hn,gn=e((()=>{mn(),n(),hn=class{constructor(e){r(this,`_nameFilter`,void 0),r(this,`_type`,void 0),r(this,`_unitFilter`,void 0),this._nameFilter=new pn(e?.name??`*`),this._type=e?.type,this._unitFilter=new $(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),_n,vn=e((()=>{mn(),n(),_n=class{constructor(e){r(this,`_nameFilter`,void 0),r(this,`_versionFilter`,void 0),r(this,`_schemaUrlFilter`,void 0),this._nameFilter=new $(e?.name),this._versionFilter=new $(e?.version),this._schemaUrlFilter=new $(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}}));function yn(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function bn(e){if(yn(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||pn.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var xn,Sn=e((()=>{mn(),an(),gn(),vn(),W(),n(),xn=class{constructor(e){r(this,`name`,void 0),r(this,`description`,void 0),r(this,`aggregation`,void 0),r(this,`attributesProcessor`,void 0),r(this,`instrumentSelector`,void 0),r(this,`meterSelector`,void 0),r(this,`aggregationCardinalityLimit`,void 0),bn(e),e.attributesProcessors==null?this.attributesProcessor=Yt():this.attributesProcessor=Xt(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Je(e.aggregation??{type:U.DEFAULT}),this.instrumentSelector=new hn({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new _n({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),Cn,wn=e((()=>{o(),re(),ln(),dn(),Sn(),n(),Cn=class{constructor(e){if(r(this,`_sharedState`,void 0),r(this,`_shutdown`,!1),this._sharedState=new cn(e?.resource??ne()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new xn(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new un(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t=``,n={}){return this._shutdown?(s.warn(`A shutdown MeterProvider cannot provide a Meter`),i()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){s.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){s.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),Tn=t({AggregationTemporality:()=>p,AggregationType:()=>U,ConsoleMetricExporter:()=>rt,DataPointType:()=>g,InMemoryMetricExporter:()=>tt,InstrumentType:()=>h,MeterProvider:()=>Cn,MetricReader:()=>Ze,PeriodicExportingMetricReader:()=>$e,TimeoutError:()=>y,createAllowListAttributesProcessor:()=>Zt,createDenyListAttributesProcessor:()=>Qt}),En=e((()=>{m(),_(),Qe(),et(),nt(),it(),wn(),W(),an(),b()}));export{g as a,p as c,W as i,m as l,En as n,h as o,U as r,_ as s,Tn as t};