@readmagic/workmate 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (461) hide show
  1. package/dist/chunks/AddWorkspaceDirectory-DWgTWJ7R.js +1 -0
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-DCvgQ6n3.js +1 -0
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-s0Orgord.js +1 -0
  4. package/dist/chunks/App-BcEI6U5j.js +1 -0
  5. package/dist/chunks/ApproveApiKey-DegdTXZl.js +1 -0
  6. package/dist/chunks/ApproveApiKey-_VXIMSwY.js +1 -0
  7. package/dist/chunks/BackgroundTasksDialog-CjBt1L0p.js +2 -0
  8. package/dist/chunks/BypassPermissionsModeDialog-D2Gesf-u.js +1 -0
  9. package/dist/chunks/CustomSelect-B46Eh0gU.js +1 -0
  10. package/dist/chunks/DiffDialog-v2IiYyi3.js +6 -0
  11. package/dist/chunks/Doctor-BP0Rqraa.js +1 -0
  12. package/dist/chunks/Doctor-By_y3C2V.js +3 -0
  13. package/dist/chunks/ExitFlow-BasHk1mk.js +2 -0
  14. package/dist/chunks/Grove-C3mhgshv.js +11 -0
  15. package/dist/chunks/InvalidConfigDialog-DYVQK5js.js +1 -0
  16. package/dist/chunks/InvalidSettingsDialog-Dg6OiStR.js +1 -0
  17. package/dist/chunks/KeybindingProviderSetup-Bn1jzN5F.js +1 -0
  18. package/dist/chunks/MCPConnectionManager-ChN4Ayjk.js +1 -0
  19. package/dist/chunks/MCPToolListView-DLSrQHDc.js +1 -0
  20. package/dist/chunks/{McpParsingWarnings-6ENzOklf.js → McpParsingWarnings-DZejAh8b.js} +1 -1
  21. package/dist/chunks/MessageSelector-CdDlJE48.js +3 -0
  22. package/dist/chunks/Messages-DuL_r1Or.js +10 -0
  23. package/dist/chunks/Onboarding-CE2GNA-h.js +1 -0
  24. package/dist/chunks/{PromptInputFooterSuggestions-Blzgj5yW.js → PromptInputFooterSuggestions-lkr_A5jQ.js} +1 -1
  25. package/dist/chunks/PromptInputHelpMenu-DaQKKyM5.js +1 -0
  26. package/dist/chunks/QueryEngine-DNNy1UCD.js +1 -0
  27. package/dist/chunks/REPL-CEhW-C41.js +1 -0
  28. package/dist/chunks/REPL-CkSL4C_8.js +124 -0
  29. package/dist/chunks/ResumeConversation-BMCO_3X7.js +1 -0
  30. package/dist/chunks/SearchExtraToolsTool-DSy_jDhf.js +1 -0
  31. package/dist/chunks/SelectMulti-CNE06VAN.js +1 -0
  32. package/dist/chunks/Settings-mDykHLok.js +2 -0
  33. package/dist/chunks/Spinner-DwsJJUtn.js +1 -0
  34. package/dist/chunks/SpinnerGlyph-A6G-gloN.js +1 -0
  35. package/dist/chunks/TextInput-7uqPhq9T.js +22 -0
  36. package/dist/chunks/ThemePicker-DT9zVy-0.js +1 -0
  37. package/dist/chunks/TrustDialog-G4jM9IfM.js +1 -0
  38. package/dist/chunks/{ValidationErrorsList-2QWIs_6h.js → ValidationErrorsList-BLtP647v.js} +1 -1
  39. package/dist/chunks/add-dir-7RfQAC3h.js +1 -0
  40. package/dist/chunks/{agentDisplay-1Y-N-gqz.js → agentDisplay-vLQHFrmq.js} +1 -1
  41. package/dist/chunks/agents-BNg_skSm.js +101 -0
  42. package/dist/chunks/{agents-CvW8XjoJ.js → agents-DLz0kfsr.js} +1 -1
  43. package/dist/chunks/allErrors-DaztSMrw.js +1 -0
  44. package/dist/chunks/appleTerminalBackup-BYKdf3of.js +1 -0
  45. package/dist/chunks/auth-BTB00dq5.js +10 -0
  46. package/dist/chunks/auth-Bbc0Ny8i.js +1 -0
  47. package/dist/chunks/backgroundHousekeeping-DYz83_8C.js +1 -0
  48. package/dist/chunks/backgroundHousekeeping-bEZtlJSf.js +17 -0
  49. package/dist/chunks/banner-mqZEluky.js +2 -0
  50. package/dist/chunks/branch-exFKkymg.js +2 -0
  51. package/dist/chunks/{break-cache-BZ_UMtEL.js → break-cache-BL2gnDLX.js} +2 -2
  52. package/dist/chunks/btw-3l78DYET.js +1 -0
  53. package/dist/chunks/caches-6Nx6tsk9.js +1 -0
  54. package/dist/chunks/caches-ouaWB9bY.js +1 -0
  55. package/dist/chunks/claudeDesktop-D3PEgx3U.js +1 -0
  56. package/dist/chunks/{clear-D2KRoibg.js → clear-CXfhVRp8.js} +1 -1
  57. package/dist/chunks/client-C01Bnxxv.js +1 -0
  58. package/dist/chunks/client-DYRgRQsr.js +1 -0
  59. package/dist/chunks/{client-C_jBL1yC.js → client-DdenNfkQ.js} +1 -1
  60. package/dist/chunks/client-DvhWKIOx.js +1 -0
  61. package/dist/chunks/commands-BoxOw75F.js +1 -0
  62. package/dist/chunks/compact-BOYr105K.js +2 -0
  63. package/dist/chunks/config-BddEvZZl.js +3 -0
  64. package/dist/chunks/config-GEv9hUzz.js +1 -0
  65. package/dist/chunks/config-kw4xg7Nk.js +1 -0
  66. package/dist/chunks/{context-Db9tH1VF.js → context-3s9wtn4L.js} +1 -1
  67. package/dist/chunks/{context-noninteractive-CacA9VlT.js → context-noninteractive-CJhUu_4y.js} +9 -9
  68. package/dist/chunks/context-noninteractive-DFvoZ2L9.js +1 -0
  69. package/dist/chunks/conversation-CoGharlH.js +1 -0
  70. package/dist/chunks/conversation-MxEVm54C.js +1 -0
  71. package/dist/chunks/conversationRecovery-Da_8uldZ.js +1 -0
  72. package/dist/chunks/crossProjectResume-CzPCHq_K.js +40 -0
  73. package/dist/chunks/cwd-BcO6WHKo.js +1 -0
  74. package/dist/chunks/cwd-CDUelriw.js +1 -0
  75. package/dist/chunks/{datadog-BuElf2EQ.js → datadog-v_mXWncN.js} +1 -1
  76. package/dist/chunks/{debug-D58GQBDG.js → debug-8DCufdSp.js} +4 -4
  77. package/dist/chunks/detectRepository-DfX8xXw2.js +1 -0
  78. package/dist/chunks/{diff-yA6v_dpP.js → diff-DJSt7QO6.js} +1 -1
  79. package/dist/chunks/directoryCompletion-CT6YVeg7.js +1 -0
  80. package/dist/chunks/doctor-DWvioSU9.js +1 -0
  81. package/dist/chunks/entry-ex0-RyYV.js +13 -0
  82. package/dist/chunks/esm-BQY8jJNR.js +1 -0
  83. package/dist/chunks/{execFileNoThrow-B_KRY4cT.js → execFileNoThrow-BsfuytkN.js} +1 -1
  84. package/dist/chunks/exit-BxC_ZEtO.js +1 -0
  85. package/dist/chunks/extraUsage-DYm33Occ.js +1 -0
  86. package/dist/chunks/extractMemories-CzN3Ax2B.js +1 -0
  87. package/dist/chunks/fast-DqUpl_Lr.js +1 -0
  88. package/dist/chunks/fast-NUdUyAaM.js +1 -0
  89. package/dist/chunks/fetchModelList-CqsTAWEN.js +1 -0
  90. package/dist/chunks/fetchModelList-DBMHE6Ng.js +1 -0
  91. package/dist/chunks/fileSuggestions-B-SLfb-o.js +3 -0
  92. package/dist/chunks/firstPartyEventLogger-C0q45h_4.js +3 -0
  93. package/dist/chunks/firstPartyEventLogger-CP8hCBDj.js +1 -0
  94. package/dist/chunks/gemini-BC9kHhwe.js +2 -0
  95. package/dist/chunks/generateSessionName-ChvKBVxB.js +1 -0
  96. package/dist/chunks/{genericProcessUtils-Cnyun_Wr.js → genericProcessUtils-BYi0OefF.js} +1 -1
  97. package/dist/chunks/goal-ByyimpVU.js +3 -0
  98. package/dist/chunks/grok-DenjixMl.js +1 -0
  99. package/dist/chunks/grove-Dq8QbQ9o.js +7 -0
  100. package/dist/chunks/help-CK90i4hE.js +1 -0
  101. package/dist/chunks/history-CNQNd6hT.js +1 -0
  102. package/dist/chunks/{hooks-BDgToO1Z.js → hooks-BRFDg9DV.js} +2 -2
  103. package/dist/chunks/hooks-BaYwmkxD.js +1 -0
  104. package/dist/chunks/install-ZMll-dAa.js +1 -0
  105. package/dist/chunks/instrumentation-BwVyvRfY.js +21 -0
  106. package/dist/chunks/{job-DYMfSglZ.js → job-G_ukhLc4.js} +1 -1
  107. package/dist/chunks/keybindings-wNxBzDVQ.js +1 -0
  108. package/dist/chunks/launchLocalMemory-BcRlXLm6.js +3 -0
  109. package/dist/chunks/launchOnboarding-CDjQ64RO.js +8 -0
  110. package/dist/chunks/{loadAgentsDir-C96o6gCj.js → loadAgentsDir-C1LkW7gl.js} +551 -621
  111. package/dist/chunks/loadAgentsDir-DKXap_Om.js +1 -0
  112. package/dist/chunks/{loadPluginHooks-0nGlugZ4.js → loadPluginHooks-DtmHtEiS.js} +1 -1
  113. package/dist/chunks/{loader-C33o_5kS.js → loader-C61fB6vU.js} +1 -1
  114. package/dist/chunks/localSearch-BB9x5C2N.js +1 -0
  115. package/dist/chunks/{localSearch-DLz5IGGu.js → localSearch-DFo_WTMm.js} +1 -1
  116. package/dist/chunks/log-DaILwWJa.js +1 -0
  117. package/dist/chunks/logoUtils-Dj_2SWmO.js +1 -0
  118. package/dist/chunks/{magicDocs-DmPNMnNY.js → magicDocs-DYc9TFmI.js} +2 -2
  119. package/dist/chunks/main-BRg8L_aw.js +346 -0
  120. package/dist/chunks/managedEnv-DsqAYOJ4.js +1 -0
  121. package/dist/chunks/managedEnv-lybrMred.js +1 -0
  122. package/dist/chunks/mcp-Bsw3cMiJ.js +6 -0
  123. package/dist/chunks/mcp-DDdud6Y7.js +1 -0
  124. package/dist/chunks/mcp-DbgTDUt7.js +2 -0
  125. package/dist/chunks/memory-CzwTzihf.js +1 -0
  126. package/dist/chunks/mode-Pan-Q2c4.js +2 -0
  127. package/dist/chunks/model-BYfmXKHf.js +1 -0
  128. package/dist/chunks/model-BwBE0Pt5.js +1 -0
  129. package/dist/chunks/modelOptions-DvNBapgG.js +1 -0
  130. package/dist/chunks/nativeInstaller-DnSNJWIi.js +1 -0
  131. package/dist/chunks/notifications-B0DTaYoy.js +1 -0
  132. package/dist/chunks/omit-Dl1Us_PY.js +1 -0
  133. package/dist/chunks/onChangeAppState-4KOJMN82.js +1 -0
  134. package/dist/chunks/openai-C_6C1_0N.js +10 -0
  135. package/dist/chunks/overlayContext-CMV7nYR9.js +1 -0
  136. package/dist/chunks/{panel-Cm23FDVt.js → panel-D9fGQgln.js} +1 -1
  137. package/dist/chunks/parser-BKAVMTyD.js +1 -0
  138. package/dist/chunks/{parser-eVu-cTRs.js → parser-D8slvrJP.js} +1 -1
  139. package/dist/chunks/partition-B504IgAa.js +1 -0
  140. package/dist/chunks/pasteStore-DNV1M5Xd.js +1 -0
  141. package/dist/chunks/permissions-CLFMhdRk.js +3 -0
  142. package/dist/chunks/pidLock-D9do1Afy.js +3 -0
  143. package/dist/chunks/{plan-s228H7IU.js → plan-CQLnPLuE.js} +1 -1
  144. package/dist/chunks/{platform-DMQxcm4K.js → platform-Dzff1WWw.js} +1 -1
  145. package/dist/chunks/plugin-BYdF7uob.js +17 -0
  146. package/dist/chunks/{pluginAutoupdate-aLXhSUVD.js → pluginAutoupdate-BJaAqwTH.js} +1 -1
  147. package/dist/chunks/{pluginBlocklist-BprCv0En.js → pluginBlocklist-DKKmOnWM.js} +1 -1
  148. package/dist/chunks/pluginCliCommands-z8TtJMKH.js +1 -0
  149. package/dist/chunks/{pluginFlagging-BSLuTk3M.js → pluginFlagging-DQP8tBi2.js} +1 -1
  150. package/dist/chunks/pluginOperations-BcfJCDco.js +2 -0
  151. package/dist/chunks/{pluginStartupCheck-xQbHZ5gf.js → pluginStartupCheck-CfRvCrFg.js} +1 -1
  152. package/dist/chunks/pluginStartupCheck-Cq4PvULa.js +1 -0
  153. package/dist/chunks/plugins-CTM8jpOw.js +4 -0
  154. package/dist/chunks/policyLimits-a7ix6GnU.js +1 -0
  155. package/dist/chunks/poorMode-C11JEH3d.js +1 -0
  156. package/dist/chunks/{poorMode-Bt_A2arj.js → poorMode-J5SYJvoY.js} +1 -1
  157. package/dist/chunks/print-u6MzL5Cr.js +13 -0
  158. package/dist/chunks/processBashCommand-DIwrI2QC.js +1 -0
  159. package/dist/chunks/processSlashCommand-B-Gujpxm.js +5 -0
  160. package/dist/chunks/projectOnboardingState-CJycxw5P.js +1 -0
  161. package/dist/chunks/{prompt-BNNE5tsG.js → prompt-BGqgPgCU.js} +3 -3
  162. package/dist/chunks/prompt-BPJDGlx5.js +1 -0
  163. package/dist/chunks/prompt-DEdZzkEz.js +1 -0
  164. package/dist/chunks/promptEditor-CmQ9p4oe.js +4 -0
  165. package/dist/chunks/{protocolHandler-DukQ6b4Q.js → protocolHandler-CJo9-PfZ.js} +2 -2
  166. package/dist/chunks/{proxy-BhIc7-mj.js → proxy-CB17QimU.js} +2 -2
  167. package/dist/chunks/reconciler-DSKLuOS7.js +1 -0
  168. package/dist/chunks/refresh-BbZFCNpn.js +1 -0
  169. package/dist/chunks/registerProtocol-CLIpzVwF.js +1 -0
  170. package/dist/chunks/reload-plugins-DjugL8jH.js +1 -0
  171. package/dist/chunks/rename-DOtCOtEr.js +1 -0
  172. package/dist/chunks/{renderOptions-D-aQZbzS.js → renderOptions-Zqfm2U1y.js} +1 -1
  173. package/dist/chunks/resume-BB4T4WIV.js +2 -0
  174. package/dist/chunks/ripgrep-BuzOTf1S.js +5 -0
  175. package/dist/chunks/ripgrep-CZ2CqaHb.js +1 -0
  176. package/dist/chunks/{runtimeObserver-DS1PK6We.js → runtimeObserver-CK_iZ6OB.js} +1 -1
  177. package/dist/chunks/{runtimeObserver-CsZw5XBt.js → runtimeObserver-CpP0L9T9.js} +4 -4
  178. package/dist/chunks/sandbox-adapter-DhJJ6WOV.js +1 -0
  179. package/dist/chunks/sandbox-toggle-KOHYvbQT.js +1 -0
  180. package/dist/chunks/searchExtraTools-CdJghGkj.js +1 -0
  181. package/dist/chunks/select-C_KXmqbI.js +1 -0
  182. package/dist/chunks/sessionFileAccessHooks-D7KbWFp7.js +1 -0
  183. package/dist/chunks/sessionObserver-DB-sLv-X.js +1 -0
  184. package/dist/chunks/{sessionObserver-N7fORFdL.js → sessionObserver-WOYv2n7C.js} +2 -2
  185. package/dist/chunks/sessionStorage-sgOAbDn7.js +1 -0
  186. package/dist/chunks/{sessionTracing-fIp8g04N.js → sessionTracing-yBre24PH.js} +2 -2
  187. package/dist/chunks/settings-C-KNkvsM.js +1 -0
  188. package/dist/chunks/settings-DKN4xSpQ.js +24 -0
  189. package/dist/chunks/setup-CN_Pk7AR.js +3 -0
  190. package/dist/chunks/{shadowedRuleDetection-DEo1hvGi.js → shadowedRuleDetection-Df-kZ_pK.js} +1 -1
  191. package/dist/chunks/{sideQuestion-C11KgNGL.js → sideQuestion-CMB8hfgX.js} +3 -3
  192. package/dist/chunks/sinks-BS17vtN0.js +1 -0
  193. package/dist/chunks/sinks-D1EjkHb4.js +1 -0
  194. package/dist/chunks/skillChangeDetector-CBKuGuEi.js +1 -0
  195. package/dist/chunks/{skillGapStore-H4MkUFUY.js → skillGapStore-CfmlO6pb.js} +2 -2
  196. package/dist/chunks/{skillLifecycle-ADUTDK7D.js → skillLifecycle-BQ2LMfMx.js} +2 -2
  197. package/dist/chunks/{skillSearchPanel-PpfVDMGR.js → skillSearchPanel-BwYuwLFs.js} +4 -4
  198. package/dist/chunks/skills-BVHPQma0.js +1 -0
  199. package/dist/chunks/startupProfiler-B_U4QDtf.js +1 -0
  200. package/dist/chunks/startupProfiler-DTs9w9EN.js +3 -0
  201. package/dist/chunks/{state-D5D6QpTX.js → state-BowF111d.js} +1 -1
  202. package/dist/chunks/state-CGuyDES7.js +1 -0
  203. package/dist/chunks/status-BurdTfyz.js +2 -0
  204. package/dist/chunks/status-DMq1An5h.js +1 -0
  205. package/dist/chunks/statusNoticeHelpers-X75JNlx5.js +1 -0
  206. package/dist/chunks/stringUtils-BQm3OfeJ.js +4 -0
  207. package/dist/chunks/{switcher-DWfKi17X.js → switcher-Bq1Ct_Sn.js} +1 -1
  208. package/dist/chunks/switcher-DGD4ORVf.js +1 -0
  209. package/dist/chunks/{tasks-BwSsj2vI.js → tasks-0c8Uy04D.js} +1 -1
  210. package/dist/chunks/tempfile-CHO5wXsV.js +1 -0
  211. package/dist/chunks/{templateJobs-fiKuu4DK.js → templateJobs-BdFzE9XG.js} +1 -1
  212. package/dist/chunks/terminalSetup-Cf_r6pwK.js +32 -0
  213. package/dist/chunks/{terminalSetup-Cte5a4hM.js → terminalSetup-D7J6bxcn.js} +1 -1
  214. package/dist/chunks/{theme-CAoGjf2D.js → theme-Bby4fssR.js} +1 -1
  215. package/dist/chunks/tipRegistry-CyRXWWTz.js +2 -0
  216. package/dist/chunks/{toolEventObserver-Cq_ZV7x9.js → toolEventObserver-CzFZUIsM.js} +1 -1
  217. package/dist/chunks/toolPool-CnrZcprA.js +1 -0
  218. package/dist/chunks/types-zk5Ltv5q.js +81 -0
  219. package/dist/chunks/udsClient-ftP0yIpe.js +1 -0
  220. package/dist/chunks/use-select-navigation-DMaC_3iw.js +1 -0
  221. package/dist/chunks/useDoublePress-C9xxQzh1.js +1 -0
  222. package/dist/chunks/useExitOnCtrlCDWithKeybindings-CjW3gUOt.js +1 -0
  223. package/dist/chunks/useMainLoopModel-DWscpA9I.js +1 -0
  224. package/dist/chunks/useManagePlugins-CYXVcql2.js +1 -0
  225. package/dist/chunks/useMergedTools-DarmnCEw.js +1 -0
  226. package/dist/chunks/useSearchInput-C2JuUW3g.js +1 -0
  227. package/dist/chunks/useSettingsErrors-DutJBiKZ.js +1 -0
  228. package/dist/chunks/util-Bq5l7FF5.js +1 -0
  229. package/dist/chunks/validatePlugin-DIdEydz_.js +1 -0
  230. package/dist/chunks/{vim-xruiCyUd.js → vim-D8prM2IH.js} +1 -1
  231. package/dist/chunks/worktree-Caqt2WRZ.js +1 -0
  232. package/dist/cli.js +1 -1
  233. package/package.json +1 -1
  234. package/dist/chunks/AddWorkspaceDirectory-DgAxYgBY.js +0 -1
  235. package/dist/chunks/AgentsMdExternalIncludesDialog-DGMRVexR.js +0 -1
  236. package/dist/chunks/AgentsMdExternalIncludesDialog-Dp6CwZyI.js +0 -1
  237. package/dist/chunks/App-VWyPd524.js +0 -1
  238. package/dist/chunks/ApproveApiKey-Bolw0sPs.js +0 -1
  239. package/dist/chunks/ApproveApiKey-CyNPMd6g.js +0 -1
  240. package/dist/chunks/BackgroundTasksDialog-DxagIOOw.js +0 -2
  241. package/dist/chunks/BypassPermissionsModeDialog-OS2S66zQ.js +0 -1
  242. package/dist/chunks/DiffDialog-CMtml9iw.js +0 -6
  243. package/dist/chunks/Doctor-Bk9P37mU.js +0 -1
  244. package/dist/chunks/Doctor-D9F3tKsr.js +0 -3
  245. package/dist/chunks/ExitFlow-DhRv5JPj.js +0 -2
  246. package/dist/chunks/Grove-Bbh8PpH0.js +0 -11
  247. package/dist/chunks/HybridTransport-P1vEUwhv.js +0 -2
  248. package/dist/chunks/InvalidConfigDialog-xAYpE-20.js +0 -1
  249. package/dist/chunks/InvalidSettingsDialog-CXFSISy3.js +0 -1
  250. package/dist/chunks/MCPConnectionManager-CoId-C__.js +0 -1
  251. package/dist/chunks/MCPToolListView-BQkQ-hyF.js +0 -1
  252. package/dist/chunks/MessageSelector-BvRVrfg6.js +0 -3
  253. package/dist/chunks/Messages-Cykztq1O.js +0 -10
  254. package/dist/chunks/Onboarding-CfeRwPNQ.js +0 -1
  255. package/dist/chunks/PromptInputHelpMenu-Ckp0k8E3.js +0 -1
  256. package/dist/chunks/QueryEngine-DduzztIG.js +0 -1
  257. package/dist/chunks/REPL-B8e5UU3H.js +0 -128
  258. package/dist/chunks/REPL-C4mbOhyL.js +0 -1
  259. package/dist/chunks/RemoteSessionManager-BPESC6Wu.js +0 -2
  260. package/dist/chunks/ResumeConversation-DG1sLryB.js +0 -1
  261. package/dist/chunks/SSETransport-CDNP2PlK.js +0 -2
  262. package/dist/chunks/SearchExtraToolsTool-vK2PP628.js +0 -1
  263. package/dist/chunks/Settings-B7n_dfP-.js +0 -2
  264. package/dist/chunks/TeleportProgress-QL3ibQfK.js +0 -1
  265. package/dist/chunks/TeleportRepoMismatchDialog-f-xl7biD.js +0 -1
  266. package/dist/chunks/TeleportResumeWrapper-DzVcrFuP.js +0 -1
  267. package/dist/chunks/ThemePicker-CIFKZza0.js +0 -1
  268. package/dist/chunks/TrustDialog-C0HEwZPk.js +0 -1
  269. package/dist/chunks/add-dir-DmEhPnvj.js +0 -1
  270. package/dist/chunks/agents-D96ng5I9.js +0 -101
  271. package/dist/chunks/allErrors-CT2dbBF3.js +0 -1
  272. package/dist/chunks/api-DTyrmy1O.js +0 -1
  273. package/dist/chunks/api-DumFOErN.js +0 -1
  274. package/dist/chunks/auth-CZ4EsFWF.js +0 -10
  275. package/dist/chunks/auth-QvonHoG9.js +0 -1
  276. package/dist/chunks/auth-jV5THRH8.js +0 -1
  277. package/dist/chunks/backgroundHousekeeping-C72oPgfD.js +0 -17
  278. package/dist/chunks/backgroundHousekeeping-D9PScHES.js +0 -1
  279. package/dist/chunks/banner-ChT5Ri7Q.js +0 -2
  280. package/dist/chunks/bg-qG2osBbP.js +0 -9
  281. package/dist/chunks/branch-K8X6jx0i.js +0 -2
  282. package/dist/chunks/bridgeConfig-C-bI-slm.js +0 -1
  283. package/dist/chunks/bridgeConfig-_xpxhGB5.js +0 -1
  284. package/dist/chunks/bridgeMessaging-DSJlYarJ.js +0 -1
  285. package/dist/chunks/bridgePointer-DfTOjgtX.js +0 -1
  286. package/dist/chunks/bridgeStatusUtil-DaEq5c69.js +0 -1
  287. package/dist/chunks/btw-BNs5OX7x.js +0 -1
  288. package/dist/chunks/bundledMode--fG1S62b.js +0 -1
  289. package/dist/chunks/caches-CC5NHwAz.js +0 -1
  290. package/dist/chunks/caches-nHxJWXgO.js +0 -1
  291. package/dist/chunks/capacityWake-BpP6c7x3.js +0 -3
  292. package/dist/chunks/ccrClient-JnhF5b3z.js +0 -1
  293. package/dist/chunks/claudeDesktop-DPc_SaVn.js +0 -1
  294. package/dist/chunks/cliLaunch-DDtwAolw.js +0 -1
  295. package/dist/chunks/client-9uHzAmFH.js +0 -1
  296. package/dist/chunks/client-BVal_QII.js +0 -1
  297. package/dist/chunks/client-BtTkq0YS.js +0 -1
  298. package/dist/chunks/client-Dd7CKMRX.js +0 -1
  299. package/dist/chunks/commands-C_rYjyQZ.js +0 -1
  300. package/dist/chunks/compact-Cqd6vKpn.js +0 -2
  301. package/dist/chunks/config-Be0BkAAr.js +0 -1
  302. package/dist/chunks/config-DUTgj3js.js +0 -3
  303. package/dist/chunks/config-DoEDgAfv.js +0 -1
  304. package/dist/chunks/context-noninteractive-D9tJYwi7.js +0 -1
  305. package/dist/chunks/controlMessageCompat-IFu4Gc1y.js +0 -1
  306. package/dist/chunks/conversation-DWfE4KGH.js +0 -1
  307. package/dist/chunks/conversation-Tvo4EDpQ.js +0 -1
  308. package/dist/chunks/createSSHSession-BQ83MMtr.js +0 -5
  309. package/dist/chunks/createSession-CqHnHhCR.js +0 -1
  310. package/dist/chunks/createSession-DqTtBycR.js +0 -1
  311. package/dist/chunks/crossProjectResume-DIXtiODF.js +0 -40
  312. package/dist/chunks/cwd-DLK3znO7.js +0 -1
  313. package/dist/chunks/cwd-Nh5IZNKO.js +0 -1
  314. package/dist/chunks/debugUtils-DXBRbwCE.js +0 -1
  315. package/dist/chunks/detached-Biz-xhu0.js +0 -4
  316. package/dist/chunks/detectRepository-DUJBh5s2.js +0 -1
  317. package/dist/chunks/detectRepository-pRAVv8SH.js +0 -1
  318. package/dist/chunks/directoryCompletion-CuA3_YIT.js +0 -1
  319. package/dist/chunks/doctor-eNAm6OiS.js +0 -1
  320. package/dist/chunks/entry-DidpiR-D.js +0 -13
  321. package/dist/chunks/esm-BCUC71kt.js +0 -1
  322. package/dist/chunks/execSyncWrapper-C3ZFV9od.js +0 -1
  323. package/dist/chunks/exit-DywUeiYd.js +0 -1
  324. package/dist/chunks/extraUsage-DiAirtuk.js +0 -1
  325. package/dist/chunks/extractMemories-_xiTnX95.js +0 -1
  326. package/dist/chunks/fast-DCXZACT9.js +0 -1
  327. package/dist/chunks/fast-Qo4WVqiW.js +0 -1
  328. package/dist/chunks/fetchModelList-fQDsmR3E.js +0 -1
  329. package/dist/chunks/fetchModelList-woVzIVde.js +0 -1
  330. package/dist/chunks/fileSuggestions-CRx1D6uk.js +0 -3
  331. package/dist/chunks/firstPartyEventLogger-B261Wksn.js +0 -3
  332. package/dist/chunks/firstPartyEventLogger-DtFTeHy-.js +0 -1
  333. package/dist/chunks/flushGate-BA8dSr0i.js +0 -1
  334. package/dist/chunks/gemini-BXAyy1JN.js +0 -1
  335. package/dist/chunks/generateSessionName-Cwmk2N3F.js +0 -1
  336. package/dist/chunks/git-Wid-XppW.js +0 -5
  337. package/dist/chunks/git-hO-TMvXc.js +0 -1
  338. package/dist/chunks/githubRepoPathMapping-OV8U1VFK.js +0 -1
  339. package/dist/chunks/goal-C9clrwEH.js +0 -3
  340. package/dist/chunks/grok-CjeCecsZ.js +0 -1
  341. package/dist/chunks/grove-DqTnK9nn.js +0 -7
  342. package/dist/chunks/hash-Tu-My5Vp.js +0 -1
  343. package/dist/chunks/help-Bb6LdzXK.js +0 -1
  344. package/dist/chunks/hooks-BX2s7aoL.js +0 -1
  345. package/dist/chunks/initReplBridge-D7cuY_os.js +0 -1
  346. package/dist/chunks/install-eCA8UACi.js +0 -1
  347. package/dist/chunks/instrumentation-BaRKojJh.js +0 -21
  348. package/dist/chunks/jwtUtils-JE2okZ70.js +0 -1
  349. package/dist/chunks/keybindings-iBqc1KHL.js +0 -1
  350. package/dist/chunks/launchLocalMemory-IZPGEzMk.js +0 -3
  351. package/dist/chunks/launchOnboarding-BeNf51Ig.js +0 -8
  352. package/dist/chunks/lazySchema-DULtBUCI.js +0 -65
  353. package/dist/chunks/lib-BlVGipXx.js +0 -14
  354. package/dist/chunks/loadAgentsDir-Bpke9CtB.js +0 -1
  355. package/dist/chunks/localSearch-dodgnjGn.js +0 -1
  356. package/dist/chunks/log-CZ7ploQm.js +0 -1
  357. package/dist/chunks/logoUtils-Cg_6QV1Z.js +0 -1
  358. package/dist/chunks/main-7ssnA9Yb.js +0 -31
  359. package/dist/chunks/main-BEv6MqMX.js +0 -356
  360. package/dist/chunks/managedEnv-CHYvwXBH.js +0 -1
  361. package/dist/chunks/managedEnv-CbjOQmEe.js +0 -1
  362. package/dist/chunks/mappers-D8VLUZ2N.js +0 -1
  363. package/dist/chunks/mcp-BUn3yqsT.js +0 -1
  364. package/dist/chunks/mcp-BskLq9iP.js +0 -2
  365. package/dist/chunks/mcp-C-0DMaXx.js +0 -6
  366. package/dist/chunks/memoize-CumjjK2Q.js +0 -1
  367. package/dist/chunks/memory-vDkJM58W.js +0 -1
  368. package/dist/chunks/mode-Dbh21H2Y.js +0 -2
  369. package/dist/chunks/model-BaMclMXn.js +0 -1
  370. package/dist/chunks/model-atn3_JBi.js +0 -1
  371. package/dist/chunks/model-vS1Iewyq.js +0 -1
  372. package/dist/chunks/modelOptions-Cw1ThINb.js +0 -1
  373. package/dist/chunks/nativeInstaller-CfZ5uNTh.js +0 -1
  374. package/dist/chunks/oauth-D38aRTUb.js +0 -1
  375. package/dist/chunks/oauth-U649LV5H.js +0 -1
  376. package/dist/chunks/omit-B7eQ9q0x.js +0 -1
  377. package/dist/chunks/onChangeAppState-kEAt8nxV.js +0 -1
  378. package/dist/chunks/openai-wh8AX5iz.js +0 -10
  379. package/dist/chunks/parser-Cq9X7HMP.js +0 -1
  380. package/dist/chunks/partition-CENvOfiS.js +0 -1
  381. package/dist/chunks/permissions-ChuIx-d4.js +0 -3
  382. package/dist/chunks/pidLock-C1hmh3YQ.js +0 -3
  383. package/dist/chunks/plugin-DVBEWwMP.js +0 -17
  384. package/dist/chunks/pluginCliCommands-WzzqR1Sr.js +0 -1
  385. package/dist/chunks/pluginOperations-Ca9Lup5G.js +0 -2
  386. package/dist/chunks/pluginStartupCheck-DdtxcNwH.js +0 -1
  387. package/dist/chunks/plugins-DdIaXpNb.js +0 -4
  388. package/dist/chunks/pollConfig-2nFzv6Hy.js +0 -1
  389. package/dist/chunks/poorMode-ZIq2oz7q.js +0 -1
  390. package/dist/chunks/print-vxrRE1O2.js +0 -14
  391. package/dist/chunks/processBashCommand-ISucgwpi.js +0 -1
  392. package/dist/chunks/processSlashCommand-BnpXO_fI.js +0 -5
  393. package/dist/chunks/prompt-2AA5W7EH.js +0 -1
  394. package/dist/chunks/prompt-AXiS2LoO.js +0 -1
  395. package/dist/chunks/promptEditor-DT6egmcb.js +0 -4
  396. package/dist/chunks/rcDebugLog-DSchf3Hs.js +0 -1
  397. package/dist/chunks/reconciler-D3zyJCnV.js +0 -1
  398. package/dist/chunks/refresh-BSG0t4cf.js +0 -1
  399. package/dist/chunks/registerProtocol-BOEYaX-X.js +0 -1
  400. package/dist/chunks/reload-plugins-BFMRhbv8.js +0 -1
  401. package/dist/chunks/remoteBridgeCore-D5OwvmAz.js +0 -1
  402. package/dist/chunks/remoteManagedSettings-DyGVvvcW.js +0 -1
  403. package/dist/chunks/rename-BrEwj3Xw.js +0 -1
  404. package/dist/chunks/resume-DR5JbICs.js +0 -2
  405. package/dist/chunks/ripgrep-Dt4a91S5.js +0 -5
  406. package/dist/chunks/ripgrep-KTOU5s9J.js +0 -1
  407. package/dist/chunks/sandbox-adapter-BqDyWcol.js +0 -1
  408. package/dist/chunks/sandbox-toggle-B9f_0NQI.js +0 -1
  409. package/dist/chunks/searchExtraTools-2pIT2C8u.js +0 -1
  410. package/dist/chunks/session-wkRTfdo8.js +0 -2
  411. package/dist/chunks/sessionFileAccessHooks-DV22q9JO.js +0 -1
  412. package/dist/chunks/sessionIdCompat-Dgp6PW_1.js +0 -1
  413. package/dist/chunks/sessionObserver-BLJg0qm_.js +0 -1
  414. package/dist/chunks/sessionState-8jutEorw.js +0 -11
  415. package/dist/chunks/sessionStorage-DRV7IhZF.js +0 -1
  416. package/dist/chunks/sessionStoragePortable-x0Yn02-G.js +0 -3
  417. package/dist/chunks/settings-BowI3jp-.js +0 -19
  418. package/dist/chunks/settings-CHn0gJCG.js +0 -1
  419. package/dist/chunks/settingsSync-DF4JgSNc.js +0 -1
  420. package/dist/chunks/setup-UiEO9i7F.js +0 -3
  421. package/dist/chunks/shellQuote-Ddgr1vif.js +0 -4
  422. package/dist/chunks/sinks-DnLqRPEC.js +0 -1
  423. package/dist/chunks/sinks-mGBiINp8.js +0 -1
  424. package/dist/chunks/skillChangeDetector-Dc6YZXJE.js +0 -1
  425. package/dist/chunks/skills-DKtN17ch.js +0 -1
  426. package/dist/chunks/startupProfiler-B90b5vuq.js +0 -3
  427. package/dist/chunks/startupProfiler-DG2TN5R_.js +0 -1
  428. package/dist/chunks/state-BStOuCh4.js +0 -1
  429. package/dist/chunks/stats-D4LEtkrw.js +0 -1
  430. package/dist/chunks/status-0ZBx6Ls0.js +0 -2
  431. package/dist/chunks/status-BUJ4-omB.js +0 -1
  432. package/dist/chunks/statusNoticeHelpers-BrpQWj0l.js +0 -1
  433. package/dist/chunks/stringUtils-D7oJIyY2.js +0 -4
  434. package/dist/chunks/subprocessEnv-CNBOhlDV.js +0 -1
  435. package/dist/chunks/subprocessEnv-DtBCqQIo.js +0 -1
  436. package/dist/chunks/switcher-D7Ey5uIi.js +0 -1
  437. package/dist/chunks/syncCache-DUhciJLz.js +0 -1
  438. package/dist/chunks/teleport-DwZMevmQ.js +0 -1
  439. package/dist/chunks/terminalSetup-a7-BNS4T.js +0 -32
  440. package/dist/chunks/tmux-DA06aewY.js +0 -1
  441. package/dist/chunks/toolPool-mdsxlKWR.js +0 -1
  442. package/dist/chunks/trustedDevice-C1m--Yjw.js +0 -1
  443. package/dist/chunks/trustedDevice-CeDIk_ln.js +0 -1
  444. package/dist/chunks/types-APu4OCXJ.js +0 -17
  445. package/dist/chunks/udsClient-BcwsY0XE.js +0 -1
  446. package/dist/chunks/upstreamproxy-CTOuotLO.js +0 -10
  447. package/dist/chunks/useExitOnCtrlCDWithKeybindings-L5idX6Kz.js +0 -1
  448. package/dist/chunks/useMainLoopModel-VXeS2EC6.js +0 -1
  449. package/dist/chunks/useManagePlugins-CAXp5CfH.js +0 -1
  450. package/dist/chunks/useMergedTools-DYXrPTIA.js +0 -1
  451. package/dist/chunks/useSearchInput-Bxl4wGcZ.js +0 -1
  452. package/dist/chunks/useSettingsErrors-sbjsaT7k.js +0 -1
  453. package/dist/chunks/userAgent-NbKd-hN7.js +0 -1
  454. package/dist/chunks/util-DU63xTwZ.js +0 -1
  455. package/dist/chunks/validatePlugin-DQ_9OCpP.js +0 -1
  456. package/dist/chunks/which-B8rchd8P.js +0 -1
  457. package/dist/chunks/windowsPaths-BdhjMYTm.js +0 -1
  458. package/dist/chunks/windowsPaths-DtGZ83kH.js +0 -1
  459. package/dist/chunks/workSecret-CaM2yIJD.js +0 -1
  460. package/dist/chunks/workerRegistry-BBgquE8F.js +0 -2
  461. package/dist/chunks/worktree-C28I8mFB.js +0 -1
@@ -1 +0,0 @@
1
- import{l as e,o as t,u as n}from"./envUtils-DcaKZlRU.js";import{Js as r,Jw as i,Md as a,Pd as o,Rd as s,Ws as c,aE as l,br as u,ea as d,gw as f,oE as p,rr as m,vw as h}from"./loadAgentsDir-C96o6gCj.js";import{$ as g,Ut as _,ft as v}from"./state-D5D6QpTX.js";import{P as y,R as b,c as x,i as S,nt as ee,tt as C}from"./debug-D58GQBDG.js";import{c as te,h as ne,y as re}from"./config-DUTgj3js.js";import{O as w,i as ie,k as T,m as E,u as D}from"./git-Wid-XppW.js";import{g as O,m as k}from"./log-CZ7ploQm.js";import{n as A,r as j}from"./analytics-DJobLaWP.js";import{At as ae,Dr as M,Or as N,Pt as oe,St as se,ct as P,dn as F,fn as I}from"./model-BaMclMXn.js";import{C as L,c as ce,n as R,w as le}from"./sessionState-8jutEorw.js";import{a as ue,i as de,r as fe,t as z}from"./sessionIdCompat-Dgp6PW_1.js";import{a as B,i as pe,n as V,o as me,t as H}from"./bridgeConfig-C-bI-slm.js";import{a as U,o as W,r as G,s as K}from"./debugUtils-DXBRbwCE.js";import{a as q,i as J,n as he,t as Y}from"./createSession-DqTtBycR.js";import{n as ge,o as X}from"./mappers-D8VLUZ2N.js";import{n as _e,r as Z,t as Q}from"./sessionTitle-k4wpUS5l.js";import{a as ve,d as ye,f as be,i as xe,l as Se,n as Ce,o as we,r as Te,t as Ee,u as De}from"./bridgeMessaging-DSJlYarJ.js";import{i as Oe,n as ke,r as Ae,t as je}from"./flushGate-BA8dSr0i.js";import{n as Me,t as Ne}from"./pollConfig-2nFzv6Hy.js";import{n as Pe,t as Fe}from"./rcDebugLog-DSchf3Hs.js";import{a as Ie,i as Le,n as $,o as Re,r as ze,t as Be}from"./capacityWake-BpP6c7x3.js";import{a as Ve,n as He,r as Ue,t as We}from"./workSecret-CaM2yIJD.js";import{i as Ge}from"./trustedDevice-C1m--Yjw.js";import{t as Ke}from"./HybridTransport-P1vEUwhv.js";import{hostname as qe}from"os";import{randomUUID as Je}from"crypto";_(),k(),E(),ne(),N(),oe(),p(),a(),d(),u(),B(),J(),ge(),Z(),S(),Fe(),w(),A(),C(),z(),c(),L(),R(),t(),W(),b(),F();var Ye=2e3,Xe=6e4,Ze=900*1e3,Qe=0;async function $e(t){let{dir:i,machineName:a,branch:o,gitRepoUrl:s,title:c,baseUrl:l,sessionIngressUrl:u,workerType:d,getAccessToken:f,createSession:p,archiveSession:m,getCurrentTitle:h=()=>c,toSDKMessages:g=()=>{throw Error(`BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages — daemon callers that only use writeSdkMessages() never hit this path.`)},onAuth401:_,getPollIntervalConfig:v=()=>Me,initialHistoryCap:b=200,initialMessages:S,previouslyFlushedUUIDs:C,onInboundMessage:te,onPermissionResponse:ne,onInterrupt:re,onSetModel:w,onSetMaxThinkingTokens:ie,onSetPermissionMode:E,onStateChange:D,onUserMessage:O,perpetual:k,initialSSESequenceNum:A=0}=t,ae=++Qe,{writeBridgePointer:M,clearBridgePointer:N,readBridgePointer:oe}=await import(`./bridgePointer-DfTOjgtX.js`),se=k?await oe(i):null,P=se?.source===`repl`?se:null;x(`[bridge:repl] initBridgeCore #${ae} starting (initialMessages=${S?.length??0}${P?` perpetual prior=env:${P.environmentId}`:``})`);let F=ze({baseUrl:l,getAccessToken:f,runnerVersion:`0.0.21`,onDebug:x,onAuth401:_,getTrustedDeviceToken:Ge}),I={dir:i,machineName:a,branch:o,gitRepoUrl:s,maxSessions:1,spawnMode:`single-session`,verbose:!1,sandbox:!1,bridgeId:Je(),workerType:d,environmentId:Je(),reuseEnvironmentId:P?.environmentId,apiBaseUrl:l,sessionIngressUrl:u},L,R;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return K(`registration_failed`,`[bridge:repl] Environment registration failed: ${y(e)}`),P&&await N(i),D?.(`failed`,y(e)),null}x(`[bridge:repl] Environment registered: ${L}`),T(`info`,`bridge_repl_env_registered`),j(`tengu_bridge_repl_env_registered`,{});async function fe(e,t){if(L!==e)return x(`[bridge:repl] Env mismatch (requested ${e}, got ${L}) — cannot reconnect in place`),!1;let n=ue(t),r=n===t?[t]:[t,n];for(let e of r)try{return await F.reconnectSession(L,e),x(`[bridge:repl] Reconnected session ${e} in place on env ${L}`),!0}catch(t){x(`[bridge:repl] reconnectSession(${e}) failed: ${y(t)}`)}return x(`[bridge:repl] reconnectSession exhausted — falling through to fresh session`),!1}let z=P?await fe(P.environmentId,P.sessionId):!1;P&&!z&&await N(i);let B;if(z&&P){if(B=P.sessionId,x(`[bridge:repl] Perpetual session reused: ${B}`),S&&C)for(let e of S)C.add(e.uuid)}else{let e=await p({environmentId:L,title:c,gitRepoUrl:s,branch:o,signal:AbortSignal.timeout(15e3)});if(!e)return x(`[bridge:repl] Session creation failed, deregistering environment`),j(`tengu_bridge_repl_session_failed`,{}),await F.deregisterEnvironment(L).catch(()=>{}),D?.(`failed`,`Session creation failed`),null;B=e,x(`[bridge:repl] Session created: ${B}`)}await M(i,{sessionId:B,environmentId:L,source:`repl`}),T(`info`,`bridge_repl_session_created`),j(`tengu_bridge_repl_started`,{has_initial_messages:!!(S&&S.length>0),inProtectedNamespace:n()});let pe=new Set;if(S)for(let e of S)pe.add(e.uuid);let V=new Ee(2e3);for(let e of pe)V.add(e);let me=new Ee(2e3),H=new AbortController,U=null;ce(e=>{H.signal.aborted||U?.reportMetadata(e)},{replayCurrent:!0});let W=0,G=z?A:0,q=null,J=null,he=Be(H.signal),Y=he.wake,ge=he.signal,X=new je,_e=!O,Z=0,Q=null;async function ye(){if(Q)return Q;Q=be();try{return await Q}finally{Q=null}}async function be(){if(Z++,Pe(`doReconnect: attempt=${Z}/3 envId=${L} sessionId=${B} workId=${q}`),W++,x(`[bridge:repl] Reconnecting after env lost (attempt ${Z}/3)`),Z>3)return x(`[bridge:repl] Environment reconnect limit reached (3), giving up`),!1;if(U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}if(Y(),X.drop(),q){let e=q;if(await F.stopWork(L,e,!1).catch(()=>{}),q!==e)return x(`[bridge:repl] Poll loop recovered during stopWork await — deferring to it`),Z=0,!0;q=null,J=null}if(H.signal.aborted)return x(`[bridge:repl] Reconnect aborted by teardown`),!1;let e=L;I.reuseEnvironmentId=e;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return I.reuseEnvironmentId=void 0,x(`[bridge:repl] Environment re-registration failed: ${y(e)}`),!1}if(I.reuseEnvironmentId=void 0,x(`[bridge:repl] Re-registered: requested=${e} got=${L}`),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after env registration, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;if(U!==null)return x(`[bridge:repl] Poll loop recovered during registerBridgeEnvironment await — deferring to it`),Z=0,!0;if(await fe(e,B))return j(`tengu_bridge_repl_reconnected_in_place`,{}),Z=0,!0;if(L!==e&&j(`tengu_bridge_repl_env_expired_fresh_session`,{}),await m(B),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after archive, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;let t=h(),n=await p({environmentId:L,title:t,gitRepoUrl:s,branch:o,signal:AbortSignal.timeout(15e3)});return n?H.signal.aborted?(x(`[bridge:repl] Reconnect aborted after session creation, cleaning up`),await m(n),!1):(B=n,r(de(n)).catch(()=>{}),G=0,me.clear(),_e=!O,x(`[bridge:repl] Re-created session: ${B}`),await M(i,{sessionId:B,environmentId:L,source:`repl`}),C?.clear(),Z=0,!0):(x(`[bridge:repl] Session creation failed during reconnection`),!1)}function Se(){return f()}function De(){let e=X.end();if(e.length===0)return;if(!U){x(`[bridge:repl] Cannot drain ${e.length} pending message(s): no transport`);return}for(let t of e)V.add(t.uuid);let t=g(e).map(e=>({...e,session_id:B}));x(`[bridge:repl] Drained ${e.length} pending message(s) after flush`),U.writeBatch(t)}let Oe=null;function Ne(){Oe?.()}function Fe(e){if(Pe(`handleTransportPermanentClose: code=${e} transport=${U?`exists`:`null`} pollAborted=${H.signal.aborted}`),x(`[bridge:repl] Transport permanently closed: code=${e}`),j(`tengu_bridge_repl_ws_closed`,{code:e}),U){let e=U.getLastSequenceNum();e>G&&(G=e),U=null}Y();let t=X.drop();if(t>0&&x(`[bridge:repl] Dropping ${t} pending message(s) on transport close (code=${e})`,{level:`warn`}),e===1e3){D?.(`failed`,`session ended`),H.abort(),Ne();return}D?.(`reconnecting`,`Remote Control connection lost (code ${e})`),x(`[bridge:repl] Transport reconnect budget exhausted (code=${e}), attempting env reconnect`),ye().then(t=>{t||H.signal.aborted||(x(`[bridge:repl] reconnectEnvironmentWithSession resolved false — tearing down`),j(`tengu_bridge_repl_reconnect_failed`,{close_code:e}),D?.(`failed`,`reconnection failed`),Ne())})}et({api:F,getCredentials:()=>({environmentId:L,environmentSecret:R}),signal:H.signal,getPollIntervalConfig:v,onStateChange:D,getWsState:()=>U?.getStateLabel()??`null`,isAtCapacity:()=>U!==null,capacitySignal:ge,onFatalError:Ne,getHeartbeatInfo:()=>!q||!J?null:{environmentId:L,workId:q,sessionToken:J},onHeartbeatFatal:e=>{if(x(`[bridge:repl] heartbeatWork fatal (status=${e.status}) — tearing down work item for fast re-dispatch`),U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}X.drop(),q&&F.stopWork(L,q,!1).catch(e=>{x(`[bridge:repl] stopWork after heartbeat fatal: ${y(e)}`)}),q=null,J=null,Y(),D?.(`reconnecting`,`Work item lease expired, fetching fresh token`)},async onEnvironmentLost(){return await ye()?{environmentId:L,environmentSecret:R}:null},onWorkReceived:(t,n,r,a)=>{if(U?.isConnectedStatus()&&x(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${r})`),x(`[bridge:repl] Work received: workId=${r} workSessionId=${t} currentSessionId=${B} match=${Ve(t,B)}`),M(i,{sessionId:B,environmentId:L,source:`repl`}),!Ve(t,B)){x(`[bridge:repl] Rejecting foreign session: expected=${B} got=${t}`);return}q=r,J=n;let o=a||e(process.env.CLAUDE_BRIDGE_USE_CCR_V2),s;if(!o){if(s=Se(),!s){x(`[bridge:repl] No OAuth token available for session ingress, skipping work`);return}le(s)}if(j(`tengu_bridge_repl_work_received`,{}),U){let e=U;U=null;let t=e.getLastSequenceNum();t>G&&(G=t),e.close()}X.deactivate();let c=e=>xe(e,{transport:U,sessionId:B,onInterrupt:re,onSetModel:w,onSetMaxThinkingTokens:ie,onSetPermissionMode:E}),d=!1,f=e=>{U=e,e.setOnConnect(()=>{if(U===e){if(x(`[bridge:repl] Ingress transport connected`),j(`tengu_bridge_repl_ws_connected`,{}),!o){let e=Se();e&&le(e)}if(Re=!1,!d&&S&&S.length>0){d=!0;let t=b,n=S.filter(e=>ve(e)&&!C?.has(e.uuid)),r=t>0&&n.length>t?n.slice(-t):n;r.length<n.length&&(x(`[bridge:repl] Capped initial flush: ${n.length} -> ${r.length} (cap=${t})`),j(`tengu_bridge_repl_history_capped`,{eligible_count:n.length,capped_count:r.length}));let i=g(r);if(i.length>0){x(`[bridge:repl] Flushing ${i.length} initial message(s) via transport`);let t=i.map(e=>({...e,session_id:B})),n=e.droppedBatchCount;e.writeBatch(t).then(()=>{if(e.droppedBatchCount>n){x(`[bridge:repl] Initial flush dropped ${e.droppedBatchCount-n} batch(es) — not marking ${i.length} UUID(s) as flushed`);return}if(C)for(let e of i)e.uuid&&C.add(e.uuid)}).catch(e=>x(`[bridge:repl] Initial flush failed: ${e}`)).finally(()=>{U===e&&(De(),D?.(`connected`))})}else De(),D?.(`connected`)}else X.active||D?.(`connected`)}}),e.setOnData(e=>{try{let t=JSON.parse(e);Pe(`ingress: type=${t.type}${t.type===`control_request`?` subtype=${t.request?.subtype} request_id=${t.request_id}`:``}${t.type===`control_response`?` subtype=${t.response?.subtype} request_id=${t.response?.request_id}`:``}${t.type===`user`?` uuid=${t.uuid}`:``}${t.type===`keep_alive`?``:` len=${e.length}`}`)}catch{Pe(`ingress (non-JSON): ${String(e).slice(0,200)}`)}Te(e,V,me,te,ne,c)}),e.setOnClose(t=>{U===e&&(Pe(`transport onClose: code=${t} connected=${e.isConnectedStatus()} state=${e.getStateLabel()} seq=${e.getLastSequenceNum()}`),Fe(t))}),!d&&S&&S.length>0&&X.start(),e.connect()};if(W++,o){let e=We(l,t),r=W;x(`[bridge:repl] CCR v2: sessionUrl=${e} session=${t} gen=${r}`),Ae({sessionUrl:e,ingressToken:n,sessionId:t,initialSequenceNum:G}).then(e=>{if(H.signal.aborted){e.close();return}if(r!==W){x(`[bridge:repl] CCR v2: discarding stale handshake gen=${r} current=${W}`),e.close();return}f(e)},e=>{x(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${y(e)}`,{level:`error`}),j(`tengu_bridge_repl_ccr_v2_init_failed`,{}),r===W&&(q&&(F.stopWork(L,q,!1).catch(e=>{x(`[bridge:repl] stopWork after v2 init failure: ${y(e)}`)}),q=null,J=null),Y())})}else{let e=He(u,t);x(`[bridge:repl] Ingress URL: ${e}`),x(`[bridge:repl] Creating HybridTransport: session=${t}`);let n=s??``;f(ke(new Ke(new URL(e),{Authorization:`Bearer ${n}`,"anthropic-version":`2023-06-01`},t,()=>({Authorization:`Bearer ${Se()??n}`,"anthropic-version":`2023-06-01`}),{maxConsecutiveFailures:50,isBridge:!0,onBatchDropped:()=>{D?.(`reconnecting`,`Lost sync with Remote Control — events could not be delivered`),Y()}})))}}});let Ie=k?setInterval(()=>{Q||M(i,{sessionId:B,environmentId:L,source:`repl`})},60*6e4):null;Ie?.unref?.();let Le=v().session_keepalive_interval_v2_ms,$=Le>0?setInterval(()=>{U&&(x(`[bridge:repl] keep_alive sent`),U.write({type:`keep_alive`}).catch(e=>{x(`[bridge:repl] keep_alive write failed: ${y(e)}`)}))},Le):null;$?.unref?.();let Re=!1;Oe=async()=>{if(Re){x(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${L} session=${B}`);return}Re=!0;let e=Date.now();if(x(`[bridge:repl] Teardown starting: env=${L} session=${B} workId=${q??`none`} transportState=${U?.getStateLabel()??`null`}`),Ie!==null&&clearInterval(Ie),$!==null&&clearInterval($),H.abort(),x(`[bridge:repl] Teardown: poll loop aborted`),U){let e=U.getLastSequenceNum();e>G&&(G=e)}if(k){U=null,X.drop(),await M(i,{sessionId:B,environmentId:L,source:`repl`}),x(`[bridge:repl] Teardown (perpetual): leaving env=${L} session=${B} alive on server, duration=${Date.now()-e}ms`);return}let t=U;if(U=null,X.drop(),t){let e={...we(B),session_id:B};t.write(e)}let n=q?F.stopWork(L,q,!0).then(()=>{x(`[bridge:repl] Teardown: stopWork completed`)}).catch(e=>{x(`[bridge:repl] Teardown stopWork failed: ${y(e)}`)}):Promise.resolve();await Promise.all([n,m(B)]),t?.close(),x(`[bridge:repl] Teardown: transport closed`),await F.deregisterEnvironment(L).catch(e=>{x(`[bridge:repl] Teardown deregister failed: ${y(e)}`)}),await N(i),x(`[bridge:repl] Teardown complete: env=${L} duration=${Date.now()-e}ms`)};let Ue=ee(()=>Oe?.());return x(`[bridge:repl] Ready: env=${L} session=${B}`),D?.(`ready`),{get bridgeSessionId(){return B},get environmentId(){return L},getSSESequenceNum(){let e=U?.getLastSequenceNum()??0;return Math.max(G,e)},sessionIngressUrl:u,writeMessages(e){let t=e.filter(e=>ve(e)&&!pe.has(e.uuid)&&!V.has(e.uuid));if(t.length===0)return;if(!_e)for(let e of t){let t=Ce(e);if(t!==void 0&&O?.(t,B)){_e=!0;break}}if(X.enqueue(...t)){x(`[bridge:repl] Queued ${t.length} message(s) during initial flush`);return}if(!U){let e=t.map(e=>e.type).join(`,`);x(`[bridge:repl] Transport not configured, dropping ${t.length} message(s) [${e}] for session=${B}`,{level:`warn`});return}for(let e of t)V.add(e.uuid);x(`[bridge:repl] Sending ${t.length} message(s) via transport`);let n=g(t).map(e=>({...e,session_id:B}));U.writeBatch(n)},writeSdkMessages(e){let t=e.filter(e=>!e.uuid||!V.has(e.uuid));if(t.length===0)return;if(!U){x(`[bridge:repl] Transport not configured, dropping ${t.length} SDK message(s) for session=${B}`,{level:`warn`});return}for(let e of t)e.uuid&&V.add(e.uuid);let n=t.map(e=>({...e,session_id:B}));U.writeBatch(n)},sendControlRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_request`);return}let t={...e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_request request_id=${e.request_id}`)},sendControlResponse(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_response`);return}let t={...e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_response`)},sendControlCancelRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_cancel_request`);return}let t={type:`control_cancel_request`,request_id:e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_cancel_request request_id=${e}`)},sendResult(){if(!U){x(`[bridge:repl] sendResult: skipping, transport not configured session=${B}`);return}U.reportState(`idle`);let e={...we(B),session_id:B};U.write(e),x(`[bridge:repl] Sent result for session=${B}`)},async teardown(){Ue(),await Oe?.(),x(`[bridge:repl] Torn down`),j(`tengu_bridge_repl_teardown`,{})}}}async function et({api:e,getCredentials:t,signal:n,onStateChange:r,onWorkReceived:i,onEnvironmentLost:a,getWsState:o,isAtCapacity:s,capacitySignal:c,onFatalError:l,getPollIntervalConfig:u=()=>Me,getHeartbeatInfo:d,onHeartbeatFatal:f}){x(`[bridge:repl] Starting work poll loop for env=${t().environmentId}`);let p=0,m=null,h=null,g=0,_=!1;for(;!n.aborted;){let{environmentId:v,environmentSecret:b}=t(),S=u();try{let t=await e.pollForWork(v,b,n,S.reclaim_older_than_ms);if(g=0,p>0&&(x(`[bridge:repl] Poll recovered after ${p} consecutive error(s)`),p=0,m=null,h=null,r?.(`ready`)),!t){let t=_;if(_=!1,s?.()&&c&&!t){let t=S.poll_interval_ms_at_capacity;if(S.non_exclusive_heartbeat_interval_ms>0&&d){j(`tengu_bridge_heartbeat_mode_entered`,{heartbeat_interval_ms:S.non_exclusive_heartbeat_interval_ms});let r=t>0?Date.now()+t:null,i=!1,a=0;for(;!n.aborted&&s()&&(r===null||Date.now()<r);){let t=u();if(t.non_exclusive_heartbeat_interval_ms<=0)break;let n=d();if(!n)break;let r=c();try{await e.heartbeatWork(n.environmentId,n.workId,n.sessionToken)}catch(e){if(x(`[bridge:repl:heartbeat] Failed: ${y(e)}`),e instanceof $){r.cleanup(),j(`tengu_bridge_heartbeat_error`,{status:e.status,error_type:e.status===401||e.status===403?`auth_failed`:`fatal`}),f?(f(e),x(`[bridge:repl:heartbeat] Fatal (status=${e.status}), work state cleared — fast-polling for re-dispatch`)):i=!0;break}}a++,await I(t.non_exclusive_heartbeat_interval_ms,r.signal),r.cleanup()}let o=i?`error`:n.aborted?`shutdown`:s()?r!==null&&Date.now()>=r?`poll_due`:`config_disabled`:`capacity_changed`;if(j(`tengu_bridge_heartbeat_mode_exited`,{reason:o,heartbeat_cycles:a}),!i){o===`poll_due`&&x(`[bridge:repl] Heartbeat poll_due after ${a} cycles — falling through to pollForWork`);continue}}let r=t>0?t:S.non_exclusive_heartbeat_interval_ms;if(r>0){let e=c(),t=Date.now();await I(r,e.signal),e.cleanup();let n=Date.now()-t-r;n>6e4&&(x(`[bridge:repl] At-capacity sleep overran by ${Math.round(n/1e3)}s — process suspension detected, forcing one fast-poll cycle`),j(`tengu_bridge_repl_suspension_detected`,{overrun_ms:n}),_=!0)}}else await I(S.poll_interval_ms_not_at_capacity,n);continue}let a;try{a=Ue(t.secret)}catch(n){x(`[bridge:repl] Failed to decode work secret: ${y(n)}`),j(`tengu_bridge_repl_work_secret_failed`,{}),await e.stopWork(v,t.id,!1).catch(()=>{});continue}x(`[bridge:repl] Acknowledging workId=${t.id}`);try{await e.acknowledgeWork(v,t.id,a.session_ingress_token)}catch(e){x(`[bridge:repl] Acknowledge failed workId=${t.id}: ${y(e)}`)}if(t.data.type===`healthcheck`){x(`[bridge:repl] Healthcheck received`);continue}if(t.data.type===`session`){let e=t.data.id;try{Re(e,`session_id`)}catch{x(`[bridge:repl] Invalid session_id in work: ${e}`);continue}i(e,a.session_ingress_token,t.id,a.use_code_sessions===!0),x(`[bridge:repl] Work accepted, continuing poll loop`)}}catch(i){if(n.aborted)break;if(i instanceof $&&i.status===404&&a){let e=t().environmentId;if(v!==e){x(`[bridge:repl] Stale poll error for old env=${v}, current env=${e} — skipping onEnvironmentLost`),p=0,m=null;continue}if(g++,x(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${g}/3)`),j(`tengu_bridge_repl_env_lost`,{attempt:g}),g>3){x(`[bridge:repl] Environment re-registration limit reached (3), giving up`),r?.(`failed`,`Environment deleted and re-registration limit reached`),l?.();break}r?.(`reconnecting`,`environment lost, recreating session`);let i=await a();if(n.aborted)break;if(i){p=0,m=null,r?.(`ready`),x(`[bridge:repl] Re-registered environment: ${i.environmentId}`);continue}r?.(`failed`,`Environment deleted and re-registration failed`),l?.();break}if(i instanceof $){let e=Le(i.errorType),t=Ie(i);x(`[bridge:repl] Fatal poll error: ${i.message} (status=${i.status}, type=${i.errorType??`unknown`})${t?` (suppressed)`:``}`),j(`tengu_bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),T(e?`info`:`error`,`bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),t||r?.(`failed`,e?`session expired · /remote-control to reconnect`:i.message),l?.();break}let s=Date.now();h!==null&&s-h>6e4*2&&(x(`[bridge:repl] Detected system sleep (${Math.round((s-h)/1e3)}s gap), resetting poll error budget`),T(`info`,`bridge_repl_poll_sleep_detected`,{gapMs:s-h}),p=0,m=null),h=s,p++,m===null&&(m=s);let c=s-m,f=U(i),_=G(i),y=o?.()??`unknown`;if(x(`[bridge:repl] Poll error (attempt ${p}, elapsed ${Math.round(c/1e3)}s, ws=${y}): ${_}`),j(`tengu_bridge_repl_poll_error`,{status:f,consecutiveErrors:p,elapsedMs:c}),p===1&&r?.(`reconnecting`,_),c>=9e5){x(`[bridge:repl] Poll failures exceeded ${Ze/1e3}s (${p} errors), giving up`),T(`info`,`bridge_repl_poll_give_up`),j(`tengu_bridge_repl_poll_give_up`,{consecutiveErrors:p,elapsedMs:c,lastStatus:f}),r?.(`failed`,`connection to server lost`);break}let b=Math.min(Ye*2**(p-1),Xe);if(u().non_exclusive_heartbeat_interval_ms>0){let t=d?.();if(t)try{await e.heartbeatWork(t.environmentId,t.workId,t.sessionToken)}catch{}}await I(b,n)}}x(`[bridge:repl] Work poll loop ended (aborted=${n.aborted}) env=${t().environmentId}`)}S(),b(),W(),z();async function tt(e){let{onInboundMessage:t,onPermissionResponse:n,onInterrupt:r,onSetModel:a,onSetMaxThinkingTokens:c,onSetPermissionMode:u,onStateChange:d,initialMessages:p,getMessages:_,previouslyFlushedUUIDs:b,initialName:S,perpetual:ee,outboundOnly:C,tags:ne}=e??{};if(fe(ye),!await De())return K(`not_enabled`,`[bridge:repl] Skipping: bridge not enabled`),null;if(!H())return K(`no_oauth`,`[bridge:repl] Skipping: no OAuth tokens`),d?.(`failed`,`authentication required`),null;if(await s(),!o(`allow_remote_control`))return K(`policy_denied`,`[bridge:repl] Skipping: allow_remote_control policy not allowed`),d?.(`failed`,`disabled by your organization's policy`),null;if(!pe()){let e=te();if(e.bridgeOauthDeadExpiresAt!=null&&(e.bridgeOauthDeadFailCount??0)>=3&&se()?.expiresAt===e.bridgeOauthDeadExpiresAt)return x(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${e.bridgeOauthDeadFailCount} times)`),null;await P();let t=se();if(t&&t.expiresAt!==null&&t.expiresAt<=Date.now()){K(`oauth_expired_unrefreshable`,`[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)`),d?.(`failed`,`authentication required`);let e=t.expiresAt;return re(t=>({...t,bridgeOauthDeadExpiresAt:e,bridgeOauthDeadFailCount:t.bridgeOauthDeadExpiresAt===e?(t.bridgeOauthDeadFailCount??0)+1:1})),null}}let w=V(),T=`remote-control-${l()}`,E=!1,O=!1;if(S)T=S,E=!0,O=!0;else{let e=v(),t=e?m(e):void 0;if(t)T=t,E=!0,O=!0;else if(p&&p.length>0)for(let e=p.length-1;e>=0;e--){let t=p[e];if(t.type!==`user`||t.isMeta||t.toolUseResult||t.isCompactSummary||t.origin&&t.origin.kind!==`human`||i(t))continue;let n=f(t.message.content);if(!n)continue;let r=rt(n);if(r){T=r,E=!0;break}}}let k=0,A,j=0,N=(e,t,n)=>{E=!0,T=e,x(`[bridge:repl] derived title from message ${n}: ${e}`),q(t,e,{baseUrl:w,getAccessToken:H}).catch(()=>{})},oe=(e,t)=>{let n=++j,r=k;_e(e,AbortSignal.timeout(15e3)).then(e=>{e&&n===j&&A===t&&!m(v())&&N(e,t,r)})},F=(e,t)=>{if(O||m(v()))return!0;if(A!==void 0&&A!==t&&(k=0),A=t,k++,k===1&&!E){let n=rt(e);n&&N(n,t,k),oe(e,t)}else if(k===3){let n=_?.(),r=n?Q(h(n)):e;oe(r,t)}return k>=3},I=me()?`self-hosted`:await M();if(!I)return K(`no_org_uuid`,`[bridge:repl] Skipping: no org UUID`),d?.(`failed`,`/login`),null;if(be()&&!ee){let e=await Oe();if(e)return K(`version_too_old`,`[bridge:repl] Skipping: ${e}`,!0),d?.(`failed`,"run `claude update` to upgrade"),null;x(`[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)`);let{initEnvLessBridgeCore:i}=await import(`./remoteBridgeCore-D5OwvmAz.js`);return i({baseUrl:w,orgUUID:I,title:T,getAccessToken:H,onAuth401:ae,toSDKMessages:X,initialHistoryCap:200,initialMessages:p,onInboundMessage:t,onUserMessage:F,onPermissionResponse:n,onInterrupt:r,onSetModel:a,onSetMaxThinkingTokens:c,onSetPermissionMode:u,onStateChange:d,outboundOnly:C,tags:ne})}let L=Se();if(L)return K(`version_too_old`,`[bridge:repl] Skipping: ${L}`),d?.(`failed`,"run `claude update` to upgrade"),null;let ce=await ie(),R=await D(),le=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||w;return $e({dir:g(),machineName:qe(),branch:ce,gitRepoUrl:R,title:T,baseUrl:w,sessionIngressUrl:le,workerType:`claude_code`,getAccessToken:H,createSession:e=>he({...e,events:[],baseUrl:w,getAccessToken:H}),archiveSession:e=>Y(e,{baseUrl:w,getAccessToken:H,timeoutMs:1500}).catch(e=>{x(`[bridge:repl] archiveBridgeSession threw: ${y(e)}`,{level:`error`})}),getCurrentTitle:()=>m(v())??T,onUserMessage:F,toSDKMessages:X,onAuth401:ae,getPollIntervalConfig:Ne,initialHistoryCap:200,initialMessages:p,previouslyFlushedUUIDs:b,onInboundMessage:t,onPermissionResponse:n,onInterrupt:r,onSetModel:a,onSetMaxThinkingTokens:c,onSetPermissionMode:u,onStateChange:d,perpetual:ee})}var nt=50;function rt(e){let t=O(e),n=(/^(.*?[.!?])\s/.exec(t)?.[1]??t).replace(/\s+/g,` `).trim();if(n)return n.length>nt?`${n.slice(0,nt-1)}\u2026`:n}export{tt as initReplBridge};
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-DaDcL9Zw.js";import{I as t,P as n,ai as r,kn as i,s as a,t as o}from"./src-DL3w8VPk.js";import{t as s}from"./jsx-runtime-Bb4Xn-E0.js";import{P as c,R as l,c as u,i as d}from"./debug-D58GQBDG.js";import{Gt as f,Jt as p,b as m,h,t as g}from"./settings-BowI3jp-.js";import{n as _,r as v}from"./analytics-DJobLaWP.js";import{a as y,n as b,r as x,s as S,t as C}from"./nativeInstaller-CfZ5uNTh.js";import{join as w}from"node:path";import{homedir as T}from"node:os";var E=e(r(),1);_(),o(),d(),p(),l(),C(),h();var D=s();function O(){let e=f.platform===`win32`,t=T();return e?w(t,`.local`,`bin`,`claude.exe`).replace(/\//g,`\\`):`~/.local/bin/claude`}function k({messages:e}){return e.length===0?null:(0,D.jsxs)(t,{flexDirection:`column`,gap:0,marginBottom:1,children:[(0,D.jsx)(t,{children:(0,D.jsxs)(n,{color:`warning`,children:[(0,D.jsx)(a,{status:`warning`,withSpace:!0}),`Setup notes:`]})}),e.map((e,r)=>(0,D.jsx)(t,{marginLeft:2,children:(0,D.jsxs)(n,{dimColor:!0,children:[`• `,e]})},r))]})}function A({onDone:e,force:r,target:i}){let[o,s]=(0,E.useState)({type:`checking`});return(0,E.useEffect)(()=>{async function e(){try{u(`Install: Starting installation process (force=${r}, target=${i})`);let e=i||g()?.autoUpdatesChannel||`latest`;s({type:`installing`,version:e}),u(`Install: Calling installLatest(channelOrVersion=${e}, forceReinstall=${r})`);let t=await S(e,r);if(u(`Install: installLatest returned version=${t.latestVersion}, wasUpdated=${t.wasUpdated}, lockFailed=${t.lockFailed}`),t.lockFailed)throw Error(`Could not install - another process is currently installing Work Mate. Please try again in a moment.`);t.latestVersion||u(`Install: Failed to retrieve version information during install`,{level:`error`}),t.wasUpdated||u(`Install: Already up to date`),s({type:`setting-up`});let n=await b(!0);u(`Install: Setup launcher completed with ${n.length} messages`),n.length>0&&n.forEach(e=>u(`Install: Setup message: ${e.message}`)),u(`Install: Cleaning up npm installations after successful install`);let{removed:a,errors:o,warnings:c}=await x();a>0&&u(`Cleaned up ${a} npm installation(s)`),o.length>0&&u(`Cleanup errors: ${o.join(`, `)}`);let l=await y();l.length>0&&u(`Shell alias cleanup: ${l.map(e=>e.message).join(`; `)}`),v(`tengu_claude_install_command`,{has_version:+!!t.latestVersion,forced:+!!r}),(i===`latest`||i===`stable`)&&(m(`userSettings`,{autoUpdatesChannel:i}),u(`Install: Saved autoUpdatesChannel=${i} to user settings`));let d=[...c,...l.map(e=>e.message)];n.length>0?(s({type:`set-up`,messages:n.map(e=>e.message)}),setTimeout(s,2e3,{type:`success`,version:t.latestVersion||`current`,setupMessages:[...n.map(e=>e.message),...d]})):(u(`Install: Shell PATH already configured`),s({type:`success`,version:t.latestVersion||`current`,setupMessages:d.length>0?d:void 0}))}catch(e){u(`Install command failed: ${e}`,{level:`error`}),s({type:`error`,message:c(e)})}}e()},[r,i]),(0,E.useEffect)(()=>{o.type===`success`?setTimeout(e,2e3,`Work Mate installation completed successfully`,{display:`system`}):o.type===`error`&&setTimeout(e,3e3,`Work Mate installation failed`,{display:`system`})},[o,e]),(0,D.jsxs)(t,{flexDirection:`column`,marginTop:1,children:[o.type===`checking`&&(0,D.jsx)(n,{color:`claude`,children:`Checking installation status...`}),o.type===`cleaning-npm`&&(0,D.jsx)(n,{color:`warning`,children:`Cleaning up old npm installations...`}),o.type===`installing`&&(0,D.jsxs)(n,{color:`claude`,children:[`Installing Work Mate native build `,o.version,`...`]}),o.type===`setting-up`&&(0,D.jsx)(n,{color:`claude`,children:`Setting up launcher and shell integration...`}),o.type===`set-up`&&(0,D.jsx)(k,{messages:o.messages}),o.type===`success`&&(0,D.jsxs)(t,{flexDirection:`column`,gap:1,children:[(0,D.jsxs)(t,{children:[(0,D.jsx)(a,{status:`success`,withSpace:!0}),(0,D.jsx)(n,{color:`success`,bold:!0,children:`Work Mate successfully installed!`})]}),(0,D.jsxs)(t,{marginLeft:2,flexDirection:`column`,gap:1,children:[o.version!==`current`&&(0,D.jsxs)(t,{children:[(0,D.jsx)(n,{dimColor:!0,children:`Version: `}),(0,D.jsx)(n,{color:`claude`,children:o.version})]}),(0,D.jsxs)(t,{children:[(0,D.jsx)(n,{dimColor:!0,children:`Location: `}),(0,D.jsx)(n,{color:`text`,children:O()})]})]}),(0,D.jsx)(t,{marginLeft:2,flexDirection:`column`,gap:1,children:(0,D.jsxs)(t,{marginTop:1,children:[(0,D.jsx)(n,{dimColor:!0,children:`Next: Run `}),(0,D.jsx)(n,{color:`claude`,bold:!0,children:`claude --help`}),(0,D.jsx)(n,{dimColor:!0,children:` to get started`})]})}),o.setupMessages&&(0,D.jsx)(k,{messages:o.setupMessages})]}),o.type===`error`&&(0,D.jsxs)(t,{flexDirection:`column`,gap:1,children:[(0,D.jsxs)(t,{children:[(0,D.jsx)(a,{status:`error`,withSpace:!0}),(0,D.jsx)(n,{color:`error`,children:`Installation failed`})]}),(0,D.jsx)(n,{color:`error`,children:o.message}),(0,D.jsx)(t,{marginTop:1,children:(0,D.jsx)(n,{dimColor:!0,children:`Try running with --force to override checks`})})]})]})}var j={type:`local-jsx`,name:`install`,description:`安装 Work Mate 原生构建`,argumentHint:`[options]`,async call(e,t,n){let r=n.includes(`--force`),a=n.filter(e=>!e.startsWith(`--`))[0],{unmount:o}=await i((0,D.jsx)(A,{onDone:(t,n)=>{o(),e(t,n)},force:r,target:a}))}};export{j as install};
@@ -1,21 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-DaDcL9Zw.js";import{l as t,o as n}from"./envUtils-DcaKZlRU.js";import{n as r,t as i}from"./defineProperty-C-QyHrDq.js";import{E as a,M as o,S as s,b as c,d as l,h as u,i as d,l as f,n as p,p as ee,s as m,v as te,w as h,y as ne}from"./esm-lWlUmoUA.js";import{A as g,C as re,S as ie,b as _,v as ae,w as oe,x as se,y as ce}from"./esm-BbMeEYcz.js";import{A as le,B as v,C as ue,D as de,E as fe,I as y,K as pe,L as b,M as me,N as he,O as ge,P as x,R as _e,U as ve,W as S,_ as C,b as ye,c as be,d as xe,h as Se,i as Ce,k as w,mt as T,n as we,o as Te,p as Ee,pt as De,q as Oe,t as ke,u as Ae,v as E,w as D,y as je}from"./esm-BCUC71kt.js";import{n as Me,t as Ne}from"./axios-DaWTGg7G.js";import{K as Pe,Nt as O,Pn as Fe,R as Ie,Ut as Le,Y as Re,fn as ze,kn as Be,nr as Ve}from"./state-D5D6QpTX.js";import{C as He,P as Ue,R as We,U as Ge,c as k,i as A,nt as Ke,r as qe,tt as Je,x as Ye}from"./debug-D58GQBDG.js";import{d as Xe,h as Ze}from"./settings-BowI3jp-.js";import{c as Qe,h as $e,n as et,y as tt}from"./config-DUTgj3js.js";import{d as nt,f as rt,o as it,s as j}from"./log-CZ7ploQm.js";import{r as at,t as ot}from"./memoize-CumjjK2Q.js";import{a as st,i as ct,o as lt}from"./platform-DMQxcm4K.js";import{n as ut,r as dt}from"./startupProfiler-B90b5vuq.js";import{Et as ft,Ft as pt,Nt as mt,Pt as ht,Xn as gt,Zn as _t,kt as vt,qn as yt,zt as bt}from"./model-BaMclMXn.js";import{_ as xt,b as St,h as Ct,l as wt,o as Tt,p as Et,u as Dt,v as Ot,y as kt}from"./proxy-BhIc7-mj.js";import{n as At,t as jt}from"./userAgent-NbKd-hN7.js";import{C as Mt,S as Nt,_ as Pt,c as Ft,g as It,l as Lt,r as Rt}from"./sessionTracing-fIp8g04N.js";var M;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(M||(M={}));var N;(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`})(N||(N={}));var P;(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(P||(P={}));function zt(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function Bt(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}var Vt=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};function F(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new Vt(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Ht(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Ut(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 Wt(e,t){return e.toLowerCase()===t.toLowerCase()}var I;(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`})(I||(I={})),r();var Gt=class{constructor(){i(this,`kind`,I.DROP)}createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}};r();function Kt(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 qt=class{constructor(e,t,n=!0,r=Kt(t)){i(this,`startTime`,void 0),i(this,`_boundaries`,void 0),i(this,`_recordMinMax`,void 0),i(this,`_current`,void 0),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}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=Ut(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Jt=class{constructor(e,t){i(this,`kind`,I.HISTOGRAM),i(this,`_boundaries`,void 0),i(this,`_recordMinMax`,void 0),this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new qt(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 qt(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 qt(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:P.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===N.GAUGE||e.type===N.UP_DOWN_COUNTER||e.type===N.OBSERVABLE_GAUGE||e.type===N.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}}})}}};r();var Yt=class e{constructor(e=new Xt,t=0,n=0,r=0){i(this,`backing`,void 0),i(this,`indexBase`,void 0),i(this,`indexStart`,void 0),i(this,`indexEnd`,void 0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=r}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))}},Xt=class e{constructor(e=[0]){i(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])}},Zt=2146435072,Qt=1048575,$t=1023,en=-1022,tn=$t,nn=2**-1022;function rn(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&Zt)>>20)-$t}function an(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),r=t.getUint32(4);return(n&Qt)*2**32+r}function on(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function sn(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var L=class extends Error{};r();var cn=class{constructor(e){i(this,`_shift`,void 0),this._shift=-e}mapToIndex(e){return e<nn?this._minNormalLowerBoundaryIndex():rn(e)+this._rightShift(an(e)-1,52)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new L(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new L(`overflow: ${e} is > maximum lower boundary: ${n}`);return on(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=en>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return tn>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}};r();var ln=class{constructor(e){i(this,`_scale`,void 0),i(this,`_scaleFactor`,void 0),i(this,`_inverseFactor`,void 0),this._scale=e,this._scaleFactor=on(Math.LOG2E,e),this._inverseFactor=on(Math.LN2,-e)}mapToIndex(e){if(e<=nn)return this._minNormalLowerBoundaryIndex()-1;if(an(e)===0)return(rn(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 L(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return nn;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new L(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return en<<this._scale}_maxNormalLowerBoundaryIndex(){return(tn+1<<this._scale)-1}},un=-10,dn=20,fn=Array.from({length:31},(e,t)=>t>10?new ln(t-10):new cn(t-10));function pn(e){if(e>dn||e<un)throw new L(`expected scale >= ${un} && <= ${dn}, got: ${e}`);return fn[e+10]}p(),r();var R=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}constructor(e,t){i(this,`low`,void 0),i(this,`high`,void 0),this.low=e,this.high=t}},mn=20,hn=160,gn=2,_n=class e{constructor(e,t=hn,n=!0,r=0,a=0,o=0,s=1/0,c=-1/0,l=new Yt,u=new Yt,d=pn(mn)){i(this,`startTime`,void 0),i(this,`_maxSize`,void 0),i(this,`_recordMinMax`,void 0),i(this,`_sum`,void 0),i(this,`_count`,void 0),i(this,`_zeroCount`,void 0),i(this,`_min`,void 0),i(this,`_max`,void 0),i(this,`_positive`,void 0),i(this,`_negative`,void 0),i(this,`_mapping`,void 0),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=a,this._zeroCount=o,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<gn&&(m.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
2
- changing to the minimum size of: ${gn}`),this._maxSize=gn)}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=sn(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=pn(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=R.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=R.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 R(0,-1);let r=t-n;return new R(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()}},vn=class{constructor(e,t){i(this,`kind`,I.EXPONENTIAL_HISTOGRAM),i(this,`_maxSize`,void 0),i(this,`_recordMinMax`,void 0),this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new _n(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:P.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===N.GAUGE||e.type===N.UP_DOWN_COUNTER||e.type===N.OBSERVABLE_GAUGE||e.type===N.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}}})}}};E(),r();var yn=class{constructor(e,t=0,n=[0,0]){i(this,`startTime`,void 0),i(this,`_current`,void 0),i(this,`sampleTime`,void 0),this.startTime=e,this._current=t,this.sampleTime=n}record(e){this._current=e,this.sampleTime=x(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},bn=class{constructor(){i(this,`kind`,I.LAST_VALUE)}createAccumulation(e){return new yn(e)}merge(e,t){let n=w(t.sampleTime)>=w(e.sampleTime)?t:e;return new yn(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=w(t.sampleTime)>=w(e.sampleTime)?t:e;return new yn(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:P.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}};r();var z=class{constructor(e,t,n=0,r=!1){i(this,`startTime`,void 0),i(this,`monotonic`,void 0),i(this,`_current`,void 0),i(this,`reset`,void 0),this.startTime=e,this.monotonic=t,this._current=n,this.reset=r}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},xn=class{constructor(e){i(this,`kind`,I.SUM),i(this,`monotonic`,void 0),this.monotonic=e}createAccumulation(e){return new z(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new z(t.startTime,this.monotonic,r,t.reset):new z(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new z(t.startTime,this.monotonic,r,!0):new z(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:P.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}};p(),r();var Sn=class e{createAggregator(t){return e.DEFAULT_INSTANCE}};i(Sn,`DEFAULT_INSTANCE`,new Gt);var Cn=class e{createAggregator(t){switch(t.type){case N.COUNTER:case N.OBSERVABLE_COUNTER:case N.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}};i(Cn,`MONOTONIC_INSTANCE`,new xn(!0)),i(Cn,`NON_MONOTONIC_INSTANCE`,new xn(!1));var wn=class e{createAggregator(t){return e.DEFAULT_INSTANCE}};i(wn,`DEFAULT_INSTANCE`,new bn);var Tn=class e{createAggregator(t){return e.DEFAULT_INSTANCE}};i(Tn,`DEFAULT_INSTANCE`,new Jt([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0));var En=class{constructor(e,t=!0){if(i(this,`_boundaries`,void 0),i(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),r=e.indexOf(1/0);r===-1&&(r=void 0),this._boundaries=e.slice(n+1,r),this._recordMinMax=t}createAggregator(e){return new Jt(this._boundaries,this._recordMinMax)}},Dn=class{constructor(e=160,t=!0){i(this,`_maxSize`,void 0),i(this,`_recordMinMax`,void 0),this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new vn(this._maxSize,this._recordMinMax)}},On=class{_resolve(e){switch(e.type){case N.COUNTER:case N.UP_DOWN_COUNTER:case N.OBSERVABLE_COUNTER:case N.OBSERVABLE_UP_DOWN_COUNTER:return An;case N.GAUGE:case N.OBSERVABLE_GAUGE:return jn;case N.HISTOGRAM:return e.advice.explicitBucketBoundaries?new En(e.advice.explicitBucketBoundaries):Mn}return m.warn(`Unable to recognize instrument type: ${e.type}`),kn}createAggregator(e){return this._resolve(e).createAggregator(e)}},kn=new Sn,An=new Cn,jn=new wn,Mn=new Tn;new Dn;var Nn=new On,B;(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`})(B||(B={}));function Pn(e){switch(e.type){case B.DEFAULT:return Nn;case B.DROP:return kn;case B.SUM:return An;case B.LAST_VALUE:return jn;case B.EXPONENTIAL_HISTOGRAM:{let t=e;return new Dn(t.options?.maxSize,t.options?.recordMinMax)}case B.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?Mn:new En(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var Fn=e=>({type:B.DEFAULT}),In=e=>M.CUMULATIVE,Ln=`otel.component.name`,Rn=`otel.component.type`,zn=`periodic_metric_reader`,Bn=`otel.sdk.metric_reader.collection.duration`,Vn=`error.type`;r();var Hn=new Map,Un=class{constructor(e,t){i(this,`collectionDuration`,void 0),i(this,`standardAttrs`,void 0);let n=Hn.get(e)??0;Hn.set(e,n+1),this.standardAttrs={[Rn]:e,[Ln]:`${e}/${n}`},this.collectionDuration=t.createHistogram(Bn,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[Vn]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}},Wn=`2.9.0`;p(),E(),r();var Gn=class{constructor(e){i(this,`_shutdown`,!1),i(this,`_metricProducers`,void 0),i(this,`_sdkMetricProducer`,void 0),i(this,`_selfObsMetrics`,void 0),i(this,`_aggregationTemporalitySelector`,void 0),i(this,`_aggregationSelector`,void 0),i(this,`_cardinalitySelector`,void 0),i(this,`_otelComponentType`,void 0),this._aggregationSelector=e?.aggregationSelector??Fn,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??In,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new Un(this._otelComponentType,a())}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}_setSelfObsMeterProvider(e){let t=e.getMeter(`@opentelemetry/sdk-metrics`,Wn);this._selfObsMetrics=new Un(this._otelComponentType,t)}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=de(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=de(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=le(ge(t,i));return this._selfObsMetrics.recordCollection(o,a.length>0?a[0].name??`collect_error`:void 0),{resourceMetrics:{resource:n.resourceMetrics.resource,scopeMetrics:n.resourceMetrics.scopeMetrics.concat(r.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:a}}async shutdown(e){if(this._shutdown){m.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await F(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){m.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await F(this.onForceFlush(),e.timeoutMillis)}};function Kn(e,t){if(!Number.isInteger(t)||t<=0)throw Error(`maxExportBatchSize must be a positive integer`);let n=[],r=0,i=[];function a(){i.length>0&&(n.push({resource:e.resource,scopeMetrics:i}),i=[],r=0)}for(let n of e.scopeMetrics){let e=null;for(let o of n.metrics){let s=o.dataPoints;if(s.length===0){e||(e={scope:n.scope,metrics:[]},i.push(e)),e.metrics.push(o);continue}let c=0;for(;c<s.length;){let l=t-r,u=Math.min(l,s.length-c);e||(e={scope:n.scope,metrics:[]},i.push(e));let d={...o,dataPoints:s.slice(c,c+u)};e.metrics.push(d),c+=u,r+=u,r===t&&(a(),e=null)}}}return a(),n}p(),E(),r();var qn=class extends Gn{constructor(e){let{exporter:t,exportIntervalMillis:n=6e4,metricProducers:r,cardinalityLimits:a,maxExportBatchSize:o}=e,{exportTimeoutMillis:s=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),otelComponentType:zn,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...a};switch(e){case N.COUNTER:return t.counter??t.default;case N.GAUGE:return t.gauge??t.default;case N.HISTOGRAM:return t.histogram??t.default;case N.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case N.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case N.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case N.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),i(this,`_interval`,void 0),i(this,`_exporter`,void 0),i(this,`_exportInterval`,void 0),i(this,`_exportTimeout`,void 0),i(this,`_maxExportBatchSize`,void 0),i(this,`_ongoingExportPromise`,null),n<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(s<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(o!==void 0&&(!Number.isInteger(o)||o<=0))throw Error(`maxExportBatchSize must be a positive integer`);if(n<s){if(`exportIntervalMillis`in e&&`exportTimeoutMillis`in e)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);m.info(`Timeout of ${s} exceeds the interval of ${n}. Clamping timeout to interval duration.`),s=n}this._exportInterval=n,this._exportTimeout=s,this._exporter=t,this._maxExportBatchSize=o}async _runOnce(){try{await this._doRun()}catch(e){v(e)}}async _doRun(){if(this._ongoingExportPromise){m.debug(`PeriodicExportingMetricReader: export already in progress, skipping`);return}let e=async()=>{let{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&m.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){m.debug(`Error while resolving async portion of resource: `,e),v(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?Kn(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await F(je._export(this._exporter,e),this._exportTimeout);t.code!==D.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof Vt){m.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}else m.error(`PeriodicExportingMetricReader: metrics export threw error`,e),r=e instanceof Error?e:Error(String(e))}if(r)throw r};this._ongoingExportPromise=e();try{await this._ongoingExportPromise}finally{this._ongoingExportPromise=null}}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!=`number`&&this._interval.unref()}async onForceFlush(){await this._awaitOngoingExport(),this._ongoingExportPromise?await this._awaitOngoingExport():await this._runOnce(),await this._exporter.forceFlush()}async _awaitOngoingExport(){if(this._ongoingExportPromise){m.debug(`PeriodicExportingMetricReader: export already in progress, awaiting ongoing export`);try{await this._ongoingExportPromise}catch{}}}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}};E(),r();var Jn=class e{constructor(e){i(this,`_shutdown`,!1),i(this,`_temporalitySelector`,void 0),this._temporalitySelector=e?.temporalitySelector??In}export(t,n){if(this._shutdown){n({code:D.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:D.SUCCESS})}};r();var Yn=class{constructor(){i(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))}};p();function V(e,t,n){return $n(e)||m.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??h.DOUBLE,advice:n?.advice??{}}}function Xn(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 Zn(e,t){return Wt(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}var Qn=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function $n(e){return Qn.test(e)}p(),r();var H=class{constructor(e,t){i(this,`_writableMetricStorage`,void 0),i(this,`_descriptor`,void 0),this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n){if(typeof e!=`number`){m.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===h.INT&&!Number.isInteger(e)&&(m.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,Date.now())}},er=class extends H{add(e,t,n){this._record(e,t,n)}},tr=class extends H{add(e,t,n){if(e<0){m.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},nr=class extends H{record(e,t,n){this._record(e,t,n)}},rr=class extends H{record(e,t,n){if(e<0){m.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},U=class{constructor(e,t,n){i(this,`_metricStorages`,void 0),i(this,`_descriptor`,void 0),i(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)}},ir=class extends U{},ar=class extends U{},or=class extends U{};function sr(e){return e instanceof U}r();var cr=class{constructor(e){i(this,`_meterSharedState`,void 0),this._meterSharedState=e}createGauge(e,t){let n=V(e,N.GAUGE,t);return new nr(this._meterSharedState.registerMetricStorage(n),n)}createHistogram(e,t){let n=V(e,N.HISTOGRAM,t);return new rr(this._meterSharedState.registerMetricStorage(n),n)}createCounter(e,t){let n=V(e,N.COUNTER,t);return new tr(this._meterSharedState.registerMetricStorage(n),n)}createUpDownCounter(e,t){let n=V(e,N.UP_DOWN_COUNTER,t);return new er(this._meterSharedState.registerMetricStorage(n),n)}createObservableGauge(e,t){let n=V(e,N.OBSERVABLE_GAUGE,t);return new ar(n,this._meterSharedState.registerAsyncMetricStorage(n),this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=V(e,N.OBSERVABLE_COUNTER,t);return new ir(n,this._meterSharedState.registerAsyncMetricStorage(n),this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=V(e,N.OBSERVABLE_UP_DOWN_COUNTER,t);return new or(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)}};r();var lr=class{constructor(e){i(this,`_instrumentDescriptor`,void 0),this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=V(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}};r();var ur=class{constructor(e){i(this,`_valueMap`,new Map),i(this,`_keyMap`,new Map),i(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}},W=class extends ur{constructor(){super(zt)}};E(),r();var dr=class{constructor(e,t){i(this,`_activeCollectionStorage`,new W),i(this,`_cumulativeMemoStorage`,new W),i(this,`_cardinalityLimit`,void 0),i(this,`_overflowAttributes`,{"otel.metric.overflow":!0}),i(this,`_overflowHashCode`,void 0),i(this,`_aggregator`,void 0),this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=zt(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=x(n);if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(i))?.record(e);return}r=this._aggregator.createAccumulation(i),this._activeCollectionStorage.set(t,r)}r?.record(e)}batchCumulate(e,t){for(let[n,r,i]of e.entries()){let e=n,a=i,o=this._aggregator.createAccumulation(t);o?.record(r);let s=o;if(this._cumulativeMemoStorage.has(e,a)){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,a=this._overflowHashCode,this._cumulativeMemoStorage.has(e,a))){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}if(this._activeCollectionStorage.has(e,a)){let t=this._activeCollectionStorage.get(e,a);s=this._aggregator.merge(t,s)}this._cumulativeMemoStorage.set(e,o,a),this._activeCollectionStorage.set(e,s,a)}}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new W,e}};r();var fr=class e{constructor(e,t){i(this,`_aggregator`,void 0),i(this,`_unreportedAccumulations`,new Map),i(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===M.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=pr(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 W,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}};function pr(e){return Array.from(e.entries())}r();var mr=class extends lr{constructor(e,t,n,r,a){super(e),i(this,`_aggregationCardinalityLimit`,void 0),i(this,`_deltaMetricStorage`,void 0),i(this,`_temporalMetricStorage`,void 0),i(this,`_attributesProcessor`,void 0),this._aggregationCardinalityLimit=a,this._deltaMetricStorage=new dr(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new fr(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new W;for(let[t,r]of e.entries())n.set(this._attributesProcessor.process(t),r);this._deltaMetricStorage.batchCumulate(n,t)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}};function hr(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 gr(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function _r(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function vr(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 yr(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 br(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:yr(e,t):vr(e,t):_r(e,t):gr(e,t)}p(),r();var xr=class e{constructor(){i(this,`_sharedRegistry`,new Map),i(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();Zn(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),m.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
- `,hr(t,e),`The longer description will be used.
7
- To resolve the conflict:`,br(t,e))),n=r):m.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
8
- `,`Details:
9
- `,hr(t,e),`To resolve the conflict:
10
- `,br(t,e))}return n}};p(),r();var Sr=class{constructor(e){i(this,`_backingStorages`,void 0),i(this,`hasAttributeProcessor`,void 0),this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=f.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}};p(),r();var Cr=class{constructor(e,t){i(this,`_buffer`,new W),i(this,`_instrumentName`,void 0),i(this,`_valueType`,void 0),this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){m.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===h.INT&&!Number.isInteger(e)&&(m.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)}},wr=class{constructor(){i(this,`_buffer`,new Map)}observe(e,t,n={}){if(!sr(e))return;let r=this._buffer.get(e);if(r??(r=new W,this._buffer.set(e,r)),typeof t!=`number`){m.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===h.INT&&!Number.isInteger(t)&&(m.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)}};p(),r();var Tr=class{constructor(){i(this,`_callbacks`,[]),i(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(sr));if(n.size===0){m.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(sr)),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 Cr(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=F(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 wr,a=Promise.resolve(n(i));t!=null&&(a=F(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&&Ht(n.instruments,t))}};p(),r();var Er=class extends lr{constructor(e,t,n,r,a){super(e),i(this,`_aggregationCardinalityLimit`,void 0),i(this,`_deltaMetricStorage`,void 0),i(this,`_temporalMetricStorage`,void 0),i(this,`_attributesProcessor`,void 0),i(this,`hasAttributeProcessor`,void 0),this._aggregationCardinalityLimit=a,this._deltaMetricStorage=new dr(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new fr(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??f.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}};r();var Dr=class{constructor(e,t){i(this,`metricStorageRegistry`,new xr),i(this,`observableRegistry`,new Tr),i(this,`meter`,void 0),i(this,`_meterProviderSharedState`,void 0),i(this,`_instrumentationScope`,void 0),this.meter=new cr(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,Er);return t.length===1?t[0]:new Sr(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,mr)}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=Xn(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,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}};r();var Or=class{constructor(e){i(this,`viewRegistry`,new Yn),i(this,`metricCollectors`,[]),i(this,`meterSharedStates`,new Map),i(this,`resource`,void 0),this.resource=e}getMeterSharedState(e){let t=Bt(e),n=this.meterSharedStates.get(t);return n??(n=new Dr(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Pn(n.selectAggregation(e))]);return t}};E(),r();var kr=class{constructor(e,t){i(this,`_sharedState`,void 0),i(this,`_metricReader`,void 0),this._sharedState=e,this._metricReader=t}async collect(e){let t=x(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}};r();var Ar=/[\^$\\.+?()[\]{}|]/g,jr=class e{constructor(t){i(this,`_matchAll`,void 0),i(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(Ar,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},G=class{constructor(e){i(this,`_matchAll`,void 0),i(this,`_pattern`,void 0),this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}};r();var Mr=class{process(e,t){return e}},Nr=class{constructor(e){i(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}};function Pr(){return Ir}function Fr(e){return new Nr(e)}var Ir=new Mr;r();var Lr=class{constructor(e){i(this,`_nameFilter`,void 0),i(this,`_type`,void 0),i(this,`_unitFilter`,void 0),this._nameFilter=new jr(e?.name??`*`),this._type=e?.type,this._unitFilter=new G(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}};r();var Rr=class{constructor(e){i(this,`_nameFilter`,void 0),i(this,`_versionFilter`,void 0),i(this,`_schemaUrlFilter`,void 0),this._nameFilter=new G(e?.name),this._versionFilter=new G(e?.version),this._schemaUrlFilter=new G(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}};r();function zr(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function Br(e){if(zr(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||jr.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 Vr=class{constructor(e){i(this,`name`,void 0),i(this,`description`,void 0),i(this,`aggregation`,void 0),i(this,`attributesProcessor`,void 0),i(this,`instrumentSelector`,void 0),i(this,`meterSelector`,void 0),i(this,`aggregationCardinalityLimit`,void 0),Br(e),e.attributesProcessors==null?this.attributesProcessor=Pr():this.attributesProcessor=Fr(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Pn(e.aggregation??{type:B.DEFAULT}),this.instrumentSelector=new Lr({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Rr({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}};p(),be(),r();var Hr=class{constructor(e){if(i(this,`_sharedState`,void 0),i(this,`_shutdown`,!1),this._sharedState=new Or(e?.resource??Se()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new Vr(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new kr(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof Gn&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(m.warn(`A shutdown MeterProvider cannot provide a Meter`),a()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){m.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){m.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}},Ur=`exception`,Wr=Symbol.for(`nodejs.util.inspect.custom`);function Gr(e){let t={};for(let[n,r]of e.getRawAttributes())typeof r?.then!=`function`&&r!=null&&(t[n]??(t[n]=r));return t}function Kr(e,t,n,r,i){if(typeof n==`number`&&n<0){let t=`[${e}]`;return r?.stylize?r.stylize(t,`special`):t}return typeof i!=`function`||!r?t:`${e} ${i(t,{...r,depth:r.depth==null?r.depth:r.depth-1})}`}p(),E(),ae(),r();var qr=class{constructor(e){i(this,`_spanContext`,void 0),i(this,`kind`,void 0),i(this,`parentSpanContext`,void 0),i(this,`attributes`,{}),i(this,`links`,[]),i(this,`events`,[]),i(this,`startTime`,void 0),i(this,`resource`,void 0),i(this,`instrumentationScope`,void 0),i(this,`_droppedAttributesCount`,0),i(this,`_droppedEventsCount`,0),i(this,`_droppedLinksCount`,0),i(this,`_attributesCount`,0),i(this,`name`,void 0),i(this,`status`,{code:l.UNSET}),i(this,`endTime`,[0,0]),i(this,`_ended`,!1),i(this,`_duration`,[-1,-1]),i(this,`_spanProcessor`,void 0),i(this,`_spanLimits`,void 0),i(this,`_attributeValueLengthLimit`,void 0),i(this,`_recordEndMetrics`,void 0),i(this,`_performanceStartTime`,void 0),i(this,`_performanceOffset`,void 0),i(this,`_startTimeProvided`,void 0);let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=y.now(),this._performanceOffset=t-(this._performanceStartTime+y.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(t==null||this._isSpanEnded())return this;if(e.length===0)return m.warn(`Invalid attribute key: ${e}`),this;if(!ve(t))return m.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:n}=this._spanLimits,r=!Object.prototype.hasOwnProperty.call(this.attributes,e);return n!==void 0&&this._attributesCount>=n&&r?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),r&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,t,n){if(this._isSpanEnded())return this;let{eventCountLimit:r}=this._spanLimits;if(r===0)return m.warn(`No events allowed.`),this._droppedEventsCount++,this;r!==void 0&&this.events.length>=r&&(this._droppedEventsCount===0&&m.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),me(t)&&(me(n)||(n=t),t=void 0);let i=S(t),{attributePerEventCountLimit:a}=this._spanLimits,o={},s=0,c=0;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];if(a!==void 0&&c>=a){s++;continue}o[e]=this._truncateToSize(t),c++}return this.events.push({name:e,attributes:o,time:this._getTime(n),droppedAttributesCount:s}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:t}=this._spanLimits;if(t===0)return this._droppedLinksCount++,this;t!==void 0&&this.links.length>=t&&(this._droppedLinksCount===0&&m.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:n}=this._spanLimits,r=S(e.attributes),i={},a=0,o=0;for(let e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let t=r[e];if(n!==void 0&&o>=n){a++;continue}i[e]=this._truncateToSize(t),o++}let s={context:e.context};return o>0&&(s.attributes=i),a>0&&(s.droppedAttributesCount=a),this.links.push(s),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===l.UNSET||this.status.code===l.OK)return this;let t={code:e.code};return e.code===l.ERROR&&(typeof e.message==`string`?t.message=e.message:e.message!=null&&m.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=t,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){if(this._isSpanEnded()){m.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=ge(this.startTime,this.endTime),this._duration[0]<0&&(m.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&m.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&m.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e==`number`&&e<=y.now())return de(e+this._performanceOffset);if(typeof e==`number`)return x(e);if(e instanceof Date)return x(e.getTime());if(he(e))return e;if(this._startTimeProvided)return x(Date.now());let t=y.now()-this._performanceStartTime;return fe(this.startTime,x(t))}isRecording(){return this._ended===!1}recordException(e,t){let n={};typeof e==`string`?n[_]=e:e&&(e.code?n[ie]=e.code.toString():e.name&&(n[ie]=e.name),e.message&&(n[_]=e.message),e.stack&&(n[se]=e.stack)),n[`exception.type`]||n[`exception.message`]?this.addEvent(Ur,n,t):m.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);m.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let t=this._attributeValueLengthLimit;return t<=0?(m.warn(`Attribute value limit must be positive, got ${t}`),e):typeof e==`string`?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,t):e):e}[Wr](e,t,n){return Kr(`SpanImpl`,{name:this.name,kind:this.kind,spanContext:this._spanContext,parentSpanContext:this.parentSpanContext,status:this.status,startTime:this.startTime,endTime:this.endTime,duration:this._duration,ended:this._ended,attributes:this.attributes,events:this.events,links:this.links,droppedAttributesCount:this._droppedAttributesCount,droppedEventsCount:this._droppedEventsCount,droppedLinksCount:this._droppedLinksCount,instrumentationScope:this.instrumentationScope,resource:{attributes:Gr(this.resource)}},e,t,n)}},K;(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(K||(K={}));var Jr=`otel.component.name`,Yr=`otel.component.type`,Xr=`otel.span.parent.origin`,Zr=`otel.span.sampling_result`,Qr=`otel.sdk.processor.span.processed`,$r=`otel.sdk.processor.span.queue.capacity`,ei=`otel.sdk.processor.span.queue.size`,ti=`otel.sdk.span.live`,ni=`otel.sdk.span.started`,ri=`batching_span_processor`;r();var ii=class{constructor(e){i(this,`startedSpans`,void 0),i(this,`liveSpans`,void 0),this.startedSpans=e.createCounter(ni,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(ti,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,t){let n=oi(t);if(this.startedSpans.add(1,{[Xr]:ai(e),[Zr]:n}),t===K.NOT_RECORD)return()=>{};let r={[Zr]:n};return this.liveSpans.add(1,r),()=>{this.liveSpans.add(-1,r)}}};function ai(e){return e?e.isRemote?`remote`:`local`:`none`}function oi(e){switch(e){case K.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case K.RECORD:return`RECORD_ONLY`;case K.NOT_RECORD:return`DROP`}}var si=`2.9.0`;p(),E(),r();var ci=class{constructor(e,t){i(this,`_sampler`,void 0),i(this,`_spanLimits`,void 0),i(this,`_idGenerator`,void 0),i(this,`instrumentationScope`,void 0),i(this,`_resource`,void 0),i(this,`_spanProcessor`,void 0),i(this,`_tracerMetrics`,void 0),this.instrumentationScope=e,this._sampler=t.sampler,this._spanLimits=t.spanLimits,this._resource=t.resource,this._idGenerator=t.idGenerator,this._spanProcessor=t.spanProcessor;let n=t.meterProvider.getMeter(`@opentelemetry/sdk-trace`,si);this._tracerMetrics=new ii(n)}startSpan(e,t={},n=f.active()){t.root&&(n=d.deleteSpan(n));let r=d.getSpan(n);if(pe(n))return m.debug(`Instrumentation suppressed, returning Noop Span`),d.wrapSpanContext(c);let i=r?.spanContext(),a=this._idGenerator.generateSpanId(),o,l,p;!i||!d.isSpanContextValid(i)?l=this._idGenerator.generateTraceId():(l=i.traceId,p=i.traceState,o=i);let te=t.kind??ee.INTERNAL,h=(t.links??[]).map(e=>({context:e.context,attributes:S(e.attributes)})),ne=S(t.attributes),g=this._sampler.shouldSample(n,l,e,te,ne,h),re=this._tracerMetrics.startSpan(i,g.decision);p=g.traceState??p;let ie=g.decision===u.RECORD_AND_SAMPLED?s.SAMPLED:s.NONE,_={traceId:l,spanId:a,traceFlags:ie,traceState:p};if(g.decision===u.NOT_RECORD)return m.debug(`Recording is off, propagating context in a non-recording span`),d.wrapSpanContext(_);let ae=S(Object.assign(ne,g.attributes));return new qr({resource:this._resource,scope:this.instrumentationScope,context:n,spanContext:_,name:e,kind:te,links:h,parentSpanContext:o,attributes:ae,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:re})}startActiveSpan(e,t,n,r){let i,a,o;if(arguments.length<2)return;arguments.length===2?o=t:arguments.length===3?(i=t,o=n):(i=t,a=n,o=r);let s=a??f.active(),c=this.startSpan(e,i,s),l=d.setSpan(s,c);return f.with(l,o,void 0,c)}[Wr](e,t,n){return Kr(`Tracer`,{instrumentationScope:this.instrumentationScope,resource:{attributes:Gr(this._resource)},spanLimits:this._spanLimits},e,t,n)}};E(),r();var li=class{constructor(e){i(this,`_spanProcessors`,void 0),this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{v(e||Error(`MultiSpanProcessor: forceFlush failed`)),t()})})}onStart(e,t){for(let n of this._spanProcessors)n.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,n)=>{Promise.all(e).then(()=>{t()},n)})}},q=class{shouldSample(){return{decision:K.NOT_RECORD}}toString(){return`AlwaysOffSampler`}},J=class{shouldSample(){return{decision:K.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}};p(),E(),r();var Y=class{constructor(e){i(this,`_root`,void 0),i(this,`_remoteParentSampled`,void 0),i(this,`_remoteParentNotSampled`,void 0),i(this,`_localParentSampled`,void 0),i(this,`_localParentNotSampled`,void 0),this._root=e.root,this._root||(v(Error(`ParentBasedSampler must have a root sampler configured`)),this._root=new J),this._remoteParentSampled=e.remoteParentSampled??new J,this._remoteParentNotSampled=e.remoteParentNotSampled??new q,this._localParentSampled=e.localParentSampled??new J,this._localParentNotSampled=e.localParentNotSampled??new q}shouldSample(e,t,n,r,i,a){let o=d.getSpanContext(e);return!o||!te(o)?this._root.shouldSample(e,t,n,r,i,a):o.isRemote?o.traceFlags&s.SAMPLED?this._remoteParentSampled.shouldSample(e,t,n,r,i,a):this._remoteParentNotSampled.shouldSample(e,t,n,r,i,a):o.traceFlags&s.SAMPLED?this._localParentSampled.shouldSample(e,t,n,r,i,a):this._localParentNotSampled.shouldSample(e,t,n,r,i,a)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}};ae(),r();var ui=new Map,di=class{constructor(e,t,n){i(this,`processedSpans`,void 0),i(this,`queueSize`,void 0),i(this,`queueSizeCallback`,void 0),i(this,`standardAttrs`,void 0),i(this,`droppedAttrs`,void 0);let r=ui.get(e)??0;if(ui.set(e,r+1),this.standardAttrs={[Yr]:e,[Jr]:`${e}/${r}`},this.droppedAttrs={...this.standardAttrs,[ce]:`queue_full`},this.processedSpans=t.createCounter(Qr,{unit:`{span}`,description:`The number of spans for which the processing has finished, either successful or failed.`}),n){let{capacity:e,getQueueSize:r}=n;t.createUpDownCounter($r,{unit:`{span}`,description:`The maximum number of spans the queue of a given instance of an SDK span processor can hold.`}).add(e,this.standardAttrs),this.queueSize=t.createObservableUpDownCounter(ei,{unit:`{span}`,description:`The number of spans in the queue of a given instance of an SDK span processor.`}),this.queueSizeCallback=e=>e.observe(r(),this.standardAttrs),this.queueSize.addCallback(this.queueSizeCallback)}}dropSpans(e){this.processedSpans.add(e,this.droppedAttrs)}finishSpans(e,t){if(!t){this.processedSpans.add(e,this.standardAttrs);return}let n={...this.standardAttrs,[ce]:t.name};this.processedSpans.add(e,n)}shutdown(){this.queueSize&&this.queueSizeCallback&&this.queueSize.removeCallback(this.queueSizeCallback)}};p(),E(),r();var fi=class{constructor(e){i(this,`_maxExportBatchSize`,void 0),i(this,`_maxQueueSize`,void 0),i(this,`_scheduledDelayMillis`,void 0),i(this,`_exportTimeoutMillis`,void 0),i(this,`_exporter`,void 0),i(this,`_metrics`,void 0),i(this,`_isExporting`,!1),i(this,`_finishedSpans`,[]),i(this,`_timer`,void 0),i(this,`_shutdownOnce`,void 0),i(this,`_droppedSpansCount`,0),this._exporter=e.exporter,this._maxExportBatchSize=e.maxExportBatchSize??512,this._maxQueueSize=e.maxQueueSize??2048,this._scheduledDelayMillis=e.scheduledDelayMillis??5e3,this._exportTimeoutMillis=e.exportTimeoutMillis??3e4,this._shutdownOnce=new ye(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(m.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize);let t=e.selfObsMeterProvider?e.selfObsMeterProvider.getMeter(`@opentelemetry/sdk-trace`):a();this._metrics=new di(ri,t,{capacity:this._maxQueueSize,getQueueSize:()=>this._finishedSpans.length})}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&s.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>(this._metrics.shutdown(),this._exporter.shutdown()))}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&m.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++,this._metrics.dropSpans(1);return}this._droppedSpansCount>0&&(m.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=r;e<t;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,t)=>{let n=setTimeout(()=>{t(Error(`Timeout`))},this._exportTimeoutMillis);f.with(Oe(f.active()),()=>{let r;this._finishedSpans.length<=this._maxExportBatchSize?(r=this._finishedSpans,this._finishedSpans=[]):r=this._finishedSpans.splice(0,this._maxExportBatchSize);let i=()=>this._exporter.export(r,i=>{clearTimeout(n),this._metrics.finishSpans(r.length,i.error),i.code===D.SUCCESS?e():t(i.error??Error(`BatchSpanProcessor: span export failed`))}),a=null;for(let e=0,t=r.length;e<t;e++){let t=r[e];t.resource.asyncAttributesPending&&t.resource.waitForAsyncAttributes&&(a??(a=[]),a.push(t.resource.waitForAsyncAttributes()))}a===null?i():Promise.all(a).then(i,e=>{v(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,v(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}},pi=class extends fi{onShutdown(){}};r();var mi=8,hi=16,gi=class{constructor(){i(this,`generateTraceId`,_i(hi)),i(this,`generateSpanId`,_i(mi))}},X=Buffer.allocUnsafe(hi);function _i(e){return function(){for(let t=0;t<e/4;t++)X.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(X[t]>0);t++)t===e-1&&(X[e-1]=1);return X.toString(`hex`,0,e)}}p(),be(),r();var Z;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(Z||(Z={}));var vi=class{constructor(e={}){i(this,`_resource`,void 0),i(this,`_activeSpanProcessor`,void 0),i(this,`_forceFlushTimeoutMillis`,void 0),i(this,`_tracerOptions`,void 0),i(this,`_tracers`,new Map),this._forceFlushTimeoutMillis=e.forceFlushTimeoutMillis??3e4,this._resource=e.resource??Se();let t=e.spanProcessors??[];this._activeSpanProcessor=new li(t),this._tracerOptions={resource:this._resource,sampler:e.sampler??new Y({root:new J}),spanLimits:{attributeCountLimit:e.spanLimits?.attributeCountLimit??128,attributeValueLengthLimit:e.spanLimits?.attributeValueLengthLimit??1/0,eventCountLimit:e.spanLimits?.eventCountLimit??128,linkCountLimit:e.spanLimits?.linkCountLimit??128,attributePerEventCountLimit:e.spanLimits?.attributePerEventCountLimit??128,attributePerLinkCountLimit:e.spanLimits?.attributePerLinkCountLimit??128},idGenerator:e.idGenerator||new gi,spanProcessor:this._activeSpanProcessor,meterProvider:e.meterProvider??{getMeter(){return a()}}}}getTracer(e,t,n){let r=`${e}@${t||``}:${n?.schemaUrl||``}`;return this._tracers.has(r)||this._tracers.set(r,new ci({name:e,version:t,schemaUrl:n?.schemaUrl},this._tracerOptions)),this._tracers.get(r)}forceFlush(){let e=this._forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(n=>{let r,i=setTimeout(()=>{n(Error(`Span processor did not completed within timeout period of ${e} ms`)),r=Z.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),r!==Z.timeout&&(r=Z.resolved,n(r))}).catch(e=>{clearTimeout(i),r=Z.error,n(e)})}));return new Promise((e,n)=>{Promise.all(t).then(t=>{let r=t.filter(e=>e!==Z.resolved);r.length>0?n(r):e()}).catch(e=>n([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}[Wr](e,t,n){let r=this._activeSpanProcessor._spanProcessors;return Kr(`TracerProvider`,{resource:{attributes:Gr(this._resource)},tracers:Array.from(this._tracers.keys()),spanProcessors:r.map(e=>e.constructor?.name??`SpanProcessor`)},e,t,n)}};E();var yi=class{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:w(e.startTime),duration:w(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,t){for(let t of e)console.dir(this._exportInfo(t),{depth:3});if(t)return t({code:D.SUCCESS})}};p(),r();var bi=class{constructor(e=0){i(this,`_ratio`,void 0),i(this,`_upperBound`,void 0),this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,t){return{decision:ne(t)&&this._accumulate(t)<this._upperBound?K.RECORD_AND_SAMPLED:K.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let n=0;n<32;n+=8){let r=0;for(let t=0;t<8;t++){let i=e.charCodeAt(n+t),a=i<58?i-48:i<71?i-55:i-87;r=r<<4|a}t=(t^r)>>>0}return t}};p(),E();var Q;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(Q||(Q={}));var $=1;function xi(){return{sampler:Si(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:b(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:b(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:b(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:b(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:b(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:b(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:b(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:b(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}function Si(){let e=_e(`OTEL_TRACES_SAMPLER`)??Q.ParentBasedAlwaysOn;switch(e){case Q.AlwaysOn:return new J;case Q.AlwaysOff:return new q;case Q.ParentBasedAlwaysOn:return new Y({root:new J});case Q.ParentBasedAlwaysOff:return new Y({root:new q});case Q.TraceIdRatio:return new bi(Ci());case Q.ParentBasedTraceIdRatio:return new Y({root:new bi(Ci())});default:return m.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${Q.ParentBasedAlwaysOn}".`),new Y({root:new J})}}function Ci(){let e=b(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(m.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${$}.`),$):e<0||e>1?(m.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to ${$}.`),$):e}E();function wi(e){let t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??b(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??b(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??b(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??b(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,Object.assign({},e,{spanLimits:t})}E();var Ti=class extends vi{constructor(e={}){let t=ue({},xi(),wi(e));delete t.generalLimits,super(t)}};E();var Ei=class extends pi{constructor(e,t){t||(t={});for(let[e,n]of[[`maxExportBatchSize`,`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`],[`maxQueueSize`,`OTEL_BSP_MAX_QUEUE_SIZE`],[`scheduledDelayMillis`,`OTEL_BSP_SCHEDULE_DELAY`],[`exportTimeoutMillis`,`OTEL_BSP_EXPORT_TIMEOUT`]])if(t[e]===void 0){let r=b(n);r!==void 0&&(t[e]=r)}super({exporter:e,...t})}};n(),De(),Le(),Je(),Ye(),lt(),ut(),Ze(),St(),Ot(),Ct(),wt(),Nt(),ke(),Ne(),ht(),$e(),A(),We(),gt(),it(),ot(),nt(),At();var Di=3600*1e3,Oi=1440*60*1e3;async function ki(){let e=yt();if(e.error)throw Error(`Auth error: ${e.error}`);let t={"Content-Type":`application/json`,"User-Agent":jt(),...e.headers};return(await Me.get(`https://api.anthropic.com/api/claude_code/organizations/metrics_enabled`,{headers:t,timeout:5e3})).data}async function Ai(){if(rt())return{enabled:!1,hasError:!1};try{let e=await _t(ki,{also403Revoked:!0});return k(`Metrics opt-out API response: enabled=${e.metrics_logging_enabled}`),{enabled:e.metrics_logging_enabled,hasError:!1}}catch(e){return k(`Failed to check metrics opt-out status: ${Ue(e)}`),j(e),{enabled:!1,hasError:!0}}}var ji=at(Ai,Di);async function Mi(){let e=await ji();if(e.hasError)return e;let t=Qe().metricsStatusCache;return t!==void 0&&t.enabled===e.enabled&&Date.now()-t.timestamp<Oi||tt(t=>({...t,metricsStatusCache:{enabled:e.enabled,timestamp:Date.now()}})),e}async function Ni(){if(bt()&&!mt())return{enabled:!1,hasError:!1};let e=Qe().metricsStatusCache;return e?(Date.now()-e.timestamp>Oi&&Mi().catch(j),{enabled:e.enabled,hasError:!1}):Mi()}E(),Ne(),ht(),$e(),A(),We(),gt(),it(),At(),r();var Pi=class{constructor(e={}){i(this,`endpoint`,void 0),i(this,`timeout`,void 0),i(this,`pendingExports`,[]),i(this,`isShutdown`,!1),this.endpoint=`https://api.anthropic.com/api/claude_code/metrics`,this.timeout=e.timeout||5e3}async export(e,t){if(this.isShutdown){t({code:D.FAILED,error:Error(`Exporter has been shutdown`)});return}let n=this.doExport(e,t);this.pendingExports.push(n),n.finally(()=>{let e=this.pendingExports.indexOf(n);e>-1&&this.pendingExports.splice(e,1)})}async doExport(e,t){try{if(!(et()||Ie())){k(`BigQuery metrics export: trust not established, skipping`),t({code:D.SUCCESS});return}if(!(await Ni()).enabled){k(`Metrics export disabled by organization setting`),t({code:D.SUCCESS});return}let n=this.transformMetricsForInternal(e),r=yt();if(r.error){k(`Metrics export failed: ${r.error}`),t({code:D.FAILED,error:Error(r.error)});return}let i={"Content-Type":`application/json`,"User-Agent":jt(),...r.headers},a=await Me.post(this.endpoint,n,{timeout:this.timeout,headers:i});k(`BigQuery metrics exported successfully`),k(`BigQuery API Response: ${He(a.data,null,2)}`),t({code:D.SUCCESS})}catch(e){k(`BigQuery metrics export failed: ${Ue(e)}`),j(e),t({code:D.FAILED,error:Ge(e)})}}transformMetricsForInternal(e){let t=e.resource.attributes,n={"service.name":t[`service.name`]||`workmate`,"service.version":t[`service.version`]||`unknown`,"os.type":t[`os.type`]||`unknown`,"os.version":t[`os.version`]||`unknown`,"host.arch":t[`host.arch`]||`unknown`,"aggregation.temporality":this.selectAggregationTemporality()===M.DELTA?`delta`:`cumulative`};if(t[`wsl.version`]&&(n[`wsl.version`]=t[`wsl.version`]),bt()){n[`user.customer_type`]=`claude_ai`;let e=vt();e&&(n[`user.subscription_type`]=e)}else n[`user.customer_type`]=`api`;return{resource_attributes:n,metrics:e.scopeMetrics.flatMap(e=>e.metrics.map(e=>({name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit,data_points:this.extractDataPoints(e)})))}}extractDataPoints(e){return(e.dataPoints||[]).filter(e=>typeof e.value==`number`).map(e=>({attributes:this.convertAttributes(e.attributes),value:e.value,timestamp:this.hrTimeToISOString(e.endTime||e.startTime||[Date.now()/1e3,0])}))}async shutdown(){this.isShutdown=!0,await this.forceFlush(),k(`BigQuery metrics exporter shutdown complete`)}async forceFlush(){await Promise.all(this.pendingExports),k(`BigQuery metrics exporter flush complete`)}convertAttributes(e){let t={};if(e)for(let[n,r]of Object.entries(e))r!=null&&(t[n]=String(r));return t}hrTimeToISOString(e){let[t,n]=e;return new Date(t*1e3+n/1e6).toISOString()}selectAggregationTemporality(){return M.DELTA}};A(),it();var Fi=class{error(e,...t){j(Error(e)),k(`[3P telemetry] OTEL diag error: ${e}`,{level:`error`})}warn(e,...t){j(Error(e)),k(`[3P telemetry] OTEL diag warn: ${e}`,{level:`warn`})}info(e,...t){}debug(e,...t){}verbose(e,...t){}};p(),be(),ae(),Le(),ht(),A(),We(),Ye(),It(),Ft();var Ii=6e4,Li=5e3,Ri=5e3,zi=class extends Error{};function Bi(e,t){return new Promise((n,r)=>{setTimeout((e,t)=>e(new zi(t)),e,r,t).unref()})}function Vi(){process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE||(process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=`delta`)}function Hi(e){return(e||``).trim().split(`,`).filter(Boolean).map(e=>e.trim()).filter(e=>e!==`none`)}async function Ui(){let t=Hi(process.env.OTEL_METRICS_EXPORTER),n=parseInt(process.env.OTEL_METRIC_EXPORT_INTERVAL||Ii.toString(),10),r=[];for(let n of t)if(n===`console`){let e=new Jn,t=e.export.bind(e);e.export=(e,n)=>(e.resource?.attributes&&(k(`
11
- === Resource Attributes ===`),k(He(e.resource.attributes)),k(`===========================
12
- `)),t(e,n)),r.push(e)}else if(n===`otlp`){let e=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),t=$i();switch(e){case`http/json`:{let{OTLPMetricExporter:e}=await import(`./esm-BadZVa27.js`);r.push(new e(t));break}default:throw Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}else if(n===`prometheus`){let{PrometheusExporter:t}=await import(`./src-BacxF9BD.js`).then(t=>e(t.default,1));r.push(new t)}else throw Error(`Unknown exporter type set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${n}`);return r.map(e=>`export`in e?new qn({exporter:e,exportIntervalMillis:n}):e)}async function Wi(){let e=Hi(process.env.OTEL_LOGS_EXPORTER),t=process.env.OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),n=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;k(`[3P telemetry] getOtlpLogExporters: types=${He(e)}, protocol=${t}, endpoint=${n}`);let r=[];for(let n of e)if(n===`console`)r.push(new Ce);else if(n===`otlp`){let e=$i();switch(t){case`http/json`:{let{OTLPLogExporter:t}=await import(`./esm-BCmY8V0C.js`);r.push(new t(e));break}default:throw Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_LOGS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${t}`)}}else throw Error(`Unknown exporter type set in OTEL_LOGS_EXPORTER env var: ${n}`);return r}async function Gi(){let e=Hi(process.env.OTEL_TRACES_EXPORTER),t=[];for(let n of e)if(n===`console`)t.push(new yi);else if(n===`otlp`){let e=process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),n=$i();switch(e){case`http/json`:{let{OTLPTraceExporter:e}=await import(`./esm-BUJtY-Rb.js`);t.push(new e(n));break}default:throw Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_TRACES_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}else throw Error(`Unknown exporter type set in OTEL_TRACES_EXPORTER env var: ${n}`);return t}function Ki(){return t(process.env.CLAUDE_CODE_ENABLE_TELEMETRY)}function qi(){return new qn({exporter:new Pi,exportIntervalMillis:300*1e3})}function Ji(){let e=vt(),t=bt()&&(e===`enterprise`||e===`team`);return pt()||t}async function Yi(e){let t=process.env.BETA_TRACING_ENDPOINT;if(!t)return;let[{OTLPTraceExporter:n},{OTLPLogExporter:r}]=await Promise.all([import(`./esm-BUJtY-Rb.js`),import(`./esm-BCmY8V0C.js`)]),i={url:`${t}/v1/traces`},a={url:`${t}/v1/logs`},o=new Ti({resource:e,spanProcessors:[new Ei(new n(i),{scheduledDelayMillis:Ri})]});d.setGlobalTracerProvider(o),Ve(o);let s=new Te({resource:e,processors:[new we(new r(a),{scheduledDelayMillis:Li})]});T.setGlobalLoggerProvider(s),Be(s),ze(T.getLogger(`com.anthropic.claude_code.events`,`0.0.21`)),process.on(`beforeExit`,async()=>{await s?.forceFlush(),await o?.forceFlush()}),process.on(`exit`,()=>{s?.forceFlush(),o?.forceFlush()})}async function Xi(){if(dt(`telemetry_init_start`),Vi(),qe())for(let e of[`OTEL_METRICS_EXPORTER`,`OTEL_LOGS_EXPORTER`,`OTEL_TRACES_EXPORTER`]){let t=process.env[e];t?.includes(`console`)&&(process.env[e]=t.split(`,`).map(e=>e.trim()).filter(e=>e!==`console`).join(`,`))}m.setLogger(new Fi,o.ERROR),Pt();let e=[],t=Ki();k(`[3P telemetry] isTelemetryEnabled=${t} (CLAUDE_CODE_ENABLE_TELEMETRY=${process.env.CLAUDE_CODE_ENABLE_TELEMETRY})`),t&&e.push(...await Ui()),Ji()&&e.push(qi());let n=ct(),r={[re]:`workmate`,[oe]:`0.0.21`};if(n===`wsl`){let e=st();e&&(r[`wsl.version`]=e)}let i=C(r),a=C(Ae.detect().attributes||{}),s=xe.detect(),c=C(s.attributes?.[`host.arch`]?{[g]:s.attributes[g]}:{}),l=C(Ee.detect().attributes||{}),u=i.merge(a).merge(c).merge(l);if(Mt()){Yi(u).catch(e=>k(`Beta tracing init failed: ${e}`,{level:`error`}));let t=new Hr({resource:u,views:[],readers:e});return Fe(t),Ke(async()=>{let e=parseInt(process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||`2000`,10);try{Rt();let n=Pe(),r=O(),i=[t.shutdown()];n&&i.push(n.forceFlush().then(()=>n.shutdown())),r&&i.push(r.forceFlush().then(()=>r.shutdown())),await Promise.race([Promise.all(i),Bi(e,`OpenTelemetry shutdown timeout`)])}catch{}}),t.getMeter(`com.anthropic.claude_code`,`0.0.21`)}let f=new Hr({resource:u,views:[],readers:e});if(Fe(f),t){let e=await Wi();if(k(`[3P telemetry] Created ${e.length} log exporter(s)`),e.length>0){let t=new Te({resource:u,processors:e.map(e=>new we(e,{scheduledDelayMillis:parseInt(process.env.OTEL_LOGS_EXPORT_INTERVAL||Li.toString(),10)}))});T.setGlobalLoggerProvider(t),Be(t),ze(T.getLogger(`com.anthropic.claude_code.events`,`0.0.21`)),k(`[3P telemetry] Event logger set successfully`),process.on(`beforeExit`,async()=>{await t?.forceFlush(),await O()?.forceFlush()}),process.on(`exit`,()=>{t?.forceFlush(),O()?.forceFlush()})}}if(t&&Lt()){let e=await Gi();if(e.length>0){let t=new Ti({resource:u,spanProcessors:e.map(e=>new Ei(e,{scheduledDelayMillis:parseInt(process.env.OTEL_TRACES_EXPORT_INTERVAL||Ri.toString(),10)}))});d.setGlobalTracerProvider(t),Ve(t)}}return Ke(async()=>{let e=parseInt(process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||`2000`,10);try{Rt();let t=[f.shutdown()],n=Pe();n&&t.push(n.shutdown());let r=O();r&&t.push(r.shutdown()),await Promise.race([Promise.all(t),Bi(e,`OpenTelemetry shutdown timeout`)])}catch(t){throw t instanceof Error&&t.message.includes(`timeout`)&&k(`
13
- OpenTelemetry telemetry flush timed out after ${e}ms
14
-
15
- To resolve this issue, you can:
16
- 1. Increase the timeout by setting CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS env var (e.g., 5000 for 5 seconds)
17
- 2. Check if your OpenTelemetry backend is experiencing scalability issues
18
- 3. Disable OpenTelemetry by unsetting CLAUDE_CODE_ENABLE_TELEMETRY env var
19
-
20
- Current timeout: ${e}ms
21
- `,{level:`error`}),t}}),f.getMeter(`com.anthropic.claude_code`,`0.0.21`)}async function Zi(){let e=Re();if(!e)return;let t=parseInt(process.env.CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS||`5000`,10);try{let n=[e.forceFlush()],r=Pe();r&&n.push(r.forceFlush());let i=O();i&&n.push(i.forceFlush()),await Promise.race([Promise.all(n),Bi(t,`OpenTelemetry flush timeout`)]),k(`Telemetry flushed successfully`)}catch(e){e instanceof zi?k(`Telemetry flush timed out after ${t}ms. Some metrics may not be exported.`,{level:`warn`}):k(`Telemetry flush failed: ${Ue(e)}`,{level:`error`})}}function Qi(){let e={},t=process.env.OTEL_EXPORTER_OTLP_HEADERS;if(t)for(let n of t.split(`,`)){let[t,...r]=n.split(`=`);t&&r.length>0&&(e[t.trim()]=r.join(`=`).trim())}return e}function $i(){let e=Tt(),t=Et(),n=Xe(),r={},i=Qi();n?.otelHeadersHelper?r.headers=async()=>{let e=ft();return{...i,...e}}:Object.keys(i).length>0&&(r.headers=async()=>i);let a=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;if(!e||a&&Dt(a)){let e=xt();return(t||e)&&(r.httpAgentOptions={...t,...e&&{ca:e}}),r}let o=xt();return r.httpAgentOptions=n=>t||o?new kt(e,{...t&&{cert:t.cert,key:t.key,passphrase:t.passphrase},...o&&{ca:o}}):new kt(e),r}export{Zi as flushTelemetry,Xi as initializeTelemetry};
@@ -1 +0,0 @@
1
- import{P as e,R as t,S as n,c as r,i,x as a}from"./debug-D58GQBDG.js";import{O as o,k as s}from"./git-Wid-XppW.js";import{n as c,r as l}from"./analytics-DJobLaWP.js";c(),i(),o(),t(),a();function u(e){if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n>0?`${t}m ${n}s`:`${t}m`}function d(e){let t=(e.startsWith(`sk-ant-si-`)?e.slice(10):e).split(`.`);if(t.length!==3||!t[1])return null;try{return n(Buffer.from(t[1],`base64url`).toString(`utf8`))}catch{return null}}function f(e){let t=d(e);return typeof t==`object`&&t&&`exp`in t&&typeof t.exp==`number`?t.exp:null}var p=300*1e3,m=1800*1e3,h=3,g=6e4;function _({getAccessToken:t,onRefresh:n,label:i,refreshBufferMs:a=p}){let o=new Map,c=new Map,d=new Map;function _(e){let t=(d.get(e)??0)+1;return d.set(e,t),t}function v(e,t){let n=f(t);if(!n){r(`[${i}:token] Could not decode JWT expiry for sessionId=${e}, token prefix=${t.slice(0,15)}…, keeping existing timer`);return}let s=o.get(e);s&&clearTimeout(s);let c=_(e),l=new Date(n*1e3).toISOString(),d=n*1e3-Date.now()-a;if(d<=0){r(`[${i}:token] Token for sessionId=${e} expires=${l} (past or within buffer), refreshing immediately`),b(e,c);return}r(`[${i}:token] Scheduled token refresh for sessionId=${e} in ${u(d)} (expires=${l}, buffer=${a/1e3}s)`);let p=setTimeout(b,d,e,c);o.set(e,p)}function y(e,t){let n=o.get(e);n&&clearTimeout(n);let s=_(e),c=Math.max(t*1e3-a,3e4);r(`[${i}:token] Scheduled token refresh for sessionId=${e} in ${u(c)} (expires_in=${t}s, buffer=${a/1e3}s)`);let l=setTimeout(b,c,e,s);o.set(e,l)}async function b(a,f){let p;try{p=await t()}catch(t){r(`[${i}:token] getAccessToken threw for sessionId=${a}: ${e(t)}`,{level:`error`})}if(d.get(a)!==f){r(`[${i}:token] doRefresh for sessionId=${a} stale (gen ${f} vs ${d.get(a)}), skipping`);return}if(!p){let e=(c.get(a)??0)+1;if(c.set(a,e),r(`[${i}:token] No OAuth token available for refresh, sessionId=${a} (failure ${e}/${h})`,{level:`error`}),s(`error`,`bridge_token_refresh_no_oauth`),e<h){let e=setTimeout(b,g,a,f);o.set(a,e)}return}c.delete(a),r(`[${i}:token] Refreshing token for sessionId=${a}: new token prefix=${p.slice(0,15)}…`),l(`tengu_bridge_token_refreshed`,{}),n(a,p);let _=setTimeout(b,m,a,f);o.set(a,_),r(`[${i}:token] Scheduled follow-up refresh for sessionId=${a} in ${u(m)}`)}function x(e){_(e);let t=o.get(e);t&&(clearTimeout(t),o.delete(e)),c.delete(e)}function S(){for(let e of d.keys())_(e);for(let e of o.values())clearTimeout(e);o.clear(),c.clear()}return{schedule:v,scheduleFromExpiresIn:y,cancel:x,cancelAll:S}}export{f as n,_ as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{GT as t,HT as n,KT as r,LT as i,RT as a,WT as o,qT as s,zT as c}from"./loadAgentsDir-C96o6gCj.js";import{C as l,F as u,R as d,x as f}from"./debug-D58GQBDG.js";import{r as p,t as m}from"./promptEditor-DT6egmcb.js";import{dirname as h}from"path";import{mkdir as g,writeFile as _}from"fs/promises";function v(e){let r=new Set(n.map(e=>t(e.key)));return e.map(e=>{let n={};for(let[i,a]of Object.entries(e.bindings))r.has(t(i))||(n[i]=a);return{context:e.context,bindings:n}}).filter(e=>Object.keys(e.bindings).length>0)}function y(){return`${l({$schema:`https://www.schemastore.org/claude-code-keybindings.json`,$docs:`https://code.workmate.com/docs/en/keybindings`,bindings:v(r)},null,2)}\n`}var b=e((()=>{f(),s(),o()}));async function x(){if(!c())return{type:`text`,value:`Keybinding customization is not enabled. This feature is currently in preview.`};let e=i(),t=!1;await g(h(e),{recursive:!0});try{await _(e,y(),{encoding:`utf-8`,flag:`wx`})}catch(e){if(u(e)===`EEXIST`)t=!0;else throw e}let n=await m(e);return n.error?{type:`text`,value:`${t?`Opened`:`Created`} ${e}. Could not open in editor: ${n.error}`}:{type:`text`,value:t?`Opened ${e} in your editor.`:`Created ${e} with template. Opened in your editor.`}}e((()=>{a(),b(),d(),p()}))();export{x as call};
@@ -1,3 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Bc as n,Gc as r,Hc as i,Kc as a,Lc as o,Lu as s,Rc as c,Ru as l,Uc as u,Vc as d,Wc as f,zc as p}from"./loadAgentsDir-C96o6gCj.js";import{I as m,P as h,ai as g,hn as _,t as v,y}from"./src-DL3w8VPk.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";function x(e){return e.mode===`list`?e.stores.length===0?(0,S.jsx)(m,{children:(0,S.jsx)(h,{dimColor:!0,children:`No memory stores found. Use /local-memory create <store> to create one.`})}):(0,S.jsxs)(m,{flexDirection:`column`,children:[(0,S.jsx)(m,{marginBottom:1,children:(0,S.jsxs)(h,{bold:!0,children:[`Local Memory Stores (`,e.stores.length,`)`]})}),e.stores.map(e=>(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{children:` `}),(0,S.jsx)(h,{color:`success`,children:`◆`}),(0,S.jsxs)(h,{children:[` `,e]})]},e))]}):e.mode===`created`?(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{color:`success`,children:`✓`}),(0,S.jsx)(h,{children:` Store created: `}),(0,S.jsx)(h,{bold:!0,children:e.store})]}):e.mode===`stored`?(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{color:`success`,children:`✓`}),(0,S.jsx)(h,{children:` Stored entry `}),(0,S.jsx)(h,{bold:!0,children:e.key}),(0,S.jsx)(h,{children:` in `}),(0,S.jsx)(h,{bold:!0,children:e.store})]}):e.mode===`fetched`?(0,S.jsxs)(m,{flexDirection:`column`,children:[(0,S.jsxs)(m,{marginBottom:1,children:[(0,S.jsx)(h,{bold:!0,children:e.store}),(0,S.jsx)(h,{dimColor:!0,children:`/`}),(0,S.jsx)(h,{bold:!0,children:e.key})]}),(0,S.jsx)(m,{children:(0,S.jsx)(h,{children:e.value})})]}):e.mode===`not-found`?(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{color:`error`,children:`Not found: `}),(0,S.jsx)(h,{bold:!0,children:e.store}),e.key?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(h,{dimColor:!0,children:`/`}),(0,S.jsx)(h,{bold:!0,children:e.key})]}):null]}):e.mode===`entries`?e.keys.length===0?(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{dimColor:!0,children:`No entries in `}),(0,S.jsx)(h,{bold:!0,children:e.store}),(0,S.jsxs)(h,{dimColor:!0,children:[`. Use /local-memory store `,e.store,` <key> <value> to add one.`]})]}):(0,S.jsxs)(m,{flexDirection:`column`,children:[(0,S.jsxs)(m,{marginBottom:1,children:[(0,S.jsx)(h,{bold:!0,children:e.store}),(0,S.jsxs)(h,{dimColor:!0,children:[` (`,e.keys.length,` entries)`]})]}),e.keys.map(e=>(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{children:` `}),(0,S.jsx)(h,{color:`success`,children:`·`}),(0,S.jsxs)(h,{children:[` `,e]})]},e))]}):e.mode===`archived`?(0,S.jsxs)(m,{children:[(0,S.jsx)(h,{color:`success`,children:`✓`}),(0,S.jsx)(h,{children:` Archived store: `}),(0,S.jsx)(h,{bold:!0,children:e.store}),(0,S.jsxs)(h,{dimColor:!0,children:[` (renamed to `,e.store,`.archived)`]})]}):(0,S.jsx)(m,{children:(0,S.jsxs)(h,{color:`error`,children:[`Error: `,e.message]})})}var S,C=e((()=>{v(),S=b()}));function w(e){let t=e.trim();if(t===``||t===`list`)return{action:`list`};let n=t.split(/\s+/),r=n[0];if(r===`list`)return{action:`list`};if(r===`create`){let e=n[1];return e?{action:`create`,store:e}:{action:`invalid`,reason:`create requires a store name. ${T}`}}if(r===`store`){let e=n[1],t=n[2];if(!e)return{action:`invalid`,reason:`store requires a store name. ${T}`};if(!t)return{action:`invalid`,reason:`store requires a key. ${T}`};let r=n.slice(3).join(` `);return r?{action:`store`,store:e,key:t,value:r}:{action:`invalid`,reason:`store requires a value. ${T}`}}if(r===`fetch`){let e=n[1],t=n[2];return e?t?{action:`fetch`,store:e,key:t}:{action:`invalid`,reason:`fetch requires a key. ${T}`}:{action:`invalid`,reason:`fetch requires a store name. ${T}`}}if(r===`entries`){let e=n[1];return e?{action:`entries`,store:e}:{action:`invalid`,reason:`entries requires a store name. ${T}`}}if(r===`archive`){let e=n[1];return e?{action:`archive`,store:e}:{action:`invalid`,reason:`archive requires a store name. ${T}`}}return{action:`invalid`,reason:`Unknown sub-command "${r}". ${T}`}}var T,E=e((()=>{T=`Usage: /local-memory list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`}));function D(e){return async(t,n,r)=>{let i=e.parseArgs(r??``);if(O(i))return t(`Invalid args: ${i.reason}`,{display:`system`}),e.errorView(i.reason);try{let r=await e.dispatch(i,t,n);return r===null?null:k.createElement(e.View,r)}catch(n){let r=n instanceof Error?n.message:String(n);return e.onDispatchError?.(n),t(`${e.commandName} failed: ${r}`,{display:`system`}),e.errorView(r)}}}function O(e){return typeof e==`object`&&!!e&&`action`in e&&e.action===`invalid`}var k,A=e((()=>{k=t(g(),1)}));function j(e){return e.length===0?`No memory stores found.`:[`Local Memory Stores`,...e.map(e=>`- ${e}`)].join(`
2
- `)}function M(e,t){return t.length===0?`No entries in "${e}".`:[`Entries in "${e}"`,...t.map(e=>`- ${e}`)].join(`
3
- `)}function N({onDone:e}){let[t,n]=F.useState({kind:`menu`}),[r,l]=F.useState(0),[g,v]=F.useState(``),[b,x]=F.useState(0),[S,C]=F.useState(null),w=F.useCallback(e=>{n(e),v(``),x(0),C(null)},[]),T=F.useCallback(t=>e(t,{display:`system`}),[e]),E=F.useCallback((e,t,n,r,a={})=>{try{if(e===`list`){T(j(u()));return}if(e===`about`){T(L);return}if(!t){C(`Internal: missing store`);return}if(e===`create`){c(t),T(`Store created: ${t}`);return}if(e===`entries`){let e=i(t);T(M(t,e));return}if(e===`archive`){o(t),T(`Archived store: ${t}`);return}if(e===`fetch`){if(!n){C(`Internal: missing key`);return}let e=p(t,n);if(e===null){T(`Entry not found: ${t}/${n}`);return}T(`Entry fetched: ${t}/${n}\n\n${e}`);return}if(e===`store`){if(!n||r===void 0){C(`Internal: missing key or value`);return}if(!a.confirmedOverwrite&&p(t,n)!==null){w({kind:`confirm-overwrite`,store:t,key:n,value:r});return}f(t,n,r),T(`Stored ${t}/${n} (${r.length} chars)`);return}}catch(e){C(e instanceof Error?e.message:String(e))}},[T,w]);if(_((e,n)=>{if(t.kind!==`menu`)return;if(n.upArrow){l(e=>Math.max(0,e-1));return}if(n.downArrow){l(e=>Math.min(z.length-1,e+1));return}if(n.return){let e=z[r];if(!e)return;if(e.kind===`list`||e.kind===`about`){E(e.kind,void 0,void 0,void 0);return}w({kind:`collect-store`,action:e.kind});return}let i=Number(e);Number.isInteger(i)&&i>=1&&i<=z.length&&l(i-1)},{isActive:t.kind===`menu`}),_((e,n)=>{if(t.kind!==`confirm-archive`&&t.kind!==`confirm-overwrite`)return;if(n.escape){w({kind:`menu`});return}let r=e.toLowerCase();r===`y`||n.return?t.kind===`confirm-archive`?E(`archive`,t.store,void 0,void 0):E(`store`,t.store,t.key,t.value,{confirmedOverwrite:!0}):r===`n`&&w({kind:`menu`})},{isActive:t.kind===`confirm-archive`||t.kind===`confirm-overwrite`}),_((e,n)=>{if(!(t.kind!==`collect-store`&&t.kind!==`collect-key`&&t.kind!==`collect-value`)&&n.escape){if(t.kind===`collect-value`){w({kind:`collect-key`,action:t.action,store:t.store});return}if(t.kind===`collect-key`){w({kind:`collect-store`,action:t.action});return}w({kind:`menu`})}},{isActive:t.kind===`collect-store`||t.kind===`collect-key`||t.kind===`collect-value`}),t.kind===`menu`)return(0,I.jsx)(y,{title:`Local Memory`,subtitle:`${z.length} actions`,onCancel:()=>T(`Local memory panel dismissed`),color:`background`,hideInputGuide:!0,children:(0,I.jsxs)(m,{flexDirection:`column`,children:[z.map((e,t)=>(0,I.jsxs)(m,{flexDirection:`row`,children:[(0,I.jsx)(h,{children:`${t===r?`›`:` `} ${e.label}`.padEnd(R)}),(0,I.jsx)(h,{dimColor:!0,children:e.description})]},e.kind)),(0,I.jsx)(m,{marginTop:1,children:(0,I.jsx)(h,{dimColor:!0,children:`↑/↓ or 1-7 select · Enter run · Esc close`})})]})});if(t.kind===`confirm-archive`)return(0,I.jsx)(y,{title:`Confirm Archive`,onCancel:()=>w({kind:`menu`}),color:`warning`,hideInputGuide:!0,children:(0,I.jsxs)(m,{flexDirection:`column`,children:[(0,I.jsxs)(h,{children:[`Archive store "`,t.store,`"? This renames it to *.archived.`]}),(0,I.jsx)(m,{marginTop:1,children:(0,I.jsx)(h,{dimColor:!0,children:`y/Enter = archive · n/Esc = cancel`})})]})});if(t.kind===`confirm-overwrite`)return(0,I.jsx)(y,{title:`Confirm Overwrite`,onCancel:()=>w({kind:`menu`}),color:`warning`,hideInputGuide:!0,children:(0,I.jsxs)(m,{flexDirection:`column`,children:[(0,I.jsxs)(h,{children:[`Entry "`,t.store,`/`,t.key,`" already exists. Overwrite with new value (`,t.value.length,` chars)?`]}),(0,I.jsx)(m,{marginTop:1,children:(0,I.jsx)(h,{dimColor:!0,children:`y/Enter = overwrite · n/Esc = cancel`})})]})});let D=t.kind===`collect-store`?`STORE NAME`:t.kind===`collect-key`?`KEY NAME`:`VALUE`,O=t.kind===`collect-store`?`e.g. my-notes`:t.kind===`collect-key`?`e.g. todo-2026-05-08`:`free text`;return(0,I.jsx)(y,{title:`Local Memory · ${t.kind.replace(`collect-`,``).toUpperCase()}`,onCancel:()=>w({kind:`menu`}),color:`background`,hideInputGuide:!0,children:(0,I.jsxs)(m,{flexDirection:`column`,children:[(0,I.jsx)(m,{children:(0,I.jsx)(h,{dimColor:!0,children:D})}),(0,I.jsxs)(m,{children:[(0,I.jsx)(h,{children:`> `}),(0,I.jsx)(s,{value:g,onChange:e=>{v(e),C(null)},cursorOffset:b,onChangeCursorOffset:x,onSubmit:e=>{let n=e.trim();if(t.kind===`collect-store`){if(!n){C(`Store name required`);return}if(!d(n)){C(`Invalid store name (no /, \\, :, null byte, or leading dot; max 255 chars)`);return}t.action===`create`||t.action===`entries`||t.action===`archive`?t.action===`archive`?w({kind:`confirm-archive`,store:n}):E(t.action,n,void 0,void 0):w({kind:`collect-key`,action:t.action,store:n});return}if(t.kind===`collect-key`){if(!n){C(`Key required`);return}if(!a(n)){C(`Invalid key (allowed: letters/digits/._- only; no leading dot; not a Windows reserved name)`);return}t.action===`fetch`?E(`fetch`,t.store,n,void 0):w({kind:`collect-value`,action:`store`,store:t.store,key:n});return}t.kind===`collect-value`&&E(`store`,t.store,t.key,e)},placeholder:O,columns:70,showCursor:!0})]}),S!==null&&(0,I.jsx)(m,{marginTop:0,children:(0,I.jsxs)(h,{color:`warning`,children:[`✗ `,S]})}),(0,I.jsx)(m,{marginTop:1,children:(0,I.jsx)(h,{dimColor:!0,children:`Enter = next · Esc = back`})})]})})}async function P(e,t){if(e.action===`list`)return t(j(u()),{display:`system`}),null;if(e.action===`create`){let{store:n}=e;return c(n),t(`Store created: ${n}`,{display:`system`}),null}if(e.action===`store`){let{store:n,key:r,value:i}=e;return f(n,r,i),t(`Stored entry "${r}" in store "${n}".`,{display:`system`}),null}if(e.action===`fetch`){let{store:n,key:r}=e,i=p(n,r);return i===null?(t(`Entry not found: ${n}/${r}`,{display:`system`}),null):(t(`Entry fetched: ${n}/${r}\n${i}`,{display:`system`}),null)}if(e.action===`entries`){let{store:n}=e;return t(M(n,i(n)),{display:`system`}),null}if(e.action===`archive`){let{store:n}=e;return o(n),t(`Archived store: ${n}`,{display:`system`}),null}return t(L,{display:`system`}),null}var F,I,L,R,z,B,V;e((()=>{F=t(g(),1),v(),n(),r(),l(),C(),E(),A(),I=b(),L=`Usage: /local-memory list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`,R=26,z=[{kind:`list`,label:`List`,description:`显示所有 store`},{kind:`create`,label:`Create`,description:`创建一个新的记忆 store`},{kind:`store`,label:`Store`,description:`写入条目:store 名 + key + value`},{kind:`fetch`,label:`Fetch`,description:`按 store 名 + key 读取条目`},{kind:`entries`,label:`Entries`,description:`列出某个 store 里的 entry key`},{kind:`archive`,label:`Archive`,description:`归档 store(重命名为 *.archived)`},{kind:`about`,label:`About`,description:`显示命令语法`}],B=D({commandName:`local-memory`,parseArgs:e=>{let t=w(e);return t.action===`invalid`?{action:`invalid`,reason:`${L}\n${t.reason}`}:t},dispatch:P,View:x,errorView:e=>F.createElement(x,{mode:`error`,message:e})}),V=async(e,t,n)=>(n??``).trim()===``?(0,I.jsx)(N,{onDone:e}):B(e,t,n)}))();export{V as callLocalMemory};
@@ -1,8 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{H as t,I as n,P as r,t as i,x as a}from"./src-DL3w8VPk.js";import{t as o}from"./jsx-runtime-Bb4Xn-E0.js";import{c as s,h as c,v as l,y as u}from"./config-DUTgj3js.js";import{n as d,r as f}from"./analytics-DJobLaWP.js";import{n as p,t as m}from"./ThemePicker-CIFKZza0.js";function h(e){return e}function g(e){let t=e.trim().toLowerCase();return t===``||t===`reset`?{sub:`full`}:b.has(t)?{sub:t}:{sub:`full`,unknownArg:t}}function _({onDone:e}){let[,n]=t();return(0,y.jsx)(a,{color:`permission`,children:(0,y.jsx)(m,{onThemeSelect:t=>{n(t),f(`tengu_onboarding_step`,{stepId:h(`theme`)}),e(`Theme set to ${t}.`)},onCancel:()=>e(`Theme picker dismissed.`),skipExitHandling:!0})})}function v({theme:e,hasCompletedOnboarding:t,lastOnboardingVersion:i}){return(0,y.jsxs)(n,{flexDirection:`column`,paddingLeft:1,children:[(0,y.jsx)(r,{bold:!0,children:`Onboarding status`}),(0,y.jsxs)(r,{children:[`- Theme: `,(0,y.jsx)(r,{bold:!0,children:e})]}),(0,y.jsxs)(r,{children:[`- Onboarding completed:`,` `,(0,y.jsx)(r,{bold:!0,color:t?`success`:`warning`,children:t?`yes`:`no`})]}),(0,y.jsxs)(r,{children:[`- Last onboarding version: `,(0,y.jsx)(r,{bold:!0,children:i})]}),(0,y.jsx)(r,{dimColor:!0,children:`Run /onboarding (no args) to re-run the full flow, or /onboarding theme | trust | model | mcp for a specific step.`})]})}var y,b,x;e((()=>{i(),d(),p(),c(),y=o(),b=new Set([`full`,`theme`,`trust`,`model`,`mcp`,`status`]),x=async(e,t,n)=>{let{sub:r,unknownArg:i}=g(n);if(f(`tengu_onboarding_step`,{stepId:h(`slash_${r}`)}),i!==void 0)return e(`Unknown /onboarding subcommand: \`${i}\`.\nValid: full | theme | trust | model | mcp | status`,{display:`system`}),null;if(r===`theme`)return(0,y.jsx)(_,{onDone:t=>e(t)});if(r===`trust`)return l(e=>({...e,hasTrustDialogAccepted:!1})),e("Workspace trust cleared for the current project. The trust dialog will appear on the next `claude` launch.",{display:`system`}),null;if(r===`model`)return e("Run `/model` to pick the AI model. Onboarding does not own the model picker; this entry exists for discoverability only.",{display:`system`}),null;if(r===`mcp`)return e("MCP server setup:\n - `/mcp` — list configured MCP servers\n - `claude mcp add <name> <command>` — add a server (in your shell)\n - `claude mcp remove <name>` — remove a server\nServers also load from `.mcp.json` in the workspace and from `~/.workmate.json` globally.",{display:`system`}),null;if(r===`status`){let e=s();return(0,y.jsx)(v,{theme:e.theme??`(unset)`,hasCompletedOnboarding:e.hasCompletedOnboarding===!0,lastOnboardingVersion:e.lastOnboardingVersion??`(unset)`})}return u(e=>({...e,hasCompletedOnboarding:!1})),e(`Onboarding flag cleared. The full first-run setup (theme, OAuth/API key, security notes, terminal-setup) will run on the next \`claude\` launch.
2
-
3
- For individual steps in this session, use:
4
- /onboarding theme — re-pick theme inline
5
- /onboarding trust — re-confirm workspace trust on next launch
6
- /onboarding model — open /model picker
7
- /onboarding mcp — show MCP setup hints
8
- /onboarding status — show current onboarding state`,{display:`system`}),null}}))();export{x as callOnboarding};