purplemux 0.2.4 → 0.2.5

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 (329) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +70 -70
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/routes-manifest.json +7 -7
  6. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0-qfa-x._.js +3 -0
  7. package/.next/standalone/.next/server/chunks/[root-of-the-server]__00nrs0h._.js +3 -0
  8. package/.next/standalone/.next/server/chunks/[root-of-the-server]__03x8rds._.js +3 -0
  9. package/.next/standalone/.next/server/chunks/[root-of-the-server]__04cr_m8._.js +1 -1
  10. package/.next/standalone/.next/server/chunks/[root-of-the-server]__06j59n1._.js +3 -0
  11. package/.next/standalone/.next/server/chunks/[root-of-the-server]__07gfnob._.js +1 -1
  12. package/.next/standalone/.next/server/chunks/[root-of-the-server]__07xijrd._.js +1 -1
  13. package/.next/standalone/.next/server/chunks/[root-of-the-server]__08tdlcm._.js +1 -1
  14. package/.next/standalone/.next/server/chunks/[root-of-the-server]__09_6_.~._.js +3 -0
  15. package/.next/standalone/.next/server/chunks/[root-of-the-server]__09gkm_6._.js +1 -1
  16. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_uldiw._.js +15 -0
  17. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0a4t.z5._.js +52 -0
  18. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0bo-su1._.js +1 -1
  19. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0c-bb5d._.js +1 -1
  20. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0dvelfj._.js +52 -0
  21. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0e.7isl._.js +5 -0
  22. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0gcec.8._.js +3 -0
  23. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ihlt6s._.js +1 -1
  24. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0qvunc5._.js +1 -1
  25. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0r77-u1._.js +52 -0
  26. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0vi8p6v._.js +1 -1
  27. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0w3m-oz._.js +1 -1
  28. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zh8xur._.js +3 -0
  29. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0~iu3jq._.js +3 -0
  30. package/.next/standalone/.next/server/chunks/[root-of-the-server]__12nr~pb._.js +1 -1
  31. package/.next/standalone/.next/server/chunks/{_0v81st0._.js → _0.pa6m1._.js} +1 -1
  32. package/.next/standalone/.next/server/chunks/_05ib7yu._.js +3 -0
  33. package/.next/standalone/.next/server/chunks/{_0ll-5~7._.js → _09y8.gr._.js} +1 -1
  34. package/.next/standalone/.next/server/chunks/{_0.5a4bu._.js → _0mwq11h._.js} +1 -1
  35. package/.next/standalone/.next/server/chunks/_0y4b49w._.js +3 -0
  36. package/.next/standalone/.next/server/chunks/_0zcb2f0._.js +3 -0
  37. package/.next/standalone/.next/server/chunks/{node_modules_ws_124xx2_._.js → _106a~ya._.js} +2 -2
  38. package/.next/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_pages-api_00-t8sq.js +1 -1
  39. package/.next/standalone/.next/server/chunks/src_lib_00fhuqb._.js +3 -0
  40. package/.next/standalone/.next/server/chunks/src_lib_0dvlmi4._.js +15 -0
  41. package/.next/standalone/.next/server/chunks/src_lib_0ojl2hg._.js +52 -0
  42. package/.next/standalone/.next/server/chunks/src_lib_layout-store_ts_0fanx7c._.js +1 -1
  43. package/.next/standalone/.next/server/chunks/src_lib_status-manager_ts_003hlhy._.js +1 -13
  44. package/.next/standalone/.next/server/chunks/src_lib_workspace-store_ts_0vqt073._.js +1 -40
  45. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0t9ru13._.js +1 -1
  46. package/.next/standalone/.next/server/chunks/ssr/{_0o8h1fd._.js → _0-kyl7i._.js} +2 -2
  47. package/.next/standalone/.next/server/chunks/ssr/_017c8be._.js +3 -0
  48. package/.next/standalone/.next/server/chunks/ssr/{_0c1yivm._.js → _070zc_o._.js} +2 -2
  49. package/.next/standalone/.next/server/chunks/ssr/_07jud1p._.js +1 -1
  50. package/.next/standalone/.next/server/chunks/ssr/_0_uqm-4._.js +3 -0
  51. package/.next/standalone/.next/server/chunks/ssr/{_0ftinmo._.js → _0ed.wmt._.js} +2 -2
  52. package/.next/standalone/.next/server/chunks/ssr/_0lpqhot._.js +3 -0
  53. package/.next/standalone/.next/server/chunks/ssr/_0pg-q18._.js +1 -1
  54. package/.next/standalone/.next/server/chunks/ssr/_0pp3e5j._.js +1 -1
  55. package/.next/standalone/.next/server/chunks/ssr/_0ttiybw._.js +18 -0
  56. package/.next/standalone/.next/server/chunks/ssr/_0w.1ts8._.js +1 -1
  57. package/.next/standalone/.next/server/chunks/ssr/_0w6jc9p._.js +1 -1
  58. package/.next/standalone/.next/server/chunks/ssr/_0xp3-y6._.js +3 -0
  59. package/.next/standalone/.next/server/chunks/ssr/{_11v_6.6._.js → _0y7o.rg._.js} +2 -2
  60. package/.next/standalone/.next/server/chunks/ssr/_0ytb_c0._.js +3 -0
  61. package/.next/standalone/.next/server/chunks/ssr/{_02jzd5g._.js → _13gee5r._.js} +2 -2
  62. package/.next/standalone/.next/server/chunks/ssr/messages_de_terminal_json_[json]_cjs_05jirtw._.js +1 -1
  63. package/.next/standalone/.next/server/chunks/ssr/messages_en_terminal_json_[json]_cjs_0~ls3g-._.js +1 -1
  64. package/.next/standalone/.next/server/chunks/ssr/messages_es_terminal_json_[json]_cjs_04g2b1_._.js +1 -1
  65. package/.next/standalone/.next/server/chunks/ssr/messages_fr_terminal_json_[json]_cjs_0uhakya._.js +1 -1
  66. package/.next/standalone/.next/server/chunks/ssr/messages_ja_terminal_json_[json]_cjs_0776z4f._.js +1 -1
  67. package/.next/standalone/.next/server/chunks/ssr/messages_ko_terminal_json_[json]_cjs_06611.3._.js +1 -1
  68. package/.next/standalone/.next/server/chunks/ssr/messages_pt-BR_terminal_json_[json]_cjs_034yyg9._.js +1 -1
  69. package/.next/standalone/.next/server/chunks/ssr/messages_ru_terminal_json_[json]_cjs_0emk8~n._.js +1 -1
  70. package/.next/standalone/.next/server/chunks/ssr/messages_tr_terminal_json_[json]_cjs_0xpix8g._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/ssr/messages_zh-CN_terminal_json_[json]_cjs_12vwl8a._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/ssr/messages_zh-TW_terminal_json_[json]_cjs_0spg5z5._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/ssr/{src_components_0_aiven._.js → src_components_0_nzv1r._.js} +1 -1
  74. package/.next/standalone/.next/server/chunks/ssr/{src_components_0geizrr._.js → src_components_0bqqfju._.js} +1 -1
  75. package/.next/standalone/.next/server/chunks/ssr/{src_components_11_1i~k._.js → src_components_0rqxlj-._.js} +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/{src_components_12mrirb._.js → src_components_0s~.n3e._.js} +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/src_components_features_mobile_mobile-terminal-page_tsx_02chzch._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/src_components_features_workspace_terminal-page_tsx_0wuq-jl._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/src_lib_workspace-store_ts_00x-rec._.js +10 -0
  80. package/.next/standalone/.next/server/middleware-build-manifest.js +70 -70
  81. package/.next/standalone/.next/server/pages/_app/build-manifest.json +3 -3
  82. package/.next/standalone/.next/server/pages/_app/client-build-manifest.json +1 -1
  83. package/.next/standalone/.next/server/pages/api/auth/login.js +2 -2
  84. package/.next/standalone/.next/server/pages/api/auth/login.js.nft.json +1 -1
  85. package/.next/standalone/.next/server/pages/api/auth/preflight.js +2 -2
  86. package/.next/standalone/.next/server/pages/api/auth/preflight.js.nft.json +1 -1
  87. package/.next/standalone/.next/server/pages/api/auth/setup.js +2 -2
  88. package/.next/standalone/.next/server/pages/api/auth/setup.js.nft.json +1 -1
  89. package/.next/standalone/.next/server/pages/api/check-claude.js +5 -1
  90. package/.next/standalone/.next/server/pages/api/check-claude.js.nft.json +1 -1
  91. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/console.js +2 -2
  92. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/console.js.nft.json +1 -1
  93. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/eval.js +2 -2
  94. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/eval.js.nft.json +1 -1
  95. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/network.js +2 -2
  96. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/network.js.nft.json +1 -1
  97. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/screenshot.js +2 -2
  98. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/screenshot.js.nft.json +1 -1
  99. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/url.js +2 -2
  100. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/browser/url.js.nft.json +1 -1
  101. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/result.js +2 -2
  102. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/result.js.nft.json +1 -1
  103. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/send.js +2 -2
  104. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/send.js.nft.json +1 -1
  105. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/status.js +2 -2
  106. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId]/status.js.nft.json +1 -1
  107. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId].js +2 -2
  108. package/.next/standalone/.next/server/pages/api/cli/tabs/[tabId].js.nft.json +1 -1
  109. package/.next/standalone/.next/server/pages/api/cli/tabs.js +2 -2
  110. package/.next/standalone/.next/server/pages/api/cli/tabs.js.nft.json +1 -1
  111. package/.next/standalone/.next/server/pages/api/cli/workspaces.js +2 -2
  112. package/.next/standalone/.next/server/pages/api/cli/workspaces.js.nft.json +1 -1
  113. package/.next/standalone/.next/server/pages/api/config.js +2 -2
  114. package/.next/standalone/.next/server/pages/api/config.js.nft.json +1 -1
  115. package/.next/standalone/.next/server/pages/api/layout/diff.js +1 -1
  116. package/.next/standalone/.next/server/pages/api/layout/diff.js.nft.json +1 -1
  117. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/[tabId]/move.js +2 -2
  118. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/[tabId]/move.js.nft.json +1 -1
  119. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/[tabId].js +5 -5
  120. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/[tabId].js.nft.json +1 -1
  121. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/order.js +2 -2
  122. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs/order.js.nft.json +1 -1
  123. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs.js +5 -5
  124. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId]/tabs.js.nft.json +1 -1
  125. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId].js +2 -2
  126. package/.next/standalone/.next/server/pages/api/layout/pane/[paneId].js.nft.json +1 -1
  127. package/.next/standalone/.next/server/pages/api/layout/pane.js +2 -2
  128. package/.next/standalone/.next/server/pages/api/layout/pane.js.nft.json +1 -1
  129. package/.next/standalone/.next/server/pages/api/layout.js +2 -2
  130. package/.next/standalone/.next/server/pages/api/layout.js.nft.json +1 -1
  131. package/.next/standalone/.next/server/pages/api/message-history.js +2 -2
  132. package/.next/standalone/.next/server/pages/api/message-history.js.nft.json +1 -1
  133. package/.next/standalone/.next/server/pages/api/preflight/runtime.js.nft.json +1 -1
  134. package/.next/standalone/.next/server/pages/api/stats/daily-report/cache.js.nft.json +1 -1
  135. package/.next/standalone/.next/server/pages/api/stats/daily-report/generate.js.nft.json +1 -1
  136. package/.next/standalone/.next/server/pages/api/stats/daily-report/list.js.nft.json +1 -1
  137. package/.next/standalone/.next/server/pages/api/stats/projects.js.nft.json +1 -1
  138. package/.next/standalone/.next/server/pages/api/stats/sessions.js.nft.json +1 -1
  139. package/.next/standalone/.next/server/pages/api/stats/uptime.js.nft.json +1 -1
  140. package/.next/standalone/.next/server/pages/api/status/hook.js +6 -6
  141. package/.next/standalone/.next/server/pages/api/status/hook.js.nft.json +1 -1
  142. package/.next/standalone/.next/server/pages/api/status/statusline.js +6 -6
  143. package/.next/standalone/.next/server/pages/api/status/statusline.js.nft.json +1 -1
  144. package/.next/standalone/.next/server/pages/api/timeline/sessions.js.nft.json +1 -1
  145. package/.next/standalone/.next/server/pages/api/tmux/permission-options.js +3 -2
  146. package/.next/standalone/.next/server/pages/api/tmux/permission-options.js.nft.json +1 -1
  147. package/.next/standalone/.next/server/pages/api/tmux/plan-options.js +3 -2
  148. package/.next/standalone/.next/server/pages/api/tmux/plan-options.js.nft.json +1 -1
  149. package/.next/standalone/.next/server/pages/api/tmux/recover-unknown.js +5 -5
  150. package/.next/standalone/.next/server/pages/api/tmux/recover-unknown.js.nft.json +1 -1
  151. package/.next/standalone/.next/server/pages/api/tmux/reset.js +5 -5
  152. package/.next/standalone/.next/server/pages/api/tmux/reset.js.nft.json +1 -1
  153. package/.next/standalone/.next/server/pages/api/workspace/[workspaceId].js +2 -2
  154. package/.next/standalone/.next/server/pages/api/workspace/[workspaceId].js.nft.json +1 -1
  155. package/.next/standalone/.next/server/pages/api/workspace/active.js +2 -2
  156. package/.next/standalone/.next/server/pages/api/workspace/active.js.nft.json +1 -1
  157. package/.next/standalone/.next/server/pages/api/workspace/group/[groupId].js +2 -2
  158. package/.next/standalone/.next/server/pages/api/workspace/group/[groupId].js.nft.json +1 -1
  159. package/.next/standalone/.next/server/pages/api/workspace/group/reorder.js +2 -2
  160. package/.next/standalone/.next/server/pages/api/workspace/group/reorder.js.nft.json +1 -1
  161. package/.next/standalone/.next/server/pages/api/workspace/group.js +2 -2
  162. package/.next/standalone/.next/server/pages/api/workspace/group.js.nft.json +1 -1
  163. package/.next/standalone/.next/server/pages/api/workspace/reorder.js +2 -2
  164. package/.next/standalone/.next/server/pages/api/workspace/reorder.js.nft.json +1 -1
  165. package/.next/standalone/.next/server/pages/api/workspace/validate.js +2 -2
  166. package/.next/standalone/.next/server/pages/api/workspace/validate.js.nft.json +1 -1
  167. package/.next/standalone/.next/server/pages/api/workspace.js +5 -5
  168. package/.next/standalone/.next/server/pages/api/workspace.js.nft.json +1 -1
  169. package/.next/standalone/.next/server/pages/de/404.html +1 -1
  170. package/.next/standalone/.next/server/pages/de/500.html +1 -1
  171. package/.next/standalone/.next/server/pages/en/404.html +1 -1
  172. package/.next/standalone/.next/server/pages/en/500.html +1 -1
  173. package/.next/standalone/.next/server/pages/es/404.html +1 -1
  174. package/.next/standalone/.next/server/pages/es/500.html +1 -1
  175. package/.next/standalone/.next/server/pages/fr/404.html +1 -1
  176. package/.next/standalone/.next/server/pages/fr/500.html +1 -1
  177. package/.next/standalone/.next/server/pages/index/build-manifest.json +15 -15
  178. package/.next/standalone/.next/server/pages/index/client-build-manifest.json +1 -1
  179. package/.next/standalone/.next/server/pages/index/react-loadable-manifest.json +6 -6
  180. package/.next/standalone/.next/server/pages/index.js +8 -8
  181. package/.next/standalone/.next/server/pages/index.js.nft.json +1 -1
  182. package/.next/standalone/.next/server/pages/ja/404.html +1 -1
  183. package/.next/standalone/.next/server/pages/ja/500.html +1 -1
  184. package/.next/standalone/.next/server/pages/ko/404.html +1 -1
  185. package/.next/standalone/.next/server/pages/ko/500.html +1 -1
  186. package/.next/standalone/.next/server/pages/login/build-manifest.json +6 -6
  187. package/.next/standalone/.next/server/pages/login/client-build-manifest.json +1 -1
  188. package/.next/standalone/.next/server/pages/login.js +4 -4
  189. package/.next/standalone/.next/server/pages/login.js.nft.json +1 -1
  190. package/.next/standalone/.next/server/pages/pt-BR/404.html +1 -1
  191. package/.next/standalone/.next/server/pages/pt-BR/500.html +1 -1
  192. package/.next/standalone/.next/server/pages/reports/build-manifest.json +14 -14
  193. package/.next/standalone/.next/server/pages/reports/client-build-manifest.json +1 -1
  194. package/.next/standalone/.next/server/pages/reports.js +9 -9
  195. package/.next/standalone/.next/server/pages/reports.js.nft.json +1 -1
  196. package/.next/standalone/.next/server/pages/reset.js.nft.json +1 -1
  197. package/.next/standalone/.next/server/pages/ru/404.html +1 -1
  198. package/.next/standalone/.next/server/pages/ru/500.html +1 -1
  199. package/.next/standalone/.next/server/pages/stats/build-manifest.json +12 -12
  200. package/.next/standalone/.next/server/pages/stats/client-build-manifest.json +1 -1
  201. package/.next/standalone/.next/server/pages/stats.js +9 -9
  202. package/.next/standalone/.next/server/pages/stats.js.nft.json +1 -1
  203. package/.next/standalone/.next/server/pages/tools-required/build-manifest.json +4 -4
  204. package/.next/standalone/.next/server/pages/tools-required/client-build-manifest.json +1 -1
  205. package/.next/standalone/.next/server/pages/tools-required.js +4 -4
  206. package/.next/standalone/.next/server/pages/tools-required.js.nft.json +1 -1
  207. package/.next/standalone/.next/server/pages/tr/404.html +1 -1
  208. package/.next/standalone/.next/server/pages/tr/500.html +1 -1
  209. package/.next/standalone/.next/server/pages/webview/build-manifest.json +13 -13
  210. package/.next/standalone/.next/server/pages/webview/client-build-manifest.json +1 -1
  211. package/.next/standalone/.next/server/pages/webview.js +6 -6
  212. package/.next/standalone/.next/server/pages/webview.js.nft.json +1 -1
  213. package/.next/standalone/.next/server/pages/zh-CN/404.html +1 -1
  214. package/.next/standalone/.next/server/pages/zh-CN/500.html +1 -1
  215. package/.next/standalone/.next/server/pages/zh-TW/404.html +1 -1
  216. package/.next/standalone/.next/server/pages/zh-TW/500.html +1 -1
  217. package/.next/standalone/.next/static/chunks/{11tnyk0iystp1.js → 0--r5y9cw3.0z.js} +1 -1
  218. package/.next/standalone/.next/static/chunks/{08.6.1cg_x8r-.js → 00gxls80r--_0.js} +6 -6
  219. package/.next/standalone/.next/static/chunks/{0w0qmu364g~xt.js → 01rmp.m_ls7z_.js} +1 -1
  220. package/.next/standalone/.next/static/chunks/{09lb6md956bhb.js → 0628quqp4ggh9.js} +1 -1
  221. package/.next/standalone/.next/static/chunks/{0zmym5gg0bnkg.js → 06ak74s111wx-.js} +1 -1
  222. package/.next/standalone/.next/static/chunks/{0g-71jn3elu8f.js → 08d6vee5l~1wn.js} +1 -1
  223. package/.next/standalone/.next/static/chunks/{16.twr9cx.kle.js → 09o2m0ingey8v.js} +1 -1
  224. package/.next/standalone/.next/static/chunks/{00s78xqkxglkv.js → 0a1xt.enr50l5.js} +1 -1
  225. package/.next/standalone/.next/static/chunks/{0p~_~afvrxx99.js → 0am7rh7xdv5lw.js} +3 -3
  226. package/.next/standalone/.next/static/chunks/{0thg_6bh34-xa.js → 0f3q6qhpk.i_r.js} +1 -1
  227. package/.next/standalone/.next/static/chunks/{0cmg_jvd.7c43.js → 0fsldybjx443~.js} +1 -1
  228. package/.next/standalone/.next/static/chunks/0gfhd.gsbt9qg.js +1 -0
  229. package/.next/standalone/.next/static/chunks/0ic.mcu6-9din.js +1 -0
  230. package/.next/standalone/.next/static/chunks/0k4b.~5c4nvtm.js +1 -0
  231. package/.next/standalone/.next/static/chunks/{0r69~xx12-zsq.js → 0lujhtd04orw5.js} +1 -1
  232. package/.next/standalone/.next/static/chunks/0qqsez8ir1.fs.js +1 -0
  233. package/.next/standalone/.next/static/chunks/{13j5zp717ie6d.js → 0rahh2v7~f4tj.js} +13 -13
  234. package/.next/standalone/.next/static/chunks/{0pxbg4s8a4y54.js → 0rb41e1r1urhx.js} +1 -1
  235. package/.next/standalone/.next/static/chunks/0uii4rziiew3_.js +1 -0
  236. package/.next/standalone/.next/static/chunks/0vtkq~yk_1~gv.js +1 -0
  237. package/.next/standalone/.next/static/chunks/0vx2hhzc46h_7.js +1 -0
  238. package/.next/standalone/.next/static/chunks/{13i76gpwz2k5a.js → 0x_.wshvak6zp.js} +1 -1
  239. package/.next/standalone/.next/static/chunks/0xpr6vw-p8oxk.js +1 -0
  240. package/.next/standalone/.next/static/chunks/{0s7sv9xe3e1c9.js → 0zn1jt__-t51p.js} +1 -1
  241. package/.next/standalone/.next/static/chunks/0zrhxc96zwjuv.js +1 -0
  242. package/.next/standalone/.next/static/chunks/0z~yy1lqrvp_a.js +1 -0
  243. package/.next/standalone/.next/static/chunks/0~cgr_3dpx0vl.js +1 -0
  244. package/.next/standalone/.next/static/chunks/{0b.a4_8picceu.js → 0~g0t2q6o3r-7.js} +4 -4
  245. package/.next/standalone/.next/static/chunks/0~vfb0ylk_9au.js +16 -0
  246. package/.next/standalone/.next/static/chunks/{0batq-3sj.qi1.js → 10uz6x-h~dv0..js} +14 -14
  247. package/.next/standalone/.next/static/chunks/{0q9y8zysz~put.js → 13q-ol3bkz8ft.js} +15 -15
  248. package/.next/standalone/.next/static/chunks/14if5vtky.3sn.js +1 -0
  249. package/.next/standalone/.next/static/chunks/15i_n03eg5uyp.js +1 -0
  250. package/.next/standalone/.next/static/chunks/1756nfyulu.9h.css +1 -0
  251. package/.next/standalone/.next/static/chunks/{0._2l5v1hwkfn.js → 17rh_.7tkk2m0.js} +12 -12
  252. package/.next/standalone/.next/static/chunks/{turbopack-0q6z-bk-atg2w.js → turbopack-02..gqxjw9fev.js} +1 -1
  253. package/.next/standalone/.next/static/chunks/{turbopack-06o7eaf8n1nth.js → turbopack-05luogg2yney~.js} +1 -1
  254. package/.next/standalone/.next/static/chunks/{turbopack-0vv2_r1br0hyc.js → turbopack-092b2t67-z3ds.js} +1 -1
  255. package/.next/standalone/.next/static/chunks/{turbopack-0sa282u154fdk.js → turbopack-0eue2xixdnbd..js} +1 -1
  256. package/.next/standalone/.next/static/chunks/{turbopack-0f2cool0ub~vp.js → turbopack-0i6l53-j6t6zg.js} +1 -1
  257. package/.next/standalone/.next/static/chunks/{turbopack-0-ooli-pimh-6.js → turbopack-0ser1ty-sh2jk.js} +1 -1
  258. package/.next/standalone/.next/static/chunks/{turbopack-0duv.5cir9jm5.js → turbopack-0zouy.~ram.7g.js} +1 -1
  259. package/.next/standalone/.next/static/{CjJlqsAWYyyu76AJtHaqt → onsm_2jNZvyggHqM9yibn}/_buildManifest.js +6 -6
  260. package/.next/standalone/messages/de/terminal.json +4 -0
  261. package/.next/standalone/messages/en/terminal.json +4 -0
  262. package/.next/standalone/messages/es/terminal.json +4 -0
  263. package/.next/standalone/messages/fr/terminal.json +4 -0
  264. package/.next/standalone/messages/ja/terminal.json +4 -0
  265. package/.next/standalone/messages/ko/terminal.json +4 -0
  266. package/.next/standalone/messages/pt-BR/terminal.json +4 -0
  267. package/.next/standalone/messages/ru/terminal.json +4 -0
  268. package/.next/standalone/messages/tr/terminal.json +4 -0
  269. package/.next/standalone/messages/zh-CN/terminal.json +4 -0
  270. package/.next/standalone/messages/zh-TW/terminal.json +4 -0
  271. package/.next/standalone/package.json +1 -1
  272. package/.next/standalone/server.js +1 -1
  273. package/.next/standalone/src/config/tmux.conf +17 -7
  274. package/.next/standalone/src/lib/providers/claude/index.ts +44 -0
  275. package/.next/standalone/src/pages/api/layout/pane/[paneId]/tabs/index.ts +13 -6
  276. package/README.de.md +1 -1
  277. package/README.es.md +1 -1
  278. package/README.fr.md +1 -1
  279. package/README.ja.md +1 -1
  280. package/README.ko.md +1 -1
  281. package/README.md +1 -1
  282. package/README.pt-BR.md +1 -1
  283. package/README.ru.md +1 -1
  284. package/README.tr.md +1 -1
  285. package/README.zh-CN.md +1 -1
  286. package/README.zh-TW.md +1 -1
  287. package/dist/server.js +970 -851
  288. package/package.json +1 -1
  289. package/src/config/tmux.conf +17 -7
  290. package/.next/standalone/.next/server/chunks/[root-of-the-server]__01.~37j._.js +0 -3
  291. package/.next/standalone/.next/server/chunks/[root-of-the-server]__016s4a9._.js +0 -3
  292. package/.next/standalone/.next/server/chunks/[root-of-the-server]__03l15.f._.js +0 -3
  293. package/.next/standalone/.next/server/chunks/[root-of-the-server]__05ij_ys._.js +0 -42
  294. package/.next/standalone/.next/server/chunks/[root-of-the-server]__06h3gzy._.js +0 -3
  295. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0auutl5._.js +0 -5
  296. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0d-inw8._.js +0 -3
  297. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0i-jyh3._.js +0 -3
  298. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0l~_wd0._.js +0 -3
  299. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ovn6yp._.js +0 -3
  300. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0un_g-o._.js +0 -3
  301. package/.next/standalone/.next/server/chunks/[root-of-the-server]__12ksl6n._.js +0 -42
  302. package/.next/standalone/.next/server/chunks/_03-duro._.js +0 -3
  303. package/.next/standalone/.next/server/chunks/_07097f~._.js +0 -3
  304. package/.next/standalone/.next/server/chunks/_0z7d6.z._.js +0 -3
  305. package/.next/standalone/.next/server/chunks/src_lib_0p.xsqi._.js +0 -3
  306. package/.next/standalone/.next/server/chunks/ssr/_016o9_-._.js +0 -3
  307. package/.next/standalone/.next/server/chunks/ssr/_0a64og5._.js +0 -3
  308. package/.next/standalone/.next/server/chunks/ssr/_0ccg0_z._.js +0 -18
  309. package/.next/standalone/.next/server/chunks/ssr/_0fnzfs-._.js +0 -3
  310. package/.next/standalone/.next/server/chunks/ssr/_0hat6~g._.js +0 -3
  311. package/.next/standalone/.next/server/chunks/ssr/_0hp8_ck._.js +0 -3
  312. package/.next/standalone/.next/server/chunks/ssr/_0hq29bt._.js +0 -3
  313. package/.next/standalone/.next/static/chunks/02ncyh-v8g~cs.css +0 -1
  314. package/.next/standalone/.next/static/chunks/08d4u-qlylmde.js +0 -1
  315. package/.next/standalone/.next/static/chunks/08f708~_7uy_i.js +0 -1
  316. package/.next/standalone/.next/static/chunks/08ojbbzi2ergt.js +0 -16
  317. package/.next/standalone/.next/static/chunks/0cvx059r5hgj1.js +0 -1
  318. package/.next/standalone/.next/static/chunks/0gn-f6_m696k0.js +0 -1
  319. package/.next/standalone/.next/static/chunks/0u.snf3d~5nvq.js +0 -1
  320. package/.next/standalone/.next/static/chunks/0v.l~.~v98c2c.js +0 -1
  321. package/.next/standalone/.next/static/chunks/0wu~4k-l8otuy.js +0 -1
  322. package/.next/standalone/.next/static/chunks/0y441gn709g7u.js +0 -1
  323. package/.next/standalone/.next/static/chunks/0yb~gw6ukzdmo.js +0 -1
  324. package/.next/standalone/.next/static/chunks/0yg3hj1g~k1ip.js +0 -1
  325. package/.next/standalone/.next/static/chunks/0~c6h8j7ut2ca.js +0 -1
  326. package/.next/standalone/.next/static/chunks/15m4y6otktj8z.js +0 -1
  327. package/.next/standalone/.next/static/chunks/17ebdp-_o5o30.js +0 -1
  328. /package/.next/standalone/.next/static/{CjJlqsAWYyyu76AJtHaqt → onsm_2jNZvyggHqM9yibn}/_clientMiddlewareManifest.js +0 -0
  329. /package/.next/standalone/.next/static/{CjJlqsAWYyyu76AJtHaqt → onsm_2jNZvyggHqM9yibn}/_ssgManifest.js +0 -0
@@ -0,0 +1,3 @@
1
+ module.exports=[758518,e=>{"use strict";var t=e.i(926747),r=e.i(190406),s=e.i(244898),a=e.i(262950),i=e.i(459015),n=e.i(322429),o=e.i(825265),l=e.i(804767);e.i(462180);var u=e.i(282992),d=e.i(25146);let p=(0,d.createLogger)("auto-resume"),m=new Set(["bash","zsh","fish","sh","dash"]),c=async()=>{let{workspaces:e}=await (0,n.getWorkspaces)(),t=[];for(let r of e){let e=await (0,o.readLayoutFile)((0,o.resolveLayoutFile)(r.id));if(e)for(let s of(0,l.collectAllTabs)(e.root)){let e=(0,u.getProviderByPanelType)(s.panelType);if(!e)continue;let a=e.readSessionId(s);a&&t.push({workspaceId:r.id,tabId:s.id,tmuxSession:s.sessionName,sessionId:a,provider:e})}}return t},g=async e=>{try{let t=await (0,i.getPaneCurrentCommand)(e.tmuxSession);if(!t)return p.warn(`Cannot check process: ${e.tmuxSession}`),!1;if(!m.has(t)){let r=(0,u.getProviderByProcessName)(t);if(r&&r.id===e.provider.id)return p.debug(`${e.provider.displayName} already running, skip: ${e.tmuxSession}`),!0;return p.debug(`Non-shell process running (${t}), skip: ${e.tmuxSession}`),!1}let r=await e.provider.buildResumeCommand(e.sessionId,{workspaceId:e.workspaceId});return p.debug(`Sending resume: ${e.tmuxSession} → ${e.sessionId}`),await (0,i.sendKeys)(e.tmuxSession,r),!0}catch(t){return p.error(`Failed: ${e.tmuxSession} — ${t instanceof Error?t.message:t}`),!1}},h=async e=>{let t=!1;for(let r of e)await (0,i.hasSession)(r.tmuxSession)||(p.debug(`No tmux session, creating new: ${r.tmuxSession}`),await (0,i.createSession)(r.tmuxSession,80,24),t=!0);t&&await new Promise(e=>setTimeout(e,500)),await Promise.allSettled(e.map(e=>g(e)))},v=async()=>{let e=await c();0!==e.length&&(p.debug(`${e.length} surface(s) auto-resume started`),h(e).then(()=>{p.debug("Auto-resume complete")}).catch(e=>{p.error(`Auto-resume error: ${e instanceof Error?e.message:e}`)}))};var f=e.i(964759);let w=(0,d.createLogger)("terminal"),S=async(e,t)=>{if("POST"!==e.method)return t.setHeader("Allow","POST"),t.status(405).json({error:"Method not allowed"});try{let e=await (0,i.listSessions)();return w.info(`tmux reset requested — killing ${e.length} session(s)`),await (0,i.killServer)(),await (0,i.scanSessions)(),await (0,i.applyConfig)(),await (0,n.initWorkspaceStore)(),await v(),await (0,f.getStatusManager)().rescan(),w.info("tmux re-initialized after reset"),t.status(200).json({killed:e.length})}catch(e){return w.error(`tmux reset failed: ${e instanceof Error?e.message:e}`),t.status(500).json({error:"tmux reset failed"})}};e.s(["default",0,S],191170);var x=e.i(191170),y=e.i(7031),P=e.i(181927),$=e.i(846432);let b=(0,a.hoist)(x,"default"),R=(0,a.hoist)(x,"config"),k=new s.PagesAPIRouteModule({definition:{kind:r.RouteKind.PAGES_API,page:"/api/tmux/reset",pathname:"/api/tmux/reset",bundlePath:"",filename:""},userland:x,distDir:".next",relativeProjectDir:""});async function A(e,r,s){s.requestMeta&&(0,$.setRequestMeta)(e,s.requestMeta),k.isDev&&(0,$.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let a="/api/tmux/reset";a=a.replace(/\/index$/,"")||"/";let i=await k.prepare(e,r,{srcPage:a});if(!i){r.statusCode=400,r.end("Bad Request"),null==s.waitUntil||s.waitUntil.call(s,Promise.resolve());return}let{query:n,params:o,prerenderManifest:l,routerServerContext:u}=i;try{let t,s=e.method||"GET",i=(0,y.getTracer)(),d=i.getActiveScopeSpan(),p=!!(null==u?void 0:u.isWrappedByNextServer),m=k.instrumentationOnRequestError.bind(k),c=async d=>k.render(e,r,{query:{...n,...o},params:o,allowedRevalidateHeaderKeys:[],multiZoneDraftMode:!1,trustHostHeader:!1,previewProps:l.preview,propagateError:!1,dev:k.isDev,page:"/api/tmux/reset",internalRevalidate:null==u?void 0:u.revalidate,onError:(...t)=>m(e,...t)}).finally(()=>{if(!d)return;d.setAttributes({"http.status_code":r.statusCode,"next.rsc":!1});let e=i.getRootSpanAttributes();if(!e)return;if(e.get("next.span_type")!==P.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${e.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=e.get("next.route");if(n){let e=`${s} ${n}`;d.setAttributes({"next.route":n,"http.route":n,"next.span_name":e}),d.updateName(e),t&&t!==d&&(t.setAttribute("http.route",n),t.updateName(e))}else d.updateName(`${s} ${a}`)});p&&d?await c(d):(t=i.getActiveScopeSpan(),await i.withPropagatedContext(e.headers,()=>i.trace(P.BaseServerSpan.handleRequest,{spanName:`${s} ${a}`,kind:y.SpanKind.SERVER,attributes:{"http.method":s,"http.target":e.url}},c),void 0,!p))}catch(e){if(k.isDev)throw e;(0,t.sendError)(r,500,"Internal Server Error")}finally{null==s.waitUntil||s.waitUntil.call(s,Promise.resolve())}}e.s(["config",0,R,"default",0,b,"handler",0,A],758518)},981532,e=>{e.v(e=>Promise.resolve().then(()=>e(322429)))},322522,e=>{e.v(e=>Promise.resolve().then(()=>e(459015)))},245061,e=>{e.v(e=>Promise.resolve().then(()=>e(785128)))}];
2
+
3
+ //# sourceMappingURL=_0y4b49w._.js.map
@@ -0,0 +1,3 @@
1
+ module.exports=[667250,e=>{"use strict";var t=e.i(926747),a=e.i(190406),r=e.i(244898),s=e.i(262950),n=e.i(825265),i=e.i(322429),o=e.i(964759);e.i(462180);var l=e.i(282992),d=e.i(459015);let u=(0,e.i(25146).createLogger)("layout"),p=async(e,t)=>{if("POST"!==e.method)return t.setHeader("Allow","POST"),t.status(405).json({error:"Method not allowed"});let a=e.query.workspace||await (0,i.getActiveWorkspaceId)();if(!a)return t.status(400).json({error:"No workspace found"});let r=e.query.paneId,{name:s,cwd:p,panelType:c,command:v,resumeSessionId:m}=e.body??{},f=m?(0,l.getProviderByPanelType)(c??"claude-code"):null;if(m){if(!f)return t.status(400).json({error:"Unknown panel type for resume"});if(!f.isValidSessionId(m))return t.status(400).json({error:"Invalid session ID format"})}try{let e=await (0,n.addTabToPane)(a,r,s,p,c,v);if(!e)return t.status(404).json({error:"Pane not found"});return"web-browser"!==e.panelType&&(0,o.getStatusManager)().registerTab(e.id,{cliState:"inactive",workspaceId:a,tabName:e.name,tmuxSession:e.sessionName,lastEvent:null,eventSeq:0}),m&&f&&!v&&(await (0,n.updateTabClaudeSessionId)(e.sessionName,m),f.writeSessionId(e,m),setTimeout(async()=>{try{let t=await f.buildResumeCommand(m,{workspaceId:a});await (0,d.sendKeys)(e.sessionName,t)}catch(e){u.warn(`resume sendKeys failed: ${e instanceof Error?e.message:e}`)}},500)),t.status(200).json(e)}catch(e){return u.error(`tab creation failed: ${e instanceof Error?e.message:e}`),t.status(500).json({error:"Failed to create tab"})}};e.s(["default",0,p],170096);var c=e.i(170096),v=e.i(7031),m=e.i(181927),f=e.i(846432);let w=(0,s.hoist)(c,"default"),h=(0,s.hoist)(c,"config"),y=new r.PagesAPIRouteModule({definition:{kind:a.RouteKind.PAGES_API,page:"/api/layout/pane/[paneId]/tabs/index",pathname:"/api/layout/pane/[paneId]/tabs",bundlePath:"",filename:""},userland:c,distDir:".next",relativeProjectDir:""});async function g(e,a,r){r.requestMeta&&(0,f.setRequestMeta)(e,r.requestMeta),y.isDev&&(0,f.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let s="/api/layout/pane/[paneId]/tabs/index";s=s.replace(/\/index$/,"")||"/";let n=await y.prepare(e,a,{srcPage:s});if(!n){a.statusCode=400,a.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve());return}let{query:i,params:o,prerenderManifest:l,routerServerContext:d}=n;try{let t,r=e.method||"GET",n=(0,v.getTracer)(),u=n.getActiveScopeSpan(),p=!!(null==d?void 0:d.isWrappedByNextServer),c=y.instrumentationOnRequestError.bind(y),f=async u=>y.render(e,a,{query:{...i,...o},params:o,allowedRevalidateHeaderKeys:[],multiZoneDraftMode:!1,trustHostHeader:!1,previewProps:l.preview,propagateError:!1,dev:y.isDev,page:"/api/layout/pane/[paneId]/tabs/index",internalRevalidate:null==d?void 0:d.revalidate,onError:(...t)=>c(e,...t)}).finally(()=>{if(!u)return;u.setAttributes({"http.status_code":a.statusCode,"next.rsc":!1});let e=n.getRootSpanAttributes();if(!e)return;if(e.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${e.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let i=e.get("next.route");if(i){let e=`${r} ${i}`;u.setAttributes({"next.route":i,"http.route":i,"next.span_name":e}),u.updateName(e),t&&t!==u&&(t.setAttribute("http.route",i),t.updateName(e))}else u.updateName(`${r} ${s}`)});p&&u?await f(u):(t=n.getActiveScopeSpan(),await n.withPropagatedContext(e.headers,()=>n.trace(m.BaseServerSpan.handleRequest,{spanName:`${r} ${s}`,kind:v.SpanKind.SERVER,attributes:{"http.method":r,"http.target":e.url}},f),void 0,!p))}catch(e){if(y.isDev)throw e;(0,t.sendError)(a,500,"Internal Server Error")}finally{null==r.waitUntil||r.waitUntil.call(r,Promise.resolve())}}e.s(["config",0,h,"default",0,w,"handler",0,g],667250)},981532,e=>{e.v(e=>Promise.resolve().then(()=>e(322429)))},322522,e=>{e.v(e=>Promise.resolve().then(()=>e(459015)))},245061,e=>{e.v(e=>Promise.resolve().then(()=>e(785128)))}];
2
+
3
+ //# sourceMappingURL=_0zcb2f0._.js.map
@@ -1,4 +1,4 @@
1
1
  module.exports=[288061,(e,t,s)=>{"use strict";let r=["nodebuffer","arraybuffer","fragments"],i="u">typeof Blob;i&&r.push("blob"),t.exports={BINARY_TYPES:r,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},202588,(e,t,s)=>{"use strict";let{EMPTY_BUFFER:r}=e.r(288061),i=Buffer[Symbol.species];function o(e,t,s,r,i){for(let o=0;o<i;o++)s[r+o]=e[o]^t[3&o]}function n(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}function a(e){let t;return(a.readOnly=!0,Buffer.isBuffer(e))?e:(e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),a.readOnly=!1),t)}if(t.exports={concat:function(e,t){if(0===e.length)return r;if(1===e.length)return e[0];let s=Buffer.allocUnsafe(t),o=0;for(let t=0;t<e.length;t++){let r=e[t];s.set(r,o),o+=r.length}return o<t?new i(s.buffer,s.byteOffset,o):s},mask:o,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:a,unmask:n},!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{let e=Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.mask=function(t,s,r,i,n){n<48?o(t,s,r,i,n):e.mask(t,s,r,i,n)},t.exports.unmask=function(t,s){t.length<32?n(t,s):e.unmask(t,s)}}catch(e){}},653640,(e,t,s)=>{"use strict";let r=Symbol("kDone"),i=Symbol("kRun");t.exports=class{constructor(e){this[r]=()=>{this.pending--,this[i]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i]()}[i](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[r])}}}},278671,(e,t,s)=>{"use strict";let r,i=e.r(406461),o=e.r(202588),n=e.r(653640),{kStatusCode:a}=e.r(288061),h=Buffer[Symbol.species],l=Buffer.from([0,0,255,255]),c=Symbol("permessage-deflate"),d=Symbol("total-length"),f=Symbol("callback"),_=Symbol("buffers"),u=Symbol("error");function p(e){this[_].push(e),this[d]+=e.length}function m(e){(this[d]+=e.length,this[c]._maxPayload<1||this[d]<=this[c]._maxPayload)?this[_].push(e):(this[u]=RangeError("Max payload size exceeded"),this[u].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[u][a]=1009,this.removeListener("data",m),this.reset())}function y(e){(this[c]._inflate=null,this[u])?this[f](this[u]):(e[a]=1007,this[f](e))}t.exports=class{constructor(e){this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._maxPayload=0|this._options.maxPayload,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,r||(r=new n(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[f];this._deflate.close(),this._deflate=null,e&&e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,s=e.find(e=>(!1!==t.serverNoContextTakeover||!e.server_no_context_takeover)&&(!e.server_max_window_bits||!1!==t.serverMaxWindowBits&&("number"!=typeof t.serverMaxWindowBits||!(t.serverMaxWindowBits>e.server_max_window_bits)))&&("number"!=typeof t.clientMaxWindowBits||!!e.client_max_window_bits));if(!s)throw Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:(!0===s.client_max_window_bits||!1===t.clientMaxWindowBits)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if("client_no_context_takeover"===t||"server_no_context_takeover"===t){if(!0!==s)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){r.add(r=>{this._decompress(e,t,(e,t)=>{r(),s(e,t)})})}compress(e,t,s){r.add(r=>{this._compress(e,t,(e,t)=>{r(),s(e,t)})})}_decompress(e,t,s){let r=this._isServer?"client":"server";if(!this._inflate){let e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[d]=0,this._inflate[_]=[],this._inflate.on("error",y),this._inflate.on("data",m)}this._inflate[f]=s,this._inflate.write(e),t&&this._inflate.write(l),this._inflate.flush(()=>{let e=this._inflate[u];if(e){this._inflate.close(),this._inflate=null,s(e);return}let i=o.concat(this._inflate[_],this._inflate[d]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[d]=0,this._inflate[_]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(e,t,s){let r=this._isServer?"server":"client";if(!this._deflate){let e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?i.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[d]=0,this._deflate[_]=[],this._deflate.on("data",p)}this._deflate[f]=s,this._deflate.write(e),this._deflate.flush(i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=o.concat(this._deflate[_],this._deflate[d]);t&&(e=new h(e.buffer,e.byteOffset,e.length-4)),this._deflate[f]=null,this._deflate[d]=0,this._deflate[_]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,e)})}}},136217,(e,t,s)=>{"use strict";let{isUtf8:r}=e.r(500874),{hasBlob:i}=e.r(288061);function o(e){let t=e.length,s=0;for(;s<t;)if((128&e[s])==0)s++;else if((224&e[s])==192){if(s+1===t||(192&e[s+1])!=128||(254&e[s])==192)return!1;s+=2}else if((240&e[s])==224){if(s+2>=t||(192&e[s+1])!=128||(192&e[s+2])!=128||224===e[s]&&(224&e[s+1])==128||237===e[s]&&(224&e[s+1])==160)return!1;s+=3}else{if((248&e[s])!=240||s+3>=t||(192&e[s+1])!=128||(192&e[s+2])!=128||(192&e[s+3])!=128||240===e[s]&&(240&e[s+1])==128||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}return!0}if(t.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:o,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},r)t.exports.isValidUTF8=function(e){return e.length<24?o(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{let e=Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e})();t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch(e){}},633257,(e,t,s)=>{"use strict";let{Writable:r}=e.r(688947),i=e.r(278671),{BINARY_TYPES:o,EMPTY_BUFFER:n,kStatusCode:a,kWebSocket:h}=e.r(288061),{concat:l,toArrayBuffer:c,unmask:d}=e.r(202588),{isValidStatusCode:f,isValidUTF8:_}=e.r(136217),u=Buffer[Symbol.species];t.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||o[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[h]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new u(t.buffer,t.byteOffset+e,t.length-e),new u(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new u(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0)return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop)this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((48&t[0])!=0)return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let s=(64&t[0])==64;if(s&&!this._extensions[i.extensionName])return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&t[0])==128,this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=s}else{if(!(this._opcode>7)||!(this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&t[1])==128,this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);s>2097151?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*s+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=n;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&d(t,this._mask)}if(this._opcode>7)return void this.controlMessage(t,e);if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void t(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(s)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?l(s,t):"arraybuffer"===this._binaryType?c(l(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(s,t);if(!this._skipUTF8Validation&&!_(r))return void e(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8===this._opcode){if(0===e.length)this._loop=!1,this.emit("conclude",1005,n),this.end();else{let s=e.readUInt16BE(0);if(!f(s))return void t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let r=new u(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_(r))return void t(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}))}createError(e,t,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[a]=r,o}}},791805,(e,t,s)=>{"use strict";let r,{Duplex:i}=e.r(688947),{randomFillSync:o}=e.r(254799),n=e.r(278671),{EMPTY_BUFFER:a,kWebSocket:h,NOOP:l}=e.r(288061),{isBlob:c,isValidStatusCode:d}=e.r(136217),{mask:f,toBuffer:_}=e.r(202588),u=Symbol("kByteLength"),p=Buffer.alloc(4),m=8192;class y{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[h]=void 0}static frame(e,t){let s,i,n=!1,a=2,h=!1;t.mask&&(s=t.maskBuffer||p,t.generateMask?t.generateMask(s):(8192===m&&(void 0===r&&(r=Buffer.alloc(8192)),o(r,0,8192),m=0),s[0]=r[m++],s[1]=r[m++],s[2]=r[m++],s[3]=r[m++]),h=(s[0]|s[1]|s[2]|s[3])==0,a=6),"string"==typeof e?i=(!t.mask||h)&&void 0!==t[u]?t[u]:(e=Buffer.from(e)).length:(i=e.length,n=t.mask&&t.readOnly&&!h);let l=i;i>=65536?(a+=8,l=127):i>125&&(a+=2,l=126);let c=Buffer.allocUnsafe(n?i+a:a);return(c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,126===l?c.writeUInt16BE(i,2):127===l&&(c[2]=c[3]=0,c.writeUIntBE(i,4,6)),t.mask)?(c[1]|=128,c[a-4]=s[0],c[a-3]=s[1],c[a-2]=s[2],c[a-1]=s[3],h)?[c,e]:n?(f(e,s,c,a,i),[c]):(f(e,s,e,0,i),[c,e]):[c,e]}close(e,t,s,r){let i;if(void 0===e)i=a;else if("number"==typeof e&&d(e))if(void 0!==t&&t.length){let s=Buffer.byteLength(t);if(s>123)throw RangeError("The message must not be greater than 123 bytes");(i=Buffer.allocUnsafe(2+s)).writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0);else throw TypeError("First argument must be a valid error code number");let o={[u]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(y.frame(i,o),r)}ping(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):c(e)?(r=e.size,i=!1):(r=(e=_(e)).length,i=_.readOnly),r>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[u]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):0!==this._state?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(y.frame(e,o),s)}pong(e,t,s){let r,i;if("string"==typeof e?(r=Buffer.byteLength(e),i=!1):c(e)?(r=e.size,i=!1):(r=(e=_(e)).length,i=_.readOnly),r>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[u]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):0!==this._state?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(y.frame(e,o),s)}send(e,t,s){let r,i,o=this._extensions[n.extensionName],a=t.binary?2:1,h=t.compress;"string"==typeof e?(r=Buffer.byteLength(e),i=!1):c(e)?(r=e.size,i=!1):(r=(e=_(e)).length,i=_.readOnly),this._firstFragment?(this._firstFragment=!1,h&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(h=r>=o._threshold),this._compress=h):(h=!1,a=0),t.fin&&(this._firstFragment=!0);let l={[u]:r,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:i,rsv1:h};c(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,l,s]):this.getBlobData(e,this._compress,l,s):0!==this._state?this.enqueue([this.dispatch,e,this._compress,l,s]):this.dispatch(e,this._compress,l,s)}getBlobData(e,t,s,r){this._bufferedBytes+=s[u],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){let e=Error("The socket was closed while the blob was being read");process.nextTick(g,this,e,r);return}this._bufferedBytes-=s[u];let i=_(e);t?this.dispatch(i,t,s,r):(this._state=0,this.sendFrame(y.frame(i,s),r),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,r)})}dispatch(e,t,s,r){if(!t)return void this.sendFrame(y.frame(e,s),r);let i=this._extensions[n.extensionName];this._bufferedBytes+=s[u],this._state=1,i.compress(e,s.fin,(e,t)=>{this._socket.destroyed?g(this,Error("The socket was closed while data was being compressed"),r):(this._bufferedBytes-=s[u],this._state=0,s.readOnly=!1,this.sendFrame(y.frame(t,s),r),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][u],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][u],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function g(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){let r=e._queue[s],i=r[r.length-1];"function"==typeof i&&i(t)}}function b(e,t,s){g(e,t,s),e.onerror(t)}t.exports=y},602875,(e,t,s)=>{"use strict";let{kForOnEventAttribute:r,kListener:i}=e.r(288061),o=Symbol("kCode"),n=Symbol("kData"),a=Symbol("kError"),h=Symbol("kMessage"),l=Symbol("kReason"),c=Symbol("kTarget"),d=Symbol("kType"),f=Symbol("kWasClean");class _{constructor(e){this[c]=null,this[d]=e}get target(){return this[c]}get type(){return this[d]}}Object.defineProperty(_.prototype,"target",{enumerable:!0}),Object.defineProperty(_.prototype,"type",{enumerable:!0});class u extends _{constructor(e,t={}){super(e),this[o]=void 0===t.code?0:t.code,this[l]=void 0===t.reason?"":t.reason,this[f]=void 0!==t.wasClean&&t.wasClean}get code(){return this[o]}get reason(){return this[l]}get wasClean(){return this[f]}}Object.defineProperty(u.prototype,"code",{enumerable:!0}),Object.defineProperty(u.prototype,"reason",{enumerable:!0}),Object.defineProperty(u.prototype,"wasClean",{enumerable:!0});class p extends _{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[h]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[h]}}Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});class m extends _{constructor(e,t={}){super(e),this[n]=void 0===t.data?null:t.data}get data(){return this[n]}}function y(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}Object.defineProperty(m.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:u,ErrorEvent:p,Event:_,EventTarget:{addEventListener(e,t,s={}){let o;for(let o of this.listeners(e))if(!s[r]&&o[i]===t&&!o[r])return;if("message"===e)o=function(e,s){let r=new m("message",{data:s?e:e.toString()});r[c]=this,y(t,this,r)};else if("close"===e)o=function(e,s){let r=new u("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[c]=this,y(t,this,r)};else if("error"===e)o=function(e){let s=new p("error",{error:e,message:e.message});s[c]=this,y(t,this,s)};else{if("open"!==e)return;o=function(){let e=new _("open");e[c]=this,y(t,this,e)}}o[r]=!!s[r],o[i]=t,s.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let s of this.listeners(e))if(s[i]===t&&!s[r]){this.removeListener(e,s);break}}},MessageEvent:m}},99434,(e,t,s)=>{"use strict";let{tokenChars:r}=e.r(136217);function i(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}t.exports={format:function(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){let t,s,o=Object.create(null),n=Object.create(null),a=!1,h=!1,l=!1,c=-1,d=-1,f=-1,_=0;for(;_<e.length;_++)if(d=e.charCodeAt(_),void 0===t)if(-1===f&&1===r[d])-1===c&&(c=_);else if(0!==_&&(32===d||9===d))-1===f&&-1!==c&&(f=_);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${_}`);-1===f&&(f=_);let s=e.slice(c,f);44===d?(i(o,s,n),n=Object.create(null)):t=s,c=f=-1}else throw SyntaxError(`Unexpected character at index ${_}`);else if(void 0===s)if(-1===f&&1===r[d])-1===c&&(c=_);else if(32===d||9===d)-1===f&&-1!==c&&(f=_);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${_}`);-1===f&&(f=_),i(n,e.slice(c,f),!0),44===d&&(i(o,t,n),n=Object.create(null),t=void 0),c=f=-1}else if(61===d&&-1!==c&&-1===f)s=e.slice(c,_),c=f=-1;else throw SyntaxError(`Unexpected character at index ${_}`);else if(h){if(1!==r[d])throw SyntaxError(`Unexpected character at index ${_}`);-1===c?c=_:a||(a=!0),h=!1}else if(l)if(1===r[d])-1===c&&(c=_);else if(34===d&&-1!==c)l=!1,f=_;else if(92===d)h=!0;else throw SyntaxError(`Unexpected character at index ${_}`);else if(34===d&&61===e.charCodeAt(_-1))l=!0;else if(-1===f&&1===r[d])-1===c&&(c=_);else if(-1!==c&&(32===d||9===d))-1===f&&(f=_);else if(59===d||44===d){if(-1===c)throw SyntaxError(`Unexpected character at index ${_}`);-1===f&&(f=_);let r=e.slice(c,f);a&&(r=r.replace(/\\/g,""),a=!1),i(n,s,r),44===d&&(i(o,t,n),n=Object.create(null),t=void 0),s=void 0,c=f=-1}else throw SyntaxError(`Unexpected character at index ${_}`);if(-1===c||l||32===d||9===d)throw SyntaxError("Unexpected end of input");-1===f&&(f=_);let u=e.slice(c,f);return void 0===t?i(o,u,n):(void 0===s?i(n,u,!0):a?i(n,s,u.replace(/\\/g,"")):i(n,s,u),i(o,t,n)),o}}},41414,(e,t,s)=>{"use strict";let r=e.r(427699),i=e.r(524836),o=e.r(921517),n=e.r(504446),a=e.r(755004),{randomBytes:h,createHash:l}=e.r(254799),{Duplex:c,Readable:d}=e.r(688947),{URL:f}=e.r(792509),_=e.r(278671),u=e.r(633257),p=e.r(791805),{isBlob:m}=e.r(136217),{BINARY_TYPES:y,CLOSE_TIMEOUT:g,EMPTY_BUFFER:b,GUID:v,kForOnEventAttribute:S,kListener:E,kStatusCode:k,kWebSocket:x,NOOP:w}=e.r(288061),{EventTarget:{addEventListener:O,removeEventListener:T}}=e.r(602875),{format:C,parse:N}=e.r(99434),{toBuffer:L}=e.r(202588),P=Symbol("kAborted"),B=[8,13],U=["CONNECTING","OPEN","CLOSING","CLOSED"],R=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class I extends r{constructor(e,t,s){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=b,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=I.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(s=t,t=[]):t=[t]),function e(t,s,r,n){let a,c,d,u,p={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:g,protocolVersion:B[1],maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=p.autoPong,t._closeTimeout=p.closeTimeout,!B.includes(p.protocolVersion))throw RangeError(`Unsupported protocol version: ${p.protocolVersion} (supported versions: ${B.join(", ")})`);if(s instanceof f)a=s;else try{a=new f(s)}catch{throw SyntaxError(`Invalid URL: ${s}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),t._url=a.href;let m="wss:"===a.protocol,y="ws+unix:"===a.protocol;if("ws:"===a.protocol||m||y?y&&!a.pathname?c="The URL's pathname is empty":a.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',c){let e=SyntaxError(c);if(0!==t._redirects)return void D(t,e);throw e}let b=m?443:80,S=h(16).toString("base64"),E=m?i.request:o.request,k=new Set;if(p.createConnection=p.createConnection||(m?W:M),p.defaultPort=p.defaultPort||b,p.port=a.port||b,p.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,p.headers={...p.headers,"Sec-WebSocket-Version":p.protocolVersion,"Sec-WebSocket-Key":S,Connection:"Upgrade",Upgrade:"websocket"},p.path=a.pathname+a.search,p.timeout=p.handshakeTimeout,p.perMessageDeflate&&(d=new _({...p.perMessageDeflate,isServer:!1,maxPayload:p.maxPayload}),p.headers["Sec-WebSocket-Extensions"]=C({[_.extensionName]:d.offer()})),r.length){for(let e of r){if("string"!=typeof e||!R.test(e)||k.has(e))throw SyntaxError("An invalid or duplicated subprotocol was specified");k.add(e)}p.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(p.origin&&(p.protocolVersion<13?p.headers["Sec-WebSocket-Origin"]=p.origin:p.headers.Origin=p.origin),(a.username||a.password)&&(p.auth=`${a.username}:${a.password}`),y){let e=p.path.split(":");p.socketPath=e[0],p.path=e[1]}if(p.followRedirects){if(0===t._redirects){t._originalIpc=y,t._originalSecure=m,t._originalHostOrSocketPath=y?p.socketPath:a.host;let e=n&&n.headers;if(n={...n,headers:{}},e)for(let[t,s]of Object.entries(e))n.headers[t.toLowerCase()]=s}else if(0===t.listenerCount("redirect")){let e=y?!!t._originalIpc&&p.socketPath===t._originalHostOrSocketPath:!t._originalIpc&&a.host===t._originalHostOrSocketPath;e&&(!t._originalSecure||m)||(delete p.headers.authorization,delete p.headers.cookie,e||delete p.headers.host,p.auth=void 0)}p.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(p.auth).toString("base64")),u=t._req=E(p),t._redirects&&t.emit("redirect",t.url,u)}else u=t._req=E(p);p.timeout&&u.on("timeout",()=>{A(t,u,"Opening handshake has timed out")}),u.on("error",e=>{null===u||u[P]||(u=t._req=null,D(t,e))}),u.on("response",i=>{let o=i.headers.location,a=i.statusCode;if(o&&p.followRedirects&&a>=300&&a<400){let i;if(++t._redirects>p.maxRedirects)return void A(t,u,"Maximum redirects exceeded");u.abort();try{i=new f(o,s)}catch(e){D(t,SyntaxError(`Invalid URL: ${o}`));return}e(t,i,r,n)}else t.emit("unexpected-response",u,i)||A(t,u,`Unexpected server response: ${i.statusCode}`)}),u.on("upgrade",(e,s,r)=>{let i;if(t.emit("upgrade",e),t.readyState!==I.CONNECTING)return;u=t._req=null;let o=e.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void A(t,s,"Invalid Upgrade header");let n=l("sha1").update(S+v).digest("base64");if(e.headers["sec-websocket-accept"]!==n)return void A(t,s,"Invalid Sec-WebSocket-Accept header");let a=e.headers["sec-websocket-protocol"];if(void 0!==a?k.size?k.has(a)||(i="Server sent an invalid subprotocol"):i="Server sent a subprotocol but none was requested":k.size&&(i="Server sent no subprotocol"),i)return void A(t,s,i);a&&(t._protocol=a);let h=e.headers["sec-websocket-extensions"];if(void 0!==h){let e;if(!d)return void A(t,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{e=N(h)}catch(e){A(t,s,"Invalid Sec-WebSocket-Extensions header");return}let r=Object.keys(e);if(1!==r.length||r[0]!==_.extensionName)return void A(t,s,"Server indicated an extension that was not requested");try{d.accept(e[_.extensionName])}catch(e){A(t,s,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[_.extensionName]=d}t.setSocket(s,r,{allowSynchronousEvents:p.allowSynchronousEvents,generateMask:p.generateMask,maxPayload:p.maxPayload,skipUTF8Validation:p.skipUTF8Validation})}),p.finishRequest?p.finishRequest(u,t):u.end()}(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){y.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,s){let r=new u({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new p(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[x]=this,i[x]=this,e[x]=this,r.on("conclude",$),r.on("drain",j),r.on("error",G),r.on("message",q),r.on("ping",z),r.on("pong",H),i.onerror=K,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Y),e.on("data",J),e.on("end",Q),e.on("error",ee),this._readyState=I.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=I.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[_.extensionName]&&this._extensions[_.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=I.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==I.CLOSED){if(this.readyState===I.CONNECTING)return void A(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===I.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=I.CLOSING,this._sender.close(e,t,!this._isServer,e=>{!e&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Z(this)}}pause(){this.readyState!==I.CONNECTING&&this.readyState!==I.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===I.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==I.OPEN)?F(this,e,s):(void 0===t&&(t=!this._isServer),this._sender.ping(e||b,t,s))}pong(e,t,s){if(this.readyState===I.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState!==I.OPEN)?F(this,e,s):(void 0===t&&(t=!this._isServer),this._sender.pong(e||b,t,s))}resume(){this.readyState!==I.CONNECTING&&this.readyState!==I.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===I.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==I.OPEN)return void F(this,e,s);let r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[_.extensionName]||(r.compress=!1),this._sender.send(e||b,r,s)}terminate(){if(this.readyState!==I.CLOSED){if(this.readyState===I.CONNECTING)return void A(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=I.CLOSING,this._socket.destroy())}}}function D(e,t){e._readyState=I.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function M(e){return e.path=e.socketPath,n.connect(e)}function W(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=n.isIP(e.host)?"":e.host),a.connect(e)}function A(e,t,s){e._readyState=I.CLOSING;let r=Error(s);Error.captureStackTrace(r,A),t.setHeader?(t[P]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function F(e,t,s){if(t){let s=m(t)?t.size:L(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${U[e.readyState]})`);process.nextTick(s,t)}}function $(e,t){let s=this[x];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[x]&&(s._socket.removeListener("data",J),process.nextTick(X,s._socket),1005===e?s.close():s.close(e,t))}function j(){let e=this[x];e.isPaused||e._socket.resume()}function G(e){let t=this[x];void 0!==t._socket[x]&&(t._socket.removeListener("data",J),process.nextTick(X,t._socket),t.close(e[k])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function V(){this[x].emitClose()}function q(e,t){this[x].emit("message",e,t)}function z(e){let t=this[x];t._autoPong&&t.pong(e,!this._isServer,w),t.emit("ping",e)}function H(e){this[x].emit("pong",e)}function X(e){e.resume()}function K(e){let t=this[x];t.readyState!==I.CLOSED&&(t.readyState===I.OPEN&&(t._readyState=I.CLOSING,Z(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Z(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Y(){let e=this[x];if(this.removeListener("close",Y),this.removeListener("data",J),this.removeListener("end",Q),e._readyState=I.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&0!==this._readableState.length){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[x]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",V),e._receiver.on("finish",V))}function J(e){this[x]._receiver.write(e)||this.pause()}function Q(){let e=this[x];e._readyState=I.CLOSING,e._receiver.end(),this.end()}function ee(){let e=this[x];this.removeListener("error",ee),this.on("error",w),e&&(e._readyState=I.CLOSING,this.destroy())}Object.defineProperty(I,"CONNECTING",{enumerable:!0,value:U.indexOf("CONNECTING")}),Object.defineProperty(I.prototype,"CONNECTING",{enumerable:!0,value:U.indexOf("CONNECTING")}),Object.defineProperty(I,"OPEN",{enumerable:!0,value:U.indexOf("OPEN")}),Object.defineProperty(I.prototype,"OPEN",{enumerable:!0,value:U.indexOf("OPEN")}),Object.defineProperty(I,"CLOSING",{enumerable:!0,value:U.indexOf("CLOSING")}),Object.defineProperty(I.prototype,"CLOSING",{enumerable:!0,value:U.indexOf("CLOSING")}),Object.defineProperty(I,"CLOSED",{enumerable:!0,value:U.indexOf("CLOSED")}),Object.defineProperty(I.prototype,"CLOSED",{enumerable:!0,value:U.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(I.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(I.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[S])return t[E];return null},set(t){for(let t of this.listeners(e))if(t[S]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[S]:!0})}})}),I.prototype.addEventListener=O,I.prototype.removeEventListener=T,t.exports=I},902699,(e,t,s)=>{"use strict";e.r(41414);let{Duplex:r}=e.r(688947);function i(e){e.emit("close")}function o(){!this.destroyed&&this._writableState.finished&&this.destroy()}function n(e){this.removeListener("error",n),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let s=!0,a=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,s){let r=!s&&a._readableState.objectMode?t.toString():t;a.push(r)||e.pause()}),e.once("error",function(e){a.destroyed||(s=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,a);return}let o=!1;e.once("error",function(e){o=!0,r(e)}),e.once("close",function(){o||r(t),process.nextTick(i,a)}),s&&e.terminate()},a._final=function(t){e.readyState===e.CONNECTING?e.once("open",function(){a._final(t)}):null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close()))},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,s,r){e.readyState===e.CONNECTING?e.once("open",function(){a._write(t,s,r)}):e.send(t,r)},a.on("end",o),a.on("error",n),a}},779163,(e,t,s)=>{"use strict";let{tokenChars:r}=e.r(136217);t.exports={parse:function(e){let t=new Set,s=-1,i=-1,o=0;for(;o<e.length;o++){let n=e.charCodeAt(o);if(-1===i&&1===r[n])-1===s&&(s=o);else if(0!==o&&(32===n||9===n))-1===i&&-1!==s&&(i=o);else if(44===n){if(-1===s)throw SyntaxError(`Unexpected character at index ${o}`);-1===i&&(i=o);let r=e.slice(s,i);if(t.has(r))throw SyntaxError(`The "${r}" subprotocol is duplicated`);t.add(r),s=i=-1}else throw SyntaxError(`Unexpected character at index ${o}`)}if(-1===s||-1!==i)throw SyntaxError("Unexpected end of input");let n=e.slice(s,o);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);return t.add(n),t}}},281814,(e,t,s)=>{"use strict";let r=e.r(427699),i=e.r(921517),{Duplex:o}=e.r(688947),{createHash:n}=e.r(254799),a=e.r(99434),h=e.r(278671),l=e.r(779163),c=e.r(41414),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:_}=e.r(288061),u=/^[+/0-9A-Za-z]{22}==$/;function p(e){e._state=2,e.emit("close")}function m(){this.destroy()}function y(e,t,s,r){s=s||i.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r
2
- `+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function g(e,t,s,r,i,o){if(e.listenerCount("wsClientError")){let r=Error(i);Error.captureStackTrace(r,g),e.emit("wsClientError",r,s,t)}else y(s,r,i,o)}t.exports=class extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let s=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(p,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(p,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{p(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",m);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void g(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void g(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!u.test(i))return void g(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==n&&8!==n)return void g(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void y(t,400);let c=e.headers["sec-websocket-protocol"],d=new Set;if(void 0!==c)try{d=l.parse(c)}catch(s){g(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&void 0!==f){let s=new h({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=a.parse(f);e[h.extensionName]&&(s.accept(e[h.extensionName]),_[h.extensionName]=s)}catch(s){g(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let o={origin:e.headers[`${8===n?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,n,a,h)=>{if(!o)return y(t,n||401,a,h);this.completeUpgrade(_,i,d,e,t,s,r)});if(!this.options.verifyClient(o))return y(t,401)}this.completeUpgrade(_,i,d,e,t,s,r)}completeUpgrade(e,t,s,r,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[_])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return y(i,503);let c=n("sha1").update(t+f).digest("base64"),d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),u._protocol=e)}if(e[h.extensionName]){let t=e[h.extensionName].params,s=a.format({[h.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${s}`),u._extensions=e}this.emit("headers",d,r),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",m),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(p,this)})),l(u,r)}}},478319,220951,e=>{"use strict";e.i(902699),e.i(99434),e.i(278671),e.i(633257),e.i(791805),e.i(779163);var t=e.i(41414);e.i(281814),t.default,e.s([],478319),e.s(["WebSocket",()=>t.default],220951)}];
2
+ `+Object.keys(r).map(e=>`${e}: ${r[e]}`).join("\r\n")+"\r\n\r\n"+s)}function g(e,t,s,r,i,o){if(e.listenerCount("wsClientError")){let r=Error(i);Error.captureStackTrace(r,g),e.emit("wsClientError",r,s,t)}else y(s,r,i,o)}t.exports=class extends r{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{let s=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,r)=>{this.handleUpgrade(t,s,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state){e&&this.once("close",()=>{e(Error("The server is not running"))}),process.nextTick(p,this);return}if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(p,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{p(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",m);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void g(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void g(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!u.test(i))return void g(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==n&&8!==n)return void g(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(e))return void y(t,400);let c=e.headers["sec-websocket-protocol"],d=new Set;if(void 0!==c)try{d=l.parse(c)}catch(s){g(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&void 0!==f){let s=new h({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=a.parse(f);e[h.extensionName]&&(s.accept(e[h.extensionName]),_[h.extensionName]=s)}catch(s){g(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let o={origin:e.headers[`${8===n?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,n,a,h)=>{if(!o)return y(t,n||401,a,h);this.completeUpgrade(_,i,d,e,t,s,r)});if(!this.options.verifyClient(o))return y(t,401)}this.completeUpgrade(_,i,d,e,t,s,r)}completeUpgrade(e,t,s,r,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[_])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return y(i,503);let c=n("sha1").update(t+f).digest("base64"),d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c}`],u=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),u._protocol=e)}if(e[h.extensionName]){let t=e[h.extensionName].params,s=a.format({[h.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${s}`),u._extensions=e}this.emit("headers",d,r),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",m),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(p,this)})),l(u,r)}}},666126,478319,220951,e=>{"use strict";e.i(902699),e.i(99434),e.i(278671),e.i(633257),e.i(791805),e.i(779163);var t=e.i(41414);e.i(281814),t.default,e.s([],478319);var s=t;e.s(["WebSocket",()=>s.default],220951);var s=t;(0,e.i(25146).createLogger)("sync");let r=globalThis;r.__ptSyncClients||(r.__ptSyncClients=new Set);let i=r.__ptSyncClients;e.s(["broadcastSync",0,e=>{let t=JSON.stringify(e);for(let e of i)e.readyState===s.default.OPEN&&e.bufferedAmount<1048576&&e.send(t)}],666126)}];
3
3
 
4
- //# sourceMappingURL=node_modules_ws_124xx2_._.js.map
4
+ //# sourceMappingURL=_106a~ya._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[135992,e=>{"use strict";var t=e.i(926747),i=e.i(190406),a=e.i(244898),n=e.i(262950),s=e.i(924868),r=e.i(814747),l=e.i(446786),o=e.i(233405),u=e.i(871911),d=e.i(796902),p=(e.i(522734),e.i(25146));let c=(0,p.createLogger)("session-stats"),f=r.default.join(l.default.homedir(),".purplemux","session-stats");r.default.join(l.default.homedir(),".claude","projects");let m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_=e=>r.default.join(f,`${e}.json`),h=e=>{let t=r.default.basename(e,".jsonl");return m.test(t)?t:null},w=async e=>{if(!m.test(e))return null;try{let t=await s.default.readFile(_(e),"utf-8");return JSON.parse(t)}catch{return null}},g=async e=>{await s.default.mkdir(f,{recursive:!0});let t=_(e.sessionId),i=`${t}.tmp`;try{await s.default.writeFile(i,JSON.stringify(e),{mode:384}),await s.default.rename(i,t)}catch(e){await s.default.unlink(i).catch(()=>{}),c.debug({err:e},"failed to write session stats")}},y=async(e,t)=>{if(!m.test(e))return;let i=await w(e)??{sessionId:e};await g({...i,...t,sessionId:e})};e.i(478319);var v=e.i(220951);e.i(143511);e.i(840665);e.i(319668);e.i(459015);e.i(746514);e.i(825265),e.i(964759);e.i(478490),e.i(133446),(0,p.createLogger)("timeline");let x=globalThis;x.__pmuxTimelineConnections||(x.__pmuxTimelineConnections=new Map),x.__pmuxTimelineFileWatchers||(x.__pmuxTimelineFileWatchers=new Map),x.__pmuxTimelineSessionWatchers||(x.__pmuxTimelineSessionWatchers=new Map),x.__pmuxTimelinePendingJsonlWatchers||(x.__pmuxTimelinePendingJsonlWatchers=new Map),x.__pmuxTimelineConnections;let S=x.__pmuxTimelineFileWatchers;x.__pmuxTimelineSessionWatchers,x.__pmuxTimelinePendingJsonlWatchers;let T=e=>e.readyState===v.WebSocket.OPEN&&e.bufferedAmount<1048576,P=(e,t)=>{T(e)&&e.send(JSON.stringify(t))},b=(0,p.createLogger)("statusline"),j=async e=>{let t=e.workspace?.project_dir,i=[];for(let e of(t&&(i.push(r.default.join(t,".claude","settings.local.json")),i.push(r.default.join(t,".claude","settings.json"))),i.push(r.default.join(l.default.homedir(),".claude","settings.json")),i))try{let t=await s.default.readFile(e,"utf-8"),i=JSON.parse(t),a=i?.statusLine?.command;if("string"==typeof a&&a.trim())return a}catch{}return null},k=async e=>{let t=e.rate_limits?.five_hour??null,i=e.rate_limits?.seven_day??null;if(!t&&!i)return;let a={ts:Date.now()/1e3,five_hour:t,seven_day:i};try{await s.default.writeFile(d.RATE_LIMITS_FILE,JSON.stringify(a))}catch(e){b.debug({err:e},"failed to write rate-limits.json")}},R=async e=>{let t=(e=>{let t=e.session_id;if(!t)return null;let i=e.context_window,a=i?.current_usage,n=a?(a.input_tokens??0)+(a.cache_creation_input_tokens??0)+(a.cache_read_input_tokens??0):0;return{sessionId:t,transcriptPath:e.transcript_path,inputTokens:i?.total_input_tokens??0,outputTokens:i?.total_output_tokens??0,cost:e.cost?.total_cost_usd??null,currentContextTokens:n,contextWindowSize:i?.context_window_size??0,usedPercentage:i?.used_percentage??null,model:e.model?.display_name??null,exceeds200k:e.exceeds_200k_tokens??!1,receivedAt:Date.now()}})(e);if(!t)return;await y(t.sessionId,t);let i=await w(t.sessionId)??t;try{for(let e of S.values())if(h(e.jsonlPath)===i.sessionId)for(let t of e.connections)P(t,{type:"timeline:stats-update",sessionStats:i})}catch(e){b.debug({err:e},"failed to broadcast session stats")}},A=async(e,t)=>{if("POST"!==e.method)return t.setHeader("Allow","POST"),t.status(405).json({error:"Method not allowed"});if(!(0,u.verifyCliToken)(e))return t.status(403).json({error:"Forbidden"});let i=e.body??{};await Promise.all([k(i),R(i)]),t.setHeader("Content-Type","text/plain; charset=utf-8");try{let e=await j(i);if(e){let a,n=await (a=JSON.stringify(i),new Promise((t,i)=>{let n=(0,o.spawn)("sh",["-c",e],{stdio:["pipe","pipe","pipe"]}),s="",r="";n.stdout.on("data",e=>{s+=e.toString()}),n.stderr.on("data",e=>{r+=e.toString()}),n.on("error",i),n.on("close",e=>{0!==e&&r&&b.debug({code:e,stderr:r},"user statusLine exited non-zero"),t(s)}),n.stdin.write(a),n.stdin.end()}));return t.status(200).send(n)}}catch(e){b.debug({err:e},"user statusLine failed")}return t.status(204).end()};e.s(["default",0,A],826327);var E=e.i(826327),N=e.i(7031),M=e.i(181927),W=e.i(846432);let I=(0,n.hoist)(E,"default"),$=(0,n.hoist)(E,"config"),q=new a.PagesAPIRouteModule({definition:{kind:i.RouteKind.PAGES_API,page:"/api/status/statusline",pathname:"/api/status/statusline",bundlePath:"",filename:""},userland:E,distDir:".next",relativeProjectDir:""});async function O(e,i,a){a.requestMeta&&(0,W.setRequestMeta)(e,a.requestMeta),q.isDev&&(0,W.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let n="/api/status/statusline";n=n.replace(/\/index$/,"")||"/";let s=await q.prepare(e,i,{srcPage:n});if(!s){i.statusCode=400,i.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve());return}let{query:r,params:l,prerenderManifest:o,routerServerContext:u}=s;try{let t,a=e.method||"GET",s=(0,N.getTracer)(),d=s.getActiveScopeSpan(),p=!!(null==u?void 0:u.isWrappedByNextServer),c=q.instrumentationOnRequestError.bind(q),f=async d=>q.render(e,i,{query:{...r,...l},params:l,allowedRevalidateHeaderKeys:[],multiZoneDraftMode:!1,trustHostHeader:!1,previewProps:o.preview,propagateError:!1,dev:q.isDev,page:"/api/status/statusline",internalRevalidate:null==u?void 0:u.revalidate,onError:(...t)=>c(e,...t)}).finally(()=>{if(!d)return;d.setAttributes({"http.status_code":i.statusCode,"next.rsc":!1});let e=s.getRootSpanAttributes();if(!e)return;if(e.get("next.span_type")!==M.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${e.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let r=e.get("next.route");if(r){let e=`${a} ${r}`;d.setAttributes({"next.route":r,"http.route":r,"next.span_name":e}),d.updateName(e),t&&t!==d&&(t.setAttribute("http.route",r),t.updateName(e))}else d.updateName(`${a} ${n}`)});p&&d?await f(d):(t=s.getActiveScopeSpan(),await s.withPropagatedContext(e.headers,()=>s.trace(M.BaseServerSpan.handleRequest,{spanName:`${a} ${n}`,kind:N.SpanKind.SERVER,attributes:{"http.method":a,"http.target":e.url}},f),void 0,!p))}catch(e){if(q.isDev)throw e;(0,t.sendError)(i,500,"Internal Server Error")}finally{null==a.waitUntil||a.waitUntil.call(a,Promise.resolve())}}e.s(["config",0,$,"default",0,I,"handler",0,O],135992)}];
1
+ module.exports=[135992,e=>{"use strict";var t=e.i(926747),i=e.i(190406),a=e.i(244898),n=e.i(262950),s=e.i(924868),r=e.i(814747),l=e.i(446786),o=e.i(233405),u=e.i(871911),d=e.i(796902),p=(e.i(522734),e.i(25146));let c=(0,p.createLogger)("session-stats"),f=r.default.join(l.default.homedir(),".purplemux","session-stats");r.default.join(l.default.homedir(),".claude","projects");let m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_=e=>r.default.join(f,`${e}.json`),h=e=>{let t=r.default.basename(e,".jsonl");return m.test(t)?t:null},w=async e=>{if(!m.test(e))return null;try{let t=await s.default.readFile(_(e),"utf-8");return JSON.parse(t)}catch{return null}},g=async e=>{await s.default.mkdir(f,{recursive:!0});let t=_(e.sessionId),i=`${t}.tmp`;try{await s.default.writeFile(i,JSON.stringify(e),{mode:384}),await s.default.rename(i,t)}catch(e){await s.default.unlink(i).catch(()=>{}),c.debug({err:e},"failed to write session stats")}},y=async(e,t)=>{if(!m.test(e))return;let i=await w(e)??{sessionId:e};await g({...i,...t,sessionId:e})};e.i(478319);var v=e.i(220951),x=e.i(840665);e.i(319668);e.i(459015);e.i(746514);e.i(825265),e.i(964759);e.i(462180),e.i(282992),e.i(133446),(0,p.createLogger)("timeline");let S=globalThis;S.__pmuxTimelineConnections||(S.__pmuxTimelineConnections=new Map),S.__pmuxTimelineFileWatchers||(S.__pmuxTimelineFileWatchers=new Map),S.__pmuxTimelineSessionWatchers||(S.__pmuxTimelineSessionWatchers=new Map),S.__pmuxTimelinePendingJsonlWatchers||(S.__pmuxTimelinePendingJsonlWatchers=new Map),S.__pmuxTimelineConnections;let T=S.__pmuxTimelineFileWatchers;S.__pmuxTimelineSessionWatchers,S.__pmuxTimelinePendingJsonlWatchers;let P=e=>e.readyState===v.WebSocket.OPEN&&e.bufferedAmount<1048576,b=(e,t)=>{P(e)&&e.send(JSON.stringify(t))},j=(0,p.createLogger)("statusline"),k=async e=>{let t=e.workspace?.project_dir,i=[];for(let e of(t&&(i.push(r.default.join(t,".claude","settings.local.json")),i.push(r.default.join(t,".claude","settings.json"))),i.push(r.default.join(l.default.homedir(),".claude","settings.json")),i))try{let t=await s.default.readFile(e,"utf-8"),i=JSON.parse(t),a=i?.statusLine?.command;if("string"==typeof a&&a.trim())return a}catch{}return null},R=async e=>{let t=e.rate_limits?.five_hour??null,i=e.rate_limits?.seven_day??null;if(!t&&!i)return;let a={ts:Date.now()/1e3,five_hour:t,seven_day:i};try{await s.default.writeFile(d.RATE_LIMITS_FILE,JSON.stringify(a))}catch(e){j.debug({err:e},"failed to write rate-limits.json")}},A=async e=>{let t=(e=>{let t=e.session_id;if(!t)return null;let i=e.context_window,a=i?.current_usage,n=a?(a.input_tokens??0)+(a.cache_creation_input_tokens??0)+(a.cache_read_input_tokens??0):0;return{sessionId:t,transcriptPath:e.transcript_path,inputTokens:i?.total_input_tokens??0,outputTokens:i?.total_output_tokens??0,cost:e.cost?.total_cost_usd??null,currentContextTokens:n,contextWindowSize:i?.context_window_size??0,usedPercentage:i?.used_percentage??null,model:e.model?.display_name??null,exceeds200k:e.exceeds_200k_tokens??!1,receivedAt:Date.now()}})(e);if(!t)return;await y(t.sessionId,t);let i=await w(t.sessionId)??t;try{for(let e of T.values())if(h(e.jsonlPath)===i.sessionId)for(let t of e.connections)b(t,{type:"timeline:stats-update",sessionStats:i})}catch(e){j.debug({err:e},"failed to broadcast session stats")}},E=async(e,t)=>{if("POST"!==e.method)return t.setHeader("Allow","POST"),t.status(405).json({error:"Method not allowed"});if(!(0,u.verifyCliToken)(e))return t.status(403).json({error:"Forbidden"});let i=e.body??{};await Promise.all([R(i),A(i)]),t.setHeader("Content-Type","text/plain; charset=utf-8");try{let e=await k(i);if(e){let a,n=await (a=JSON.stringify(i),new Promise((t,i)=>{let n=(0,o.spawn)("sh",["-c",e],{stdio:["pipe","pipe","pipe"]}),s="",r="";n.stdout.on("data",e=>{s+=e.toString()}),n.stderr.on("data",e=>{r+=e.toString()}),n.on("error",i),n.on("close",e=>{0!==e&&r&&j.debug({code:e,stderr:r},"user statusLine exited non-zero"),t(s)}),n.stdin.write(a),n.stdin.end()}));return t.status(200).send(n)}}catch(e){j.debug({err:e},"user statusLine failed")}return t.status(204).end()};e.s(["default",0,E],826327);var N=e.i(826327),M=e.i(7031),W=e.i(181927),I=e.i(846432);let $=(0,n.hoist)(N,"default"),q=(0,n.hoist)(N,"config"),O=new a.PagesAPIRouteModule({definition:{kind:i.RouteKind.PAGES_API,page:"/api/status/statusline",pathname:"/api/status/statusline",bundlePath:"",filename:""},userland:N,distDir:".next",relativeProjectDir:""});async function F(e,i,a){a.requestMeta&&(0,I.setRequestMeta)(e,a.requestMeta),O.isDev&&(0,I.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let n="/api/status/statusline";n=n.replace(/\/index$/,"")||"/";let s=await O.prepare(e,i,{srcPage:n});if(!s){i.statusCode=400,i.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve());return}let{query:r,params:l,prerenderManifest:o,routerServerContext:u}=s;try{let t,a=e.method||"GET",s=(0,M.getTracer)(),d=s.getActiveScopeSpan(),p=!!(null==u?void 0:u.isWrappedByNextServer),c=O.instrumentationOnRequestError.bind(O),f=async d=>O.render(e,i,{query:{...r,...l},params:l,allowedRevalidateHeaderKeys:[],multiZoneDraftMode:!1,trustHostHeader:!1,previewProps:o.preview,propagateError:!1,dev:O.isDev,page:"/api/status/statusline",internalRevalidate:null==u?void 0:u.revalidate,onError:(...t)=>c(e,...t)}).finally(()=>{if(!d)return;d.setAttributes({"http.status_code":i.statusCode,"next.rsc":!1});let e=s.getRootSpanAttributes();if(!e)return;if(e.get("next.span_type")!==W.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${e.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let r=e.get("next.route");if(r){let e=`${a} ${r}`;d.setAttributes({"next.route":r,"http.route":r,"next.span_name":e}),d.updateName(e),t&&t!==d&&(t.setAttribute("http.route",r),t.updateName(e))}else d.updateName(`${a} ${n}`)});p&&d?await f(d):(t=s.getActiveScopeSpan(),await s.withPropagatedContext(e.headers,()=>s.trace(W.BaseServerSpan.handleRequest,{spanName:`${a} ${n}`,kind:M.SpanKind.SERVER,attributes:{"http.method":a,"http.target":e.url}},f),void 0,!p))}catch(e){if(O.isDev)throw e;(0,t.sendError)(i,500,"Internal Server Error")}finally{null==a.waitUntil||a.waitUntil.call(a,Promise.resolve())}}e.s(["config",0,q,"default",0,$,"handler",0,F],135992)}];
2
2
 
3
3
  //# sourceMappingURL=node_modules_next_dist_esm_build_templates_pages-api_00-t8sq.js.map
@@ -0,0 +1,3 @@
1
+ module.exports=[871911,e=>{"use strict";var t=e.i(254799),r=e.i(522734),l=e.i(814747),i=e.i(446786);let n=l.default.join(i.default.homedir(),".purplemux","cli-token"),o=globalThis;e.s(["verifyCliToken",0,e=>{let i=e.headers["x-pmux-token"];var u="string"==typeof i?i:void 0;if(!u)return!1;let s=(()=>{if(o.__ptCliToken)return o.__ptCliToken;let e=(()=>{try{return r.default.readFileSync(n,"utf-8").trim()||null}catch{return null}})();if(e)return o.__ptCliToken=e,e;let i=(0,t.randomBytes)(32).toString("hex");o.__ptCliToken=i;try{r.default.mkdirSync(l.default.dirname(n),{recursive:!0}),r.default.writeFileSync(n,i,{mode:384})}catch{}return i})();return u.length===s.length&&(0,t.timingSafeEqual)(Buffer.from(u),Buffer.from(s))}])},133446,e=>{"use strict";var t=e.i(814747),r=e.i(446786);let l=t.default.join(r.default.homedir(),".claude","projects");e.s(["isAllowedJsonlPath",0,e=>{let r=t.default.resolve(e);return r.startsWith(l+t.default.sep)&&r.endsWith(".jsonl")}])},981532,e=>{e.v(e=>Promise.resolve().then(()=>e(322429)))},322522,e=>{e.v(e=>Promise.resolve().then(()=>e(459015)))},245061,e=>{e.v(e=>Promise.resolve().then(()=>e(785128)))}];
2
+
3
+ //# sourceMappingURL=src_lib_00fhuqb._.js.map
@@ -0,0 +1,15 @@
1
+ module.exports=[845994,t=>{"use strict";var e=t.i(924868),a=t.i(814747),n=t.i(446786),l=t.i(254799),i=t.i(666126);(0,t.i(25146).createLogger)("config");let r=a.default.join(n.default.homedir(),".purplemux"),s=a.default.join(r,"config.json"),u=globalThis;u.__ptConfigLock||(u.__ptConfigLock=Promise.resolve());let o=async t=>{let e,a=new Promise(t=>{e=t}),n=u.__ptConfigLock;u.__ptConfigLock=a,await n;try{return await t()}finally{e()}},c=()=>({updatedAt:new Date().toISOString()}),d=async()=>{try{let t=await e.default.readFile(s,"utf-8");return JSON.parse(t)}catch{return null}},f=async t=>{let{updatedAt:a,...n}=t,l=JSON.stringify(n);if(u.__ptConfigContentCache===l)return;t.updatedAt=new Date().toISOString();let r=s+".tmp";try{await e.default.writeFile(r,JSON.stringify(t,null,2),{mode:384}),await e.default.rename(r,s)}catch(t){throw await e.default.unlink(r).catch(()=>{}),t}u.__ptConfigContentCache=l,(0,i.broadcastSync)({type:"config"})},h="scrypt:",p=t=>"string"==typeof t&&t.startsWith(h),w=async t=>{let e=l.default.randomBytes(16),a=await new Promise((a,n)=>{l.default.scrypt(t,e,64,(t,e)=>{t?n(t):a(e)})});return`${h}${e.toString("hex")}:${a.toString("hex")}`},y=async(t,e)=>{if(!p(e))return!1;let[,a,n]=e.split(":"),i=Buffer.from(a,"hex"),r=Buffer.from(n,"hex"),s=await new Promise((e,a)=>{l.default.scrypt(t,i,r.length,(t,n)=>{t?a(t):e(n)})});return l.default.timingSafeEqual(s,r)},m=async()=>await d()??c(),g=async t=>o(async()=>{let e=await d()??c();Object.assign(e,t),await f(e)}),S=async()=>{let t=await d();return!p(t?.authPassword)},P=async()=>{let t=await d();return t?.dangerouslySkipPermissions??!1};t.s(["generateSecret",0,()=>l.default.randomBytes(32).toString("hex"),"getConfig",0,m,"getDangerouslySkipPermissions",0,P,"hashPassword",0,w,"needsSetup",0,S,"updateConfig",0,g,"verifyPassword",0,y])},713915,t=>{"use strict";var e=t.i(233405),a=t.i(924868),n=t.i(446786),l=t.i(814747),i=t.i(224361),r=t.i(597789),s=t.i(965898);let u=(0,i.promisify)(e.execFile),o=null,c=null,d=async()=>{let t=n.default.userInfo().shell||(0,r.defaultShell)();try{let{stdout:e}=await u(t,["-ilc",'echo -n "$PATH"'],{timeout:5e3,env:{...(0,r.buildShellEnv)(),SHELL:t,DISABLE_AUTO_UPDATE:"true",ZSH_TMUX_AUTOSTARTED:"true"}});return e.toString().trim()}catch{return s.PRISTINE_ENV.PATH||""}},f=async()=>o||(c||(c=d().then(t=>(o=t,c=null,t))),c),h=async(t,e,a)=>{try{let n=await f(),{stdout:l}=await u(t,e,{timeout:5e3,env:{...process.env,PATH:n}});return{installed:!0,version:a(l)}}catch{return{installed:!1,version:null}}},p=t=>t.trim().match(/(\d+\.\d+[\d.]*)/)?.[1]??null,w=[l.default.join(n.default.homedir(),".local","bin")],y=async()=>{for(let t of w)try{return await (0,a.access)(l.default.join(t,"claude")),t}catch{}return null},m=t=>t.installed&&null!==t.version&&parseFloat(t.version)>=2.9,g=async()=>{o=await d();let[t,e,i]=await Promise.all([h("tmux",["-V"],p),h("git",["--version"],p),h("claude",["--version"],p)]),r=(m(t)&&e.installed&&i.installed,i.installed?null:await y()),s=!1;if(i.installed||r)try{await (0,a.access)(l.default.join(n.default.homedir(),".claude")),s=!0}catch{}return{tmux:{...t,compatible:m(t)},git:e,claude:{...i,binaryPath:r,loggedIn:s}}},S=null,P=null,v=null,I=null,A=async()=>v&&Date.now()-v.checkedAt<1e3?v.result:I||(I=g().then(t=>(v={result:t,checkedAt:Date.now()},I=null,t)).catch(t=>{throw I=null,t})),T=async()=>{o=await d();let[t,e,a]=await Promise.all([h("tmux",["-V"],p),h("git",["--version"],p),h("claude",["--version"],p)]);return{tmux:{...t,compatible:m(t)},git:e,claude:a}},j=async()=>S&&Date.now()-S.checkedAt<3e4?S.result:P||(P=T().then(t=>(S={result:t,checkedAt:Date.now()},P=null,t)).catch(t=>{throw P=null,t}));t.s(["getCachedPreflightStatus",0,A,"getCachedRuntimePreflight",0,j,"getShellPath",0,f,"invalidateRuntimeCache",0,()=>{S=null,P=null}])},143511,t=>{"use strict";var e=t.i(924868),a=t.i(522734),n=t.i(814747),l=t.i(446786),i=t.i(233405),r=t.i(224361),s=t.i(713915),u=t.i(544538);let o=(0,r.promisify)(i.execFile),c=n.default.join(l.default.homedir(),".claude"),d=n.default.join(c,"sessions"),f=n.default.join(c,"projects"),h=[n.default.join(l.default.homedir(),".local","bin","claude")],p=t=>{let e=t.replace(/[^a-zA-Z0-9]/g,"-");if(e.length<=200)return e;let a=w(t);return`${e.slice(0,200)}-${a}`},w=t=>{let e=0;for(let a=0;a<t.length;a++)e=(e<<5)-e+t.charCodeAt(a)|0;return Math.abs(e).toString(36)},y=async t=>{try{let{stdout:e}=await o("pgrep",["-P",String(t)]);return e.trim().split("\n").map(t=>parseInt(t,10)).filter(t=>!Number.isNaN(t))}catch{return[]}},m=async t=>{if(u.isLinux)try{return await e.default.readlink(`/proc/${t}/cwd`)}catch{return null}try{let{stdout:e}=await o("lsof",["-a","-p",String(t),"-d","cwd","-Fn"]),a=e.split("\n").find(t=>t.startsWith("n/"));return a?a.slice(1):null}catch{return null}},g=async t=>{for(let e of t)try{let{stdout:t}=await o("ps",["-p",String(e),"-o","args="]),a=t.trim().match(/claude\s+--resume\s+([0-9a-f-]{36})/);if(a){let t=await m(e);return{pid:e,sessionId:a[1],cwd:t}}}catch{continue}return null},S=async t=>{try{let a=await e.default.readFile(t,"utf-8"),n=JSON.parse(a);if(!n.pid||!n.sessionId)return null;return n}catch{return null}},P=async(t,a)=>{let l=n.default.join(t,`${a}.jsonl`);try{return await e.default.access(l),l}catch{return null}},v=async()=>{try{return await o("claude",["--version"],{timeout:5e3,env:{...process.env,PATH:await (0,s.getShellPath)()}}),!0}catch{for(let t of h)try{return await e.default.access(t),!0}catch{}return!1}},I=async(t,e)=>{for(let a of e??await y(t))try{let{stdout:t}=await o("ps",["-p",String(a),"-o","args="]);if(t.trim().includes("claude"))return!0}catch{continue}return!1},A=async(t,a)=>{try{await e.default.access(c)}catch{return{status:await v()?"not-initialized":"not-installed",sessionId:null,jsonlPath:null,pid:null,startedAt:null,cwd:null}}let l=a??await y(t);if(0===l.length)return{status:"not-running",sessionId:null,jsonlPath:null,pid:null,startedAt:null,cwd:null};let i=(await Promise.all(l.map(y))).flat(),r=[...l,...i],s=new Set(r);try{for(let t of(await e.default.readdir(d)).filter(t=>t.endsWith(".json"))){let a=await S(n.default.join(d,t));if(!a||!s.has(a.pid))continue;let l="";try{let{stdout:t}=await o("ps",["-p",String(a.pid),"-o","args="]);l=t.trim()}catch{try{await e.default.unlink(n.default.join(d,t))}catch{}continue}if(!l.includes("claude")){try{await e.default.unlink(n.default.join(d,t))}catch{}continue}let i=p(a.cwd),r=n.default.join(f,i),u=await P(r,a.sessionId),c=a.sessionId;if(!u){let t=l.match(/--resume\s+([0-9a-f-]{36})/);if(t){let e=t[1],a=await P(r,e);a&&(u=a,c=e)}}return{status:"running",sessionId:c,jsonlPath:u,pid:a.pid,startedAt:a.startedAt,cwd:a.cwd}}}catch{}let u=await g(r);if(u){let t=u.cwd;if(t){let e=p(t),a=n.default.join(f,e),l=await P(a,u.sessionId);return{status:"running",sessionId:u.sessionId,jsonlPath:l,pid:u.pid,startedAt:null,cwd:t}}}return{status:"not-running",sessionId:null,jsonlPath:null,pid:null,startedAt:null,cwd:null}};t.s(["detectActiveSession",0,A,"getChildPids",0,y,"isClaudeRunning",0,I,"toClaudeProjectName",0,p,"watchSessionsDir",0,(t,n,l)=>{let r=null,s=null,u=null,o=null,c=null,f=!1,h=async()=>{let e;!f&&c&&(await (e=c,new Promise(t=>{(0,i.execFile)("ps",["-p",String(e)],e=>{t(!e)})}))||f||(c=null,n(await A(t))))},p=()=>{f||(u&&clearTimeout(u),u=setTimeout(async()=>{if(f)return;let e=await A(t);e.pid&&(c=e.pid),n(e)},200))},w=()=>{if(!f)try{(r=(0,a.watch)(d,p)).on("error",()=>{}),o&&(clearInterval(o),o=null)}catch{o||(o=setInterval(async()=>{if(!f)try{await e.default.access(d),w();let a=await A(t);a.pid&&(c=a.pid),n(a)}catch{}},6e4))}};return w(),s=setInterval(h,1e4),l?.skipInitial||A(t).then(t=>{f||(t.pid&&(c=t.pid),n(t))}),{stop:()=>{f=!0,r&&r.close(),s&&clearInterval(s),u&&clearTimeout(u),o&&clearInterval(o)}}}])},462180,796902,282992,t=>{"use strict";var e=t.i(143511),a=t.i(845994);t.i(924868);var n=t.i(814747),l=t.i(446786),i=t.i(25146);let r=n.default.join(l.default.homedir(),".purplemux"),s=n.default.join(r,"statusline.sh"),u=n.default.join(r,"rate-limits.json"),o=`#!/bin/sh
2
+ PORT_FILE="$HOME/.purplemux/port"
3
+ TOKEN_FILE="$HOME/.purplemux/cli-token"
4
+ [ -f "$PORT_FILE" ] || exit 0
5
+ [ -f "$TOKEN_FILE" ] || exit 0
6
+ PORT=$(cat "$PORT_FILE")
7
+ TOKEN=$(cat "$TOKEN_FILE")
8
+ curl -sf --max-time 2 -X POST \\
9
+ -H 'Content-Type: application/json' \\
10
+ -H "x-pmux-token: \${TOKEN}" \\
11
+ --data-binary @- \\
12
+ "http://localhost:\${PORT}/api/status/statusline" 2>/dev/null || exit 0
13
+ `;t.s(["RATE_LIMITS_FILE",0,u,"STATUSLINE_SCRIPT_CONTENT",0,o,"STATUSLINE_SCRIPT_PATH",0,s],796902),(0,i.createLogger)("hooks");let c=n.default.join(l.default.homedir(),".purplemux"),d=n.default.join(c,"hooks.json");n.default.join(c,"port"),n.default.join(c,"status-hook.sh");var f=t.i(160874);let h=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=t=>"string"==typeof t&&h.test(t),w=async t=>{let e=await (0,a.getDangerouslySkipPermissions)(),n=[`--settings ${d}`];return t&&n.push(`--append-system-prompt-file ${(0,f.getClaudePromptPath)(t)}`),e&&n.push("--dangerously-skip-permissions"),n.join(" ")},y=async(t,e)=>{if(!p(t))throw Error(`Invalid session ID format: ${t}`);let a=await w(e);return`claude --resume ${t} ${a}`},m=globalThis;m.__ptAgentProviders||(m.__ptAgentProviders=new Map);let g=m.__ptAgentProviders,S=t=>{g.set(t.id,t)},P=()=>Array.from(g.values());t.s(["getProviderByPanelType",0,t=>{if(!t)return null;for(let e of g.values())if(e.panelType===t)return e;return null},"getProviderByProcessName",0,t=>{for(let e of g.values())if(e.matchesProcess(t))return e;return null},"listProviders",0,P,"registerProvider",0,S],282992),S({id:"claude",displayName:"Claude Code",panelType:"claude-code",matchesProcess:t=>"claude"===t||"node"===t,isValidSessionId:p,detectActiveSession:(t,a)=>(0,e.detectActiveSession)(t,a),isAgentRunning:(t,a)=>(0,e.isClaudeRunning)(t,a),watchSessions:(t,a,n)=>(0,e.watchSessionsDir)(t,a,n),buildResumeCommand:(t,{workspaceId:e})=>y(t,e),buildLaunchCommand:async({workspaceId:t})=>{let e=await w(t);return`claude ${e}`},readSessionId:t=>t.claudeSessionId??null,writeSessionId:(t,e)=>{t.claudeSessionId=e??null},readJsonlPath:t=>t.claudeJsonlPath??null,writeJsonlPath:(t,e)=>{t.claudeJsonlPath=e??null},readSummary:t=>t.claudeSummary??null,writeSummary:(t,e)=>{t.claudeSummary=e??null}});let v={status:"not-running",sessionId:null,jsonlPath:null,pid:null,startedAt:null,cwd:null},I={status:"not-installed",sessionId:null,jsonlPath:null,pid:null,startedAt:null,cwd:null},A=async(t,e)=>{let a=P(),n=a.length>0;for(let l of a){let a=await l.detectActiveSession(t,e);if("running"===a.status)return{provider:l,info:a};"not-installed"!==a.status&&(n=!1)}return{provider:null,info:n?I:v}},T=async(t,e)=>{for(let a of P())if(await a.isAgentRunning(t,e))return!0;return!1};t.s(["detectAnyActiveSession",0,A,"isAnyAgentRunning",0,T],462180)}];
14
+
15
+ //# sourceMappingURL=src_lib_0dvlmi4._.js.map
@@ -0,0 +1,52 @@
1
+ module.exports=[160874,e=>{"use strict";var t=e.i(924868),a=e.i(814747),r=e.i(25146),i=e.i(825265);(0,r.createLogger)("claude-prompt");let s=e=>a.default.join((0,i.resolveLayoutDir)(e),"claude-prompt.md"),o=async e=>{let r=s(e.id);await t.default.mkdir(a.default.dirname(r),{recursive:!0});let i=`# purplemux context
2
+
3
+ You are running inside a purplemux workspace tab.
4
+
5
+ - **Workspace ID**: \`${e.id}\`
6
+
7
+ Use \`purplemux workspaces\` if you need the workspace name or directories.
8
+
9
+ ## purplemux CLI
10
+
11
+ The \`purplemux\` CLI lets you inspect and control other tabs in this workspace.
12
+ It reads port and token from \`~/.purplemux/{port,cli-token}\` automatically,
13
+ so no environment setup is needed.
14
+
15
+ ### Commands
16
+
17
+ \`\`\`bash
18
+ purplemux workspaces # list all workspaces
19
+ purplemux tab list -w ${e.id} # list tabs in this workspace
20
+ purplemux tab create -w ${e.id} [-n NAME] [-t TYPE] # create a tab (type: terminal | claude-code | web-browser | diff)
21
+ purplemux tab send -w ${e.id} TAB_ID CONTENT... # send input to a tab
22
+ purplemux tab status -w ${e.id} TAB_ID # tab status
23
+ purplemux tab result -w ${e.id} TAB_ID # capture current pane content
24
+ purplemux tab close -w ${e.id} TAB_ID # close a tab
25
+ \`\`\`
26
+
27
+ For the full HTTP API reference (including endpoint paths and payloads),
28
+ run:
29
+
30
+ \`\`\`bash
31
+ purplemux api-guide
32
+ \`\`\`
33
+
34
+ ### When to use
35
+
36
+ - Delegate work to another tab when a task benefits from isolation
37
+ (long-running builds, different project context, parallel exploration).
38
+ - Poll \`status\` and read \`result\` to verify delegated work.
39
+ - Prefer small, scoped tabs over cramming everything into one session.
40
+
41
+ ### Tab type notes
42
+
43
+ - **\`web-browser\` tabs**: Electron webviews, not tmux. The \`alive\` field in
44
+ \`tab list\` / \`tab status\` is always \`false\` for these — that is the normal
45
+ value, not a sign the tab is dead. Do not gate actions on \`alive\`. Use the
46
+ browser-specific HTTP endpoints (\`/browser/url\`, \`/browser/screenshot\`, …;
47
+ see \`purplemux api-guide\`) directly.
48
+ - **\`terminal\` / \`claude-code\` tabs**: run inside tmux, so \`alive\` is a valid
49
+ liveness signal.
50
+ `;try{if(await t.default.readFile(r,"utf-8")===i)return r}catch{}return await t.default.writeFile(r,i,"utf-8"),r};e.s(["getClaudePromptPath",0,s,"writeClaudePromptFile",0,o])},322429,e=>{"use strict";var t=e.i(924868),a=e.i(814747),r=e.i(446786),i=e.i(44014),s=e.i(459015),o=e.i(25146),l=e.i(666126),n=e.i(825265),u=e.i(804767),d=e.i(160874);let c=(0,o.createLogger)("workspace"),p="Workspace ",w=a.default.join(r.default.homedir(),".purplemux"),f=a.default.join(w,"workspaces.json"),y=a.default.join(w,"layout.json"),m=a.default.join(w,"tabs.json"),k=globalThis;k.__purplemuxWorkspaceLock||(k.__purplemuxWorkspaceLock=Promise.resolve());let g=async e=>{let t,a=new Promise(e=>{t=e}),r=k.__purplemuxWorkspaceLock;k.__purplemuxWorkspaceLock=a,await r;try{return await e()}finally{t()}},h=()=>({workspaces:[],groups:[],sidebarCollapsed:!1,sidebarWidth:240,updatedAt:new Date().toISOString()}),b=e=>(e.groups||(e.groups=[]),e.groups),v=async()=>{let e;try{e=await t.default.readFile(f,"utf-8")}catch{return null}try{let t=JSON.parse(e);for(let e of t.workspaces)!e.directories&&e.directory&&(e.directories=[e.directory],delete e.directory),delete e.order;for(let e of(Array.isArray(t.groups)||(t.groups=[]),t.groups))delete e.order;let a=new Set(t.groups.map(e=>e.id));for(let e of t.workspaces)e.groupId&&!a.has(e.groupId)&&(e.groupId=null);return t}catch{c.warn("Failed to parse workspaces.json, starting empty");try{await t.default.copyFile(f,f.replace(/\.json$/,".json.bak"))}catch{}return null}},I=async e=>{let a;a=b(e),e.workspaces=((e,t)=>{let a=new Set(t.map(e=>e.id)),r=new Map,i=[];for(let t of e){let e=t.groupId??null;if(e&&a.has(e)){let a=r.get(e)??[];a.push(t),r.set(e,a)}else i.push(t)}let s=[];for(let e of t){let t=r.get(e.id);t&&s.push(...t)}return s.push(...i),s})(e.workspaces,a);let{workspaces:r,groups:i,activeWorkspaceId:s,sidebarCollapsed:o,sidebarWidth:n}=e,u=JSON.stringify({workspaces:r,groups:i??[],activeWorkspaceId:s,sidebarCollapsed:o,sidebarWidth:n});if(k.__purplemuxWorkspacesContentCache===u)return;e.updatedAt=new Date().toISOString();let d=f+".tmp";try{await t.default.writeFile(d,JSON.stringify(e,null,2),{mode:384}),await t.default.rename(d,f)}catch(e){throw await t.default.unlink(d).catch(()=>{}),e}k.__purplemuxWorkspacesContentCache=u,(0,l.broadcastSync)({type:"workspace"})},W=async()=>{let e=await (0,n.readLayoutFile)(y);if(!e)return null;let a="ws-default";await t.default.mkdir((0,n.resolveLayoutDir)(a),{recursive:!0}),await (0,n.writeLayoutFile)(e,(0,n.resolveLayoutFile)(a));let i={workspaces:[{id:a,name:"default",directories:[r.default.homedir()]}],sidebarCollapsed:!1,sidebarWidth:240,updatedAt:e.updatedAt||new Date().toISOString()};return await I(i),c.info("Phase 4 layout.json → Workspace 'default' migration complete"),i},x=async()=>{try{let e=await t.default.readFile(m,"utf-8"),a=JSON.parse(e);if(!Array.isArray(a.tabs)||0===a.tabs.length)return null;let r=`pane-${(0,i.nanoid)(6)}`,s={root:{type:"pane",id:r,tabs:a.tabs,activeTabId:a.activeTabId??null},activePaneId:r,updatedAt:new Date().toISOString()},o=y+".tmp";try{await t.default.writeFile(o,JSON.stringify(s,null,2),{mode:384}),await t.default.rename(o,y)}catch(e){throw await t.default.unlink(o).catch(()=>{}),e}return c.info("tabs.json → layout.json migration complete"),await W()}catch{return null}},$=async()=>{await t.default.mkdir(a.default.join(w,"workspaces"),{recursive:!0});let e=await v();if(!e&&(await t.default.access(y).then(()=>!0).catch(()=>!1)?e=await W():await t.default.access(m).then(()=>!0).catch(()=>!1)&&(e=await x())),!e){let t=h();await I(t),e=t,c.info("Initial workspaces.json created")}if(0===e.workspaces.length)return;let r=await (0,s.listSessions)();for(let t of e.workspaces){let e=(0,n.resolveLayoutFile)(t.id),a=await (0,n.readLayoutFile)(e);if(!a){c.warn(`Workspace '${t.name}': layout.json corrupted, reset to default pane`),a=await (0,n.createDefaultLayout)(t.id,t.directories[0]),await (0,n.writeLayoutFile)(a,e);continue}let i=(0,u.collectAllTabs)(a.root).map(e=>e.sessionName),s=`pt-${t.id}-`,o=r.filter(e=>i.includes(e)||e.startsWith(s));try{await (0,n.crossCheckLayout)(a,o,t.id,t.directories[0])&&await (0,n.writeLayoutFile)(a,e)}catch(e){c.error(`Workspace '${t.name}': tmux consistency check failed: ${e instanceof Error?e.message:e}`)}}},L=async()=>{let e=await v();return e?{workspaces:e.workspaces,groups:e.groups??[],activeWorkspaceId:e.activeWorkspaceId,sidebarCollapsed:e.sidebarCollapsed,sidebarWidth:e.sidebarWidth}:{workspaces:[],groups:[],sidebarCollapsed:!1,sidebarWidth:220}},F=async()=>{let e=await v();return e?.activeWorkspaceId&&e.workspaces.some(t=>t.id===e.activeWorkspaceId)?e.activeWorkspaceId:e?.workspaces[0]?.id??null},C=async e=>{let t=await v();return t?.workspaces.find(t=>t.id===e)},D=async(e,a,r)=>g(async()=>{let s;try{s=await t.default.stat(e)}catch{throw Error("Directory does not exist")}if(!s.isDirectory())throw Error("Please enter a directory path, not a file");let o=await v()??h(),l=`ws-${(0,i.nanoid)(6)}`,u=a?.trim()||(e=>{let t=0;for(let a of e)if(a.name.startsWith(p)){let e=parseInt(a.name.slice(p.length),10);e>t&&(t=e)}return`${p}${t+1}`})(o.workspaces),w=await (0,n.createDefaultLayout)(l,e,r);await t.default.mkdir((0,n.resolveLayoutDir)(l),{recursive:!0}),await (0,n.writeLayoutFile)(w,(0,n.resolveLayoutFile)(l));let f={id:l,name:u,directories:[e]};return o.workspaces.push(f),await I(o),await (0,d.writeClaudePromptFile)(f),c.debug(`Created: ${l} (${u}, ${e})`),f}),S=async e=>g(async()=>{let t=await v()??h(),a=t.workspaces.findIndex(t=>t.id===e);if(-1===a)return!1;let r=t.workspaces[a],i=await (0,n.readLayoutFile)((0,n.resolveLayoutFile)(e));if(i)for(let e of(0,u.collectAllTabs)(i.root))try{await (0,s.killSession)(e.sessionName)}catch{}try{await (0,n.removeLayoutFile)(e)}catch{}return t.workspaces.splice(a,1),await I(t),c.info(`Deleted: ${e} (${r.name})`),!0}),A=async(e,t)=>g(async()=>{let a=await v();if(!a)return null;let r=a.workspaces.find(t=>t.id===e);return r?(r.name=t,await I(a),await (0,d.writeClaudePromptFile)(r),c.debug(`Renamed: ${e} → "${t}"`),{...r}):null}),T=async e=>g(async()=>{let t=await v()??h();void 0!==e.activeWorkspaceId&&(t.activeWorkspaceId=e.activeWorkspaceId),void 0!==e.sidebarCollapsed&&(t.sidebarCollapsed=e.sidebarCollapsed),void 0!==e.sidebarWidth&&(t.sidebarWidth=e.sidebarWidth),await I(t)}),j=async(e,t)=>g(async()=>{let a=await v();if(!a)return;let r=a.workspaces.find(t=>t.id===e);r&&JSON.stringify(r.directories)!==JSON.stringify(t)&&(r.directories=t,await I(a),await (0,d.writeClaudePromptFile)(r))}),P=async e=>g(async()=>{let t=await v()??h(),a=new Map(t.workspaces.map(e=>[e.id,e])),r=new Set((t.groups??[]).map(e=>e.id)),i=[];for(let t of e){let e=a.get(t.id);if(!e)return!1;void 0!==t.groupId&&(e.groupId=t.groupId&&r.has(t.groupId)?t.groupId:null),i.push(e)}return i.length===t.workspaces.length&&(t.workspaces=i,await I(t),!0)}),_=async e=>g(async()=>{let t=await v()??h(),a=b(t),r=e.trim()||`Group ${a.length+1}`,s={id:`grp-${(0,i.nanoid)(6)}`,name:r,collapsed:!1};return a.push(s),await I(t),c.debug(`Group created: ${s.id} (${s.name})`),s}),N=async(e,t)=>g(async()=>{let a=await v();if(!a)return null;let r=(a.groups??[]).find(t=>t.id===e);if(!r)return null;let i=t.trim();return i?(r.name=i,await I(a),{...r}):r}),O=async(e,t)=>g(async()=>{let a=await v();if(!a)return!1;let r=(a.groups??[]).find(t=>t.id===e);return!!r&&(r.collapsed===t||(r.collapsed=t,await I(a),!0))}),G=async e=>g(async()=>{let t=await v();if(!t)return!1;let a=b(t),r=a.findIndex(t=>t.id===e);if(-1===r)return!1;for(let a of t.workspaces)a.groupId===e&&(a.groupId=null);return a.splice(r,1),await I(t),c.info(`Group ungrouped: ${e}`),!0}),E=async e=>g(async()=>{let t=await v();if(!t)return!1;let a=b(t),r=new Map(a.map(e=>[e.id,e])),i=[];for(let t of e){let e=r.get(t);if(!e)return!1;i.push(e)}return i.length===a.length&&(t.groups=i,await I(t),!0)}),J=async(e,t)=>g(async()=>{let a=await v();if(!a)return!1;let r=a.workspaces.find(t=>t.id===e);if(!r)return!1;let i=new Set((a.groups??[]).map(e=>e.id)),s=t&&i.has(t)?t:null;return(r.groupId??null)===s||(r.groupId=s,await I(a),!0)}),B=async e=>{try{if(!(await t.default.stat(e)).isDirectory())return{valid:!1,error:"Please enter a directory path, not a file"}}catch{return{valid:!1,error:"Directory does not exist"}}return{valid:!0,suggestedName:a.default.basename(e)}};e.s(["createGroup",0,_,"createWorkspace",0,D,"deleteWorkspace",0,S,"getActiveWorkspaceId",0,F,"getWorkspaceById",0,C,"getWorkspaces",0,L,"initWorkspaceStore",0,$,"renameGroup",0,N,"renameWorkspace",0,A,"reorderGroups",0,E,"reorderWorkspaces",0,P,"setGroupCollapsed",0,O,"setWorkspaceGroup",0,J,"ungroupGroup",0,G,"updateActive",0,T,"updateWorkspaceDirectories",0,j,"validateDirectory",0,B],322429)}];
51
+
52
+ //# sourceMappingURL=src_lib_0ojl2hg._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[825265,804767,e=>{"use strict";var t=e.i(924868),a=e.i(814747),n=e.i(446786),i=e.i(44014),r=e.i(459015),l=e.i(666126),o=e.i(25146);let s=e=>"pane"===e.type?[e]:[...s(e.children[0]),...s(e.children[1])],d=e=>s(e).flatMap(e=>e.tabs),c=(e,t)=>"pane"===e.type?e.id===t?e:null:c(e.children[0],t)||c(e.children[1],t),u=e=>"pane"===e.type?e.id:u(e.children[0]),p=e=>"pane"===e.type?e.id:p(e.children[1]),w=(e,t,a)=>"pane"===e.type?e.id===t?a:e:{...e,children:[w(e.children[0],t,a),w(e.children[1],t,a)]},y=(e,t)=>{if("pane"===e.type)return null;let[a,n]=e.children;if("pane"===a.type&&a.id===t)return n;if("pane"===n.type&&n.id===t)return a;let i=y(a,t);if(i)return{...e,children:[i,n]};let r=y(n,t);return r?{...e,children:[a,r]}:null},f=(e,t)=>{if("pane"===e.type)return null;let[a,n]=e.children;return"pane"===a.type&&a.id===t?u(n):"pane"===n.type&&n.id===t?p(a):f(a,t)||f(n,t)},b=(e,t)=>{let a=f(e.root,t),n=y(e.root,t);n&&(e.root=n),e.activePaneId===t&&(e.activePaneId=a??s(e.root)[0]?.id??null)},m=(e,t,a)=>{if("split"!==e.type)return e;if(0===t.length)return{...e,ratio:a};let[n,...i]=t,r=[e.children[0],e.children[1]];return r[n]=m(e.children[n],i,a),{...e,children:r}},h=(e,t)=>"pane"===e.type||e.orientation!==t?1:h(e.children[0],t)+h(e.children[1],t),v=e=>{if("pane"===e.type)return!0;let t=h(e.children[0],e.orientation),a=h(e.children[1],e.orientation);return!(Math.abs(e.ratio-t/(t+a)*100)>1)&&v(e.children[0])&&v(e.children[1])},I=e=>{if("pane"===e.type)return e;let t=h(e.children[0],e.orientation),a=Math.round(t/(t+h(e.children[1],e.orientation))*1e4)/100;return{...e,ratio:a,children:[I(e.children[0]),I(e.children[1])]}};e.s(["collectAllTabs",0,d,"collectPanes",0,s,"equalizeNode",0,I,"findPane",0,c,"getFirstPaneId",0,u,"isEqualized",0,v,"removePaneWithFocus",0,b,"replacePane",0,w,"updateRatioAtPath",0,m],804767);let S=(0,o.createLogger)("layout"),T=a.default.join(n.default.homedir(),".purplemux"),g=globalThis;g.__ptLayoutLock||(g.__ptLayoutLock=Promise.resolve()),g.__ptLayoutContentCache||(g.__ptLayoutContentCache=new Map),void 0===g.__ptLayoutReconciler&&(g.__ptLayoutReconciler=null);let P=async e=>{let t,a=new Promise(e=>{t=e}),n=g.__ptLayoutLock;g.__ptLayoutLock=a,await n;try{return await e()}finally{t()}},L=()=>`pane-${(0,i.nanoid)(6)}`,N=()=>`tab-${(0,i.nanoid)(6)}`,_=e=>a.default.join(T,"workspaces",e),k=e=>a.default.join(_(e),"layout.json"),C=(e,t)=>{let a=L(),n=((e,t,a=0,n)=>{let i=N(),l={id:i,sessionName:(0,r.workspaceSessionName)(e,t,i),name:"",order:a};return n&&(l.cwd=n),l})(e,a,0,t);return{pane:{type:"pane",id:a,tabs:[n],activeTabId:n.id},tab:n}},A=async e=>{let a;try{a=await t.default.readFile(e,"utf-8")}catch{return null}try{return JSON.parse(a)}catch{S.warn(`${e} parse failed`);try{await t.default.copyFile(e,e.replace(/\.json$/,".json.bak"))}catch{}return null}},O=async(e,n)=>{let i,r=JSON.stringify({root:e.root,activePaneId:e.activePaneId}),o=g.__ptLayoutContentCache;if(o.get(n)===r)return;await t.default.mkdir(a.default.dirname(n),{recursive:!0});let s=n+".tmp";try{await t.default.writeFile(s,JSON.stringify(e,null,2),{mode:384}),await t.default.rename(s,n)}catch(e){throw await t.default.unlink(s).catch(()=>{}),e}o.set(n,r);let c=(i=n.match(/workspaces\/(ws-[^/]+)\//),i?.[1]??null);if(c){let t=g.__ptLayoutReconciler;if(t){let a=d(e.root).map(e=>e.id);t.reconcileWorkspaceTabs(c,a)}(0,l.broadcastSync)({type:"layout",workspaceId:c})}},D=async e=>{await t.default.rm(_(e),{recursive:!0,force:!0}),F(e);let a=g.__ptLayoutReconciler;a&&a.removeWorkspaceTabs(e),(0,l.broadcastSync)({type:"layout",workspaceId:e})},F=e=>{let t=k(e);g.__ptLayoutContentCache.delete(t)},M=(t,a)=>{let n=[...new Set(d(a).map(e=>e.cwd).filter(e=>!!e))];n.length>0&&e.A(981532).then(({updateWorkspaceDirectories:e})=>{e(t,n).catch(()=>{})}).catch(()=>{})},R=async(e,t,a,n)=>{let i=!1,l=new Set(t),o=s(e.root),d=new Set;for(let e of o)for(let t of e.tabs)if("web-browser"!==t.panelType&&(d.add(t.sessionName),!l.has(t.sessionName)&&"claude-code"===t.panelType)){let e=t.cwd||n;S.debug(`crossCheck: Claude tab session recreated: ${t.sessionName} (cwd: ${e})`),await (0,r.createSession)(t.sessionName,80,24,e),i=!0}let c=t.filter(e=>!d.has(e));if(c.length>0){i=!0;let e=o[0];if(e){let t=e.tabs.length>0?Math.max(...e.tabs.map(e=>e.order)):-1;for(let a of c)t++,e.tabs.push({id:N(),sessionName:a,name:"",order:t});!e.activeTabId&&e.tabs.length>0&&(e.activeTabId=e.tabs[0].id)}}if(i){e.updatedAt=new Date().toISOString();let t=s(e.root);e.activePaneId&&!t.some(t=>t.id===e.activePaneId)&&(e.activePaneId=t[0]?.id??null)}return i},U=async(e,t,a)=>{let{pane:n,tab:i}=C(e,t);return a?.panelType&&(i.panelType=a.panelType),await (0,r.createSession)(i.sessionName,80,24,t),{root:n,activePaneId:n.id,updatedAt:new Date().toISOString()}},$=async(e,t)=>P(async()=>{let a=k(e),n=await A(a);if(n)return n;let{pane:i,tab:l}=C(e,t);await (0,r.createSession)(l.sessionName,80,24,t);let o={root:i,activePaneId:i.id,updatedAt:new Date().toISOString()};return await O(o,a),o}),j=async(e,t)=>{let a=L(),n=N(),i=(0,r.workspaceSessionName)(e,a,n);return await (0,r.createSession)(i,80,24,t),{paneId:a,tab:{id:n,sessionName:i,name:"",order:0,...t?{cwd:t}:{}}}},x=async(e,t=[])=>{for(let e of t)try{await (0,r.killSession)(e)}catch{}},W=async(e,t,a,n,i,l)=>P(async()=>{let o=k(e),d=await A(o);if(!d)return null;let c=s(d.root).find(e=>e.id===t);if(!c)return null;let u="web-browser"===i,p=N(),w=(0,r.workspaceSessionName)(e,t,p);!u&&(await (0,r.createSession)(w,80,24,n),l&&await (0,r.sendKeys)(w,l));let y=c.tabs.length>0?Math.max(...c.tabs.map(e=>e.order))+1:0,f={id:p,sessionName:w,name:a?.trim()||(u?"Web Browser":""),order:y,...n?{cwd:n}:{},...i?{panelType:i}:{}};return c.tabs.push(f),c.activeTabId=p,d.updatedAt=new Date().toISOString(),await O(d,o),M(e,d.root),f}),E=async(e,t,a)=>{let n=await P(async()=>{let n=k(e),i=await A(n);if(!i)return null;let r=s(i.root).find(e=>e.id===t);if(!r)return null;let l=r.tabs.find(e=>e.id===a);return l?{sessionName:l.sessionName,panelType:l.panelType}:null});return!!n&&("web-browser"!==n.panelType&&await (0,r.killSession)(n.sessionName),P(async()=>{let n=k(e),i=await A(n);if(!i)return!1;let r=s(i.root).find(e=>e.id===t);if(!r)return!1;let l=r.tabs.findIndex(e=>e.id===a);return -1!==l&&(r.tabs.splice(l,1),r.activeTabId===a&&(r.activeTabId=r.tabs[0]?.id??null),0===r.tabs.length&&s(i.root).length>1&&b(i,t),r.tabs.forEach((e,t)=>{e.order=t}),i.updatedAt=new Date().toISOString(),await O(i,n),M(e,i.root),!0)}))},q=async(e,t,a,n)=>P(async()=>{let i=k(e),l=await A(i);if(!l)return!1;let o=s(l.root).find(e=>e.id===t);if(!o)return!1;let d=o.tabs.find(e=>e.id===a);return!!d&&(!!await (0,r.hasSession)(d.sessionName)||(await (0,r.createSession)(d.sessionName,80,24,d.cwd),n&&await (0,r.sendKeys)(d.sessionName,n),!0))}),z=e=>{let t=e.match(/^pt-(ws-.*?)-(pane-.*?)-(tab-.+)$/);return t?{wsId:t[1],paneId:t[2],tabId:t[3]}:null},B=async(e,t)=>{let a=z(e);a&&await P(async()=>{let n=k(a.wsId),i=await A(n);if(!i)return;let r=d(i.root).find(t=>t.sessionName===e);r&&(r.claudeSessionId=t,i.updatedAt=new Date().toISOString(),await O(i,n))})},J=async(e,t)=>{let a=z(e);a&&await P(async()=>{let n=k(a.wsId),i=await A(n);if(!i)return;let r=d(i.root).find(t=>t.sessionName===e);r&&r.claudeSummary!==t&&(r.claudeSummary=t,i.updatedAt=new Date().toISOString(),await O(i,n))})},K=async(e,t)=>{let a=z(e);a&&await P(async()=>{let n=k(a.wsId),i=await A(n);if(!i)return;let r=d(i.root).find(t=>t.sessionName===e);r&&r.lastUserMessage!==t&&(r.lastUserMessage=t,i.updatedAt=new Date().toISOString(),await O(i,n))})},G=async(e,t,a)=>{let n=z(e);n&&await P(async()=>{let i=k(n.wsId),r=await A(i);if(!r)return;let l=d(r.root).find(t=>t.sessionName===e);l&&(l.cliState!==t||l.dismissedAt!==a)&&(l.cliState=t,l.dismissedAt=a,r.updatedAt=new Date().toISOString(),await O(r,i))})},H=async(e,t)=>P(async()=>{let a=k(e),n=await A(a);if(!n)return null;let i=t(n);return i?(i.updatedAt=new Date().toISOString(),await O(i,a),M(e,i.root),i):null}),Q=async(e,t)=>H(e,e=>{if(void 0!==t.activePaneId){if(!c(e.root,t.activePaneId))return null;e.activePaneId=t.activePaneId}return t.ratioUpdate&&(e.root=m(e.root,t.ratioUpdate.path,t.ratioUpdate.ratio)),t.equalize&&(e.root=I(e.root)),e}),V=async(e,t,a)=>H(e,e=>{let n=c(e.root,t);if(!n)return null;if(void 0!==a.activeTabId){if(!n.tabs.some(e=>e.id===a.activeTabId))return null;n.activeTabId=a.activeTabId}return e}),X=async(e,t,a,n,i)=>{let l="web-browser"===i,o=L(),s=N(),d=(0,r.workspaceSessionName)(e,o,s);l||await (0,r.createSession)(d,80,24,n);let u={id:s,sessionName:d,name:l?"Web Browser":"",order:0,...n?{cwd:n}:{}};i&&(u.panelType=i);let p={type:"pane",id:o,tabs:[u],activeTabId:s},y=await H(e,e=>{let i=c(e.root,t);if(!i)return null;let r=v(e.root);if(n){let e=i.tabs.find(e=>e.id===i.activeTabId);e&&(e.cwd=n)}let l={type:"split",orientation:a,ratio:50,children:[{...i},p]};return e.root=w(e.root,t,l),r&&(e.root=I(e.root)),e.activePaneId=o,e});return y||l||await (0,r.killSession)(d).catch(()=>{}),y},Y=async(e,t)=>{let a=[],n=await P(async()=>{let n=k(e),i=await A(n);if(!i)return null;let r=c(i.root,t);if(!r||s(i.root).length<=1)return null;a=r.tabs.filter(e=>"web-browser"!==e.panelType).map(e=>e.sessionName);let l=v(i.root);return b(i,t),l&&(i.root=I(i.root)),i.updatedAt=new Date().toISOString(),await O(i,n),M(e,i.root),i});return await Promise.all(a.map(e=>(0,r.killSession)(e).catch(()=>{}))),n},Z=async(e,t,a)=>H(e,e=>{let n=c(e.root,t);if(!n)return null;let i=new Map(n.tabs.map(e=>[e.id,e])),r=a.map((e,t)=>{let a=i.get(e);return a?{...a,order:t}:null}).filter(e=>null!==e);return r.length!==n.tabs.length?null:(n.tabs=r,e)}),ee=async(e,t,a,n,i)=>H(e,e=>{let r=c(e.root,a),l=c(e.root,n);if(!r||!l)return null;let o=r.tabs.findIndex(e=>e.id===t);if(-1===o)return null;let[d]=r.tabs.splice(o,1);return r.activeTabId===t&&(r.activeTabId=r.tabs[0]?.id??null),r.tabs.forEach((e,t)=>{e.order=t}),l.tabs.splice(i,0,d),l.tabs.forEach((e,t)=>{e.order=t}),l.activeTabId=t,0===r.tabs.length&&s(e.root).length>1&&b(e,a),e.activePaneId=n,e}),et=async(t,a,n,i)=>{let r,l;if(void 0!==i.cwd||void 0!==i.title){let o=await (async()=>{let e=k(t),i=await A(e);return i?c(i.root,a)?.tabs.find(e=>e.id===n)?.sessionName??null:null})();if(o){let{getSessionCwd:t,getPaneCurrentCommand:a}=await e.A(322522),{formatTabTitle:n}=await e.A(245061);if(void 0!==i.cwd&&(r=await t(o)),void 0!==i.title){let[e,i]=await Promise.all([a(o),void 0!==r?Promise.resolve(r):t(o)]);e&&i&&(l=n(`${e}|${i}`))}}}return H(t,e=>{let t=c(e.root,a);if(!t)return null;let o=t.tabs.find(e=>e.id===n);if(!o)return null;let s=void 0!==i.title?l??i.title:void 0;return void 0!==i.name&&(o.name=i.name),void 0!==i.panelType&&(o.panelType=i.panelType),void 0!==s&&(o.title=s),void 0!==i.cwd&&(o.cwd=r??i.cwd),void 0!==i.lastCommand&&(o.lastCommand=i.lastCommand),void 0!==i.webUrl&&(o.webUrl=i.webUrl),void 0!==i.terminalRatio&&(o.terminalRatio=i.terminalRatio),void 0!==i.terminalCollapsed&&(o.terminalCollapsed=i.terminalCollapsed),e})};e.s(["addTabToPane",0,W,"closePaneInLayout",0,Y,"createDefaultLayout",0,U,"createPane",0,j,"crossCheckLayout",0,R,"deletePane",0,x,"getLayout",0,$,"moveTabBetweenPanes",0,ee,"parseSessionName",0,z,"patchLayout",0,Q,"patchPane",0,V,"patchTab",0,et,"readLayoutFile",0,A,"removeLayoutFile",0,D,"removeTabFromPane",0,E,"reorderTabsInPane",0,Z,"resolveLayoutDir",0,_,"resolveLayoutFile",0,k,"restartTabSession",0,q,"setLayoutReconciler",0,e=>{g.__ptLayoutReconciler=e},"splitPaneInLayout",0,X,"updateTabClaudeSessionId",0,B,"updateTabClaudeSummary",0,J,"updateTabCliStatus",0,G,"updateTabLastUserMessage",0,K,"writeLayoutFile",0,O],825265)}];
1
+ module.exports=[825265,804767,e=>{"use strict";var t=e.i(924868),a=e.i(814747),n=e.i(446786),i=e.i(44014),r=e.i(459015),l=e.i(666126),o=e.i(25146);let s=e=>"pane"===e.type?[e]:[...s(e.children[0]),...s(e.children[1])],d=e=>s(e).flatMap(e=>e.tabs),c=(e,t)=>"pane"===e.type?e.id===t?e:null:c(e.children[0],t)||c(e.children[1],t),u=e=>"pane"===e.type?e.id:u(e.children[0]),p=e=>"pane"===e.type?e.id:p(e.children[1]),w=(e,t,a)=>"pane"===e.type?e.id===t?a:e:{...e,children:[w(e.children[0],t,a),w(e.children[1],t,a)]},y=(e,t)=>{if("pane"===e.type)return null;let[a,n]=e.children;if("pane"===a.type&&a.id===t)return n;if("pane"===n.type&&n.id===t)return a;let i=y(a,t);if(i)return{...e,children:[i,n]};let r=y(n,t);return r?{...e,children:[a,r]}:null},f=(e,t)=>{if("pane"===e.type)return null;let[a,n]=e.children;return"pane"===a.type&&a.id===t?u(n):"pane"===n.type&&n.id===t?p(a):f(a,t)||f(n,t)},m=(e,t)=>{let a=f(e.root,t),n=y(e.root,t);n&&(e.root=n),e.activePaneId===t&&(e.activePaneId=a??s(e.root)[0]?.id??null)},b=(e,t,a)=>{if("split"!==e.type)return e;if(0===t.length)return{...e,ratio:a};let[n,...i]=t,r=[e.children[0],e.children[1]];return r[n]=b(e.children[n],i,a),{...e,children:r}},h=(e,t)=>"pane"===e.type||e.orientation!==t?1:h(e.children[0],t)+h(e.children[1],t),v=e=>{if("pane"===e.type)return!0;let t=h(e.children[0],e.orientation),a=h(e.children[1],e.orientation);return!(Math.abs(e.ratio-t/(t+a)*100)>1)&&v(e.children[0])&&v(e.children[1])},I=e=>{if("pane"===e.type)return e;let t=h(e.children[0],e.orientation),a=Math.round(t/(t+h(e.children[1],e.orientation))*1e4)/100;return{...e,ratio:a,children:[I(e.children[0]),I(e.children[1])]}};e.s(["collectAllTabs",0,d,"collectPanes",0,s,"equalizeNode",0,I,"findPane",0,c,"getFirstPaneId",0,u,"isEqualized",0,v,"removePaneWithFocus",0,m,"replacePane",0,w,"updateRatioAtPath",0,b],804767);let S=(0,o.createLogger)("layout"),T=a.default.join(n.default.homedir(),".purplemux"),g=globalThis;g.__ptLayoutLock||(g.__ptLayoutLock=Promise.resolve()),g.__ptLayoutContentCache||(g.__ptLayoutContentCache=new Map),void 0===g.__ptLayoutReconciler&&(g.__ptLayoutReconciler=null);let P=async e=>{let t,a=new Promise(e=>{t=e}),n=g.__ptLayoutLock;g.__ptLayoutLock=a,await n;try{return await e()}finally{t()}},L=()=>`pane-${(0,i.nanoid)(6)}`,N=()=>`tab-${(0,i.nanoid)(6)}`,_=e=>a.default.join(T,"workspaces",e),k=e=>a.default.join(_(e),"layout.json"),C=(e,t)=>{let a=L(),n=((e,t,a=0,n)=>{let i=N(),l={id:i,sessionName:(0,r.workspaceSessionName)(e,t,i),name:"",order:a};return n&&(l.cwd=n),l})(e,a,0,t);return{pane:{type:"pane",id:a,tabs:[n],activeTabId:n.id},tab:n}},A=async e=>{let a;try{a=await t.default.readFile(e,"utf-8")}catch{return null}try{return JSON.parse(a)}catch{S.warn(`${e} parse failed`);try{await t.default.copyFile(e,e.replace(/\.json$/,".json.bak"))}catch{}return null}},D=async(e,n)=>{let i,r=JSON.stringify({root:e.root,activePaneId:e.activePaneId}),o=g.__ptLayoutContentCache;if(o.get(n)===r)return;await t.default.mkdir(a.default.dirname(n),{recursive:!0});let s=n+".tmp";try{await t.default.writeFile(s,JSON.stringify(e,null,2),{mode:384}),await t.default.rename(s,n)}catch(e){throw await t.default.unlink(s).catch(()=>{}),e}o.set(n,r);let c=(i=n.match(/workspaces\/(ws-[^/]+)\//),i?.[1]??null);if(c){let t=g.__ptLayoutReconciler;if(t){let a=d(e.root).map(e=>e.id);t.reconcileWorkspaceTabs(c,a)}(0,l.broadcastSync)({type:"layout",workspaceId:c})}},$=async e=>{await t.default.rm(_(e),{recursive:!0,force:!0}),O(e);let a=g.__ptLayoutReconciler;a&&a.removeWorkspaceTabs(e),(0,l.broadcastSync)({type:"layout",workspaceId:e})},O=e=>{let t=k(e);g.__ptLayoutContentCache.delete(t)},F=(t,a)=>{let n=[...new Set(d(a).map(e=>e.cwd).filter(e=>!!e))];n.length>0&&e.A(981532).then(({updateWorkspaceDirectories:e})=>{e(t,n).catch(()=>{})}).catch(()=>{})},M=async(e,t,a,n)=>{let i=!1,l=new Set(t),o=s(e.root),d=new Set;for(let e of o)for(let t of e.tabs)if("web-browser"!==t.panelType&&(d.add(t.sessionName),!l.has(t.sessionName)&&"claude-code"===t.panelType)){let e=t.cwd||n;S.debug(`crossCheck: Claude tab session recreated: ${t.sessionName} (cwd: ${e})`),await (0,r.createSession)(t.sessionName,80,24,e),i=!0}let c=t.filter(e=>!d.has(e));if(c.length>0){i=!0;let e=o[0];if(e){let t=e.tabs.length>0?Math.max(...e.tabs.map(e=>e.order)):-1;for(let a of c)t++,e.tabs.push({id:N(),sessionName:a,name:"",order:t});!e.activeTabId&&e.tabs.length>0&&(e.activeTabId=e.tabs[0].id)}}if(i){e.updatedAt=new Date().toISOString();let t=s(e.root);e.activePaneId&&!t.some(t=>t.id===e.activePaneId)&&(e.activePaneId=t[0]?.id??null)}return i},R=async(e,t,a)=>{let{pane:n,tab:i}=C(e,t);return a?.panelType&&(i.panelType=a.panelType),await (0,r.createSession)(i.sessionName,80,24,t),{root:n,activePaneId:n.id,updatedAt:new Date().toISOString()}},U=async(e,t)=>P(async()=>{let a=k(e),n=await A(a);if(n)return n;let{pane:i,tab:l}=C(e,t);await (0,r.createSession)(l.sessionName,80,24,t);let o={root:i,activePaneId:i.id,updatedAt:new Date().toISOString()};return await D(o,a),o}),x=async(e,t)=>{let a=L(),n=N(),i=(0,r.workspaceSessionName)(e,a,n);return await (0,r.createSession)(i,80,24,t),{paneId:a,tab:{id:n,sessionName:i,name:"",order:0,...t?{cwd:t}:{}}}},j=async(e,t=[])=>{for(let e of t)try{await (0,r.killSession)(e)}catch{}},E=async(e,t,a,n,i,l)=>P(async()=>{let o=k(e),d=await A(o);if(!d)return null;let c=s(d.root).find(e=>e.id===t);if(!c)return null;let u="web-browser"===i,p=N(),w=(0,r.workspaceSessionName)(e,t,p);!u&&(await (0,r.createSession)(w,80,24,n),l&&await (0,r.sendKeys)(w,l));let y=c.tabs.length>0?Math.max(...c.tabs.map(e=>e.order))+1:0,f={id:p,sessionName:w,name:a?.trim()||(u?"Web Browser":""),order:y,...n?{cwd:n}:{},...i?{panelType:i}:{}};return c.tabs.push(f),c.activeTabId=p,d.updatedAt=new Date().toISOString(),await D(d,o),F(e,d.root),f}),W=async(e,t,a)=>{let n=await P(async()=>{let n=k(e),i=await A(n);if(!i)return null;let r=s(i.root).find(e=>e.id===t);if(!r)return null;let l=r.tabs.find(e=>e.id===a);return l?{sessionName:l.sessionName,panelType:l.panelType}:null});return!!n&&("web-browser"!==n.panelType&&await (0,r.killSession)(n.sessionName),P(async()=>{let n=k(e),i=await A(n);if(!i)return!1;let r=s(i.root).find(e=>e.id===t);if(!r)return!1;let l=r.tabs.findIndex(e=>e.id===a);return -1!==l&&(r.tabs.splice(l,1),r.activeTabId===a&&(r.activeTabId=r.tabs[0]?.id??null),0===r.tabs.length&&s(i.root).length>1&&m(i,t),r.tabs.forEach((e,t)=>{e.order=t}),i.updatedAt=new Date().toISOString(),await D(i,n),F(e,i.root),!0)}))},q=async(e,t,a,n)=>P(async()=>{let i=k(e),l=await A(i);if(!l)return!1;let o=s(l.root).find(e=>e.id===t);if(!o)return!1;let d=o.tabs.find(e=>e.id===a);if(!d)return!1;if(await (0,r.hasSession)(d.sessionName))return!0;let c=await (0,r.resolveExistingDir)(d.cwd),u=!!(d.cwd&&d.cwd!==c);return await (0,r.createSession)(d.sessionName,80,24,c),n&&!u&&await (0,r.sendKeys)(d.sessionName,n),u&&(S.warn(`tab cwd missing, falling back to ${c}: ${d.sessionName} (was ${d.cwd})`),d.cwd=c,delete d.lastCommand,l.updatedAt=new Date().toISOString(),await D(l,i)),!0}),z=async e=>P(async()=>{let t=B(e);if(!t)return;let a=k(t.wsId),n=await A(a);if(!n)return;let i=s(n.root).find(e=>e.id===t.paneId);if(!i)return;let l=i.tabs.find(e=>e.id===t.tabId);if(!l||!l.cwd)return;let o=await (0,r.resolveExistingDir)(l.cwd);o!==l.cwd&&(S.warn(`tab cwd missing, clearing: ${e} (was ${l.cwd})`),l.cwd=o,delete l.lastCommand,n.updatedAt=new Date().toISOString(),await D(n,a))}),B=e=>{let t=e.match(/^pt-(ws-.*?)-(pane-.*?)-(tab-.+)$/);return t?{wsId:t[1],paneId:t[2],tabId:t[3]}:null},J=async(e,t)=>{let a=B(e);a&&await P(async()=>{let n=k(a.wsId),i=await A(n);if(!i)return;let r=d(i.root).find(t=>t.sessionName===e);!r||t(r)&&(i.updatedAt=new Date().toISOString(),await D(i,n))})},K=async(e,t)=>P(async()=>{let a=k(e),n=await A(a);if(!n)return null;let i=t(n);return i?(i.updatedAt=new Date().toISOString(),await D(i,a),F(e,i.root),i):null}),G=async(e,t)=>K(e,e=>{if(void 0!==t.activePaneId){if(!c(e.root,t.activePaneId))return null;e.activePaneId=t.activePaneId}return t.ratioUpdate&&(e.root=b(e.root,t.ratioUpdate.path,t.ratioUpdate.ratio)),t.equalize&&(e.root=I(e.root)),e}),H=async(e,t,a)=>K(e,e=>{let n=c(e.root,t);if(!n)return null;if(void 0!==a.activeTabId){if(!n.tabs.some(e=>e.id===a.activeTabId))return null;n.activeTabId=a.activeTabId}return e}),Q=async(e,t,a,n,i)=>{let l="web-browser"===i,o=L(),s=N(),d=(0,r.workspaceSessionName)(e,o,s);l||await (0,r.createSession)(d,80,24,n);let u={id:s,sessionName:d,name:l?"Web Browser":"",order:0,...n?{cwd:n}:{}};i&&(u.panelType=i);let p={type:"pane",id:o,tabs:[u],activeTabId:s},y=await K(e,e=>{let i=c(e.root,t);if(!i)return null;let r=v(e.root);if(n){let e=i.tabs.find(e=>e.id===i.activeTabId);e&&(e.cwd=n)}let l={type:"split",orientation:a,ratio:50,children:[{...i},p]};return e.root=w(e.root,t,l),r&&(e.root=I(e.root)),e.activePaneId=o,e});return y||l||await (0,r.killSession)(d).catch(()=>{}),y},V=async(e,t)=>{let a=[],n=await P(async()=>{let n=k(e),i=await A(n);if(!i)return null;let r=c(i.root,t);if(!r||s(i.root).length<=1)return null;a=r.tabs.filter(e=>"web-browser"!==e.panelType).map(e=>e.sessionName);let l=v(i.root);return m(i,t),l&&(i.root=I(i.root)),i.updatedAt=new Date().toISOString(),await D(i,n),F(e,i.root),i});return await Promise.all(a.map(e=>(0,r.killSession)(e).catch(()=>{}))),n},X=async(e,t,a)=>K(e,e=>{let n=c(e.root,t);if(!n)return null;let i=new Map(n.tabs.map(e=>[e.id,e])),r=a.map((e,t)=>{let a=i.get(e);return a?{...a,order:t}:null}).filter(e=>null!==e);return r.length!==n.tabs.length?null:(n.tabs=r,e)}),Y=async(e,t,a,n,i)=>K(e,e=>{let r=c(e.root,a),l=c(e.root,n);if(!r||!l)return null;let o=r.tabs.findIndex(e=>e.id===t);if(-1===o)return null;let[d]=r.tabs.splice(o,1);return r.activeTabId===t&&(r.activeTabId=r.tabs[0]?.id??null),r.tabs.forEach((e,t)=>{e.order=t}),l.tabs.splice(i,0,d),l.tabs.forEach((e,t)=>{e.order=t}),l.activeTabId=t,0===r.tabs.length&&s(e.root).length>1&&m(e,a),e.activePaneId=n,e}),Z=async(t,a,n,i)=>{let r,l;if(void 0!==i.cwd||void 0!==i.title){let o=await (async()=>{let e=k(t),i=await A(e);return i?c(i.root,a)?.tabs.find(e=>e.id===n)?.sessionName??null:null})();if(o){let{getSessionCwd:t,getPaneCurrentCommand:a}=await e.A(322522),{formatTabTitle:n}=await e.A(245061);if(void 0!==i.cwd&&(r=await t(o)),void 0!==i.title){let[e,i]=await Promise.all([a(o),void 0!==r?Promise.resolve(r):t(o)]);e&&i&&(l=n(`${e}|${i}`))}}}return K(t,e=>{let t=c(e.root,a);if(!t)return null;let o=t.tabs.find(e=>e.id===n);if(!o)return null;let s=void 0!==i.title?l??i.title:void 0;return void 0!==i.name&&(o.name=i.name),void 0!==i.panelType&&(o.panelType=i.panelType),void 0!==s&&(o.title=s),void 0!==i.cwd&&(o.cwd=r??i.cwd),void 0!==i.lastCommand&&(o.lastCommand=i.lastCommand),void 0!==i.webUrl&&(o.webUrl=i.webUrl),void 0!==i.terminalRatio&&(o.terminalRatio=i.terminalRatio),void 0!==i.terminalCollapsed&&(o.terminalCollapsed=i.terminalCollapsed),e})};e.s(["addTabToPane",0,E,"closePaneInLayout",0,V,"createDefaultLayout",0,R,"createPane",0,x,"crossCheckLayout",0,M,"deletePane",0,j,"getLayout",0,U,"moveTabBetweenPanes",0,Y,"parseSessionName",0,B,"patchLayout",0,G,"patchPane",0,H,"patchTab",0,Z,"readLayoutFile",0,A,"reconcileTabCwd",0,z,"removeLayoutFile",0,$,"removeTabFromPane",0,W,"reorderTabsInPane",0,X,"resolveLayoutDir",0,_,"resolveLayoutFile",0,k,"restartTabSession",0,q,"setLayoutReconciler",0,e=>{g.__ptLayoutReconciler=e},"splitPaneInLayout",0,Q,"updateTabAgentSessionId",0,(e,t,a)=>J(e,e=>t.readSessionId(e)!==a&&(t.writeSessionId(e,a),!0)),"updateTabAgentSummary",0,(e,t,a)=>J(e,e=>t.readSummary(e)!==a&&(t.writeSummary(e,a),!0)),"updateTabClaudeSessionId",0,(e,t)=>J(e,e=>e.claudeSessionId!==t&&(e.claudeSessionId=t,!0)),"updateTabClaudeSummary",0,(e,t)=>J(e,e=>e.claudeSummary!==t&&(e.claudeSummary=t,!0)),"updateTabCliStatus",0,(e,t,a)=>J(e,e=>(e.cliState!==t||e.dismissedAt!==a)&&(e.cliState=t,e.dismissedAt=a,!0)),"updateTabLastUserMessage",0,(e,t)=>J(e,e=>e.lastUserMessage!==t&&(e.lastUserMessage=t,!0)),"writeLayoutFile",0,D],825265)}];
2
2
 
3
3
  //# sourceMappingURL=src_lib_layout-store_ts_0fanx7c._.js.map
@@ -1,15 +1,3 @@
1
- module.exports=[964759,796902,t=>{"use strict";t.i(478319);var e=t.i(220951),s=t.i(322429),a=t.i(825265),i=t.i(804767),n=t.i(459015),l=t.i(143511),r=t.i(746514),o=t.i(785128),c=t.i(840665),u=t.i(522734),d=t.i(924868),p=t.i(814747),h=t.i(25146),m=t.i(446786);let y=p.default.join(m.default.homedir(),".purplemux"),S=p.default.join(y,"statusline.sh"),f=p.default.join(y,"rate-limits.json"),g=`#!/bin/sh
2
- PORT_FILE="$HOME/.purplemux/port"
3
- TOKEN_FILE="$HOME/.purplemux/cli-token"
4
- [ -f "$PORT_FILE" ] || exit 0
5
- [ -f "$TOKEN_FILE" ] || exit 0
6
- PORT=$(cat "$PORT_FILE")
7
- TOKEN=$(cat "$TOKEN_FILE")
8
- curl -sf --max-time 2 -X POST \\
9
- -H 'Content-Type: application/json' \\
10
- -H "x-pmux-token: \${TOKEN}" \\
11
- --data-binary @- \\
12
- "http://localhost:\${PORT}/api/status/statusline" 2>/dev/null || exit 0
13
- `;t.s(["RATE_LIMITS_FILE",0,f,"STATUSLINE_SCRIPT_CONTENT",0,g,"STATUSLINE_SCRIPT_PATH",0,S],796902);let b=(0,h.createLogger)("rate-limits"),w=p.default.dirname(f),T=p.default.basename(f);var A=t.i(971780),v=t.i(443571);let P=(0,h.createLogger)("session-history"),k=p.default.join(m.default.homedir(),".purplemux"),M=p.default.join(k,"session-history.json"),I=globalThis;I.__purplemuxSessionHistoryLock||(I.__purplemuxSessionHistoryLock=Promise.resolve());let E=async t=>{let e,s=new Promise(t=>{e=t}),a=I.__purplemuxSessionHistoryLock;I.__purplemuxSessionHistoryLock=s,await a;try{return await t()}finally{e()}},j=()=>({version:1,entries:[]}),U=async()=>{let t;try{t=await d.default.readFile(M,"utf-8")}catch{return j()}try{return JSON.parse(t)}catch{P.warn("Failed to parse session-history.json, starting empty");try{await d.default.copyFile(M,M.replace(/\.json$/,".json.bak"))}catch{}return j()}},W=async t=>{let e=JSON.stringify(t.entries);if(I.__purplemuxSessionHistoryContentCache===e)return;let s=M+".tmp";try{await d.default.writeFile(s,JSON.stringify(t,null,2),{mode:384}),await d.default.rename(s,M)}catch(t){throw await d.default.unlink(s).catch(()=>{}),t}I.__purplemuxSessionHistoryContentCache=e},L=async t=>{await E(async()=>{let e=await U();e.entries.unshift(t),e.entries.length>200&&(e.entries=e.entries.slice(0,200)),await W(e)})},_=async(t,e)=>await E(async()=>{let s=await U(),a=s.entries.find(e=>e.tabId===t&&null===e.dismissedAt);return a?(a.dismissedAt=e,await W(s),a):null});var N=t.i(157469),R=t.i(75874),x=t.i(228448),C=t.i(44014);let F=(0,h.createLogger)("status"),J=(0,h.createLogger)("hooks"),O=t=>t?p.default.basename(t,".jsonl"):null,$=new Set(["permission_prompt","worker_permission_prompt"]),D=new Map,H=t=>{let e=t.name??"Tool",s=t.input??{};return{toolName:e,summary:(0,c.summarizeToolCall)(e,s)}},z=t=>{let e=!1;for(let s=t.length-1;s>=0;s--)try{let a=JSON.parse(t[s]);if(a.isSidechain)continue;if("user"===a.type){let t=a.message?.content;Array.isArray(t)&&t.some(t=>"tool_result"===t.type)||(e=!0);continue}if("assistant"!==a.type||!a.message?.content)continue;if(e)return{lastAssistantSnippet:null,currentAction:null,reset:!0};let i=a.message.content;if(!Array.isArray(i))continue;let n=null,l=null;for(let t=i.length-1;t>=0;t--){let e=i[t];if("tool_use"===e.type){l=H(e);break}if("text"===e.type&&e.text?.trim()){let t=e.text.trim();l={toolName:null,summary:t.length>200?t.slice(0,200)+"…":t};break}}for(let t=i.length-1;t>=0;t--)if("text"===i[t].type&&i[t].text?.trim()){let e=i[t].text.trim();n=e.length>200?e.slice(0,200)+"…":e;break}return{lastAssistantSnippet:n,currentAction:l,reset:!1}}catch{continue}return{lastAssistantSnippet:null,currentAction:null,reset:!1}},q=(t,e)=>{for(let s=t.length-1;s>=0;s--)try{let a=JSON.parse(t[s]);if(a.isSidechain)continue;let i=a.timestamp?new Date(a.timestamp).getTime():null;if("system"===a.type&&("stop_hook_summary"===a.subtype||"turn_duration"===a.subtype))return{matched:!0,idle:!0,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!1};if("assistant"===a.type){let t=a.message?.stop_reason;if(!t){let t=e>2e4;return{matched:!0,idle:t,stale:!0,needsStaleRecheck:!t,staleMs:2e4,lastEntryTs:i,interrupted:!1}}return{matched:!0,idle:"tool_use"!==t,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!1}}if("user"===a.type){let t=a.message?.content;if(Array.isArray(t)&&1===t.length&&"string"==typeof t[0]?.text&&t[0].text.startsWith(c.INTERRUPT_PREFIX))return{matched:!0,idle:!0,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!0};let s=e>9e4;return{matched:!0,idle:s,stale:!0,needsStaleRecheck:!s,staleMs:9e4,lastEntryTs:i,interrupted:!1}}}catch{continue}return{matched:!1,idle:e>9e4,stale:!0,needsStaleRecheck:e<=9e4,staleMs:9e4,lastEntryTs:null,interrupted:!1}},K=async t=>{try{let e=await d.default.stat(t);if(0===e.size)return{idle:!0,stale:!1,lastAssistantSnippet:null,currentAction:null,reset:!1,lastEntryTs:null,staleMs:0,interrupted:!1};let s=D.get(t);if(s&&s.mtimeMs===e.mtimeMs){if(D.delete(t),D.set(t,s),s.idle)return{idle:!0,stale:s.stale,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted};if(s.needsStaleRecheck)return{idle:Date.now()-e.mtimeMs>s.staleMs,stale:!0,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted};return{idle:!1,stale:!1,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted}}let a=await d.default.open(t,"r");try{let s=Date.now()-e.mtimeMs,i=Math.min(e.size,8192),n=Buffer.alloc(i);await a.read(n,0,i,e.size-i);let l=n.toString("utf-8").split("\n").filter(t=>t.trim()),r=q(l,s),o=z(l);if(!r.matched&&e.size>8192){let t=Math.min(e.size,131072),i=Buffer.alloc(t);await a.read(i,0,t,e.size-t);let n=i.toString("utf-8").split("\n").filter(t=>t.trim());r=q(n,s),o.lastAssistantSnippet||o.currentAction||(o=z(n))}return D.size>=256&&D.delete(D.keys().next().value),D.set(t,{mtimeMs:e.mtimeMs,idle:r.idle,stale:r.stale,needsStaleRecheck:r.needsStaleRecheck,staleMs:r.staleMs,lastAssistantSnippet:o.lastAssistantSnippet,currentAction:o.currentAction,reset:o.reset,lastEntryTs:r.lastEntryTs,interrupted:r.interrupted}),{idle:r.idle,stale:r.stale,lastAssistantSnippet:o.lastAssistantSnippet,currentAction:o.currentAction,reset:o.reset,lastEntryTs:r.lastEntryTs,staleMs:r.staleMs,interrupted:r.interrupted}}finally{await a.close()}}catch{return{idle:!1,stale:!1,lastAssistantSnippet:null,currentAction:null,reset:!1,lastEntryTs:null,staleMs:0,interrupted:!1}}},B=async t=>{let e={toolUsage:{},touchedFiles:[],lastAssistantText:null,lastUserText:null,firstUserTs:null,lastAssistantTs:null,turnDurationMs:null};try{let s=await d.default.stat(t);if(0===s.size)return e;let a=await d.default.open(t,"r");try{let t=Math.min(s.size,131072),e=Buffer.alloc(t);await a.read(e,0,t,s.size-t);let i=e.toString("utf-8").split("\n").filter(t=>t.trim()),n={},l=new Set,r=null,o=null,c=null,u=null,d=null;for(let t=i.length-1;t>=0;t--)try{let e=JSON.parse(i[t]);if("file-history-snapshot"===e.type)break;if(e.isSidechain)continue;"system"!==e.type||"turn_duration"!==e.subtype||"number"!=typeof e.durationMs||d||(d=e.durationMs);let s=e.timestamp?new Date(e.timestamp).getTime():null;if("user"===e.type&&(s&&(u=s),!o&&Array.isArray(e.message?.content))){for(let t of e.message.content)if("text"===t.type&&t.text){o=t.text;break}}if("assistant"===e.type&&(s&&!c&&(c=s),Array.isArray(e.message?.content))){let t=null;for(let s of e.message.content)"tool_use"===s.type&&s.name&&(n[s.name]=(n[s.name]??0)+1,("Edit"===s.name||"Write"===s.name)&&s.input?.file_path&&l.add(String(s.input.file_path))),"text"===s.type&&s.text&&(t=s.text);!r&&t&&(r=t)}}catch{continue}return{toolUsage:n,touchedFiles:[...l],lastAssistantText:r,lastUserText:o,firstUserTs:u,lastAssistantTs:c,turnDurationMs:d}}finally{await a.close()}}catch{return e}},V=/^[✳⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⠐⠈]\s+/,X=t=>t&&V.test(t)&&t.replace(V,"").trim()||null,G=globalThis;class Q{tabs=new Map;pollingTimer=null;currentInterval=0;clients=new Set;initialized=!1;rateLimitsWatcher=null;lastRateLimits=null;jsonlWatchers=new Map;compactStaleTimers=new Map;async init(){if(!this.initialized){var t;let e,s,a,i,n,l;this.initialized=!0,await this.scanAll(),this.startPolling(),this.rateLimitsWatcher=(t=t=>{this.lastRateLimits=t,this.broadcast({type:"rate-limits:update",data:t})},e=null,s=null,a=0,i=async()=>{try{let e=await d.default.readFile(f,"utf-8"),s=JSON.parse(e);s.ts&&s.ts!==a&&(a=s.ts,t(s))}catch{}},n=()=>{i();try{(e=u.default.watch(w,(t,e)=>{e===T&&(s&&clearTimeout(s),s=setTimeout(i,500))})).on("error",()=>{b.debug(`${w} watch error, retrying...`),l(),setTimeout(n,5e3)})}catch{b.debug(`${w} not available yet, retrying...`),setTimeout(n,5e3)}},{start:n,stop:l=()=>{s&&(clearTimeout(s),s=null),e&&(e.close(),e=null)}}),this.rateLimitsWatcher.start()}}async scanAll(){let{workspaces:t}=await (0,s.getWorkspaces)(),e=await (0,n.getAllPanesInfo)();for(let t of[...this.jsonlWatchers.keys()])this.stopJsonlWatch(t);for(let s of(this.tabs.clear(),t)){let t=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(s.id));if(t)for(let a of(0,i.collectAllTabs)(t.root)){let t=e.get(a.sessionName),i=await this.readTabMetadata(t),n=a.cliState??"idle",l="busy"===n?"unknown":n,{terminalStatus:r,listeningPorts:c}="claude-code"===a.panelType?{terminalStatus:"idle",listeningPorts:[]}:await this.detectTerminalStatus(t),u=t?.command,d=t?`${t.command}|${t.path}`:void 0,p="needs-input"===l?{name:"notification",at:Date.now(),seq:0}:null;this.tabs.set(a.id,{cliState:l,workspaceId:s.id,tabName:a.name||(d?(0,o.formatTabTitle)(d):""),currentProcess:u,paneTitle:d,tmuxSession:a.sessionName,panelType:a.panelType,terminalStatus:r,listeningPorts:c,claudeSummary:a.claudeSummary,lastUserMessage:a.lastUserMessage,lastAssistantMessage:i.lastAssistantSnippet,currentAction:i.currentAction,readyForReviewAt:"ready-for-review"===l?Date.now():null,busySince:null,dismissedAt:a.dismissedAt??null,claudeSessionId:O(i.jsonlPath)??a.claudeSessionId??null,jsonlPath:i.jsonlPath,lastEvent:p,eventSeq:0}),("needs-input"===l||"unknown"===l)&&i.jsonlPath&&this.startJsonlWatch(a.id,i.jsonlPath),"unknown"===l&&this.resolveUnknown(a.id).catch(t=>F.warn("resolveUnknown failed: %s",t))}}}async resolveUnknown(t){let e=this.tabs.get(t);if(!e||"unknown"!==e.cliState)return;let s=(await (0,n.getAllPanesInfo)()).get(e.tmuxSession),a=s?.pid?await (0,l.getChildPids)(s.pid):[];if(!(s?.pid&&await (0,l.isClaudeRunning)(s.pid,a))){this.applyCliState(t,e,"idle",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e);return}if(e.jsonlPath){let{idle:s,stale:a,lastAssistantSnippet:i}=await K(e.jsonlPath);if(s&&!a&&i){this.applyCliState(t,e,"ready-for-review",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e);return}}}async readTabMetadata(t){let e={lastAssistantSnippet:null,currentAction:null,jsonlPath:null};if(!t||!t.pid)return e;let s=await (0,l.getChildPids)(t.pid);if(!await (0,l.isClaudeRunning)(t.pid,s))return e;let a=await (0,l.detectActiveSession)(t.pid,s);if("running"!==a.status||!a.jsonlPath)return{lastAssistantSnippet:null,currentAction:null,jsonlPath:a.jsonlPath??null};let{lastAssistantSnippet:i,currentAction:n}=await K(a.jsonlPath);return{lastAssistantSnippet:i,currentAction:n,jsonlPath:a.jsonlPath}}async detectTerminalStatus(t){if(!t||!t.pid)return{terminalStatus:"idle",listeningPorts:[]};let e=await (0,n.getListeningPorts)(t.pid);return e.length>0?{terminalStatus:"server",listeningPorts:e}:{terminalStatus:n.SAFE_SHELLS.has(t.command)?"idle":"running",listeningPorts:[]}}getPollingInterval(){let t=this.tabs.size;return t>=21?6e4:t>=11?45e3:3e4}async rescan(){await this.scanAll()}startPolling(){this.stopPolling(),this.currentInterval=this.getPollingInterval(),this.pollingTimer=setInterval(()=>{this.poll().catch(t=>{F.error({err:t},"Polling error")})},this.currentInterval)}stopPolling(){this.pollingTimer&&(clearInterval(this.pollingTimer),this.pollingTimer=null,this.currentInterval=0)}async poll(){let{workspaces:t}=await (0,s.getWorkspaces)(),e=await (0,n.getAllPanesInfo)(),r=new Set,c=new Set(this.tabs.keys()),u=Date.now();for(let s of t){let t=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(s.id));if(t)for(let c of(0,i.collectAllTabs)(t.root)){r.add(c.id);let t=this.tabs.get(c.id),i=e.get(c.sessionName),{terminalStatus:d,listeningPorts:p}="claude-code"===c.panelType?{terminalStatus:"idle",listeningPorts:[]}:await this.detectTerminalStatus(i),h=i?.command,m=i?`${i.command}|${i.path}`:void 0;if(!t){let t=c.cliState??"idle",e="busy"===t?"unknown":t,a=await this.readTabMetadata(i),n="needs-input"===e?{name:"notification",at:Date.now(),seq:0}:null,l={cliState:e,workspaceId:s.id,tabName:c.name||(m?(0,o.formatTabTitle)(m):""),currentProcess:h,paneTitle:m,tmuxSession:c.sessionName,panelType:c.panelType,terminalStatus:d,listeningPorts:p,claudeSummary:c.claudeSummary,lastUserMessage:c.lastUserMessage,lastAssistantMessage:a.lastAssistantSnippet,currentAction:a.currentAction,claudeSessionId:O(a.jsonlPath)??c.claudeSessionId??null,jsonlPath:a.jsonlPath,lastEvent:n,eventSeq:0};this.tabs.set(c.id,l),this.persistToLayout(l),this.broadcastUpdate(c.id,l),"unknown"===e&&this.resolveUnknown(c.id).catch(t=>F.warn("resolveUnknown failed: %s",t));continue}let y=t.currentProcess!==h,S=t.lastUserMessage!==c.lastUserMessage,f=t.panelType!==c.panelType,g=await this.readTabMetadata(i);t.tabName=c.name||(m?(0,o.formatTabTitle)(m):""),t.currentProcess=h,t.paneTitle=m,t.workspaceId=s.id,t.panelType=c.panelType,t.claudeSessionId=O(g.jsonlPath)??c.claudeSessionId??null,t.jsonlPath=g.jsonlPath??t.jsonlPath,t.lastUserMessage=c.lastUserMessage,y&&(t.processRetries=3);let b=!y&&(t.processRetries??0)>0;b&&(t.processRetries=t.processRetries-1);let w=t.listeningPorts,T=w?.length!==p.length||p.some((t,e)=>w[e]!==t),A=t.terminalStatus!==d||T;A&&(t.terminalStatus=d,t.listeningPorts=p);let v=!1;if("busy"===t.cliState||"needs-input"===t.cliState){let e=X(await (0,n.getPaneTitle)(c.sessionName));e&&e!==t.claudeSummary&&(t.claudeSummary=e,v=!0,(0,a.updateTabClaudeSummary)(c.sessionName,e).catch(()=>{}))}else t.claudeSummary!==c.claudeSummary&&(t.claudeSummary=c.claudeSummary,v=!0);if("busy"===t.cliState&&t.lastEvent&&u-t.lastEvent.at>6e5){let e=i?.pid?await (0,l.getChildPids)(i.pid):[];if(!(i?.pid&&await (0,l.isClaudeRunning)(i.pid,e))){F.info({tabId:c.id},"busy stuck — Claude process gone, forcing idle"),this.applyCliState(c.id,t,"idle",{silent:!0}),this.persistToLayout(t),this.broadcastUpdate(c.id,t);continue}}(A||y||b||S||f||v)&&this.broadcastUpdate(c.id,t)}}for(let t of c)!r.has(t)&&this.tabs.has(t)&&(this.stopJsonlWatch(t),this.tabs.delete(t),this.broadcastRemove(t));let d=this.getPollingInterval();this.pollingTimer&&d!==this.currentInterval&&this.startPolling()}getAllForClient(){let t={};for(let[e,s]of this.tabs)t[e]={cliState:s.cliState,workspaceId:s.workspaceId,tabName:s.tabName,currentProcess:s.currentProcess,paneTitle:s.paneTitle,panelType:s.panelType,terminalStatus:s.terminalStatus,listeningPorts:s.listeningPorts,claudeSummary:s.claudeSummary,lastUserMessage:s.lastUserMessage,lastAssistantMessage:s.lastAssistantMessage,currentAction:s.currentAction,readyForReviewAt:s.readyForReviewAt,busySince:s.busySince,dismissedAt:s.dismissedAt,claudeSessionId:s.claudeSessionId,lastEvent:s.lastEvent,eventSeq:s.eventSeq};return t}applyCliState(t,e,s,a={}){if(e.cliState===s)return;let i=e.busySince;e.cliState=s,e.readyForReviewAt="ready-for-review"===s?Date.now():null,e.busySince="busy"===s?Date.now():null,"busy"===s&&(e.dismissedAt=null),"ready-for-review"===s&&e.jsonlPath&&new Promise(t=>setTimeout(t,500)).then(()=>this.saveSessionHistory(t,e,i,!1)).catch(t=>{F.warn("Failed to save session history: %s",t)}),"ready-for-review"!==s||a.silent||this.sendWebPush(t,e,"review").catch(t=>{F.warn("Web push failed: %s",t)}),"needs-input"!==s||a.silent||this.sendWebPush(t,e,"needs-input").catch(t=>{F.warn("Web push failed: %s",t)});let n=("busy"===s||"needs-input"===s)&&e.jsonlPath,l="ready-for-review"===s&&this.jsonlWatchers.has(t);n&&!this.jsonlWatchers.has(t)?this.startJsonlWatch(t,e.jsonlPath):!n&&!l&&this.jsonlWatchers.has(t)&&this.stopJsonlWatch(t)}async saveSessionHistory(t,e,a,i){if(!e.lastUserMessage)return;let n=e.jsonlPath?await B(e.jsonlPath):null,{workspaces:l}=await (0,s.getWorkspaces)(),r=l.find(t=>t.id===e.workspaceId),o=Date.now(),c=n?.firstUserTs??a??o,u=i?o:n?.lastAssistantTs??o,d=i?u-c:n?.turnDurationMs??u-c,p={id:(0,C.nanoid)(),workspaceId:e.workspaceId,workspaceName:r?.name??e.workspaceId,workspaceDir:r?.directories[0]??null,tabId:t,claudeSessionId:e.claudeSessionId??null,prompt:n?.lastUserText??e.lastUserMessage,result:n?.lastAssistantText??null,startedAt:c,completedAt:u,duration:d,dismissedAt:u,toolUsage:n?.toolUsage??{},touchedFiles:n?.touchedFiles??[],...i?{cancelled:!0}:{}};await L(p),this.broadcast({type:"session-history:update",entry:p})}dismissTab(t,e){let s=this.tabs.get(t);if(!s||"ready-for-review"!==s.cliState)return;let a=Date.now();this.applyCliState(t,s,"idle",{silent:!0}),s.dismissedAt=a,this.persistToLayout(s),this.broadcastUpdate(t,s,e),_(t,a).then(t=>{t&&this.broadcast({type:"session-history:update",entry:t})}).catch(t=>{F.warn("Failed to update session history dismissedAt: %s",t)})}ackNotificationInput(t,e){let s=this.tabs.get(t);s&&"needs-input"===s.cliState&&s.lastEvent?.name==="notification"&&s.lastEvent.seq===e&&(J.debug({tabId:t,seq:e},"ack: needs-input→busy"),this.applyCliState(t,s,"busy"),this.persistToLayout(s),this.broadcastUpdate(t,s))}async recoverUnknownIfPending(t){let e=this.tabs.get(t);if(!e)return{recovered:!1,reason:"no-entry"};if("unknown"!==e.cliState)return{recovered:!1,reason:"not-unknown"};let s=await (0,A.capturePaneAtWidth)(e.tmuxSession,120,50).catch(t=>(F.warn("recoverUnknownIfPending capture failed: %s",t),null));if(!s)return{recovered:!1,reason:"capture-failed"};let{options:a}=(0,v.parsePermissionOptions)(s);if(0===a.length)return{recovered:!1,reason:"no-options"};let i=Date.now(),n=(e.eventSeq??0)+1;return e.eventSeq=n,e.lastEvent={name:"notification",at:i,seq:n},J.debug({tabId:t,seq:n,options:a.length},"recover unknown→needs-input from pane capture"),this.applyCliState(t,e,"needs-input",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e),{recovered:!0}}findTabIdBySession(t){for(let[e,s]of this.tabs)if(s.tmuxSession===t)return e}updateTabFromHook(t,e,s){let a=this.findTabIdBySession(t);if(!a)return void J.debug({tmuxSession:t,event:e,notificationType:s},"no tabId for session");let i=this.tabs.get(a);if(!i)return void J.debug({tabId:a,event:e,notificationType:s},"no entry for tab");if("pre-compact"===e||"post-compact"===e){J.debug({tabId:a,event:e},"compact hook"),this.setCompacting(a,i,"pre-compact"===e?Date.now():null);return}if("session-start"!==e&&"prompt-submit"!==e&&"notification"!==e&&"stop"!==e&&"interrupt"!==e)return void J.debug({tabId:a,event:e,notificationType:s},"unknown event, ignoring");if("notification"===e&&s&&!$.has(s))return void J.debug({tabId:a,event:e,notificationType:s},"non-input notification, skipping state transition");let n=Date.now(),l=(i.eventSeq??0)+1;i.eventSeq=l,i.lastEvent={name:e,at:n,seq:l},this.broadcast({type:"status:hook-event",tabId:a,event:i.lastEvent});let r=i.cliState,o="cancelled"===r?r:((t,e)=>{if(!t)return e;switch(t.name){case"session-start":case"interrupt":return"idle";case"prompt-submit":return"busy";case"notification":return"needs-input";case"stop":return"ready-for-review"}})(i.lastEvent,r);if(J.debug({tabId:a,event:e,notificationType:s,seq:l,prevState:r,newState:o,transition:r!==o},`processed ${e}${s?`(${s})`:""} ${r}→${o}`),r!==o&&(this.applyCliState(a,i,o),this.persistToLayout(i),this.broadcastUpdate(a,i)),"busy"!==o&&"needs-input"!==o||i.jsonlPath||this.resolveAndWatchJsonl(a,t).catch(()=>{}),"stop"===e&&i.jsonlPath){let t=()=>{K(i.jsonlPath).then(({currentAction:t,lastAssistantSnippet:e,reset:s})=>{let n=!1;s?(null!==i.currentAction&&(i.currentAction=null,n=!0),null!==i.lastAssistantMessage&&(i.lastAssistantMessage=null,n=!0)):(null!==t&&t.summary!==i.currentAction?.summary&&(i.currentAction=t,n=!0),null!==e&&i.lastAssistantMessage!==e&&(i.lastAssistantMessage=e,n=!0)),n&&this.broadcastUpdate(a,i)}).catch(()=>{})};t(),setTimeout(()=>{D.delete(i.jsonlPath),t()},500)}}setCompacting(t,e,s){let a=this.compactStaleTimers.get(t);if(a&&(clearTimeout(a),this.compactStaleTimers.delete(t)),(e.compactingSince??null)!==s&&(e.compactingSince=s,this.broadcastUpdate(t,e),null!==s)){let e=setTimeout(()=>{this.compactStaleTimers.delete(t);let e=this.tabs.get(t);e&&e.compactingSince===s&&(e.compactingSince=null,J.debug({tabId:t},"compact stale, auto-cleared"),this.broadcastUpdate(t,e))},6e4);this.compactStaleTimers.set(t,e)}}removeTab(t){let e=this.tabs.get(t);e&&("busy"===e.cliState||"needs-input"===e.cliState)&&e.lastUserMessage&&this.saveSessionHistory(t,e,e.busySince,!0).catch(t=>{F.warn("Failed to save cancelled session history: %s",t)}),this.stopJsonlWatch(t);let s=this.compactStaleTimers.get(t);s&&(clearTimeout(s),this.compactStaleTimers.delete(t)),this.tabs.delete(t),this.broadcastRemove(t)}reconcileWorkspaceTabs(t,e){let s=new Set(e);for(let[e,a]of this.tabs)a.workspaceId!==t||s.has(e)||this.removeTab(e)}removeWorkspaceTabs(t){for(let[e,s]of this.tabs)s.workspaceId===t&&this.removeTab(e)}registerTab(t,e){this.tabs.set(t,e),this.broadcastUpdate(t,e)}addClient(t){this.clients.add(t),this.lastRateLimits&&t.readyState===e.WebSocket.OPEN&&t.send(JSON.stringify({type:"rate-limits:update",data:this.lastRateLimits}))}removeClient(t){this.clients.delete(t)}persistToLayout(t){(0,a.updateTabCliStatus)(t.tmuxSession,t.cliState,t.dismissedAt).catch(()=>{})}broadcastUpdate(t,e,s){let a={type:"status:update",tabId:t,cliState:e.cliState,workspaceId:e.workspaceId,tabName:e.tabName,currentProcess:e.currentProcess,paneTitle:e.paneTitle,panelType:e.panelType,terminalStatus:e.terminalStatus,listeningPorts:e.listeningPorts,claudeSummary:e.claudeSummary,lastUserMessage:e.lastUserMessage,lastAssistantMessage:e.lastAssistantMessage,currentAction:e.currentAction,readyForReviewAt:e.readyForReviewAt,busySince:e.busySince,dismissedAt:e.dismissedAt,claudeSessionId:e.claudeSessionId,compactingSince:e.compactingSince,lastEvent:e.lastEvent,eventSeq:e.eventSeq};this.broadcast(a,s)}broadcastRemove(t){this.broadcast({type:"status:update",tabId:t,cliState:null,workspaceId:"",tabName:""})}static BACKPRESSURE_LIMIT=1048576;broadcast(t,s){let a=JSON.stringify(t);for(let t of this.clients)t!==s&&t.readyState===e.WebSocket.OPEN&&t.bufferedAmount<Q.BACKPRESSURE_LIMIT&&t.send(a)}async resolveAndWatchJsonl(t,e){let s=this.tabs.get(t);if(!s||s.jsonlPath)return;let o=null,c=(0,a.parseSessionName)(e);if(c){let l=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(c.wsId));if(l){let a=(0,i.collectAllTabs)(l.root).find(t=>t.sessionName===e);if(a?.claudeSessionId){let t=await (0,n.getSessionCwd)(e);if(t){let e=`${(0,r.cwdToProjectPath)(t)}/${a.claudeSessionId}.jsonl`;try{await d.default.access(e),o=e}catch{}}}a?.lastUserMessage&&s.lastUserMessage!==a.lastUserMessage&&(s.lastUserMessage=a.lastUserMessage,this.broadcastUpdate(t,s))}}if(!o){let t=await (0,n.getSessionPanePid)(e);t&&(o=(await (0,l.detectActiveSession)(t)).jsonlPath)}o&&(s.jsonlPath=o,s.claudeSessionId=O(o)??s.claudeSessionId,"busy"!==s.cliState&&"needs-input"!==s.cliState||this.jsonlWatchers.has(t)||this.startJsonlWatch(t,o))}startJsonlWatch(t,e){let s=this.jsonlWatchers.get(t);if(s?.jsonlPath!==e){s&&this.stopJsonlWatch(t),F.debug("startJsonlWatch tabId=%s path=%s",t,e);try{let s=(0,u.watch)(e,()=>{let s=this.jsonlWatchers.get(t);s&&(s.debounceTimer&&clearTimeout(s.debounceTimer),s.debounceTimer=setTimeout(()=>{this.onJsonlFileChange(t,e).catch(()=>{})},100))});s.on("error",()=>{this.stopJsonlWatch(t)}),this.jsonlWatchers.set(t,{watcher:s,jsonlPath:e,debounceTimer:null})}catch{}}}stopJsonlWatch(t){let e=this.jsonlWatchers.get(t);if(e){F.debug("stopJsonlWatch tabId=%s",t),e.debounceTimer&&clearTimeout(e.debounceTimer);try{e.watcher.close()}catch{}this.jsonlWatchers.delete(t)}}async onJsonlFileChange(t,e){let s=this.tabs.get(t);if(!s||"busy"!==s.cliState&&"needs-input"!==s.cliState&&"unknown"!==s.cliState&&"ready-for-review"!==s.cliState)return void this.stopJsonlWatch(t);let{currentAction:a,lastAssistantSnippet:i,reset:n,interrupted:l,lastEntryTs:r}=await K(e);l&&"busy"===s.cliState&&null!==r&&r>(s.lastInterruptTs??0)&&r>(s.lastEvent?.at??0)&&(s.lastInterruptTs=r,J.debug({tabId:t,lastEntryTs:r},"synthetic interrupt from JSONL"),this.updateTabFromHook(s.tmuxSession,"interrupt"));let o=!1;n?(null!==s.currentAction&&(s.currentAction=null,o=!0),null!==s.lastAssistantMessage&&(s.lastAssistantMessage=null,o=!0)):(null!==a&&a.summary!==s.currentAction?.summary&&(s.currentAction=a,o=!0),null!==i&&s.lastAssistantMessage!==i&&(s.lastAssistantMessage=i,o=!0)),o&&this.broadcastUpdate(t,s)}shutdown(){for(let t of(this.stopPolling(),this.rateLimitsWatcher?.stop(),[...this.jsonlWatchers.keys()]))this.stopJsonlWatch(t);for(let t of this.clients)t.readyState===e.WebSocket.OPEN&&t.close(1001,"Server shutting down");this.clients.clear()}notifyLastUserMessage(t,e){let s=(0,a.parseSessionName)(t);if(!s)return;let i=this.tabs.get(s.tabId);i&&i.lastUserMessage!==e&&(i.lastUserMessage=e,this.broadcastUpdate(s.tabId,i))}async sendWebPush(t,e,a){let i=await (0,R.getSubscriptions)();if(0===i.length)return;let n=await (0,x.getVAPIDKeys)();N.default.setVapidDetails("mailto:noreply@purplemux.app",n.publicKey,n.privateKey);let l=e.lastUserMessage?.slice(0,100)||e.tabName||t,r=(await (0,s.getWorkspaces)()).workspaces.find(t=>t.id===e.workspaceId),o=JSON.stringify({title:"needs-input"===a?"Input Required":"Task Complete",body:l,tabId:t,workspaceId:e.workspaceId,claudeSessionId:e.claudeSessionId??null,workspaceName:r?.name??"",workspaceDir:r?.directories[0]??null});if(!(0,R.isAnyDeviceVisible)())for(let t of i)try{await N.default.sendNotification(t,o)}catch(s){let e=s.statusCode;(410===e||404===e)&&await (0,R.removeSubscription)(t.endpoint),F.warn("Web push send error: %s",e)}}}t.s(["getStatusManager",0,()=>{if(!G.__ptStatusManager){let t=new Q;G.__ptStatusManager=t,(0,a.setLayoutReconciler)({reconcileWorkspaceTabs:(e,s)=>t.reconcileWorkspaceTabs(e,s),removeWorkspaceTabs:e=>t.removeWorkspaceTabs(e)})}return G.__ptStatusManager}],964759)}];
1
+ module.exports=[964759,t=>{"use strict";t.i(478319);var e=t.i(220951),s=t.i(322429),a=t.i(825265),i=t.i(804767),n=t.i(459015),l=t.i(143511),r=t.i(462180),o=t.i(282992),c=t.i(746514),u=t.i(785128),d=t.i(840665),p=t.i(522734),h=t.i(924868),m=t.i(814747),y=t.i(25146),S=t.i(796902);let g=(0,y.createLogger)("rate-limits"),f=m.default.dirname(S.RATE_LIMITS_FILE),b=m.default.basename(S.RATE_LIMITS_FILE);var w=t.i(971780),T=t.i(443571),A=t.i(446786);let v=(0,y.createLogger)("session-history"),P=m.default.join(A.default.homedir(),".purplemux"),k=m.default.join(P,"session-history.json"),M=globalThis;M.__purplemuxSessionHistoryLock||(M.__purplemuxSessionHistoryLock=Promise.resolve());let I=async t=>{let e,s=new Promise(t=>{e=t}),a=M.__purplemuxSessionHistoryLock;M.__purplemuxSessionHistoryLock=s,await a;try{return await t()}finally{e()}},U=()=>({version:1,entries:[]}),j=async()=>{let t;try{t=await h.default.readFile(k,"utf-8")}catch{return U()}try{return JSON.parse(t)}catch{v.warn("Failed to parse session-history.json, starting empty");try{await h.default.copyFile(k,k.replace(/\.json$/,".json.bak"))}catch{}return U()}},W=async t=>{let e=JSON.stringify(t.entries);if(M.__purplemuxSessionHistoryContentCache===e)return;let s=k+".tmp";try{await h.default.writeFile(s,JSON.stringify(t,null,2),{mode:384}),await h.default.rename(s,k)}catch(t){throw await h.default.unlink(s).catch(()=>{}),t}M.__purplemuxSessionHistoryContentCache=e},E=async t=>{await I(async()=>{let e=await j();e.entries.unshift(t),e.entries.length>200&&(e.entries=e.entries.slice(0,200)),await W(e)})},L=async(t,e)=>await I(async()=>{let s=await j(),a=s.entries.find(e=>e.tabId===t&&null===e.dismissedAt);return a?(a.dismissedAt=e,await W(s),a):null});var _=t.i(157469),R=t.i(75874),N=t.i(228448),x=t.i(44014);let F=(0,y.createLogger)("status"),C=(0,y.createLogger)("hooks"),J=t=>t?m.default.basename(t,".jsonl"):null,D=new Set(["permission_prompt","worker_permission_prompt"]),z=new Map,O=t=>{let e=t.name??"Tool",s=t.input??{};return{toolName:e,summary:(0,d.summarizeToolCall)(e,s)}},q=t=>{let e=!1;for(let s=t.length-1;s>=0;s--)try{let a=JSON.parse(t[s]);if(a.isSidechain)continue;if("user"===a.type){let t=a.message?.content;Array.isArray(t)&&t.some(t=>"tool_result"===t.type)||(e=!0);continue}if("assistant"!==a.type||!a.message?.content)continue;if(e)return{lastAssistantSnippet:null,currentAction:null,reset:!0};let i=a.message.content;if(!Array.isArray(i))continue;let n=null,l=null;for(let t=i.length-1;t>=0;t--){let e=i[t];if("tool_use"===e.type){l=O(e);break}if("text"===e.type&&e.text?.trim()){let t=e.text.trim();l={toolName:null,summary:t.length>200?t.slice(0,200)+"…":t};break}}for(let t=i.length-1;t>=0;t--)if("text"===i[t].type&&i[t].text?.trim()){let e=i[t].text.trim();n=e.length>200?e.slice(0,200)+"…":e;break}return{lastAssistantSnippet:n,currentAction:l,reset:!1}}catch{continue}return{lastAssistantSnippet:null,currentAction:null,reset:!1}},$=(t,e)=>{for(let s=t.length-1;s>=0;s--)try{let a=JSON.parse(t[s]);if(a.isSidechain)continue;let i=a.timestamp?new Date(a.timestamp).getTime():null;if("system"===a.type&&("stop_hook_summary"===a.subtype||"turn_duration"===a.subtype))return{matched:!0,idle:!0,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!1};if("assistant"===a.type){let t=a.message?.stop_reason;if(!t){let t=e>2e4;return{matched:!0,idle:t,stale:!0,needsStaleRecheck:!t,staleMs:2e4,lastEntryTs:i,interrupted:!1}}return{matched:!0,idle:"tool_use"!==t,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!1}}if("user"===a.type){let t=a.message?.content;if(Array.isArray(t)&&1===t.length&&"string"==typeof t[0]?.text&&t[0].text.startsWith(d.INTERRUPT_PREFIX))return{matched:!0,idle:!0,stale:!1,needsStaleRecheck:!1,staleMs:0,lastEntryTs:i,interrupted:!0};let s=e>9e4;return{matched:!0,idle:s,stale:!0,needsStaleRecheck:!s,staleMs:9e4,lastEntryTs:i,interrupted:!1}}}catch{continue}return{matched:!1,idle:e>9e4,stale:!0,needsStaleRecheck:e<=9e4,staleMs:9e4,lastEntryTs:null,interrupted:!1}},H=async t=>{try{let e=await h.default.stat(t);if(0===e.size)return{idle:!0,stale:!1,lastAssistantSnippet:null,currentAction:null,reset:!1,lastEntryTs:null,staleMs:0,interrupted:!1};let s=z.get(t);if(s&&s.mtimeMs===e.mtimeMs){if(z.delete(t),z.set(t,s),s.idle)return{idle:!0,stale:s.stale,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted};if(s.needsStaleRecheck)return{idle:Date.now()-e.mtimeMs>s.staleMs,stale:!0,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted};return{idle:!1,stale:!1,lastAssistantSnippet:s.lastAssistantSnippet,currentAction:s.currentAction,reset:s.reset,lastEntryTs:s.lastEntryTs,staleMs:s.staleMs,interrupted:s.interrupted}}let a=await h.default.open(t,"r");try{let s=Date.now()-e.mtimeMs,i=Math.min(e.size,8192),n=Buffer.alloc(i);await a.read(n,0,i,e.size-i);let l=n.toString("utf-8").split("\n").filter(t=>t.trim()),r=$(l,s),o=q(l);if(!r.matched&&e.size>8192){let t=Math.min(e.size,131072),i=Buffer.alloc(t);await a.read(i,0,t,e.size-t);let n=i.toString("utf-8").split("\n").filter(t=>t.trim());r=$(n,s),o.lastAssistantSnippet||o.currentAction||(o=q(n))}return z.size>=256&&z.delete(z.keys().next().value),z.set(t,{mtimeMs:e.mtimeMs,idle:r.idle,stale:r.stale,needsStaleRecheck:r.needsStaleRecheck,staleMs:r.staleMs,lastAssistantSnippet:o.lastAssistantSnippet,currentAction:o.currentAction,reset:o.reset,lastEntryTs:r.lastEntryTs,interrupted:r.interrupted}),{idle:r.idle,stale:r.stale,lastAssistantSnippet:o.lastAssistantSnippet,currentAction:o.currentAction,reset:o.reset,lastEntryTs:r.lastEntryTs,staleMs:r.staleMs,interrupted:r.interrupted}}finally{await a.close()}}catch{return{idle:!1,stale:!1,lastAssistantSnippet:null,currentAction:null,reset:!1,lastEntryTs:null,staleMs:0,interrupted:!1}}},B=async t=>{let e={toolUsage:{},touchedFiles:[],lastAssistantText:null,lastUserText:null,firstUserTs:null,lastAssistantTs:null,turnDurationMs:null};try{let s=await h.default.stat(t);if(0===s.size)return e;let a=await h.default.open(t,"r");try{let t=Math.min(s.size,131072),e=Buffer.alloc(t);await a.read(e,0,t,s.size-t);let i=e.toString("utf-8").split("\n").filter(t=>t.trim()),n={},l=new Set,r=null,o=null,c=null,u=null,d=null;for(let t=i.length-1;t>=0;t--)try{let e=JSON.parse(i[t]);if("file-history-snapshot"===e.type)break;if(e.isSidechain)continue;"system"!==e.type||"turn_duration"!==e.subtype||"number"!=typeof e.durationMs||d||(d=e.durationMs);let s=e.timestamp?new Date(e.timestamp).getTime():null;if("user"===e.type&&(s&&(u=s),!o&&Array.isArray(e.message?.content))){for(let t of e.message.content)if("text"===t.type&&t.text){o=t.text;break}}if("assistant"===e.type&&(s&&!c&&(c=s),Array.isArray(e.message?.content))){let t=null;for(let s of e.message.content)"tool_use"===s.type&&s.name&&(n[s.name]=(n[s.name]??0)+1,("Edit"===s.name||"Write"===s.name)&&s.input?.file_path&&l.add(String(s.input.file_path))),"text"===s.type&&s.text&&(t=s.text);!r&&t&&(r=t)}}catch{continue}return{toolUsage:n,touchedFiles:[...l],lastAssistantText:r,lastUserText:o,firstUserTs:u,lastAssistantTs:c,turnDurationMs:d}}finally{await a.close()}}catch{return e}},K=/^[✳⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⠐⠈]\s+/,V=t=>t&&K.test(t)&&t.replace(K,"").trim()||null,X=globalThis;class G{tabs=new Map;pollingTimer=null;currentInterval=0;clients=new Set;initialized=!1;rateLimitsWatcher=null;lastRateLimits=null;jsonlWatchers=new Map;compactStaleTimers=new Map;async init(){if(!this.initialized){var t;let e,s,a,i,n,l;this.initialized=!0,await this.scanAll(),this.startPolling(),this.rateLimitsWatcher=(t=t=>{this.lastRateLimits=t,this.broadcast({type:"rate-limits:update",data:t})},e=null,s=null,a=0,i=async()=>{try{let e=await h.default.readFile(S.RATE_LIMITS_FILE,"utf-8"),s=JSON.parse(e);s.ts&&s.ts!==a&&(a=s.ts,t(s))}catch{}},n=()=>{i();try{(e=p.default.watch(f,(t,e)=>{e===b&&(s&&clearTimeout(s),s=setTimeout(i,500))})).on("error",()=>{g.debug(`${f} watch error, retrying...`),l(),setTimeout(n,5e3)})}catch{g.debug(`${f} not available yet, retrying...`),setTimeout(n,5e3)}},{start:n,stop:l=()=>{s&&(clearTimeout(s),s=null),e&&(e.close(),e=null)}}),this.rateLimitsWatcher.start()}}async scanAll(){let{workspaces:t}=await (0,s.getWorkspaces)(),e=await (0,n.getAllPanesInfo)();for(let t of[...this.jsonlWatchers.keys()])this.stopJsonlWatch(t);for(let s of(this.tabs.clear(),t)){let t=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(s.id));if(t)for(let a of(0,i.collectAllTabs)(t.root)){let t=e.get(a.sessionName),i=(0,o.getProviderByPanelType)(a.panelType),n=await this.readTabMetadata(t,i),l=a.cliState??"idle",r="busy"===l?"unknown":l,{terminalStatus:c,listeningPorts:d}=i?{terminalStatus:"idle",listeningPorts:[]}:await this.detectTerminalStatus(t),p=t?.command,h=t?`${t.command}|${t.path}`:void 0,m="needs-input"===r?{name:"notification",at:Date.now(),seq:0}:null;this.tabs.set(a.id,{cliState:r,workspaceId:s.id,tabName:a.name||(h?(0,u.formatTabTitle)(h):""),currentProcess:p,paneTitle:h,tmuxSession:a.sessionName,panelType:a.panelType,terminalStatus:c,listeningPorts:d,claudeSummary:a.claudeSummary,lastUserMessage:a.lastUserMessage,lastAssistantMessage:n.lastAssistantSnippet,currentAction:n.currentAction,readyForReviewAt:"ready-for-review"===r?Date.now():null,busySince:null,dismissedAt:a.dismissedAt??null,claudeSessionId:J(n.jsonlPath)??a.claudeSessionId??null,jsonlPath:n.jsonlPath,lastEvent:m,eventSeq:0}),("needs-input"===r||"unknown"===r)&&n.jsonlPath&&this.startJsonlWatch(a.id,n.jsonlPath),"unknown"===r&&this.resolveUnknown(a.id).catch(t=>F.warn("resolveUnknown failed: %s",t))}}}async resolveUnknown(t){let e=this.tabs.get(t);if(!e||"unknown"!==e.cliState)return;let s=(0,o.getProviderByPanelType)(e.panelType),a=(await (0,n.getAllPanesInfo)()).get(e.tmuxSession),i=a?.pid?await (0,l.getChildPids)(a.pid):[];if(!(a?.pid&&s&&await s.isAgentRunning(a.pid,i))){this.applyCliState(t,e,"idle",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e);return}if(e.jsonlPath){let{idle:s,stale:a,lastAssistantSnippet:i}=await H(e.jsonlPath);if(s&&!a&&i){this.applyCliState(t,e,"ready-for-review",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e);return}}}async readTabMetadata(t,e){let s={lastAssistantSnippet:null,currentAction:null,jsonlPath:null};if(!t||!t.pid||!e)return s;let a=await (0,l.getChildPids)(t.pid);if(!await e.isAgentRunning(t.pid,a))return s;let i=await e.detectActiveSession(t.pid,a);if("running"!==i.status||!i.jsonlPath)return{lastAssistantSnippet:null,currentAction:null,jsonlPath:i.jsonlPath??null};let{lastAssistantSnippet:n,currentAction:r}=await H(i.jsonlPath);return{lastAssistantSnippet:n,currentAction:r,jsonlPath:i.jsonlPath}}async detectTerminalStatus(t){if(!t||!t.pid)return{terminalStatus:"idle",listeningPorts:[]};let e=await (0,n.getListeningPorts)(t.pid);return e.length>0?{terminalStatus:"server",listeningPorts:e}:{terminalStatus:n.SAFE_SHELLS.has(t.command)?"idle":"running",listeningPorts:[]}}getPollingInterval(){let t=this.tabs.size;return t>=21?6e4:t>=11?45e3:3e4}async rescan(){await this.scanAll()}startPolling(){this.stopPolling(),this.currentInterval=this.getPollingInterval(),this.pollingTimer=setInterval(()=>{this.poll().catch(t=>{F.error({err:t},"Polling error")})},this.currentInterval)}stopPolling(){this.pollingTimer&&(clearInterval(this.pollingTimer),this.pollingTimer=null,this.currentInterval=0)}async poll(){let{workspaces:t}=await (0,s.getWorkspaces)(),e=await (0,n.getAllPanesInfo)(),r=new Set,c=new Set(this.tabs.keys()),d=Date.now();for(let s of t){let t=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(s.id));if(t)for(let c of(0,i.collectAllTabs)(t.root)){r.add(c.id);let t=this.tabs.get(c.id),i=e.get(c.sessionName),p=(0,o.getProviderByPanelType)(c.panelType),{terminalStatus:h,listeningPorts:m}=p?{terminalStatus:"idle",listeningPorts:[]}:await this.detectTerminalStatus(i),y=i?.command,S=i?`${i.command}|${i.path}`:void 0;if(!t){let t=c.cliState??"idle",e="busy"===t?"unknown":t,a=await this.readTabMetadata(i,p),n="needs-input"===e?{name:"notification",at:Date.now(),seq:0}:null,l={cliState:e,workspaceId:s.id,tabName:c.name||(S?(0,u.formatTabTitle)(S):""),currentProcess:y,paneTitle:S,tmuxSession:c.sessionName,panelType:c.panelType,terminalStatus:h,listeningPorts:m,claudeSummary:c.claudeSummary,lastUserMessage:c.lastUserMessage,lastAssistantMessage:a.lastAssistantSnippet,currentAction:a.currentAction,claudeSessionId:J(a.jsonlPath)??c.claudeSessionId??null,jsonlPath:a.jsonlPath,lastEvent:n,eventSeq:0};this.tabs.set(c.id,l),this.persistToLayout(l),this.broadcastUpdate(c.id,l),"unknown"===e&&this.resolveUnknown(c.id).catch(t=>F.warn("resolveUnknown failed: %s",t));continue}let g=t.currentProcess!==y,f=t.lastUserMessage!==c.lastUserMessage,b=t.panelType!==c.panelType,w=await this.readTabMetadata(i,p);t.tabName=c.name||(S?(0,u.formatTabTitle)(S):""),t.currentProcess=y,t.paneTitle=S,t.workspaceId=s.id,t.panelType=c.panelType,t.claudeSessionId=J(w.jsonlPath)??c.claudeSessionId??null,t.jsonlPath=w.jsonlPath??t.jsonlPath,t.lastUserMessage=c.lastUserMessage,g&&(t.processRetries=3);let T=!g&&(t.processRetries??0)>0;T&&(t.processRetries=t.processRetries-1);let A=t.listeningPorts,v=A?.length!==m.length||m.some((t,e)=>A[e]!==t),P=t.terminalStatus!==h||v;P&&(t.terminalStatus=h,t.listeningPorts=m);let k=!1;if("busy"===t.cliState||"needs-input"===t.cliState){let e=V(await (0,n.getPaneTitle)(c.sessionName));e&&e!==t.claudeSummary&&(t.claudeSummary=e,k=!0,(0,a.updateTabClaudeSummary)(c.sessionName,e).catch(()=>{}))}else t.claudeSummary!==c.claudeSummary&&(t.claudeSummary=c.claudeSummary,k=!0);if("busy"===t.cliState&&t.lastEvent&&d-t.lastEvent.at>6e5){let e=i?.pid?await (0,l.getChildPids)(i.pid):[];if(!(i?.pid&&p&&await p.isAgentRunning(i.pid,e))){F.info({tabId:c.id},"busy stuck — agent process gone, forcing idle"),this.applyCliState(c.id,t,"idle",{silent:!0}),this.persistToLayout(t),this.broadcastUpdate(c.id,t);continue}}(P||g||T||f||b||k)&&this.broadcastUpdate(c.id,t)}}for(let t of c)!r.has(t)&&this.tabs.has(t)&&(this.stopJsonlWatch(t),this.tabs.delete(t),this.broadcastRemove(t));let p=this.getPollingInterval();this.pollingTimer&&p!==this.currentInterval&&this.startPolling()}getAllForClient(){let t={};for(let[e,s]of this.tabs)t[e]={cliState:s.cliState,workspaceId:s.workspaceId,tabName:s.tabName,currentProcess:s.currentProcess,paneTitle:s.paneTitle,panelType:s.panelType,terminalStatus:s.terminalStatus,listeningPorts:s.listeningPorts,claudeSummary:s.claudeSummary,lastUserMessage:s.lastUserMessage,lastAssistantMessage:s.lastAssistantMessage,currentAction:s.currentAction,readyForReviewAt:s.readyForReviewAt,busySince:s.busySince,dismissedAt:s.dismissedAt,claudeSessionId:s.claudeSessionId,lastEvent:s.lastEvent,eventSeq:s.eventSeq};return t}applyCliState(t,e,s,a={}){if(e.cliState===s)return;let i=e.busySince;e.cliState=s,e.readyForReviewAt="ready-for-review"===s?Date.now():null,e.busySince="busy"===s?Date.now():null,"busy"===s&&(e.dismissedAt=null),"ready-for-review"===s&&e.jsonlPath&&new Promise(t=>setTimeout(t,500)).then(()=>this.saveSessionHistory(t,e,i,!1)).catch(t=>{F.warn("Failed to save session history: %s",t)}),"ready-for-review"!==s||a.silent||this.sendWebPush(t,e,"review").catch(t=>{F.warn("Web push failed: %s",t)}),"needs-input"!==s||a.silent||this.sendWebPush(t,e,"needs-input").catch(t=>{F.warn("Web push failed: %s",t)});let n=("busy"===s||"needs-input"===s)&&e.jsonlPath,l="ready-for-review"===s&&this.jsonlWatchers.has(t);n&&!this.jsonlWatchers.has(t)?this.startJsonlWatch(t,e.jsonlPath):!n&&!l&&this.jsonlWatchers.has(t)&&this.stopJsonlWatch(t)}async saveSessionHistory(t,e,a,i){if(!e.lastUserMessage)return;let n=e.jsonlPath?await B(e.jsonlPath):null,{workspaces:l}=await (0,s.getWorkspaces)(),r=l.find(t=>t.id===e.workspaceId),o=Date.now(),c=n?.firstUserTs??a??o,u=i?o:n?.lastAssistantTs??o,d=i?u-c:n?.turnDurationMs??u-c,p={id:(0,x.nanoid)(),workspaceId:e.workspaceId,workspaceName:r?.name??e.workspaceId,workspaceDir:r?.directories[0]??null,tabId:t,claudeSessionId:e.claudeSessionId??null,prompt:n?.lastUserText??e.lastUserMessage,result:n?.lastAssistantText??null,startedAt:c,completedAt:u,duration:d,dismissedAt:u,toolUsage:n?.toolUsage??{},touchedFiles:n?.touchedFiles??[],...i?{cancelled:!0}:{}};await E(p),this.broadcast({type:"session-history:update",entry:p})}dismissTab(t,e){let s=this.tabs.get(t);if(!s||"ready-for-review"!==s.cliState)return;let a=Date.now();this.applyCliState(t,s,"idle",{silent:!0}),s.dismissedAt=a,this.persistToLayout(s),this.broadcastUpdate(t,s,e),L(t,a).then(t=>{t&&this.broadcast({type:"session-history:update",entry:t})}).catch(t=>{F.warn("Failed to update session history dismissedAt: %s",t)})}ackNotificationInput(t,e){let s=this.tabs.get(t);s&&"needs-input"===s.cliState&&s.lastEvent?.name==="notification"&&s.lastEvent.seq===e&&(C.debug({tabId:t,seq:e},"ack: needs-input→busy"),this.applyCliState(t,s,"busy"),this.persistToLayout(s),this.broadcastUpdate(t,s))}async recoverUnknownIfPending(t){let e=this.tabs.get(t);if(!e)return{recovered:!1,reason:"no-entry"};if("unknown"!==e.cliState)return{recovered:!1,reason:"not-unknown"};let s=await (0,w.capturePaneAtWidth)(e.tmuxSession,120,50).catch(t=>(F.warn("recoverUnknownIfPending capture failed: %s",t),null));if(!s)return{recovered:!1,reason:"capture-failed"};let{options:a}=(0,T.parsePermissionOptions)(s);if(0===a.length)return{recovered:!1,reason:"no-options"};let i=Date.now(),n=(e.eventSeq??0)+1;return e.eventSeq=n,e.lastEvent={name:"notification",at:i,seq:n},C.debug({tabId:t,seq:n,options:a.length},"recover unknown→needs-input from pane capture"),this.applyCliState(t,e,"needs-input",{silent:!0}),this.persistToLayout(e),this.broadcastUpdate(t,e),{recovered:!0}}findTabIdBySession(t){for(let[e,s]of this.tabs)if(s.tmuxSession===t)return e}updateTabFromHook(t,e,s){let a=this.findTabIdBySession(t);if(!a)return void C.debug({tmuxSession:t,event:e,notificationType:s},"no tabId for session");let i=this.tabs.get(a);if(!i)return void C.debug({tabId:a,event:e,notificationType:s},"no entry for tab");if("pre-compact"===e||"post-compact"===e){C.debug({tabId:a,event:e},"compact hook"),this.setCompacting(a,i,"pre-compact"===e?Date.now():null);return}if("session-start"!==e&&"prompt-submit"!==e&&"notification"!==e&&"stop"!==e&&"interrupt"!==e)return void C.debug({tabId:a,event:e,notificationType:s},"unknown event, ignoring");if("notification"===e&&s&&!D.has(s))return void C.debug({tabId:a,event:e,notificationType:s},"non-input notification, skipping state transition");let n=Date.now(),l=(i.eventSeq??0)+1;i.eventSeq=l,i.lastEvent={name:e,at:n,seq:l},this.broadcast({type:"status:hook-event",tabId:a,event:i.lastEvent});let r=i.cliState,o="cancelled"===r?r:((t,e)=>{if(!t)return e;switch(t.name){case"session-start":case"interrupt":return"idle";case"prompt-submit":return"busy";case"notification":return"needs-input";case"stop":return"ready-for-review"}})(i.lastEvent,r);if(C.debug({tabId:a,event:e,notificationType:s,seq:l,prevState:r,newState:o,transition:r!==o},`processed ${e}${s?`(${s})`:""} ${r}→${o}`),r!==o&&(this.applyCliState(a,i,o),this.persistToLayout(i),this.broadcastUpdate(a,i)),"busy"!==o&&"needs-input"!==o||i.jsonlPath||this.resolveAndWatchJsonl(a,t).catch(()=>{}),"stop"===e&&i.jsonlPath){let t=()=>{H(i.jsonlPath).then(({currentAction:t,lastAssistantSnippet:e,reset:s})=>{let n=!1;s?(null!==i.currentAction&&(i.currentAction=null,n=!0),null!==i.lastAssistantMessage&&(i.lastAssistantMessage=null,n=!0)):(null!==t&&t.summary!==i.currentAction?.summary&&(i.currentAction=t,n=!0),null!==e&&i.lastAssistantMessage!==e&&(i.lastAssistantMessage=e,n=!0)),n&&this.broadcastUpdate(a,i)}).catch(()=>{})};t(),setTimeout(()=>{z.delete(i.jsonlPath),t()},500)}}setCompacting(t,e,s){let a=this.compactStaleTimers.get(t);if(a&&(clearTimeout(a),this.compactStaleTimers.delete(t)),(e.compactingSince??null)!==s&&(e.compactingSince=s,this.broadcastUpdate(t,e),null!==s)){let e=setTimeout(()=>{this.compactStaleTimers.delete(t);let e=this.tabs.get(t);e&&e.compactingSince===s&&(e.compactingSince=null,C.debug({tabId:t},"compact stale, auto-cleared"),this.broadcastUpdate(t,e))},6e4);this.compactStaleTimers.set(t,e)}}removeTab(t){let e=this.tabs.get(t);e&&("busy"===e.cliState||"needs-input"===e.cliState)&&e.lastUserMessage&&this.saveSessionHistory(t,e,e.busySince,!0).catch(t=>{F.warn("Failed to save cancelled session history: %s",t)}),this.stopJsonlWatch(t);let s=this.compactStaleTimers.get(t);s&&(clearTimeout(s),this.compactStaleTimers.delete(t)),this.tabs.delete(t),this.broadcastRemove(t)}reconcileWorkspaceTabs(t,e){let s=new Set(e);for(let[e,a]of this.tabs)a.workspaceId!==t||s.has(e)||this.removeTab(e)}removeWorkspaceTabs(t){for(let[e,s]of this.tabs)s.workspaceId===t&&this.removeTab(e)}registerTab(t,e){this.tabs.set(t,e),this.broadcastUpdate(t,e)}addClient(t){this.clients.add(t),this.lastRateLimits&&t.readyState===e.WebSocket.OPEN&&t.send(JSON.stringify({type:"rate-limits:update",data:this.lastRateLimits}))}removeClient(t){this.clients.delete(t)}persistToLayout(t){(0,a.updateTabCliStatus)(t.tmuxSession,t.cliState,t.dismissedAt).catch(()=>{})}broadcastUpdate(t,e,s){let a={type:"status:update",tabId:t,cliState:e.cliState,workspaceId:e.workspaceId,tabName:e.tabName,currentProcess:e.currentProcess,paneTitle:e.paneTitle,panelType:e.panelType,terminalStatus:e.terminalStatus,listeningPorts:e.listeningPorts,claudeSummary:e.claudeSummary,lastUserMessage:e.lastUserMessage,lastAssistantMessage:e.lastAssistantMessage,currentAction:e.currentAction,readyForReviewAt:e.readyForReviewAt,busySince:e.busySince,dismissedAt:e.dismissedAt,claudeSessionId:e.claudeSessionId,compactingSince:e.compactingSince,lastEvent:e.lastEvent,eventSeq:e.eventSeq};this.broadcast(a,s)}broadcastRemove(t){this.broadcast({type:"status:update",tabId:t,cliState:null,workspaceId:"",tabName:""})}static BACKPRESSURE_LIMIT=1048576;broadcast(t,s){let a=JSON.stringify(t);for(let t of this.clients)t!==s&&t.readyState===e.WebSocket.OPEN&&t.bufferedAmount<G.BACKPRESSURE_LIMIT&&t.send(a)}async resolveAndWatchJsonl(t,e){let s=this.tabs.get(t);if(!s||s.jsonlPath)return;let l=null,o=(0,a.parseSessionName)(e);if(o){let r=await (0,a.readLayoutFile)((0,a.resolveLayoutFile)(o.wsId));if(r){let a=(0,i.collectAllTabs)(r.root).find(t=>t.sessionName===e);if(a?.claudeSessionId){let t=await (0,n.getSessionCwd)(e);if(t){let e=`${(0,c.cwdToProjectPath)(t)}/${a.claudeSessionId}.jsonl`;try{await h.default.access(e),l=e}catch{}}}a?.lastUserMessage&&s.lastUserMessage!==a.lastUserMessage&&(s.lastUserMessage=a.lastUserMessage,this.broadcastUpdate(t,s))}}if(!l){let t=await (0,n.getSessionPanePid)(e);if(t){let{info:e}=await (0,r.detectAnyActiveSession)(t);l=e.jsonlPath}}l&&(s.jsonlPath=l,s.claudeSessionId=J(l)??s.claudeSessionId,"busy"!==s.cliState&&"needs-input"!==s.cliState||this.jsonlWatchers.has(t)||this.startJsonlWatch(t,l))}startJsonlWatch(t,e){let s=this.jsonlWatchers.get(t);if(s?.jsonlPath!==e){s&&this.stopJsonlWatch(t),F.debug("startJsonlWatch tabId=%s path=%s",t,e);try{let s=(0,p.watch)(e,()=>{let s=this.jsonlWatchers.get(t);s&&(s.debounceTimer&&clearTimeout(s.debounceTimer),s.debounceTimer=setTimeout(()=>{this.onJsonlFileChange(t,e).catch(()=>{})},100))});s.on("error",()=>{this.stopJsonlWatch(t)}),this.jsonlWatchers.set(t,{watcher:s,jsonlPath:e,debounceTimer:null})}catch{}}}stopJsonlWatch(t){let e=this.jsonlWatchers.get(t);if(e){F.debug("stopJsonlWatch tabId=%s",t),e.debounceTimer&&clearTimeout(e.debounceTimer);try{e.watcher.close()}catch{}this.jsonlWatchers.delete(t)}}async onJsonlFileChange(t,e){let s=this.tabs.get(t);if(!s||"busy"!==s.cliState&&"needs-input"!==s.cliState&&"unknown"!==s.cliState&&"ready-for-review"!==s.cliState)return void this.stopJsonlWatch(t);let{currentAction:a,lastAssistantSnippet:i,reset:n,interrupted:l,lastEntryTs:r}=await H(e);l&&"busy"===s.cliState&&null!==r&&r>(s.lastInterruptTs??0)&&r>(s.lastEvent?.at??0)&&(s.lastInterruptTs=r,C.debug({tabId:t,lastEntryTs:r},"synthetic interrupt from JSONL"),this.updateTabFromHook(s.tmuxSession,"interrupt"));let o=!1;n?(null!==s.currentAction&&(s.currentAction=null,o=!0),null!==s.lastAssistantMessage&&(s.lastAssistantMessage=null,o=!0)):(null!==a&&a.summary!==s.currentAction?.summary&&(s.currentAction=a,o=!0),null!==i&&s.lastAssistantMessage!==i&&(s.lastAssistantMessage=i,o=!0)),o&&this.broadcastUpdate(t,s)}shutdown(){for(let t of(this.stopPolling(),this.rateLimitsWatcher?.stop(),[...this.jsonlWatchers.keys()]))this.stopJsonlWatch(t);for(let t of this.clients)t.readyState===e.WebSocket.OPEN&&t.close(1001,"Server shutting down");this.clients.clear()}notifyLastUserMessage(t,e){let s=(0,a.parseSessionName)(t);if(!s)return;let i=this.tabs.get(s.tabId);i&&i.lastUserMessage!==e&&(i.lastUserMessage=e,this.broadcastUpdate(s.tabId,i))}async sendWebPush(t,e,a){let i=await (0,R.getSubscriptions)();if(0===i.length)return;let n=await (0,N.getVAPIDKeys)();_.default.setVapidDetails("mailto:noreply@purplemux.app",n.publicKey,n.privateKey);let l=e.lastUserMessage?.slice(0,100)||e.tabName||t,r=(await (0,s.getWorkspaces)()).workspaces.find(t=>t.id===e.workspaceId),o=JSON.stringify({title:"needs-input"===a?"Input Required":"Task Complete",body:l,tabId:t,workspaceId:e.workspaceId,claudeSessionId:e.claudeSessionId??null,workspaceName:r?.name??"",workspaceDir:r?.directories[0]??null});if(!(0,R.isAnyDeviceVisible)())for(let t of i)try{await _.default.sendNotification(t,o)}catch(s){let e=s.statusCode;(410===e||404===e)&&await (0,R.removeSubscription)(t.endpoint),F.warn("Web push send error: %s",e)}}}t.s(["getStatusManager",0,()=>{if(!X.__ptStatusManager){let t=new G;X.__ptStatusManager=t,(0,a.setLayoutReconciler)({reconcileWorkspaceTabs:(e,s)=>t.reconcileWorkspaceTabs(e,s),removeWorkspaceTabs:e=>t.removeWorkspaceTabs(e)})}return X.__ptStatusManager}],964759)}];
14
2
 
15
3
  //# sourceMappingURL=src_lib_status-manager_ts_003hlhy._.js.map