@readmagic/workmate 0.0.5 → 0.0.6

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 (346) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-DJRkEz7o.js → AddWorkspaceDirectory-ClHi-Dr6.js} +1 -1
  2. package/dist/chunks/{App-iJu5qyiF.js → App-BP06lHmf.js} +1 -1
  3. package/dist/chunks/{ApproveApiKey-CRejTHUw.js → ApproveApiKey-Bsy8kr2a.js} +1 -1
  4. package/dist/chunks/ApproveApiKey-a2ZonQ3n.js +1 -0
  5. package/dist/chunks/{AssistantSessionChooser-CBLQ1v-J.js → AssistantSessionChooser-CcocKoTJ.js} +1 -1
  6. package/dist/chunks/{BackgroundTasksDialog-CyoLEYWH.js → BackgroundTasksDialog-DNeBhGCf.js} +1 -1
  7. package/dist/chunks/{BypassPermissionsModeDialog-D1FCKVOi.js → BypassPermissionsModeDialog-BKj_3Idm.js} +1 -1
  8. package/dist/chunks/{ClaudeMdExternalIncludesDialog-CI0yF6sZ.js → ClaudeMdExternalIncludesDialog-BD-7yAZh.js} +1 -1
  9. package/dist/chunks/ClaudeMdExternalIncludesDialog-DFivNFuo.js +1 -0
  10. package/dist/chunks/ConsoleOAuthFlow-CS3zjEPF.js +1 -0
  11. package/dist/chunks/{DesktopHandoff-D1rrMxeP.js → DesktopHandoff-BmPmCfT3.js} +1 -1
  12. package/dist/chunks/{DiffDialog-BKcfKx7O.js → DiffDialog-C4XSSjvV.js} +1 -1
  13. package/dist/chunks/Doctor-BhD-ZzZm.js +1 -0
  14. package/dist/chunks/{Doctor-Yco1McrL.js → Doctor-DEQe2q16.js} +1 -1
  15. package/dist/chunks/{ExitFlow-D3csukbB.js → ExitFlow-BttnAv-O.js} +1 -1
  16. package/dist/chunks/{Feedback-bEUtrHia.js → Feedback-BaYA8-SU.js} +1 -1
  17. package/dist/chunks/Grove-BJziCbZH.js +11 -0
  18. package/dist/chunks/Grove-sWm-oLBf.js +1 -0
  19. package/dist/chunks/{HybridTransport-9fTBC2Pv.js → HybridTransport-B8V6O6rM.js} +1 -1
  20. package/dist/chunks/{InvalidConfigDialog-9M-1nfZ6.js → InvalidConfigDialog-CHzBSJDf.js} +1 -1
  21. package/dist/chunks/{InvalidSettingsDialog-B2F6pryH.js → InvalidSettingsDialog-BKenH3bD.js} +1 -1
  22. package/dist/chunks/{MCPConnectionManager-MWpKjeZT.js → MCPConnectionManager-CNh9dNlk.js} +1 -1
  23. package/dist/chunks/{McpParsingWarnings-BPBb7Npe.js → McpParsingWarnings-Bj2-YL8o.js} +1 -1
  24. package/dist/chunks/{MessageSelector-DsQmqFt2.js → MessageSelector-DdR6wJhh.js} +1 -1
  25. package/dist/chunks/{Messages-B3sGRx5A.js → Messages-Ch6cboMV.js} +2 -2
  26. package/dist/chunks/{Onboarding-cHcnsBGp.js → Onboarding-BrAJp0aL.js} +1 -1
  27. package/dist/chunks/{OverageCreditUpsell-CWCD_RpM.js → OverageCreditUpsell-Ds1cB7RC.js} +1 -1
  28. package/dist/chunks/PluginSettings-CGqEzejq.js +17 -0
  29. package/dist/chunks/{PromptInputFooterSuggestions-D5sAO6y-.js → PromptInputFooterSuggestions-egs9VvUs.js} +1 -1
  30. package/dist/chunks/{PromptInputHelpMenu-n6hAdsto.js → PromptInputHelpMenu-SieM5NoY.js} +1 -1
  31. package/dist/chunks/{QueryEngine-cwdsr4dr.js → QueryEngine-CZZMl3PB.js} +1 -1
  32. package/dist/chunks/{REPL-CJzScgbZ.js → REPL-CG2N7E4Q.js} +6 -6
  33. package/dist/chunks/REPL-DvA910N_.js +1 -0
  34. package/dist/chunks/{RemoteCallout-CiA4rCEs.js → RemoteCallout-Cs-ro8_i.js} +1 -1
  35. package/dist/chunks/{RemoteSessionManager-zdHfmvfj.js → RemoteSessionManager-B740Dp6m.js} +1 -1
  36. package/dist/chunks/{ResumeConversation-Rxwd6HAJ.js → ResumeConversation-DzV2zmuX.js} +1 -1
  37. package/dist/chunks/{SSETransport-BPbhCa2f.js → SSETransport-DtpMDekF.js} +1 -1
  38. package/dist/chunks/SearchExtraToolsTool-C4uO-Zx3.js +1 -0
  39. package/dist/chunks/{Settings-CxI_KHUj.js → Settings-XKw6FI_m.js} +2 -2
  40. package/dist/chunks/{TeleportProgress-DrulEQ7z.js → TeleportProgress-rYaHIEfe.js} +1 -1
  41. package/dist/chunks/{TeleportRepoMismatchDialog-D3FOLr0P.js → TeleportRepoMismatchDialog-DY97YZMB.js} +1 -1
  42. package/dist/chunks/{TeleportResumeWrapper-DI5iRFND.js → TeleportResumeWrapper-jaQzyTCh.js} +1 -1
  43. package/dist/chunks/{ThemePicker-CQ7dfFtv.js → ThemePicker-BViWzLp3.js} +1 -1
  44. package/dist/chunks/{TrustDialog-CnVKrdxQ.js → TrustDialog-DGJ_BisZ.js} +1 -1
  45. package/dist/chunks/{ValidationErrorsList-CPYeuppg.js → ValidationErrorsList-B8pRiGuy.js} +1 -1
  46. package/dist/chunks/{WelcomeV2-C-UXdIng.js → WelcomeV2-DqnbSdIu.js} +1 -1
  47. package/dist/chunks/{add-dir-xTz4COgn.js → add-dir-C2Hu3oE4.js} +1 -1
  48. package/dist/chunks/{agentDisplay-BuSReYxu.js → agentDisplay-XoDJhr03.js} +1 -1
  49. package/dist/chunks/{agents-Du9KYHqN.js → agents-BIHTGDYh.js} +1 -1
  50. package/dist/chunks/{agents-CiLlKN2I.js → agents-C4QXeHIJ.js} +1 -1
  51. package/dist/chunks/{allErrors-P3utlEeA.js → allErrors-1896uQA1.js} +1 -1
  52. package/dist/chunks/{ant-CBIfqmAb.js → ant-B6k6cBts.js} +1 -1
  53. package/dist/chunks/api-BsFW57_Q.js +1 -0
  54. package/dist/chunks/{api-B-5jqiMg.js → api-gqTA-D7n.js} +1 -1
  55. package/dist/chunks/{assistant-XOnU01yl.js → assistant-DJ9hd4uC.js} +1 -1
  56. package/dist/chunks/auth-8Vd3_U8t.js +1 -0
  57. package/dist/chunks/{auth-DT2yxy94.js → auth-BnSrKyJe.js} +1 -1
  58. package/dist/chunks/auth-DRTjfnGy.js +1 -0
  59. package/dist/chunks/{autoMode-CEMflt3g.js → autoMode-BNukrVAB.js} +1 -1
  60. package/dist/chunks/{autonomy-_N8aDaA8.js → autonomy-BEmI7WVW.js} +1 -1
  61. package/dist/chunks/{autonomy-Cg5zweUa.js → autonomy-DGcy5Rml.js} +1 -1
  62. package/dist/chunks/{autonomyPanel-I4yCy3Fr.js → autonomyPanel-fhge09AG.js} +1 -1
  63. package/dist/chunks/backgroundHousekeeping-3i_d_WW5.js +1 -0
  64. package/dist/chunks/{backgroundHousekeeping-DhF2lrQ9.js → backgroundHousekeeping-BVMf_Tjn.js} +2 -2
  65. package/dist/chunks/{branch-BIX-pyHp.js → branch-Bpe-gocq.js} +1 -1
  66. package/dist/chunks/{break-cache-BQfgkNAo.js → break-cache-C_p7Kmx2.js} +3 -3
  67. package/dist/chunks/{bridge-CYskzVt8.js → bridge-D12Shbkj.js} +2 -2
  68. package/dist/chunks/{bridgeConfig-5p_w4s5r.js → bridgeConfig-BhxRF2vm.js} +1 -1
  69. package/dist/chunks/bridgeConfig-CqIQ_rvD.js +1 -0
  70. package/dist/chunks/bridgeEnabled-D0XC5kNh.js +1 -0
  71. package/dist/chunks/{bridgeEnabled-DhFrLTbG.js → bridgeEnabled-SbB-6zdY.js} +1 -1
  72. package/dist/chunks/{bridgeMain-BX2AkLPs.js → bridgeMain-DHUpZFgL.js} +6 -6
  73. package/dist/chunks/bridgeMain-DUbQjgCp.js +1 -0
  74. package/dist/chunks/{bridgeMessaging-B5Lbzr8e.js → bridgeMessaging-DHc5dOhB.js} +1 -1
  75. package/dist/chunks/{btw-CWWFO7u8.js → btw-D9hMM5d2.js} +1 -1
  76. package/dist/chunks/caches-CWzT7e6Y.js +1 -0
  77. package/dist/chunks/{caches-DPqPIogk.js → caches-UeVVM3T0.js} +2 -2
  78. package/dist/chunks/{ccrClient-CTLnU9Y1.js → ccrClient-Iza0L8Zw.js} +1 -1
  79. package/dist/chunks/{clear-DCAgZwc4.js → clear-B4d38ssF.js} +1 -1
  80. package/dist/chunks/client-BzKQTXzF.js +1 -0
  81. package/dist/chunks/{color-CmJGInHL.js → color-D8VOyoYl.js} +1 -1
  82. package/dist/chunks/commands-DDamMmo4.js +1 -0
  83. package/dist/chunks/commitAttribution-CgohL8vD.js +1 -0
  84. package/dist/chunks/{commitAttribution-CGZr7XNO.js → commitAttribution-ChAgixdj.js} +1 -1
  85. package/dist/chunks/{compact-C6-lMHgn.js → compact-IFHwxjZ9.js} +1 -1
  86. package/dist/chunks/config-DY5-_kk_.js +1 -0
  87. package/dist/chunks/{config-3m_9zSrj.js → config-DmomySWC.js} +1 -1
  88. package/dist/chunks/config-WxgxrQoP.js +1 -0
  89. package/dist/chunks/{context-C9V4GF0n.js → context-Cl6BJ2vm.js} +1 -1
  90. package/dist/chunks/{context-noninteractive-BmC4o5xo.js → context-noninteractive-9hELVC29.js} +1 -1
  91. package/dist/chunks/context-noninteractive-Beij5MfU.js +1 -0
  92. package/dist/chunks/conversation-BBB91hEw.js +1 -0
  93. package/dist/chunks/{conversation-CYqqk0o7.js → conversation-BWVTM40Y.js} +1 -1
  94. package/dist/chunks/{createSSHSession-BL6j0AU5.js → createSSHSession-BM-5pbv6.js} +1 -1
  95. package/dist/chunks/createSession-CoQtL5Rj.js +1 -0
  96. package/dist/chunks/{createSession-D_sgO1Xy.js → createSession-Cvl1Q50F.js} +1 -1
  97. package/dist/chunks/{crossProjectResume-D5hTOfnE.js → crossProjectResume-BasMLl2n.js} +1 -1
  98. package/dist/chunks/{datadog-UkGdjL8-.js → datadog-CpqEQbHa.js} +1 -1
  99. package/dist/chunks/{desktop-HbYKh-VK.js → desktop-B_L6T6jI.js} +1 -1
  100. package/dist/chunks/{diff-nTV17iWX.js → diff-CVzOodeg.js} +1 -1
  101. package/dist/chunks/doctor-1L0TFuGw.js +1 -0
  102. package/dist/chunks/{entry-CCFI6-gM.js → entry-DHVYCR26.js} +1 -1
  103. package/dist/chunks/envLessBridgeConfig-CN0_44-p.js +1 -0
  104. package/dist/chunks/{envLessBridgeConfig-DXd10GXD.js → envLessBridgeConfig-Ck2-KMq0.js} +1 -1
  105. package/dist/chunks/{esm-CGoYrggU.js → esm-D5q6s4l8.js} +1 -1
  106. package/dist/chunks/{exit-ropaQiOr.js → exit-Bm1S_f3i.js} +1 -1
  107. package/dist/chunks/extra-usage-UHAWtypK.js +1 -0
  108. package/dist/chunks/{extra-usage-core-DLYHAInT.js → extra-usage-core-BFOolqoi.js} +1 -1
  109. package/dist/chunks/{extra-usage-noninteractive-D8iszH3c.js → extra-usage-noninteractive-cUGZy0en.js} +1 -1
  110. package/dist/chunks/{extra-usage-g2Pw4zt_.js → extra-usage-zDHVtWKZ.js} +1 -1
  111. package/dist/chunks/{extraUsage-C2Ylufhj.js → extraUsage-Dq66zzqR.js} +1 -1
  112. package/dist/chunks/extractMemories-BcaklA33.js +1 -0
  113. package/dist/chunks/fast-DALAHO3d.js +1 -0
  114. package/dist/chunks/{fast-Dx2fTmWr.js → fast-MS7WZpD8.js} +1 -1
  115. package/dist/chunks/{feedback-DCQ4pJ3v.js → feedback-Fw4m28ZC.js} +1 -1
  116. package/dist/chunks/firstPartyEventLogger-CS9jVz6D.js +1 -0
  117. package/dist/chunks/{firstPartyEventLogger-BNGPPBNP.js → firstPartyEventLogger-CoSUd0a1.js} +2 -2
  118. package/dist/chunks/{flushGate-XaheIZZT.js → flushGate-De-yppeo.js} +1 -1
  119. package/dist/chunks/{gemini-BCCLHK3K.js → gemini-BPziscyN.js} +1 -1
  120. package/dist/chunks/{generateRecap-BhvbixY2.js → generateRecap-jGDLI_wU.js} +1 -1
  121. package/dist/chunks/{generateSessionName-CN1oh7Fa.js → generateSessionName-hDJ6HBJ1.js} +1 -1
  122. package/dist/chunks/{githubRepoPathMapping-B4AM8luI.js → githubRepoPathMapping-qAoiyj6P.js} +1 -1
  123. package/dist/chunks/{goal-Bp6fyGqo.js → goal-CFx4eRkf.js} +1 -1
  124. package/dist/chunks/{grok-ax26ju8y.js → grok-Byblph7F.js} +1 -1
  125. package/dist/chunks/{grove-DrBVaZSN.js → grove-CpqjcGCb.js} +1 -1
  126. package/dist/chunks/{heapdump-JseysNDr.js → heapdump-C4kPlqGt.js} +1 -1
  127. package/dist/chunks/{help-DR9hKneR.js → help-B1h-faJ3.js} +1 -1
  128. package/dist/chunks/hooks-DPLIIpAD.js +1 -0
  129. package/dist/chunks/{hooks-C5n23H1E.js → hooks-X6J03MnA.js} +1 -1
  130. package/dist/chunks/hostGuard-BHI6Q8Mt.js +1 -0
  131. package/dist/chunks/inboundAttachments-BekVc0W-.js +1 -0
  132. package/dist/chunks/{inboundAttachments-Cp8XvLMZ.js → inboundAttachments-CUJE3KaU.js} +1 -1
  133. package/dist/chunks/{initReplBridge-DJs28ZkI.js → initReplBridge-JQ-afRx9.js} +1 -1
  134. package/dist/chunks/{install-C7qTB0V5.js → install-D5YORIJL.js} +1 -1
  135. package/dist/chunks/{instrumentation-CLZttr_u.js → instrumentation-Bw3CxPQf.js} +3 -3
  136. package/dist/chunks/{job-BhiazwPH.js → job-DOWtcltx.js} +1 -1
  137. package/dist/chunks/{keybindings-CkL8BzUt.js → keybindings-BLw5J-Zj.js} +1 -1
  138. package/dist/chunks/{language-DIw2871r.js → language-C6Fq-XOZ.js} +1 -1
  139. package/dist/chunks/language-Cqw5gYJR.js +1 -0
  140. package/dist/chunks/{launchAgentsPlatform-j-mWpwW1.js → launchAgentsPlatform-jWWf-Lk9.js} +1 -1
  141. package/dist/chunks/{launchLocalMemory-DmoXp0Xo.js → launchLocalMemory-kHeD0I0y.js} +1 -1
  142. package/dist/chunks/{launchLocalVault-1uKe0HjA.js → launchLocalVault-DLqkOjmb.js} +1 -1
  143. package/dist/chunks/{launchMemoryStores-SxDKjHJ3.js → launchMemoryStores-Ct7AVXrO.js} +1 -1
  144. package/dist/chunks/{launchOnboarding-CTtpnXcs.js → launchOnboarding-Cc6WwPX9.js} +1 -1
  145. package/dist/chunks/{launchSchedule-BDVnGhaL.js → launchSchedule-ZyvuvjgU.js} +1 -1
  146. package/dist/chunks/{launchSkillStore-SmMLxp4K.js → launchSkillStore-BejQnLog.js} +1 -1
  147. package/dist/chunks/{launchTeleport-B472ZSGz.js → launchTeleport-8CuYUfIR.js} +1 -1
  148. package/dist/chunks/{launchVault-CsyBgxle.js → launchVault-DIvIOuPh.js} +1 -1
  149. package/dist/chunks/{loadAgentsDir-Clu7Uk6a.js → loadAgentsDir-D206qwP3.js} +47 -47
  150. package/dist/chunks/loadAgentsDir-TZjwTqdr.js +1 -0
  151. package/dist/chunks/{loadPluginHooks-Cvd5VdjQ.js → loadPluginHooks-Ddhsyn0_.js} +1 -1
  152. package/dist/chunks/{localSearch-iA6JTk19.js → localSearch-CzrbOklu.js} +1 -1
  153. package/dist/chunks/localSearch-DrOAL6f4.js +1 -0
  154. package/dist/chunks/{logoV2Utils-YHBJLIrC.js → logoV2Utils-8M56V7oN.js} +1 -1
  155. package/dist/chunks/{magicDocs-Bf1fqnHN.js → magicDocs-DWjL2k7P.js} +1 -1
  156. package/dist/chunks/{main-gtV_TqXP.js → main-BohPzJFF.js} +16 -16
  157. package/dist/chunks/{mappers-C8lYERPX.js → mappers-BDMZFgKx.js} +1 -1
  158. package/dist/chunks/{mcp-Ci0OPVrR.js → mcp-Bt1ITh-Z.js} +1 -1
  159. package/dist/chunks/{mcp-CNuhEGP6.js → mcp-CwJ-AIpt.js} +2 -2
  160. package/dist/chunks/{mcp-CwIYauZl.js → mcp-W0LFoyFR.js} +1 -1
  161. package/dist/chunks/{memory-DCGqfQ1U.js → memory-3wV7m7UU.js} +1 -1
  162. package/dist/chunks/{mode-DO6g7nkX.js → mode-CUkHFkju.js} +1 -1
  163. package/dist/chunks/{model-DLXL0CNu.js → model-BY3auM2c.js} +1 -1
  164. package/dist/chunks/model-CKkOnnnx.js +1 -0
  165. package/dist/chunks/model-DRXcJyU9.js +1 -0
  166. package/dist/chunks/{nativeInstaller-OPuO2sm_.js → nativeInstaller-CA5d6_G7.js} +1 -1
  167. package/dist/chunks/{onChangeAppState-CHhRDkM7.js → onChangeAppState-DBmy2Ow_.js} +1 -1
  168. package/dist/chunks/{openai-HOebt-8k.js → openai-Cbomn0Ws.js} +1 -1
  169. package/dist/chunks/{overageCreditGrant-Bi1CTBAx.js → overageCreditGrant-DsUrmeBh.js} +1 -1
  170. package/dist/chunks/{panel-CrTPqXCv.js → panel-BSZGX6jN.js} +1 -1
  171. package/dist/chunks/{panelCall-D0eURklm.js → panelCall-BsVoL1uF.js} +1 -1
  172. package/dist/chunks/{partition-C8RSL3SQ.js → partition-BAakXjvj.js} +1 -1
  173. package/dist/chunks/{passes-BJci5SM_.js → passes-CLRt7Cvm.js} +1 -1
  174. package/dist/chunks/{permissions-JU9CGHgI.js → permissions-BVSFuwNP.js} +1 -1
  175. package/dist/chunks/{pidLock-Bd2e6xuT.js → pidLock-D5rUnDB-.js} +2 -2
  176. package/dist/chunks/{plan-D4gMsK7i.js → plan-SYZ4DXR8.js} +1 -1
  177. package/dist/chunks/{plugin-CwCo5Kik.js → plugin-Bfjzhmrk.js} +1 -1
  178. package/dist/chunks/{pluginAutoupdate-CO-n9bqe.js → pluginAutoupdate-reO2PgtQ.js} +1 -1
  179. package/dist/chunks/{pluginBlocklist-5qbaTRbV.js → pluginBlocklist-C3H2afWG.js} +1 -1
  180. package/dist/chunks/{pluginCliCommands-I-lsw_us.js → pluginCliCommands-lqdxdkQp.js} +1 -1
  181. package/dist/chunks/{pluginFlagging-DNPBbJZo.js → pluginFlagging-D9HKAGBC.js} +1 -1
  182. package/dist/chunks/{pluginOperations-Cz6eQ0Vu.js → pluginOperations-EN3EKLux.js} +1 -1
  183. package/dist/chunks/{pluginStartupCheck-DJ9fslCK.js → pluginStartupCheck-BY73BMT2.js} +1 -1
  184. package/dist/chunks/pluginStartupCheck-CwWOlveD.js +1 -0
  185. package/dist/chunks/{plugins-CzJIuPfb.js → plugins-Dn6ceWrT.js} +1 -1
  186. package/dist/chunks/policyLimits-CkTI5KEt.js +1 -0
  187. package/dist/chunks/{poor-Dha9p9RF.js → poor-j-y-bv8o.js} +1 -1
  188. package/dist/chunks/{poorMode-1NLYiS3Y.js → poorMode-DhzFKpPl.js} +1 -1
  189. package/dist/chunks/poorMode-V11s-3cf.js +1 -0
  190. package/dist/chunks/{print-BL4EUT5Z.js → print-Db_VXmfO.js} +4 -4
  191. package/dist/chunks/{privacy-settings-6ZWxR4Qt.js → privacy-settings-DHMJREbb.js} +1 -1
  192. package/dist/chunks/{processBashCommand-BZs9wggV.js → processBashCommand-BcM_fhV9.js} +1 -1
  193. package/dist/chunks/{processSlashCommand-D8lKLNzM.js → processSlashCommand-DEVo3GPX.js} +1 -1
  194. package/dist/chunks/{prompt-Bg_1U0gO.js → prompt-BNHtszmZ.js} +1 -1
  195. package/dist/chunks/prompt-CrX31AGm.js +1 -0
  196. package/dist/chunks/prompt-IAvMxKDl.js +1 -0
  197. package/dist/chunks/{promptEditor-BhYDmwdS.js → promptEditor-DeMrXUir.js} +1 -1
  198. package/dist/chunks/{protocolHandler-Dnb7lITm.js → protocolHandler-BHxBy84Z.js} +1 -1
  199. package/dist/chunks/{rate-limit-options-DVzT3eWH.js → rate-limit-options-DIudL9fb.js} +1 -1
  200. package/dist/chunks/{rcDebugLog-VKwMl0yg.js → rcDebugLog-CUy1_F23.js} +1 -1
  201. package/dist/chunks/{reconciler-BdRXZTJf.js → reconciler-BXpPyfSY.js} +1 -1
  202. package/dist/chunks/{referral-BlrMpBAV.js → referral-CUaIo_vT.js} +1 -1
  203. package/dist/chunks/{refresh-jwqnoK2h.js → refresh-CuaVBIQ0.js} +1 -1
  204. package/dist/chunks/{registerProtocol-CuKZAiCc.js → registerProtocol-B7Fzdofu.js} +1 -1
  205. package/dist/chunks/{release-notes-BgP8u7NE.js → release-notes-fbfv2DC0.js} +1 -1
  206. package/dist/chunks/{releaseNotes-CunqVlbU.js → releaseNotes-CxAHFLPl.js} +2 -2
  207. package/dist/chunks/{reload-plugins-CD9TzvFm.js → reload-plugins-B9IT9CFA.js} +1 -1
  208. package/dist/chunks/{remote-env-QaP_W_sv.js → remote-env-BOklGlll.js} +1 -1
  209. package/dist/chunks/{remoteBridgeCore-9-HVMo63.js → remoteBridgeCore-j0bG1zjv.js} +1 -1
  210. package/dist/chunks/{remoteManagedSettings-jZ6u8ZBT.js → remoteManagedSettings-Cq994lyc.js} +1 -1
  211. package/dist/chunks/{rename-29qxHf8W.js → rename-Iev7wQsI.js} +1 -1
  212. package/dist/chunks/{resume-D-SpOy_1.js → resume-y7MCTZHJ.js} +1 -1
  213. package/dist/chunks/{runtimeObserver-DOEcrylu.js → runtimeObserver-BZcJ1FbH.js} +1 -1
  214. package/dist/chunks/{runtimeObserver-Dm3LIUMp.js → runtimeObserver-CyzLASla.js} +2 -2
  215. package/dist/chunks/sandbox-adapter-Cu1FYrkh.js +1 -0
  216. package/dist/chunks/{sandbox-toggle-B61AeBor.js → sandbox-toggle-CWpBO228.js} +1 -1
  217. package/dist/chunks/searchExtraTools-BUOUds7p.js +1 -0
  218. package/dist/chunks/{session-RwJCIIcs.js → session-DL4cA_8l.js} +1 -1
  219. package/dist/chunks/{sessionDiscovery-dkFeWcA3.js → sessionDiscovery-DAfNKqp1.js} +1 -1
  220. package/dist/chunks/sessionFileAccessHooks-2cgIIxPk.js +1 -0
  221. package/dist/chunks/{sessionMemory-btARBn8H.js → sessionMemory-BS8_TbKj.js} +1 -1
  222. package/dist/chunks/sessionMemory-D5fSHXvZ.js +1 -0
  223. package/dist/chunks/sessionMemoryUtils-BWUztNh6.js +1 -0
  224. package/dist/chunks/sessionObserver-ChfQtK2m.js +1 -0
  225. package/dist/chunks/{sessionObserver-CSOYgsvH.js → sessionObserver-ShbCwJ8x.js} +1 -1
  226. package/dist/chunks/sessionStorage-Cf5wmnyB.js +1 -0
  227. package/dist/chunks/{sessionTitle-CLOlPZ_M.js → sessionTitle-coed9IuJ.js} +1 -1
  228. package/dist/chunks/{sessionTracing-D8wr9j4X.js → sessionTracing-D9rUyiq0.js} +1 -1
  229. package/dist/chunks/{settings-Dlp5JTa_.js → settings-BovzmwMP.js} +2 -2
  230. package/dist/chunks/{settingsSync-QWA0VZSu.js → settingsSync-PqU9XGJq.js} +1 -1
  231. package/dist/chunks/{setup-UI9uv2-K.js → setup-B_FOvNpp.js} +2 -2
  232. package/dist/chunks/{shadowedRuleDetection-CXsmUY2o.js → shadowedRuleDetection-D1wsAdpp.js} +1 -1
  233. package/dist/chunks/{sideQuestion-CHpOVzY5.js → sideQuestion-wSi38p81.js} +1 -1
  234. package/dist/chunks/sinks-BpcRrN_T.js +1 -0
  235. package/dist/chunks/{sinks-1hFrW9HK.js → sinks-C_Dl1p4K.js} +2 -2
  236. package/dist/chunks/{skill-learning-Ck17rwH8.js → skill-learning-B5tmc7EX.js} +1 -1
  237. package/dist/chunks/{skillChangeDetector-s0F9Yf9a.js → skillChangeDetector-DNqohXxz.js} +1 -1
  238. package/dist/chunks/{skillGapStore-BJ1h2LVr.js → skillGapStore-D-kQKVDZ.js} +1 -1
  239. package/dist/chunks/{skillGapStore-DyqNKuNy.js → skillGapStore-Df5BWAk5.js} +2 -2
  240. package/dist/chunks/{skillGenerator-BT8NGzXT.js → skillGenerator-DbcdpAkw.js} +2 -2
  241. package/dist/chunks/skillLearning-C5cXZE6_.js +1 -0
  242. package/dist/chunks/{skillLearning-Cn9Uw0Kd.js → skillLearning-ClRiDcJH.js} +1 -1
  243. package/dist/chunks/{skillPanel-N0GoWjIi.js → skillPanel-LBd4E-MM.js} +3 -3
  244. package/dist/chunks/{skillSearchPanel-CTwtgTzy.js → skillSearchPanel-CErRnUwo.js} +2 -2
  245. package/dist/chunks/{skills-Bv3lH-aA.js → skills-CBKhfg_a.js} +1 -1
  246. package/dist/chunks/{stats-C1Ff6w4i.js → stats-BY4dskVg.js} +1 -1
  247. package/dist/chunks/{status-DyXiBa0m.js → status-BnJIXtKl.js} +2 -2
  248. package/dist/chunks/{status-FD7HVYS7.js → status-DU-B4SMW.js} +1 -1
  249. package/dist/chunks/{statusNoticeHelpers-kTp9Rdk6.js → statusNoticeHelpers-CzTuGNuC.js} +1 -1
  250. package/dist/chunks/{tag-RzOSA5T0.js → tag-B-wVW9Aj.js} +1 -1
  251. package/dist/chunks/{tasks-eJrOcdhB.js → tasks-CBVL005y.js} +1 -1
  252. package/dist/chunks/{teleport-ABA-hdmP.js → teleport-dtqQXM4x.js} +1 -1
  253. package/dist/chunks/{templateJobs-BnOBSFtq.js → templateJobs-D6998LcG.js} +1 -1
  254. package/dist/chunks/{terminalSetup-BfvmoJaK.js → terminalSetup-0SBdyKF5.js} +1 -1
  255. package/dist/chunks/{terminalSetup-D_P5iZmq.js → terminalSetup-CuV-qU6v.js} +1 -1
  256. package/dist/chunks/{theme-S0kVMVt4.js → theme-p0AooruD.js} +1 -1
  257. package/dist/chunks/thinkback-Catprqs_.js +1 -0
  258. package/dist/chunks/{thinkback-HyW_R_88.js → thinkback-DI2NpvG-.js} +1 -1
  259. package/dist/chunks/{thinkback-play-H6md4czq.js → thinkback-play-CqrIRx2o.js} +1 -1
  260. package/dist/chunks/{toolEventObserver-BAFzvePj.js → toolEventObserver-DTccwC3c.js} +1 -1
  261. package/dist/chunks/{toolEventObserver--Z6jENks.js → toolEventObserver-DlH73w-S.js} +1 -1
  262. package/dist/chunks/{toolPool-CR61XXm3.js → toolPool-B64V-jmK.js} +1 -1
  263. package/dist/chunks/{trustedDevice-Dn4rXbxT.js → trustedDevice-BTYoQCkC.js} +1 -1
  264. package/dist/chunks/trustedDevice-CiwjT_Y6.js +1 -0
  265. package/dist/chunks/{ultrareviewCommand-mYDTBCFD.js → ultrareviewCommand-BDFUS3hf.js} +1 -1
  266. package/dist/chunks/undercover-XYapZ_SS.js +1 -0
  267. package/dist/chunks/{undercover-CdapzvNH.js → undercover-vuTpCnQJ.js} +2 -2
  268. package/dist/chunks/{updateCCB-DPShheOr.js → updateCCB-DFL5Wt_I.js} +1 -1
  269. package/dist/chunks/{upgrade-BOeakAP6.js → upgrade-D5qwcaWQ.js} +1 -1
  270. package/dist/chunks/upgrade-DIg3j929.js +1 -0
  271. package/dist/chunks/{upload-BXQsDtLW.js → upload-B_yADHX9.js} +1 -1
  272. package/dist/chunks/{usage-iNQzY960.js → usage-C0SnnC-i.js} +1 -1
  273. package/dist/chunks/usage-CYJKE8N6.js +1 -0
  274. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-CntByfTQ.js → useExitOnCtrlCDWithKeybindings-DKIqRraH.js} +1 -1
  275. package/dist/chunks/useMainLoopModel-XetDUXd-.js +1 -0
  276. package/dist/chunks/{useManagePlugins-B8HD0RUh.js → useManagePlugins-B2KhKiu5.js} +1 -1
  277. package/dist/chunks/{useMergedTools-DfchLQZC.js → useMergedTools-CKvwz_Zt.js} +1 -1
  278. package/dist/chunks/{useSearchInput-H-8hJeFD.js → useSearchInput-D1Vr2Js1.js} +1 -1
  279. package/dist/chunks/{useSettingsErrors-BF5i5Xju.js → useSettingsErrors-B7BXHchG.js} +1 -1
  280. package/dist/chunks/{util-CoicMvOv.js → util-BaDs-wL5.js} +1 -1
  281. package/dist/chunks/{validatePlugin-z2fcngf8.js → validatePlugin-DtiYlXby.js} +1 -1
  282. package/dist/chunks/{vim-DdvQlLDm.js → vim-C-icQDz1.js} +1 -1
  283. package/dist/chunks/{workerRegistry-CzqQwCHC.js → workerRegistry-ChqPPIaO.js} +1 -1
  284. package/dist/chunks/worktree-DAn8ooa1.js +1 -0
  285. package/dist/cli.js +1 -1
  286. package/package.json +1 -1
  287. package/dist/chunks/ApproveApiKey-CKfn7U1R.js +0 -1
  288. package/dist/chunks/ClaudeMdExternalIncludesDialog-TypH-X8e.js +0 -1
  289. package/dist/chunks/ConsoleOAuthFlow-wGQuFt41.js +0 -1
  290. package/dist/chunks/Doctor-CcJUwSQn.js +0 -1
  291. package/dist/chunks/Grove-DPkIjqg8.js +0 -1
  292. package/dist/chunks/Grove-Dsd7F39b.js +0 -11
  293. package/dist/chunks/PluginSettings-B0jbwB2M.js +0 -17
  294. package/dist/chunks/REPL-DlBJIPCw.js +0 -1
  295. package/dist/chunks/SearchExtraToolsTool-VP87ErGx.js +0 -1
  296. package/dist/chunks/api-BiwZmmsh.js +0 -1
  297. package/dist/chunks/auth-BQa4kzQo.js +0 -1
  298. package/dist/chunks/auth-UAJhZNmZ.js +0 -1
  299. package/dist/chunks/backgroundHousekeeping-BUUZ7Csq.js +0 -1
  300. package/dist/chunks/bridgeConfig-DWEqKbXk.js +0 -1
  301. package/dist/chunks/bridgeEnabled-CjVCMwnq.js +0 -1
  302. package/dist/chunks/bridgeMain-6lollTtZ.js +0 -1
  303. package/dist/chunks/caches-C46fa77L.js +0 -1
  304. package/dist/chunks/client-Bup0Sgcn.js +0 -1
  305. package/dist/chunks/commands-BdB1eFvP.js +0 -1
  306. package/dist/chunks/commitAttribution-D6J3NuhB.js +0 -1
  307. package/dist/chunks/config-Bxt1UH1T.js +0 -1
  308. package/dist/chunks/config-CjjXZfNi.js +0 -1
  309. package/dist/chunks/context-noninteractive-DvGo1l7b.js +0 -1
  310. package/dist/chunks/conversation-CH9ouFai.js +0 -1
  311. package/dist/chunks/createSession-DUfOAeyE.js +0 -1
  312. package/dist/chunks/doctor-7fgVhEKL.js +0 -1
  313. package/dist/chunks/envLessBridgeConfig-B2HYnEKo.js +0 -1
  314. package/dist/chunks/extra-usage-CLhv1Z4g.js +0 -1
  315. package/dist/chunks/extractMemories-B2IAvbXM.js +0 -1
  316. package/dist/chunks/fast-_G6zcFye.js +0 -1
  317. package/dist/chunks/firstPartyEventLogger-C9LzVy6y.js +0 -1
  318. package/dist/chunks/hooks-BUJLxdFJ.js +0 -1
  319. package/dist/chunks/hostGuard-C5xydXZI.js +0 -1
  320. package/dist/chunks/inboundAttachments-C0nMTtCi.js +0 -1
  321. package/dist/chunks/language-DfOAuDFc.js +0 -1
  322. package/dist/chunks/loadAgentsDir-DTbJJff-.js +0 -1
  323. package/dist/chunks/localSearch-DKv8PRLD.js +0 -1
  324. package/dist/chunks/model-BQF64tZx.js +0 -1
  325. package/dist/chunks/model-DvrvG6BB.js +0 -1
  326. package/dist/chunks/pluginStartupCheck-CoW7073W.js +0 -1
  327. package/dist/chunks/policyLimits-BkjgMQD0.js +0 -1
  328. package/dist/chunks/poorMode-qlxqU8Hm.js +0 -1
  329. package/dist/chunks/prompt-CN7gBNKS.js +0 -1
  330. package/dist/chunks/prompt-D-zHhqp8.js +0 -1
  331. package/dist/chunks/sandbox-adapter-LzTcKwBp.js +0 -1
  332. package/dist/chunks/searchExtraTools-CbJJQqzH.js +0 -1
  333. package/dist/chunks/sessionFileAccessHooks-B_nNW0zE.js +0 -1
  334. package/dist/chunks/sessionMemory-C4JAUZ6V.js +0 -1
  335. package/dist/chunks/sessionMemoryUtils-BlqAy8oR.js +0 -1
  336. package/dist/chunks/sessionObserver-DMvWci8-.js +0 -1
  337. package/dist/chunks/sessionStorage-Diyuvt20.js +0 -1
  338. package/dist/chunks/sinks-CXq8-7Qn.js +0 -1
  339. package/dist/chunks/skillLearning-1ZfYIzfL.js +0 -1
  340. package/dist/chunks/thinkback-C6gV2LpU.js +0 -1
  341. package/dist/chunks/trustedDevice-DUrFWupL.js +0 -1
  342. package/dist/chunks/undercover-k3JoOKAb.js +0 -1
  343. package/dist/chunks/upgrade-D7iGU0PQ.js +0 -1
  344. package/dist/chunks/usage-DbRdMJog.js +0 -1
  345. package/dist/chunks/useMainLoopModel-DHkRIgNs.js +0 -1
  346. package/dist/chunks/worktree-DMhP5T0p.js +0 -1
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./axios-DaWTGg7G.js";import{i as r,n as i,r as a,t as o}from"./lazySchema-DcIJE_0i.js";import{F as s,S as c,W as l,a as u,l as d,w as f,z as p}from"./debug-BrXObCdR.js";import{c as m,g as h}from"./config-3m_9zSrj.js";import{o as g,s as _}from"./log-BMCygSzM.js";import{l as v,u as y}from"./oauth-BqJqV-2M.js";import{Bt as b,Lr as x,Ot as S,Rr as C,_n as w,vn as T}from"./model-BQF64tZx.js";import{a as E,i as D}from"./detectRepository-BPr0VWNO.js";import{randomUUID as O}from"crypto";function k(e){return t.isAxiosError(e)?!e.response||e.response.status>=500:!1}async function A(e,n){let r;for(let i=0;i<=V;i++)try{return await t.get(e,n)}catch(e){if(r=e,!k(e))throw e;if(i>=V)throw d(`Teleport request failed after ${i+1} attempts: ${s(e)}`),e;let t=B[i]??2e3;d(`Teleport request failed (attempt ${i+1}/${V+1}), retrying in ${t}ms: ${s(e)}`),await T(t)}throw r}function j(e){return e===null||typeof e==`string`&&e.trim()===``}async function M(){let e=m(),t=process.env.ANTHROPIC_API_KEY?.trim()||e.workspaceApiKey?.trim();if(!t){let t=e.workspaceApiKey,n=j(t)?`Your workspace API key was cleared. `:`A workspace API key (sk-ant-api03-*) is required to use workspace endpoints (/v1/agents, /v1/vaults, /v1/memory_stores, /v1/skills). `;throw Error(n+`Set ANTHROPIC_API_KEY=<key> and restart. Obtain a key from https://console.anthropic.com/settings/keys. Subscription OAuth (claude.ai login) cannot reach these endpoints.`)}if(!t.startsWith(`sk-ant-api03-`))throw Error(`Workspace API key must start with sk-ant-api03-, got prefix "${t.slice(0,4)}...". Obtain a workspace API key from https://console.anthropic.com/settings/keys.`);return{apiKey:t}}async function N(){let e=S()?.accessToken;if(e===void 0)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await x();if(!t)throw Error(`Unable to get organization UUID`);return{accessToken:e,orgUUID:t}}async function P(){let{accessToken:e,orgUUID:t}=await N(),n=`${v().BASE_API_URL}/v1/sessions`;try{let r=await A(n,{headers:{...F(e),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":t}});if(r.status!==200)throw Error(`Failed to fetch code sessions: ${r.statusText}`);return r.data.data.map(e=>{let t=e.session_context.sources.find(e=>e.type===`git_repository`),n=null;if(t?.url){let e=E(t.url);if(e){let[r,i]=e.split(`/`);r&&i&&(n={name:i,owner:{login:r},default_branch:t.revision||void 0})}}return{id:e.id,title:e.title||`Untitled`,description:``,status:e.session_status,repo:n,turns:[],created_at:e.created_at,updated_at:e.updated_at}})}catch(e){throw _(l(e)),e}}function F(e){return{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,"anthropic-version":`2023-06-01`}}async function I(e){let{accessToken:n,orgUUID:r}=await N(),i=`${v().BASE_API_URL}/v1/sessions/${e}`,a={...F(n),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":r},o=await t.get(i,{headers:a,timeout:15e3,validateStatus:e=>e<500});if(o.status!==200){let t=o.data?.error?.message;throw o.status===404?Error(`Session not found: ${e}`):o.status===401?Error(`Session expired.`):Error(t||`Failed to fetch session: ${o.status} ${o.statusText}`)}return o.data}function L(e){return(e.session_context.outcomes?.find(e=>e.type===`git_repository`))?.git_info?.branches[0]}async function R(e,n,r){try{let{accessToken:i,orgUUID:a}=await N(),o=`${v().BASE_API_URL}/v1/sessions/${e}/events`,s={...F(i),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":a},c={events:[{uuid:r?.uuid??O(),session_id:e,type:`user`,parent_tool_use_id:null,message:{role:`user`,content:n}}]};d(`[sendEventToRemoteSession] Sending event to session ${e}`);let l=await t.post(o,c,{headers:s,validateStatus:e=>e<500,timeout:3e4});return l.status===200||l.status===201?(d(`[sendEventToRemoteSession] Successfully sent event to session ${e}`),!0):(d(`[sendEventToRemoteSession] Failed with status ${l.status}: ${f(l.data)}`),!1)}catch(e){return d(`[sendEventToRemoteSession] Error: ${s(e)}`),!1}}async function z(e,n){try{let{accessToken:r,orgUUID:i}=await N(),a=`${v().BASE_API_URL}/v1/sessions/${e}`,o={...F(r),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":i};d(`[updateSessionTitle] Updating title for session ${e}: "${n}"`);let s=await t.patch(a,{title:n},{headers:o,validateStatus:e=>e<500});return s.status===200?(d(`[updateSessionTitle] Successfully updated title for session ${e}`),!0):(d(`[updateSessionTitle] Failed with status ${s.status}: ${f(s.data)}`),!1)}catch(e){return d(`[updateSessionTitle] Error: ${s(e)}`),!1}}var B,V,H=e((()=>{n(),y(),C(),a(),b(),h(),u(),D(),p(),o(),g(),w(),c(),B=[2e3,4e3,8e3,16e3],V=B.length,i(()=>r.object({id:r.string(),title:r.string(),description:r.string(),status:r.enum([`idle`,`working`,`waiting`,`completed`,`archived`,`cancelled`,`rejected`]),repo:r.object({name:r.string(),owner:r.object({login:r.string()}),default_branch:r.string().optional()}).nullable(),turns:r.array(r.string()),created_at:r.string(),updated_at:r.string()}))}));export{F as a,j as c,R as d,z as f,L as i,N as l,P as n,H as o,I as r,k as s,A as t,M as u};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./axios-DaWTGg7G.js";import{i as r,n as i,r as a,t as o}from"./lazySchema-DcIJE_0i.js";import{F as s,S as c,W as l,a as u,l as d,w as f,z as p}from"./debug-BrXObCdR.js";import{c as m,g as h}from"./config-DmomySWC.js";import{o as g,s as _}from"./log-BMCygSzM.js";import{l as v,u as y}from"./oauth-BqJqV-2M.js";import{Bt as b,Lr as x,Ot as S,Rr as C,_n as w,vn as T}from"./model-CKkOnnnx.js";import{a as E,i as D}from"./detectRepository-BPr0VWNO.js";import{randomUUID as O}from"crypto";function k(e){return t.isAxiosError(e)?!e.response||e.response.status>=500:!1}async function A(e,n){let r;for(let i=0;i<=V;i++)try{return await t.get(e,n)}catch(e){if(r=e,!k(e))throw e;if(i>=V)throw d(`Teleport request failed after ${i+1} attempts: ${s(e)}`),e;let t=B[i]??2e3;d(`Teleport request failed (attempt ${i+1}/${V+1}), retrying in ${t}ms: ${s(e)}`),await T(t)}throw r}function j(e){return e===null||typeof e==`string`&&e.trim()===``}async function M(){let e=m(),t=process.env.ANTHROPIC_API_KEY?.trim()||e.workspaceApiKey?.trim();if(!t){let t=e.workspaceApiKey,n=j(t)?`Your workspace API key was cleared. `:`A workspace API key (sk-ant-api03-*) is required to use workspace endpoints (/v1/agents, /v1/vaults, /v1/memory_stores, /v1/skills). `;throw Error(n+`Set ANTHROPIC_API_KEY=<key> and restart. Obtain a key from https://console.anthropic.com/settings/keys. Subscription OAuth (claude.ai login) cannot reach these endpoints.`)}if(!t.startsWith(`sk-ant-api03-`))throw Error(`Workspace API key must start with sk-ant-api03-, got prefix "${t.slice(0,4)}...". Obtain a workspace API key from https://console.anthropic.com/settings/keys.`);return{apiKey:t}}async function N(){let e=S()?.accessToken;if(e===void 0)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await x();if(!t)throw Error(`Unable to get organization UUID`);return{accessToken:e,orgUUID:t}}async function P(){let{accessToken:e,orgUUID:t}=await N(),n=`${v().BASE_API_URL}/v1/sessions`;try{let r=await A(n,{headers:{...F(e),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":t}});if(r.status!==200)throw Error(`Failed to fetch code sessions: ${r.statusText}`);return r.data.data.map(e=>{let t=e.session_context.sources.find(e=>e.type===`git_repository`),n=null;if(t?.url){let e=E(t.url);if(e){let[r,i]=e.split(`/`);r&&i&&(n={name:i,owner:{login:r},default_branch:t.revision||void 0})}}return{id:e.id,title:e.title||`Untitled`,description:``,status:e.session_status,repo:n,turns:[],created_at:e.created_at,updated_at:e.updated_at}})}catch(e){throw _(l(e)),e}}function F(e){return{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,"anthropic-version":`2023-06-01`}}async function I(e){let{accessToken:n,orgUUID:r}=await N(),i=`${v().BASE_API_URL}/v1/sessions/${e}`,a={...F(n),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":r},o=await t.get(i,{headers:a,timeout:15e3,validateStatus:e=>e<500});if(o.status!==200){let t=o.data?.error?.message;throw o.status===404?Error(`Session not found: ${e}`):o.status===401?Error(`Session expired.`):Error(t||`Failed to fetch session: ${o.status} ${o.statusText}`)}return o.data}function L(e){return(e.session_context.outcomes?.find(e=>e.type===`git_repository`))?.git_info?.branches[0]}async function R(e,n,r){try{let{accessToken:i,orgUUID:a}=await N(),o=`${v().BASE_API_URL}/v1/sessions/${e}/events`,s={...F(i),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":a},c={events:[{uuid:r?.uuid??O(),session_id:e,type:`user`,parent_tool_use_id:null,message:{role:`user`,content:n}}]};d(`[sendEventToRemoteSession] Sending event to session ${e}`);let l=await t.post(o,c,{headers:s,validateStatus:e=>e<500,timeout:3e4});return l.status===200||l.status===201?(d(`[sendEventToRemoteSession] Successfully sent event to session ${e}`),!0):(d(`[sendEventToRemoteSession] Failed with status ${l.status}: ${f(l.data)}`),!1)}catch(e){return d(`[sendEventToRemoteSession] Error: ${s(e)}`),!1}}async function z(e,n){try{let{accessToken:r,orgUUID:i}=await N(),a=`${v().BASE_API_URL}/v1/sessions/${e}`,o={...F(r),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":i};d(`[updateSessionTitle] Updating title for session ${e}: "${n}"`);let s=await t.patch(a,{title:n},{headers:o,validateStatus:e=>e<500});return s.status===200?(d(`[updateSessionTitle] Successfully updated title for session ${e}`),!0):(d(`[updateSessionTitle] Failed with status ${s.status}: ${f(s.data)}`),!1)}catch(e){return d(`[updateSessionTitle] Error: ${s(e)}`),!1}}var B,V,H=e((()=>{n(),y(),C(),a(),b(),h(),u(),D(),p(),o(),g(),w(),c(),B=[2e3,4e3,8e3,16e3],V=B.length,i(()=>r.object({id:r.string(),title:r.string(),description:r.string(),status:r.enum([`idle`,`working`,`waiting`,`completed`,`archived`,`cancelled`,`rejected`]),repo:r.object({name:r.string(),owner:r.object({login:r.string()}),default_branch:r.string().optional()}).nullable(),turns:r.array(r.string()),created_at:r.string(),updated_at:r.string()}))}));export{F as a,j as c,R as d,z as f,L as i,N as l,P as n,H as o,I as r,k as s,A as t,M as u};
@@ -1 +1 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Gt as n,I as r,P as i,_ as a,fi as o,t as s,y as c}from"./src-CDCSSo0U2.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{H as u,Pn as d,en as f}from"./state-ix0xIunV.js";import{_x as p,bx as m}from"./loadAgentsDir-Clu7Uk6a.js";import{_ as h,r as g}from"./git-Do0wJvux.js";import{u as _}from"./referral-BlrMpBAV.js";import{t as v}from"./Dialog-vfLXEPed.js";import{t as y}from"./ListItem-vfLXEPed.js";import{i as b,o as x,t as S}from"./cliLaunch-BkPAatcs.js";import{resolve as C}from"path";async function w(){let e=process.cwd();return g(e)||C(e)}function T({defaultDir:e,onInstalled:t,onCancel:o,onError:s}){m(`assistant-install-wizard`);let[l,u]=(0,D.useState)(0),[d,f]=(0,D.useState)(!1);n({"select:next":()=>u(e=>(e+1)%2),"select:previous":()=>u(e=>(e-1+2)%2),"select:accept":()=>{l===0?p():o()}},{context:`Select`});function p(){if(d)return;f(!0);let n=e||C(`.`);try{let e=x(S([`daemon`,`start`,`--dir=${n}`]),{cwd:n,stdio:`ignore`,detached:!0});e.unref(),e.on(`error`,e=>{s(`Failed to start daemon: ${e.message}`)}),setTimeout(()=>{t(n)},1500)}catch(e){s(`Failed to start daemon: ${e instanceof Error?e.message:String(e)}`)}}return d?(0,O.jsx)(c,{title:`Assistant Setup`,onCancel:o,hideInputGuide:!0,children:(0,O.jsxs)(i,{children:[`Starting daemon in `,e,`...`]})}):(0,O.jsx)(c,{title:`Assistant Setup`,onCancel:o,hideInputGuide:!0,children:(0,O.jsxs)(r,{flexDirection:`column`,gap:1,children:[(0,O.jsx)(i,{children:`No active assistant sessions found.`}),(0,O.jsxs)(i,{children:[`Start a daemon in `,(0,O.jsx)(i,{bold:!0,children:e||`.`}),` to create a cloud session?`]}),(0,O.jsxs)(r,{flexDirection:`column`,children:[(0,O.jsx)(a,{isFocused:l===0,children:(0,O.jsx)(i,{children:`Start assistant daemon`})}),(0,O.jsx)(a,{isFocused:l===1,children:(0,O.jsx)(i,{children:`Cancel`})})]}),(0,O.jsx)(i,{dimColor:!0,children:`Enter to select · Esc to cancel`})]})})}async function E(e,t,n){let{setAppState:r,getAppState:i}=t;return u()?(i().assistantPanelVisible?(r(e=>({...e,assistantPanelVisible:!1})),e(`Assistant panel hidden.`,{display:`system`})):(r(e=>({...e,assistantPanelVisible:!0})),e(`Assistant panel opened.`,{display:`system`})),null):(d(!0),r(e=>({...e,kairosEnabled:!0,assistantPanelVisible:!0})),e(`KAIROS assistant mode activated.`,{display:`system`}),null)}var D,O;e((()=>{o(),D=t(o(),1),s(),v(),y(),p(),_(),h(),b(),f(),O=l()}))();export{T as NewInstallWizard,E as call,w as computeDefaultInstallDir};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Gt as n,I as r,P as i,_ as a,fi as o,t as s,y as c}from"./src-CDCSSo0U2.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{H as u,Pn as d,en as f}from"./state-ix0xIunV.js";import{_x as p,bx as m}from"./loadAgentsDir-D206qwP3.js";import{_ as h,r as g}from"./git-Do0wJvux.js";import{u as _}from"./referral-CUaIo_vT.js";import{t as v}from"./Dialog-vfLXEPed.js";import{t as y}from"./ListItem-vfLXEPed.js";import{i as b,o as x,t as S}from"./cliLaunch-BkPAatcs.js";import{resolve as C}from"path";async function w(){let e=process.cwd();return g(e)||C(e)}function T({defaultDir:e,onInstalled:t,onCancel:o,onError:s}){m(`assistant-install-wizard`);let[l,u]=(0,D.useState)(0),[d,f]=(0,D.useState)(!1);n({"select:next":()=>u(e=>(e+1)%2),"select:previous":()=>u(e=>(e-1+2)%2),"select:accept":()=>{l===0?p():o()}},{context:`Select`});function p(){if(d)return;f(!0);let n=e||C(`.`);try{let e=x(S([`daemon`,`start`,`--dir=${n}`]),{cwd:n,stdio:`ignore`,detached:!0});e.unref(),e.on(`error`,e=>{s(`Failed to start daemon: ${e.message}`)}),setTimeout(()=>{t(n)},1500)}catch(e){s(`Failed to start daemon: ${e instanceof Error?e.message:String(e)}`)}}return d?(0,O.jsx)(c,{title:`Assistant Setup`,onCancel:o,hideInputGuide:!0,children:(0,O.jsxs)(i,{children:[`Starting daemon in `,e,`...`]})}):(0,O.jsx)(c,{title:`Assistant Setup`,onCancel:o,hideInputGuide:!0,children:(0,O.jsxs)(r,{flexDirection:`column`,gap:1,children:[(0,O.jsx)(i,{children:`No active assistant sessions found.`}),(0,O.jsxs)(i,{children:[`Start a daemon in `,(0,O.jsx)(i,{bold:!0,children:e||`.`}),` to create a cloud session?`]}),(0,O.jsxs)(r,{flexDirection:`column`,children:[(0,O.jsx)(a,{isFocused:l===0,children:(0,O.jsx)(i,{children:`Start assistant daemon`})}),(0,O.jsx)(a,{isFocused:l===1,children:(0,O.jsx)(i,{children:`Cancel`})})]}),(0,O.jsx)(i,{dimColor:!0,children:`Enter to select · Esc to cancel`})]})})}async function E(e,t,n){let{setAppState:r,getAppState:i}=t;return u()?(i().assistantPanelVisible?(r(e=>({...e,assistantPanelVisible:!1})),e(`Assistant panel hidden.`,{display:`system`})):(r(e=>({...e,assistantPanelVisible:!0})),e(`Assistant panel opened.`,{display:`system`})),null):(d(!0),r(e=>({...e,kairosEnabled:!0,assistantPanelVisible:!0})),e(`KAIROS assistant mode activated.`,{display:`system`}),null)}var D,O;e((()=>{o(),D=t(o(),1),s(),v(),y(),p(),_(),h(),b(),f(),O=l()}))();export{T as NewInstallWizard,E as call,w as computeDefaultInstallDir};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./auth-BnSrKyJe.js";export{t as authLogin,e as authStatus};
@@ -1,4 +1,4 @@
1
- import{d as e,o as t}from"./envUtils-DSxRz_kt.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{n as i,t as a}from"./axios-DaWTGg7G.js";import{Ba as o,Va as s}from"./loadAgentsDir-Clu7Uk6a.js";import{F as c,S as l,a as u,l as d,w as f,z as p}from"./debug-BrXObCdR.js";import{g as ee,n as te}from"./settings-Dlp5JTa_.js";import{b as m,c as ne,g as h}from"./config-3m_9zSrj.js";import{o as g,s as _}from"./log-BMCygSzM.js";import{n as v,r as y}from"./analytics-BotDBGh0.js";import{l as b,u as x}from"./oauth-BqJqV-2M.js";import{$n as S,Br as C,Bt as w,Cn as T,Dt as E,En as re,Fr as ie,Ft as ae,Hr as oe,Ir as se,Kr as D,Mr as O,Nr as k,Ot as A,Pr as j,Rr as M,Si as N,Sn as P,St as F,Ur as I,Wr as L,ar as R,fn as z,gn as B,jn as V,jt as H,mn as U,nn as W,or as G,pn as K,qr as ce,rr as le,un as ue,wi as de,yt as q}from"./model-BQF64tZx.js";import{P as fe,W as J}from"./rcDebugLog-VKwMl0yg.js";import{d as pe,u as me}from"./firstPartyEventLogger-BNGPPBNP.js";import{n as he,t as ge}from"./browser-BmZuQom6.js";import{n as _e}from"./trustedDevice-Dn4rXbxT.js";import{a as ve,i as ye,r as be}from"./grove-DrBVaZSN.js";import{t as xe}from"./remoteManagedSettings-jZ6u8ZBT.js";import{d as Se,n as Ce,t as we}from"./status-DyXiBa0m.js";import{createHash as Te,randomBytes as Y}from"crypto";import{createServer as Ee}from"http";ve(),s(),w(),V(),h(),T(),B(),me();async function X(){A.cache?.clear?.(),_e(),re(),U(),pe(),be.cache?.clear?.(),ye.cache?.clear?.(),await xe(),await o()}async function De({clearOnboarding:e=!1}){let{flushTelemetry:t}=await import(`./instrumentation-CLZttr_u.js`);await t(),await ue(),P().delete(),await X(),m(t=>{let n={...t};return e&&(n.hasCompletedOnboarding=!1,n.subscriptionNoticeCount=0,n.hasAvailableSubscription=!1,n.customApiKeyResponses?.approved&&(n.customApiKeyResponses={...n.customApiKeyResponses,approved:[]})),n.oauthAccount=void 0,n})}t(),n(),p(),l(),u(),v(),ee(),de(),ce(),M(),fe(),a(),x(),h(),le(),g(),G();async function Oe(){try{if(ne().claudeCodeFirstTokenDate!==void 0)return;let e=S();if(e.error){_(Error(`Failed to get auth headers: ${e.error}`));return}let t=`${b().BASE_API_URL}/api/organization/claude_code_first_token_date`,n=(await i.get(t,{headers:{...e.headers,"User-Agent":R()},timeout:1e4})).data?.first_token_date??null;if(n!==null){let e=new Date(n).getTime();if(isNaN(e)){_(Error(`Received invalid first_token_date from API: ${n}`));return}}m(e=>({...e,claudeCodeFirstTokenDate:n}))}catch(e){_(e)}}ge(),x(),g();var ke=class{constructor(e=`/callback`){r(this,`localServer`,void 0),r(this,`port`,0),r(this,`promiseResolver`,null),r(this,`promiseRejecter`,null),r(this,`expectedState`,null),r(this,`pendingResponse`,null),r(this,`callbackPath`,void 0),this.localServer=Ee(),this.callbackPath=e}async start(e){return new Promise((t,n)=>{this.localServer.once(`error`,e=>{n(Error(`Failed to start OAuth callback server: ${e.message}`))}),this.localServer.listen(e??0,`localhost`,()=>{let e=this.localServer.address();this.port=e.port,t(this.port)})})}getPort(){return this.port}hasPendingResponse(){return this.pendingResponse!==null}async waitForAuthorization(e,t){return new Promise((n,r)=>{this.promiseResolver=n,this.promiseRejecter=r,this.expectedState=e,this.startLocalListener(t)})}handleSuccessRedirect(e,t){if(!this.pendingResponse)return;if(t){t(this.pendingResponse,e),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect`,{custom_handler:!0});return}let n=I(e)?b().CLAUDEAI_SUCCESS_URL:b().CONSOLE_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:n}),this.pendingResponse.end(),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect`,{})}handleErrorRedirect(){if(!this.pendingResponse)return;let e=b().CLAUDEAI_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:e}),this.pendingResponse.end(),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect_error`,{})}startLocalListener(e){this.localServer.on(`request`,this.handleRedirect.bind(this)),this.localServer.on(`error`,this.handleError.bind(this)),e()}handleRedirect(e,t){let n=new URL(e.url||``,`http://${e.headers.host||`localhost`}`);if(n.pathname!==this.callbackPath){t.writeHead(404),t.end();return}let r=n.searchParams.get(`code`)??void 0,i=n.searchParams.get(`state`)??void 0;this.validateAndRespond(r,i,t)}validateAndRespond(e,t,n){if(!e){n.writeHead(400),n.end(`Authorization code not found`),this.reject(Error(`No authorization code received`));return}if(t!==this.expectedState){n.writeHead(400),n.end(`Invalid state parameter`),this.reject(Error(`Invalid state parameter`));return}this.pendingResponse=n,this.resolve(e)}handleError(e){_(e),this.close(),this.reject(e)}resolve(e){this.promiseResolver&&(this.promiseResolver(e),this.promiseResolver=null,this.promiseRejecter=null)}reject(e){this.promiseRejecter&&(this.promiseRejecter(e),this.promiseResolver=null,this.promiseRejecter=null)}close(){this.pendingResponse&&this.handleErrorRedirect(),this.localServer&&(this.localServer.removeAllListeners(),this.localServer.close())}};function Z(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Ae(){return Z(Y(32))}function je(e){let t=Te(`sha256`);return t.update(e),Z(t.digest())}function Me(){return Z(Y(32))}v(),M(),n();var Q=class{constructor(){r(this,`codeVerifier`,void 0),r(this,`authCodeListener`,null),r(this,`port`,null),r(this,`manualAuthCodeResolver`,null),this.codeVerifier=Ae()}async startOAuthFlow(e,t){this.authCodeListener=new ke,this.port=await this.authCodeListener.start();let n=je(this.codeVerifier),r=Me(),i={codeChallenge:n,state:r,port:this.port,loginWithClaudeAi:t?.loginWithClaudeAi,inferenceOnly:t?.inferenceOnly,orgUUID:t?.orgUUID,loginHint:t?.loginHint,loginMethod:t?.loginMethod},a=O({...i,isManual:!0}),o=O({...i,isManual:!1}),s=await this.waitForAuthorizationCode(r,async()=>{t?.skipBrowserOpen?await e(a,o):(await e(a),await he(o))}),c=this.authCodeListener?.hasPendingResponse()??!1;y(`tengu_oauth_auth_code_received`,{automatic:c});try{let e=await j(s,r,this.codeVerifier,this.port,!c,t?.expiresIn),n=await se(e.access_token);if(c){let t=C(e.scope);this.authCodeListener?.handleSuccessRedirect(t)}return this.formatTokens(e,n.subscriptionType,n.rateLimitTier,n.rawProfile)}catch(e){throw c&&this.authCodeListener?.handleErrorRedirect(),e}finally{this.authCodeListener?.close()}}async waitForAuthorizationCode(e,t){return new Promise((n,r)=>{this.manualAuthCodeResolver=n,this.authCodeListener?.waitForAuthorization(e,t).then(e=>{this.manualAuthCodeResolver=null,n(e)}).catch(e=>{this.manualAuthCodeResolver=null,r(e)})})}handleManualAuthCodeInput(e){this.manualAuthCodeResolver&&(this.manualAuthCodeResolver(e.authorizationCode),this.manualAuthCodeResolver=null,this.authCodeListener?.close())}formatTokens(e,t,n,r){return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:Date.now()+e.expires_in*1e3,scopes:C(e.scope),subscriptionType:t,rateLimitTier:n,profile:r,tokenAccount:e.account?{uuid:e.account.uuid,emailAddress:e.account.email_address,organizationUuid:e.organization?.uuid}:void 0}}cleanup(){this.authCodeListener?.close(),this.manualAuthCodeResolver=null}};v(),M(),w(),h(),g(),Se();async function $(e){await De({clearOnboarding:!1});let t=e.profile??await D(e.accessToken);t?L({accountUuid:t.account.uuid,emailAddress:t.account.email,organizationUuid:t.organization.uuid,displayName:t.account.display_name||void 0,hasExtraUsageEnabled:t.organization.has_extra_usage_enabled??void 0,billingType:t.organization.billing_type??void 0,subscriptionCreatedAt:t.organization.subscription_created_at??void 0,accountCreatedAt:t.account.created_at}):e.tokenAccount&&L({accountUuid:e.tokenAccount.uuid,emailAddress:e.tokenAccount.emailAddress,organizationUuid:e.tokenAccount.organizationUuid});let n=z(e);if(q(),n.warning&&y(`tengu_oauth_storage_warning`,{warning:n.warning}),await ie(e.accessToken).catch(e=>d(String(e),{level:`error`})),I(e.scopes))await Oe().catch(e=>d(String(e),{level:`error`}));else if(!await k(e.accessToken))throw Error(`Unable to create API key. The server accepted the request but did not return a key.`);await X()}async function Ne({email:e,sso:t,console:n,claudeai:r}){n&&r&&(process.stderr.write(`Error: --console and --claudeai cannot be used together.
1
+ import{d as e,o as t}from"./envUtils-DSxRz_kt.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{n as i,t as a}from"./axios-DaWTGg7G.js";import{Ba as o,Va as s}from"./loadAgentsDir-D206qwP3.js";import{F as c,S as l,a as u,l as d,w as f,z as p}from"./debug-BrXObCdR.js";import{g as ee,n as te}from"./settings-BovzmwMP.js";import{b as m,c as ne,g as h}from"./config-DmomySWC.js";import{o as g,s as _}from"./log-BMCygSzM.js";import{n as v,r as y}from"./analytics-BotDBGh0.js";import{l as b,u as x}from"./oauth-BqJqV-2M.js";import{$n as S,Br as C,Bt as w,Cn as T,Dt as E,En as re,Fr as ie,Ft as ae,Hr as oe,Ir as se,Kr as D,Mr as O,Nr as k,Ot as A,Pr as j,Rr as M,Si as N,Sn as P,St as F,Ur as I,Wr as L,ar as R,fn as z,gn as B,jn as V,jt as H,mn as U,nn as W,or as G,pn as K,qr as ce,rr as le,un as ue,wi as de,yt as q}from"./model-CKkOnnnx.js";import{P as fe,W as J}from"./rcDebugLog-CUy1_F23.js";import{d as pe,u as me}from"./firstPartyEventLogger-CoSUd0a1.js";import{n as he,t as ge}from"./browser-BmZuQom6.js";import{n as _e}from"./trustedDevice-BTYoQCkC.js";import{a as ve,i as ye,r as be}from"./grove-CpqjcGCb.js";import{t as xe}from"./remoteManagedSettings-Cq994lyc.js";import{d as Se,n as Ce,t as we}from"./status-BnJIXtKl.js";import{createHash as Te,randomBytes as Y}from"crypto";import{createServer as Ee}from"http";ve(),s(),w(),V(),h(),T(),B(),me();async function X(){A.cache?.clear?.(),_e(),re(),U(),pe(),be.cache?.clear?.(),ye.cache?.clear?.(),await xe(),await o()}async function De({clearOnboarding:e=!1}){let{flushTelemetry:t}=await import(`./instrumentation-Bw3CxPQf.js`);await t(),await ue(),P().delete(),await X(),m(t=>{let n={...t};return e&&(n.hasCompletedOnboarding=!1,n.subscriptionNoticeCount=0,n.hasAvailableSubscription=!1,n.customApiKeyResponses?.approved&&(n.customApiKeyResponses={...n.customApiKeyResponses,approved:[]})),n.oauthAccount=void 0,n})}t(),n(),p(),l(),u(),v(),ee(),de(),ce(),M(),fe(),a(),x(),h(),le(),g(),G();async function Oe(){try{if(ne().claudeCodeFirstTokenDate!==void 0)return;let e=S();if(e.error){_(Error(`Failed to get auth headers: ${e.error}`));return}let t=`${b().BASE_API_URL}/api/organization/claude_code_first_token_date`,n=(await i.get(t,{headers:{...e.headers,"User-Agent":R()},timeout:1e4})).data?.first_token_date??null;if(n!==null){let e=new Date(n).getTime();if(isNaN(e)){_(Error(`Received invalid first_token_date from API: ${n}`));return}}m(e=>({...e,claudeCodeFirstTokenDate:n}))}catch(e){_(e)}}ge(),x(),g();var ke=class{constructor(e=`/callback`){r(this,`localServer`,void 0),r(this,`port`,0),r(this,`promiseResolver`,null),r(this,`promiseRejecter`,null),r(this,`expectedState`,null),r(this,`pendingResponse`,null),r(this,`callbackPath`,void 0),this.localServer=Ee(),this.callbackPath=e}async start(e){return new Promise((t,n)=>{this.localServer.once(`error`,e=>{n(Error(`Failed to start OAuth callback server: ${e.message}`))}),this.localServer.listen(e??0,`localhost`,()=>{let e=this.localServer.address();this.port=e.port,t(this.port)})})}getPort(){return this.port}hasPendingResponse(){return this.pendingResponse!==null}async waitForAuthorization(e,t){return new Promise((n,r)=>{this.promiseResolver=n,this.promiseRejecter=r,this.expectedState=e,this.startLocalListener(t)})}handleSuccessRedirect(e,t){if(!this.pendingResponse)return;if(t){t(this.pendingResponse,e),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect`,{custom_handler:!0});return}let n=I(e)?b().CLAUDEAI_SUCCESS_URL:b().CONSOLE_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:n}),this.pendingResponse.end(),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect`,{})}handleErrorRedirect(){if(!this.pendingResponse)return;let e=b().CLAUDEAI_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:e}),this.pendingResponse.end(),this.pendingResponse=null,y(`tengu_oauth_automatic_redirect_error`,{})}startLocalListener(e){this.localServer.on(`request`,this.handleRedirect.bind(this)),this.localServer.on(`error`,this.handleError.bind(this)),e()}handleRedirect(e,t){let n=new URL(e.url||``,`http://${e.headers.host||`localhost`}`);if(n.pathname!==this.callbackPath){t.writeHead(404),t.end();return}let r=n.searchParams.get(`code`)??void 0,i=n.searchParams.get(`state`)??void 0;this.validateAndRespond(r,i,t)}validateAndRespond(e,t,n){if(!e){n.writeHead(400),n.end(`Authorization code not found`),this.reject(Error(`No authorization code received`));return}if(t!==this.expectedState){n.writeHead(400),n.end(`Invalid state parameter`),this.reject(Error(`Invalid state parameter`));return}this.pendingResponse=n,this.resolve(e)}handleError(e){_(e),this.close(),this.reject(e)}resolve(e){this.promiseResolver&&(this.promiseResolver(e),this.promiseResolver=null,this.promiseRejecter=null)}reject(e){this.promiseRejecter&&(this.promiseRejecter(e),this.promiseResolver=null,this.promiseRejecter=null)}close(){this.pendingResponse&&this.handleErrorRedirect(),this.localServer&&(this.localServer.removeAllListeners(),this.localServer.close())}};function Z(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Ae(){return Z(Y(32))}function je(e){let t=Te(`sha256`);return t.update(e),Z(t.digest())}function Me(){return Z(Y(32))}v(),M(),n();var Q=class{constructor(){r(this,`codeVerifier`,void 0),r(this,`authCodeListener`,null),r(this,`port`,null),r(this,`manualAuthCodeResolver`,null),this.codeVerifier=Ae()}async startOAuthFlow(e,t){this.authCodeListener=new ke,this.port=await this.authCodeListener.start();let n=je(this.codeVerifier),r=Me(),i={codeChallenge:n,state:r,port:this.port,loginWithClaudeAi:t?.loginWithClaudeAi,inferenceOnly:t?.inferenceOnly,orgUUID:t?.orgUUID,loginHint:t?.loginHint,loginMethod:t?.loginMethod},a=O({...i,isManual:!0}),o=O({...i,isManual:!1}),s=await this.waitForAuthorizationCode(r,async()=>{t?.skipBrowserOpen?await e(a,o):(await e(a),await he(o))}),c=this.authCodeListener?.hasPendingResponse()??!1;y(`tengu_oauth_auth_code_received`,{automatic:c});try{let e=await j(s,r,this.codeVerifier,this.port,!c,t?.expiresIn),n=await se(e.access_token);if(c){let t=C(e.scope);this.authCodeListener?.handleSuccessRedirect(t)}return this.formatTokens(e,n.subscriptionType,n.rateLimitTier,n.rawProfile)}catch(e){throw c&&this.authCodeListener?.handleErrorRedirect(),e}finally{this.authCodeListener?.close()}}async waitForAuthorizationCode(e,t){return new Promise((n,r)=>{this.manualAuthCodeResolver=n,this.authCodeListener?.waitForAuthorization(e,t).then(e=>{this.manualAuthCodeResolver=null,n(e)}).catch(e=>{this.manualAuthCodeResolver=null,r(e)})})}handleManualAuthCodeInput(e){this.manualAuthCodeResolver&&(this.manualAuthCodeResolver(e.authorizationCode),this.manualAuthCodeResolver=null,this.authCodeListener?.close())}formatTokens(e,t,n,r){return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:Date.now()+e.expires_in*1e3,scopes:C(e.scope),subscriptionType:t,rateLimitTier:n,profile:r,tokenAccount:e.account?{uuid:e.account.uuid,emailAddress:e.account.email_address,organizationUuid:e.organization?.uuid}:void 0}}cleanup(){this.authCodeListener?.close(),this.manualAuthCodeResolver=null}};v(),M(),w(),h(),g(),Se();async function $(e){await De({clearOnboarding:!1});let t=e.profile??await D(e.accessToken);t?L({accountUuid:t.account.uuid,emailAddress:t.account.email,organizationUuid:t.organization.uuid,displayName:t.account.display_name||void 0,hasExtraUsageEnabled:t.organization.has_extra_usage_enabled??void 0,billingType:t.organization.billing_type??void 0,subscriptionCreatedAt:t.organization.subscription_created_at??void 0,accountCreatedAt:t.account.created_at}):e.tokenAccount&&L({accountUuid:e.tokenAccount.uuid,emailAddress:e.tokenAccount.emailAddress,organizationUuid:e.tokenAccount.organizationUuid});let n=z(e);if(q(),n.warning&&y(`tengu_oauth_storage_warning`,{warning:n.warning}),await ie(e.accessToken).catch(e=>d(String(e),{level:`error`})),I(e.scopes))await Oe().catch(e=>d(String(e),{level:`error`}));else if(!await k(e.accessToken))throw Error(`Unable to create API key. The server accepted the request but did not return a key.`);await X()}async function Ne({email:e,sso:t,console:n,claudeai:r}){n&&r&&(process.stderr.write(`Error: --console and --claudeai cannot be used together.
2
2
  `),process.exit(1));let i=te(),a=i.forceLoginMethod?i.forceLoginMethod===`claudeai`:!n,o=i.forceLoginOrgUUID,s=process.env.CLAUDE_CODE_OAUTH_REFRESH_TOKEN;if(s){let e=process.env.CLAUDE_CODE_OAUTH_SCOPES;e||(process.stderr.write(`CLAUDE_CODE_OAUTH_SCOPES is required when using CLAUDE_CODE_OAUTH_REFRESH_TOKEN.
3
3
  Set it to the space-separated scopes the refresh token was issued with
4
4
  (e.g. "user:inference" or "user:profile user:inference user:sessions:claude_code user:mcp_servers").
@@ -0,0 +1 @@
1
+ import{Bt as e,It as t,Ot as n,mt as r,yt as i}from"./model-CKkOnnnx.js";e();export{r as checkAndRefreshOAuthTokenIfNeeded,i as clearOAuthTokenCache,n as getClaudeAIOAuthTokens,t as handleOAuth401Error};
@@ -1,4 +1,4 @@
1
- import{Fh as e,Mh as t,Nh as n,Ph as r,jh as i}from"./loadAgentsDir-Clu7Uk6a.js";import{F as a,S as o,w as s,z as c}from"./debug-BrXObCdR.js";import{g as l,t as u}from"./settings-Dlp5JTa_.js";import{C as d,_ as f,h as p,u as m}from"./model-BQF64tZx.js";import{n as h,t as g}from"./poorMode-1NLYiS3Y.js";c(),f(),n(),l(),g(),r(),o();function _(e){process.stdout.write(s(e,null,2)+`
1
+ import{Fh as e,Mh as t,Nh as n,Ph as r,jh as i}from"./loadAgentsDir-D206qwP3.js";import{F as a,S as o,w as s,z as c}from"./debug-BrXObCdR.js";import{g as l,t as u}from"./settings-BovzmwMP.js";import{C as d,_ as f,h as p,u as m}from"./model-CKkOnnnx.js";import{n as h,t as g}from"./poorMode-DhzFKpPl.js";c(),f(),n(),l(),g(),r(),o();function _(e){process.stdout.write(s(e,null,2)+`
2
2
  `)}function v(){_(t())}function y(){let e=u(),n=t();_({allow:e?.allow?.length?e.allow:n.allow,soft_deny:e?.soft_deny?.length?e.soft_deny:n.soft_deny,environment:e?.environment?.length?e.environment:n.environment})}var b=`You are an expert reviewer of auto mode classifier rules for Work Mate.
3
3
 
4
4
  Work Mate has an "auto mode" that uses an AI classifier to decide whether tool calls should be auto-approved or require user confirmation. Users can write custom rules in three categories:
@@ -1 +1 @@
1
- import{a as e,c as t,i as n,m as r,n as i,o as a,r as o,t as s}from"./autonomy-Cg5zweUa.js";r();export{s as autonomyFlowCancelHandler,i as autonomyFlowHandler,o as autonomyFlowResumeHandler,n as autonomyFlowsHandler,e as autonomyRunsHandler,a as autonomyStatusHandler,t as getAutonomyCommandText};
1
+ import{a as e,c as t,i as n,m as r,n as i,o as a,r as o,t as s}from"./autonomy-DGcy5Rml.js";r();export{s as autonomyFlowCancelHandler,i as autonomyFlowHandler,o as autonomyFlowResumeHandler,n as autonomyFlowsHandler,e as autonomyRunsHandler,a as autonomyStatusHandler,t as getAutonomyCommandText};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{en as t,ot as n}from"./state-ix0xIunV.js";import{C as r,CT as i,E as a,OT as ee,PT as o,ST as s,_T as te,bT as c,dT as l,dd as u,fT as d,fd as ne,gT as f,hT as p,mT as m,pT as h,ud as g,vT as _,x as re,xT as v,yT as y,zT as ie}from"./loadAgentsDir-Clu7Uk6a.js";import{s as ae,u as oe}from"./types-C-MRCL8J.js";import{a as se,n as ce,o as le,t as ue}from"./bridgeConfig-5p_w4s5r.js";import{i as b,o as x}from"./bg-WnYN5ifx.js";import{n as S,t as C}from"./state-Cn_m2NOf.js";import{n as w,r as T}from"./pipeTransport-CqCnc-Ys.js";import{join as E}from"path";import"crypto";import{readFile as D,readdir as O}from"fs/promises";function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e){return typeof e==`string`&&z.includes(e)}function j(e){return typeof e==`string`&&B.includes(e)}function M(e){return!k(e)||typeof e.name!=`string`||!j(e.status)?null:{name:e.name,...typeof e.prompt==`string`?{prompt:e.prompt}:{},status:e.status,...typeof e.startedAt==`number`?{startedAt:e.startedAt}:{},...typeof e.completedAt==`number`?{completedAt:e.completedAt}:{}}}function N(e){if(!k(e)||typeof e.runId!=`string`||typeof e.workflow!=`string`||!A(e.status)||typeof e.createdAt!=`number`||typeof e.updatedAt!=`number`||typeof e.currentStepIndex!=`number`||!Array.isArray(e.steps))return null;let t=e.steps.map(M).filter(e=>e!==null);return t.length===e.steps.length?{runId:e.runId,workflow:e.workflow,...typeof e.args==`string`?{args:e.args}:{},status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,currentStepIndex:e.currentStepIndex,steps:t}:null}async function P(e,t){try{return N(oe(await D(E(e,L,`${t}.json`),`utf-8`),!1))}catch{return null}}async function F(e=n()){let t;try{t=await O(E(e,L))}catch{return[]}let r=t.filter(e=>e.endsWith(`.json`));return(await Promise.all(r.slice(0,R).map(t=>P(e,t.slice(0,-5))))).filter(e=>e!==null).sort((e,t)=>t.updatedAt-e.updatedAt)}function I(e){if(e.length===0)return[`Workflow runs: 0`,` none`].join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{en as t,ot as n}from"./state-ix0xIunV.js";import{C as r,CT as i,E as a,OT as ee,PT as o,ST as s,_T as te,bT as c,dT as l,dd as u,fT as d,fd as ne,gT as f,hT as p,mT as m,pT as h,ud as g,vT as _,x as re,xT as v,yT as y,zT as ie}from"./loadAgentsDir-D206qwP3.js";import{s as ae,u as oe}from"./types-C-MRCL8J.js";import{a as se,n as ce,o as le,t as ue}from"./bridgeConfig-BhxRF2vm.js";import{i as b,o as x}from"./bg-WnYN5ifx.js";import{n as S,t as C}from"./state-Cn_m2NOf.js";import{n as w,r as T}from"./pipeTransport-CqCnc-Ys.js";import{join as E}from"path";import"crypto";import{readFile as D,readdir as O}from"fs/promises";function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e){return typeof e==`string`&&z.includes(e)}function j(e){return typeof e==`string`&&B.includes(e)}function M(e){return!k(e)||typeof e.name!=`string`||!j(e.status)?null:{name:e.name,...typeof e.prompt==`string`?{prompt:e.prompt}:{},status:e.status,...typeof e.startedAt==`number`?{startedAt:e.startedAt}:{},...typeof e.completedAt==`number`?{completedAt:e.completedAt}:{}}}function N(e){if(!k(e)||typeof e.runId!=`string`||typeof e.workflow!=`string`||!A(e.status)||typeof e.createdAt!=`number`||typeof e.updatedAt!=`number`||typeof e.currentStepIndex!=`number`||!Array.isArray(e.steps))return null;let t=e.steps.map(M).filter(e=>e!==null);return t.length===e.steps.length?{runId:e.runId,workflow:e.workflow,...typeof e.args==`string`?{args:e.args}:{},status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,currentStepIndex:e.currentStepIndex,steps:t}:null}async function P(e,t){try{return N(oe(await D(E(e,L,`${t}.json`),`utf-8`),!1))}catch{return null}}async function F(e=n()){let t;try{t=await O(E(e,L))}catch{return[]}let r=t.filter(e=>e.endsWith(`.json`));return(await Promise.all(r.slice(0,R).map(t=>P(e,t.slice(0,-5))))).filter(e=>e!==null).sort((e,t)=>t.updatedAt-e.updatedAt)}function I(e){if(e.length===0)return[`Workflow runs: 0`,` none`].join(`
2
2
  `);let t=e.filter(e=>e.status===`running`).length,n=e.filter(e=>e.status===`completed`).length,r=e.filter(e=>e.status===`cancelled`).length,i=[`Workflow runs: ${e.length}`,` Running: ${t}`,` Completed: ${n}`,` Cancelled: ${r}`];for(let t of e.slice(0,10)){let e=t.steps[t.currentStepIndex];i.push(` ${t.runId}: ${t.workflow}: ${t.status} step=${e?.name??`none`} updated=${new Date(t.updatedAt).toLocaleString()}`)}return e.length>10&&i.push(` ... ${e.length-10} more workflow run(s)`),i.join(`
3
3
  `)}var L,R,z,B,V=e((()=>{t(),ae(),L=E(`.claude`,`workflow-runs`),R=200,z=[`running`,`completed`,`cancelled`],B=[`pending`,`running`,`completed`,`cancelled`]}));function H(){return E(w(),`registry.json`)}async function U(){try{let e=await D(H(),`utf8`),t=JSON.parse(e);return t.version===1?t:{...W}}catch{return{...W}}}var W,de=e((()=>{T(),W={version:1,mainMachineId:null,main:null,subs:[]}}));async function fe(){return pe(await U())}function pe(e){let t=[`Pipe registry: ${+!!e.main} main, ${e.subs.length} sub(s)`];e.mainMachineId&&t.push(` main_machine=${e.mainMachineId.slice(0,8)}...`),e.main&&t.push(` [main] ${e.main.pipeName} pid=${e.main.pid} host=${e.main.hostname} tcp=${e.main.tcpPort??`none`}`);for(let n of e.subs.slice(0,10))t.push(` [sub-${n.subIndex}] ${n.pipeName} pid=${n.pid} host=${n.hostname} bound=${n.boundToMain??`none`} tcp=${n.tcpPort??`none`}`);return!e.main&&e.subs.length===0&&t.push(` none`),e.subs.length>10&&t.push(` ... ${e.subs.length-10} more sub pipe(s)`),t.join(`
4
4
  `)}var me=e((()=>{de()}));function he(){try{let e=le(),t=ue();return[`Remote Control: ${e?`self-hosted`:`official`}`,` base_url=${ce()}`,` token=${t?`present`:`missing`}`,` entitlement=checked at remote-control startup`].join(`
@@ -1 +1 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{I as n,P as r,fi as i,hn as a,t as o,y as s}from"./src-CDCSSo0U2.js";import{t as c}from"./jsx-runtime-Bb4Xn-E0.js";import{ST as l,_x as u,bx as d,xT as f}from"./loadAgentsDir-Clu7Uk6a.js";import{c as p,l as m,m as h,p as g}from"./autonomy-Cg5zweUa.js";function _(){return S}function v({onDone:e}){d(`autonomy-panel`);let[t,i]=(0,b.useState)(0),[o,c]=(0,b.useState)([]);(0,b.useEffect)(()=>{let e=!1;return l().then(t=>{e||c(t.slice(0,5))}),()=>{e=!0}},[]);let u=(0,b.useMemo)(()=>{let e=[{label:`Overview`,description:`Show run and flow counts plus the latest automatic activity`,run:()=>g()},{label:`Full deep status`,description:`Print every local autonomy surface in one diagnostic report`,run:()=>g({deep:!0})},{label:`Auto mode`,description:`Check whether auto permission mode is available and why`,run:()=>m(`auto-mode`)},{label:`Runs summary`,description:`Show queued/running/completed/failed run totals and latest run`,run:()=>m(`runs`)},{label:`Recent runs`,description:`List recent autonomy run IDs, triggers, statuses, and prompts`,run:()=>p(`runs 10`)},{label:`Flows summary`,description:`Show managed flow totals across queued/running/waiting states`,run:()=>m(`flows`)},{label:`Recent flows`,description:`List recent managed flow IDs, status, current step, and goal`,run:()=>p(`flows 10`)},{label:`Workflow runs`,description:`Show persisted WorkflowTool runs and their current workflow step`,run:()=>m(`workflow-runs`)},{label:`Pipes`,description:`Show UDS/named-pipe and LAN registry for terminal messaging`,run:()=>m(`pipes`)},{label:`Runtime`,description:`Show daemon state and live background or interactive sessions`,run:()=>m(`runtime`)},{label:`Remote Control`,description:`Show bridge mode, base URL, token presence, and entitlement note`,run:()=>m(`remote-control`)},{label:`RemoteTrigger`,description:`Show recent remote trigger audit records, failures, and latest call`,run:()=>m(`remote-trigger`)}],t=o.flatMap(e=>{let t=e.flowId.slice(0,8),n=[{label:`Flow ${t}`,description:`${e.status}: ${e.goal}`,run:()=>p(`flow ${e.flowId}`)}];return e.status===`waiting`&&n.push({label:`Resume ${t}`,description:e.currentStep?`Resume waiting step: ${e.currentStep}`:`Resume waiting flow`,run:()=>p(`flow resume ${e.flowId}`,{enqueueInMemory:!0})}),(e.status===`queued`||e.status===`running`||e.status===`waiting`||e.status===`blocked`)&&n.push({label:`Cancel ${t}`,description:`Cancel ${e.status} flow`,run:()=>p(`flow cancel ${e.flowId}`,{removeQueuedInMemory:!0})}),n});return[...e,...t]},[o]),f=()=>{let n=u[t];n&&n.run().then(t=>{e(t,{display:`system`})})};return a((e,t)=>{if(t.upArrow){i(e=>Math.max(0,e-1));return}if(t.downArrow){i(e=>Math.min(u.length-1,e+1));return}t.return&&f()}),(0,x.jsx)(s,{title:`Autonomy`,subtitle:`${u.length} actions`,onCancel:()=>e(`Autonomy panel dismissed`,{display:`system`}),color:`background`,hideInputGuide:!0,children:(0,x.jsxs)(n,{flexDirection:`column`,children:[u.map((e,i)=>(0,x.jsxs)(n,{flexDirection:`row`,children:[(0,x.jsx)(r,{children:`${i===t?`›`:` `} ${e.label}`.padEnd(C)}),(0,x.jsx)(r,{dimColor:!0,children:e.description})]},`${e.label}-${i}`)),(0,x.jsx)(n,{marginTop:1,children:(0,x.jsx)(r,{dimColor:!0,children:`↑/↓ select · Enter run · Esc close`})})]})})}async function y(e,t,n){let r=n?.trim()??``;return r?(e(await p(r,{enqueueInMemory:!0,removeQueuedInMemory:!0}),{display:`system`}),null):(0,x.jsx)(v,{onDone:e})}var b,x,S,C;e((()=>{b=t(i(),1),o(),u(),h(),f(),x=c(),S=14,C=24}))();export{y as call,_ as getAutonomyPanelBaseActionCountForTests};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{I as n,P as r,fi as i,hn as a,t as o,y as s}from"./src-CDCSSo0U2.js";import{t as c}from"./jsx-runtime-Bb4Xn-E0.js";import{ST as l,_x as u,bx as d,xT as f}from"./loadAgentsDir-D206qwP3.js";import{c as p,l as m,m as h,p as g}from"./autonomy-DGcy5Rml.js";function _(){return S}function v({onDone:e}){d(`autonomy-panel`);let[t,i]=(0,b.useState)(0),[o,c]=(0,b.useState)([]);(0,b.useEffect)(()=>{let e=!1;return l().then(t=>{e||c(t.slice(0,5))}),()=>{e=!0}},[]);let u=(0,b.useMemo)(()=>{let e=[{label:`Overview`,description:`Show run and flow counts plus the latest automatic activity`,run:()=>g()},{label:`Full deep status`,description:`Print every local autonomy surface in one diagnostic report`,run:()=>g({deep:!0})},{label:`Auto mode`,description:`Check whether auto permission mode is available and why`,run:()=>m(`auto-mode`)},{label:`Runs summary`,description:`Show queued/running/completed/failed run totals and latest run`,run:()=>m(`runs`)},{label:`Recent runs`,description:`List recent autonomy run IDs, triggers, statuses, and prompts`,run:()=>p(`runs 10`)},{label:`Flows summary`,description:`Show managed flow totals across queued/running/waiting states`,run:()=>m(`flows`)},{label:`Recent flows`,description:`List recent managed flow IDs, status, current step, and goal`,run:()=>p(`flows 10`)},{label:`Workflow runs`,description:`Show persisted WorkflowTool runs and their current workflow step`,run:()=>m(`workflow-runs`)},{label:`Pipes`,description:`Show UDS/named-pipe and LAN registry for terminal messaging`,run:()=>m(`pipes`)},{label:`Runtime`,description:`Show daemon state and live background or interactive sessions`,run:()=>m(`runtime`)},{label:`Remote Control`,description:`Show bridge mode, base URL, token presence, and entitlement note`,run:()=>m(`remote-control`)},{label:`RemoteTrigger`,description:`Show recent remote trigger audit records, failures, and latest call`,run:()=>m(`remote-trigger`)}],t=o.flatMap(e=>{let t=e.flowId.slice(0,8),n=[{label:`Flow ${t}`,description:`${e.status}: ${e.goal}`,run:()=>p(`flow ${e.flowId}`)}];return e.status===`waiting`&&n.push({label:`Resume ${t}`,description:e.currentStep?`Resume waiting step: ${e.currentStep}`:`Resume waiting flow`,run:()=>p(`flow resume ${e.flowId}`,{enqueueInMemory:!0})}),(e.status===`queued`||e.status===`running`||e.status===`waiting`||e.status===`blocked`)&&n.push({label:`Cancel ${t}`,description:`Cancel ${e.status} flow`,run:()=>p(`flow cancel ${e.flowId}`,{removeQueuedInMemory:!0})}),n});return[...e,...t]},[o]),f=()=>{let n=u[t];n&&n.run().then(t=>{e(t,{display:`system`})})};return a((e,t)=>{if(t.upArrow){i(e=>Math.max(0,e-1));return}if(t.downArrow){i(e=>Math.min(u.length-1,e+1));return}t.return&&f()}),(0,x.jsx)(s,{title:`Autonomy`,subtitle:`${u.length} actions`,onCancel:()=>e(`Autonomy panel dismissed`,{display:`system`}),color:`background`,hideInputGuide:!0,children:(0,x.jsxs)(n,{flexDirection:`column`,children:[u.map((e,i)=>(0,x.jsxs)(n,{flexDirection:`row`,children:[(0,x.jsx)(r,{children:`${i===t?`›`:` `} ${e.label}`.padEnd(C)}),(0,x.jsx)(r,{dimColor:!0,children:e.description})]},`${e.label}-${i}`)),(0,x.jsx)(n,{marginTop:1,children:(0,x.jsx)(r,{dimColor:!0,children:`↑/↓ select · Enter run · Esc close`})})]})})}async function y(e,t,n){let r=n?.trim()??``;return r?(e(await p(r,{enqueueInMemory:!0,removeQueuedInMemory:!0}),{display:`system`}),null):(0,x.jsx)(v,{onDone:e})}var b,x,S,C;e((()=>{b=t(i(),1),o(),u(),h(),f(),x=c(),S=14,C=24}))();export{y as call,_ as getAutonomyPanelBaseActionCountForTests};
@@ -0,0 +1 @@
1
+ import{t as e}from"./backgroundHousekeeping-BVMf_Tjn.js";export{e as startBackgroundHousekeeping};
@@ -1,4 +1,4 @@
1
- import{a as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,o as r}from"./envUtils-DSxRz_kt.js";import{K as i,R as a,en as o}from"./state-ix0xIunV.js";import{Dx as s,Et as c,Gw as l,Hg as u,So as d,To as f,Wg as ee,Ww as te,Xl as ne,Yl as p,Yw as m,ZT as h,br as g,et as _,hS as v,ht as y,jr as re,kx as ie,mS as ae,nt as oe,wo as se,zo as b}from"./loadAgentsDir-Clu7Uk6a.js";import{n as ce,t as le}from"./cwd-CYmmnQVS.js";import{S as ue,W as de,a as fe,d as x,l as S,p as C,z as w}from"./debug-BrXObCdR.js";import{f as T,g as E,v as D}from"./settings-Dlp5JTa_.js";import{C as O,T as k,w as A}from"./config-3m_9zSrj.js";import{o as j,s as M,v as N,y as P}from"./log-BMCygSzM.js";import{n as F,r as I}from"./analytics-BotDBGh0.js";import{_ as L,h as R}from"./model-BQF64tZx.js";import{Tn as z,wn as B}from"./prompt-Bg_1U0gO.js";import{st as V}from"./rcDebugLog-VKwMl0yg.js";import{i as H,t as U}from"./nativeInstaller-OPuO2sm_.js";import{n as pe,t as me}from"./allErrors-P3utlEeA.js";import{n as he,r as ge}from"./magicDocs-Bf1fqnHN.js";import{n as _e,t as ve}from"./pluginAutoupdate-CO-n9bqe.js";import{n as ye,r as be}from"./registerProtocol-CuKZAiCc.js";import{homedir as xe}from"os";import{join as W}from"path";import"crypto";import*as G from"fs/promises";r(),o(),ce(),ue(),C(),fe(),P(),E(),z(),L(),m(),ne(),re(),ge(),_(),j(),w(),b(),h(),_(),l(),w(),j(),b(),h();async function Se(e,t){if(!e)return;let{join:n}=await import(`path`),r=await import(`fs/promises`),i=n(le(),`.claude`,`skills`,e,`SKILL.md`),a;try{a=await r.readFile(i,`utf-8`)}catch{M(Error(`Failed to read skill file for improvement: ${i}`));return}let o=t.map(e=>`- ${e.section}: ${e.change}`).join(`
1
+ import{a as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,o as r}from"./envUtils-DSxRz_kt.js";import{K as i,R as a,en as o}from"./state-ix0xIunV.js";import{Dx as s,Et as c,Gw as l,Hg as u,So as d,To as f,Wg as ee,Ww as te,Xl as ne,Yl as p,Yw as m,ZT as h,br as g,et as _,hS as v,ht as y,jr as re,kx as ie,mS as ae,nt as oe,wo as se,zo as b}from"./loadAgentsDir-D206qwP3.js";import{n as ce,t as le}from"./cwd-CYmmnQVS.js";import{S as ue,W as de,a as fe,d as x,l as S,p as C,z as w}from"./debug-BrXObCdR.js";import{f as T,g as E,v as D}from"./settings-BovzmwMP.js";import{C as O,T as k,w as A}from"./config-DmomySWC.js";import{o as j,s as M,v as N,y as P}from"./log-BMCygSzM.js";import{n as F,r as I}from"./analytics-BotDBGh0.js";import{_ as L,h as R}from"./model-CKkOnnnx.js";import{Tn as z,wn as B}from"./prompt-BNHtszmZ.js";import{st as V}from"./rcDebugLog-CUy1_F23.js";import{i as H,t as U}from"./nativeInstaller-CA5d6_G7.js";import{n as pe,t as me}from"./allErrors-1896uQA1.js";import{n as he,r as ge}from"./magicDocs-DWjL2k7P.js";import{n as _e,t as ve}from"./pluginAutoupdate-reO2PgtQ.js";import{n as ye,r as be}from"./registerProtocol-B7Fzdofu.js";import{homedir as xe}from"os";import{join as W}from"path";import"crypto";import*as G from"fs/promises";r(),o(),ce(),ue(),C(),fe(),P(),E(),z(),L(),m(),ne(),re(),ge(),_(),j(),w(),b(),h(),_(),l(),w(),j(),b(),h();async function Se(e,t){if(!e)return;let{join:n}=await import(`path`),r=await import(`fs/promises`),i=n(le(),`.claude`,`skills`,e,`SKILL.md`),a;try{a=await r.readFile(i,`utf-8`)}catch{M(Error(`Failed to read skill file for improvement: ${i}`));return}let o=t.map(e=>`- ${e.section}: ${e.change}`).join(`
2
2
  `),s=R(),c=await oe({messages:[d({content:`You are editing a skill definition file. Apply the following improvements to the skill.
3
3
 
4
4
  <current_skill_file>
@@ -14,4 +14,4 @@ Rules:
14
14
  - Preserve frontmatter (--- block) exactly as-is
15
15
  - Preserve the overall format and style
16
16
  - Do not remove existing content unless an improvement explicitly replaces it
17
- - Output the complete updated file inside <updated_file> tags`})],systemPrompt:V([`You edit skill definition files to incorporate user preferences. Output only the updated file content.`]),thinkingConfig:{type:`disabled`},tools:[],signal:te().signal,options:{getToolPermissionContext:async()=>B(),model:s,toolChoice:void 0,isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,temperatureOverride:0,agents:[],querySource:`skill_improvement_apply`,mcpTools:[]}}),l=se(f(Array.isArray(c.message.content)?c.message.content:[]).trim(),`updated_file`);if(!l){M(Error(`Skill improvement apply: no updated_file tag in response`));return}try{await r.writeFile(i,l,`utf-8`)}catch(e){M(de(e))}}F(),ie(),O(),j(),U(),v(),pe(),ee(),c();var Ce=30;function K(){let e=((T()||{}).cleanupPeriodDays??Ce)*24*60*60*1e3;return new Date(Date.now()-e)}function we(e,t){return{messages:e.messages+t.messages,errors:e.errors+t.errors}}function Te(e){let t=e.split(`.`)[0].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/,`T$1:$2:$3.$4Z`);return new Date(t)}async function q(e,t,n){let r={messages:0,errors:0};try{let i=await x().readdir(e);for(let a of i)try{Te(a.name)<t&&(await x().unlink(W(e,a.name)),n?r.messages++:r.errors++)}catch(e){M(e)}}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&M(e)}return r}async function Ee(){let e=x(),t=K(),n=N.errors(),r=N.baseLogs(),i=await q(n,t,!1);try{let n;try{n=await e.readdir(r)}catch{return i}let a=n.filter(e=>e.isDirectory()&&e.name.startsWith(`mcp-logs-`)).map(e=>W(r,e.name));for(let n of a)i=we(i,await q(n,t,!0)),await Y(n,e)}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&M(e)}return i}async function J(e,t,n){return(await n.stat(e)).mtime<t?(await n.unlink(e),!0):!1}async function Y(e,t){try{await t.rmdir(e)}catch{}}async function De(){let e=K(),t={messages:0,errors:0},n=g(),r=x(),i;try{i=await r.readdir(n)}catch{return t}for(let a of i){if(!a.isDirectory())continue;let i=W(n,a.name),o;try{o=await r.readdir(i)}catch{t.errors++;continue}for(let n of o)if(n.isFile()){if(!n.name.endsWith(`.jsonl`)&&!n.name.endsWith(`.cast`))continue;try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}}else if(n.isDirectory()){let a=W(i,n.name),o=W(a,u),s;try{s=await r.readdir(o)}catch{await Y(a,r);continue}for(let n of s)if(n.isFile())try{await J(W(o,n.name),e,r)&&t.messages++}catch{t.errors++}else if(n.isDirectory()){let i=W(o,n.name),a;try{a=await r.readdir(i)}catch{continue}for(let n of a)if(n.isFile())try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}await Y(i,r)}await Y(o,r),await Y(a,r)}await Y(i,r)}return t}async function Oe(e,t,n=!0){let r=K(),i={messages:0,errors:0},a=x(),o;try{o=await a.readdir(e)}catch{return i}for(let n of o)if(!(!n.isFile()||!n.name.endsWith(t)))try{await J(W(e,n.name),r,a)&&i.messages++}catch{i.errors++}return n&&await Y(e,a),i}function ke(){return Oe(W(n(),`plans`),`.md`)}async function Ae(){let e=K(),t={messages:0,errors:0},r=x();try{let i=W(n(),`file-history`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));await Promise.all(o.map(async n=>{try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}})),await Y(i,r)}catch(e){M(e)}return t}async function X(){let e=K(),t={messages:0,errors:0},r=x();try{let i=W(n(),`session-env`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));for(let n of o)try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}await Y(i,r)}catch(e){M(e)}return t}async function je(){let e=K(),t={messages:0,errors:0},r=x(),i=W(n(),`debug`),a;try{a=await r.readdir(i)}catch{return t}for(let n of a)if(!(!n.isFile()||!n.name.endsWith(`.txt`)||n.name===`latest`))try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}return t}var Z=1440*60*1e3;async function Q(){let e=W(n(),`.npm-cache-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){S(`npm cache cleanup: skipping, ran recently`);return}}catch{}try{await A(e,{retries:0,realpath:!1})}catch{S(`npm cache cleanup: skipping, lock held`);return}S(`npm cache cleanup: starting`);let r=W(xe(),`.npm`,`_cacache`),i=Date.now();try{let n=await import(`./lib-rQZENxQg.js`).then(e=>t(e.default,1)),a=i-Z,o=n.ls.stream(r),s=[];for await(let e of o)e.key.includes(`@anthropic-ai/claude-`)&&s.push({key:e.key,time:e.time});let c=new Map;for(let e of s){let t=e.key.lastIndexOf(`@`),n=t>0?e.key.slice(0,t):e.key,r=c.get(n)??[];r.push(e),c.set(n,r)}let l=[];for(let[,e]of c){e.sort((e,t)=>t.time-e.time);for(let t=0;t<e.length;t++){let n=e[t];(n.time<a||t>=5)&&l.push(n.key)}}await Promise.all(l.map(e=>n.rm.entry(r,e))),await G.writeFile(e,new Date().toISOString());let u=Date.now()-i;l.length>0?S(`npm cache cleanup: Removed ${l.length} old @anthropic-ai entries in ${u}ms`):S(`npm cache cleanup: completed in ${u}ms`),I(`tengu_npm_cache_cleanup`,{success:!0,durationMs:u,entriesRemoved:l.length})}catch(e){M(e),I(`tengu_npm_cache_cleanup`,{success:!1,durationMs:Date.now()-i})}finally{await k(e,{realpath:!1}).catch(()=>{})}}async function Me(){let e=W(n(),`.version-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){S(`version cleanup: skipping, ran recently`);return}}catch{}try{await A(e,{retries:0,realpath:!1})}catch{S(`version cleanup: skipping, lock held`);return}S(`version cleanup: starting (throttled)`);try{await H(),await G.writeFile(e,new Date().toISOString())}catch(e){M(e)}finally{await k(e,{realpath:!1}).catch(()=>{})}}async function Ne(){let{errors:e}=me();if(e.length>0&&D(`cleanupPeriodDays`)){S(`Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup.`);return}await Ee(),await De(),await ke(),await Ae(),await X(),await je(),await s(),await ae(K());let t=await y(K());t>0&&I(`tengu_worktree_cleanup`,{removed:t}),process.env.USER_TYPE===`ant`&&await Q()}o(),U(),_e();var Pe=(ye(),e(be)),Fe=1440*60*1e3,$=600*1e3;function Ie(){he(),import(`./extractMemories-B2IAvbXM.js`).then(({initExtractMemories:e})=>{e()}).catch(()=>{}),p(),ve(),a()&&Pe.ensureDeepLinkProtocolRegistered();let e=!0;async function t(){if(a()&&i()>Date.now()-1e3*60){setTimeout(t,$).unref();return}if(e&&(e=!1,await Ne()),a()&&i()>Date.now()-1e3*60){setTimeout(t,$).unref();return}await H()}setTimeout(t,$).unref(),process.env.USER_TYPE===`ant`&&setInterval(()=>{Q(),Me()},Fe).unref()}export{Se as n,Ie as t};
17
+ - Output the complete updated file inside <updated_file> tags`})],systemPrompt:V([`You edit skill definition files to incorporate user preferences. Output only the updated file content.`]),thinkingConfig:{type:`disabled`},tools:[],signal:te().signal,options:{getToolPermissionContext:async()=>B(),model:s,toolChoice:void 0,isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,temperatureOverride:0,agents:[],querySource:`skill_improvement_apply`,mcpTools:[]}}),l=se(f(Array.isArray(c.message.content)?c.message.content:[]).trim(),`updated_file`);if(!l){M(Error(`Skill improvement apply: no updated_file tag in response`));return}try{await r.writeFile(i,l,`utf-8`)}catch(e){M(de(e))}}F(),ie(),O(),j(),U(),v(),pe(),ee(),c();var Ce=30;function K(){let e=((T()||{}).cleanupPeriodDays??Ce)*24*60*60*1e3;return new Date(Date.now()-e)}function we(e,t){return{messages:e.messages+t.messages,errors:e.errors+t.errors}}function Te(e){let t=e.split(`.`)[0].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/,`T$1:$2:$3.$4Z`);return new Date(t)}async function q(e,t,n){let r={messages:0,errors:0};try{let i=await x().readdir(e);for(let a of i)try{Te(a.name)<t&&(await x().unlink(W(e,a.name)),n?r.messages++:r.errors++)}catch(e){M(e)}}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&M(e)}return r}async function Ee(){let e=x(),t=K(),n=N.errors(),r=N.baseLogs(),i=await q(n,t,!1);try{let n;try{n=await e.readdir(r)}catch{return i}let a=n.filter(e=>e.isDirectory()&&e.name.startsWith(`mcp-logs-`)).map(e=>W(r,e.name));for(let n of a)i=we(i,await q(n,t,!0)),await Y(n,e)}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&M(e)}return i}async function J(e,t,n){return(await n.stat(e)).mtime<t?(await n.unlink(e),!0):!1}async function Y(e,t){try{await t.rmdir(e)}catch{}}async function De(){let e=K(),t={messages:0,errors:0},n=g(),r=x(),i;try{i=await r.readdir(n)}catch{return t}for(let a of i){if(!a.isDirectory())continue;let i=W(n,a.name),o;try{o=await r.readdir(i)}catch{t.errors++;continue}for(let n of o)if(n.isFile()){if(!n.name.endsWith(`.jsonl`)&&!n.name.endsWith(`.cast`))continue;try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}}else if(n.isDirectory()){let a=W(i,n.name),o=W(a,u),s;try{s=await r.readdir(o)}catch{await Y(a,r);continue}for(let n of s)if(n.isFile())try{await J(W(o,n.name),e,r)&&t.messages++}catch{t.errors++}else if(n.isDirectory()){let i=W(o,n.name),a;try{a=await r.readdir(i)}catch{continue}for(let n of a)if(n.isFile())try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}await Y(i,r)}await Y(o,r),await Y(a,r)}await Y(i,r)}return t}async function Oe(e,t,n=!0){let r=K(),i={messages:0,errors:0},a=x(),o;try{o=await a.readdir(e)}catch{return i}for(let n of o)if(!(!n.isFile()||!n.name.endsWith(t)))try{await J(W(e,n.name),r,a)&&i.messages++}catch{i.errors++}return n&&await Y(e,a),i}function ke(){return Oe(W(n(),`plans`),`.md`)}async function Ae(){let e=K(),t={messages:0,errors:0},r=x();try{let i=W(n(),`file-history`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));await Promise.all(o.map(async n=>{try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}})),await Y(i,r)}catch(e){M(e)}return t}async function X(){let e=K(),t={messages:0,errors:0},r=x();try{let i=W(n(),`session-env`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));for(let n of o)try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}await Y(i,r)}catch(e){M(e)}return t}async function je(){let e=K(),t={messages:0,errors:0},r=x(),i=W(n(),`debug`),a;try{a=await r.readdir(i)}catch{return t}for(let n of a)if(!(!n.isFile()||!n.name.endsWith(`.txt`)||n.name===`latest`))try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}return t}var Z=1440*60*1e3;async function Q(){let e=W(n(),`.npm-cache-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){S(`npm cache cleanup: skipping, ran recently`);return}}catch{}try{await A(e,{retries:0,realpath:!1})}catch{S(`npm cache cleanup: skipping, lock held`);return}S(`npm cache cleanup: starting`);let r=W(xe(),`.npm`,`_cacache`),i=Date.now();try{let n=await import(`./lib-rQZENxQg.js`).then(e=>t(e.default,1)),a=i-Z,o=n.ls.stream(r),s=[];for await(let e of o)e.key.includes(`@anthropic-ai/claude-`)&&s.push({key:e.key,time:e.time});let c=new Map;for(let e of s){let t=e.key.lastIndexOf(`@`),n=t>0?e.key.slice(0,t):e.key,r=c.get(n)??[];r.push(e),c.set(n,r)}let l=[];for(let[,e]of c){e.sort((e,t)=>t.time-e.time);for(let t=0;t<e.length;t++){let n=e[t];(n.time<a||t>=5)&&l.push(n.key)}}await Promise.all(l.map(e=>n.rm.entry(r,e))),await G.writeFile(e,new Date().toISOString());let u=Date.now()-i;l.length>0?S(`npm cache cleanup: Removed ${l.length} old @anthropic-ai entries in ${u}ms`):S(`npm cache cleanup: completed in ${u}ms`),I(`tengu_npm_cache_cleanup`,{success:!0,durationMs:u,entriesRemoved:l.length})}catch(e){M(e),I(`tengu_npm_cache_cleanup`,{success:!1,durationMs:Date.now()-i})}finally{await k(e,{realpath:!1}).catch(()=>{})}}async function Me(){let e=W(n(),`.version-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){S(`version cleanup: skipping, ran recently`);return}}catch{}try{await A(e,{retries:0,realpath:!1})}catch{S(`version cleanup: skipping, lock held`);return}S(`version cleanup: starting (throttled)`);try{await H(),await G.writeFile(e,new Date().toISOString())}catch(e){M(e)}finally{await k(e,{realpath:!1}).catch(()=>{})}}async function Ne(){let{errors:e}=me();if(e.length>0&&D(`cleanupPeriodDays`)){S(`Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup.`);return}await Ee(),await De(),await ke(),await Ae(),await X(),await je(),await s(),await ae(K());let t=await y(K());t>0&&I(`tengu_worktree_cleanup`,{removed:t}),process.env.USER_TYPE===`ant`&&await Q()}o(),U(),_e();var Pe=(ye(),e(be)),Fe=1440*60*1e3,$=600*1e3;function Ie(){he(),import(`./extractMemories-BcaklA33.js`).then(({initExtractMemories:e})=>{e()}).catch(()=>{}),p(),ve(),a()&&Pe.ensureDeepLinkProtocolRegistered();let e=!0;async function t(){if(a()&&i()>Date.now()-1e3*60){setTimeout(t,$).unref();return}if(e&&(e=!1,await Ne()),a()&&i()>Date.now()-1e3*60){setTimeout(t,$).unref();return}await H()}setTimeout(t,$).unref(),process.env.USER_TYPE===`ant`&&setInterval(()=>{Q(),Me()},Fe).unref()}export{Se as n,Ie as t};
@@ -1,3 +1,3 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{en as t,ht as n,nt as r}from"./state-ix0xIunV.js";import{Dr as i,Er as a,Lr as o,jr as s,vi as c,wi as l,yr as u}from"./loadAgentsDir-Clu7Uk6a.js";import{S as d,w as f}from"./debug-BrXObCdR.js";import{c as p,s as m}from"./types-C-MRCL8J.js";import{n as h,r as g}from"./analytics-BotDBGh0.js";import{i as _,o as v}from"./stringUtils-DGLPkqJ4.js";import{randomUUID as y}from"crypto";import{mkdir as b,readFile as x,writeFile as S}from"fs/promises";function C(e){let t=e?.message?.content;if(!t)return`Branched conversation`;let n=typeof t==`string`?t:t.find(e=>e.type===`text`)?.text;return n&&n.replace(/\s+/g,` `).trim().slice(0,100)||`Branched conversation`}async function w(e){let t=y(),s=n(),c=u(r()),l=i(t),d=a();await b(c,{recursive:!0,mode:448});let m;try{m=await x(d)}catch{throw Error(`No conversation to branch`)}if(m.length===0)throw Error(`No conversation to branch`);let h=p(m),g=h.filter(e=>o(e)&&!e.isSidechain),_=h.filter(e=>e.type===`content-replacement`&&e.sessionId===s).flatMap(e=>e.replacements);if(g.length===0)throw Error(`No messages to branch`);let v=null,C=[],w=[];for(let e of g){let n={...e,sessionId:t,parentUuid:v,isSidechain:!1,forkedFrom:{sessionId:s,messageUuid:e.uuid}},r={...e,sessionId:t};w.push(r),C.push(f(n)),e.type!==`progress`&&(v=e.uuid)}if(_.length>0){let e={type:`content-replacement`,sessionId:t,replacements:_};C.push(f(e))}return await S(l,C.join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{en as t,ht as n,nt as r}from"./state-ix0xIunV.js";import{Dr as i,Er as a,Lr as o,jr as s,vi as c,wi as l,yr as u}from"./loadAgentsDir-D206qwP3.js";import{S as d,w as f}from"./debug-BrXObCdR.js";import{c as p,s as m}from"./types-C-MRCL8J.js";import{n as h,r as g}from"./analytics-BotDBGh0.js";import{i as _,o as v}from"./stringUtils-DGLPkqJ4.js";import{randomUUID as y}from"crypto";import{mkdir as b,readFile as x,writeFile as S}from"fs/promises";function C(e){let t=e?.message?.content;if(!t)return`Branched conversation`;let n=typeof t==`string`?t:t.find(e=>e.type===`text`)?.text;return n&&n.replace(/\s+/g,` `).trim().slice(0,100)||`Branched conversation`}async function w(e){let t=y(),s=n(),c=u(r()),l=i(t),d=a();await b(c,{recursive:!0,mode:448});let m;try{m=await x(d)}catch{throw Error(`No conversation to branch`)}if(m.length===0)throw Error(`No conversation to branch`);let h=p(m),g=h.filter(e=>o(e)&&!e.isSidechain),_=h.filter(e=>e.type===`content-replacement`&&e.sessionId===s).flatMap(e=>e.replacements);if(g.length===0)throw Error(`No messages to branch`);let v=null,C=[],w=[];for(let e of g){let n={...e,sessionId:t,parentUuid:v,isSidechain:!1,forkedFrom:{sessionId:s,messageUuid:e.uuid}},r={...e,sessionId:t};w.push(r),C.push(f(n)),e.type!==`progress`&&(v=e.uuid)}if(_.length>0){let e={type:`content-replacement`,sessionId:t,replacements:_};C.push(f(e))}return await S(l,C.join(`
2
2
  `)+`
3
3
  `,{encoding:`utf8`,mode:384}),{sessionId:t,title:e,forkPath:l,serializedMessages:w,contentReplacementRecords:_}}async function T(e){let t=`${e} (Branch)`;if((await l(t,{exact:!0})).length===0)return t;let n=await l(`${e} (Branch`),r=new Set([1]),i=RegExp(`^${_(e)} \\(Branch(?: (\\d+))?\\)$`);for(let e of n){let t=e.customTitle?.match(i);t&&(t[1]?r.add(parseInt(t[1],10)):r.add(1))}let a=2;for(;r.has(a);)a++;return`${e} (Branch ${a})`}async function E(e,t,r){let i=r?.trim()||void 0,a=n();try{let{sessionId:n,title:r,forkPath:o,serializedMessages:s,contentReplacementRecords:l}=await w(i),u=new Date,d=C(s.find(e=>e.type===`user`)),f=await T(r??d);await c(n,f,o),g(`tengu_conversation_forked`,{message_count:s.length,has_custom_title:!!r});let p={date:u.toISOString().split(`T`)[0],messages:s,fullPath:o,value:u.getTime(),created:u,modified:u,firstPrompt:d,messageCount:s.length,isSidechain:!1,sessionId:n,customTitle:f,contentReplacements:l},m=r?` "${r}"`:``,h=`Branched conversation${m}. You are now in the branch.${`\nTo resume the original: claude -r ${a}`}`;return t.resume?(await t.resume(n,p,`fork`),e(h,{display:`system`})):e(`Branched conversation${m}. Resume with: /resume ${n}`),null}catch(t){return e(`Failed to branch conversation: ${t instanceof Error?t.message:`Unknown error occurred`}`),null}}e((()=>{t(),h(),m(),s(),d(),v()}))();export{E as call,C as deriveFirstPrompt};
@@ -2,7 +2,7 @@ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,o as n}from"./e
2
2
  `).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>e!==null),t=e.filter(e=>e.kind===`once`),n=e[e.length-1],r=e.filter(e=>e.kind===`always_on`||e.kind===`always_off`),i=r[r.length-1];return{totalBreaks:t.length,lastBreakAt:n?.at??null,alwaysModeEnabled:i?.kind===`always_on`}}catch{return{totalBreaks:0,lastBreakAt:null,alwaysModeEnabled:!1}}}function g(e){let n=m();c(t(),{recursive:!0});let r={at:new Date().toISOString(),kind:e};o(n,JSON.stringify(r)+`
3
3
  `,`utf8`)}function _(){g(`once`)}async function v(e){let t=e.trim().toLowerCase(),n=f(),r=p();if(t===`status`){let e=h(),t=s(n),i=s(r);return{type:`text`,value:[`## Break-Cache Status`,``,` Once marker: ${t?`ACTIVE (next call will bust cache)`:`not set`}`,` Always mode: ${i?`ON (every call busts cache)`:`off`}`,``,`## Stats`,` total_breaks: ${e.totalBreaks}`,` last_break_at: ${e.lastBreakAt??`never`}`].join(`
4
4
  `)}}if(t===`off`){let e=!1;return s(n)&&(u(n),e=!0),s(r)&&(u(r),e=!0),g(`always_off`),{type:`text`,value:e?`Break-cache disabled. Removed once marker and/or always flag.`:`Break-cache was not active.`}}if(t===`--clear`)return s(n)?(u(n),{type:`text`,value:`Cache-break marker cleared.\n \`${n}\``}):{type:`text`,value:`No cache-break marker was set.`};if(t===`always`)return d(r,new Date().toISOString(),`utf8`),g(`always_on`),{type:`text`,value:[`## Always-on cache break enabled`,``,`Flag written: \`${r}\``,``,`Every API call will now append a random nonce to the system prompt,`,`permanently preventing prompt-cache hits for this session.`,``,"To disable: `/break-cache off`"].join(`
5
- `)};if(t===``||t===`once`){let e=new Date().toISOString();d(n,e,`utf8`),_();let t=h();return{type:`text`,value:[`## Cache break scheduled`,``,`Marker written: \`${n}\``,`Timestamp: ${e}`,``,`The next API call will append a random nonce to the system prompt,`,`causing a cache miss. The marker is removed automatically after use.`,``,"To cancel before the next call: `/break-cache --clear`","For every call: `/break-cache always`",``,`Total breaks this session: ${t.totalBreaks}`,``,`_How it works: Anthropic prompt cache keys on the system-prompt prefix hash._`,`_A unique nonce invalidates the hash, forcing a fresh compute._`].join(`
5
+ `)};if(t===``||t===`once`){let e=new Date().toISOString();d(n,e,`utf8`),_();let t=h();return{type:`text`,value:[`## Cache break scheduled`,``,`Marker written: \`${n}\``,`Timestamp: ${e}`,``,`The next API call will append a random nonce to the system prompt,`,`causing a cache miss. The marker is removed automatically after use.`,``,"To cancel before the next call: `/break-cache --clear`","For every call: `/break-cache always`",``,`Total breaks this session: ${t.totalBreaks}`,``,`_How it works: The prompt cache keys on the system-prompt prefix hash._`,`_A unique nonce invalidates the hash, forcing a fresh compute._`].join(`
6
6
  `)}}return{type:`text`,value:[`Unknown scope: "${t}"`,``,y].join(`
7
- `)}}var y,b,x,S=e((()=>{r(),n(),y=[`Usage: /break-cache [scope]`,``,` (no args) Schedule a one-time cache break for the next API call`,` once Same as no args`,` always Enable persistent cache-break mode (every request)`,` off Disable always mode and clear any pending marker`,` --clear Clear the pending once marker (cancel before next call)`,` status Show current break-cache status and stats`,``,`How it works:`,` The Anthropic prompt cache keys on the system-prompt prefix hash.`,` A unique nonce invalidates the hash, forcing a fresh compute.`,` This is useful when you want to ensure a clean context window.`].join(`
8
- `),b={type:`local-jsx`,name:`break-cache`,description:`Manage prompt-cache breaking. Open actions or run: once, status, always, off`,isHidden:!1,isEnabled:()=>!i(),argumentHint:`[once|status|always|off|--clear]`,bridgeSafe:!0,getBridgeInvocationError:e=>e.trim()?void 0:`Use /break-cache once/status/always/off over Remote Control.`,load:()=>import(`./panel-CrTPqXCv.js`)},x={type:`local`,name:`break-cache`,description:`Force the next (or all) API call(s) to miss prompt cache. Scopes: once, status, always, off`,isHidden:!1,isEnabled:()=>i(),supportsNonInteractive:!0,bridgeSafe:!0,load:async()=>({call:v})}}));export{f as a,p as i,x as n,S as o,v as r,b as t};
7
+ `)}}var y,b,x,S=e((()=>{r(),n(),y=[`Usage: /break-cache [scope]`,``,` (no args) Schedule a one-time cache break for the next API call`,` once Same as no args`,` always Enable persistent cache-break mode (every request)`,` off Disable always mode and clear any pending marker`,` --clear Clear the pending once marker (cancel before next call)`,` status Show current break-cache status and stats`,``,`How it works:`,` The prompt cache keys on the system-prompt prefix hash.`,` A unique nonce invalidates the hash, forcing a fresh compute.`,` This is useful when you want to ensure a clean context window.`].join(`
8
+ `),b={type:`local-jsx`,name:`break-cache`,description:`Manage prompt-cache breaking. Open actions or run: once, status, always, off`,isHidden:!1,isEnabled:()=>!i(),argumentHint:`[once|status|always|off|--clear]`,bridgeSafe:!0,getBridgeInvocationError:e=>e.trim()?void 0:`Use /break-cache once/status/always/off over Remote Control.`,load:()=>import(`./panel-BSZGX6jN.js`)},x={type:`local`,name:`break-cache`,description:`Force the next (or all) API call(s) to miss prompt cache. Scopes: once, status, always, off`,isHidden:!1,isEnabled:()=>i(),supportsNonInteractive:!0,bridgeSafe:!0,load:async()=>({call:v})}}));export{f as a,p as i,x as n,S as o,v as r,b as t};
@@ -1,2 +1,2 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Gt as n,I as r,P as i,_ as a,fi as o,t as s,y as c}from"./src-CDCSSo0U2.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{KS as u,US as d,WS as f,_x as p,bx as m}from"./loadAgentsDir-Clu7Uk6a.js";import{a as h,l as g}from"./debug-BrXObCdR.js";import{n as _,r as v}from"./analytics-BotDBGh0.js";import{u as y}from"./referral-BlrMpBAV.js";import{a as b,t as x}from"./bridgeConfig-5p_w4s5r.js";import{n as S,r as C,s as w,t as T}from"./bridgeEnabled-DhFrLTbG.js";import{a as E,i as D,n as O}from"./types-Bh9S_JG5.js";import{t as k}from"./lib-BlVGipXx.js";import{i as A,n as j}from"./envLessBridgeConfig-DXd10GXD.js";import{n as M,r as N}from"./RemoteCallout-CiA4rCEs.js";function P({onDone:e,name:t}){let n=u(),r=f(e=>e.replBridgeConnected),i=f(e=>e.replBridgeEnabled),a=f(e=>e.replBridgeOutboundOnly),[o,s]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{if((r||i)&&!a){s(!0);return}let o=!1;return(async()=>{let r=await I();if(!o){if(r){v(`tengu_bridge_command`,{action:`preflight_failed`}),e(r,{display:`system`});return}if(N()){n(e=>e.showRemoteCallout?e:{...e,showRemoteCallout:!0,replBridgeInitialName:t}),e(``,{display:`system`});return}v(`tengu_bridge_command`,{action:`connect`}),n(e=>e.replBridgeEnabled&&!e.replBridgeOutboundOnly?e:{...e,replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1,replBridgeInitialName:t}),e(`Remote Control connecting…`,{display:`system`})}})(),()=>{o=!0}},[]),o?(0,B.jsx)(F,{onDone:e}):null}function F({onDone:e}){m(`bridge-disconnect-dialog`);let t=u(),o=f(e=>e.replBridgeSessionUrl),s=f(e=>e.replBridgeConnectUrl),l=f(e=>e.replBridgeSessionActive),[d,p]=(0,z.useState)(2),[h,g]=(0,z.useState)(!1),[_,y]=(0,z.useState)(``),b=l?o:s;(0,z.useEffect)(()=>{if(!h||!b){y(``);return}(0,R.toString)(b,{type:`utf8`,errorCorrectionLevel:`L`,small:!0}).then(y).catch(()=>y(``))},[h,b]);function x(){t(e=>e.replBridgeEnabled?{...e,replBridgeEnabled:!1,replBridgeExplicit:!1,replBridgeOutboundOnly:!1}:e),v(`tengu_bridge_command`,{action:`disconnect`}),e(D,{display:`system`})}function S(){g(e=>!e)}function C(){e(void 0,{display:`skip`})}n({"select:next":()=>p(e=>(e+1)%3),"select:previous":()=>p(e=>(e-1+3)%3),"select:accept":()=>{d===0?x():d===1?S():C()}},{context:`Select`});let w=_?_.split(`
2
- `).filter(e=>e.length>0):[];return(0,B.jsx)(c,{title:`Remote Control`,onCancel:C,hideInputGuide:!0,children:(0,B.jsxs)(r,{flexDirection:`column`,gap:1,children:[(0,B.jsxs)(i,{children:[`This session is available via Remote Control`,b?` at ${b}`:``,`.`]}),h&&w.length>0&&(0,B.jsx)(r,{flexDirection:`column`,children:w.map((e,t)=>(0,B.jsx)(i,{children:e},t))}),(0,B.jsxs)(r,{flexDirection:`column`,children:[(0,B.jsx)(a,{isFocused:d===0,children:(0,B.jsx)(i,{children:`Disconnect this session`})}),(0,B.jsx)(a,{isFocused:d===1,children:(0,B.jsx)(i,{children:h?`Hide QR code`:`Show QR code`})}),(0,B.jsx)(a,{isFocused:d===2,children:(0,B.jsx)(i,{children:`Continue`})})]}),(0,B.jsx)(i,{dimColor:!0,children:`Enter to select · Esc to continue`})]})})}async function I(){let{waitForPolicyLimitsToLoad:e,isPolicyAllowed:t}=await import(`./policyLimits-BkjgMQD0.js`);if(await e(),!t(`allow_remote_control`))return`Remote Control is disabled by your organization's policy.`;let n=await S();if(n)return n;let r=w();if(r){let{isAssistantMode:e}=await import(`./assistant-z2o4-UJe.js`);e()&&(r=!1)}return(r?await j():T())||(x()?(g(`[bridge] Prerequisites passed, enabling bridge`),null):O)}async function L(e,t,n){return(0,B.jsx)(P,{onDone:e,name:n.trim()||void 0})}var R,z,B;e((()=>{R=k(),o(),z=t(o(),1),b(),C(),A(),E(),s(),M(),p(),y(),_(),d(),h(),B=l()}))();export{L as call};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Gt as n,I as r,P as i,_ as a,fi as o,t as s,y as c}from"./src-CDCSSo0U2.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{KS as u,US as d,WS as f,_x as p,bx as m}from"./loadAgentsDir-D206qwP3.js";import{a as h,l as g}from"./debug-BrXObCdR.js";import{n as _,r as v}from"./analytics-BotDBGh0.js";import{u as y}from"./referral-CUaIo_vT.js";import{a as b,t as x}from"./bridgeConfig-BhxRF2vm.js";import{n as S,r as C,s as w,t as T}from"./bridgeEnabled-SbB-6zdY.js";import{a as E,i as D,n as O}from"./types-Bh9S_JG5.js";import{t as k}from"./lib-BlVGipXx.js";import{i as A,n as j}from"./envLessBridgeConfig-Ck2-KMq0.js";import{n as M,r as N}from"./RemoteCallout-Cs-ro8_i.js";function P({onDone:e,name:t}){let n=u(),r=f(e=>e.replBridgeConnected),i=f(e=>e.replBridgeEnabled),a=f(e=>e.replBridgeOutboundOnly),[o,s]=(0,z.useState)(!1);return(0,z.useEffect)(()=>{if((r||i)&&!a){s(!0);return}let o=!1;return(async()=>{let r=await I();if(!o){if(r){v(`tengu_bridge_command`,{action:`preflight_failed`}),e(r,{display:`system`});return}if(N()){n(e=>e.showRemoteCallout?e:{...e,showRemoteCallout:!0,replBridgeInitialName:t}),e(``,{display:`system`});return}v(`tengu_bridge_command`,{action:`connect`}),n(e=>e.replBridgeEnabled&&!e.replBridgeOutboundOnly?e:{...e,replBridgeEnabled:!0,replBridgeExplicit:!0,replBridgeOutboundOnly:!1,replBridgeInitialName:t}),e(`Remote Control connecting…`,{display:`system`})}})(),()=>{o=!0}},[]),o?(0,B.jsx)(F,{onDone:e}):null}function F({onDone:e}){m(`bridge-disconnect-dialog`);let t=u(),o=f(e=>e.replBridgeSessionUrl),s=f(e=>e.replBridgeConnectUrl),l=f(e=>e.replBridgeSessionActive),[d,p]=(0,z.useState)(2),[h,g]=(0,z.useState)(!1),[_,y]=(0,z.useState)(``),b=l?o:s;(0,z.useEffect)(()=>{if(!h||!b){y(``);return}(0,R.toString)(b,{type:`utf8`,errorCorrectionLevel:`L`,small:!0}).then(y).catch(()=>y(``))},[h,b]);function x(){t(e=>e.replBridgeEnabled?{...e,replBridgeEnabled:!1,replBridgeExplicit:!1,replBridgeOutboundOnly:!1}:e),v(`tengu_bridge_command`,{action:`disconnect`}),e(D,{display:`system`})}function S(){g(e=>!e)}function C(){e(void 0,{display:`skip`})}n({"select:next":()=>p(e=>(e+1)%3),"select:previous":()=>p(e=>(e-1+3)%3),"select:accept":()=>{d===0?x():d===1?S():C()}},{context:`Select`});let w=_?_.split(`
2
+ `).filter(e=>e.length>0):[];return(0,B.jsx)(c,{title:`Remote Control`,onCancel:C,hideInputGuide:!0,children:(0,B.jsxs)(r,{flexDirection:`column`,gap:1,children:[(0,B.jsxs)(i,{children:[`This session is available via Remote Control`,b?` at ${b}`:``,`.`]}),h&&w.length>0&&(0,B.jsx)(r,{flexDirection:`column`,children:w.map((e,t)=>(0,B.jsx)(i,{children:e},t))}),(0,B.jsxs)(r,{flexDirection:`column`,children:[(0,B.jsx)(a,{isFocused:d===0,children:(0,B.jsx)(i,{children:`Disconnect this session`})}),(0,B.jsx)(a,{isFocused:d===1,children:(0,B.jsx)(i,{children:h?`Hide QR code`:`Show QR code`})}),(0,B.jsx)(a,{isFocused:d===2,children:(0,B.jsx)(i,{children:`Continue`})})]}),(0,B.jsx)(i,{dimColor:!0,children:`Enter to select · Esc to continue`})]})})}async function I(){let{waitForPolicyLimitsToLoad:e,isPolicyAllowed:t}=await import(`./policyLimits-CkTI5KEt.js`);if(await e(),!t(`allow_remote_control`))return`Remote Control is disabled by your organization's policy.`;let n=await S();if(n)return n;let r=w();if(r){let{isAssistantMode:e}=await import(`./assistant-z2o4-UJe.js`);e()&&(r=!1)}return(r?await j():T())||(x()?(g(`[bridge] Prerequisites passed, enabling bridge`),null):O)}async function L(e,t,n){return(0,B.jsx)(P,{onDone:e,name:n.trim()||void 0})}var R,z,B;e((()=>{R=k(),o(),z=t(o(),1),b(),C(),A(),E(),s(),M(),p(),y(),_(),d(),h(),B=l()}))();export{L as call};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{l as t,u as n}from"./oauth-BqJqV-2M.js";import{Bt as r,Ot as i}from"./model-BQF64tZx.js";function a(){return process.env.CLAUDE_BRIDGE_OAUTH_TOKEN||void 0}function o(){return process.env.CLAUDE_BRIDGE_BASE_URL||void 0}function s(){return a()??i()?.accessToken}function c(){return o()??t().BASE_API_URL}function l(){return!!o()}var u=e((()=>{n(),r()}));export{u as a,a as i,c as n,l as o,o as r,s as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{l as t,u as n}from"./oauth-BqJqV-2M.js";import{Bt as r,Ot as i}from"./model-CKkOnnnx.js";function a(){return process.env.CLAUDE_BRIDGE_OAUTH_TOKEN||void 0}function o(){return process.env.CLAUDE_BRIDGE_BASE_URL||void 0}function s(){return a()??i()?.accessToken}function c(){return o()??t().BASE_API_URL}function l(){return!!o()}var u=e((()=>{n(),r()}));export{u as a,a as i,c as n,l as o,o as r,s as t};
@@ -0,0 +1 @@
1
+ import{a as e,n as t,o as n,t as r}from"./bridgeConfig-BhxRF2vm.js";e();export{r as getBridgeAccessToken,t as getBridgeBaseUrl,n as isSelfHostedBridge};
@@ -0,0 +1 @@
1
+ import{n as e,r as t,t as n}from"./bridgeEnabled-SbB-6zdY.js";t();export{n as checkBridgeMinVersion,e as getBridgeDisabledReason};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{o as t}from"./envUtils-DSxRz_kt.js";import{Bt as n,Gt as r,jt as i,zt as a}from"./model-BQF64tZx.js";import{i as o,r as s}from"./semver-BMRJYn3q.js";import{a as c,o as l}from"./bridgeConfig-5p_w4s5r.js";function u(){return l()?!0:p()}async function d(){return l()?!0:p()}async function f(){return l()?null:p()?m()?h()?.organizationUuid?null:`Unable to determine your organization for Remote Control eligibility.`:"Remote Control requires a full-scope login token. Long-lived tokens (from `claude setup-token` or CLAUDE_CODE_OAUTH_TOKEN) are limited to inference-only for security reasons.":`Remote Control requires a claude.ai subscription.`}function p(){try{return r()}catch{return!1}}function m(){try{return a()}catch{return!1}}function h(){try{return i()}catch{return}}function g(){return!1}function _(){return!0}function v(){{let e={minVersion:`0.0.0`};if(e.minVersion&&o(`0.0.5`,e.minVersion))return`Your version of Work Mate (0.0.5) is too old for Remote Control.\nVersion ${e.minVersion} or higher is required. Run \`claude update\` to update.`}return null}var y=e((()=>{c(),n(),t(),s()}));export{d as a,u as i,f as n,_ as o,y as r,g as s,v as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{o as t}from"./envUtils-DSxRz_kt.js";import{Bt as n,Gt as r,jt as i,zt as a}from"./model-CKkOnnnx.js";import{i as o,r as s}from"./semver-BMRJYn3q.js";import{a as c,o as l}from"./bridgeConfig-BhxRF2vm.js";function u(){return l()?!0:p()}async function d(){return l()?!0:p()}async function f(){return l()?null:p()?m()?h()?.organizationUuid?null:`Unable to determine your organization for Remote Control eligibility.`:"Remote Control requires a full-scope login token. Long-lived tokens (from `claude setup-token` or CLAUDE_CODE_OAUTH_TOKEN) are limited to inference-only for security reasons.":`Remote Control requires a claude.ai subscription.`}function p(){try{return r()}catch{return!1}}function m(){try{return a()}catch{return!1}}function h(){try{return i()}catch{return}}function g(){return!1}function _(){return!0}function v(){{let e={minVersion:`0.0.0`};if(e.minVersion&&o(`0.0.6`,e.minVersion))return`Your version of Work Mate (0.0.6) is too old for Remote Control.\nVersion ${e.minVersion} or higher is required. Run \`claude update\` to update.`}return null}var y=e((()=>{c(),n(),t(),s()}));export{d as a,u as i,f as n,_ as o,y as r,g as s,v as t};
@@ -1,9 +1,9 @@
1
- import{l as e,o as t,u as n}from"./envUtils-DSxRz_kt.js";import{Gr as r,di as i,t as a,ui as o}from"./src-CDCSSo0U2.js";import{Aa as s,Et as c,Fa as l,Ma as u,NC as d,Na as f,PC as p,Pa as m,ax as h,dx as g,ix as _,ja as v,jt as y,lx as b,nx as ee,ox as x,sx as S,ux as C,vt as w}from"./loadAgentsDir-Clu7Uk6a.js";import{C as T,F as E,S as D,a as O,l as k,w as A,z as j}from"./debug-BrXObCdR.js";import{Gt as M,Kt as N,Wt as te}from"./settings-Dlp5JTa_.js";import{M as P,j as F}from"./git-Do0wJvux.js";import{o as I,s as L}from"./log-BMCygSzM.js";import{i as R,n as z,r as B}from"./analytics-BotDBGh0.js";import{T as V,b as H,u as U}from"./startupProfiler-xa3NmN7Z.js";import{_n as W,vn as G}from"./model-BQF64tZx.js";import{n as K,t as q}from"./rcDebugLog-VKwMl0yg.js";import{c as J,d as ne,f as re,n as Y,o as X,r as ie}from"./debugUtils-NO5KtXqi.js";import{n as ae,s as oe}from"./firstPartyEventLogger-BNGPPBNP.js";import{n as se,t as ce}from"./datadog-UkGdjL8-.js";import{a as le,t as ue}from"./types-Bh9S_JG5.js";import{i as de,n as Z,r as Q}from"./cliLaunch-BkPAatcs.js";import{t as $}from"./lib-BlVGipXx.js";import{t as fe}from"./capacityWake-CV_x9H8j.js";import{t as pe}from"./jwtUtils-DE2GPUcx.js";import{t as me}from"./pollConfig-DH2oCtFS.js";import{i as he}from"./trustedDevice-Dn4rXbxT.js";import{a as ge,i as _e,n as ve,r as ye,t as be}from"./workSecret-CNWiR2uQ.js";import{hostname as xe,tmpdir as Se}from"os";import{basename as Ce,dirname as we,join as Te,resolve as Ee}from"path";import{createWriteStream as De}from"fs";import{randomUUID as Oe}from"crypto";import{spawn as ke}from"child_process";import{createInterface as Ae}from"readline";t(),j(),D(),F(),I(),z(),H(),W(),p(),ce(),ae(),X(),q(),le(),u(),c(),de(),i();var je=$();N(),a(),O(),b();var Me={type:`utf8`,errorCorrectionLevel:`L`,small:!0};async function Ne(e){return(await(0,je.toString)(e,Me)).split(`
1
+ import{l as e,o as t,u as n}from"./envUtils-DSxRz_kt.js";import{Gr as r,di as i,t as a,ui as o}from"./src-CDCSSo0U2.js";import{Aa as s,Et as c,Fa as l,Ma as u,NC as d,Na as f,PC as p,Pa as m,ax as h,dx as g,ix as _,ja as v,jt as y,lx as b,nx as ee,ox as x,sx as S,ux as C,vt as w}from"./loadAgentsDir-D206qwP3.js";import{C as T,F as E,S as D,a as O,l as k,w as A,z as j}from"./debug-BrXObCdR.js";import{Gt as M,Kt as N,Wt as te}from"./settings-BovzmwMP.js";import{M as P,j as F}from"./git-Do0wJvux.js";import{o as I,s as L}from"./log-BMCygSzM.js";import{i as R,n as z,r as B}from"./analytics-BotDBGh0.js";import{T as V,b as H,u as U}from"./startupProfiler-xa3NmN7Z.js";import{_n as W,vn as G}from"./model-CKkOnnnx.js";import{n as K,t as q}from"./rcDebugLog-CUy1_F23.js";import{c as J,d as ne,f as re,n as Y,o as X,r as ie}from"./debugUtils-NO5KtXqi.js";import{n as ae,s as oe}from"./firstPartyEventLogger-CoSUd0a1.js";import{n as se,t as ce}from"./datadog-CpqEQbHa.js";import{a as le,t as ue}from"./types-Bh9S_JG5.js";import{i as de,n as Z,r as Q}from"./cliLaunch-BkPAatcs.js";import{t as $}from"./lib-BlVGipXx.js";import{t as fe}from"./capacityWake-CV_x9H8j.js";import{t as pe}from"./jwtUtils-DE2GPUcx.js";import{t as me}from"./pollConfig-DH2oCtFS.js";import{i as he}from"./trustedDevice-BTYoQCkC.js";import{a as ge,i as _e,n as ve,r as ye,t as be}from"./workSecret-CNWiR2uQ.js";import{hostname as xe,tmpdir as Se}from"os";import{basename as Ce,dirname as we,join as Te,resolve as Ee}from"path";import{createWriteStream as De}from"fs";import{randomUUID as Oe}from"crypto";import{spawn as ke}from"child_process";import{createInterface as Ae}from"readline";t(),j(),D(),F(),I(),z(),H(),W(),p(),ce(),ae(),X(),q(),le(),u(),c(),de(),i();var je=$();N(),a(),O(),b();var Me={type:`utf8`,errorCorrectionLevel:`L`,small:!0};async function Ne(e){return(await(0,je.toString)(e,Me)).split(`
2
2
  `).filter(e=>e.length>0)}function Pe(e){let t=e.write??(e=>process.stdout.write(e)),n=e.verbose,i=0,a=`idle`,s=`Ready`,c=``,l=``,u=``,d=``,f=``,p=``,m=null,v=[],y=!1,b=null,w=0,T=0,E=1,D=null,O=`single-session`,A=new Map,j=null,N=0;function P(e){let t=process.stdout.columns||80,n=0;for(let i of e.split(`
3
3
  `)){if(i.length===0){n++;continue}let e=r(i);n+=Math.max(1,Math.ceil(e/t))}return e.endsWith(`
4
4
  `)&&n--,n}function F(e){t(e),i+=P(e)}function I(){i<=0||(k(`[bridge:ui] clearStatusLines count=${i}`),t(`\x1b[${i}A`),t(`\x1B[J`),i=0)}function L(e){I(),t(e)}function R(e){Ne(e).then(e=>{v=e,W()}).catch(e=>{k(`QR code generation failed: ${e}`,{level:`error`})})}function z(){I();let e=M[N%M.length],t=``;c&&(t+=o.dim(` · `)+o.dim(c)),l&&(t+=o.dim(` · `)+o.dim(l)),F(`${o.yellow(e)} ${o.yellow(`Connecting`)}${t}\n`)}function B(){H(),z(),j=setInterval(()=>{N++,z()},150)}function H(){j&&(clearInterval(j),j=null)}function W(){if(a===`reconnecting`||a===`failed`)return;I();let e=a===`idle`;if(y)for(let e of v)F(`${o.dim(e)}\n`);let t=te,n=e?o.green:o.cyan,r=(e?o.green:o.cyan)(s),i=``;if(c&&(i+=o.dim(` · `)+o.dim(c)),l&&O!==`worktree`&&(i+=o.dim(` · `)+o.dim(l)),process.env.USER_TYPE===`ant`&&u&&F(`${o.yellow(`[ANT-ONLY] Logs:`)} ${o.dim(u)}\n`),F(`${n(t)} ${r}${i}\n`),E>1){let e=O===`worktree`?`New sessions will be created in an isolated worktree`:`New sessions will be created in the current directory`;F(` ${o.dim(`Capacity: ${T}/${E} \u00b7 ${e}`)}\n`);for(let[,e]of A){let t=g(e.title?V(e.title,35):o.dim(`Attached`),e.url),n=e.activity;F(` ${t}${n&&n.type!==`result`&&n.type!==`error`?o.dim(` ${V(n.summary,40)}`):``}
5
5
  `)}}if(E===1){let e=O===`single-session`?`Single session · exits when complete`:O===`worktree`?`Capacity: ${T}/1 \u00b7 New sessions will be created in an isolated worktree`:`Capacity: ${T}/1 \u00b7 New sessions will be created in the current directory`;F(` ${o.dim(e)}\n`)}E===1&&!e&&b&&Date.now()-w<3e4&&F(` ${o.dim(V(b,60))}\n`);let f=m??d;if(f){F(`
6
- `);let t=e?S(f):_(f),n=y?o.dim.italic(`space to hide QR code`):o.dim.italic(`space to show QR code`),r=D?o.dim.italic(` · w to toggle spawn mode`):``;F(`${o.dim(t)}\n`),F(`${n}${r}\n`)}}return{printBanner(e,r){f=e.sessionIngressUrl,p=r,d=h(r,f),R(d),n&&t(o.dim(`Remote Control`)+` v0.0.5
6
+ `);let t=e?S(f):_(f),n=y?o.dim.italic(`space to hide QR code`):o.dim.italic(`space to show QR code`),r=D?o.dim.italic(` · w to toggle spawn mode`):``;F(`${o.dim(t)}\n`),F(`${n}${r}\n`)}}return{printBanner(e,r){f=e.sessionIngressUrl,p=r,d=h(r,f),R(d),n&&t(o.dim(`Remote Control`)+` v0.0.6
7
7
  `),n&&(e.spawnMode!==`single-session`&&(t(o.dim(`Spawn mode: `)+`${e.spawnMode}\n`),t(o.dim(`Max concurrent sessions: `)+`${e.maxSessions}\n`)),t(o.dim(`Environment ID: `)+`${r}\n`)),e.sandbox&&t(o.dim(`Sandbox: `)+`${o.green(`Enabled`)}\n`),t(`
8
8
  `),B()},logSessionStart(e,t){if(n){let n=V(t,80);L(o.dim(`[${C()}]`)+` Session started: ${o.white(`"${n}"`)} (${o.dim(e)})\n`)}},logSessionComplete(e,t){L(o.dim(`[${C()}]`)+` Session ${o.green(`completed`)} (${U(t)}) ${o.dim(e)}\n`)},logSessionFailed(e,t){L(o.dim(`[${C()}]`)+` Session ${o.red(`failed`)}: ${t} ${o.dim(e)}\n`)},logStatus(e){L(o.dim(`[${C()}]`)+` ${e}\n`)},logVerbose(e){n&&L(o.dim(`[${C()}] ${e}`)+`
9
9
  `)},logError(e){L(o.red(`[${C()}] Error: ${e}`)+`
@@ -12,7 +12,7 @@ import{l as e,o as t,u as n}from"./envUtils-DSxRz_kt.js";import{Gr as r,di as i,
12
12
  `),e.onDebug(`[bridge:ws] sessionId=${t.sessionId} <<< ${Y(n)}`),e.verbose&&process.stderr.write(n+`
13
13
  `);let r=Be(n,t.sessionId,e.onDebug);for(let n of r)u.length>=Fe&&u.shift(),u.push(n),d=n,e.onActivity?.(t.sessionId,n);{let r;try{r=T(n)}catch{}if(r&&typeof r==`object`){let n=r;if(n.type===`control_request`)n.request?.subtype===`can_use_tool`&&e.onPermissionRequest&&e.onPermissionRequest(t.sessionId,r,t.accessToken);else if(n.type===`user`&&!m&&t.onFirstUserMessage){let e=Ve(n);e&&(m=!0,t.onFirstUserMessage(e))}}}});let h=new Promise(n=>{l.on(`close`,(r,i)=>{a&&(a.end(),a=null),i===`SIGTERM`||i===`SIGINT`?(e.onDebug(`[bridge:session] sessionId=${t.sessionId} interrupted signal=${i} pid=${l.pid}`),n(`interrupted`)):r===0?(e.onDebug(`[bridge:session] sessionId=${t.sessionId} completed exit_code=0 pid=${l.pid}`),n(`completed`)):(e.onDebug(`[bridge:session] sessionId=${t.sessionId} failed exit_code=${r} pid=${l.pid}`),n(`failed`))}),l.on(`error`,r=>{e.onDebug(`[bridge:session] sessionId=${t.sessionId} spawn error: ${r.message}`),n(`failed`)})}),g={sessionId:t.sessionId,done:h,activities:u,accessToken:t.accessToken,lastStderr:f,get currentActivity(){return d},kill(){l.killed||(e.onDebug(`[bridge:session] Sending SIGTERM to sessionId=${t.sessionId} pid=${l.pid}`),process.platform===`win32`?l.kill():l.kill(`SIGTERM`))},forceKill(){!p&&l.pid&&(p=!0,e.onDebug(`[bridge:session] Sending SIGKILL to sessionId=${t.sessionId} pid=${l.pid}`),process.platform===`win32`?l.kill():l.kill(`SIGKILL`))},writeStdin(n){l.stdin&&!l.stdin.destroyed&&(e.onDebug(`[bridge:ws] sessionId=${t.sessionId} >>> ${Y(n)}`),l.stdin.write(n))},updateAccessToken(n){g.accessToken=n,g.writeStdin(A({type:`update_environment_variables`,variables:{CLAUDE_CODE_SESSION_ACCESS_TOKEN:n}})+`
14
14
  `),e.onDebug(`[bridge:session] Sent token refresh via stdin for sessionId=${t.sessionId}`)}};return g}}}O(),b(),X();var We={connInitialMs:2e3,connCapMs:12e4,connGiveUpMs:6e5,generalInitialMs:500,generalCapMs:3e4,generalGiveUpMs:6e5},Ge=1e3,Ke=32;async function qe(){return!1}function Je(e){return e.connCapMs*2}function Ye(){let e=[...Z()],t=Q();return t&&e.push(t),e}function Xe(e,t,n){try{return e.spawn(t,n)}catch(e){let t=E(e);return L(Error(`Session spawn failed: ${t}`)),t}}async function Ze(t,r,i,a,o,c,u,p=We,h,g){let _=new AbortController;u.aborted?_.abort():u.addEventListener(`abort`,()=>_.abort(),{once:!0});let v=_.signal,b=new Map,ee=new Map,x=new Map,S=new Map,C=new Map,T=new Map,D=new Set,O=new Map,A=new Set,j=new Set,M=fe(v);async function N(){K(`heartbeat: checking ${b.size} active session(s)`);let e=!1,t=!1,n=[];for(let[i]of b){let o=x.get(i),c=C.get(i);if(!(!o||!c))try{await a.heartbeatWork(r,o,c),e=!0}catch(e){k(`[bridge:heartbeat] Failed for sessionId=${i} workId=${o}: ${E(e)}`),e instanceof s&&(B(`tengu_bridge_heartbeat_error`,{status:e.status,error_type:e.status===401||e.status===403?`auth_failed`:`fatal`}),e.status===401||e.status===403?n.push(i):t=!0)}}for(let e of n){c.logVerbose(`Session ${e} token expired — re-queuing via bridge/reconnect`);try{await a.reconnectSession(r,e),k(`[bridge:heartbeat] Re-queued sessionId=${e} via bridge/reconnect`)}catch(t){c.logError(`Failed to refresh session ${e} token: ${E(t)}`),k(`[bridge:heartbeat] reconnectSession(${e}) failed: ${E(t)}`,{level:`error`})}}return t?`fatal`:n.length>0?`auth_failed`:e?`ok`:`failed`}let te=new Set,F=g?pe({getAccessToken:g,onRefresh:(e,t)=>{let n=b.get(e);n&&(te.has(e)?(c.logVerbose(`Refreshing session ${e} token via bridge/reconnect`),a.reconnectSession(r,e).catch(t=>{c.logError(`Failed to refresh session ${e} token: ${E(t)}`),k(`[bridge:token] reconnectSession(${e}) failed: ${E(t)}`,{level:`error`})})):n.updateAccessToken(t))},label:`bridge`}):null,I=Date.now(),R=new Set;function z(e){R.add(e),e.finally(()=>R.delete(e))}let V=0,H=0,W=null,q=null,J=null,re=null,Y=!1;if(k(`[bridge:work] Starting poll loop spawnMode=${t.spawnMode} maxSessions=${t.maxSessions} environmentId=${r}`),P(`info`,`bridge_loop_started`,{max_sessions:t.maxSessions,spawn_mode:t.spawnMode}),process.env.USER_TYPE===`ant`){let e;if(t.debugFile){let n=t.debugFile.lastIndexOf(`.`);e=n>0?`${t.debugFile.slice(0,n)}-*${t.debugFile.slice(n)}`:`${t.debugFile}-*`}else e=Te(Se(),`claude`,`bridge-session-*.log`);c.setDebugLogPath(e)}c.printBanner(t,r),c.updateSessionCount(0,t.maxSessions,t.spawnMode),h&&c.setAttached(h);function X(){c.updateSessionCount(b.size,t.maxSessions,t.spawnMode);for(let[e,t]of b){let n=t.currentActivity;n&&c.updateSessionActivity(S.get(e)??e,n)}if(b.size===0){c.updateIdleStatus();return}let[e,n]=[...b.entries()].pop(),r=ee.get(e);if(!r)return;let i=n.currentActivity;if(!i||i.type===`result`||i.type===`error`){t.maxSessions>1&&c.refreshDisplay();return}let a=U(Date.now()-r),o=n.activities.filter(e=>e.type===`tool_start`).slice(-5).map(e=>e.summary);c.updateSessionStatus(e,a,i,o)}function ae(){oe(),X(),re=setInterval(X,Ge)}function oe(){re&&(clearInterval(re),re=null)}function se(e,n,i){return o=>{let s=x.get(e);K(`session done: sessionId=${e} workId=${s??`none`} status=${o} wasTimedOut=${A.has(e)} duration=${Math.round((Date.now()-n)/1e3)}s stderr=${i.lastStderr.length>0?i.lastStderr.join(`\\n`).slice(0,500):`(none)`}`),b.delete(e),ee.delete(e),x.delete(e),C.delete(e);let l=S.get(e)??e;S.delete(e),c.removeSession(l),j.delete(l),te.delete(e);let u=T.get(e);u&&(clearTimeout(u),T.delete(e)),F?.cancel(e),M.wake();let d=A.delete(e),f=d&&o===`interrupted`?`failed`:o,m=Date.now()-n;k(`[bridge:session] sessionId=${e} workId=${s??`unknown`} exited status=${f} duration=${U(m)}`),B(`tengu_bridge_session_done`,{status:f,duration_ms:m}),P(`info`,`bridge_session_done`,{status:f,duration_ms:m}),c.clearStatus(),oe();let h=i.lastStderr.length>0?i.lastStderr.join(`
15
- `):void 0,g;switch(f){case`completed`:c.logSessionComplete(e,m);break;case`failed`:!d&&!v.aborted&&(g=h??`Process exited with error`,c.logSessionFailed(e,g),L(Error(`Bridge session failed: ${g}`)));break;case`interrupted`:c.logVerbose(`Session ${e} interrupted`);break}f!==`interrupted`&&s&&(z(rt(a,r,s,c,p.stopWorkBaseDelayMs)),D.add(s));let w=O.get(e);if(w&&(O.delete(e),z(y(w.worktreePath,w.worktreeBranch,w.gitRoot,w.hookBased).catch(e=>c.logVerbose(`Failed to remove worktree ${w.worktreePath}: ${E(e)}`)))),f!==`interrupted`&&!v.aborted)if(t.spawnMode!==`single-session`)z(a.archiveSession(l).catch(t=>c.logVerbose(`Failed to archive session ${e}: ${E(t)}`))),k(`[bridge:session] Session ${f}, returning to idle (multi-session mode)`);else{k(`[bridge:session] Session ${f}, aborting poll loop to tear down environment`),_.abort();return}v.aborted||ae()}}for(h||ae();!v.aborted;){let u=me();try{K(`poll: envId=${r} activeSessions=${b.size}`);let s=await a.pollForWork(r,i,v,u.reclaim_older_than_ms);if(W!==null||q!==null){let e=Date.now()-(W??q??Date.now());c.logReconnected(e),k(`[bridge:poll] Reconnected after ${U(e)}`),B(`tengu_bridge_reconnected`,{disconnected_ms:e})}if(V=0,H=0,W=null,q=null,J=null,!s){if(b.size>=t.maxSessions){let e=u.multisession_poll_interval_ms_at_capacity;if(u.non_exclusive_heartbeat_interval_ms>0){B(`tengu_bridge_heartbeat_mode_entered`,{active_sessions:b.size,heartbeat_interval_ms:u.non_exclusive_heartbeat_interval_ms});let n=e>0?Date.now()+e:null,r=`ok`,i=0;for(;!v.aborted&&b.size>=t.maxSessions&&(n===null||Date.now()<n);){let e=me();if(e.non_exclusive_heartbeat_interval_ms<=0)break;let t=M.signal();if(r=await N(),r===`auth_failed`||r===`fatal`){t.cleanup();break}i++,await G(e.non_exclusive_heartbeat_interval_ms,t.signal),t.cleanup()}let a=r===`auth_failed`||r===`fatal`?r:v.aborted?`shutdown`:b.size<t.maxSessions?`capacity_changed`:n!==null&&Date.now()>=n?`poll_due`:`config_disabled`;if(B(`tengu_bridge_heartbeat_mode_exited`,{reason:a,heartbeat_cycles:i,active_sessions:b.size}),a===`poll_due`&&k(`[bridge:poll] Heartbeat poll_due after ${i} cycles — falling through to pollForWork`),r===`auth_failed`||r===`fatal`){let t=M.signal();await G(e>0?e:u.non_exclusive_heartbeat_interval_ms,t.signal),t.cleanup()}}else if(e>0){let t=M.signal();await G(e,t.signal),t.cleanup()}}else await G(b.size>0?u.multisession_poll_interval_ms_partial_capacity:u.multisession_poll_interval_ms_not_at_capacity,v);continue}let f=b.size>=t.maxSessions;if(D.has(s.id)){if(k(`[bridge:work] Skipping already-completed workId=${s.id}`),f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}else await G(1e3,v);continue}let m;try{m=ye(s.secret)}catch(e){let t=E(e);if(c.logError(`Failed to decode work secret for workId=${s.id}: ${t}`),B(`tengu_bridge_work_secret_failed`,{}),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs)),f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}continue}let g=async()=>{k(`[bridge:work] Acknowledging workId=${s.id}`);try{await a.acknowledgeWork(r,s.id,m.session_ingress_token)}catch(e){k(`[bridge:work] Acknowledge failed workId=${s.id}: ${E(e)}`)}},_=s.data.type;switch(s.data.type){case`healthcheck`:await g(),k(`[bridge:work] Healthcheck received`),c.logVerbose(`Healthcheck received`);break;case`session`:{let i=s.data.id;K(`work received: type=session sessionId=${i} workId=${s.id}`);try{l(i,`session_id`)}catch{await g(),c.logError(`Invalid session_id received: ${i}`);break}let u=b.get(i);if(u){u.updateAccessToken(m.session_ingress_token),C.set(i,m.session_ingress_token),x.set(i,s.id),F?.schedule(i,m.session_ingress_token),k(`[bridge:work] Updated access token for existing sessionId=${i} workId=${s.id}`),await g();break}if(b.size>=t.maxSessions){k(`[bridge:work] At capacity (${b.size}/${t.maxSessions}), cannot spawn new session for workId=${s.id}`);break}await g();let f=Date.now(),_,M=!1,N;if(m.use_code_sessions===!0||e(process.env.CLAUDE_BRIDGE_USE_CCR_V2)){_=be(t.apiBaseUrl,i);for(let e=1;e<=2;e++)try{N=await _e(_,m.session_ingress_token),M=!0,k(`[bridge:session] CCR v2: registered worker sessionId=${i} epoch=${N} attempt=${e}`);break}catch(t){let n=E(t);if(e<2){if(k(`[bridge:session] CCR v2: registerWorker attempt ${e} failed, retrying: ${n}`),await G(2e3,v),v.aborted)break;continue}c.logError(`CCR v2 worker registration failed for session ${i}: ${n}`),L(Error(`registerWorker failed: ${n}`)),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs))}if(!M)break}else _=ve(t.sessionIngressUrl,i);let I=t.spawnMode,R=t.dir,V=0;if(I===`worktree`&&(h===void 0||!ge(i,h))){let e=Date.now();try{let t=await w(`bridge-${Le(i)}`);V=Date.now()-e,O.set(i,{worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,gitRoot:t.gitRoot,hookBased:t.hookBased}),R=t.worktreePath,k(`[bridge:session] Created worktree for sessionId=${i} at ${t.worktreePath}`)}catch(e){let t=E(e);c.logError(`Failed to create worktree for session ${i}: ${t}`),L(Error(`Worktree creation failed: ${t}`)),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs));break}}k(`[bridge:session] Spawning sessionId=${i} sdkUrl=${_}`);let H=ne(i);K(`spawning session: sessionId=${i} sdkUrl=${_} useCcrV2=${M} workerEpoch=${N} dir=${R} accessToken=${m.session_ingress_token?m.session_ingress_token.slice(0,8)+`...`:`NONE`}`);let U=Xe(o,{sessionId:i,sdkUrl:_,accessToken:m.session_ingress_token,useCcrV2:M,workerEpoch:N,onFirstUserMessage:e=>{if(j.has(H))return;j.add(H);let n=dt(e);c.setSessionTitle(H,n),k(`[bridge:title] derived title for ${H}: ${n}`),import(`./createSession-DUfOAeyE.js`).then(({updateBridgeSessionTitle:e})=>e(H,n,{baseUrl:t.apiBaseUrl})).catch(e=>k(`[bridge:title] failed to update title for ${H}: ${e}`,{level:`error`}))}},R);if(typeof U==`string`){c.logError(`Failed to spawn session ${i}: ${U}`);let e=O.get(i);e&&(O.delete(i),z(y(e.worktreePath,e.worktreeBranch,e.gitRoot,e.hookBased).catch(t=>c.logVerbose(`Failed to remove worktree ${e.worktreePath}: ${E(t)}`)))),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs));break}let W=U,q=Date.now()-f;B(`tengu_bridge_session_started`,{active_sessions:b.size,spawn_mode:I,in_worktree:O.has(i),spawn_duration_ms:q,worktree_create_ms:V,inProtectedNamespace:n()}),P(`info`,`bridge_session_started`,{spawn_mode:I,in_worktree:O.has(i),spawn_duration_ms:q,worktree_create_ms:V}),b.set(i,W),x.set(i,s.id),C.set(i,m.session_ingress_token),S.set(i,H);let J=Date.now();ee.set(i,J),c.logSessionStart(i,`Session ${i}`);let re=Le(i),Y;if(t.debugFile){let e=t.debugFile.lastIndexOf(`.`);Y=e>0?`${t.debugFile.slice(0,e)}-${re}${t.debugFile.slice(e)}`:`${t.debugFile}-${re}`}else(t.verbose||process.env.USER_TYPE===`ant`)&&(Y=Te(Se(),`claude`,`bridge-session-${re}.log`));Y&&c.logVerbose(`Debug log: ${Y}`),c.addSession(H,d(H,t.sessionIngressUrl)),ae(),c.setAttached(H),ft(H,t.apiBaseUrl).then(e=>{e&&b.has(i)&&(j.add(H),c.setSessionTitle(H,e),k(`[bridge:title] server title for ${H}: ${e}`))}).catch(e=>k(`[bridge:title] failed to fetch title for ${H}: ${e}`,{level:`error`}));let X=t.sessionTimeoutMs??864e5;if(X>0){let e=setTimeout(it,X,i,X,c,A,W);T.set(i,e)}M&&te.add(i),F?.schedule(i,m.session_ingress_token),W.done.then(se(i,J,W));break}default:await g(),k(`[bridge:work] Unknown work type: ${_}, skipping`);break}if(f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}}catch(e){if(v.aborted)break;if(e instanceof s){Y=!0,f(e.errorType)?c.logStatus(e.message):m(e)?k(`[bridge:work] Suppressed 403 error: ${e.message}`):(c.logError(e.message),L(e)),B(`tengu_bridge_fatal_error`,{status:e.status,error_type:e.errorType}),P(f(e.errorType)?`info`:`error`,`bridge_fatal_error`,{status:e.status,error_type:e.errorType});break}let t=ie(e);if(K(`poll error: ${t} isConn=${$e(e)} isServer=${et(e)} activeSessions=${b.size}`),$e(e)||et(e)){let e=Date.now();J!==null&&e-J>Je(p)&&(k(`[bridge:work] Detected system sleep (${Math.round((e-J)/1e3)}s gap), resetting error budget`),P(`info`,`bridge_poll_sleep_detected`,{gapMs:e-J}),W=null,V=0,q=null,H=0),J=e,W||(W=e);let n=e-W;if(n>=p.connGiveUpMs){c.logError(`Server unreachable for ${Math.round(n/6e4)} minutes, giving up.`),B(`tengu_bridge_poll_give_up`,{error_type:`connection`,elapsed_ms:n}),P(`error`,`bridge_poll_give_up`,{error_type:`connection`,elapsed_ms:n}),Y=!0;break}q=null,H=0,V=V?Math.min(V*2,p.connCapMs):p.connInitialMs;let r=tt(V);c.logVerbose(`Connection error, retrying in ${nt(r)} (${Math.round(n/1e3)}s elapsed): ${t}`),c.updateReconnectingStatus(nt(r),U(n)),me().non_exclusive_heartbeat_interval_ms>0&&await N(),await G(r,v)}else{let e=Date.now();J!==null&&e-J>Je(p)&&(k(`[bridge:work] Detected system sleep (${Math.round((e-J)/1e3)}s gap), resetting error budget`),P(`info`,`bridge_poll_sleep_detected`,{gapMs:e-J}),W=null,V=0,q=null,H=0),J=e,q||(q=e);let n=e-q;if(n>=p.generalGiveUpMs){c.logError(`Persistent errors for ${Math.round(n/6e4)} minutes, giving up.`),B(`tengu_bridge_poll_give_up`,{error_type:`general`,elapsed_ms:n}),P(`error`,`bridge_poll_give_up`,{error_type:`general`,elapsed_ms:n}),Y=!0;break}W=null,V=0,H=H?Math.min(H*2,p.generalCapMs):p.generalInitialMs;let r=tt(H);c.logVerbose(`Poll failed, retrying in ${nt(r)} (${Math.round(n/1e3)}s elapsed): ${t}`),c.updateReconnectingStatus(nt(r),U(n)),me().non_exclusive_heartbeat_interval_ms>0&&await N(),await G(r,v)}}}oe(),c.clearStatus();let ce=Date.now()-I;B(`tengu_bridge_shutdown`,{active_sessions:b.size,loop_duration_ms:ce}),P(`info`,`bridge_shutdown`,{active_sessions:b.size,loop_duration_ms:ce});let le=new Set(b.keys());h&&le.add(h);let ue=new Map(S);if(b.size>0){k(`[bridge:shutdown] Shutting down ${b.size} active session(s)`),c.logStatus(`Shutting down ${b.size} active session(s)\u2026`);let e=new Map(x);for(let[e,t]of b.entries())k(`[bridge:shutdown] Sending SIGTERM to sessionId=${e}`),t.kill();let t=new AbortController;await Promise.race([Promise.allSettled([...b.values()].map(e=>e.done)),G(p.shutdownGraceMs??3e4,t.signal)]),t.abort();for(let[e,t]of b.entries())k(`[bridge:shutdown] Force-killing stuck sessionId=${e}`),t.forceKill();for(let e of T.values())clearTimeout(e);if(T.clear(),F?.cancelAll(),O.size>0){let e=[...O.values()];O.clear(),k(`[bridge:shutdown] Cleaning up ${e.length} worktree(s)`),await Promise.allSettled(e.map(e=>y(e.worktreePath,e.worktreeBranch,e.gitRoot,e.hookBased)))}await Promise.allSettled([...e.entries()].map(([e,t])=>a.stopWork(r,t,!0).catch(n=>c.logVerbose(`Failed to stop work ${t} for session ${e}: ${E(n)}`))))}if(R.size>0&&await Promise.allSettled([...R]),t.spawnMode===`single-session`&&h&&!Y){c.logStatus("Resume this session by running `claude remote-control --continue`"),k(`[bridge:shutdown] Skipping archive+deregister to allow resume of session ${h}`);return}le.size>0&&(k(`[bridge:shutdown] Archiving ${le.size} session(s)`),await Promise.allSettled([...le].map(e=>a.archiveSession(ue.get(e)??ne(e)).catch(t=>c.logVerbose(`Failed to archive session ${e}: ${E(t)}`)))));try{await a.deregisterEnvironment(r),k(`[bridge:shutdown] Environment deregistered, bridge offline`),c.logVerbose(`Environment deregistered.`)}catch(e){c.logVerbose(`Failed to deregister environment: ${E(e)}`)}let{clearBridgePointer:de}=await import(`./bridgePointer-MqLe5Asm.js`);await de(t.dir),c.logVerbose(`Environment offline.`)}var Qe=new Set([`ECONNREFUSED`,`ECONNRESET`,`ETIMEDOUT`,`ENETUNREACH`,`EHOSTUNREACH`]);function $e(e){return!!(e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`&&Qe.has(e.code))}function et(e){return!!e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`&&e.code===`ERR_BAD_RESPONSE`}function tt(e){return Math.max(0,e+e*.25*(2*Math.random()-1))}function nt(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}async function rt(e,t,n,r,i=1e3){for(let a=1;a<=3;a++)try{await e.stopWork(t,n,!1),k(`[bridge:work] stopWork succeeded for workId=${n} on attempt ${a}/3`);return}catch(e){if(e instanceof s){m(e)?k(`[bridge:work] Suppressed stopWork 403 for ${n}: ${e.message}`):r.logError(`Failed to stop work ${n}: ${e.message}`),P(`error`,`bridge_stop_work_failed`,{attempts:a,fatal:!0});return}let t=E(e);if(a<3){let e=tt(i*2**(a-1));r.logVerbose(`Failed to stop work ${n} (attempt ${a}/3), retrying in ${nt(e)}: ${t}`),await G(e)}else r.logError(`Failed to stop work ${n} after 3 attempts: ${t}`),P(`error`,`bridge_stop_work_failed`,{attempts:3})}}function it(e,t,n,r,i){k(`[bridge:session] sessionId=${e} timed out after ${U(t)}`),B(`tengu_bridge_session_timeout`,{timeout_ms:t}),n.logSessionFailed(e,`Session timed out after ${U(t)}`),r.add(e),i.kill()}var at=[`session`,`same-dir`,`worktree`];function ot(e){return e===`session`?`single-session`:e===`same-dir`?`same-dir`:e===`worktree`?`worktree`:`--spawn requires one of: ${at.join(`, `)} (got: ${e??`<missing>`})`}function st(e){let t=e===void 0?NaN:parseInt(e,10);return isNaN(t)||t<1?`--capacity requires a positive integer (got: ${e??`<missing>`})`:t}function ct(e){let t=!1,n=!1,r,i,a,o,s=!1,c,l,u,d,f=!1;for(let m=0;m<e.length;m++){let h=e[m];if(h===`--help`||h===`-h`)s=!0;else if(h===`--verbose`||h===`-v`)t=!0;else if(h===`--sandbox`)n=!0;else if(h===`--no-sandbox`)n=!1;else if(h===`--debug-file`&&m+1<e.length)r=Ee(e[++m]);else if(h.startsWith(`--debug-file=`))r=Ee(h.slice(13));else if(h===`--session-timeout`&&m+1<e.length)i=parseInt(e[++m],10)*1e3;else if(h.startsWith(`--session-timeout=`))i=parseInt(h.slice(18),10)*1e3;else if(h===`--permission-mode`&&m+1<e.length)a=e[++m];else if(h.startsWith(`--permission-mode=`))a=h.slice(18);else if(h===`--name`&&m+1<e.length)o=e[++m];else if(h.startsWith(`--name=`))o=h.slice(7);else if(h===`--session-id`&&m+1<e.length){if(d=e[++m],!d)return p(`--session-id requires a value`)}else if(h.startsWith(`--session-id=`)){if(d=h.slice(13),!d)return p(`--session-id requires a value`)}else if(h===`--continue`||h===`-c`)f=!0;else if(h===`--spawn`||h.startsWith(`--spawn=`)){if(c!==void 0)return p(`--spawn may only be specified once`);let t=ot(h.startsWith(`--spawn=`)?h.slice(8):e[++m]);if(t===`single-session`||t===`same-dir`||t===`worktree`)c=t;else return p(t)}else if(h===`--capacity`||h.startsWith(`--capacity=`)){if(l!==void 0)return p(`--capacity may only be specified once`);let t=st(h.startsWith(`--capacity=`)?h.slice(11):e[++m]);if(typeof t==`number`)l=t;else return p(t)}else if(h===`--create-session-in-dir`)u=!0;else if(h===`--no-create-session-in-dir`)u=!1;else return p(`Unknown argument: ${h}\nRun 'claude remote-control --help' for usage.`)}if(c===`single-session`&&l!==void 0)return p(`--capacity cannot be used with --spawn=session (single-session mode has fixed capacity 1).`);if((d||f)&&(c!==void 0||l!==void 0||u!==void 0))return p(`--session-id and --continue cannot be used with --spawn, --capacity, or --create-session-in-dir.`);if(d&&f)return p(`--session-id and --continue cannot be used together.`);return{verbose:t,sandbox:n,debugFile:r,sessionTimeoutMs:i,permissionMode:a,name:o,spawnMode:c,capacity:l,createSessionInDir:u,sessionId:d,continueSession:f,help:s};function p(e){return{verbose:t,sandbox:n,debugFile:r,sessionTimeoutMs:i,permissionMode:a,name:o,spawnMode:c,capacity:l,createSessionInDir:u,sessionId:d,continueSession:f,help:s,error:e}}}async function lt(){let{EXTERNAL_PERMISSION_MODES:e}=await import(`./permissions-CeYKbtSC.js`),t=e.join(`, `),n=await qe(),r=`
15
+ `):void 0,g;switch(f){case`completed`:c.logSessionComplete(e,m);break;case`failed`:!d&&!v.aborted&&(g=h??`Process exited with error`,c.logSessionFailed(e,g),L(Error(`Bridge session failed: ${g}`)));break;case`interrupted`:c.logVerbose(`Session ${e} interrupted`);break}f!==`interrupted`&&s&&(z(rt(a,r,s,c,p.stopWorkBaseDelayMs)),D.add(s));let w=O.get(e);if(w&&(O.delete(e),z(y(w.worktreePath,w.worktreeBranch,w.gitRoot,w.hookBased).catch(e=>c.logVerbose(`Failed to remove worktree ${w.worktreePath}: ${E(e)}`)))),f!==`interrupted`&&!v.aborted)if(t.spawnMode!==`single-session`)z(a.archiveSession(l).catch(t=>c.logVerbose(`Failed to archive session ${e}: ${E(t)}`))),k(`[bridge:session] Session ${f}, returning to idle (multi-session mode)`);else{k(`[bridge:session] Session ${f}, aborting poll loop to tear down environment`),_.abort();return}v.aborted||ae()}}for(h||ae();!v.aborted;){let u=me();try{K(`poll: envId=${r} activeSessions=${b.size}`);let s=await a.pollForWork(r,i,v,u.reclaim_older_than_ms);if(W!==null||q!==null){let e=Date.now()-(W??q??Date.now());c.logReconnected(e),k(`[bridge:poll] Reconnected after ${U(e)}`),B(`tengu_bridge_reconnected`,{disconnected_ms:e})}if(V=0,H=0,W=null,q=null,J=null,!s){if(b.size>=t.maxSessions){let e=u.multisession_poll_interval_ms_at_capacity;if(u.non_exclusive_heartbeat_interval_ms>0){B(`tengu_bridge_heartbeat_mode_entered`,{active_sessions:b.size,heartbeat_interval_ms:u.non_exclusive_heartbeat_interval_ms});let n=e>0?Date.now()+e:null,r=`ok`,i=0;for(;!v.aborted&&b.size>=t.maxSessions&&(n===null||Date.now()<n);){let e=me();if(e.non_exclusive_heartbeat_interval_ms<=0)break;let t=M.signal();if(r=await N(),r===`auth_failed`||r===`fatal`){t.cleanup();break}i++,await G(e.non_exclusive_heartbeat_interval_ms,t.signal),t.cleanup()}let a=r===`auth_failed`||r===`fatal`?r:v.aborted?`shutdown`:b.size<t.maxSessions?`capacity_changed`:n!==null&&Date.now()>=n?`poll_due`:`config_disabled`;if(B(`tengu_bridge_heartbeat_mode_exited`,{reason:a,heartbeat_cycles:i,active_sessions:b.size}),a===`poll_due`&&k(`[bridge:poll] Heartbeat poll_due after ${i} cycles — falling through to pollForWork`),r===`auth_failed`||r===`fatal`){let t=M.signal();await G(e>0?e:u.non_exclusive_heartbeat_interval_ms,t.signal),t.cleanup()}}else if(e>0){let t=M.signal();await G(e,t.signal),t.cleanup()}}else await G(b.size>0?u.multisession_poll_interval_ms_partial_capacity:u.multisession_poll_interval_ms_not_at_capacity,v);continue}let f=b.size>=t.maxSessions;if(D.has(s.id)){if(k(`[bridge:work] Skipping already-completed workId=${s.id}`),f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}else await G(1e3,v);continue}let m;try{m=ye(s.secret)}catch(e){let t=E(e);if(c.logError(`Failed to decode work secret for workId=${s.id}: ${t}`),B(`tengu_bridge_work_secret_failed`,{}),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs)),f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}continue}let g=async()=>{k(`[bridge:work] Acknowledging workId=${s.id}`);try{await a.acknowledgeWork(r,s.id,m.session_ingress_token)}catch(e){k(`[bridge:work] Acknowledge failed workId=${s.id}: ${E(e)}`)}},_=s.data.type;switch(s.data.type){case`healthcheck`:await g(),k(`[bridge:work] Healthcheck received`),c.logVerbose(`Healthcheck received`);break;case`session`:{let i=s.data.id;K(`work received: type=session sessionId=${i} workId=${s.id}`);try{l(i,`session_id`)}catch{await g(),c.logError(`Invalid session_id received: ${i}`);break}let u=b.get(i);if(u){u.updateAccessToken(m.session_ingress_token),C.set(i,m.session_ingress_token),x.set(i,s.id),F?.schedule(i,m.session_ingress_token),k(`[bridge:work] Updated access token for existing sessionId=${i} workId=${s.id}`),await g();break}if(b.size>=t.maxSessions){k(`[bridge:work] At capacity (${b.size}/${t.maxSessions}), cannot spawn new session for workId=${s.id}`);break}await g();let f=Date.now(),_,M=!1,N;if(m.use_code_sessions===!0||e(process.env.CLAUDE_BRIDGE_USE_CCR_V2)){_=be(t.apiBaseUrl,i);for(let e=1;e<=2;e++)try{N=await _e(_,m.session_ingress_token),M=!0,k(`[bridge:session] CCR v2: registered worker sessionId=${i} epoch=${N} attempt=${e}`);break}catch(t){let n=E(t);if(e<2){if(k(`[bridge:session] CCR v2: registerWorker attempt ${e} failed, retrying: ${n}`),await G(2e3,v),v.aborted)break;continue}c.logError(`CCR v2 worker registration failed for session ${i}: ${n}`),L(Error(`registerWorker failed: ${n}`)),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs))}if(!M)break}else _=ve(t.sessionIngressUrl,i);let I=t.spawnMode,R=t.dir,V=0;if(I===`worktree`&&(h===void 0||!ge(i,h))){let e=Date.now();try{let t=await w(`bridge-${Le(i)}`);V=Date.now()-e,O.set(i,{worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,gitRoot:t.gitRoot,hookBased:t.hookBased}),R=t.worktreePath,k(`[bridge:session] Created worktree for sessionId=${i} at ${t.worktreePath}`)}catch(e){let t=E(e);c.logError(`Failed to create worktree for session ${i}: ${t}`),L(Error(`Worktree creation failed: ${t}`)),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs));break}}k(`[bridge:session] Spawning sessionId=${i} sdkUrl=${_}`);let H=ne(i);K(`spawning session: sessionId=${i} sdkUrl=${_} useCcrV2=${M} workerEpoch=${N} dir=${R} accessToken=${m.session_ingress_token?m.session_ingress_token.slice(0,8)+`...`:`NONE`}`);let U=Xe(o,{sessionId:i,sdkUrl:_,accessToken:m.session_ingress_token,useCcrV2:M,workerEpoch:N,onFirstUserMessage:e=>{if(j.has(H))return;j.add(H);let n=dt(e);c.setSessionTitle(H,n),k(`[bridge:title] derived title for ${H}: ${n}`),import(`./createSession-CoQtL5Rj.js`).then(({updateBridgeSessionTitle:e})=>e(H,n,{baseUrl:t.apiBaseUrl})).catch(e=>k(`[bridge:title] failed to update title for ${H}: ${e}`,{level:`error`}))}},R);if(typeof U==`string`){c.logError(`Failed to spawn session ${i}: ${U}`);let e=O.get(i);e&&(O.delete(i),z(y(e.worktreePath,e.worktreeBranch,e.gitRoot,e.hookBased).catch(t=>c.logVerbose(`Failed to remove worktree ${e.worktreePath}: ${E(t)}`)))),D.add(s.id),z(rt(a,r,s.id,c,p.stopWorkBaseDelayMs));break}let W=U,q=Date.now()-f;B(`tengu_bridge_session_started`,{active_sessions:b.size,spawn_mode:I,in_worktree:O.has(i),spawn_duration_ms:q,worktree_create_ms:V,inProtectedNamespace:n()}),P(`info`,`bridge_session_started`,{spawn_mode:I,in_worktree:O.has(i),spawn_duration_ms:q,worktree_create_ms:V}),b.set(i,W),x.set(i,s.id),C.set(i,m.session_ingress_token),S.set(i,H);let J=Date.now();ee.set(i,J),c.logSessionStart(i,`Session ${i}`);let re=Le(i),Y;if(t.debugFile){let e=t.debugFile.lastIndexOf(`.`);Y=e>0?`${t.debugFile.slice(0,e)}-${re}${t.debugFile.slice(e)}`:`${t.debugFile}-${re}`}else(t.verbose||process.env.USER_TYPE===`ant`)&&(Y=Te(Se(),`claude`,`bridge-session-${re}.log`));Y&&c.logVerbose(`Debug log: ${Y}`),c.addSession(H,d(H,t.sessionIngressUrl)),ae(),c.setAttached(H),ft(H,t.apiBaseUrl).then(e=>{e&&b.has(i)&&(j.add(H),c.setSessionTitle(H,e),k(`[bridge:title] server title for ${H}: ${e}`))}).catch(e=>k(`[bridge:title] failed to fetch title for ${H}: ${e}`,{level:`error`}));let X=t.sessionTimeoutMs??864e5;if(X>0){let e=setTimeout(it,X,i,X,c,A,W);T.set(i,e)}M&&te.add(i),F?.schedule(i,m.session_ingress_token),W.done.then(se(i,J,W));break}default:await g(),k(`[bridge:work] Unknown work type: ${_}, skipping`);break}if(f){let e=M.signal();u.non_exclusive_heartbeat_interval_ms>0?(await N(),await G(u.non_exclusive_heartbeat_interval_ms,e.signal)):u.multisession_poll_interval_ms_at_capacity>0&&await G(u.multisession_poll_interval_ms_at_capacity,e.signal),e.cleanup()}}catch(e){if(v.aborted)break;if(e instanceof s){Y=!0,f(e.errorType)?c.logStatus(e.message):m(e)?k(`[bridge:work] Suppressed 403 error: ${e.message}`):(c.logError(e.message),L(e)),B(`tengu_bridge_fatal_error`,{status:e.status,error_type:e.errorType}),P(f(e.errorType)?`info`:`error`,`bridge_fatal_error`,{status:e.status,error_type:e.errorType});break}let t=ie(e);if(K(`poll error: ${t} isConn=${$e(e)} isServer=${et(e)} activeSessions=${b.size}`),$e(e)||et(e)){let e=Date.now();J!==null&&e-J>Je(p)&&(k(`[bridge:work] Detected system sleep (${Math.round((e-J)/1e3)}s gap), resetting error budget`),P(`info`,`bridge_poll_sleep_detected`,{gapMs:e-J}),W=null,V=0,q=null,H=0),J=e,W||(W=e);let n=e-W;if(n>=p.connGiveUpMs){c.logError(`Server unreachable for ${Math.round(n/6e4)} minutes, giving up.`),B(`tengu_bridge_poll_give_up`,{error_type:`connection`,elapsed_ms:n}),P(`error`,`bridge_poll_give_up`,{error_type:`connection`,elapsed_ms:n}),Y=!0;break}q=null,H=0,V=V?Math.min(V*2,p.connCapMs):p.connInitialMs;let r=tt(V);c.logVerbose(`Connection error, retrying in ${nt(r)} (${Math.round(n/1e3)}s elapsed): ${t}`),c.updateReconnectingStatus(nt(r),U(n)),me().non_exclusive_heartbeat_interval_ms>0&&await N(),await G(r,v)}else{let e=Date.now();J!==null&&e-J>Je(p)&&(k(`[bridge:work] Detected system sleep (${Math.round((e-J)/1e3)}s gap), resetting error budget`),P(`info`,`bridge_poll_sleep_detected`,{gapMs:e-J}),W=null,V=0,q=null,H=0),J=e,q||(q=e);let n=e-q;if(n>=p.generalGiveUpMs){c.logError(`Persistent errors for ${Math.round(n/6e4)} minutes, giving up.`),B(`tengu_bridge_poll_give_up`,{error_type:`general`,elapsed_ms:n}),P(`error`,`bridge_poll_give_up`,{error_type:`general`,elapsed_ms:n}),Y=!0;break}W=null,V=0,H=H?Math.min(H*2,p.generalCapMs):p.generalInitialMs;let r=tt(H);c.logVerbose(`Poll failed, retrying in ${nt(r)} (${Math.round(n/1e3)}s elapsed): ${t}`),c.updateReconnectingStatus(nt(r),U(n)),me().non_exclusive_heartbeat_interval_ms>0&&await N(),await G(r,v)}}}oe(),c.clearStatus();let ce=Date.now()-I;B(`tengu_bridge_shutdown`,{active_sessions:b.size,loop_duration_ms:ce}),P(`info`,`bridge_shutdown`,{active_sessions:b.size,loop_duration_ms:ce});let le=new Set(b.keys());h&&le.add(h);let ue=new Map(S);if(b.size>0){k(`[bridge:shutdown] Shutting down ${b.size} active session(s)`),c.logStatus(`Shutting down ${b.size} active session(s)\u2026`);let e=new Map(x);for(let[e,t]of b.entries())k(`[bridge:shutdown] Sending SIGTERM to sessionId=${e}`),t.kill();let t=new AbortController;await Promise.race([Promise.allSettled([...b.values()].map(e=>e.done)),G(p.shutdownGraceMs??3e4,t.signal)]),t.abort();for(let[e,t]of b.entries())k(`[bridge:shutdown] Force-killing stuck sessionId=${e}`),t.forceKill();for(let e of T.values())clearTimeout(e);if(T.clear(),F?.cancelAll(),O.size>0){let e=[...O.values()];O.clear(),k(`[bridge:shutdown] Cleaning up ${e.length} worktree(s)`),await Promise.allSettled(e.map(e=>y(e.worktreePath,e.worktreeBranch,e.gitRoot,e.hookBased)))}await Promise.allSettled([...e.entries()].map(([e,t])=>a.stopWork(r,t,!0).catch(n=>c.logVerbose(`Failed to stop work ${t} for session ${e}: ${E(n)}`))))}if(R.size>0&&await Promise.allSettled([...R]),t.spawnMode===`single-session`&&h&&!Y){c.logStatus("Resume this session by running `claude remote-control --continue`"),k(`[bridge:shutdown] Skipping archive+deregister to allow resume of session ${h}`);return}le.size>0&&(k(`[bridge:shutdown] Archiving ${le.size} session(s)`),await Promise.allSettled([...le].map(e=>a.archiveSession(ue.get(e)??ne(e)).catch(t=>c.logVerbose(`Failed to archive session ${e}: ${E(t)}`)))));try{await a.deregisterEnvironment(r),k(`[bridge:shutdown] Environment deregistered, bridge offline`),c.logVerbose(`Environment deregistered.`)}catch(e){c.logVerbose(`Failed to deregister environment: ${E(e)}`)}let{clearBridgePointer:de}=await import(`./bridgePointer-MqLe5Asm.js`);await de(t.dir),c.logVerbose(`Environment offline.`)}var Qe=new Set([`ECONNREFUSED`,`ECONNRESET`,`ETIMEDOUT`,`ENETUNREACH`,`EHOSTUNREACH`]);function $e(e){return!!(e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`&&Qe.has(e.code))}function et(e){return!!e&&typeof e==`object`&&`code`in e&&typeof e.code==`string`&&e.code===`ERR_BAD_RESPONSE`}function tt(e){return Math.max(0,e+e*.25*(2*Math.random()-1))}function nt(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}async function rt(e,t,n,r,i=1e3){for(let a=1;a<=3;a++)try{await e.stopWork(t,n,!1),k(`[bridge:work] stopWork succeeded for workId=${n} on attempt ${a}/3`);return}catch(e){if(e instanceof s){m(e)?k(`[bridge:work] Suppressed stopWork 403 for ${n}: ${e.message}`):r.logError(`Failed to stop work ${n}: ${e.message}`),P(`error`,`bridge_stop_work_failed`,{attempts:a,fatal:!0});return}let t=E(e);if(a<3){let e=tt(i*2**(a-1));r.logVerbose(`Failed to stop work ${n} (attempt ${a}/3), retrying in ${nt(e)}: ${t}`),await G(e)}else r.logError(`Failed to stop work ${n} after 3 attempts: ${t}`),P(`error`,`bridge_stop_work_failed`,{attempts:3})}}function it(e,t,n,r,i){k(`[bridge:session] sessionId=${e} timed out after ${U(t)}`),B(`tengu_bridge_session_timeout`,{timeout_ms:t}),n.logSessionFailed(e,`Session timed out after ${U(t)}`),r.add(e),i.kill()}var at=[`session`,`same-dir`,`worktree`];function ot(e){return e===`session`?`single-session`:e===`same-dir`?`same-dir`:e===`worktree`?`worktree`:`--spawn requires one of: ${at.join(`, `)} (got: ${e??`<missing>`})`}function st(e){let t=e===void 0?NaN:parseInt(e,10);return isNaN(t)||t<1?`--capacity requires a positive integer (got: ${e??`<missing>`})`:t}function ct(e){let t=!1,n=!1,r,i,a,o,s=!1,c,l,u,d,f=!1;for(let m=0;m<e.length;m++){let h=e[m];if(h===`--help`||h===`-h`)s=!0;else if(h===`--verbose`||h===`-v`)t=!0;else if(h===`--sandbox`)n=!0;else if(h===`--no-sandbox`)n=!1;else if(h===`--debug-file`&&m+1<e.length)r=Ee(e[++m]);else if(h.startsWith(`--debug-file=`))r=Ee(h.slice(13));else if(h===`--session-timeout`&&m+1<e.length)i=parseInt(e[++m],10)*1e3;else if(h.startsWith(`--session-timeout=`))i=parseInt(h.slice(18),10)*1e3;else if(h===`--permission-mode`&&m+1<e.length)a=e[++m];else if(h.startsWith(`--permission-mode=`))a=h.slice(18);else if(h===`--name`&&m+1<e.length)o=e[++m];else if(h.startsWith(`--name=`))o=h.slice(7);else if(h===`--session-id`&&m+1<e.length){if(d=e[++m],!d)return p(`--session-id requires a value`)}else if(h.startsWith(`--session-id=`)){if(d=h.slice(13),!d)return p(`--session-id requires a value`)}else if(h===`--continue`||h===`-c`)f=!0;else if(h===`--spawn`||h.startsWith(`--spawn=`)){if(c!==void 0)return p(`--spawn may only be specified once`);let t=ot(h.startsWith(`--spawn=`)?h.slice(8):e[++m]);if(t===`single-session`||t===`same-dir`||t===`worktree`)c=t;else return p(t)}else if(h===`--capacity`||h.startsWith(`--capacity=`)){if(l!==void 0)return p(`--capacity may only be specified once`);let t=st(h.startsWith(`--capacity=`)?h.slice(11):e[++m]);if(typeof t==`number`)l=t;else return p(t)}else if(h===`--create-session-in-dir`)u=!0;else if(h===`--no-create-session-in-dir`)u=!1;else return p(`Unknown argument: ${h}\nRun 'claude remote-control --help' for usage.`)}if(c===`single-session`&&l!==void 0)return p(`--capacity cannot be used with --spawn=session (single-session mode has fixed capacity 1).`);if((d||f)&&(c!==void 0||l!==void 0||u!==void 0))return p(`--session-id and --continue cannot be used with --spawn, --capacity, or --create-session-in-dir.`);if(d&&f)return p(`--session-id and --continue cannot be used together.`);return{verbose:t,sandbox:n,debugFile:r,sessionTimeoutMs:i,permissionMode:a,name:o,spawnMode:c,capacity:l,createSessionInDir:u,sessionId:d,continueSession:f,help:s};function p(e){return{verbose:t,sandbox:n,debugFile:r,sessionTimeoutMs:i,permissionMode:a,name:o,spawnMode:c,capacity:l,createSessionInDir:u,sessionId:d,continueSession:f,help:s,error:e}}}async function lt(){let{EXTERNAL_PERMISSION_MODES:e}=await import(`./permissions-CeYKbtSC.js`),t=e.join(`, `),n=await qe(),r=`
16
16
  Remote Control - Connect your local environment to claude.ai/code
17
17
 
18
18
  USAGE
@@ -52,12 +52,12 @@ NOTES
52
52
  - You must be logged in with a Claude account that has a subscription
53
53
  - Run \`claude\` first in the directory to accept the workspace trust dialog
54
54
  ${n?` - Worktree mode requires a git repository or WorktreeCreate/WorktreeRemove hooks
55
- `:``}`;console.log(r)}var ut=80;function dt(e){return V(e.replace(/\s+/g,` `).trim(),ut)}async function ft(e,t){let{getBridgeSession:n}=await import(`./createSession-DUfOAeyE.js`);return(await n(e,{baseUrl:t}))?.title||void 0}async function pt(e){let t=ct(e);if(t.help){await lt();return}t.error&&(console.error(`Error: ${t.error}`),process.exit(1));let{verbose:n,sandbox:r,debugFile:i,sessionTimeoutMs:a,permissionMode:o,name:c,spawnMode:u,capacity:d,createSessionInDir:f,sessionId:p,continueSession:m}=t,h=p,g,_=u!==void 0||d!==void 0||f!==void 0;if(o!==void 0){let{PERMISSION_MODES:e}=await import(`./permissions-CeYKbtSC.js`),t=e;t.includes(o)||(console.error(`Error: Invalid permission mode '${o}'. Valid modes: ${t.join(`, `)}`),process.exit(1))}let y=Ee(`.`),{enableConfigs:b,checkHasTrustDialogAccepted:ee}=await import(`./config-Bxt1UH1T.js`);b();let{initSinks:x}=await import(`./sinks-CXq8-7Qn.js`);x();let S=await qe();_&&!S&&(await R(`tengu_bridge_multi_session_denied`,{used_spawn:u!==void 0,used_capacity:d!==void 0,used_create_session_in_dir:f!==void 0}),await Promise.race([Promise.all([oe(),se()]),G(500,void 0,{unref:!0})]).catch(()=>{}),console.error(`Error: Multi-session Remote Control is not enabled for your account yet.`),process.exit(1));let{setOriginalCwd:C,setCwdState:w}=await import(`./state-BOa-3Av3.js`);C(y),w(y),ee()||(console.error(`Error: Workspace not trusted. Please run \`claude\` in ${y} first to review and accept the workspace trust dialog.`),process.exit(1));let{clearOAuthTokenCache:T,checkAndRefreshOAuthTokenIfNeeded:D}=await import(`./auth-BQa4kzQo.js`),{getBridgeAccessToken:O,getBridgeBaseUrl:A}=await import(`./bridgeConfig-DWEqKbXk.js`);O()||(console.error(ue),process.exit(1));let{getGlobalConfig:j,saveGlobalConfig:M,getCurrentProjectConfig:N,saveCurrentProjectConfig:te}=await import(`./config-Bxt1UH1T.js`);if(!j().remoteDialogSeen){let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});console.log(`
55
+ `:``}`;console.log(r)}var ut=80;function dt(e){return V(e.replace(/\s+/g,` `).trim(),ut)}async function ft(e,t){let{getBridgeSession:n}=await import(`./createSession-CoQtL5Rj.js`);return(await n(e,{baseUrl:t}))?.title||void 0}async function pt(e){let t=ct(e);if(t.help){await lt();return}t.error&&(console.error(`Error: ${t.error}`),process.exit(1));let{verbose:n,sandbox:r,debugFile:i,sessionTimeoutMs:a,permissionMode:o,name:c,spawnMode:u,capacity:d,createSessionInDir:f,sessionId:p,continueSession:m}=t,h=p,g,_=u!==void 0||d!==void 0||f!==void 0;if(o!==void 0){let{PERMISSION_MODES:e}=await import(`./permissions-CeYKbtSC.js`),t=e;t.includes(o)||(console.error(`Error: Invalid permission mode '${o}'. Valid modes: ${t.join(`, `)}`),process.exit(1))}let y=Ee(`.`),{enableConfigs:b,checkHasTrustDialogAccepted:ee}=await import(`./config-DY5-_kk_.js`);b();let{initSinks:x}=await import(`./sinks-BpcRrN_T.js`);x();let S=await qe();_&&!S&&(await R(`tengu_bridge_multi_session_denied`,{used_spawn:u!==void 0,used_capacity:d!==void 0,used_create_session_in_dir:f!==void 0}),await Promise.race([Promise.all([oe(),se()]),G(500,void 0,{unref:!0})]).catch(()=>{}),console.error(`Error: Multi-session Remote Control is not enabled for your account yet.`),process.exit(1));let{setOriginalCwd:C,setCwdState:w}=await import(`./state-BOa-3Av3.js`);C(y),w(y),ee()||(console.error(`Error: Workspace not trusted. Please run \`claude\` in ${y} first to review and accept the workspace trust dialog.`),process.exit(1));let{clearOAuthTokenCache:T,checkAndRefreshOAuthTokenIfNeeded:D}=await import(`./auth-DRTjfnGy.js`),{getBridgeAccessToken:O,getBridgeBaseUrl:A}=await import(`./bridgeConfig-CqIQ_rvD.js`);O()||(console.error(ue),process.exit(1));let{getGlobalConfig:j,saveGlobalConfig:M,getCurrentProjectConfig:N,saveCurrentProjectConfig:te}=await import(`./config-DY5-_kk_.js`);if(!j().remoteDialogSeen){let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});console.log(`
56
56
  Remote Control lets you access this CLI session from the web (claude.ai/code)
57
57
  or the Claude app, so you can pick up where you left off on any device.
58
58
 
59
59
  You can disconnect remote access anytime by running /remote-control again.
60
- `);let t=await new Promise(t=>{e.question(`Enable Remote Control? (y/n) `,t)});e.close(),M(e=>e.remoteDialogSeen?e:{...e,remoteDialogSeen:!0}),t.toLowerCase()!==`y`&&t.toLowerCase()!==`yes`&&process.exit(0)}if(m){let{readBridgePointerAcrossWorktrees:e}=await import(`./bridgePointer-MqLe5Asm.js`),t=await e(y);t||(console.error("Error: No recent session found in this directory or its worktrees. Run `claude remote-control` to start a new one."),process.exit(1));let{pointer:n,dir:r}=t,i=Math.round(n.ageMs/6e4),a=i<60?`${i}m`:`${Math.round(i/60)}h`,o=r===y?``:` from worktree ${r}`;console.error(`Resuming session ${n.sessionId} (${a} ago)${o}\u2026`),h=n.sessionId,g=r}let F=A();F.startsWith(`http://`)&&!F.includes(`localhost`)&&!F.includes(`127.0.0.1`)&&(console.error(`Error: Remote Control base URL uses HTTP. Only HTTPS or localhost HTTP is allowed.`),process.exit(1));let I=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||F,{getBranch:z,getRemoteUrl:V,findGitRoot:H}=await import(`./git-CbcnOf0E.js`),{hasWorktreeCreateHook:U}=await import(`./hooks-BUJLxdFJ.js`),W=U()||H(y)!==null,K=S?N().remoteControlSpawnMode:void 0;if(K===`worktree`&&!W&&(console.error(`Warning: Saved spawn mode is worktree but this directory is not a git repository. Falling back to same-dir.`),K=void 0,te(e=>e.remoteControlSpawnMode===void 0?e:{...e,remoteControlSpawnMode:void 0})),S&&!K&&W&&u===void 0&&!h&&process.stdin.isTTY){let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});console.log(`
60
+ `);let t=await new Promise(t=>{e.question(`Enable Remote Control? (y/n) `,t)});e.close(),M(e=>e.remoteDialogSeen?e:{...e,remoteDialogSeen:!0}),t.toLowerCase()!==`y`&&t.toLowerCase()!==`yes`&&process.exit(0)}if(m){let{readBridgePointerAcrossWorktrees:e}=await import(`./bridgePointer-MqLe5Asm.js`),t=await e(y);t||(console.error("Error: No recent session found in this directory or its worktrees. Run `claude remote-control` to start a new one."),process.exit(1));let{pointer:n,dir:r}=t,i=Math.round(n.ageMs/6e4),a=i<60?`${i}m`:`${Math.round(i/60)}h`,o=r===y?``:` from worktree ${r}`;console.error(`Resuming session ${n.sessionId} (${a} ago)${o}\u2026`),h=n.sessionId,g=r}let F=A();F.startsWith(`http://`)&&!F.includes(`localhost`)&&!F.includes(`127.0.0.1`)&&(console.error(`Error: Remote Control base URL uses HTTP. Only HTTPS or localhost HTTP is allowed.`),process.exit(1));let I=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||F,{getBranch:z,getRemoteUrl:V,findGitRoot:H}=await import(`./git-CbcnOf0E.js`),{hasWorktreeCreateHook:U}=await import(`./hooks-DPLIIpAD.js`),W=U()||H(y)!==null,K=S?N().remoteControlSpawnMode:void 0;if(K===`worktree`&&!W&&(console.error(`Warning: Saved spawn mode is worktree but this directory is not a git repository. Falling back to same-dir.`),K=void 0,te(e=>e.remoteControlSpawnMode===void 0?e:{...e,remoteControlSpawnMode:void 0})),S&&!K&&W&&u===void 0&&!h&&process.stdin.isTTY){let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});console.log(`
61
61
  Claude Remote Control is launching in spawn mode which lets you create new sessions in this project from Work Mate on Web or your Mobile app. Learn more here: https://code.claude.com/docs/en/remote-control
62
62
 
63
63
  Spawn mode for this project:
@@ -65,4 +65,4 @@ Spawn mode for this project:
65
65
  [2] worktree — each session gets an isolated git worktree
66
66
 
67
67
  This can be changed later or explicitly set with --spawn=same-dir or --spawn=worktree.
68
- `);let t=await new Promise(t=>{e.question(`Choose [1/2] (default: 1): `,t)});e.close();let n=t.trim()===`2`?`worktree`:`same-dir`;K=n,B(`tengu_bridge_spawn_mode_chosen`,{spawn_mode:n}),te(e=>e.remoteControlSpawnMode===n?e:{...e,remoteControlSpawnMode:n})}let q,J;h?(J=`single-session`,q=`resume`):u===void 0?K===void 0?(J=S?`same-dir`:`single-session`,q=`gate_default`):(J=K,q=`saved`):(J=u,q=`flag`);let ne=J===`single-session`?1:d??Ke,Y=f??!0;if(!h){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(y)}J===`worktree`&&!W&&(console.error(`Error: Worktree mode requires a git repository or WorktreeCreate hooks configured. Use --spawn=session for single-session mode.`),process.exit(1));let X=await z(),ie=await V(),ae=xe(),ce=Oe(),{handleOAuth401Error:le}=await import(`./auth-BQa4kzQo.js`),de=v({baseUrl:F,getAccessToken:O,runnerVersion:`0.0.5`,onDebug:k,onAuth401:le,getTrustedDeviceToken:he}),Z;if(h){try{l(h,`sessionId`)}catch{console.error(`Error: Invalid session ID "${h}". Session IDs must not contain unsafe characters.`),process.exit(1)}await D(),T();let{getBridgeSession:e}=await import(`./createSession-DUfOAeyE.js`),t=await e(h,{baseUrl:F,getAccessToken:O});if(!t){if(g){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(`Error: Session ${h} not found. It may have been archived or expired.`),process.exit(1)}if(!t.environment_id){if(g){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(`Error: Session ${h} has no environment_id. It may never have been attached to a bridge.`),process.exit(1)}Z=t.environment_id,k(`[bridge:init] Resuming session ${h} on environment ${Z}`)}let Q={dir:y,machineName:ae,branch:X,gitRepoUrl:ie,maxSessions:ne,spawnMode:J,verbose:n,sandbox:r,bridgeId:ce,workerType:`claude_code`,environmentId:Oe(),reuseEnvironmentId:Z,apiBaseUrl:F,sessionIngressUrl:I,debugFile:i,sessionTimeoutMs:a};k(`[bridge:init] bridgeId=${ce}${Z?` reuseEnvironmentId=${Z}`:``} dir=${y} branch=${X} gitRepoUrl=${ie} machine=${ae}`),k(`[bridge:init] apiBaseUrl=${F} sessionIngressUrl=${I}`),k(`[bridge:init] sandbox=${r}${i?` debugFile=${i}`:``}`);let $,fe;try{let e=await de.registerBridgeEnvironment(Q);$=e.environment_id,fe=e.environment_secret}catch(e){B(`tengu_bridge_registration_failed`,{status:e instanceof s?e.status:void 0}),console.error(e instanceof s&&e.status===404?`Remote Control environments are not available for your account.`:`Error: ${E(e)}`),process.exit(1)}let pe;if(h)if(Z&&$!==Z)L(Error(`Bridge resume env mismatch: requested ${Z}, backend returned ${$}. Falling back to fresh session.`)),console.warn(`Warning: Could not resume session ${h} — its environment has expired. Creating a fresh session instead.`);else{let e=re(h),t=e===h?[h]:[h,e],n=!1,r;for(let e of t)try{await de.reconnectSession($,e),k(`[bridge:init] Session ${e} re-queued via bridge/reconnect`),pe=h,n=!0;break}catch(t){r=t,k(`[bridge:init] reconnectSession(${e}) failed: ${E(t)}`)}if(!n){let e=r,t=e instanceof s;if(g&&t){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(t?`Error: ${E(e)}`:`Error: Failed to reconnect session ${h}: ${E(e)}\nThe session may still be resumable — try running the same command again.`),process.exit(1)}}k(`[bridge:init] Registered, server environmentId=${$}`);let ge=me();B(`tengu_bridge_started`,{max_sessions:Q.maxSessions,has_debug_file:!!Q.debugFile,sandbox:Q.sandbox,verbose:Q.verbose,heartbeat_interval_ms:ge.non_exclusive_heartbeat_interval_ms,spawn_mode:Q.spawnMode,spawn_mode_source:q,multi_session_gate:S,pre_create_session:Y,worktree_available:W}),P(`info`,`bridge_started`,{max_sessions:Q.maxSessions,sandbox:Q.sandbox,spawn_mode:Q.spawnMode});let _e=Ue({execPath:process.execPath,scriptArgs:Ye(),env:process.env,verbose:n,sandbox:r,debugFile:i,permissionMode:o,onDebug:k,onActivity:(e,t)=>{k(`[bridge:activity] sessionId=${e} ${t.type} ${t.summary}`)},onPermissionRequest:(e,t,n)=>{k(`[bridge:perm] sessionId=${e} tool=${t.request.tool_name} request_id=${t.request_id} (not auto-approving)`)}}),ve=Pe({verbose:n}),{parseGitHubRepository:ye}=await import(`./detectRepository-BTPgN89l.js`),be=ie?ye(ie):null,Se=be?be.split(`/`).pop():Ce(y);ve.setRepoInfo(Se,X);let we=J!==`single-session`&&W;we&&ve.setSpawnModeDisplay(J);let Te=e=>{if(e[0]===3||e[0]===4){process.emit(`SIGINT`);return}if(e[0]===32){ve.toggleQr();return}if(e[0]===119){if(!we)return;let e=Q.spawnMode===`same-dir`?`worktree`:`same-dir`;Q.spawnMode=e,B(`tengu_bridge_spawn_mode_toggled`,{spawn_mode:e}),ve.logStatus(e===`worktree`?`Spawn mode: worktree (new sessions get isolated git worktrees)`:`Spawn mode: same-dir (new sessions share the current directory)`),ve.setSpawnModeDisplay(e),ve.refreshDisplay(),te(t=>t.remoteControlSpawnMode===e?t:{...t,remoteControlSpawnMode:e});return}};process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,Te));let De=new AbortController,ke=()=>{k(`[bridge:shutdown] SIGINT received, shutting down`),De.abort()},Ae=()=>{k(`[bridge:shutdown] SIGTERM received, shutting down`),De.abort()};process.on(`SIGINT`,ke),process.on(`SIGTERM`,Ae);let je=pe||null;if(Y&&!pe){let{createBridgeSession:e}=await import(`./createSession-DUfOAeyE.js`);try{je=await e({environmentId:$,title:c,events:[],gitRepoUrl:ie,branch:X,signal:De.signal,baseUrl:F,getAccessToken:O,permissionMode:o}),je&&k(`[bridge:init] Created initial session ${je}`)}catch(e){k(`[bridge:init] Session creation failed (non-fatal): ${E(e)}`)}}let Me=null;if(je&&J===`single-session`){let{writeBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`),t={sessionId:je,environmentId:$,source:`standalone`};await e(Q.dir,t),Me=setInterval(e,3600*1e3,Q.dir,t),Me.unref?.()}try{await Ze(Q,$,fe,de,_e,ve,De.signal,void 0,je??void 0,async()=>(T(),await D(),O()))}finally{Me!==null&&clearInterval(Me),process.off(`SIGINT`,ke),process.off(`SIGTERM`,Ae),process.stdin.off(`data`,Te),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}process.exit(0)}var mt=class extends Error{constructor(e){super(e),this.name=`BridgeHeadlessPermanentError`}};async function ht(e,t){let{dir:n,log:r}=e;process.chdir(n);let{setOriginalCwd:i,setCwdState:a}=await import(`./state-BOa-3Av3.js`);i(n),a(n);let{enableConfigs:o,checkHasTrustDialogAccepted:s}=await import(`./config-Bxt1UH1T.js`);o();let{initSinks:c}=await import(`./sinks-CXq8-7Qn.js`);if(c(),!s())throw new mt(`Workspace not trusted: ${n}. Run \`claude\` in that directory first to accept the trust dialog.`);if(!e.getAccessToken())throw Error(ue);let{getBridgeBaseUrl:l}=await import(`./bridgeConfig-DWEqKbXk.js`),u=l();if(u.startsWith(`http://`)&&!u.includes(`localhost`)&&!u.includes(`127.0.0.1`))throw new mt(`Remote Control base URL uses HTTP. Only HTTPS or localhost HTTP is allowed.`);let d=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||u,{getBranch:f,getRemoteUrl:p,findGitRoot:m}=await import(`./git-CbcnOf0E.js`),{hasWorktreeCreateHook:h}=await import(`./hooks-BUJLxdFJ.js`);if(e.spawnMode===`worktree`&&!(h()||m(n)!==null))throw new mt(`Worktree mode requires a git repository or WorktreeCreate hooks. Directory ${n} has neither.`);let g=await f(),_=await p(),y=xe(),b=Oe(),ee={dir:n,machineName:y,branch:g,gitRepoUrl:_,maxSessions:e.capacity,spawnMode:e.spawnMode,verbose:!1,sandbox:e.sandbox,bridgeId:b,workerType:`claude_code`,environmentId:Oe(),apiBaseUrl:u,sessionIngressUrl:d,sessionTimeoutMs:e.sessionTimeoutMs},x=v({baseUrl:u,getAccessToken:e.getAccessToken,runnerVersion:`0.0.5`,onDebug:r,onAuth401:e.onAuth401,getTrustedDeviceToken:he}),S,C;try{let e=await x.registerBridgeEnvironment(ee);S=e.environment_id,C=e.environment_secret}catch(e){throw Error(`Bridge registration failed: ${E(e)}`)}let w=Ue({execPath:process.execPath,scriptArgs:Ye(),env:process.env,verbose:!1,sandbox:e.sandbox,permissionMode:e.permissionMode,onDebug:r}),T=gt(r);T.printBanner(ee,S);let D;if(e.createSessionOnStart){let{createBridgeSession:n}=await import(`./createSession-DUfOAeyE.js`);try{let i=await n({environmentId:S,title:e.name,events:[],gitRepoUrl:_,branch:g,signal:t,baseUrl:u,getAccessToken:e.getAccessToken,permissionMode:e.permissionMode});i&&(D=i,r(`created initial session ${i}`))}catch(e){r(`session pre-creation failed (non-fatal): ${E(e)}`)}}await Ze(ee,S,C,x,w,T,t,void 0,D,async()=>e.getAccessToken())}function gt(e){let t=()=>{};return{printBanner:(t,n)=>e(`registered environmentId=${n} dir=${t.dir} spawnMode=${t.spawnMode} capacity=${t.maxSessions}`),logSessionStart:(t,n)=>e(`session start ${t}`),logSessionComplete:(t,n)=>e(`session complete ${t} (${n}ms)`),logSessionFailed:(t,n)=>e(`session failed ${t}: ${n}`),logStatus:e,logVerbose:e,logError:t=>e(`error: ${t}`),logReconnected:t=>e(`reconnected after ${t}ms`),addSession:(t,n)=>e(`session attached ${t}`),removeSession:t=>e(`session detached ${t}`),updateIdleStatus:t,updateReconnectingStatus:t,updateSessionStatus:t,updateSessionActivity:t,updateSessionCount:t,updateFailedStatus:t,setSpawnModeDisplay:t,setRepoInfo:t,setDebugLogPath:t,setAttached:t,setSessionTitle:t,clearStatus:t,toggleQr:t,refreshDisplay:t}}export{ct as a,et as i,pt as n,ht as o,$e as r,Ze as s,mt as t};
68
+ `);let t=await new Promise(t=>{e.question(`Choose [1/2] (default: 1): `,t)});e.close();let n=t.trim()===`2`?`worktree`:`same-dir`;K=n,B(`tengu_bridge_spawn_mode_chosen`,{spawn_mode:n}),te(e=>e.remoteControlSpawnMode===n?e:{...e,remoteControlSpawnMode:n})}let q,J;h?(J=`single-session`,q=`resume`):u===void 0?K===void 0?(J=S?`same-dir`:`single-session`,q=`gate_default`):(J=K,q=`saved`):(J=u,q=`flag`);let ne=J===`single-session`?1:d??Ke,Y=f??!0;if(!h){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(y)}J===`worktree`&&!W&&(console.error(`Error: Worktree mode requires a git repository or WorktreeCreate hooks configured. Use --spawn=session for single-session mode.`),process.exit(1));let X=await z(),ie=await V(),ae=xe(),ce=Oe(),{handleOAuth401Error:le}=await import(`./auth-DRTjfnGy.js`),de=v({baseUrl:F,getAccessToken:O,runnerVersion:`0.0.6`,onDebug:k,onAuth401:le,getTrustedDeviceToken:he}),Z;if(h){try{l(h,`sessionId`)}catch{console.error(`Error: Invalid session ID "${h}". Session IDs must not contain unsafe characters.`),process.exit(1)}await D(),T();let{getBridgeSession:e}=await import(`./createSession-CoQtL5Rj.js`),t=await e(h,{baseUrl:F,getAccessToken:O});if(!t){if(g){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(`Error: Session ${h} not found. It may have been archived or expired.`),process.exit(1)}if(!t.environment_id){if(g){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(`Error: Session ${h} has no environment_id. It may never have been attached to a bridge.`),process.exit(1)}Z=t.environment_id,k(`[bridge:init] Resuming session ${h} on environment ${Z}`)}let Q={dir:y,machineName:ae,branch:X,gitRepoUrl:ie,maxSessions:ne,spawnMode:J,verbose:n,sandbox:r,bridgeId:ce,workerType:`claude_code`,environmentId:Oe(),reuseEnvironmentId:Z,apiBaseUrl:F,sessionIngressUrl:I,debugFile:i,sessionTimeoutMs:a};k(`[bridge:init] bridgeId=${ce}${Z?` reuseEnvironmentId=${Z}`:``} dir=${y} branch=${X} gitRepoUrl=${ie} machine=${ae}`),k(`[bridge:init] apiBaseUrl=${F} sessionIngressUrl=${I}`),k(`[bridge:init] sandbox=${r}${i?` debugFile=${i}`:``}`);let $,fe;try{let e=await de.registerBridgeEnvironment(Q);$=e.environment_id,fe=e.environment_secret}catch(e){B(`tengu_bridge_registration_failed`,{status:e instanceof s?e.status:void 0}),console.error(e instanceof s&&e.status===404?`Remote Control environments are not available for your account.`:`Error: ${E(e)}`),process.exit(1)}let pe;if(h)if(Z&&$!==Z)L(Error(`Bridge resume env mismatch: requested ${Z}, backend returned ${$}. Falling back to fresh session.`)),console.warn(`Warning: Could not resume session ${h} — its environment has expired. Creating a fresh session instead.`);else{let e=re(h),t=e===h?[h]:[h,e],n=!1,r;for(let e of t)try{await de.reconnectSession($,e),k(`[bridge:init] Session ${e} re-queued via bridge/reconnect`),pe=h,n=!0;break}catch(t){r=t,k(`[bridge:init] reconnectSession(${e}) failed: ${E(t)}`)}if(!n){let e=r,t=e instanceof s;if(g&&t){let{clearBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`);await e(g)}console.error(t?`Error: ${E(e)}`:`Error: Failed to reconnect session ${h}: ${E(e)}\nThe session may still be resumable — try running the same command again.`),process.exit(1)}}k(`[bridge:init] Registered, server environmentId=${$}`);let ge=me();B(`tengu_bridge_started`,{max_sessions:Q.maxSessions,has_debug_file:!!Q.debugFile,sandbox:Q.sandbox,verbose:Q.verbose,heartbeat_interval_ms:ge.non_exclusive_heartbeat_interval_ms,spawn_mode:Q.spawnMode,spawn_mode_source:q,multi_session_gate:S,pre_create_session:Y,worktree_available:W}),P(`info`,`bridge_started`,{max_sessions:Q.maxSessions,sandbox:Q.sandbox,spawn_mode:Q.spawnMode});let _e=Ue({execPath:process.execPath,scriptArgs:Ye(),env:process.env,verbose:n,sandbox:r,debugFile:i,permissionMode:o,onDebug:k,onActivity:(e,t)=>{k(`[bridge:activity] sessionId=${e} ${t.type} ${t.summary}`)},onPermissionRequest:(e,t,n)=>{k(`[bridge:perm] sessionId=${e} tool=${t.request.tool_name} request_id=${t.request_id} (not auto-approving)`)}}),ve=Pe({verbose:n}),{parseGitHubRepository:ye}=await import(`./detectRepository-BTPgN89l.js`),be=ie?ye(ie):null,Se=be?be.split(`/`).pop():Ce(y);ve.setRepoInfo(Se,X);let we=J!==`single-session`&&W;we&&ve.setSpawnModeDisplay(J);let Te=e=>{if(e[0]===3||e[0]===4){process.emit(`SIGINT`);return}if(e[0]===32){ve.toggleQr();return}if(e[0]===119){if(!we)return;let e=Q.spawnMode===`same-dir`?`worktree`:`same-dir`;Q.spawnMode=e,B(`tengu_bridge_spawn_mode_toggled`,{spawn_mode:e}),ve.logStatus(e===`worktree`?`Spawn mode: worktree (new sessions get isolated git worktrees)`:`Spawn mode: same-dir (new sessions share the current directory)`),ve.setSpawnModeDisplay(e),ve.refreshDisplay(),te(t=>t.remoteControlSpawnMode===e?t:{...t,remoteControlSpawnMode:e});return}};process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,Te));let De=new AbortController,ke=()=>{k(`[bridge:shutdown] SIGINT received, shutting down`),De.abort()},Ae=()=>{k(`[bridge:shutdown] SIGTERM received, shutting down`),De.abort()};process.on(`SIGINT`,ke),process.on(`SIGTERM`,Ae);let je=pe||null;if(Y&&!pe){let{createBridgeSession:e}=await import(`./createSession-CoQtL5Rj.js`);try{je=await e({environmentId:$,title:c,events:[],gitRepoUrl:ie,branch:X,signal:De.signal,baseUrl:F,getAccessToken:O,permissionMode:o}),je&&k(`[bridge:init] Created initial session ${je}`)}catch(e){k(`[bridge:init] Session creation failed (non-fatal): ${E(e)}`)}}let Me=null;if(je&&J===`single-session`){let{writeBridgePointer:e}=await import(`./bridgePointer-MqLe5Asm.js`),t={sessionId:je,environmentId:$,source:`standalone`};await e(Q.dir,t),Me=setInterval(e,3600*1e3,Q.dir,t),Me.unref?.()}try{await Ze(Q,$,fe,de,_e,ve,De.signal,void 0,je??void 0,async()=>(T(),await D(),O()))}finally{Me!==null&&clearInterval(Me),process.off(`SIGINT`,ke),process.off(`SIGTERM`,Ae),process.stdin.off(`data`,Te),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}process.exit(0)}var mt=class extends Error{constructor(e){super(e),this.name=`BridgeHeadlessPermanentError`}};async function ht(e,t){let{dir:n,log:r}=e;process.chdir(n);let{setOriginalCwd:i,setCwdState:a}=await import(`./state-BOa-3Av3.js`);i(n),a(n);let{enableConfigs:o,checkHasTrustDialogAccepted:s}=await import(`./config-DY5-_kk_.js`);o();let{initSinks:c}=await import(`./sinks-BpcRrN_T.js`);if(c(),!s())throw new mt(`Workspace not trusted: ${n}. Run \`claude\` in that directory first to accept the trust dialog.`);if(!e.getAccessToken())throw Error(ue);let{getBridgeBaseUrl:l}=await import(`./bridgeConfig-CqIQ_rvD.js`),u=l();if(u.startsWith(`http://`)&&!u.includes(`localhost`)&&!u.includes(`127.0.0.1`))throw new mt(`Remote Control base URL uses HTTP. Only HTTPS or localhost HTTP is allowed.`);let d=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||u,{getBranch:f,getRemoteUrl:p,findGitRoot:m}=await import(`./git-CbcnOf0E.js`),{hasWorktreeCreateHook:h}=await import(`./hooks-DPLIIpAD.js`);if(e.spawnMode===`worktree`&&!(h()||m(n)!==null))throw new mt(`Worktree mode requires a git repository or WorktreeCreate hooks. Directory ${n} has neither.`);let g=await f(),_=await p(),y=xe(),b=Oe(),ee={dir:n,machineName:y,branch:g,gitRepoUrl:_,maxSessions:e.capacity,spawnMode:e.spawnMode,verbose:!1,sandbox:e.sandbox,bridgeId:b,workerType:`claude_code`,environmentId:Oe(),apiBaseUrl:u,sessionIngressUrl:d,sessionTimeoutMs:e.sessionTimeoutMs},x=v({baseUrl:u,getAccessToken:e.getAccessToken,runnerVersion:`0.0.6`,onDebug:r,onAuth401:e.onAuth401,getTrustedDeviceToken:he}),S,C;try{let e=await x.registerBridgeEnvironment(ee);S=e.environment_id,C=e.environment_secret}catch(e){throw Error(`Bridge registration failed: ${E(e)}`)}let w=Ue({execPath:process.execPath,scriptArgs:Ye(),env:process.env,verbose:!1,sandbox:e.sandbox,permissionMode:e.permissionMode,onDebug:r}),T=gt(r);T.printBanner(ee,S);let D;if(e.createSessionOnStart){let{createBridgeSession:n}=await import(`./createSession-CoQtL5Rj.js`);try{let i=await n({environmentId:S,title:e.name,events:[],gitRepoUrl:_,branch:g,signal:t,baseUrl:u,getAccessToken:e.getAccessToken,permissionMode:e.permissionMode});i&&(D=i,r(`created initial session ${i}`))}catch(e){r(`session pre-creation failed (non-fatal): ${E(e)}`)}}await Ze(ee,S,C,x,w,T,t,void 0,D,async()=>e.getAccessToken())}function gt(e){let t=()=>{};return{printBanner:(t,n)=>e(`registered environmentId=${n} dir=${t.dir} spawnMode=${t.spawnMode} capacity=${t.maxSessions}`),logSessionStart:(t,n)=>e(`session start ${t}`),logSessionComplete:(t,n)=>e(`session complete ${t} (${n}ms)`),logSessionFailed:(t,n)=>e(`session failed ${t}: ${n}`),logStatus:e,logVerbose:e,logError:t=>e(`error: ${t}`),logReconnected:t=>e(`reconnected after ${t}ms`),addSession:(t,n)=>e(`session attached ${t}`),removeSession:t=>e(`session detached ${t}`),updateIdleStatus:t,updateReconnectingStatus:t,updateSessionStatus:t,updateSessionActivity:t,updateSessionCount:t,updateFailedStatus:t,setSpawnModeDisplay:t,setRepoInfo:t,setDebugLogPath:t,setAttached:t,setSessionTitle:t,clearStatus:t,toggleQr:t,refreshDisplay:t}}export{ct as a,et as i,pt as n,ht as o,$e as r,Ze as s,mt as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./bridgeMain-DHUpZFgL.js";export{e as bridgeMain};
@@ -1 +1 @@
1
- import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,F as r,S as i,a,l as o,z as s}from"./debug-BrXObCdR.js";import{B as c,F as l,G as u,I as d,O as f,U as p,Y as m,b as h,g,m as _}from"./log-BMCygSzM.js";import{n as v,r as y}from"./analytics-BotDBGh0.js";import{P as b,lt as x,n as S,t as C}from"./rcDebugLog-VKwMl0yg.js";import{t as w}from"./controlMessageCompat-IFu4Gc1y.js";import{randomUUID as T}from"crypto";v(),b(),a(),C(),_(),s(),i(),m(),e();function E(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}function D(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_response`&&`response`in e}function O(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_request`&&`request_id`in e&&`request`in e}function k(e){return(e.type===`user`||e.type===`assistant`)&&e.isVirtual?!1:e.type===`user`||e.type===`assistant`||e.type===`system`&&e.subtype===`local_command`}function A(e){if(e.type!==`user`||e.isMeta||e.toolUseResult||e.isCompactSummary||e.origin&&e.origin.kind!==`human`)return;let t=e.message.content,n;if(typeof t==`string`)n=t;else for(let e of t??[])if(e.type===`text`){n=e.text;break}if(n)return g(n)||void 0}var j=`system-reminder`,M=/\s*<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/gy,N=new Set([h,f,l,d,c,p,u]);function P(e){let t=e.message?.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>!!e&&typeof e==`object`&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``):``}function F(e){let t=e.trim();if(!t)return null;M.lastIndex=0;let n=[];for(;M.lastIndex<t.length;){let e=M.exec(t);if(!e)return null;n.push(e[1])}return n.length>0?n:null}function I(e){if(e.type!==`user`||e.isVisibleInTranscriptOnly)return!1;if(e.toolUseResult!==void 0||!e.isMeta)return!0;let t=F(P(e));return!t||t.some(e=>e!==`local-command-caveat`&&e!==j&&N.has(e))}function L(e){return e.some(I)}function R(e,t,i,a,s,c){try{let r=w(n(e));if(D(r)){o(`[bridge:repl] Ingress message type=control_response`),s?.(r);return}if(O(r)){o(`[bridge:repl] Inbound control_request subtype=${r.request.subtype}`),c?.(r);return}if(!E(r))return;let l=`uuid`in r&&typeof r.uuid==`string`?r.uuid:void 0;if(l&&t.has(l)){o(`[bridge:repl] Ignoring echo: type=${r.type} uuid=${l}`);return}if(l&&i.has(l)){o(`[bridge:repl] Ignoring re-delivered inbound: type=${r.type} uuid=${l}`);return}o(`[bridge:repl] Ingress message type=${r.type}${l?` uuid=${l}`:``}`),r.type===`user`?(l&&i.add(l),y(`tengu_bridge_message_received`,{is_repl:!0}),a?.(r)):o(`[bridge:repl] Ignoring non-user inbound message: type=${r.type}`)}catch(e){o(`[bridge:repl] Failed to parse ingress message: ${r(e)}`)}}var z=`This session is outbound-only. Enable Remote Control locally to allow inbound control.`;function B(e,t){let{transport:n,sessionId:r,outboundOnly:i,onInterrupt:a,onSetModel:s,onSetMaxThinkingTokens:c,onSetPermissionMode:l}=t;if(!n){o(`[bridge:repl] Cannot respond to control_request: transport not configured`);return}let u,d=e.request;if(i&&d.subtype!==`initialize`){u={type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:z}};let t={...u,session_id:r};n.write(t),o(`[bridge:repl] Rejected ${d.subtype} (outbound-only) request_id=${e.request_id}`);return}switch(d.subtype){case`initialize`:u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:{commands:[],output_style:`normal`,available_output_styles:[`normal`],models:[],account:{},pid:process.pid}}};break;case`set_model`:s?.(d.model),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;case`set_max_thinking_tokens`:c?.(d.max_thinking_tokens??null),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;case`set_permission_mode`:{let t=l?.(d.mode)??{ok:!1,error:`set_permission_mode is not supported in this context (onSetPermissionMode callback not registered)`};u=t.ok?{type:`control_response`,response:{subtype:`success`,request_id:e.request_id}}:{type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t.error}};break}case`interrupt`:a?.(),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;default:u={type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:`REPL bridge does not handle control_request subtype: ${d.subtype}`}}}let f={...u,session_id:r};n.write(f),S(`control_response: subtype=${d.subtype} request_id=${e.request_id} result=${u.response.subtype}`),o(`[bridge:repl] Sent control_response for ${d.subtype} request_id=${e.request_id} result=${u.response.subtype}`)}function V(e){return{type:`result_success`,subtype:`success`,duration_ms:0,duration_api_ms:0,is_error:!1,num_turns:0,result:``,stop_reason:null,total_cost_usd:0,usage:{...x},modelUsage:{},permission_denials:[],session_id:e,uuid:T()}}var H=class{constructor(e){t(this,`capacity`,void 0),t(this,`ring`,void 0),t(this,`set`,new Set),t(this,`writeIdx`,0),this.capacity=e,this.ring=Array(e)}add(e){if(this.set.has(e))return;let t=this.ring[this.writeIdx];t!==void 0&&this.set.delete(t),this.ring[this.writeIdx]=e,this.set.add(e),this.writeIdx=(this.writeIdx+1)%this.capacity}has(e){return this.set.has(e)}clear(){this.set.clear(),this.ring.fill(void 0),this.writeIdx=0}};export{k as a,L as c,B as i,A as n,V as o,R as r,I as s,H as t};
1
+ import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,F as r,S as i,a,l as o,z as s}from"./debug-BrXObCdR.js";import{B as c,F as l,G as u,I as d,O as f,U as p,Y as m,b as h,g,m as _}from"./log-BMCygSzM.js";import{n as v,r as y}from"./analytics-BotDBGh0.js";import{P as b,lt as x,n as S,t as C}from"./rcDebugLog-CUy1_F23.js";import{t as w}from"./controlMessageCompat-IFu4Gc1y.js";import{randomUUID as T}from"crypto";v(),b(),a(),C(),_(),s(),i(),m(),e();function E(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}function D(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_response`&&`response`in e}function O(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_request`&&`request_id`in e&&`request`in e}function k(e){return(e.type===`user`||e.type===`assistant`)&&e.isVirtual?!1:e.type===`user`||e.type===`assistant`||e.type===`system`&&e.subtype===`local_command`}function A(e){if(e.type!==`user`||e.isMeta||e.toolUseResult||e.isCompactSummary||e.origin&&e.origin.kind!==`human`)return;let t=e.message.content,n;if(typeof t==`string`)n=t;else for(let e of t??[])if(e.type===`text`){n=e.text;break}if(n)return g(n)||void 0}var j=`system-reminder`,M=/\s*<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/gy,N=new Set([h,f,l,d,c,p,u]);function P(e){let t=e.message?.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>!!e&&typeof e==`object`&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``):``}function F(e){let t=e.trim();if(!t)return null;M.lastIndex=0;let n=[];for(;M.lastIndex<t.length;){let e=M.exec(t);if(!e)return null;n.push(e[1])}return n.length>0?n:null}function I(e){if(e.type!==`user`||e.isVisibleInTranscriptOnly)return!1;if(e.toolUseResult!==void 0||!e.isMeta)return!0;let t=F(P(e));return!t||t.some(e=>e!==`local-command-caveat`&&e!==j&&N.has(e))}function L(e){return e.some(I)}function R(e,t,i,a,s,c){try{let r=w(n(e));if(D(r)){o(`[bridge:repl] Ingress message type=control_response`),s?.(r);return}if(O(r)){o(`[bridge:repl] Inbound control_request subtype=${r.request.subtype}`),c?.(r);return}if(!E(r))return;let l=`uuid`in r&&typeof r.uuid==`string`?r.uuid:void 0;if(l&&t.has(l)){o(`[bridge:repl] Ignoring echo: type=${r.type} uuid=${l}`);return}if(l&&i.has(l)){o(`[bridge:repl] Ignoring re-delivered inbound: type=${r.type} uuid=${l}`);return}o(`[bridge:repl] Ingress message type=${r.type}${l?` uuid=${l}`:``}`),r.type===`user`?(l&&i.add(l),y(`tengu_bridge_message_received`,{is_repl:!0}),a?.(r)):o(`[bridge:repl] Ignoring non-user inbound message: type=${r.type}`)}catch(e){o(`[bridge:repl] Failed to parse ingress message: ${r(e)}`)}}var z=`This session is outbound-only. Enable Remote Control locally to allow inbound control.`;function B(e,t){let{transport:n,sessionId:r,outboundOnly:i,onInterrupt:a,onSetModel:s,onSetMaxThinkingTokens:c,onSetPermissionMode:l}=t;if(!n){o(`[bridge:repl] Cannot respond to control_request: transport not configured`);return}let u,d=e.request;if(i&&d.subtype!==`initialize`){u={type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:z}};let t={...u,session_id:r};n.write(t),o(`[bridge:repl] Rejected ${d.subtype} (outbound-only) request_id=${e.request_id}`);return}switch(d.subtype){case`initialize`:u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:{commands:[],output_style:`normal`,available_output_styles:[`normal`],models:[],account:{},pid:process.pid}}};break;case`set_model`:s?.(d.model),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;case`set_max_thinking_tokens`:c?.(d.max_thinking_tokens??null),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;case`set_permission_mode`:{let t=l?.(d.mode)??{ok:!1,error:`set_permission_mode is not supported in this context (onSetPermissionMode callback not registered)`};u=t.ok?{type:`control_response`,response:{subtype:`success`,request_id:e.request_id}}:{type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t.error}};break}case`interrupt`:a?.(),u={type:`control_response`,response:{subtype:`success`,request_id:e.request_id}};break;default:u={type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:`REPL bridge does not handle control_request subtype: ${d.subtype}`}}}let f={...u,session_id:r};n.write(f),S(`control_response: subtype=${d.subtype} request_id=${e.request_id} result=${u.response.subtype}`),o(`[bridge:repl] Sent control_response for ${d.subtype} request_id=${e.request_id} result=${u.response.subtype}`)}function V(e){return{type:`result_success`,subtype:`success`,duration_ms:0,duration_api_ms:0,is_error:!1,num_turns:0,result:``,stop_reason:null,total_cost_usd:0,usage:{...x},modelUsage:{},permission_denials:[],session_id:e,uuid:T()}}var H=class{constructor(e){t(this,`capacity`,void 0),t(this,`ring`,void 0),t(this,`set`,new Set),t(this,`writeIdx`,0),this.capacity=e,this.ring=Array(e)}add(e){if(this.set.has(e))return;let t=this.ring[this.writeIdx];t!==void 0&&this.set.delete(t),this.ring[this.writeIdx]=e,this.set.add(e),this.writeIdx=(this.writeIdx+1)%this.capacity}has(e){return this.set.has(e)}clear(){this.set.clear(),this.ring.fill(void 0),this.writeIdx=0}};export{k as a,L as c,B as i,A as n,V as o,R as r,I as s,H as t};
@@ -1 +1 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{I as n,P as r,bn as i,fi as a,ot as o,t as s,vn as c,xt as l}from"./src-CDCSSo0U2.js";import{t as u}from"./jsx-runtime-Bb4Xn-E0.js";import{Al as d,Ao as f,Bb as p,Gw as m,ME as h,NE as g,Vb as _,Ww as v,ZT as y,aC as b,jE as x,kl as S,lh as C,lt as w,sh as T,ut as E,zo as D}from"./loadAgentsDir-Clu7Uk6a.js";import{F as O,z as k}from"./debug-BrXObCdR.js";import{Kt as A}from"./settings-Dlp5JTa_.js";import{b as j,g as M}from"./config-3m_9zSrj.js";import{st as N}from"./rcDebugLog-VKwMl0yg.js";import{n as P,r as F}from"./sideQuestion-CHpOVzY5.js";import{i as I,n as L}from"./modalContext-DFjKLCB6.js";function R({question:e,context:t,onDone:a}){let[s,c]=(0,H.useState)(null),[u,d]=(0,H.useState)(null),[f,m]=(0,H.useState)(0),h=(0,H.useRef)(null),{rows:g}=I(o());i(()=>m(e=>e+1),s||u?null:80);function _(e){if(e.key===`escape`||e.key===`return`||e.key===` `||e.ctrl&&(e.key===`c`||e.key===`d`)){e.preventDefault(),a(void 0,{display:`skip`});return}(e.key===`up`||e.ctrl&&e.key===`p`)&&(e.preventDefault(),h.current?.scrollBy(-3)),(e.key===`down`||e.ctrl&&e.key===`n`)&&(e.preventDefault(),h.current?.scrollBy(K))}(0,H.useEffect)(()=>{let n=v();async function r(){try{let r=await F({question:e,cacheSafeParams:await B(t)});n.signal.aborted||(r.response?c(r.response):d(`No response received`))}catch(e){n.signal.aborted||d(O(e)||`Failed to get response`)}}return r(),()=>{n.abort()}},[e,t]);let y=Math.max(5,g-W-G);return(0,U.jsxs)(n,{flexDirection:`column`,paddingLeft:2,marginTop:1,tabIndex:0,autoFocus:!0,onKeyDown:_,children:[(0,U.jsxs)(n,{children:[(0,U.jsxs)(r,{color:`warning`,bold:!0,children:[`/btw`,` `]}),(0,U.jsx)(r,{dimColor:!0,children:e})]}),(0,U.jsx)(n,{marginTop:1,marginLeft:2,maxHeight:y,children:(0,U.jsx)(l,{ref:h,flexDirection:`column`,flexGrow:1,children:u?(0,U.jsx)(r,{color:`error`,children:u}):s?(0,U.jsx)(T,{children:s}):(0,U.jsxs)(n,{children:[(0,U.jsx)(p,{frame:f,messageColor:`warning`}),(0,U.jsx)(r,{color:`warning`,children:`Answering...`})]})})}),(s||u)&&(0,U.jsx)(n,{marginTop:1,children:(0,U.jsxs)(r,{dimColor:!0,children:[`↑`,`/`,`↓`,` to scroll · Space, Enter, or Escape to dismiss`]})})]})}function z(e){let t=e.at(-1);return t?.type===`assistant`&&t.message.stop_reason===null?e.slice(0,-1):e}async function B(e){let t=f(z(e.messages)),n=S();if(n)return{systemPrompt:n.systemPrompt,userContext:n.userContext,systemContext:n.systemContext,toolUseContext:e,forkContextMessages:t};let[r,i,a]=await Promise.all([w(e.options.tools,e.options.mainLoopModel,[],e.options.mcpClients),h(),x()]);return{systemPrompt:N(r),userContext:i,systemContext:a,toolUseContext:e,forkContextMessages:t}}async function V(e,t,n){let r=n?.trim();return r?(j(e=>({...e,btwUseCount:e.btwUseCount+1})),(0,U.jsx)(R,{question:r,context:t,onDone:e})):(e(`Usage: /btw <your question>`,{display:`system`}),null)}var H,U,W,G,K;e((()=>{a(),H=t(a(),1),c(),C(),_(),A(),E(),L(),g(),b(),s(),m(),M(),k(),d(),D(),P(),y(),U=u(),W=5,G=6,K=3}))();export{V as call};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{I as n,P as r,bn as i,fi as a,ot as o,t as s,vn as c,xt as l}from"./src-CDCSSo0U2.js";import{t as u}from"./jsx-runtime-Bb4Xn-E0.js";import{Al as d,Ao as f,Bb as p,Gw as m,ME as h,NE as g,Vb as _,Ww as v,ZT as y,aC as b,jE as x,kl as S,lh as C,lt as w,sh as T,ut as E,zo as D}from"./loadAgentsDir-D206qwP3.js";import{F as O,z as k}from"./debug-BrXObCdR.js";import{Kt as A}from"./settings-BovzmwMP.js";import{b as j,g as M}from"./config-DmomySWC.js";import{st as N}from"./rcDebugLog-CUy1_F23.js";import{n as P,r as F}from"./sideQuestion-wSi38p81.js";import{i as I,n as L}from"./modalContext-DFjKLCB6.js";function R({question:e,context:t,onDone:a}){let[s,c]=(0,H.useState)(null),[u,d]=(0,H.useState)(null),[f,m]=(0,H.useState)(0),h=(0,H.useRef)(null),{rows:g}=I(o());i(()=>m(e=>e+1),s||u?null:80);function _(e){if(e.key===`escape`||e.key===`return`||e.key===` `||e.ctrl&&(e.key===`c`||e.key===`d`)){e.preventDefault(),a(void 0,{display:`skip`});return}(e.key===`up`||e.ctrl&&e.key===`p`)&&(e.preventDefault(),h.current?.scrollBy(-3)),(e.key===`down`||e.ctrl&&e.key===`n`)&&(e.preventDefault(),h.current?.scrollBy(K))}(0,H.useEffect)(()=>{let n=v();async function r(){try{let r=await F({question:e,cacheSafeParams:await B(t)});n.signal.aborted||(r.response?c(r.response):d(`No response received`))}catch(e){n.signal.aborted||d(O(e)||`Failed to get response`)}}return r(),()=>{n.abort()}},[e,t]);let y=Math.max(5,g-W-G);return(0,U.jsxs)(n,{flexDirection:`column`,paddingLeft:2,marginTop:1,tabIndex:0,autoFocus:!0,onKeyDown:_,children:[(0,U.jsxs)(n,{children:[(0,U.jsxs)(r,{color:`warning`,bold:!0,children:[`/btw`,` `]}),(0,U.jsx)(r,{dimColor:!0,children:e})]}),(0,U.jsx)(n,{marginTop:1,marginLeft:2,maxHeight:y,children:(0,U.jsx)(l,{ref:h,flexDirection:`column`,flexGrow:1,children:u?(0,U.jsx)(r,{color:`error`,children:u}):s?(0,U.jsx)(T,{children:s}):(0,U.jsxs)(n,{children:[(0,U.jsx)(p,{frame:f,messageColor:`warning`}),(0,U.jsx)(r,{color:`warning`,children:`Answering...`})]})})}),(s||u)&&(0,U.jsx)(n,{marginTop:1,children:(0,U.jsxs)(r,{dimColor:!0,children:[`↑`,`/`,`↓`,` to scroll · Space, Enter, or Escape to dismiss`]})})]})}function z(e){let t=e.at(-1);return t?.type===`assistant`&&t.message.stop_reason===null?e.slice(0,-1):e}async function B(e){let t=f(z(e.messages)),n=S();if(n)return{systemPrompt:n.systemPrompt,userContext:n.userContext,systemContext:n.systemContext,toolUseContext:e,forkContextMessages:t};let[r,i,a]=await Promise.all([w(e.options.tools,e.options.mainLoopModel,[],e.options.mcpClients),h(),x()]);return{systemPrompt:N(r),userContext:i,systemContext:a,toolUseContext:e,forkContextMessages:t}}async function V(e,t,n){let r=n?.trim();return r?(j(e=>({...e,btwUseCount:e.btwUseCount+1})),(0,U.jsx)(R,{question:r,context:t,onDone:e})):(e(`Usage: /btw <your question>`,{display:`system`}),null)}var H,U,W,G,K;e((()=>{a(),H=t(a(),1),c(),C(),_(),A(),E(),L(),g(),b(),s(),m(),M(),k(),d(),D(),P(),y(),U=u(),W=5,G=6,K=3}))();export{V as call};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./caches-UeVVM3T0.js";e();export{t as clearSessionCaches};