@readmagic/workmate 0.0.12 → 0.0.13

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 (312) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-CtRxzRny.js → AddWorkspaceDirectory-BzNj9rS6.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-CDZPR488.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-_yJJ0wqu.js → AgentsMdExternalIncludesDialog-CH9x1Ngp.js} +1 -1
  4. package/dist/chunks/App-D-bYAYAl.js +1 -0
  5. package/dist/chunks/ApproveApiKey-BEGV9Zj9.js +1 -0
  6. package/dist/chunks/ApproveApiKey-CjacpIqq.js +1 -0
  7. package/dist/chunks/BackgroundTasksDialog-A9hw_SV0.js +2 -0
  8. package/dist/chunks/{BypassPermissionsModeDialog-COI_V57z.js → BypassPermissionsModeDialog-B0BizN_J.js} +1 -1
  9. package/dist/chunks/{DiffDialog-CRWtQ1R5.js → DiffDialog-mQ-5_TSv.js} +3 -3
  10. package/dist/chunks/Doctor-BC6IuQhd.js +3 -0
  11. package/dist/chunks/Doctor-i_5_AQd-.js +1 -0
  12. package/dist/chunks/ExitFlow-Bu2cVGpC.js +2 -0
  13. package/dist/chunks/{Grove-DRZrhbF0.js → Grove-D0nn8zOV.js} +2 -2
  14. package/dist/chunks/{HybridTransport-BadJQe6u.js → HybridTransport-BQNLZNa_.js} +2 -2
  15. package/dist/chunks/InvalidConfigDialog-C5CIiSIE.js +1 -0
  16. package/dist/chunks/{InvalidSettingsDialog-ISzcIGPU.js → InvalidSettingsDialog-Dq7hKXcO.js} +1 -1
  17. package/dist/chunks/MCPConnectionManager-aDDsYkGM.js +1 -0
  18. package/dist/chunks/MCPToolListView-Cr0MDkzT.js +1 -0
  19. package/dist/chunks/{McpParsingWarnings-xv0RZCSL.js → McpParsingWarnings-CUx2zexI.js} +1 -1
  20. package/dist/chunks/MessageSelector-DwGOWKKL.js +3 -0
  21. package/dist/chunks/Messages-C1jh4ixt.js +11 -0
  22. package/dist/chunks/Onboarding-t-P6Q5O6.js +1 -0
  23. package/dist/chunks/{PromptInputFooterSuggestions-8-awCxOn.js → PromptInputFooterSuggestions-R12fbdmp.js} +1 -1
  24. package/dist/chunks/PromptInputHelpMenu-BgADIzRj.js +1 -0
  25. package/dist/chunks/QueryEngine-HlLQJmsd.js +1 -0
  26. package/dist/chunks/REPL-Rs_JQkDc.js +1 -0
  27. package/dist/chunks/REPL-VKAmKkII.js +133 -0
  28. package/dist/chunks/RemoteSessionManager-BbgXeM-t.js +2 -0
  29. package/dist/chunks/ResumeConversation-66zbx12g.js +1 -0
  30. package/dist/chunks/{SSETransport-je346ofV.js → SSETransport-BBQkdn4e.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-Bq87I_vu.js +1 -0
  32. package/dist/chunks/Settings-BKdLcyXe.js +2 -0
  33. package/dist/chunks/{TeleportProgress-zmdAsogZ.js → TeleportProgress-3hmIApkj.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-CG32I4cO.js → TeleportRepoMismatchDialog-BA1a66RK.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-2Yjr74Lq.js → TeleportResumeWrapper-BT4O-Wsi.js} +1 -1
  36. package/dist/chunks/{ThemePicker-p7_hHk1V.js → ThemePicker-DUlhcoso.js} +1 -1
  37. package/dist/chunks/{TrustDialog-BVcny9vs.js → TrustDialog-Dpk03V1Y.js} +1 -1
  38. package/dist/chunks/add-dir-BUr0z-VU.js +1 -0
  39. package/dist/chunks/{agentDisplay-CfMLGPGH.js → agentDisplay-D7bdOOG7.js} +1 -1
  40. package/dist/chunks/{agents-BT82hwBN.js → agents-22wiC58F.js} +1 -1
  41. package/dist/chunks/agents-8ELI8RJo.js +103 -0
  42. package/dist/chunks/{allErrors-CS77lRvU.js → allErrors-C1eMbHSv.js} +1 -1
  43. package/dist/chunks/api-DgjIFdMn.js +1 -0
  44. package/dist/chunks/{api-DAubp5q9.js → api-f3GN2I_J.js} +1 -1
  45. package/dist/chunks/auth-B73a4Cob.js +1 -0
  46. package/dist/chunks/{auth-yDsvFcM7.js → auth-Czy7GoRh.js} +1 -1
  47. package/dist/chunks/auth-D_0waidQ.js +1 -0
  48. package/dist/chunks/backgroundHousekeeping-C_ArdTFX.js +17 -0
  49. package/dist/chunks/backgroundHousekeeping-YJhvZ0dh.js +1 -0
  50. package/dist/chunks/{branch-DJiMa8td.js → branch-bb4-bErF.js} +2 -2
  51. package/dist/chunks/{bridgeConfig-BB6Hgali.js → bridgeConfig-B80T_lw7.js} +1 -1
  52. package/dist/chunks/bridgeConfig-DywkIo_k.js +1 -0
  53. package/dist/chunks/{bridgeMessaging-C9D0Lly2.js → bridgeMessaging-DyvHd16Z.js} +1 -1
  54. package/dist/chunks/{bridgeStatusUtil-D8UbcVrZ.js → bridgeStatusUtil-DStiD05t.js} +1 -1
  55. package/dist/chunks/{btw-BO2B23f-.js → btw-BRmV51bR.js} +1 -1
  56. package/dist/chunks/caches-C5DIVdvI.js +1 -0
  57. package/dist/chunks/caches-zDZEgNKq.js +1 -0
  58. package/dist/chunks/{ccrClient-BG9HU_fW.js → ccrClient-BALhzhPF.js} +1 -1
  59. package/dist/chunks/{clear-B4XN2fib.js → clear-B_yVyJXP.js} +1 -1
  60. package/dist/chunks/client-DVg8PpFX.js +1 -0
  61. package/dist/chunks/commands-ByFXqW43.js +1 -0
  62. package/dist/chunks/compact-BUShp2eQ.js +2 -0
  63. package/dist/chunks/config-BwHNU_pI.js +1 -0
  64. package/dist/chunks/{context-BY5oO5is.js → context-6Pk3iVhh.js} +1 -1
  65. package/dist/chunks/{context-noninteractive-mAQt1p9l.js → context-noninteractive-CHzerxnH.js} +2 -2
  66. package/dist/chunks/context-noninteractive-DFwRQyFE.js +1 -0
  67. package/dist/chunks/conversation-5zb5XkSA.js +1 -0
  68. package/dist/chunks/conversation-JP2ZXrwu.js +1 -0
  69. package/dist/chunks/{createSSHSession-DjLSGm-0.js → createSSHSession-XkHMiGRN.js} +1 -1
  70. package/dist/chunks/{createSession-CftIZ3aq.js → createSession-BNGm9fL4.js} +1 -1
  71. package/dist/chunks/createSession-VTqzWAu6.js +1 -0
  72. package/dist/chunks/crossProjectResume-DxgQVYSi.js +40 -0
  73. package/dist/chunks/{datadog-BGati3aQ.js → datadog-3WUWcCFn.js} +1 -1
  74. package/dist/chunks/{diff-1HsxKGBh.js → diff-CKlLimGq.js} +1 -1
  75. package/dist/chunks/doctor-Bvx0u0sO.js +1 -0
  76. package/dist/chunks/entry-DCbq734V.js +14 -0
  77. package/dist/chunks/{esm-BkOWaWVb.js → esm-CtQkOk5D.js} +1 -1
  78. package/dist/chunks/exit-DTsz5Lcb.js +1 -0
  79. package/dist/chunks/{extraUsage-0pUcYexI.js → extraUsage-C86bZVgt.js} +1 -1
  80. package/dist/chunks/extractMemories-6OnMgL2S.js +1 -0
  81. package/dist/chunks/fast-B2ziqJEA.js +1 -0
  82. package/dist/chunks/{fast-VOu2FUlV.js → fast-BkhjaTkZ.js} +1 -1
  83. package/dist/chunks/{fileSuggestions-Be-pyLLq.js → fileSuggestions-BalHmi1-.js} +2 -2
  84. package/dist/chunks/{firstPartyEventLogger-aFhcruXA.js → firstPartyEventLogger-1RTgXHSz.js} +2 -2
  85. package/dist/chunks/firstPartyEventLogger-CXMzhLrF.js +1 -0
  86. package/dist/chunks/{flushGate-BUSrMj_6.js → flushGate-DWL05x7v.js} +1 -1
  87. package/dist/chunks/{gemini-DB4M-MYv.js → gemini-BLpLJyli.js} +1 -1
  88. package/dist/chunks/generateSessionName-CdbMksHi.js +1 -0
  89. package/dist/chunks/goal-V3qix-i1.js +3 -0
  90. package/dist/chunks/grok-BLLATotv.js +1 -0
  91. package/dist/chunks/{grove-BnzBbGsX.js → grove-b9gGKgu4.js} +2 -2
  92. package/dist/chunks/{help-C5ankDi4.js → help-BR7UEr5R.js} +1 -1
  93. package/dist/chunks/{hooks-BZS105Rd.js → hooks-C-QMGvCg.js} +2 -2
  94. package/dist/chunks/hooks-D6wtd0Qq.js +1 -0
  95. package/dist/chunks/{initReplBridge-DL4klK0C.js → initReplBridge-DyScxedy.js} +1 -1
  96. package/dist/chunks/{install-NZvHd_40.js → install-DGH_bjUh.js} +1 -1
  97. package/dist/chunks/{instrumentation-CjBlVlFq.js → instrumentation-DQ705pC7.js} +3 -3
  98. package/dist/chunks/{job-D502Zf8J.js → job-BaMT6Lb2.js} +1 -1
  99. package/dist/chunks/keybindings-CG292HS1.js +2 -0
  100. package/dist/chunks/{launchLocalMemory-DxC3LojF.js → launchLocalMemory-CtZrkmaw.js} +2 -2
  101. package/dist/chunks/{launchOnboarding-BLp5k_H4.js → launchOnboarding-CyOtdZkT.js} +1 -1
  102. package/dist/chunks/loadAgentsDir-4UC4yLg1.js +1 -0
  103. package/dist/chunks/{loadAgentsDir-BXtV2jiO.js → loadAgentsDir-mcRW90aq.js} +389 -390
  104. package/dist/chunks/loadPluginHooks-CWI0RMUx.js +1 -0
  105. package/dist/chunks/{localSearch-CeP4ef0a.js → localSearch-CCCDKpYx.js} +1 -1
  106. package/dist/chunks/localSearch-D4hVR7-d.js +1 -0
  107. package/dist/chunks/{logoV2Utils-CEnU8qad.js → logoV2Utils--8OUQQPd.js} +1 -1
  108. package/dist/chunks/{magicDocs-YtfrqVC6.js → magicDocs-26J_l1De.js} +2 -2
  109. package/dist/chunks/main-DUjtDK1Q.js +513 -0
  110. package/dist/chunks/managedEnv-BuCurT_S.js +1 -0
  111. package/dist/chunks/{managedEnv-B-BNY0xC.js → managedEnv-Ds6MlFQE.js} +1 -1
  112. package/dist/chunks/{mappers-IuJeXgvr.js → mappers-DwZw084m.js} +1 -1
  113. package/dist/chunks/mcp-CEKR7PjL.js +6 -0
  114. package/dist/chunks/mcp-DCAf2hHD.js +1 -0
  115. package/dist/chunks/mcp-mCuc8dNe.js +2 -0
  116. package/dist/chunks/memory-B5SkpC7u.js +1 -0
  117. package/dist/chunks/{mode-GzBwK--u.js → mode-B80CHkqo.js} +2 -2
  118. package/dist/chunks/model-BqaneI4D.js +1 -0
  119. package/dist/chunks/{model-CDnVaVDR.js → model-C29_32BD.js} +1 -1
  120. package/dist/chunks/{model-BydaMaPr.js → model-NG8fvuT2.js} +1 -1
  121. package/dist/chunks/{modelOptions-ut0xePEe.js → modelOptions-CiZgZxZC.js} +1 -1
  122. package/dist/chunks/{nativeInstaller-fgCMR_c0.js → nativeInstaller-DqbEfGSX.js} +1 -1
  123. package/dist/chunks/{omit-D4Udf-p-.js → omit-KEhe84f4.js} +1 -1
  124. package/dist/chunks/{onChangeAppState-WbvtqDtk.js → onChangeAppState-Dq1tIEJI.js} +1 -1
  125. package/dist/chunks/{openai-DaVFXyBB.js → openai-BvnsYTpQ.js} +3 -3
  126. package/dist/chunks/{partition-CzW_31Y1.js → partition-DeT341qu.js} +1 -1
  127. package/dist/chunks/permissions-BPpeHxpk.js +3 -0
  128. package/dist/chunks/pidLock-DQGDoFQP.js +3 -0
  129. package/dist/chunks/{plan-M9DG3AqN.js → plan-BRiC5ujG.js} +1 -1
  130. package/dist/chunks/plugin-Dcg_GGR9.js +17 -0
  131. package/dist/chunks/{pluginAutoupdate-B5lel6s5.js → pluginAutoupdate-ByH9IPC9.js} +1 -1
  132. package/dist/chunks/pluginBlocklist-BfoLN9a-.js +1 -0
  133. package/dist/chunks/pluginCliCommands-Bc2Iybhz.js +1 -0
  134. package/dist/chunks/{pluginFlagging-CXSSOj4J.js → pluginFlagging-Cr0d0hBA.js} +1 -1
  135. package/dist/chunks/pluginOperations-CKNyYjS-.js +2 -0
  136. package/dist/chunks/pluginStartupCheck-B48_cGgo.js +1 -0
  137. package/dist/chunks/{pluginStartupCheck-BEd0VeQC.js → pluginStartupCheck-DiCDQQlr.js} +1 -1
  138. package/dist/chunks/plugins-BP_36tOl.js +4 -0
  139. package/dist/chunks/print-2uavraPq.js +26 -0
  140. package/dist/chunks/processBashCommand-g3sAMpHt.js +1 -0
  141. package/dist/chunks/processSlashCommand-tIbeCrv5.js +5 -0
  142. package/dist/chunks/{prompt-CRc2QEZ5.js → prompt-DIlq8NTy.js} +1 -1
  143. package/dist/chunks/prompt-DLv-Cd67.js +1 -0
  144. package/dist/chunks/prompt-DV5tCLRh.js +1 -0
  145. package/dist/chunks/{promptEditor-Bo1d8ZLq.js → promptEditor-BILqOGl1.js} +2 -2
  146. package/dist/chunks/{reconciler-BGav_ezX.js → reconciler-CDq6XgAS.js} +1 -1
  147. package/dist/chunks/refresh-ysrhoWCo.js +1 -0
  148. package/dist/chunks/{reload-plugins-DNEgQ5vo.js → reload-plugins-CGb0HTsH.js} +1 -1
  149. package/dist/chunks/{remoteBridgeCore-BGOqHADF.js → remoteBridgeCore-BmteXmI9.js} +1 -1
  150. package/dist/chunks/{remoteManagedSettings-26nhzuca.js → remoteManagedSettings-CwDGxL5p.js} +1 -1
  151. package/dist/chunks/rename-1GLIUlYk.js +1 -0
  152. package/dist/chunks/resume-DWtlUiHW.js +2 -0
  153. package/dist/chunks/{runtimeObserver-BZrF3GnQ.js → runtimeObserver-4ZqaCXYy.js} +4 -4
  154. package/dist/chunks/{runtimeObserver-CBV-7-w7.js → runtimeObserver-CtNY8Al2.js} +1 -1
  155. package/dist/chunks/sandbox-adapter-BzjRQh_r.js +1 -0
  156. package/dist/chunks/{sandbox-toggle-D61gVqcT.js → sandbox-toggle-Bz49-F6e.js} +1 -1
  157. package/dist/chunks/searchExtraTools-D6vj8qJ-.js +1 -0
  158. package/dist/chunks/{session-Dy-_R7KP.js → session-wb6X4Wrq.js} +1 -1
  159. package/dist/chunks/sessionFileAccessHooks-Da97UA2n.js +1 -0
  160. package/dist/chunks/{sessionObserver-CyLpHSkw.js → sessionObserver-BJQ5hwjU.js} +2 -2
  161. package/dist/chunks/sessionObserver-DXO4trhk.js +1 -0
  162. package/dist/chunks/{sessionState-DSWN4tMV.js → sessionState-Bn3ESS5f.js} +1 -1
  163. package/dist/chunks/sessionStorage-DlPVsQn9.js +1 -0
  164. package/dist/chunks/{sessionTitle-L5tyJgdU.js → sessionTitle-Cbzrb9jT.js} +2 -2
  165. package/dist/chunks/{sessionTracing-DpHGGIZm.js → sessionTracing-CEsm8pZL.js} +1 -1
  166. package/dist/chunks/{settingsSync-dBqlrbcU.js → settingsSync-eHaSngKo.js} +1 -1
  167. package/dist/chunks/setup-DeyiuGNX.js +3 -0
  168. package/dist/chunks/{shadowedRuleDetection-DZ0AA2Rw.js → shadowedRuleDetection-D5X5fhzj.js} +1 -1
  169. package/dist/chunks/{sideQuestion-BYT8FdPF.js → sideQuestion-BHRtwhyj.js} +3 -3
  170. package/dist/chunks/{sinks-mFsijQ_S.js → sinks-Bgy2UNK-.js} +2 -2
  171. package/dist/chunks/sinks-CgzLmim2.js +1 -0
  172. package/dist/chunks/skillChangeDetector-BlSP16j6.js +1 -0
  173. package/dist/chunks/{skillGapStore-DQXHqoP7.js → skillGapStore-BjQSSz2E.js} +2 -2
  174. package/dist/chunks/{skillLifecycle-BG_RnGSh.js → skillLifecycle-Sp8strFv.js} +2 -2
  175. package/dist/chunks/{skillSearchPanel-DxYP4Q6R.js → skillSearchPanel-3sYRez_Q.js} +4 -4
  176. package/dist/chunks/{skills-BD-2ofXA.js → skills-CJhWI8t1.js} +1 -1
  177. package/dist/chunks/{status-BmHu-c7I.js → status-CDCurOqs.js} +2 -2
  178. package/dist/chunks/{status-CrmnCDIE.js → status-yoQIQ2Ni.js} +1 -1
  179. package/dist/chunks/statusNoticeHelpers-Sl4jjauz.js +1 -0
  180. package/dist/chunks/switcher-C-m6MUwE.js +1 -0
  181. package/dist/chunks/{switcher-sYTxnJQA.js → switcher-uoQMHmEZ.js} +1 -1
  182. package/dist/chunks/{syncCache-BofuFJEe.js → syncCache-BooMjgU6.js} +1 -1
  183. package/dist/chunks/{tasks-NpI1iEem.js → tasks-CHG_6sXQ.js} +1 -1
  184. package/dist/chunks/teleport-C9KRE4X8.js +1 -0
  185. package/dist/chunks/{templateJobs-C94jEE6O.js → templateJobs-BYYfF4m5.js} +1 -1
  186. package/dist/chunks/{theme-CEi3b_8f.js → theme-MvX7hojJ.js} +1 -1
  187. package/dist/chunks/{toolEventObserver-DlL9CHmI.js → toolEventObserver-BFEl47bq.js} +1 -1
  188. package/dist/chunks/toolPool-Cq74Cvjp.js +1 -0
  189. package/dist/chunks/trustedDevice-BGwujSqc.js +1 -0
  190. package/dist/chunks/{trustedDevice-Bzz03jCy.js → trustedDevice-BLiKbGpG.js} +1 -1
  191. package/dist/chunks/{updateCCB-CzBxsuJe.js → updateCCB-CfckOy7T.js} +6 -6
  192. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-BHQfwlAl.js → useExitOnCtrlCDWithKeybindings-CPLBDluY.js} +1 -1
  193. package/dist/chunks/useMainLoopModel-C00PbZ1Q.js +1 -0
  194. package/dist/chunks/useManagePlugins-DFaGntzJ.js +1 -0
  195. package/dist/chunks/{useMergedTools-CHxnwR7R.js → useMergedTools-DYobZ5N4.js} +1 -1
  196. package/dist/chunks/{useSearchInput-q2CFPU4W.js → useSearchInput-KFKh2ozY.js} +1 -1
  197. package/dist/chunks/useSettingsErrors-BRgjvaHd.js +1 -0
  198. package/dist/chunks/{userAgent-B7WkjI6I.js → userAgent-DUrr02yh.js} +1 -1
  199. package/dist/chunks/util-D7uwPgF1.js +1 -0
  200. package/dist/chunks/validatePlugin-VukX52bx.js +1 -0
  201. package/dist/chunks/{workerRegistry-Cfo7bKlm.js → workerRegistry-BA37PVbv.js} +3 -3
  202. package/dist/chunks/worktree-Lik8xuKd.js +1 -0
  203. package/dist/cli.js +1 -1
  204. package/package.json +1 -1
  205. package/dist/chunks/AgentsMdExternalIncludesDialog-_bI4jo_P.js +0 -1
  206. package/dist/chunks/App-DoAZ7CYS.js +0 -1
  207. package/dist/chunks/ApproveApiKey-C8LwmDM2.js +0 -1
  208. package/dist/chunks/ApproveApiKey-DQP3qmb0.js +0 -1
  209. package/dist/chunks/BackgroundTasksDialog-CDA2noEk.js +0 -2
  210. package/dist/chunks/ConsoleOAuthFlow-Dn8fO-o_.js +0 -1
  211. package/dist/chunks/Doctor-CZ513Df9.js +0 -3
  212. package/dist/chunks/Doctor-CzPvNZzF.js +0 -1
  213. package/dist/chunks/ExitFlow-BFeftDv0.js +0 -2
  214. package/dist/chunks/InvalidConfigDialog-DQaT6aen.js +0 -1
  215. package/dist/chunks/MCPConnectionManager-BpjC7CEo.js +0 -1
  216. package/dist/chunks/MCPToolListView-Rb1Q--jG.js +0 -1
  217. package/dist/chunks/MessageSelector-BHB55sZb.js +0 -3
  218. package/dist/chunks/Messages-CPX-nIdA.js +0 -11
  219. package/dist/chunks/Onboarding-CymgipoF.js +0 -1
  220. package/dist/chunks/PromptInputHelpMenu-BP3UgCdi.js +0 -1
  221. package/dist/chunks/QueryEngine-HkswHUNv.js +0 -1
  222. package/dist/chunks/REPL-CZfg65kg.js +0 -133
  223. package/dist/chunks/REPL-eZsYNBfl.js +0 -1
  224. package/dist/chunks/RemoteSessionManager-B4jqKVd3.js +0 -2
  225. package/dist/chunks/ResumeConversation-B03XN_SP.js +0 -1
  226. package/dist/chunks/SearchExtraToolsTool-C85Sanww.js +0 -1
  227. package/dist/chunks/Settings-C8GKWod1.js +0 -2
  228. package/dist/chunks/WelcomeV2-BnSYhyfu.js +0 -1
  229. package/dist/chunks/add-dir-Bd7pilVx.js +0 -1
  230. package/dist/chunks/agents-qR6r94-F.js +0 -103
  231. package/dist/chunks/api-C4VflFau.js +0 -1
  232. package/dist/chunks/auth-CNCehj7y.js +0 -1
  233. package/dist/chunks/auth-DrD9DW6X.js +0 -1
  234. package/dist/chunks/autoMode-C2lnBot9.js +0 -45
  235. package/dist/chunks/backgroundHousekeeping-DbpTGbwl.js +0 -1
  236. package/dist/chunks/backgroundHousekeeping-SpTxViUq.js +0 -17
  237. package/dist/chunks/bridgeConfig-Ccm79Jze.js +0 -1
  238. package/dist/chunks/caches-BQmbXerw.js +0 -1
  239. package/dist/chunks/caches-Dtjmjm6G.js +0 -1
  240. package/dist/chunks/client-B-2ccQZk.js +0 -1
  241. package/dist/chunks/commands-D_-v6_A0.js +0 -1
  242. package/dist/chunks/compact-kM0ETtB2.js +0 -2
  243. package/dist/chunks/config-Crf6Mzu3.js +0 -1
  244. package/dist/chunks/connectHeadless-CqRoEtrg.js +0 -1
  245. package/dist/chunks/context-noninteractive-tc4KTYfI.js +0 -1
  246. package/dist/chunks/conversation-CFIn-KsW.js +0 -1
  247. package/dist/chunks/conversation-DPI7VKBL.js +0 -1
  248. package/dist/chunks/createSession-CjdLcRec.js +0 -1
  249. package/dist/chunks/crossProjectResume-BJqXBzkf.js +0 -40
  250. package/dist/chunks/dangerousBackend-DwcP0P08.js +0 -1
  251. package/dist/chunks/doctor-CJfvt9zR.js +0 -1
  252. package/dist/chunks/entry-CrZCZQQC.js +0 -14
  253. package/dist/chunks/exit-B8MA4Ltm.js +0 -1
  254. package/dist/chunks/extractMemories-DqhN0lba.js +0 -1
  255. package/dist/chunks/fast-DT5WDe3L.js +0 -1
  256. package/dist/chunks/firstPartyEventLogger-B8RVGBQB.js +0 -1
  257. package/dist/chunks/generateSessionName-DhCypqJ_.js +0 -1
  258. package/dist/chunks/goal-TxXtfkQ6.js +0 -3
  259. package/dist/chunks/grok-D2a_J5wE.js +0 -1
  260. package/dist/chunks/hooks-D-twhU_z.js +0 -1
  261. package/dist/chunks/keybindings-D9Boc8FD.js +0 -2
  262. package/dist/chunks/loadAgentsDir-BjsAQWqt.js +0 -1
  263. package/dist/chunks/loadPluginHooks-Dt3XQ-3N.js +0 -1
  264. package/dist/chunks/localSearch-Cz8Ot7k2.js +0 -1
  265. package/dist/chunks/lockfile-D5-j7HOZ.js +0 -1
  266. package/dist/chunks/main-CkjTzYj1.js +0 -513
  267. package/dist/chunks/managedEnv-K9Si1UuL.js +0 -1
  268. package/dist/chunks/mcp-DMBoeQzm.js +0 -6
  269. package/dist/chunks/mcp-TMOPfLcW.js +0 -1
  270. package/dist/chunks/mcp-x5rgv-uv.js +0 -2
  271. package/dist/chunks/memory-DDUoR63T.js +0 -1
  272. package/dist/chunks/model-CIvbC7rW.js +0 -1
  273. package/dist/chunks/parseConnectUrl-BiyKR5-x.js +0 -1
  274. package/dist/chunks/permissions-BT3lxYBM.js +0 -3
  275. package/dist/chunks/pidLock-d1VPd6CG.js +0 -3
  276. package/dist/chunks/plugin-BiNHuq3h.js +0 -17
  277. package/dist/chunks/pluginBlocklist-CNGmIlwU.js +0 -1
  278. package/dist/chunks/pluginCliCommands-WLOEhb2M.js +0 -1
  279. package/dist/chunks/pluginOperations-BFbty6WT.js +0 -2
  280. package/dist/chunks/pluginStartupCheck-Bcdxg484.js +0 -1
  281. package/dist/chunks/plugins-BMZ3aYKP.js +0 -4
  282. package/dist/chunks/print-DmoLcwVq.js +0 -26
  283. package/dist/chunks/processBashCommand-B-VqME9O.js +0 -1
  284. package/dist/chunks/processSlashCommand-D6zEooTy.js +0 -5
  285. package/dist/chunks/prompt-C3RRe4kW.js +0 -1
  286. package/dist/chunks/prompt-EtAanewG.js +0 -1
  287. package/dist/chunks/refresh-DumNiLvM.js +0 -1
  288. package/dist/chunks/rename-BPknfVGF.js +0 -1
  289. package/dist/chunks/resume-DGz04xDh.js +0 -2
  290. package/dist/chunks/sandbox-adapter-DUqeqkQD.js +0 -1
  291. package/dist/chunks/searchExtraTools-CgsV6kb1.js +0 -1
  292. package/dist/chunks/server-LdbAb0sV.js +0 -1
  293. package/dist/chunks/serverBanner-BdExKFHT.js +0 -1
  294. package/dist/chunks/serverLog-BFmvyJ93.js +0 -1
  295. package/dist/chunks/sessionFileAccessHooks-BJlrZaRD.js +0 -1
  296. package/dist/chunks/sessionManager-CPa049BO.js +0 -1
  297. package/dist/chunks/sessionObserver-BGYoLRGx.js +0 -1
  298. package/dist/chunks/sessionStorage-zJ1esSCE.js +0 -1
  299. package/dist/chunks/setup-zf3v3ICe.js +0 -3
  300. package/dist/chunks/sinks-DppGvgz1.js +0 -1
  301. package/dist/chunks/skillChangeDetector-D-iq09Xs.js +0 -1
  302. package/dist/chunks/statusNoticeHelpers-DakAVtQO.js +0 -1
  303. package/dist/chunks/switcher-Dm646gO5.js +0 -1
  304. package/dist/chunks/teleport-Bs3kEipi.js +0 -1
  305. package/dist/chunks/toolPool-DIT_uhtD.js +0 -1
  306. package/dist/chunks/trustedDevice-BokywSKL.js +0 -1
  307. package/dist/chunks/useMainLoopModel-BkyIIW9t.js +0 -1
  308. package/dist/chunks/useManagePlugins-BWROoGDs.js +0 -1
  309. package/dist/chunks/useSettingsErrors-CPVQbsqq.js +0 -1
  310. package/dist/chunks/util-BfqXOA-P.js +0 -1
  311. package/dist/chunks/validatePlugin-jrcrYEIu.js +0 -1
  312. package/dist/chunks/worktree-D0k_pCEz.js +0 -1
@@ -1,4 +1,4 @@
1
- import{d as e,o as t}from"./envUtils-DcaKZlRU.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{n as i,t as a}from"./axios-DaWTGg7G.js";import{bS as o,of as s,sf as c,xS as l}from"./loadAgentsDir-BXtV2jiO.js";import{C as ee,P as u,R as te,c as d,i as ne,x as re}from"./debug-Dr1SjdXn.js";import{g as f,n as p}from"./settings-DiBMs2gM.js";import{c as m,h,y as g}from"./config-9rLTDOYW.js";import{o as _,s as v}from"./log-27kCA_9u.js";import{n as y,r as b}from"./analytics-DJobLaWP.js";import{l as x,u as S}from"./oauth-D38aRTUb.js";import{$n as ie,Ar as ae,Br as C,Bt as w,Cn as oe,Dt as se,En as ce,Fr as T,Ft as E,Lr as D,Mr as O,Nr as k,Ot as A,Sn as j,St as M,Ur as N,Vr as P,Wr as F,ai as I,fn as L,gn as R,jn as z,jr as B,jt as V,kr as H,mn as U,nn as W,nr as G,pn as K,si as le,un as ue,yt as de,zr as fe}from"./model-CDnVaVDR.js";import{n as pe,t as me}from"./userAgent-B7WkjI6I.js";import{H as q,M as he}from"./sessionState-DSWN4tMV.js";import{d as ge,u as _e}from"./firstPartyEventLogger-aFhcruXA.js";import{n as ve}from"./trustedDevice-Bzz03jCy.js";import{i as ye,r as be}from"./grove-BnzBbGsX.js";import{t as xe}from"./remoteManagedSettings-26nhzuca.js";import{d as Se,n as Ce,t as we}from"./status-BmHu-c7I.js";import{createHash as Te,randomBytes as J}from"crypto";import{createServer as Ee}from"http";c(),w(),z(),h(),oe(),R(),_e();async function Y(){A.cache?.clear?.(),ve(),ce(),U(),ge(),be.cache?.clear?.(),ye.cache?.clear?.(),await xe(),await s()}async function De({clearOnboarding:e=!1}){let{flushTelemetry:t}=await import(`./instrumentation-CjBlVlFq.js`);await t(),await ue(),j().delete(),await Y(),g(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(),te(),re(),ne(),y(),f(),le(),F(),T(),he(),a(),S(),h(),G(),_(),pe();async function Oe(){try{if(m().claudeCodeFirstTokenDate!==void 0)return;let e=ie();if(e.error){v(Error(`Failed to get auth headers: ${e.error}`));return}let t=`${x().BASE_API_URL}/api/organization/claude_code_first_token_date`,n=(await i.get(t,{headers:{...e.headers,"User-Agent":me()},timeout:1e4})).data?.first_token_date??null;if(n!==null){let e=new Date(n).getTime();if(isNaN(e)){v(Error(`Received invalid first_token_date from API: ${n}`));return}}g(e=>({...e,claudeCodeFirstTokenDate:n}))}catch(e){v(e)}}o(),S(),_();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,b(`tengu_oauth_automatic_redirect`,{custom_handler:!0});return}let n=C(e)?x().CLAUDEAI_SUCCESS_URL:x().CONSOLE_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:n}),this.pendingResponse.end(),this.pendingResponse=null,b(`tengu_oauth_automatic_redirect`,{})}handleErrorRedirect(){if(!this.pendingResponse)return;let e=x().CLAUDEAI_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:e}),this.pendingResponse.end(),this.pendingResponse=null,b(`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){v(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 X(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Z(){return X(J(32))}function Ae(e){let t=Te(`sha256`);return t.update(e),X(t.digest())}function je(){return X(J(32))}y(),T(),n();var Q=class{constructor(){r(this,`codeVerifier`,void 0),r(this,`authCodeListener`,null),r(this,`port`,null),r(this,`manualAuthCodeResolver`,null),this.codeVerifier=Z()}async startOAuthFlow(e,t){this.authCodeListener=new ke,this.port=await this.authCodeListener.start();let n=Ae(this.codeVerifier),r=je(),i={codeChallenge:n,state:r,port:this.port,loginWithClaudeAi:t?.loginWithClaudeAi,inferenceOnly:t?.inferenceOnly,orgUUID:t?.orgUUID,loginHint:t?.loginHint,loginMethod:t?.loginMethod},a=H({...i,isManual:!0}),o=H({...i,isManual:!1}),s=await this.waitForAuthorizationCode(r,async()=>{t?.skipBrowserOpen?await e(a,o):(await e(a),await l(o))}),c=this.authCodeListener?.hasPendingResponse()??!1;b(`tengu_oauth_auth_code_received`,{automatic:c});try{let e=await B(s,r,this.codeVerifier,this.port,!c,t?.expiresIn),n=await k(e.access_token);if(c){let t=D(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:D(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}};y(),T(),w(),h(),_(),Se();async function $(e){await De({clearOnboarding:!1});let t=e.profile??await N(e.accessToken);t?P({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&&P({accountUuid:e.tokenAccount.uuid,emailAddress:e.tokenAccount.emailAddress,organizationUuid:e.tokenAccount.organizationUuid});let n=L(e);if(de(),n.warning&&b(`tengu_oauth_storage_warning`,{warning:n.warning}),await O(e.accessToken).catch(e=>d(String(e),{level:`error`})),C(e.scopes))await Oe().catch(e=>d(String(e),{level:`error`}));else if(!await ae(e.accessToken))throw Error(`Unable to create API key. The server accepted the request but did not return a key.`);await Y()}async function Me({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-DcaKZlRU.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{n as i,t as a}from"./axios-DaWTGg7G.js";import{_S as o,af as s,gS as c,of as l}from"./loadAgentsDir-mcRW90aq.js";import{C as ee,P as u,R as te,c as d,i as ne,x as re}from"./debug-Dr1SjdXn.js";import{g as f,n as p}from"./settings-DiBMs2gM.js";import{c as m,h,y as g}from"./config-9rLTDOYW.js";import{o as _,s as v}from"./log-27kCA_9u.js";import{n as y,r as b}from"./analytics-DJobLaWP.js";import{l as x,u as S}from"./oauth-D38aRTUb.js";import{$n as ie,Ar as ae,Br as C,Bt as w,Cn as oe,Dt as se,En as ce,Fr as T,Ft as E,Lr as D,Mr as O,Nr as k,Ot as A,Sn as j,St as M,Ur as N,Vr as P,Wr as F,ai as I,fn as L,gn as R,jn as z,jr as B,jt as V,kr as H,mn as U,nn as W,nr as G,pn as K,si as le,un as ue,yt as de,zr as fe}from"./model-C29_32BD.js";import{n as pe,t as me}from"./userAgent-DUrr02yh.js";import{H as q,M as he}from"./sessionState-Bn3ESS5f.js";import{d as ge,u as _e}from"./firstPartyEventLogger-1RTgXHSz.js";import{n as ve}from"./trustedDevice-BLiKbGpG.js";import{i as ye,r as be}from"./grove-b9gGKgu4.js";import{t as xe}from"./remoteManagedSettings-CwDGxL5p.js";import{d as Se,n as Ce,t as we}from"./status-CDCurOqs.js";import{createHash as Te,randomBytes as J}from"crypto";import{createServer as Ee}from"http";l(),w(),z(),h(),oe(),R(),_e();async function Y(){A.cache?.clear?.(),ve(),ce(),U(),ge(),be.cache?.clear?.(),ye.cache?.clear?.(),await xe(),await s()}async function De({clearOnboarding:e=!1}){let{flushTelemetry:t}=await import(`./instrumentation-DQ705pC7.js`);await t(),await ue(),j().delete(),await Y(),g(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(),te(),re(),ne(),y(),f(),le(),F(),T(),he(),a(),S(),h(),G(),_(),pe();async function Oe(){try{if(m().claudeCodeFirstTokenDate!==void 0)return;let e=ie();if(e.error){v(Error(`Failed to get auth headers: ${e.error}`));return}let t=`${x().BASE_API_URL}/api/organization/claude_code_first_token_date`,n=(await i.get(t,{headers:{...e.headers,"User-Agent":me()},timeout:1e4})).data?.first_token_date??null;if(n!==null){let e=new Date(n).getTime();if(isNaN(e)){v(Error(`Received invalid first_token_date from API: ${n}`));return}}g(e=>({...e,claudeCodeFirstTokenDate:n}))}catch(e){v(e)}}c(),S(),_();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,b(`tengu_oauth_automatic_redirect`,{custom_handler:!0});return}let n=C(e)?x().CLAUDEAI_SUCCESS_URL:x().CONSOLE_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:n}),this.pendingResponse.end(),this.pendingResponse=null,b(`tengu_oauth_automatic_redirect`,{})}handleErrorRedirect(){if(!this.pendingResponse)return;let e=x().CLAUDEAI_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:e}),this.pendingResponse.end(),this.pendingResponse=null,b(`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){v(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 X(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Z(){return X(J(32))}function Ae(e){let t=Te(`sha256`);return t.update(e),X(t.digest())}function je(){return X(J(32))}y(),T(),n();var Q=class{constructor(){r(this,`codeVerifier`,void 0),r(this,`authCodeListener`,null),r(this,`port`,null),r(this,`manualAuthCodeResolver`,null),this.codeVerifier=Z()}async startOAuthFlow(e,t){this.authCodeListener=new ke,this.port=await this.authCodeListener.start();let n=Ae(this.codeVerifier),r=je(),i={codeChallenge:n,state:r,port:this.port,loginWithClaudeAi:t?.loginWithClaudeAi,inferenceOnly:t?.inferenceOnly,orgUUID:t?.orgUUID,loginHint:t?.loginHint,loginMethod:t?.loginMethod},a=H({...i,isManual:!0}),s=H({...i,isManual:!1}),c=await this.waitForAuthorizationCode(r,async()=>{t?.skipBrowserOpen?await e(a,s):(await e(a),await o(s))}),l=this.authCodeListener?.hasPendingResponse()??!1;b(`tengu_oauth_auth_code_received`,{automatic:l});try{let e=await B(c,r,this.codeVerifier,this.port,!l,t?.expiresIn),n=await k(e.access_token);if(l){let t=D(e.scope);this.authCodeListener?.handleSuccessRedirect(t)}return this.formatTokens(e,n.subscriptionType,n.rateLimitTier,n.rawProfile)}catch(e){throw l&&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:D(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}};y(),T(),w(),h(),_(),Se();async function $(e){await De({clearOnboarding:!1});let t=e.profile??await N(e.accessToken);t?P({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&&P({accountUuid:e.tokenAccount.uuid,emailAddress:e.tokenAccount.emailAddress,organizationUuid:e.tokenAccount.organizationUuid});let n=L(e);if(de(),n.warning&&b(`tengu_oauth_storage_warning`,{warning:n.warning}),await O(e.accessToken).catch(e=>d(String(e),{level:`error`})),C(e.scopes))await Oe().catch(e=>d(String(e),{level:`error`}));else if(!await ae(e.accessToken))throw Error(`Unable to create API key. The server accepted the request but did not return a key.`);await Y()}async function Me({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=p(),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-C29_32BD.js";e();export{r as checkAndRefreshOAuthTokenIfNeeded,i as clearOAuthTokenCache,n as getClaudeAIOAuthTokens,t as handleOAuth401Error};
@@ -0,0 +1,17 @@
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{i as t,o as n}from"./envUtils-DcaKZlRU.js";import{Ac as r,Da as i,Ea as a,IC as o,Ld as s,Q as c,Q_ as l,RC as u,Rd as d,Sr as ee,Xb as te,Zb as ne,dm as re,dr as f,et as p,jc as m,pt as h,rp as g,tp as ie,wa as ae,wt as oe,za as _}from"./loadAgentsDir-mcRW90aq.js";import{R as v,W as y,Wt as b}from"./state-BPFYBqm1.js";import{n as se,t as x}from"./cwd-Besi3Os3.js";import{R as S,U as C,c as w,f as T,i as E,u as D,x as O}from"./debug-Dr1SjdXn.js";import{f as k,g as A,y as j}from"./settings-DiBMs2gM.js";import{S as M}from"./config-9rLTDOYW.js";import{o as N,s as P,v as F,y as I}from"./log-27kCA_9u.js";import{n as L,r as R}from"./analytics-DJobLaWP.js";import{_ as z,h as B}from"./model-C29_32BD.js";import{bn as V,yn as H}from"./prompt-DIlq8NTy.js";import{at as U}from"./sessionState-Bn3ESS5f.js";import{i as W,t as G}from"./nativeInstaller-DqbEfGSX.js";import{n as K,t as ce}from"./allErrors-C1eMbHSv.js";import{r as le}from"./magicDocs-26J_l1De.js";import{n as ue,t as de}from"./pluginAutoupdate-ByH9IPC9.js";import{n as fe,r as pe}from"./registerProtocol-DduKPsn_.js";import"os";import{join as q}from"path";import"crypto";n(),b(),se(),O(),T(),E(),I(),A(),V(),z(),m(),ee(),le(),c(),N(),S(),_(),l(),c(),ne(),S(),N(),_(),l(),re();async function me(e,t){if(!e)return;let{join:n}=await import(`path`),r=await import(`fs/promises`),o=n(x(),`.workmate`,`skills`,e,`SKILL.md`),s;try{s=await r.readFile(o,`utf-8`)}catch{P(Error(`Failed to read skill file for improvement: ${o}`));return}let c=t.map(e=>`- ${e.section}: ${e.change}`).join(`
2
+ `),l=B(),u=await p({messages:[ae({content:`You are editing a skill definition file. Apply the following improvements to the skill.
3
+
4
+ <current_skill_file>
5
+ ${s}
6
+ </current_skill_file>
7
+
8
+ <improvements>
9
+ ${c}
10
+ </improvements>
11
+
12
+ Rules:
13
+ - Integrate the improvements naturally into the existing structure
14
+ - Preserve frontmatter (--- block) exactly as-is
15
+ - Preserve the overall format and style
16
+ - Do not remove existing content unless an improvement explicitly replaces it
17
+ - Output the complete updated file inside <updated_file> tags`})],systemPrompt:U([`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()=>H(),model:l,toolChoice:void 0,isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,temperatureOverride:0,agents:[],querySource:`skill_improvement_apply`,mcpTools:[]}}),d=a(i(Array.isArray(u.message.content)?u.message.content:[]).trim(),`updated_file`);if(!d){P(Error(`Skill improvement apply: no updated_file tag in response`));return}try{await r.writeFile(o,d,`utf-8`)}catch(e){P(C(e))}}L(),g(),M(),N(),G(),d(),K(),u(),oe();var he=30;function J(){let e=((k()||{}).cleanupPeriodDays??he)*24*60*60*1e3;return new Date(Date.now()-e)}function ge(e,t){return{messages:e.messages+t.messages,errors:e.errors+t.errors}}function _e(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 Y(e,t,n){let r={messages:0,errors:0};try{let i=await D().readdir(e);for(let a of i)try{_e(a.name)<t&&(await D().unlink(q(e,a.name)),n?r.messages++:r.errors++)}catch(e){P(e)}}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&P(e)}return r}async function ve(){let e=D(),t=J(),n=F.errors(),r=F.baseLogs(),i=await Y(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=>q(r,e.name));for(let n of a)i=ge(i,await Y(n,t,!0)),await Z(n,e)}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&P(e)}return i}async function X(e,t,n){return(await n.stat(e)).mtime<t?(await n.unlink(e),!0):!1}async function Z(e,t){try{await t.rmdir(e)}catch{}}async function ye(){let e=J(),t={messages:0,errors:0},n=f(),r=D(),i;try{i=await r.readdir(n)}catch{return t}for(let a of i){if(!a.isDirectory())continue;let i=q(n,a.name),s;try{s=await r.readdir(i)}catch{t.errors++;continue}for(let n of s)if(n.isFile()){if(!n.name.endsWith(`.jsonl`)&&!n.name.endsWith(`.cast`))continue;try{await X(q(i,n.name),e,r)&&t.messages++}catch{t.errors++}}else if(n.isDirectory()){let a=q(i,n.name),s=q(a,o),c;try{c=await r.readdir(s)}catch{await Z(a,r);continue}for(let n of c)if(n.isFile())try{await X(q(s,n.name),e,r)&&t.messages++}catch{t.errors++}else if(n.isDirectory()){let i=q(s,n.name),a;try{a=await r.readdir(i)}catch{continue}for(let n of a)if(n.isFile())try{await X(q(i,n.name),e,r)&&t.messages++}catch{t.errors++}await Z(i,r)}await Z(s,r),await Z(a,r)}await Z(i,r)}return t}async function be(e,t,n=!0){let r=J(),i={messages:0,errors:0},a=D(),o;try{o=await a.readdir(e)}catch{return i}for(let n of o)if(!(!n.isFile()||!n.name.endsWith(t)))try{await X(q(e,n.name),r,a)&&i.messages++}catch{i.errors++}return n&&await Z(e,a),i}function xe(){return be(q(t(),`plans`),`.md`)}async function Se(){let e=J(),n={messages:0,errors:0},r=D();try{let i=q(t(),`file-history`),a;try{a=await r.readdir(i)}catch{return n}let o=a.filter(e=>e.isDirectory()).map(e=>q(i,e.name));await Promise.all(o.map(async t=>{try{(await r.stat(t)).mtime<e&&(await r.rm(t,{recursive:!0,force:!0}),n.messages++)}catch{n.errors++}})),await Z(i,r)}catch(e){P(e)}return n}async function Ce(){let e=J(),n={messages:0,errors:0},r=D();try{let i=q(t(),`session-env`),a;try{a=await r.readdir(i)}catch{return n}let o=a.filter(e=>e.isDirectory()).map(e=>q(i,e.name));for(let t of o)try{(await r.stat(t)).mtime<e&&(await r.rm(t,{recursive:!0,force:!0}),n.messages++)}catch{n.errors++}await Z(i,r)}catch(e){P(e)}return n}async function we(){let e=J(),n={messages:0,errors:0},r=D(),i=q(t(),`debug`),a;try{a=await r.readdir(i)}catch{return n}for(let t of a)if(!(!t.isFile()||!t.name.endsWith(`.txt`)||t.name===`latest`))try{await X(q(i,t.name),e,r)&&n.messages++}catch{n.errors++}return n}async function Q(){let{errors:e}=ce();if(e.length>0&&j(`cleanupPeriodDays`)){w(`Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup.`);return}await ve(),await ye(),await xe(),await Se(),await Ce(),await we(),await ie(),await s(J());let t=await h(J());t>0&&R(`tengu_worktree_cleanup`,{removed:t})}b(),G(),ue();var Te=(fe(),e(pe)),$=600*1e3;function Ee(){import(`./extractMemories-6OnMgL2S.js`).then(({initExtractMemories:e})=>{e()}).catch(()=>{}),r(),de(),v()&&Te.ensureDeepLinkProtocolRegistered();let e=!0;async function t(){if(v()&&y()>Date.now()-1e3*60){setTimeout(t,$).unref();return}if(e&&(e=!1,await Q()),v()&&y()>Date.now()-1e3*60){setTimeout(t,$).unref();return}await W()}setTimeout(t,$).unref()}export{me as n,Ee as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./backgroundHousekeeping-C_ArdTFX.js";export{e as startBackgroundHousekeeping};
@@ -1,3 +1,3 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Cr as t,dr as n,hi as r,kr as i,li as a,vr as o,yr as s}from"./loadAgentsDir-BXtV2jiO.js";import{Wt as c,et as l,pt as u}from"./state-BPFYBqm1.js";import{C as d,x as f}from"./debug-Dr1SjdXn.js";import{c as p,s as m}from"./types-BJ7qTz75.js";import{n as h,r as g}from"./analytics-DJobLaWP.js";import{i as _,o as v}from"./stringUtils-Df-Lnjxd.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(),r=u(),a=n(l()),c=s(t),f=o();await b(a,{recursive:!0,mode:448});let m;try{m=await x(f)}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=>i(e)&&!e.isSidechain),_=h.filter(e=>e.type===`content-replacement`&&e.sessionId===r).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:r,messageUuid:e.uuid}},i={...e,sessionId:t};w.push(i),C.push(d(n)),e.type!==`progress`&&(v=e.uuid)}if(_.length>0){let e={type:`content-replacement`,sessionId:t,replacements:_};C.push(d(e))}return await S(c,C.join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Or as t,Sr as n,_r as r,ci as i,mi as a,ur as o,vr as s}from"./loadAgentsDir-mcRW90aq.js";import{Wt as c,et as l,pt as u}from"./state-BPFYBqm1.js";import{C as d,x as f}from"./debug-Dr1SjdXn.js";import{c as p,s as m}from"./types-BJ7qTz75.js";import{n as h,r as g}from"./analytics-DJobLaWP.js";import{i as _,o as v}from"./stringUtils-Df-Lnjxd.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 n=y(),i=u(),a=o(l()),c=s(n),f=r();await b(a,{recursive:!0,mode:448});let m;try{m=await x(f)}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=>t(e)&&!e.isSidechain),_=h.filter(e=>e.type===`content-replacement`&&e.sessionId===i).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 t={...e,sessionId:n,parentUuid:v,isSidechain:!1,forkedFrom:{sessionId:i,messageUuid:e.uuid}},r={...e,sessionId:n};w.push(r),C.push(d(t)),e.type!==`progress`&&(v=e.uuid)}if(_.length>0){let e={type:`content-replacement`,sessionId:n,replacements:_};C.push(d(e))}return await S(c,C.join(`
2
2
  `)+`
3
- `,{encoding:`utf8`,mode:384}),{sessionId:t,title:e,forkPath:c,serializedMessages:w,contentReplacementRecords:_}}async function T(e){let t=`${e} (Branch)`;if((await r(t,{exact:!0})).length===0)return t;let n=await r(`${e} (Branch`),i=new Set([1]),a=RegExp(`^${_(e)} \\(Branch(?: (\\d+))?\\)$`);for(let e of n){let t=e.customTitle?.match(a);t&&(t[1]?i.add(parseInt(t[1],10)):i.add(1))}let o=2;for(;i.has(o);)o++;return`${e} (Branch ${o})`}async function E(e,t,n){let r=n?.trim()||void 0,i=u();try{let{sessionId:n,title:o,forkPath:s,serializedMessages:c,contentReplacementRecords:l}=await w(r),u=new Date,d=C(c.find(e=>e.type===`user`)),f=await T(o??d);await a(n,f,s),g(`tengu_conversation_forked`,{message_count:c.length,has_custom_title:!!o});let p={date:u.toISOString().split(`T`)[0],messages:c,fullPath:s,value:u.getTime(),created:u,modified:u,firstPrompt:d,messageCount:c.length,isSidechain:!1,sessionId:n,customTitle:f,contentReplacements:l},m=o?` "${o}"`:``,h=`Branched conversation${m}. You are now in the branch.${`\nTo resume the original: claude -r ${i}`}`;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((()=>{c(),h(),m(),t(),f(),v()}))();export{E as call,C as deriveFirstPrompt};
3
+ `,{encoding:`utf8`,mode:384}),{sessionId:n,title:e,forkPath:c,serializedMessages:w,contentReplacementRecords:_}}async function T(e){let t=`${e} (Branch)`;if((await a(t,{exact:!0})).length===0)return t;let n=await a(`${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 o=2;for(;r.has(o);)o++;return`${e} (Branch ${o})`}async function E(e,t,n){let r=n?.trim()||void 0,a=u();try{let{sessionId:n,title:o,forkPath:s,serializedMessages:c,contentReplacementRecords:l}=await w(r),u=new Date,d=C(c.find(e=>e.type===`user`)),f=await T(o??d);await i(n,f,s),g(`tengu_conversation_forked`,{message_count:c.length,has_custom_title:!!o});let p={date:u.toISOString().split(`T`)[0],messages:c,fullPath:s,value:u.getTime(),created:u,modified:u,firstPrompt:d,messageCount:c.length,isSidechain:!1,sessionId:n,customTitle:f,contentReplacements:l},m=o?` "${o}"`:``,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((()=>{c(),h(),m(),n(),f(),v()}))();export{E as call,C as deriveFirstPrompt};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{l as t,u as n}from"./oauth-D38aRTUb.js";import{Bt as r,Ot as i}from"./model-CDnVaVDR.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-D38aRTUb.js";import{Bt as r,Ot as i}from"./model-C29_32BD.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-B80T_lw7.js";e();export{r as getBridgeAccessToken,t as getBridgeBaseUrl,n as isSelfHostedBridge};
@@ -1 +1 @@
1
- import{o as e}from"./envUtils-DcaKZlRU.js";import{n as t,t as n}from"./defineProperty-C-QyHrDq.js";import{P as r,R as i,S as a,c as o,i as s,x as c}from"./debug-Dr1SjdXn.js";import{B as l,F as u,H as d,I as f,O as p,b as m,g as h,m as g,q as _}from"./log-27kCA_9u.js";import{n as v,r as y}from"./analytics-DJobLaWP.js";import{M as b,st as x}from"./sessionState-DSWN4tMV.js";import{n as S,t as C}from"./rcDebugLog-DSchf3Hs.js";import{t as w}from"./controlMessageCompat-IFu4Gc1y.js";import{randomUUID as T}from"crypto";e();async function E(){return!1}function D(){return!1}function O(){return!0}function k(){return null}v(),b(),s(),C(),g(),i(),c(),_(),t();function A(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}function j(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_response`&&`response`in e}function M(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_request`&&`request_id`in e&&`request`in e}function N(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 P(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 h(n)||void 0}var F=`system-reminder`,I=/\s*<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/gy,L=new Set([m,p,u,f,l,d]);function R(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 z(e){let t=e.trim();if(!t)return null;I.lastIndex=0;let n=[];for(;I.lastIndex<t.length;){let e=I.exec(t);if(!e)return null;n.push(e[1])}return n.length>0?n:null}function B(e){if(e.type!==`user`||e.isVisibleInTranscriptOnly)return!1;if(e.toolUseResult!==void 0||!e.isMeta)return!0;let t=z(R(e));return!t||t.some(e=>e!==`local-command-caveat`&&e!==F&&L.has(e))}function V(e){return e.some(B)}function H(e,t,n,i,s,c){try{let r=w(a(e));if(j(r)){o(`[bridge:repl] Ingress message type=control_response`),s?.(r);return}if(M(r)){o(`[bridge:repl] Inbound control_request subtype=${r.request.subtype}`),c?.(r);return}if(!A(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&&n.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&&n.add(l),y(`tengu_bridge_message_received`,{is_repl:!0}),i?.(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 U=`This session is outbound-only. Enable Remote Control locally to allow inbound control.`;function W(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:U}};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 G(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 K=class{constructor(e){n(this,`capacity`,void 0),n(this,`ring`,void 0),n(this,`set`,new Set),n(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{N as a,V as c,O as d,D as f,W as i,k as l,P as n,G as o,H as r,B as s,K as t,E as u};
1
+ import{o as e}from"./envUtils-DcaKZlRU.js";import{n as t,t as n}from"./defineProperty-C-QyHrDq.js";import{P as r,R as i,S as a,c as o,i as s,x as c}from"./debug-Dr1SjdXn.js";import{B as l,F as u,H as d,I as f,O as p,b as m,g as h,m as g,q as _}from"./log-27kCA_9u.js";import{n as v,r as y}from"./analytics-DJobLaWP.js";import{M as b,st as x}from"./sessionState-Bn3ESS5f.js";import{n as S,t as C}from"./rcDebugLog-DSchf3Hs.js";import{t as w}from"./controlMessageCompat-IFu4Gc1y.js";import{randomUUID as T}from"crypto";e();async function E(){return!1}function D(){return!1}function O(){return!0}function k(){return null}v(),b(),s(),C(),g(),i(),c(),_(),t();function A(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}function j(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_response`&&`response`in e}function M(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`control_request`&&`request_id`in e&&`request`in e}function N(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 P(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 h(n)||void 0}var F=`system-reminder`,I=/\s*<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/gy,L=new Set([m,p,u,f,l,d]);function R(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 z(e){let t=e.trim();if(!t)return null;I.lastIndex=0;let n=[];for(;I.lastIndex<t.length;){let e=I.exec(t);if(!e)return null;n.push(e[1])}return n.length>0?n:null}function B(e){if(e.type!==`user`||e.isVisibleInTranscriptOnly)return!1;if(e.toolUseResult!==void 0||!e.isMeta)return!0;let t=z(R(e));return!t||t.some(e=>e!==`local-command-caveat`&&e!==F&&L.has(e))}function V(e){return e.some(B)}function H(e,t,n,i,s,c){try{let r=w(a(e));if(j(r)){o(`[bridge:repl] Ingress message type=control_response`),s?.(r);return}if(M(r)){o(`[bridge:repl] Inbound control_request subtype=${r.request.subtype}`),c?.(r);return}if(!A(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&&n.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&&n.add(l),y(`tengu_bridge_message_received`,{is_repl:!0}),i?.(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 U=`This session is outbound-only. Enable Remote Control locally to allow inbound control.`;function W(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:U}};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 G(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 K=class{constructor(e){n(this,`capacity`,void 0),n(this,`ring`,void 0),n(this,`set`,new Set),n(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{N as a,V as c,O as d,D as f,W as i,k as l,P as n,G as o,H as r,B as s,K as t,E as u};
@@ -1 +1 @@
1
- import{DS as e,TS as t}from"./loadAgentsDir-BXtV2jiO.js";import{t as n}from"./src-P_wYS_NJ2.js";import{v as r}from"./startupProfiler-Dc5r6LgE.js";import{a as i,n as a,o}from"./bridgeConfig-BB6Hgali.js";e(),i(),n(),r();function s(e,n){return`${o()?a():t(void 0,n)}/code?bridge=${e}`}function c({error:e,connected:t,sessionActive:n,reconnecting:r}){return e?{label:`Remote Control failed`,color:`error`}:r?{label:`Remote Control reconnecting`,color:`warning`}:n||t?{label:`Remote Control active`,color:`success`}:{label:`Remote Control connecting…`,color:`warning`}}function l(e){return`Code everywhere with the Claude app or ${e}`}function u(e){return`Continue coding in the Claude app or ${e}`}var d=`Something went wrong, please try again`;export{c as a,l as i,u as n,s as r,d as t};
1
+ import{CS as e,xS as t}from"./loadAgentsDir-mcRW90aq.js";import{t as n}from"./src-P_wYS_NJ2.js";import{v as r}from"./startupProfiler-Dc5r6LgE.js";import{a as i,n as a,o}from"./bridgeConfig-B80T_lw7.js";e(),i(),n(),r();function s(e,n){return`${o()?a():t(void 0,n)}/code?bridge=${e}`}function c({error:e,connected:t,sessionActive:n,reconnecting:r}){return e?{label:`Remote Control failed`,color:`error`}:r?{label:`Remote Control reconnecting`,color:`warning`}:n||t?{label:`Remote Control active`,color:`success`}:{label:`Remote Control connecting…`,color:`warning`}}function l(e){return`Code everywhere with the Claude app or ${e}`}function u(e){return`Continue coding in the Claude app or ${e}`}var d=`Something went wrong, please try again`;export{c as a,l as i,u as n,s as r,d as t};
@@ -1 +1 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Ba as n,Ep as r,IC as i,Iu as a,Lu as o,Ma as s,Op as c,av as l,ct as u,dc as d,ex as f,fc as p,iv as m,lt as h,nv as g,ov as _,tx as v}from"./loadAgentsDir-BXtV2jiO.js";import{I as y,P as b,bn as x,fi as S,ot as C,t as w,vn as T,xt as E}from"./src-P_wYS_NJ2.js";import{t as D}from"./jsx-runtime-Bb4Xn-E0.js";import{P as O,R as k}from"./debug-Dr1SjdXn.js";import{Wt as A}from"./settings-DiBMs2gM.js";import{h as j,y as M}from"./config-9rLTDOYW.js";import{at as N}from"./sessionState-DSWN4tMV.js";import{n as P,r as F}from"./sideQuestion-BYT8FdPF.js";import{i as I,n as L}from"./modalContext-CUThy6Ph.js";function R({question:e,context:t,onDone:n}){let[i,o]=(0,H.useState)(null),[s,c]=(0,H.useState)(null),[l,u]=(0,H.useState)(0),d=(0,H.useRef)(null),{rows:p}=I(C());x(()=>u(e=>e+1),i||s?null:80);function m(e){if(e.key===`escape`||e.key===`return`||e.key===` `||e.ctrl&&(e.key===`c`||e.key===`d`)){e.preventDefault(),n(void 0,{display:`skip`});return}(e.key===`up`||e.ctrl&&e.key===`p`)&&(e.preventDefault(),d.current?.scrollBy(-3)),(e.key===`down`||e.ctrl&&e.key===`n`)&&(e.preventDefault(),d.current?.scrollBy(K))}(0,H.useEffect)(()=>{let n=f();async function r(){try{let r=await F({question:e,cacheSafeParams:await B(t)});n.signal.aborted||(r.response?o(r.response):c(`No response received`))}catch(e){n.signal.aborted||c(O(e)||`Failed to get response`)}}return r(),()=>{n.abort()}},[e,t]);let h=Math.max(5,p-W-G);return(0,U.jsxs)(y,{flexDirection:`column`,paddingLeft:2,marginTop:1,tabIndex:0,autoFocus:!0,onKeyDown:m,children:[(0,U.jsxs)(y,{children:[(0,U.jsxs)(b,{color:`warning`,bold:!0,children:[`/btw`,` `]}),(0,U.jsx)(b,{dimColor:!0,children:e})]}),(0,U.jsx)(y,{marginTop:1,marginLeft:2,maxHeight:h,children:(0,U.jsx)(E,{ref:d,flexDirection:`column`,flexGrow:1,children:s?(0,U.jsx)(b,{color:`error`,children:s}):i?(0,U.jsx)(r,{children:i}):(0,U.jsxs)(y,{children:[(0,U.jsx)(a,{frame:l,messageColor:`warning`}),(0,U.jsx)(b,{color:`warning`,children:`Answering...`})]})})}),(i||s)&&(0,U.jsx)(y,{marginTop:1,children:(0,U.jsxs)(b,{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=s(z(e.messages)),n=d();if(n)return{systemPrompt:n.systemPrompt,userContext:n.userContext,systemContext:n.systemContext,toolUseContext:e,forkContextMessages:t};let[r,i,a]=await Promise.all([u(e.options.tools,e.options.mainLoopModel,[],e.options.mcpClients),l(),m()]);return{systemPrompt:N(r),userContext:i,systemContext:a,toolUseContext:e,forkContextMessages:t}}async function V(e,t,n){let r=n?.trim();return r?(M(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((()=>{S(),H=t(S(),1),T(),c(),o(),A(),h(),L(),_(),i(),w(),v(),j(),k(),p(),n(),P(),g(),U=D(),W=5,G=6,K=3}))();export{V as call};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Dp as n,Fu as r,Iu as i,MC as a,Q_ as o,Tp as s,Xb as c,Zb as l,ct as u,dc as d,ev as f,ja as p,nv as m,st as h,tv as g,uc as _,za as v}from"./loadAgentsDir-mcRW90aq.js";import{I as y,P as b,bn as x,fi as S,ot as C,t as w,vn as T,xt as E}from"./src-P_wYS_NJ2.js";import{t as D}from"./jsx-runtime-Bb4Xn-E0.js";import{P as O,R as k}from"./debug-Dr1SjdXn.js";import{Wt as A}from"./settings-DiBMs2gM.js";import{h as j,y as M}from"./config-9rLTDOYW.js";import{at as N}from"./sessionState-Bn3ESS5f.js";import{n as P,r as F}from"./sideQuestion-BHRtwhyj.js";import{i as I,n as L}from"./modalContext-CUThy6Ph.js";function R({question:e,context:t,onDone:n}){let[i,a]=(0,H.useState)(null),[o,l]=(0,H.useState)(null),[u,d]=(0,H.useState)(0),f=(0,H.useRef)(null),{rows:p}=I(C());x(()=>d(e=>e+1),i||o?null:80);function m(e){if(e.key===`escape`||e.key===`return`||e.key===` `||e.ctrl&&(e.key===`c`||e.key===`d`)){e.preventDefault(),n(void 0,{display:`skip`});return}(e.key===`up`||e.ctrl&&e.key===`p`)&&(e.preventDefault(),f.current?.scrollBy(-3)),(e.key===`down`||e.ctrl&&e.key===`n`)&&(e.preventDefault(),f.current?.scrollBy(K))}(0,H.useEffect)(()=>{let n=c();async function r(){try{let r=await F({question:e,cacheSafeParams:await B(t)});n.signal.aborted||(r.response?a(r.response):l(`No response received`))}catch(e){n.signal.aborted||l(O(e)||`Failed to get response`)}}return r(),()=>{n.abort()}},[e,t]);let h=Math.max(5,p-W-G);return(0,U.jsxs)(y,{flexDirection:`column`,paddingLeft:2,marginTop:1,tabIndex:0,autoFocus:!0,onKeyDown:m,children:[(0,U.jsxs)(y,{children:[(0,U.jsxs)(b,{color:`warning`,bold:!0,children:[`/btw`,` `]}),(0,U.jsx)(b,{dimColor:!0,children:e})]}),(0,U.jsx)(y,{marginTop:1,marginLeft:2,maxHeight:h,children:(0,U.jsx)(E,{ref:f,flexDirection:`column`,flexGrow:1,children:o?(0,U.jsx)(b,{color:`error`,children:o}):i?(0,U.jsx)(s,{children:i}):(0,U.jsxs)(y,{children:[(0,U.jsx)(r,{frame:u,messageColor:`warning`}),(0,U.jsx)(b,{color:`warning`,children:`Answering...`})]})})}),(i||o)&&(0,U.jsx)(y,{marginTop:1,children:(0,U.jsxs)(b,{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=p(z(e.messages)),n=_();if(n)return{systemPrompt:n.systemPrompt,userContext:n.userContext,systemContext:n.systemContext,toolUseContext:e,forkContextMessages:t};let[r,i,a]=await Promise.all([h(e.options.tools,e.options.mainLoopModel,[],e.options.mcpClients),g(),f()]);return{systemPrompt:N(r),userContext:i,systemContext:a,toolUseContext:e,forkContextMessages:t}}async function V(e,t,n){let r=n?.trim();return r?(M(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((()=>{S(),H=t(S(),1),T(),n(),i(),A(),u(),L(),m(),a(),w(),l(),j(),k(),d(),v(),P(),o(),U=D(),W=5,G=6,K=3}))();export{V as call};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$_ as t,As as n,Dv as r,Eh as i,JC as a,Ji as o,Lm as s,Qi as c,Th as l,Tu as u,Y as d,av as f,ev as p,ib as m,iv as h,ki as g,ks as _,kv as v,np as y,nv as b,om as x,q as S,qC as C,rb as w,rp as T,rv as E,tv as D,wu as O,zi as k,zm as A}from"./loadAgentsDir-mcRW90aq.js";import{On as j,Wt as M,l as N}from"./state-BPFYBqm1.js";import{S as P,v as F}from"./git-CoQQ6YEf.js";import{i as I,t as L}from"./detectRepository-CMEkS5_2.js";import{a as R,n as z}from"./fileSuggestions-BalHmi1-.js";import{r as B,t as V}from"./magicDocs-26J_l1De.js";function H(e=new Set){let r=e.size>0;D.cache.clear?.(),p.cache.clear?.(),t.cache.clear?.(),h.cache.clear?.(),z(),g(),r||v(),E(null),j(null),A(),n(),m(`session_start`),y(),O(),import(`./attributionHooks-CUAoGkU6.js`).then(({clearAttributionCaches:e})=>e()),L(),S(),N(e),F(),o(),i(),V(),C(),import(`./SearchExtraToolsTool-Bq87I_vu.js`).then(({clearSearchExtraToolsDescriptionCache:e})=>e()),import(`./loadAgentsDir-4UC4yLg1.js`).then(({clearAgentDefinitionsCache:e})=>e()),import(`./prompt-DV5tCLRh.js`).then(({clearPromptCache:e})=>e())}var U=e((()=>{M(),k(),f(),b(),R(),x(),r(),u(),s(),l(),B(),c(),_(),d(),w(),I(),P(),T(),a()}));export{U as n,H as t};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./caches-C5DIVdvI.js";e();export{t as clearSessionCaches};
@@ -1 +1 @@
1
- import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,F as r,P as i,R as a,c as o,i as s,x as c}from"./debug-Dr1SjdXn.js";import{O as l,k as u}from"./git-CoQQ6YEf.js";import{_n as d,vn as f}from"./model-CDnVaVDR.js";import{l as p,r as m}from"./proxy-BEKNaTXI.js";import{n as h,t as g}from"./userAgent-B7WkjI6I.js";import{A as _,O as v,f as y,g as b,k as x,u as S}from"./sessionState-DSWN4tMV.js";import{n as C}from"./jwtUtils-FQWtM6iM.js";import{randomUUID as w}from"crypto";a(),s(),l(),p(),h(),d(),_(),S(),c(),e();var T=class extends Error{constructor(e,n){super(e),t(this,`retryAfterMs`,void 0),this.retryAfterMs=n}},E=class{constructor(e){t(this,`pending`,[]),t(this,`pendingAtClose`,0),t(this,`draining`,!1),t(this,`closed`,!1),t(this,`backpressureResolvers`,[]),t(this,`sleepResolve`,null),t(this,`flushResolvers`,[]),t(this,`droppedBatches`,0),t(this,`config`,void 0),this.config=e}get droppedBatchCount(){return this.droppedBatches}get pendingCount(){return this.closed?this.pendingAtClose:this.pending.length}async enqueue(e){if(this.closed)return;let t=Array.isArray(e)?e:[e];if(t.length!==0){for(;this.pending.length+t.length>this.config.maxQueueSize&&!this.closed;)await new Promise(e=>{this.backpressureResolvers.push(e)});this.closed||(this.pending.push(...t),this.drain())}}flush(){return this.pending.length===0&&!this.draining?Promise.resolve():(this.drain(),new Promise(e=>{this.flushResolvers.push(e)}))}close(){if(!this.closed){this.closed=!0,this.pendingAtClose=this.pending.length,this.pending=[],this.sleepResolve?.(),this.sleepResolve=null;for(let e of this.backpressureResolvers)e();this.backpressureResolvers=[];for(let e of this.flushResolvers)e();this.flushResolvers=[]}}async drain(){if(this.draining||this.closed)return;this.draining=!0;let e=0;try{for(;this.pending.length>0&&!this.closed;){let t=this.takeBatch();if(t.length!==0){try{await this.config.send(t),e=0}catch(n){if(e++,this.config.maxConsecutiveFailures!==void 0&&e>=this.config.maxConsecutiveFailures){this.droppedBatches++,this.config.onBatchDropped?.(t.length,e),e=0,this.releaseBackpressure();continue}this.pending=t.concat(this.pending);let r=n instanceof T?n.retryAfterMs:void 0;await this.sleep(this.retryDelay(e,r));continue}this.releaseBackpressure()}}}finally{if(this.draining=!1,this.pending.length===0){for(let e of this.flushResolvers)e();this.flushResolvers=[]}}}takeBatch(){let{maxBatchSize:e,maxBatchBytes:t}=this.config;if(t===void 0)return this.pending.splice(0,e);let r=0,i=0;for(;i<this.pending.length&&i<e;){let e;try{e=Buffer.byteLength(n(this.pending[i]))}catch{this.pending.splice(i,1);continue}if(i>0&&r+e>t)break;r+=e,i++}return this.pending.splice(0,i)}retryDelay(e,t){let n=Math.random()*this.config.jitterMs;return t===void 0?Math.min(this.config.baseDelayMs*2**(e-1),this.config.maxDelayMs)+n:Math.max(this.config.baseDelayMs,Math.min(t,this.config.maxDelayMs))+n}releaseBackpressure(){let e=this.backpressureResolvers;this.backpressureResolvers=[];for(let t of e)t()}sleep(e){return new Promise(t=>{this.sleepResolve=t,setTimeout((e,t)=>{e.sleepResolve=null,t()},e,this,t)})}};e();var D=class{constructor(e){t(this,`inflight`,null),t(this,`pending`,null),t(this,`closed`,!1),t(this,`config`,void 0),this.config=e}enqueue(e){this.closed||(this.pending=this.pending?O(this.pending,e):e,this.drain())}close(){this.closed=!0,this.pending=null}async drain(){if(this.inflight||this.closed||!this.pending)return;let e=this.pending;this.pending=null,this.inflight=this.sendWithRetry(e).then(()=>{this.inflight=null,this.pending&&!this.closed&&this.drain()})}async sendWithRetry(e){let t=e,n=0;for(;!this.closed;){if(await this.config.send(t))return;n++,await f(this.retryDelay(n)),this.pending&&!this.closed&&(t=O(t,this.pending),this.pending=null)}}retryDelay(e){return Math.min(this.config.baseDelayMs*2**(e-1),this.config.maxDelayMs)+Math.random()*this.config.jitterMs}};function O(e,t){let n={...e};for(let[e,r]of Object.entries(t))(e===`external_metadata`||e===`internal_metadata`)&&n[e]&&typeof n[e]==`object`&&typeof r==`object`&&r?n[e]={...n[e],...r}:n[e]=r;return n}d(),e();var k=2e4,A=100;function j(){return!0}var M=class extends Error{constructor(e){super(`CCRClient init failed: ${e}`),t(this,`reason`,void 0),this.reason=e}},N=10;function P(){return{byMessage:new Map,scopeToMessage:new Map}}function F(e){return`${e.session_id}:${e.parent_tool_use_id??``}`}function I(e,t){let n=[],r=new Map;for(let i of e){let e=i.event;switch(e.type){case`message_start`:{let r=e.message.id,a=t.scopeToMessage.get(F(i));a&&t.byMessage.delete(a),t.scopeToMessage.set(F(i),r),t.byMessage.set(r,[]),n.push(i);break}case`content_block_delta`:{let a=e.delta;if(a.type!==`text_delta`){n.push(i);break}let o=t.scopeToMessage.get(F(i)),s=o?t.byMessage.get(o):void 0;if(!s){n.push(i);break}let c=e.index,l=s[c]??(s[c]=[]);l.push(a.text);let u=r.get(l);if(u){u.event.delta={type:`text_delta`,text:l.join(``)};break}let d={type:`stream_event`,uuid:i.uuid,session_id:i.session_id,parent_tool_use_id:i.parent_tool_use_id,event:{type:`content_block_delta`,index:c,delta:{type:`text_delta`,text:l.join(``)}}};r.set(l,d),n.push(d);break}default:n.push(i)}}return n}function L(e,t){e.byMessage.delete(t.message.id);let n=F(t);e.scopeToMessage.get(n)===t.message.id&&e.scopeToMessage.delete(n)}var R=class{constructor(e,n,r){if(t(this,`workerEpoch`,0),t(this,`heartbeatIntervalMs`,void 0),t(this,`heartbeatJitterFraction`,void 0),t(this,`heartbeatTimer`,null),t(this,`heartbeatInFlight`,!1),t(this,`closed`,!1),t(this,`consecutiveAuthFailures`,0),t(this,`currentState`,null),t(this,`sessionBaseUrl`,void 0),t(this,`sessionId`,void 0),t(this,`http`,m({keepAlive:!0})),t(this,`streamEventBuffer`,[]),t(this,`streamEventTimer`,null),t(this,`streamTextAccumulator`,P()),t(this,`workerState`,void 0),t(this,`eventUploader`,void 0),t(this,`internalEventUploader`,void 0),t(this,`deliveryUploader`,void 0),t(this,`onEpochMismatch`,void 0),t(this,`getAuthHeaders`,void 0),this.onEpochMismatch=r?.onEpochMismatch??(()=>{process.exit(1)}),this.heartbeatIntervalMs=r?.heartbeatIntervalMs??k,this.heartbeatJitterFraction=r?.heartbeatJitterFraction??0,this.getAuthHeaders=r?.getAuthHeaders??v,n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`CCRClient: Expected http(s) URL, got ${n.protocol}`);let i=n.pathname.replace(/\/$/,``);this.sessionBaseUrl=`${n.protocol}//${n.host}${i}`,this.sessionId=i.split(`/`).pop()||``,this.workerState=new D({send:e=>this.request(`put`,`/worker`,{worker_epoch:this.workerEpoch,...e},`PUT worker`).then(e=>e.ok),baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.eventUploader=new E({maxBatchSize:100,maxBatchBytes:10*1024*1024,maxQueueSize:1e5,send:async e=>{let t=await this.request(`post`,`/worker/events`,{worker_epoch:this.workerEpoch,events:e},`client events`);if(!t.ok)throw new T(`client event POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.internalEventUploader=new E({maxBatchSize:100,maxBatchBytes:10*1024*1024,maxQueueSize:200,send:async e=>{let t=await this.request(`post`,`/worker/internal-events`,{worker_epoch:this.workerEpoch,events:e},`internal events`);if(!t.ok)throw new T(`internal event POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.deliveryUploader=new E({maxBatchSize:64,maxQueueSize:64,send:async e=>{let t=await this.request(`post`,`/worker/events/delivery`,{worker_epoch:this.workerEpoch,updates:e.map(e=>({event_id:e.eventId,status:e.status}))},`delivery batch`);if(!t.ok)throw new T(`delivery POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),e.setOnEvent(e=>{this.reportDelivery(e.event_id,`received`)})}async initialize(e){let t=Date.now();if(Object.keys(this.getAuthHeaders()).length===0)throw new M(`no_auth_headers`);if(e===void 0){let t=process.env.CLAUDE_CODE_WORKER_EPOCH;e=t?parseInt(t,10):NaN}if(isNaN(e))throw new M(`missing_epoch`);this.workerEpoch=e;let n=this.getWorkerState();if(!(await this.request(`put`,`/worker`,{worker_status:`idle`,worker_epoch:this.workerEpoch,external_metadata:{pending_action:null,task_summary:null,automation_state:null}},`PUT worker (init)`)).ok)throw new M(`worker_register_failed`);this.currentState=`idle`,this.startHeartbeat(),y(()=>{this.writeEvent({type:`keep_alive`})}),o(`CCRClient: initialized, epoch=${this.workerEpoch}`),u(`info`,`cli_worker_lifecycle_initialized`,{epoch:this.workerEpoch,duration_ms:Date.now()-t});let{metadata:r,durationMs:i}=await n;return this.closed||u(`info`,`cli_worker_state_restored`,{duration_ms:i,had_state:r!==null}),r}async getWorkerState(){let e=Date.now(),t=this.getAuthHeaders();return Object.keys(t).length===0?{metadata:null,durationMs:0}:{metadata:(await this.getWithRetry(`${this.sessionBaseUrl}/worker`,t,`worker_state`))?.worker?.external_metadata??null,durationMs:Date.now()-e}}async request(e,t,n,a,{timeout:s=1e4}={}){let c=this.getAuthHeaders();if(Object.keys(c).length===0)return{ok:!1};try{let r=await this.http[e](`${this.sessionBaseUrl}${t}`,n,{headers:{...c,"Content-Type":`application/json`,"anthropic-version":`2023-06-01`,"User-Agent":g()},validateStatus:j,timeout:s});if(r.status>=200&&r.status<300)return this.consecutiveAuthFailures=0,{ok:!0};if(r.status===409&&this.handleEpochMismatch(),r.status===401||r.status===403){let e=x(),t=e?C(e):null;t!==null&&t*1e3<Date.now()&&(o(`CCRClient: session_token expired (exp=${new Date(t*1e3).toISOString()}) — no refresh was delivered, exiting`,{level:`error`}),u(`error`,`cli_worker_token_expired_no_refresh`),this.onEpochMismatch()),this.consecutiveAuthFailures++,this.consecutiveAuthFailures>=N&&(o(`CCRClient: ${this.consecutiveAuthFailures} consecutive auth failures with a valid-looking token — server-side auth unrecoverable, exiting`,{level:`error`}),u(`error`,`cli_worker_auth_failures_exhausted`),this.onEpochMismatch())}if(o(`CCRClient: ${a} returned ${r.status}`,{level:`warn`}),u(`warn`,`cli_worker_request_failed`,{method:e,path:t,status:r.status}),r.status===429){let e=r.headers?.[`retry-after`],t=typeof e==`string`?parseInt(e,10):NaN;if(!isNaN(t)&&t>=0)return{ok:!1,retryAfterMs:t*1e3}}return{ok:!1}}catch(n){return o(`CCRClient: ${a} failed: ${i(n)}`,{level:`warn`}),u(`warn`,`cli_worker_request_error`,{method:e,path:t,error_code:r(n)}),{ok:!1}}}reportState(e,t){e===this.currentState&&!t||(this.currentState=e,this.workerState.enqueue({worker_status:e,requires_action_details:t?{tool_name:t.tool_name,action_description:t.action_description,request_id:t.request_id}:null}))}reportMetadata(e){this.workerState.enqueue({external_metadata:e})}handleEpochMismatch(){o(`CCRClient: Epoch mismatch (409), shutting down`,{level:`error`}),u(`error`,`cli_worker_epoch_mismatch`),this.onEpochMismatch()}startHeartbeat(){this.stopHeartbeat();let e=()=>{let e=this.heartbeatIntervalMs*this.heartbeatJitterFraction*(2*Math.random()-1);this.heartbeatTimer=setTimeout(t,this.heartbeatIntervalMs+e)},t=()=>{this.sendHeartbeat(),this.heartbeatTimer!==null&&e()};e()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null)}async sendHeartbeat(){if(!this.heartbeatInFlight){this.heartbeatInFlight=!0;try{(await this.request(`post`,`/worker/heartbeat`,{session_id:this.sessionId,worker_epoch:this.workerEpoch},`Heartbeat`,{timeout:5e3})).ok&&o(`CCRClient: Heartbeat sent`)}finally{this.heartbeatInFlight=!1}}}async writeEvent(e){if(e.type===`stream_event`){this.streamEventBuffer.push(e),this.streamEventTimer||(this.streamEventTimer=setTimeout(()=>void this.flushStreamEventBuffer(),A));return}await this.flushStreamEventBuffer(),e.type===`assistant`&&L(this.streamTextAccumulator,e),await this.eventUploader.enqueue(this.toClientEvent(e))}toClientEvent(e){let t=e;return{payload:{...t,uuid:typeof t.uuid==`string`?t.uuid:w()}}}async flushStreamEventBuffer(){if(this.streamEventTimer&&(clearTimeout(this.streamEventTimer),this.streamEventTimer=null),this.streamEventBuffer.length===0)return;let e=this.streamEventBuffer;this.streamEventBuffer=[];let t=I(e,this.streamTextAccumulator);await this.eventUploader.enqueue(t.map(e=>({payload:e,ephemeral:!0})))}async writeInternalEvent(e,t,{isCompaction:n=!1,agentId:r}={}){let i={payload:{type:e,...t,uuid:typeof t.uuid==`string`?t.uuid:w()},...n&&{is_compaction:!0},...r&&{agent_id:r}};await this.internalEventUploader.enqueue(i)}flushInternalEvents(){return this.internalEventUploader.flush()}async flush(){return await this.flushStreamEventBuffer(),this.eventUploader.flush()}async readInternalEvents(){return this.paginatedGet(`/worker/internal-events`,{},`internal_events`)}async readSubagentInternalEvents(){return this.paginatedGet(`/worker/internal-events`,{subagents:`true`},`subagent_events`)}async paginatedGet(e,t,n){let r=this.getAuthHeaders();if(Object.keys(r).length===0)return null;let i=[],a;do{let o=new URL(`${this.sessionBaseUrl}${e}`);for(let[e,n]of Object.entries(t))o.searchParams.set(e,n);a&&o.searchParams.set(`cursor`,a);let s=await this.getWithRetry(o.toString(),r,n);if(!s)return null;i.push(...s.data??[]),a=s.next_cursor}while(a);return o(`CCRClient: Read ${i.length} internal events from ${e}${t.subagents?` (subagents)`:``}`),i}async getWithRetry(e,t,n){for(let n=1;n<=10;n++){let r;try{r=await this.http.get(e,{headers:{...t,"anthropic-version":`2023-06-01`,"User-Agent":g()},validateStatus:j,timeout:3e4})}catch(t){o(`CCRClient: GET ${e} failed (attempt ${n}/10): ${i(t)}`,{level:`warn`}),n<10&&await f(Math.min(500*2**(n-1),3e4)+Math.random()*500);continue}if(r.status>=200&&r.status<300)return r.data;r.status===409&&this.handleEpochMismatch(),o(`CCRClient: GET ${e} returned ${r.status} (attempt ${n}/10)`,{level:`warn`}),n<10&&await f(Math.min(500*2**(n-1),3e4)+Math.random()*500)}return o(`CCRClient: GET retries exhausted`,{level:`error`}),u(`error`,`cli_worker_get_retries_exhausted`,{context:n}),null}reportDelivery(e,t){this.deliveryUploader.enqueue({eventId:e,status:t})}getWorkerEpoch(){return this.workerEpoch}get internalEventsPending(){return this.internalEventUploader.pendingCount}close(){this.closed=!0,this.stopHeartbeat(),b(),this.streamEventTimer&&(clearTimeout(this.streamEventTimer),this.streamEventTimer=null),this.streamEventBuffer=[],this.streamTextAccumulator.byMessage.clear(),this.streamTextAccumulator.scopeToMessage.clear(),this.workerState.close(),this.eventUploader.close(),this.internalEventUploader.close(),this.deliveryUploader.close()}};export{M as n,E as r,R as t};
1
+ import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,F as r,P as i,R as a,c as o,i as s,x as c}from"./debug-Dr1SjdXn.js";import{O as l,k as u}from"./git-CoQQ6YEf.js";import{_n as d,vn as f}from"./model-C29_32BD.js";import{l as p,r as m}from"./proxy-BEKNaTXI.js";import{n as h,t as g}from"./userAgent-DUrr02yh.js";import{A as _,O as v,f as y,g as b,k as x,u as S}from"./sessionState-Bn3ESS5f.js";import{n as C}from"./jwtUtils-FQWtM6iM.js";import{randomUUID as w}from"crypto";a(),s(),l(),p(),h(),d(),_(),S(),c(),e();var T=class extends Error{constructor(e,n){super(e),t(this,`retryAfterMs`,void 0),this.retryAfterMs=n}},E=class{constructor(e){t(this,`pending`,[]),t(this,`pendingAtClose`,0),t(this,`draining`,!1),t(this,`closed`,!1),t(this,`backpressureResolvers`,[]),t(this,`sleepResolve`,null),t(this,`flushResolvers`,[]),t(this,`droppedBatches`,0),t(this,`config`,void 0),this.config=e}get droppedBatchCount(){return this.droppedBatches}get pendingCount(){return this.closed?this.pendingAtClose:this.pending.length}async enqueue(e){if(this.closed)return;let t=Array.isArray(e)?e:[e];if(t.length!==0){for(;this.pending.length+t.length>this.config.maxQueueSize&&!this.closed;)await new Promise(e=>{this.backpressureResolvers.push(e)});this.closed||(this.pending.push(...t),this.drain())}}flush(){return this.pending.length===0&&!this.draining?Promise.resolve():(this.drain(),new Promise(e=>{this.flushResolvers.push(e)}))}close(){if(!this.closed){this.closed=!0,this.pendingAtClose=this.pending.length,this.pending=[],this.sleepResolve?.(),this.sleepResolve=null;for(let e of this.backpressureResolvers)e();this.backpressureResolvers=[];for(let e of this.flushResolvers)e();this.flushResolvers=[]}}async drain(){if(this.draining||this.closed)return;this.draining=!0;let e=0;try{for(;this.pending.length>0&&!this.closed;){let t=this.takeBatch();if(t.length!==0){try{await this.config.send(t),e=0}catch(n){if(e++,this.config.maxConsecutiveFailures!==void 0&&e>=this.config.maxConsecutiveFailures){this.droppedBatches++,this.config.onBatchDropped?.(t.length,e),e=0,this.releaseBackpressure();continue}this.pending=t.concat(this.pending);let r=n instanceof T?n.retryAfterMs:void 0;await this.sleep(this.retryDelay(e,r));continue}this.releaseBackpressure()}}}finally{if(this.draining=!1,this.pending.length===0){for(let e of this.flushResolvers)e();this.flushResolvers=[]}}}takeBatch(){let{maxBatchSize:e,maxBatchBytes:t}=this.config;if(t===void 0)return this.pending.splice(0,e);let r=0,i=0;for(;i<this.pending.length&&i<e;){let e;try{e=Buffer.byteLength(n(this.pending[i]))}catch{this.pending.splice(i,1);continue}if(i>0&&r+e>t)break;r+=e,i++}return this.pending.splice(0,i)}retryDelay(e,t){let n=Math.random()*this.config.jitterMs;return t===void 0?Math.min(this.config.baseDelayMs*2**(e-1),this.config.maxDelayMs)+n:Math.max(this.config.baseDelayMs,Math.min(t,this.config.maxDelayMs))+n}releaseBackpressure(){let e=this.backpressureResolvers;this.backpressureResolvers=[];for(let t of e)t()}sleep(e){return new Promise(t=>{this.sleepResolve=t,setTimeout((e,t)=>{e.sleepResolve=null,t()},e,this,t)})}};e();var D=class{constructor(e){t(this,`inflight`,null),t(this,`pending`,null),t(this,`closed`,!1),t(this,`config`,void 0),this.config=e}enqueue(e){this.closed||(this.pending=this.pending?O(this.pending,e):e,this.drain())}close(){this.closed=!0,this.pending=null}async drain(){if(this.inflight||this.closed||!this.pending)return;let e=this.pending;this.pending=null,this.inflight=this.sendWithRetry(e).then(()=>{this.inflight=null,this.pending&&!this.closed&&this.drain()})}async sendWithRetry(e){let t=e,n=0;for(;!this.closed;){if(await this.config.send(t))return;n++,await f(this.retryDelay(n)),this.pending&&!this.closed&&(t=O(t,this.pending),this.pending=null)}}retryDelay(e){return Math.min(this.config.baseDelayMs*2**(e-1),this.config.maxDelayMs)+Math.random()*this.config.jitterMs}};function O(e,t){let n={...e};for(let[e,r]of Object.entries(t))(e===`external_metadata`||e===`internal_metadata`)&&n[e]&&typeof n[e]==`object`&&typeof r==`object`&&r?n[e]={...n[e],...r}:n[e]=r;return n}d(),e();var k=2e4,A=100;function j(){return!0}var M=class extends Error{constructor(e){super(`CCRClient init failed: ${e}`),t(this,`reason`,void 0),this.reason=e}},N=10;function P(){return{byMessage:new Map,scopeToMessage:new Map}}function F(e){return`${e.session_id}:${e.parent_tool_use_id??``}`}function I(e,t){let n=[],r=new Map;for(let i of e){let e=i.event;switch(e.type){case`message_start`:{let r=e.message.id,a=t.scopeToMessage.get(F(i));a&&t.byMessage.delete(a),t.scopeToMessage.set(F(i),r),t.byMessage.set(r,[]),n.push(i);break}case`content_block_delta`:{let a=e.delta;if(a.type!==`text_delta`){n.push(i);break}let o=t.scopeToMessage.get(F(i)),s=o?t.byMessage.get(o):void 0;if(!s){n.push(i);break}let c=e.index,l=s[c]??(s[c]=[]);l.push(a.text);let u=r.get(l);if(u){u.event.delta={type:`text_delta`,text:l.join(``)};break}let d={type:`stream_event`,uuid:i.uuid,session_id:i.session_id,parent_tool_use_id:i.parent_tool_use_id,event:{type:`content_block_delta`,index:c,delta:{type:`text_delta`,text:l.join(``)}}};r.set(l,d),n.push(d);break}default:n.push(i)}}return n}function L(e,t){e.byMessage.delete(t.message.id);let n=F(t);e.scopeToMessage.get(n)===t.message.id&&e.scopeToMessage.delete(n)}var R=class{constructor(e,n,r){if(t(this,`workerEpoch`,0),t(this,`heartbeatIntervalMs`,void 0),t(this,`heartbeatJitterFraction`,void 0),t(this,`heartbeatTimer`,null),t(this,`heartbeatInFlight`,!1),t(this,`closed`,!1),t(this,`consecutiveAuthFailures`,0),t(this,`currentState`,null),t(this,`sessionBaseUrl`,void 0),t(this,`sessionId`,void 0),t(this,`http`,m({keepAlive:!0})),t(this,`streamEventBuffer`,[]),t(this,`streamEventTimer`,null),t(this,`streamTextAccumulator`,P()),t(this,`workerState`,void 0),t(this,`eventUploader`,void 0),t(this,`internalEventUploader`,void 0),t(this,`deliveryUploader`,void 0),t(this,`onEpochMismatch`,void 0),t(this,`getAuthHeaders`,void 0),this.onEpochMismatch=r?.onEpochMismatch??(()=>{process.exit(1)}),this.heartbeatIntervalMs=r?.heartbeatIntervalMs??k,this.heartbeatJitterFraction=r?.heartbeatJitterFraction??0,this.getAuthHeaders=r?.getAuthHeaders??v,n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`CCRClient: Expected http(s) URL, got ${n.protocol}`);let i=n.pathname.replace(/\/$/,``);this.sessionBaseUrl=`${n.protocol}//${n.host}${i}`,this.sessionId=i.split(`/`).pop()||``,this.workerState=new D({send:e=>this.request(`put`,`/worker`,{worker_epoch:this.workerEpoch,...e},`PUT worker`).then(e=>e.ok),baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.eventUploader=new E({maxBatchSize:100,maxBatchBytes:10*1024*1024,maxQueueSize:1e5,send:async e=>{let t=await this.request(`post`,`/worker/events`,{worker_epoch:this.workerEpoch,events:e},`client events`);if(!t.ok)throw new T(`client event POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.internalEventUploader=new E({maxBatchSize:100,maxBatchBytes:10*1024*1024,maxQueueSize:200,send:async e=>{let t=await this.request(`post`,`/worker/internal-events`,{worker_epoch:this.workerEpoch,events:e},`internal events`);if(!t.ok)throw new T(`internal event POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),this.deliveryUploader=new E({maxBatchSize:64,maxQueueSize:64,send:async e=>{let t=await this.request(`post`,`/worker/events/delivery`,{worker_epoch:this.workerEpoch,updates:e.map(e=>({event_id:e.eventId,status:e.status}))},`delivery batch`);if(!t.ok)throw new T(`delivery POST failed`,t.retryAfterMs)},baseDelayMs:500,maxDelayMs:3e4,jitterMs:500}),e.setOnEvent(e=>{this.reportDelivery(e.event_id,`received`)})}async initialize(e){let t=Date.now();if(Object.keys(this.getAuthHeaders()).length===0)throw new M(`no_auth_headers`);if(e===void 0){let t=process.env.CLAUDE_CODE_WORKER_EPOCH;e=t?parseInt(t,10):NaN}if(isNaN(e))throw new M(`missing_epoch`);this.workerEpoch=e;let n=this.getWorkerState();if(!(await this.request(`put`,`/worker`,{worker_status:`idle`,worker_epoch:this.workerEpoch,external_metadata:{pending_action:null,task_summary:null,automation_state:null}},`PUT worker (init)`)).ok)throw new M(`worker_register_failed`);this.currentState=`idle`,this.startHeartbeat(),y(()=>{this.writeEvent({type:`keep_alive`})}),o(`CCRClient: initialized, epoch=${this.workerEpoch}`),u(`info`,`cli_worker_lifecycle_initialized`,{epoch:this.workerEpoch,duration_ms:Date.now()-t});let{metadata:r,durationMs:i}=await n;return this.closed||u(`info`,`cli_worker_state_restored`,{duration_ms:i,had_state:r!==null}),r}async getWorkerState(){let e=Date.now(),t=this.getAuthHeaders();return Object.keys(t).length===0?{metadata:null,durationMs:0}:{metadata:(await this.getWithRetry(`${this.sessionBaseUrl}/worker`,t,`worker_state`))?.worker?.external_metadata??null,durationMs:Date.now()-e}}async request(e,t,n,a,{timeout:s=1e4}={}){let c=this.getAuthHeaders();if(Object.keys(c).length===0)return{ok:!1};try{let r=await this.http[e](`${this.sessionBaseUrl}${t}`,n,{headers:{...c,"Content-Type":`application/json`,"anthropic-version":`2023-06-01`,"User-Agent":g()},validateStatus:j,timeout:s});if(r.status>=200&&r.status<300)return this.consecutiveAuthFailures=0,{ok:!0};if(r.status===409&&this.handleEpochMismatch(),r.status===401||r.status===403){let e=x(),t=e?C(e):null;t!==null&&t*1e3<Date.now()&&(o(`CCRClient: session_token expired (exp=${new Date(t*1e3).toISOString()}) — no refresh was delivered, exiting`,{level:`error`}),u(`error`,`cli_worker_token_expired_no_refresh`),this.onEpochMismatch()),this.consecutiveAuthFailures++,this.consecutiveAuthFailures>=N&&(o(`CCRClient: ${this.consecutiveAuthFailures} consecutive auth failures with a valid-looking token — server-side auth unrecoverable, exiting`,{level:`error`}),u(`error`,`cli_worker_auth_failures_exhausted`),this.onEpochMismatch())}if(o(`CCRClient: ${a} returned ${r.status}`,{level:`warn`}),u(`warn`,`cli_worker_request_failed`,{method:e,path:t,status:r.status}),r.status===429){let e=r.headers?.[`retry-after`],t=typeof e==`string`?parseInt(e,10):NaN;if(!isNaN(t)&&t>=0)return{ok:!1,retryAfterMs:t*1e3}}return{ok:!1}}catch(n){return o(`CCRClient: ${a} failed: ${i(n)}`,{level:`warn`}),u(`warn`,`cli_worker_request_error`,{method:e,path:t,error_code:r(n)}),{ok:!1}}}reportState(e,t){e===this.currentState&&!t||(this.currentState=e,this.workerState.enqueue({worker_status:e,requires_action_details:t?{tool_name:t.tool_name,action_description:t.action_description,request_id:t.request_id}:null}))}reportMetadata(e){this.workerState.enqueue({external_metadata:e})}handleEpochMismatch(){o(`CCRClient: Epoch mismatch (409), shutting down`,{level:`error`}),u(`error`,`cli_worker_epoch_mismatch`),this.onEpochMismatch()}startHeartbeat(){this.stopHeartbeat();let e=()=>{let e=this.heartbeatIntervalMs*this.heartbeatJitterFraction*(2*Math.random()-1);this.heartbeatTimer=setTimeout(t,this.heartbeatIntervalMs+e)},t=()=>{this.sendHeartbeat(),this.heartbeatTimer!==null&&e()};e()}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null)}async sendHeartbeat(){if(!this.heartbeatInFlight){this.heartbeatInFlight=!0;try{(await this.request(`post`,`/worker/heartbeat`,{session_id:this.sessionId,worker_epoch:this.workerEpoch},`Heartbeat`,{timeout:5e3})).ok&&o(`CCRClient: Heartbeat sent`)}finally{this.heartbeatInFlight=!1}}}async writeEvent(e){if(e.type===`stream_event`){this.streamEventBuffer.push(e),this.streamEventTimer||(this.streamEventTimer=setTimeout(()=>void this.flushStreamEventBuffer(),A));return}await this.flushStreamEventBuffer(),e.type===`assistant`&&L(this.streamTextAccumulator,e),await this.eventUploader.enqueue(this.toClientEvent(e))}toClientEvent(e){let t=e;return{payload:{...t,uuid:typeof t.uuid==`string`?t.uuid:w()}}}async flushStreamEventBuffer(){if(this.streamEventTimer&&(clearTimeout(this.streamEventTimer),this.streamEventTimer=null),this.streamEventBuffer.length===0)return;let e=this.streamEventBuffer;this.streamEventBuffer=[];let t=I(e,this.streamTextAccumulator);await this.eventUploader.enqueue(t.map(e=>({payload:e,ephemeral:!0})))}async writeInternalEvent(e,t,{isCompaction:n=!1,agentId:r}={}){let i={payload:{type:e,...t,uuid:typeof t.uuid==`string`?t.uuid:w()},...n&&{is_compaction:!0},...r&&{agent_id:r}};await this.internalEventUploader.enqueue(i)}flushInternalEvents(){return this.internalEventUploader.flush()}async flush(){return await this.flushStreamEventBuffer(),this.eventUploader.flush()}async readInternalEvents(){return this.paginatedGet(`/worker/internal-events`,{},`internal_events`)}async readSubagentInternalEvents(){return this.paginatedGet(`/worker/internal-events`,{subagents:`true`},`subagent_events`)}async paginatedGet(e,t,n){let r=this.getAuthHeaders();if(Object.keys(r).length===0)return null;let i=[],a;do{let o=new URL(`${this.sessionBaseUrl}${e}`);for(let[e,n]of Object.entries(t))o.searchParams.set(e,n);a&&o.searchParams.set(`cursor`,a);let s=await this.getWithRetry(o.toString(),r,n);if(!s)return null;i.push(...s.data??[]),a=s.next_cursor}while(a);return o(`CCRClient: Read ${i.length} internal events from ${e}${t.subagents?` (subagents)`:``}`),i}async getWithRetry(e,t,n){for(let n=1;n<=10;n++){let r;try{r=await this.http.get(e,{headers:{...t,"anthropic-version":`2023-06-01`,"User-Agent":g()},validateStatus:j,timeout:3e4})}catch(t){o(`CCRClient: GET ${e} failed (attempt ${n}/10): ${i(t)}`,{level:`warn`}),n<10&&await f(Math.min(500*2**(n-1),3e4)+Math.random()*500);continue}if(r.status>=200&&r.status<300)return r.data;r.status===409&&this.handleEpochMismatch(),o(`CCRClient: GET ${e} returned ${r.status} (attempt ${n}/10)`,{level:`warn`}),n<10&&await f(Math.min(500*2**(n-1),3e4)+Math.random()*500)}return o(`CCRClient: GET retries exhausted`,{level:`error`}),u(`error`,`cli_worker_get_retries_exhausted`,{context:n}),null}reportDelivery(e,t){this.deliveryUploader.enqueue({eventId:e,status:t})}getWorkerEpoch(){return this.workerEpoch}get internalEventsPending(){return this.internalEventUploader.pendingCount}close(){this.closed=!0,this.stopHeartbeat(),b(),this.streamEventTimer&&(clearTimeout(this.streamEventTimer),this.streamEventTimer=null),this.streamEventBuffer=[],this.streamTextAccumulator.byMessage.clear(),this.streamTextAccumulator.scopeToMessage.clear(),this.workerState.close(),this.eventUploader.close(),this.internalEventUploader.close(),this.deliveryUploader.close()}};export{M as n,E as r,R as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./conversation-DPI7VKBL.js";var r;e((()=>{t(),r=async(e,t)=>(await n(t),{type:`text`,value:``})}))();export{r as call};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./conversation-5zb5XkSA.js";var r;e((()=>{t(),r=async(e,t)=>(await n(t),{type:`text`,value:``})}))();export{r as call};
@@ -0,0 +1 @@
1
+ import{Fr as e,Pr as t}from"./model-C29_32BD.js";e();export{t as getOrganizationUUID};
@@ -0,0 +1 @@
1
+ import{Pi as e,ki as t,zi as n}from"./loadAgentsDir-mcRW90aq.js";n();export{t as clearCommandsCache,e as getCommands};
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{AC as t,Dv as n,Lm as r,Nm as i,Ov as a,Tv as o,X_ as s,Z_ as c,_n as l,bp as u,ct as d,dv as f,ev as p,f_ as m,g_ as h,h_ as g,jC as _,ja as v,jm as y,nv as b,ov as x,p_ as S,st as C,sv as w,tv as T,uv as E,xp as D,yv as O,za as k,zm as A}from"./loadAgentsDir-mcRW90aq.js";import{di as j,ui as M}from"./src-P_wYS_NJ2.js";import{Wt as N,qt as P}from"./state-BPFYBqm1.js";import{L as F,R as I}from"./debug-Dr1SjdXn.js";import{o as L,s as R}from"./log-27kCA_9u.js";function z(e,n){let r=u(`tip`),i=t(`app:toggleTranscript`,`Global`,`ctrl+o`),a=[...e.options.verbose?[]:[`(${i} to see full summary)`],...n?[n]:[],...r?[r]:[]];return M.dim(`Compacted `+a.join(`
2
+ `))}async function B(e,t){let n=e.getAppState(),r=await C(e.options.tools,e.options.mainLoopModel,Array.from(n.toolPermissionContext.additionalWorkingDirectories.keys()),e.options.mcpClients),i=s({mainThreadAgentDefinition:void 0,toolUseContext:e,customSystemPrompt:e.options.customSystemPrompt,defaultSystemPrompt:r,appendSystemPrompt:e.options.appendSystemPrompt}),[a,o]=await Promise.all([T(),p()]);return{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:e,forkContextMessages:t}}var V;e((()=>{j(),N(),d(),b(),_(),n(),h(),E(),x(),r(),y(),O(),I(),l(),L(),k(),D(),c(),V=async(e,t)=>{let{abortController:n}=t,{messages:r}=t;if(r=v(r),r.length===0)throw Error(`No messages to compact`);let s=e.trim();try{if(!s){let e=await i(r,t.agentId);if(e)return T.cache.clear?.(),A(),a(t.options.querySource??`compact`,t.agentId),P(),f(),{type:`compact`,compactionResult:e,displayText:z(t)}}let e=(await w(r,t)).messages,n=await g(e,t,await B(t,e),!1,s,!1);return o(void 0),f(),T.cache.clear?.(),A(),{type:`compact`,compactionResult:n,displayText:z(t,n.userDisplayMessage)}}catch(e){throw n.signal.aborted?Error(`Compaction canceled.`):F(e,`Not enough messages to compact. Send a few more messages first, then try again.`)?Error(S):F(e,`Compaction interrupted · This may be due to network issues — please try again.`)?Error(m):(R(e),Error(`Error during compaction: ${e}`))}}}))();export{V as call};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Settings-BKdLcyXe.js";var i,a;e((()=>{n(),i=t(),a=async(e,t)=>(0,i.jsx)(r,{onClose:e,context:t,defaultTab:`Config`})}))();export{a as call};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./figures-5ThXQEtq.js";import{$_ as r,Ba as i,Ma as a,Z_ as o,dv as s,uv as c}from"./loadAgentsDir-BXtV2jiO.js";import{I as l,P as u,fi as d,s as f,t as p}from"./src-P_wYS_NJ2.js";import{t as m}from"./jsx-runtime-Bb4Xn-E0.js";import{cn as h,ln as g,wn as _,xn as v}from"./settings-DiBMs2gM.js";import{_ as y,v as b}from"./startupProfiler-Dc5r6LgE.js";import{Et as x,Zt as S,an as C,on as w,rn as T,wt as E}from"./prompt-CRc2QEZ5.js";import{n as D,t as O}from"./staticRender-DrU6eWoq.js";function k(e){let t=[];return A(e,t),j(e,t),N(e,t),P(e,t),F(e,t),t.sort((e,t)=>e.severity===t.severity?(t.savingsTokens??0)-(e.savingsTokens??0):e.severity===`warning`?-1:1),t}function A(e,t){e.percentage>=z&&t.push({severity:`warning`,title:`Context is ${e.percentage}% full`,detail:e.isAutoCompactEnabled?`Autocompact will trigger soon, which discards older messages. Use /compact now to control what gets kept.`:`Autocompact is disabled. Use /compact to free space, or enable autocompact in /config.`})}function j(e,t){if(e.messageBreakdown)for(let n of e.messageBreakdown.toolCallsByType){let r=n.callTokens+n.resultTokens,i=r/e.rawMaxTokens*100;if(i<I||r<L)continue;let a=M(n.name,r,i);a&&t.push(a)}}function M(e,t,n){let r=y(t);switch(e){case C:return{severity:`warning`,title:`Bash results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Pipe output through head, tail, or grep to reduce result size. Avoid cat on large files — use Read with offset/limit instead.`,savingsTokens:Math.floor(t*.5)};case S:return{severity:`info`,title:`Read results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Use offset and limit parameters to read only the sections you need. Avoid re-reading entire files when you only need a few lines.`,savingsTokens:Math.floor(t*.3)};case E:return{severity:`info`,title:`Grep results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Add more specific patterns or use the glob or type parameter to narrow file types. Consider Glob for file discovery instead of Grep.`,savingsTokens:Math.floor(t*.3)};default:return n>=20?{severity:`info`,title:`${e} using ${r} tokens (${n.toFixed(0)}%)`,detail:`This tool is consuming a significant portion of context.`,savingsTokens:Math.floor(t*.2)}:null}}function N(e,t){if(!e.messageBreakdown)return;let n=e.messageBreakdown.toolCallsByType.find(e=>e.name===S);if(!n)return;let r=n.callTokens+n.resultTokens,i=r/e.rawMaxTokens*100,a=n.resultTokens/e.rawMaxTokens*100;i>=I&&r>=L||a>=R&&n.resultTokens>=L&&t.push({severity:`info`,title:`File reads using ${y(n.resultTokens)} tokens (${a.toFixed(0)}%)`,detail:`If you are re-reading files, consider referencing earlier reads. Use offset/limit for large files.`,savingsTokens:Math.floor(n.resultTokens*.3)})}function P(e,t){let n=e.memoryFiles.reduce((e,t)=>e+t.tokens,0),r=n/e.rawMaxTokens*100;if(r>=B&&n>=V){let i=[...e.memoryFiles].sort((e,t)=>t.tokens-e.tokens).slice(0,3).map(e=>`${v(e.path)} (${y(e.tokens)})`).join(`, `);t.push({severity:`info`,title:`Memory files using ${y(n)} tokens (${r.toFixed(0)}%)`,detail:`Largest: ${i}. Use /memory to review and prune stale entries.`,savingsTokens:Math.floor(n*.3)})}}function F(e,t){!e.isAutoCompactEnabled&&e.percentage>=50&&e.percentage<z&&t.push({severity:`info`,title:`Autocompact is disabled`,detail:`Without autocompact, you will hit context limits and lose the conversation. Enable it in /config or use /compact manually.`})}var I,L,R,z,B,V,H=e((()=>{w(),T(),x(),_(),b(),I=15,L=1e4,R=5,z=80,B=5,V=5e3}));function U({suggestions:e}){return e.length===0?null:(0,W.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,W.jsx)(u,{bold:!0,children:`Suggestions`}),e.map((e,t)=>(0,W.jsxs)(l,{flexDirection:`column`,marginTop:t===0?0:1,children:[(0,W.jsxs)(l,{children:[(0,W.jsx)(f,{status:e.severity,withSpace:!0}),(0,W.jsx)(u,{bold:!0,children:e.title}),e.savingsTokens?(0,W.jsxs)(u,{dimColor:!0,children:[` `,n.arrowRight,` save ~`,y(e.savingsTokens)]}):null]}),(0,W.jsx)(l,{marginLeft:2,children:(0,W.jsx)(u,{dimColor:!0,children:e.detail})})]},t))]})}var W,G=e((()=>{t(),d(),p(),b(),W=m()}));function K(){return null}function q(e){let t=new Map;for(let n of e){let e=h(n.source),r=t.get(e)||[];r.push(n),t.set(e,r)}for(let[e,n]of t.entries())t.set(e,n.sort((e,t)=>t.tokens-e.tokens));let n=new Map;for(let e of Z){let r=t.get(e);r&&n.set(e,r)}return n}function J({data:e}){let{categories:t,totalTokens:n,rawMaxTokens:r,percentage:i,gridRows:a,model:o,memoryFiles:s,mcpTools:c,deferredBuiltinTools:d=[],agents:f,skills:p,cacheHitRate:m,cacheThreshold:h}=e,g=t.filter(e=>e.tokens>0&&e.name!==`Free space`&&e.name!==X&&!e.isDeferred),_=t.some(e=>e.isDeferred&&e.name.includes(`MCP`)),b=t.find(e=>e.name===X);return(0,Y.jsxs)(l,{flexDirection:`column`,paddingLeft:1,children:[(0,Y.jsx)(u,{bold:!0,children:`Context Usage`}),(0,Y.jsxs)(l,{flexDirection:`row`,gap:2,children:[(0,Y.jsx)(l,{flexDirection:`column`,flexShrink:0,children:a.map((e,t)=>(0,Y.jsx)(l,{flexDirection:`row`,marginLeft:-1,children:e.map((e,t)=>e.categoryName===`Free space`?(0,Y.jsx)(u,{dimColor:!0,children:`⛶ `},t):e.categoryName===X?(0,Y.jsx)(u,{color:e.color,children:`⛝ `},t):(0,Y.jsx)(u,{color:e.color,children:e.squareFullness>=.7?`⛁ `:`⛀ `},t))},t))}),(0,Y.jsxs)(l,{flexDirection:`column`,gap:0,flexShrink:0,children:[(0,Y.jsxs)(u,{dimColor:!0,children:[o,` · `,y(n),`/`,y(r),` tokens (`,i,`%)`]}),(0,Y.jsx)(K,{}),m!==void 0&&h!==void 0&&(0,Y.jsxs)(u,{color:m<h?`warning`:void 0,children:[`Cache hit rate: `,m.toFixed(0),`%`,m<h?` (below ${h}% threshold)`:``]}),(0,Y.jsx)(u,{children:` `}),(0,Y.jsx)(u,{dimColor:!0,italic:!0,children:`Estimated usage by category`}),g.map((e,t)=>{let n=y(e.tokens),i=e.isDeferred?`N/A`:`${(e.tokens/r*100).toFixed(1)}%`,a=e.name===X,o=e.name,s=e.isDeferred?` `:a?`⛝`:`⛁`;return(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{color:e.color,children:s}),(0,Y.jsxs)(u,{children:[` `,o,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[n,` tokens (`,i,`)`]})]},t)}),(t.find(e=>e.name===`Free space`)?.tokens??0)>0&&(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{dimColor:!0,children:`⛶`}),(0,Y.jsx)(u,{children:` Free space: `}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(t.find(e=>e.name===`Free space`)?.tokens||0),` (`,((t.find(e=>e.name===`Free space`)?.tokens||0)/r*100).toFixed(1),`%)`]})]}),b&&b.tokens>0&&(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{color:b.color,children:`⛝`}),(0,Y.jsxs)(u,{dimColor:!0,children:[` `,b.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(b.tokens),` tokens (`,(b.tokens/r*100).toFixed(1),`%)`]})]})]})]}),(0,Y.jsxs)(l,{flexDirection:`column`,marginLeft:-1,children:[c.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`MCP tools`}),(0,Y.jsxs)(u,{dimColor:!0,children:[` · /mcp`,_?` (loaded on-demand)`:``]})]}),c.some(e=>e.isLoaded)&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:`Loaded`}),c.filter(e=>e.isLoaded).map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),_&&c.some(e=>!e.isLoaded)&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:`Available`}),c.filter(e=>!e.isLoaded).map((e,t)=>(0,Y.jsx)(l,{children:(0,Y.jsxs)(u,{dimColor:!0,children:[`└ `,e.name]})},t))]}),!_&&c.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),f.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Custom agents`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /agents`})]}),Array.from(q(f).entries()).map(([e,t])=>(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:e}),t.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.agentType,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]},e))]}),s.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Memory files`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /memory`})]}),s.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,v(e.path),`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),p&&p.tokens>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Skills`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /skills`})]}),Array.from(q(p.skillFrontmatter).entries()).map(([e,t])=>(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:e}),t.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]},e))]})]}),(0,Y.jsx)(U,{suggestions:k(e)})]})}var Y,X,Z,Q=e((()=>{d(),p(),H(),_(),b(),g(),G(),Y=m(),X=`Autocompact buffer`,Z=[`Project`,`User`,`Managed`,`Plugin`,`Built-in`]}));function ee(e){return a(e)}async function te(e,t){let{messages:n,getAppState:r,options:{mainLoopModel:i,tools:a}}=t,c=ee(n),{messages:l}=await s(c),u=process.stdout.columns||80,d=r();return e(await D((0,$.jsx)(J,{data:await o(l,i,async()=>d.toolPermissionContext,a,d.agentDefinitions,u,t,void 0,c)}))),null}var $;e((()=>{d(),Q(),c(),r(),i(),O(),$=m()}))();export{te as call};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./figures-5ThXQEtq.js";import{Y_ as r,ja as i,ov as a,q_ as o,sv as s,za as c}from"./loadAgentsDir-mcRW90aq.js";import{I as l,P as u,fi as d,s as f,t as p}from"./src-P_wYS_NJ2.js";import{t as m}from"./jsx-runtime-Bb4Xn-E0.js";import{cn as h,ln as g,wn as _,xn as v}from"./settings-DiBMs2gM.js";import{_ as y,v as b}from"./startupProfiler-Dc5r6LgE.js";import{Et as x,Zt as S,an as C,on as w,rn as T,wt as E}from"./prompt-DIlq8NTy.js";import{n as D,t as O}from"./staticRender-DrU6eWoq.js";function k(e){let t=[];return A(e,t),j(e,t),N(e,t),P(e,t),F(e,t),t.sort((e,t)=>e.severity===t.severity?(t.savingsTokens??0)-(e.savingsTokens??0):e.severity===`warning`?-1:1),t}function A(e,t){e.percentage>=z&&t.push({severity:`warning`,title:`Context is ${e.percentage}% full`,detail:e.isAutoCompactEnabled?`Autocompact will trigger soon, which discards older messages. Use /compact now to control what gets kept.`:`Autocompact is disabled. Use /compact to free space, or enable autocompact in /config.`})}function j(e,t){if(e.messageBreakdown)for(let n of e.messageBreakdown.toolCallsByType){let r=n.callTokens+n.resultTokens,i=r/e.rawMaxTokens*100;if(i<I||r<L)continue;let a=M(n.name,r,i);a&&t.push(a)}}function M(e,t,n){let r=y(t);switch(e){case C:return{severity:`warning`,title:`Bash results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Pipe output through head, tail, or grep to reduce result size. Avoid cat on large files — use Read with offset/limit instead.`,savingsTokens:Math.floor(t*.5)};case S:return{severity:`info`,title:`Read results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Use offset and limit parameters to read only the sections you need. Avoid re-reading entire files when you only need a few lines.`,savingsTokens:Math.floor(t*.3)};case E:return{severity:`info`,title:`Grep results using ${r} tokens (${n.toFixed(0)}%)`,detail:`Add more specific patterns or use the glob or type parameter to narrow file types. Consider Glob for file discovery instead of Grep.`,savingsTokens:Math.floor(t*.3)};default:return n>=20?{severity:`info`,title:`${e} using ${r} tokens (${n.toFixed(0)}%)`,detail:`This tool is consuming a significant portion of context.`,savingsTokens:Math.floor(t*.2)}:null}}function N(e,t){if(!e.messageBreakdown)return;let n=e.messageBreakdown.toolCallsByType.find(e=>e.name===S);if(!n)return;let r=n.callTokens+n.resultTokens,i=r/e.rawMaxTokens*100,a=n.resultTokens/e.rawMaxTokens*100;i>=I&&r>=L||a>=R&&n.resultTokens>=L&&t.push({severity:`info`,title:`File reads using ${y(n.resultTokens)} tokens (${a.toFixed(0)}%)`,detail:`If you are re-reading files, consider referencing earlier reads. Use offset/limit for large files.`,savingsTokens:Math.floor(n.resultTokens*.3)})}function P(e,t){let n=e.memoryFiles.reduce((e,t)=>e+t.tokens,0),r=n/e.rawMaxTokens*100;if(r>=B&&n>=V){let i=[...e.memoryFiles].sort((e,t)=>t.tokens-e.tokens).slice(0,3).map(e=>`${v(e.path)} (${y(e.tokens)})`).join(`, `);t.push({severity:`info`,title:`Memory files using ${y(n)} tokens (${r.toFixed(0)}%)`,detail:`Largest: ${i}. Use /memory to review and prune stale entries.`,savingsTokens:Math.floor(n*.3)})}}function F(e,t){!e.isAutoCompactEnabled&&e.percentage>=50&&e.percentage<z&&t.push({severity:`info`,title:`Autocompact is disabled`,detail:`Without autocompact, you will hit context limits and lose the conversation. Enable it in /config or use /compact manually.`})}var I,L,R,z,B,V,H=e((()=>{w(),T(),x(),_(),b(),I=15,L=1e4,R=5,z=80,B=5,V=5e3}));function U({suggestions:e}){return e.length===0?null:(0,W.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,W.jsx)(u,{bold:!0,children:`Suggestions`}),e.map((e,t)=>(0,W.jsxs)(l,{flexDirection:`column`,marginTop:t===0?0:1,children:[(0,W.jsxs)(l,{children:[(0,W.jsx)(f,{status:e.severity,withSpace:!0}),(0,W.jsx)(u,{bold:!0,children:e.title}),e.savingsTokens?(0,W.jsxs)(u,{dimColor:!0,children:[` `,n.arrowRight,` save ~`,y(e.savingsTokens)]}):null]}),(0,W.jsx)(l,{marginLeft:2,children:(0,W.jsx)(u,{dimColor:!0,children:e.detail})})]},t))]})}var W,G=e((()=>{t(),d(),p(),b(),W=m()}));function K(){return null}function q(e){let t=new Map;for(let n of e){let e=h(n.source),r=t.get(e)||[];r.push(n),t.set(e,r)}for(let[e,n]of t.entries())t.set(e,n.sort((e,t)=>t.tokens-e.tokens));let n=new Map;for(let e of Z){let r=t.get(e);r&&n.set(e,r)}return n}function J({data:e}){let{categories:t,totalTokens:n,rawMaxTokens:r,percentage:i,gridRows:a,model:o,memoryFiles:s,mcpTools:c,deferredBuiltinTools:d=[],agents:f,skills:p,cacheHitRate:m,cacheThreshold:h}=e,g=t.filter(e=>e.tokens>0&&e.name!==`Free space`&&e.name!==X&&!e.isDeferred),_=t.some(e=>e.isDeferred&&e.name.includes(`MCP`)),b=t.find(e=>e.name===X);return(0,Y.jsxs)(l,{flexDirection:`column`,paddingLeft:1,children:[(0,Y.jsx)(u,{bold:!0,children:`Context Usage`}),(0,Y.jsxs)(l,{flexDirection:`row`,gap:2,children:[(0,Y.jsx)(l,{flexDirection:`column`,flexShrink:0,children:a.map((e,t)=>(0,Y.jsx)(l,{flexDirection:`row`,marginLeft:-1,children:e.map((e,t)=>e.categoryName===`Free space`?(0,Y.jsx)(u,{dimColor:!0,children:`⛶ `},t):e.categoryName===X?(0,Y.jsx)(u,{color:e.color,children:`⛝ `},t):(0,Y.jsx)(u,{color:e.color,children:e.squareFullness>=.7?`⛁ `:`⛀ `},t))},t))}),(0,Y.jsxs)(l,{flexDirection:`column`,gap:0,flexShrink:0,children:[(0,Y.jsxs)(u,{dimColor:!0,children:[o,` · `,y(n),`/`,y(r),` tokens (`,i,`%)`]}),(0,Y.jsx)(K,{}),m!==void 0&&h!==void 0&&(0,Y.jsxs)(u,{color:m<h?`warning`:void 0,children:[`Cache hit rate: `,m.toFixed(0),`%`,m<h?` (below ${h}% threshold)`:``]}),(0,Y.jsx)(u,{children:` `}),(0,Y.jsx)(u,{dimColor:!0,italic:!0,children:`Estimated usage by category`}),g.map((e,t)=>{let n=y(e.tokens),i=e.isDeferred?`N/A`:`${(e.tokens/r*100).toFixed(1)}%`,a=e.name===X,o=e.name,s=e.isDeferred?` `:a?`⛝`:`⛁`;return(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{color:e.color,children:s}),(0,Y.jsxs)(u,{children:[` `,o,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[n,` tokens (`,i,`)`]})]},t)}),(t.find(e=>e.name===`Free space`)?.tokens??0)>0&&(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{dimColor:!0,children:`⛶`}),(0,Y.jsx)(u,{children:` Free space: `}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(t.find(e=>e.name===`Free space`)?.tokens||0),` (`,((t.find(e=>e.name===`Free space`)?.tokens||0)/r*100).toFixed(1),`%)`]})]}),b&&b.tokens>0&&(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{color:b.color,children:`⛝`}),(0,Y.jsxs)(u,{dimColor:!0,children:[` `,b.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(b.tokens),` tokens (`,(b.tokens/r*100).toFixed(1),`%)`]})]})]})]}),(0,Y.jsxs)(l,{flexDirection:`column`,marginLeft:-1,children:[c.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`MCP tools`}),(0,Y.jsxs)(u,{dimColor:!0,children:[` · /mcp`,_?` (loaded on-demand)`:``]})]}),c.some(e=>e.isLoaded)&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:`Loaded`}),c.filter(e=>e.isLoaded).map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),_&&c.some(e=>!e.isLoaded)&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:`Available`}),c.filter(e=>!e.isLoaded).map((e,t)=>(0,Y.jsx)(l,{children:(0,Y.jsxs)(u,{dimColor:!0,children:[`└ `,e.name]})},t))]}),!_&&c.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),f.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Custom agents`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /agents`})]}),Array.from(q(f).entries()).map(([e,t])=>(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:e}),t.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.agentType,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]},e))]}),s.length>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Memory files`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /memory`})]}),s.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,v(e.path),`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]}),p&&p.tokens>0&&(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsxs)(l,{children:[(0,Y.jsx)(u,{bold:!0,children:`Skills`}),(0,Y.jsx)(u,{dimColor:!0,children:` · /skills`})]}),Array.from(q(p.skillFrontmatter).entries()).map(([e,t])=>(0,Y.jsxs)(l,{flexDirection:`column`,marginTop:1,children:[(0,Y.jsx)(u,{dimColor:!0,children:e}),t.map((e,t)=>(0,Y.jsxs)(l,{children:[(0,Y.jsxs)(u,{children:[`└ `,e.name,`: `]}),(0,Y.jsxs)(u,{dimColor:!0,children:[y(e.tokens),` tokens`]})]},t))]},e))]})]}),(0,Y.jsx)(U,{suggestions:k(e)})]})}var Y,X,Z,Q=e((()=>{d(),p(),H(),_(),b(),g(),G(),Y=m(),X=`Autocompact buffer`,Z=[`Project`,`User`,`Managed`,`Plugin`,`Built-in`]}));function ee(e){return i(e)}async function te(e,t){let{messages:n,getAppState:r,options:{mainLoopModel:i,tools:a}}=t,c=ee(n),{messages:l}=await s(c),u=process.stdout.columns||80,d=r();return e(await D((0,$.jsx)(J,{data:await o(l,i,async()=>d.toolPermissionContext,a,d.agentDefinitions,u,t,void 0,c)}))),null}var $;e((()=>{d(),Q(),a(),r(),c(),O(),$=m()}))();export{te as call};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$_ as t,Ba as n,Ma as r,Z_ as i,dv as a,uv as o}from"./loadAgentsDir-BXtV2jiO.js";import{cn as s,ln as c}from"./settings-DiBMs2gM.js";import{_ as l,v as u}from"./startupProfiler-Dc5r6LgE.js";async function d(e){let{messages:t,getAppState:n,options:{mainLoopModel:o,tools:s,agentDefinitions:c,customSystemPrompt:l,appendSystemPrompt:u}}=e,d=r(t),{messages:f}=await a(d),p=n();return i(f,o,async()=>p.toolPermissionContext,s,c,void 0,{options:{customSystemPrompt:l,appendSystemPrompt:u}},void 0,d)}async function f(e,t){return{type:`text`,value:p(await d(t))}}function p(e){let{categories:t,totalTokens:n,rawMaxTokens:r,percentage:i,model:a,memoryFiles:o,mcpTools:c,agents:u,skills:d}=e,f=`## Context Usage
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Y_ as t,ja as n,ov as r,q_ as i,sv as a,za as o}from"./loadAgentsDir-mcRW90aq.js";import{cn as s,ln as c}from"./settings-DiBMs2gM.js";import{_ as l,v as u}from"./startupProfiler-Dc5r6LgE.js";async function d(e){let{messages:t,getAppState:r,options:{mainLoopModel:o,tools:s,agentDefinitions:c,customSystemPrompt:l,appendSystemPrompt:u}}=e,d=n(t),{messages:f}=await a(d),p=r();return i(f,o,async()=>p.toolPermissionContext,s,c,void 0,{options:{customSystemPrompt:l,appendSystemPrompt:u}},void 0,d)}async function f(e,t){return{type:`text`,value:p(await d(t))}}function p(e){let{categories:t,totalTokens:n,rawMaxTokens:r,percentage:i,model:a,memoryFiles:o,mcpTools:c,agents:u,skills:d}=e,f=`## Context Usage
2
2
 
3
3
  `;f+=`**Model:** ${a} \n`,f+=`**Tokens:** ${l(n)} / ${l(r)} (${i}%)\n`,f+=`
4
4
  `;let p=t.filter(e=>e.tokens>0&&e.name!==`Free space`&&e.name!==`Autocompact buffer`);if(p.length>0){f+=`### Estimated usage by category
@@ -26,4 +26,4 @@ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$_ as t,Ba as n,Ma as
26
26
  `,f+=`| Skill | Source | Tokens |
27
27
  `,f+=`|-------|--------|--------|
28
28
  `;for(let e of d.skillFrontmatter)f+=`| ${e.name} | ${s(e.source)} | ${l(e.tokens)} |\n`;f+=`
29
- `}return f}var m=e((()=>{o(),t(),u(),n(),c()}));export{d as n,m as r,f as t};
29
+ `}return f}var m=e((()=>{r(),t(),u(),o(),c()}));export{d as n,m as r,f as t};
@@ -0,0 +1 @@
1
+ import{n as e,r as t,t as n}from"./context-noninteractive-CHzerxnH.js";t();export{n as call,e as collectContextData};
@@ -0,0 +1 @@
1
+ import{a as e,n as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Ah as n,An as r,Bs as i,Dn as a,GC as o,Jn as s,KC as c,Lg as l,Oh as u,Rg as d,Sr as f,Ug as p,Vg as m,Yt as h,_c as g,_n as _,b_ as v,gi as y,kn as b,ln as x,oE as S,pE as C,pi as w,ri as T,rr as E,wt as D,x_ as O,xt as k,zs as A}from"./loadAgentsDir-mcRW90aq.js";import{Dn as j,G as M,Qt as N,Tn as P,Wt as F,en as I,et as L,wn as R}from"./state-BPFYBqm1.js";import{o as z,s as B}from"./log-27kCA_9u.js";import{n as V,r as H}from"./analytics-DJobLaWP.js";import{_ as U,x as W}from"./sessionState-Bn3ESS5f.js";import{n as G,t as K}from"./caches-C5DIVdvI.js";import{randomUUID as q}from"crypto";function J(){return Y}var Y,X=t((()=>{g(),Y=null}));function Z(){let e=J();if(!e)return;e.markTranscriptReset?.();let t={type:`status`,subtype:`status`,status:`conversation_cleared`,message:`conversation_cleared`,uuid:q()};e.writeSdkMessages([t])}async function Q({setMessages:t,readFileState:n,discoveredSkillNames:r,loadedNestedMemoryPaths:o,getAppState:l,setAppState:p,setConversationId:g}){let _=x();await h(`clear`,{getAppState:l,setAppState:p,signal:AbortSignal.timeout(_),timeoutMs:_});let v=M();v&&H(`tengu_cache_eviction_hint`,{scope:`conversation_clear`,last_request_id:v});let C=new Set,D=[],A=e=>`isBackgrounded`in e&&e.isBackgrounded===!1;if(l)for(let e of Object.values(l().tasks))A(e)||i(e)&&(C.add(e.agentId),D.push(e));t(()=>[]),Z();{let{setContextBlocked:t}=(U(),e(W));t(!1)}g&&g(q()),K(C),R(null),P(null),j(null),I(),c(L()),n.clear(),r?.clear(),o?.clear(),p&&p(e=>{let t={};for(let[n,r]of Object.entries(e.tasks)){if(!A(r)){t[n]=r;continue}try{r.status===`running`&&(d(r)&&(r.shellCommand?.kill(),r.shellCommand?.cleanup(),r.cleanupTimeoutId&&clearTimeout(r.cleanupTimeoutId)),`abortController`in r&&r.abortController?.abort(),`unregisterCleanup`in r&&r.unregisterCleanup?.())}catch(e){B(e)}a(n)}return{...e,tasks:t,attribution:u(),standaloneAgentContext:void 0,fileHistory:{snapshots:[],trackedFiles:new Set,snapshotSequence:0},mcp:{clients:[],tools:[],commands:[],resources:{},pluginReconnectKey:e.mcp.pluginReconnectKey}}}),S(),s(),N({setCurrentAsParent:!0}),await T();for(let e of D)e.status===`running`&&b(e.id,E(m(e.agentId)));let{saveMode:F}=(f(),e(y));F(`normal`);let z=k();z&&w(z);let V=await O(`clear`);V.length>0&&t(()=>V)}var $=t((()=>{X(),F(),V(),A(),l(),p(),n(),_(),z(),C(),o(),v(),f(),r(),D(),G()}));export{$ as n,Q as t};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./conversation-5zb5XkSA.js";e();export{t as clearConversation};
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,S as r,c as i,i as a,x as o}from"./debug-Dr1SjdXn.js";import{l as s,u as c}from"./oauth-D38aRTUb.js";import{Bt as l,Ot as u}from"./model-CDnVaVDR.js";import{t as d}from"./cliLaunch-OPOtzhvA.js";import{resolve as f}from"path";import{existsSync as p,unlinkSync as m}from"fs";import{randomUUID as h}from"crypto";a(),o(),e();function g(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}var _=2e3,v=15e3,y=3,b=class{constructor(e,n){t(this,`proc`,void 0),t(this,`options`,void 0),t(this,`connected`,!1),t(this,`disconnected`,!1),t(this,`readLoopAbort`,null),t(this,`reconnectAttempt`,0),t(this,`maxReconnectAttempts`,void 0),t(this,`userInitiatedDisconnect`,!1),t(this,`reconnecting`,!1),this.proc=e,this.options=n,this.maxReconnectAttempts=n.maxReconnectAttempts??y}connect(){this.connected||(this.readLoopAbort=new AbortController,this.startReadLoop(),this.monitorExit(),this.connected=!0,this.options.onConnected())}async startReadLoop(){let e=this.proc.stdout;if(!e){this.options.onError(Error(`SSH process stdout is not available`));return}let t=e.getReader(),n=new TextDecoder,r=``;try{for(;!this.disconnected;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.split(`
1
+ import{n as e,t}from"./defineProperty-C-QyHrDq.js";import{C as n,S as r,c as i,i as a,x as o}from"./debug-Dr1SjdXn.js";import{l as s,u as c}from"./oauth-D38aRTUb.js";import{Bt as l,Ot as u}from"./model-C29_32BD.js";import{t as d}from"./cliLaunch-OPOtzhvA.js";import{resolve as f}from"path";import{existsSync as p,unlinkSync as m}from"fs";import{randomUUID as h}from"crypto";a(),o(),e();function g(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`}var _=2e3,v=15e3,y=3,b=class{constructor(e,n){t(this,`proc`,void 0),t(this,`options`,void 0),t(this,`connected`,!1),t(this,`disconnected`,!1),t(this,`readLoopAbort`,null),t(this,`reconnectAttempt`,0),t(this,`maxReconnectAttempts`,void 0),t(this,`userInitiatedDisconnect`,!1),t(this,`reconnecting`,!1),this.proc=e,this.options=n,this.maxReconnectAttempts=n.maxReconnectAttempts??y}connect(){this.connected||(this.readLoopAbort=new AbortController,this.startReadLoop(),this.monitorExit(),this.connected=!0,this.options.onConnected())}async startReadLoop(){let e=this.proc.stdout;if(!e){this.options.onError(Error(`SSH process stdout is not available`));return}let t=e.getReader(),n=new TextDecoder,r=``;try{for(;!this.disconnected;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.split(`
2
2
  `);r=a.pop()??``;for(let e of a){let t=e.trim();t&&this.processLine(t)}}}catch(e){this.disconnected||this.options.onError(e instanceof Error?e:Error(String(e)))}finally{t.releaseLock(),!this.disconnected&&!this.userInitiatedDisconnect&&this.handleProcessExit()}}monitorExit(){if(this.proc.exitCode!==null){this.userInitiatedDisconnect||this.handleProcessExit();return}this.proc.exited.then(()=>{!this.disconnected&&!this.userInitiatedDisconnect&&this.handleProcessExit()}).catch(()=>{!this.disconnected&&!this.userInitiatedDisconnect&&this.handleProcessExit()})}async handleProcessExit(){if(!(this.disconnected||this.reconnecting)){if(this.connected=!1,!this.options.reconnect){this.disconnected=!0,this.options.onDisconnected();return}if(this.reconnectAttempt>=this.maxReconnectAttempts){this.disconnected=!0,this.options.onDisconnected();return}this.reconnecting=!0;try{await this.attemptReconnect()}finally{this.reconnecting=!1}}}async attemptReconnect(){let e=this.options.reconnect;for(;this.reconnectAttempt<this.maxReconnectAttempts;){this.reconnectAttempt++,this.options.onReconnecting(this.reconnectAttempt,this.maxReconnectAttempts);let t=Math.min(_*2**(this.reconnectAttempt-1),v);if(await new Promise(e=>setTimeout(e,t)),this.userInitiatedDisconnect)return;try{let t=await e();this.proc=t,this.reconnectAttempt=0,this.connected=!0,this.startReadLoop(),this.monitorExit(),this.options.onConnected();return}catch(e){i(`[SSH] reconnect attempt ${this.reconnectAttempt} failed: ${e instanceof Error?e.message:String(e)}`)}}this.disconnected=!0,this.options.onDisconnected()}processLine(e){let t;try{t=r(e)}catch{return}if(!g(t))return;let n=t;if(n.type===`control_request`){let e=n;e.request.subtype===`can_use_tool`?this.options.onPermissionRequest(e.request,e.request_id):(i(`[SSH] Unsupported control request subtype: ${e.request.subtype}`),this.sendErrorResponse(e.request_id,`Unsupported control request subtype: ${e.request.subtype}`));return}n.type!==`control_response`&&n.type!==`keep_alive`&&n.type!==`control_cancel_request`&&n.type!==`streamlined_text`&&n.type!==`streamlined_tool_use_summary`&&!(n.type===`system`&&n.subtype===`post_turn_summary`)&&this.options.onMessage(n)}writeToStdin(e){try{let t=this.proc.stdin;if(!t||typeof t==`number`||this.disconnected)return!1;let n=new TextEncoder().encode(e+`
3
3
  `);return t.write(n),t.flush?.(),!0}catch{return!1}}async sendMessage(e){let t=n({type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null,session_id:``});return this.writeToStdin(t)}sendInterrupt(){let e=n({type:`control_request`,request_id:crypto.randomUUID(),request:{subtype:`interrupt`}});this.writeToStdin(e)}respondToPermissionRequest(e,t){let r=n({type:`control_response`,response:{subtype:`success`,request_id:e,response:{behavior:t.behavior,...t.behavior===`allow`?{updatedInput:t.updatedInput}:{message:t.message}}}});this.writeToStdin(r)}sendErrorResponse(e,t){let r=n({type:`control_response`,response:{subtype:`error`,request_id:e,error:t}});this.writeToStdin(r)}disconnect(){if(!this.disconnected){this.userInitiatedDisconnect=!0,this.disconnected=!0,this.connected=!1,this.readLoopAbort?.abort();try{let e=this.proc.stdin;e&&typeof e!=`number`&&e.end?.()}catch{}try{this.proc.kill()}catch{}}}isConnected(){return this.connected&&!this.disconnected}};l(),c(),a();var x=process.platform===`win32`;function S(){let e=process.env.ANTHROPIC_API_KEY;if(e)return{"x-api-key":e};let t=u();return t?.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{}}function C(){return process.env.ANTHROPIC_BASE_URL||s().BASE_API_URL}async function w(e,t){if(t&&e.headers.get(`x-auth-nonce`)!==t)return new Response(`Forbidden`,{status:403});let n=C(),r=new URL(e.url),a=`${n}${r.pathname}${r.search}`,o=S();if(Object.keys(o).length===0)return new Response(JSON.stringify({error:`No API credentials available on local machine`}),{status:401,headers:{"content-type":`application/json`}});let s=new Headers(e.headers);for(let[e,t]of Object.entries(o))s.set(e,t);s.delete(`host`),s.delete(`x-auth-nonce`),i(`[SSHAuthProxy] ${e.method} ${r.pathname} -> ${a}`);try{let t=await fetch(a,{method:e.method,headers:s,body:e.body,duplex:`half`}),n=new Headers(t.headers);return n.delete(`content-encoding`),n.delete(`content-length`),new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}catch(e){let t=e instanceof Error?e.message:String(e);return i(`[SSHAuthProxy] upstream error: ${t}`),new Response(JSON.stringify({error:`Proxy upstream error: ${t}`}),{status:502,headers:{"content-type":`application/json`}})}}async function T(){let e=h();return x?D(e):E(e)}async function E(e){let t=`/tmp/claude-ssh-auth-${e}.sock`,n=Bun.serve({unix:t,fetch:e=>w(e,null)});return i(`[SSHAuthProxy] listening on unix:${t}`),{proxy:{stop(){n.stop(!0);try{m(t)}catch{}}},localAddress:t,authEnv:{ANTHROPIC_AUTH_SOCKET:t}}}async function D(e){let t=h(),n=Bun.serve({port:0,hostname:`127.0.0.1`,fetch:e=>w(e,t)}),r=n.port;return i(`[SSHAuthProxy] listening on TCP 127.0.0.1:${r} (nonce-protected)`),{proxy:{stop(){n.stop(!0)}},localAddress:`127.0.0.1:${r}`,authEnv:{ANTHROPIC_BASE_URL:`http://127.0.0.1:${r}`,ANTHROPIC_AUTH_NONCE:t}}}a();var O=15e3,k=class extends Error{constructor(e){super(e),this.name=`SSHProbeError`}};async function A(e,t){t?.(`Probing remote host…`);let n=Bun.spawn([`ssh`,`-o`,`BatchMode=yes`,`-o`,`ConnectTimeout=10`,e,`CLAUDE_BIN=$(test -x "$HOME/.local/bin/claude" && echo "$HOME/.local/bin/claude" || command -v claude 2>/dev/null); echo "$CLAUDE_BIN"; $CLAUDE_BIN --version 2>/dev/null; uname -sm; pwd`],{stdin:`ignore`,stdout:`pipe`,stderr:`pipe`}),r=await Promise.race([n.exited,new Promise((e,t)=>setTimeout(()=>t(new k(`SSH probe timed out after ${O/1e3}s`)),O))]),a=await new Response(n.stdout).text(),o=await new Response(n.stderr).text();if(r!==0)throw new k(`SSH probe failed: ${o.trim()||`exit code ${r}`}`);let s=a.split(`
4
4
  `).map(e=>e.trim()).filter(Boolean);i(`[SSHProbe] raw lines: ${JSON.stringify(s)}`);let c=s.findIndex(e=>/^(Linux|Darwin)\s/.test(e));if(c===-1)throw new k(`Could not detect remote platform (uname output missing)`);let l=c>=2&&s[c-2]||null,u=c>=1&&s[c-1]||null,d=u&&/^\d+\.\d+/.test(u)?u:null,f=l!==null&&l.startsWith(`/`),p=s[c+1]||`/`,[m,h]=s[c].split(/\s+/),g=m===`Darwin`?`darwin`:`linux`,_=h===`aarch64`||h===`arm64`?`arm64`:`x64`;return t?.(`Detected ${g}/${_}`),{hasBinary:f&&d!==null,remoteVersion:d,remotePlatform:g,remoteArch:_,defaultCwd:p,binaryPath:f?l:null}}a();var j=6e4,M=`~/.local/bin`,N=`claude-code-cli.js`,P=`claude`;async function F(e,t,n=j){let r=Bun.spawn([`ssh`,`-o`,`ConnectTimeout=10`,e,t],{stdout:`pipe`,stderr:`pipe`}),i=setTimeout(()=>r.kill(),n);try{let[e,t]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text()]),n=await r.exited;return{stdout:e.trim(),stderr:t.trim(),exitCode:n}}finally{clearTimeout(i)}}function I(){let e=f(import.meta.dir,`../..`),t=f(e,`dist/cli.js`);if(p(t))return t;let n=f(e,`src/entrypoints/cli.tsx`);if(p(n))return n;throw Error("Cannot find local CLI binary to deploy. Run `bun run build` first.")}async function L(e){let{host:t,remotePlatform:n,remoteArch:r,localVersion:a,onProgress:o}=e;if(n!==`linux`&&n!==`darwin`)throw Error(`Remote platform "${n}" is not supported. Only linux and darwin are supported.`);i(`[SSHDeploy] deploying to ${t} (${n}/${r}, v${a})`);let s=I();i(`[SSHDeploy] local binary: ${s}`),o?.(`Creating remote directory...`);let c=await F(t,`mkdir -p ${M}`);if(c.exitCode!==0)throw Error(`Failed to create remote directory: ${c.stderr}`);o?.(`Uploading binary...`);let l=`${M}/${N}`,u=Bun.spawn([`scp`,`-o`,`ConnectTimeout=10`,s,`${t}:${l}`],{stdout:`pipe`,stderr:`pipe`}),d=setTimeout(()=>u.kill(),j),f=await new Response(u.stderr).text(),p=await u.exited;if(clearTimeout(d),p!==0)throw Error(`SCP upload failed (exit ${p}): ${f.trim()}`);o?.(`Installing wrapper script...`);let m=await F(t,[`cat > ${M}/${P} << 'WRAPPER'`,`#!/bin/sh`,`exec bun ${M}/${N} "$@"`,`WRAPPER`,`chmod +x ${M}/${P}`].join(`
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{P as t,R as n,c as r,i}from"./debug-Dr1SjdXn.js";import{i as a,t as o}from"./sessionIdCompat-DMayYBrf.js";import{i as s,o as c}from"./debugUtils-cK-iOsEV.js";async function l({environmentId:e,title:n,events:i,gitRepoUrl:a,branch:o,signal:c,baseUrl:l,getAccessToken:u,permissionMode:d}){let{getClaudeAIOAuthTokens:f}=await import(`./auth-DrD9DW6X.js`),{getOrganizationUUID:p}=await import(`./client-B-2ccQZk.js`),{getOauthConfig:m}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:h}=await import(`./api-C4VflFau.js`),{parseGitHubRepository:g}=await import(`./detectRepository-BsKZDRoI.js`),{getDefaultBranch:_}=await import(`./git-Bs1vtuvX.js`),{getMainLoopModel:v}=await import(`./model-CIvbC7rW.js`),{default:y}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:b}=await import(`./bridgeConfig-Ccm79Jze.js`),x=u?.()??f()?.accessToken;if(!x)return r(`[bridge] No access token for session creation`),null;let S=b()?`self-hosted`:await p();if(!S)return r(`[bridge] No org UUID for session creation`),null;let C=null,w=null;if(a){let{parseGitRemote:e}=await import(`./detectRepository-BsKZDRoI.js`),t=e(a);if(t){let{host:e,owner:n,name:r}=t,i=o||await _()||void 0;C={type:`git_repository`,url:`https://${e}/${n}/${r}`,revision:i},w={type:`git_repository`,git_info:{type:`github`,repo:`${n}/${r}`,branches:[`claude/${o||`task`}`]}}}else{let e=g(a);if(e){let[t,n]=e.split(`/`);if(t&&n){let e=o||await _()||void 0;C={type:`git_repository`,url:`https://github.com/${t}/${n}`,revision:e},w={type:`git_repository`,git_info:{type:`github`,repo:`${t}/${n}`,branches:[`claude/${o||`task`}`]}}}}}}let T={...n!==void 0&&{title:n},events:i,session_context:{sources:C?[C]:[],outcomes:w?[w]:[],model:v()},environment_id:e,source:`remote-control`,...d&&{permission_mode:d}},E={...h(x),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":S},D=`${l??m().BASE_API_URL}/v1/sessions`,O;try{O=await y.post(D,T,{headers:E,signal:c,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session creation request failed: ${t(e)}`),null}if(!(O.status===200||O.status===201)){let e=s(O.data);return r(`[bridge] Session creation failed with status ${O.status}${e?`: ${e}`:``}`),null}let k=O.data;return!k||typeof k!=`object`||!(`id`in k)||typeof k.id!=`string`?(r(`[bridge] No session ID in response`),null):k.id}async function u(e,n){let{getClaudeAIOAuthTokens:i}=await import(`./auth-DrD9DW6X.js`),{getOrganizationUUID:a}=await import(`./client-B-2ccQZk.js`),{getOauthConfig:o}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:c}=await import(`./api-C4VflFau.js`),{default:l}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:u}=await import(`./bridgeConfig-Ccm79Jze.js`),d=n?.getAccessToken?.()??i()?.accessToken;if(!d)return r(`[bridge] No access token for session fetch`),null;let f=u()?`self-hosted`:await a();if(!f)return r(`[bridge] No org UUID for session fetch`),null;let p={...c(d),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":f},m=`${n?.baseUrl??o().BASE_API_URL}/v1/sessions/${e}`;r(`[bridge] Fetching session ${e}`);let h;try{h=await l.get(m,{headers:p,timeout:1e4,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session fetch request failed: ${t(e)}`),null}if(h.status!==200){let e=s(h.data);return r(`[bridge] Session fetch failed with status ${h.status}${e?`: ${e}`:``}`),null}return h.data}async function d(e,t){let{getClaudeAIOAuthTokens:n}=await import(`./auth-DrD9DW6X.js`),{getOrganizationUUID:i}=await import(`./client-B-2ccQZk.js`),{getOauthConfig:a}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:o}=await import(`./api-C4VflFau.js`),{default:c}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:l}=await import(`./bridgeConfig-Ccm79Jze.js`),u=t?.getAccessToken?.()??n()?.accessToken;if(!u){r(`[bridge] No access token for session archive`);return}let d=l()?`self-hosted`:await i();if(!d){r(`[bridge] No org UUID for session archive`);return}let f={...o(u),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":d},p=`${t?.baseUrl??a().BASE_API_URL}/v1/sessions/${e}/archive`;r(`[bridge] Archiving session ${e}`);let m=await c.post(p,{},{headers:f,timeout:t?.timeoutMs??1e4,validateStatus:e=>e<500});if(m.status===200)r(`[bridge] Session ${e} archived successfully`);else{let e=s(m.data);r(`[bridge] Session archive failed with status ${m.status}${e?`: ${e}`:``}`)}}async function f(e,n,i){let{getClaudeAIOAuthTokens:o}=await import(`./auth-DrD9DW6X.js`),{getOrganizationUUID:c}=await import(`./client-B-2ccQZk.js`),{getOauthConfig:l}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:u}=await import(`./api-C4VflFau.js`),{default:d}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:f}=await import(`./bridgeConfig-Ccm79Jze.js`),p=i?.getAccessToken?.()??o()?.accessToken;if(!p){r(`[bridge] No access token for session title update`);return}let m=f()?`self-hosted`:await c();if(!m){r(`[bridge] No org UUID for session title update`);return}let h={...u(p),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":m},g=a(e),_=`${i?.baseUrl??l().BASE_API_URL}/v1/sessions/${g}`;r(`[bridge] Updating session title: ${g} → ${n}`);try{let e=await d.patch(_,{title:n},{headers:h,timeout:1e4,validateStatus:e=>e<500});if(e.status===200)r(`[bridge] Session title updated successfully`);else{let t=s(e.data);r(`[bridge] Session title update failed with status ${e.status}${t?`: ${t}`:``}`)}}catch(e){r(`[bridge] Session title update request failed: ${t(e)}`)}}var p=e((()=>{i(),n(),c(),o()}));export{f as a,p as i,l as n,u as r,d as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{P as t,R as n,c as r,i}from"./debug-Dr1SjdXn.js";import{i as a,t as o}from"./sessionIdCompat-DMayYBrf.js";import{i as s,o as c}from"./debugUtils-cK-iOsEV.js";async function l({environmentId:e,title:n,events:i,gitRepoUrl:a,branch:o,signal:c,baseUrl:l,getAccessToken:u,permissionMode:d}){let{getClaudeAIOAuthTokens:f}=await import(`./auth-D_0waidQ.js`),{getOrganizationUUID:p}=await import(`./client-DVg8PpFX.js`),{getOauthConfig:m}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:h}=await import(`./api-DgjIFdMn.js`),{parseGitHubRepository:g}=await import(`./detectRepository-BsKZDRoI.js`),{getDefaultBranch:_}=await import(`./git-Bs1vtuvX.js`),{getMainLoopModel:v}=await import(`./model-BqaneI4D.js`),{default:y}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:b}=await import(`./bridgeConfig-DywkIo_k.js`),x=u?.()??f()?.accessToken;if(!x)return r(`[bridge] No access token for session creation`),null;let S=b()?`self-hosted`:await p();if(!S)return r(`[bridge] No org UUID for session creation`),null;let C=null,w=null;if(a){let{parseGitRemote:e}=await import(`./detectRepository-BsKZDRoI.js`),t=e(a);if(t){let{host:e,owner:n,name:r}=t,i=o||await _()||void 0;C={type:`git_repository`,url:`https://${e}/${n}/${r}`,revision:i},w={type:`git_repository`,git_info:{type:`github`,repo:`${n}/${r}`,branches:[`claude/${o||`task`}`]}}}else{let e=g(a);if(e){let[t,n]=e.split(`/`);if(t&&n){let e=o||await _()||void 0;C={type:`git_repository`,url:`https://github.com/${t}/${n}`,revision:e},w={type:`git_repository`,git_info:{type:`github`,repo:`${t}/${n}`,branches:[`claude/${o||`task`}`]}}}}}}let T={...n!==void 0&&{title:n},events:i,session_context:{sources:C?[C]:[],outcomes:w?[w]:[],model:v()},environment_id:e,source:`remote-control`,...d&&{permission_mode:d}},E={...h(x),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":S},D=`${l??m().BASE_API_URL}/v1/sessions`,O;try{O=await y.post(D,T,{headers:E,signal:c,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session creation request failed: ${t(e)}`),null}if(!(O.status===200||O.status===201)){let e=s(O.data);return r(`[bridge] Session creation failed with status ${O.status}${e?`: ${e}`:``}`),null}let k=O.data;return!k||typeof k!=`object`||!(`id`in k)||typeof k.id!=`string`?(r(`[bridge] No session ID in response`),null):k.id}async function u(e,n){let{getClaudeAIOAuthTokens:i}=await import(`./auth-D_0waidQ.js`),{getOrganizationUUID:a}=await import(`./client-DVg8PpFX.js`),{getOauthConfig:o}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:c}=await import(`./api-DgjIFdMn.js`),{default:l}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:u}=await import(`./bridgeConfig-DywkIo_k.js`),d=n?.getAccessToken?.()??i()?.accessToken;if(!d)return r(`[bridge] No access token for session fetch`),null;let f=u()?`self-hosted`:await a();if(!f)return r(`[bridge] No org UUID for session fetch`),null;let p={...c(d),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":f},m=`${n?.baseUrl??o().BASE_API_URL}/v1/sessions/${e}`;r(`[bridge] Fetching session ${e}`);let h;try{h=await l.get(m,{headers:p,timeout:1e4,validateStatus:e=>e<500})}catch(e){return r(`[bridge] Session fetch request failed: ${t(e)}`),null}if(h.status!==200){let e=s(h.data);return r(`[bridge] Session fetch failed with status ${h.status}${e?`: ${e}`:``}`),null}return h.data}async function d(e,t){let{getClaudeAIOAuthTokens:n}=await import(`./auth-D_0waidQ.js`),{getOrganizationUUID:i}=await import(`./client-DVg8PpFX.js`),{getOauthConfig:a}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:o}=await import(`./api-DgjIFdMn.js`),{default:c}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:l}=await import(`./bridgeConfig-DywkIo_k.js`),u=t?.getAccessToken?.()??n()?.accessToken;if(!u){r(`[bridge] No access token for session archive`);return}let d=l()?`self-hosted`:await i();if(!d){r(`[bridge] No org UUID for session archive`);return}let f={...o(u),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":d},p=`${t?.baseUrl??a().BASE_API_URL}/v1/sessions/${e}/archive`;r(`[bridge] Archiving session ${e}`);let m=await c.post(p,{},{headers:f,timeout:t?.timeoutMs??1e4,validateStatus:e=>e<500});if(m.status===200)r(`[bridge] Session ${e} archived successfully`);else{let e=s(m.data);r(`[bridge] Session archive failed with status ${m.status}${e?`: ${e}`:``}`)}}async function f(e,n,i){let{getClaudeAIOAuthTokens:o}=await import(`./auth-D_0waidQ.js`),{getOrganizationUUID:c}=await import(`./client-DVg8PpFX.js`),{getOauthConfig:l}=await import(`./oauth-U649LV5H.js`),{getOAuthHeaders:u}=await import(`./api-DgjIFdMn.js`),{default:d}=await import(`./axios-BHBm_hhU.js`),{isSelfHostedBridge:f}=await import(`./bridgeConfig-DywkIo_k.js`),p=i?.getAccessToken?.()??o()?.accessToken;if(!p){r(`[bridge] No access token for session title update`);return}let m=f()?`self-hosted`:await c();if(!m){r(`[bridge] No org UUID for session title update`);return}let h={...u(p),"anthropic-beta":`ccr-byoc-2025-07-29`,"x-organization-uuid":m},g=a(e),_=`${i?.baseUrl??l().BASE_API_URL}/v1/sessions/${g}`;r(`[bridge] Updating session title: ${g} → ${n}`);try{let e=await d.patch(_,{title:n},{headers:h,timeout:1e4,validateStatus:e=>e<500});if(e.status===200)r(`[bridge] Session title updated successfully`);else{let t=s(e.data);r(`[bridge] Session title update failed with status ${e.status}${t?`: ${t}`:``}`)}}catch(e){r(`[bridge] Session title update request failed: ${t(e)}`)}}var p=e((()=>{i(),n(),c(),o()}));export{f as a,p as i,l as n,u as r,d as t};
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,r}from"./createSession-BNGm9fL4.js";t();export{n as createBridgeSession,r as getBridgeSession,e as updateBridgeSessionTitle};
@@ -0,0 +1,40 @@
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Ap as n,Au as r,Bu as i,EC as a,Er as o,Fr as s,MC as c,Mu as l,Qc as u,Sr as d,Ti as f,Vu as p,Xu as ee,Zu as m,aT as h,ci as te,el as g,jp as ne,mr as _,oT as v,od as re,or as ie,sd as ae,wi as oe,wr as se}from"./loadAgentsDir-mcRW90aq.js";import{C as ce,D as y,Gr as b,H as le,I as x,P as S,T as C,Wt as ue,Xn as de,ai as fe,di as w,fi as T,hn as pe,k as me,ot as he,p as ge,t as E,ui as _e}from"./src-P_wYS_NJ2.js";import{t as D}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as ve,et as ye,pt as be}from"./state-BPFYBqm1.js";import{S as O,c as k,i as xe,x as Se}from"./debug-Dr1SjdXn.js";import{Ln as A,Rn as Ce}from"./settings-DiBMs2gM.js";import{i as we,m as Te}from"./git-CoQQ6YEf.js";import{a as j,o as Ee,s as De}from"./log-27kCA_9u.js";import{n as Oe,r as M}from"./analytics-DJobLaWP.js";import{C as ke,d as Ae,m as je,v as Me}from"./startupProfiler-Dc5r6LgE.js";import{_ as N,h as P}from"./model-C29_32BD.js";import{i as Ne,r as Pe}from"./shellQuote-C_I6DHLV.js";import{n as Fe,t as Ie}from"./useExitOnCtrlCDWithKeybindings-CPLBDluY.js";import{t as Le}from"./SearchBox-C9vUA4IM.js";import{n as Re,t as ze}from"./useSearchInput-KFKh2ozY.js";import{n as F,t as I}from"./Messages-C1jh4ixt.js";function Be({log:e,onExit:t,onSelect:r}){let[i,a]=L.useState(null);L.useEffect(()=>{a(null),o(e)&&s(e).then(a)},[e]);let c=o(e)&&i===null,l=i??e,d=_(l)||``,f=u();return ue(`confirm:no`,t,{context:`Confirmation`}),ue(`confirm:yes`,(0,L.useCallback)(()=>{r(i??e)},[r,i,e]),{context:`Confirmation`}),c?(0,R.jsxs)(x,{flexDirection:`column`,padding:1,children:[(0,R.jsx)(ge,{message:`Loading session…`}),(0,R.jsx)(S,{dimColor:!0,children:(0,R.jsx)(C,{children:(0,R.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})})})]}):(0,R.jsxs)(x,{flexDirection:`column`,children:[(0,R.jsx)(I,{messages:l.messages,tools:f,commands:[],verbose:!0,toolJSX:null,toolUseConfirmQueue:[],inProgressToolUseIDs:new Set,isMessageSelectorVisible:!1,conversationId:d,screen:`transcript`,streamingToolUses:[],showAllInTranscript:!0,isLoading:!1}),(0,R.jsxs)(x,{flexShrink:0,flexDirection:`column`,borderTopDimColor:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,paddingLeft:2,children:[(0,R.jsxs)(S,{children:[je(l.modified),` · `,l.messageCount,` messages`,l.gitBranch?` · ${l.gitBranch}`:``]}),(0,R.jsx)(S,{dimColor:!0,children:(0,R.jsxs)(C,{children:[(0,R.jsx)(y,{shortcut:`Enter`,action:`resume`}),(0,R.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})]})]})}var L,R,Ve=e((()=>{L=t(T(),1),E(),a(),g(),Me(),d(),ne(),F(),R=D()}));function z(e,t){if(e===V)return 5;let n=b(e),r=t?Math.min(n,t-H-U):n;return Math.max(0,r)+H+U}function He(e,t){let n=t-H-U;return b(e)<=n?e:n<=1?e.charAt(0):ke(e,n)}function Ue({tabs:e,selectedIndex:t,availableWidth:n,showAllProjects:r=!1}){let i=r?`Resume (All Projects)`:`Resume`,a=i.length+1,o=Math.max(Je,G),s=n-a-o-2,c=Math.max(0,Math.min(t,e.length-1)),l=Math.max(20,Math.floor(s/2)),u=e.map(e=>z(e,l)),d=0,f=e.length;if(u.reduce((e,t,n)=>e+t+ +(n<u.length-1),0)>s){let t=s-qe,n=u[c]??0;for(d=c,f=c+1;d>0||f<e.length;){let r=d>0,i=f<e.length;if(r){let e=(u[d-1]??0)+1;if(n+e<=t){d--,n+=e;continue}}if(i){let e=(u[f]??0)+1;if(n+e<=t){f++,n+=e;continue}}break}}let p=d,ee=e.length-f,m=e.slice(d,f),h=m.map((e,t)=>d+t);return(0,B.jsxs)(x,{flexDirection:`row`,gap:1,children:[(0,B.jsx)(S,{color:`suggestion`,children:i}),p>0&&(0,B.jsxs)(S,{dimColor:!0,children:[W,p]}),m.map((e,t)=>{let n=h[t]===c,r=e===V?e:`#${He(e,l-H)}`;return(0,B.jsxs)(S,{backgroundColor:n?`suggestion`:void 0,color:n?`inverseText`:void 0,bold:n,children:[` `,r,` `]},e)}),ee>0?(0,B.jsxs)(S,{dimColor:!0,children:[We,ee,Ge]}):(0,B.jsx)(S,{dimColor:!0,children:Ke})]})}var B,V,H,U,W,We,Ge,Ke,qe,Je,G,K=e((()=>{T(),E(),Me(),B=D(),V=`All`,H=2,U=1,W=`← `,We=`→`,Ge=` (tab to cycle)`,Ke=`(tab to cycle)`,qe=5,Je=18,G=14}));function Ye({nodes:e,onSelect:t,onCancel:n,onFocus:r,focusNodeId:i,visibleOptionCount:a,layout:o=`expanded`,isDisabled:s=!1,hideIndexes:c=!1,isNodeExpanded:l,onExpand:u,onCollapse:d,getParentPrefix:f,getChildPrefix:p,onUpFromFirstItem:m}){let[h,te]=q.useState(new Set),g=q.useRef(!1),ne=q.useRef(null),_=q.useCallback(e=>l?l(e):h.has(e),[l,h]),v=q.useMemo(()=>{let t=[];function n(e,r,i){let a=!!e.children&&e.children.length>0,o=_(e.id);if(t.push({node:e,depth:r,isExpanded:o,hasChildren:a,parentId:i}),a&&o&&e.children)for(let t of e.children)n(t,r+1,e.id)}for(let t of e)n(t,0);return t},[e,_]),re=q.useCallback(e=>e?`▼ `:`▶ `,[]),ie=q.useCallback(e=>` ▸ `,[]),ae=f??re,oe=p??ie,se=q.useCallback(e=>{let t=``;return e.hasChildren?t=ae(e.isExpanded):e.depth>0&&(t=oe(e.depth)),t+e.node.label},[ae,oe]),ce=q.useMemo(()=>v.map(e=>({label:se(e),description:e.node.description,dimDescription:e.node.dimDescription??!0,value:e.node.id})),[v,se]),y=q.useMemo(()=>{let e=new Map;return v.forEach(t=>e.set(t.node.id,t.node)),e},[v]),b=q.useCallback(e=>v.find(t=>t.node.id===e),[v]),le=q.useCallback((e,t)=>{let n=b(e);!n||!n.hasChildren||(t?u?u(e):te(t=>new Set(t).add(e)):d?d(e):te(t=>{let n=new Set(t);return n.delete(e),n}))},[b,u,d]);return(0,Xe.jsx)(x,{tabIndex:0,autoFocus:!0,onKeyDown:e=>{if(!i||s)return;let t=b(i);if(t){if(e.key===`right`&&t.hasChildren)e.preventDefault(),le(i,!0);else if(e.key===`left`){if(t.hasChildren&&t.isExpanded)e.preventDefault(),le(i,!1);else if(t.parentId!==void 0&&(e.preventDefault(),g.current=!0,le(t.parentId,!1),r)){let e=y.get(t.parentId);e&&r(e)}}}},children:(0,Xe.jsx)(ee,{options:ce,onChange:q.useCallback(e=>{let n=y.get(e);n&&t(n)},[y,t]),onFocus:q.useCallback(e=>{if(g.current){g.current=!1;return}if(ne.current!==e&&(ne.current=e,r)){let t=y.get(e);t&&r(t)}},[r,y]),onCancel:n,defaultFocusValue:i,visibleOptionCount:a,layout:o,isDisabled:s,hideIndexes:c,onUpFromFirstItem:m})})}var q,Xe,Ze=e((()=>{q=t(T(),1),E(),m(),Xe=D()}));function Qe(e,t){return ke(e.replace(/\s+/g,` `).trim(),t)}function $e({before:e,match:t,after:n},r){return _e.dim(e)+r(t)+_e.dim(n)}function et(e,t,n){let r=e.toLowerCase().indexOf(t.toLowerCase());if(r===-1)return null;let i=r+t.length,a=Math.max(0,r-n),o=Math.min(e.length,i+n),s=e.slice(a,r),c=e.slice(r,i),l=e.slice(i,o);return{before:(a>0?`…`:``)+s.replace(/\s+/g,` `).trimStart(),match:c.trim(),after:l.replace(/\s+/g,` `).trimEnd()+(o<e.length?`…`:``)}}function tt(e,t,n){let{isGroupHeader:r=!1,isChild:i=!1,forkCount:a=0}=n||{},o=r&&a>0?ct:i?lt:0,s=r&&a>0?` (+${a} other ${a===1?`session`:`sessions`})`:``,c=e.isSidechain?` (sidechain)`:``,l=t-o-c.length-s.length;return`${Qe(j(e),l)}${c}${s}`}function nt(e,t){let{isChild:n=!1,showProjectPath:r=!1}=t||{},i=n?` `:``,a=Ae(e),o=r&&e.projectPath?` · ${e.projectPath}`:``;return i+a+o}function rt({logs:e,maxHeight:t=1/0,forceWidth:a,onCancel:o,onSelect:s,onLogsChanged:c,onLoadMore:l,initialSearchQuery:u,showAllProjects:d=!1,onToggleAllProjects:f,onAgenticSearch:p}){let m=he(),h=a===void 0?m.columns:a,g=Fe(o),ne=de(),v=se(),[ae]=le(),b=i(ae),w=J.useMemo(()=>e=>fe(e,b.warning),[b.warning]),[T,ge]=J.useState(null),[E,_e]=J.useState(!1),[D,ve]=J.useState(!1),[O,k]=J.useState(!1),xe=J.useMemo(()=>ye(),[]),[Se,A]=J.useState(``),[Ce,Te]=J.useState(0),[Ee,De]=J.useState(new Set),[Oe,ke]=J.useState(null),[je,Me]=J.useState(1),[N,P]=J.useState(`list`),[Ne,Pe]=J.useState(null),Ie=J.useRef(null),[Le,ze]=J.useState(0),[F,I]=J.useState({status:`idle`}),[L,R]=J.useState(!1),Ve=J.useRef(null),{query:z,setQuery:He,cursorOffset:B}=Re({isActive:N===`search`&&F.status!==`searching`,onExit:()=>{P(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},onExitUp:()=>{P(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},passthroughCtrlKeys:[`n`],initialQuery:u||``}),V=J.useDeferredValue(z),[H,U]=J.useState(``);J.useEffect(()=>{if(!V){U(``);return}let e=setTimeout(U,300,V);return()=>clearTimeout(e)},[V]);let[W,We]=J.useState(null),[Ge,Ke]=J.useState(!1);J.useEffect(()=>{we().then(e=>ge(e)),oe(xe).then(e=>{k(e.length>1)})},[xe]);let qe=J.useMemo(()=>new Map(e.map(e=>[e,at(e)])),[e]),Je=J.useMemo(()=>null,[e,qe,!1]),G=J.useMemo(()=>st(e),[e]),K=G.length>0,q=J.useMemo(()=>K?[`All`,...G]:[],[K,G]),Xe=q.length>0&&Le<q.length?Le:0,Ze=q[Xe],rt=Ze===`All`?void 0:Ze,it=+!!K,ct=J.useMemo(()=>{let t=e;return v&&(t=e.filter(e=>{let t=be(),n=_(e);return!!(t&&n===t||e.customTitle||ie(e.messages)||e.firstPrompt||e.customTitle)})),rt!==void 0&&(t=t.filter(e=>e.tag===rt)),E&&T&&(t=t.filter(e=>e.gitBranch===T)),O&&!D&&(t=t.filter(e=>e.projectPath===xe)),t},[e,v,rt,E,T,O,D,xe]),lt=J.useMemo(()=>{if(!z)return ct;let e=z.toLowerCase();return ct.filter(t=>{let n=j(t).toLowerCase(),r=(t.gitBranch||``).toLowerCase(),i=(t.tag||``).toLowerCase(),a=t.prNumber?`pr #${t.prNumber} ${t.prRepository||``}`.toLowerCase():``;return n.includes(e)||r.includes(e)||i.includes(e)||a.includes(e)})},[ct,z]);J.useEffect(()=>{},[V,H,!1]),J.useEffect(()=>{We(null),Ke(!1)},[H,Je,!1]);let{filteredLogs:ut,snippets:X}=J.useMemo(()=>{let e=new Map,t=lt;if(W&&H&&W.query===H){for(let t of W.results)if(t.searchableText){let n=et(t.searchableText,H,dt);n&&e.set(t.log,n)}let n=new Set(t.map(e=>e.messages[0]?.uuid)),r=W.results.map(e=>e.log).filter(e=>!n.has(e.messages[0]?.uuid));t=[...t,...r]}return{filteredLogs:t,snippets:e}},[lt,W,H]),Z=J.useMemo(()=>F.status===`results`&&F.results.length>0?F.results:ut,[F,ut]),Q=Math.max(30,h-4),ft=J.useMemo(()=>{if(!v)return[];let e=ot(Z);return Array.from(e.entries()).map(([e,t])=>{let n=t[0],r=Z.indexOf(n),i=X.get(n),a=i?$e(i,w):null;if(t.length===1){let t=nt(n,{showProjectPath:d});return{id:`log:${e}:0`,value:{log:n,indexInFiltered:r},label:tt(n,Q),description:a?`${t}\n ${a}`:t,dimDescription:!0}}let o=t.length-1,s=t.slice(1).map((t,n)=>{let r=Z.indexOf(t),i=X.get(t),a=i?$e(i,w):null,o=nt(t,{isChild:!0,showProjectPath:d});return{id:`log:${e}:${n+1}`,value:{log:t,indexInFiltered:r},label:tt(t,Q,{isChild:!0}),description:a?`${o}\n ${a}`:o,dimDescription:!0}}),c=nt(n,{showProjectPath:d});return{id:`group:${e}`,value:{log:n,indexInFiltered:r},label:tt(n,Q,{isGroupHeader:!0,forkCount:o}),description:a?`${c}\n ${a}`:c,dimDescription:!0,children:s}})},[v,Z,Q,d,X,w]),pt=J.useMemo(()=>v?[]:Z.map((e,t)=>{let n=Qe(j(e)+(e.isSidechain?` (sidechain)`:``),Q),r=Ae(e),i=d&&e.projectPath?` · ${e.projectPath}`:``,a=X.get(e),o=a?$e(a,w):null;return{label:n,description:o?`${r}${i}\n ${o}`:r+i,dimDescription:!0,value:t.toString()}}),[v,Z,w,Q,d,X]),$=Oe?.value.log??null,mt=()=>{if(!v||!$)return``;let e=_($);if(!e)return``;let t=Z.filter(t=>_(t)===e);if(!(t.length>1))return``;let n=Ee.has(e);return t.indexOf($)>0||n?`← to collapse`:`→ to expand`},ht=J.useCallback(async()=>{let e=$?_($):void 0;if(!$||!e){P(`list`),A(``);return}Se.trim()&&(await te(e,Se.trim(),$.fullPath),v&&c&&c()),P(`list`),A(``)},[$,Se,c,v]),gt=J.useCallback(()=>{P(`list`),M(`tengu_session_search_toggled`,{enabled:!1})},[]),_t=J.useCallback(()=>{P(`search`),M(`tengu_session_search_toggled`,{enabled:!0})},[]),vt=J.useCallback(async()=>{if(!z.trim()||!p||!0)return;Ve.current?.abort();let t=new AbortController;Ve.current=t,I({status:`searching`}),M(`tengu_agentic_search_started`,{query_length:z.length});try{let n=await p(z,e,t.signal);if(t.signal.aborted)return;I({status:`results`,results:n,query:z}),M(`tengu_agentic_search_completed`,{query_length:z.length,results_count:n.length})}catch(e){if(t.signal.aborted)return;I({status:`error`,message:e instanceof Error?e.message:`Search failed`}),M(`tengu_agentic_search_error`,{query_length:z.length})}},[z,p,!1,e]);J.useEffect(()=>{F.status!==`idle`&&F.status!==`searching`&&(F.status===`results`&&F.query!==z||F.status===`error`)&&I({status:`idle`})},[z,F]),J.useEffect(()=>()=>{Ve.current?.abort()},[]);let yt=J.useRef(F.status);J.useEffect(()=>{let e=yt.current;if(yt.current=F.status,e===`searching`&&F.status===`results`){if(v&&ft.length>0)ke(ft[0]);else if(!v&&Z.length>0){let e=Z[0];ke({id:`0`,value:{log:e,indexInFiltered:0},label:``})}}},[F.status,v,ft,Z]);let bt=J.useCallback(e=>{let t=parseInt(e,10),n=Z[t];!n||Ie.current===t.toString()||(Ie.current=t.toString(),ke({id:t.toString(),value:{log:n,indexInFiltered:t},label:``}),Me(t+1))},[Z]),xt=J.useCallback(e=>{ke(e);let t=Z.findIndex(t=>_(t)===_(e.value.log));t>=0&&Me(t+1)},[Z]);ue(`confirm:no`,()=>{Ve.current?.abort(),I({status:`idle`}),M(`tengu_agentic_search_cancelled`,{})},{context:`Confirmation`,isActive:N!==`preview`&&F.status===`searching`}),ue(`confirm:no`,()=>{P(`list`),A(``)},{context:`Settings`,isActive:N===`rename`&&F.status!==`searching`}),ue(`confirm:no`,()=>{He(``),R(!1),o?.()},{context:`Confirmation`,isActive:N!==`preview`&&N!==`rename`&&N!==`search`&&L&&F.status!==`searching`}),pe((e,t)=>{if(N!==`preview`&&F.status!==`searching`&&N!==`rename`)if(N===`search`)e.toLowerCase()===`n`&&t.ctrl?gt():(t.return||t.downArrow)&&z.trim();else{if(L){if(t.return){vt(),R(!1);return}else if(t.downArrow){R(!1);return}else if(t.upArrow){P(`search`),R(!1);return}}if(K&&t.tab){let e=t.shift?-1:1;ze(t=>{let n=((t<q.length?t:0)+q.length+e)%q.length,r=q[n];return M(`tengu_session_tag_filter_changed`,{is_all:r===`All`,tag_count:G.length}),n});return}let n=!t.ctrl&&!t.meta,r=e.toLowerCase();if(r===`a`&&t.ctrl&&f)f(),M(`tengu_session_all_projects_toggled`,{enabled:!d});else if(r===`b`&&t.ctrl){let e=!E;_e(e),M(`tengu_session_branch_filter_toggled`,{enabled:e})}else if(r===`w`&&t.ctrl&&O){let e=!D;ve(e),M(`tengu_session_worktree_filter_toggled`,{enabled:e})}else r===`/`&&n?(P(`search`),M(`tengu_session_search_toggled`,{enabled:!0})):r===`r`&&t.ctrl&&$?(P(`rename`),A(``),M(`tengu_session_rename_started`,{})):r===`v`&&t.ctrl&&$?(Pe($),P(`preview`),M(`tengu_session_preview_opened`,{messageCount:$.messageCount})):$&&n&&e.length>0&&!/^\s+$/.test(e)&&(P(`search`),He(e),M(`tengu_session_search_toggled`,{enabled:!0}))}},{isActive:!0});let St=[];E&&T&&St.push(T),O&&!D&&St.push(`current worktree`);let Ct=8+ +(St.length>0&&N!==`search`)+it,wt=Math.max(1,Math.floor((t-Ct-2)/3));return J.useEffect(()=>{if(!l)return;let e=wt*2;je+e>=Z.length&&l(wt*3)},[je,wt,Z.length,l]),e.length===0?null:N===`preview`&&Ne&&v?(0,Y.jsx)(Be,{log:Ne,onExit:()=>{P(`list`),Pe(null)},onSelect:s}):(0,Y.jsxs)(x,{flexDirection:`column`,height:t-1,children:[(0,Y.jsx)(x,{flexShrink:0,children:(0,Y.jsx)(ce,{color:`suggestion`})}),(0,Y.jsx)(x,{flexShrink:0,children:(0,Y.jsx)(S,{children:` `})}),K?(0,Y.jsx)(Ue,{tabs:q,selectedIndex:Xe,availableWidth:h,showAllProjects:d}):(0,Y.jsx)(x,{flexShrink:0,children:(0,Y.jsxs)(S,{bold:!0,color:`suggestion`,children:[`Resume Session`,N===`list`&&Z.length>wt&&(0,Y.jsxs)(S,{dimColor:!0,children:[` `,`(`,je,` of `,Z.length,`)`]})]})}),(0,Y.jsx)(me,{query:z,isFocused:N===`search`,isTerminalFocused:ne,cursorOffset:B}),St.length>0&&N!==`search`&&(0,Y.jsx)(x,{flexShrink:0,paddingLeft:2,children:(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsx)(C,{children:St})})}),(0,Y.jsx)(x,{flexShrink:0,children:(0,Y.jsx)(S,{children:` `})}),F.status===`searching`&&(0,Y.jsxs)(x,{paddingLeft:1,flexShrink:0,children:[(0,Y.jsx)(r,{}),(0,Y.jsx)(S,{children:` Searching…`})]}),F.status===`results`&&F.results.length>0&&(0,Y.jsx)(x,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(S,{dimColor:!0,italic:!0,children:`Claude found these results:`})}),F.status===`results`&&F.results.length===0&&ut.length===0&&(0,Y.jsx)(x,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(S,{dimColor:!0,italic:!0,children:`No matching sessions found.`})}),F.status===`error`&&ut.length===0&&(0,Y.jsx)(x,{paddingLeft:1,marginBottom:1,flexShrink:0,children:(0,Y.jsx)(S,{dimColor:!0,italic:!0,children:`No matching sessions found.`})}),!!z.trim()&&p&&!1,F.status===`searching`?null:N===`rename`&&$?(0,Y.jsxs)(x,{paddingLeft:2,flexDirection:`column`,children:[(0,Y.jsx)(S,{bold:!0,children:`Rename session:`}),(0,Y.jsx)(x,{paddingTop:1,children:(0,Y.jsx)(re,{value:Se,onChange:A,onSubmit:ht,placeholder:j($,`Enter new session name`),columns:h,cursorOffset:Ce,onChangeCursorOffset:Te,showCursor:!0})})]}):v?(0,Y.jsx)(Ye,{nodes:ft,onSelect:e=>{s(e.value.log)},onFocus:xt,onCancel:o,focusNodeId:Oe?.id,visibleOptionCount:wt,layout:`expanded`,isDisabled:N===`search`||L,hideIndexes:!1,isNodeExpanded:e=>{if(N===`search`||E)return!0;let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;return t?Ee.has(t):!1},onExpand:e=>{let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;t&&(De(e=>new Set(e).add(t)),M(`tengu_session_group_expanded`,{}))},onCollapse:e=>{let t=typeof e==`string`&&e.startsWith(`group:`)?e.substring(6):null;t&&De(e=>{let n=new Set(e);return n.delete(t),n})},onUpFromFirstItem:_t}):(0,Y.jsx)(ee,{options:pt,onChange:e=>{let t=Z[parseInt(e,10)];t&&s(t)},visibleOptionCount:wt,onCancel:o,onFocus:bt,defaultFocusValue:Oe?.id.toString(),layout:`expanded`,isDisabled:N===`search`||L,onUpFromFirstItem:_t}),(0,Y.jsx)(x,{paddingLeft:2,children:g.pending?(0,Y.jsxs)(S,{dimColor:!0,children:[`Press `,g.keyName,` again to exit`]}):N===`rename`?(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsxs)(C,{children:[(0,Y.jsx)(y,{shortcut:`Enter`,action:`save`}),(0,Y.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):F.status===`searching`?(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsxs)(C,{children:[(0,Y.jsx)(S,{children:`Searching with Claude…`}),(0,Y.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):L?(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsxs)(C,{children:[(0,Y.jsx)(y,{shortcut:`Enter`,action:`search`}),(0,Y.jsx)(y,{shortcut:`↓`,action:`skip`}),(0,Y.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})}):N===`search`?(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsxs)(C,{children:[(0,Y.jsx)(S,{children:`Type to Search`}),(0,Y.jsx)(y,{shortcut:`Enter`,action:`select`}),(0,Y.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`clear`})]})}):(0,Y.jsx)(S,{dimColor:!0,children:(0,Y.jsxs)(C,{children:[f&&(0,Y.jsx)(y,{shortcut:`Ctrl+A`,action:`show ${d?`current dir`:`all projects`}`}),T&&(0,Y.jsx)(y,{shortcut:`Ctrl+B`,action:`toggle branch`}),O&&(0,Y.jsx)(y,{shortcut:`Ctrl+W`,action:`show ${D?`current worktree`:`all worktrees`}`}),(0,Y.jsx)(y,{shortcut:`Ctrl+V`,action:`preview`}),(0,Y.jsx)(y,{shortcut:`Ctrl+R`,action:`rename`}),(0,Y.jsx)(S,{children:`Type to search`}),(0,Y.jsx)(n,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`}),mt()&&(0,Y.jsx)(S,{children:mt()})]})})})]})}function it(e){if(e.type!==`user`&&e.type!==`assistant`)return``;let t=`message`in e?e.message?.content:void 0;return t?typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(` `):``:``}function at(e){let t=(e.messages.length<=ut?e.messages:[...e.messages.slice(0,X),...e.messages.slice(-1e3)]).map(it).filter(Boolean).join(` `),n=`${[e.customTitle,e.summary,e.firstPrompt,e.gitBranch,e.tag,e.prNumber?`PR #${e.prNumber}`:void 0,e.prRepository].filter(Boolean).join(` `)} ${t}`.trim();return n.length>Z?n.slice(0,Z):n}function ot(e){let t=new Map;for(let n of e){let e=_(n);if(e){let r=t.get(e);r?r.push(n):t.set(e,[n])}}return t.forEach(e=>e.sort((e,t)=>new Date(t.modified).getTime()-new Date(e.modified).getTime())),t}function st(e){let t=new Set;for(let n of e)n.tag&&t.add(n.tag);return Array.from(t).sort((e,t)=>e.localeCompare(t))}var J,Y,ct,lt,ut,X,Z,dt,Q=e((()=>{w(),J=t(T(),1),ve(),Ie(),ze(),c(),E(),a(),Oe(),Me(),f(),Te(),Ee(),d(),p(),ne(),m(),Le(),Ve(),l(),K(),ae(),Ze(),Y=D(),ct=2,lt=4,ut=2e3,X=1e3,Z=5e4,dt=50}));function ft(e){if(e.type!==`user`&&e.type!==`assistant`)return``;let t=`message`in e?e.message?.content:void 0;return t?typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:`text`in e&&typeof e.text==`string`?e.text:``).filter(Boolean).join(` `):``:``}function pt(e){if(e.length===0)return``;let t=(e.length<=gt?e:[...e.slice(0,gt/2),...e.slice(-100/2)]).map(ft).filter(Boolean).join(` `).replace(/\s+/g,` `).trim();return t.length>ht?t.slice(0,ht)+`…`:t}function $(e,t){return!!(j(e).toLowerCase().includes(t)||e.customTitle?.toLowerCase().includes(t)||e.tag?.toLowerCase().includes(t)||e.gitBranch?.toLowerCase().includes(t)||e.summary?.toLowerCase().includes(t)||e.firstPrompt?.toLowerCase().includes(t)||e.messages&&e.messages.length>0&&pt(e.messages).toLowerCase().includes(t))}async function mt(e,t,n){if(!e.trim()||t.length===0)return[];let r=e.toLowerCase(),i=t.filter(e=>$(e,r)),a;if(i.length>=_t)a=i.slice(0,_t);else{let e=t.filter(e=>!$(e,r)),n=_t-i.length;a=[...i,...e.slice(0,n)]}k(`Agentic search: ${a.length}/${t.length} logs, query="${e}", matching: ${i.length}, with messages: ${A(a,e=>e.messages?.length>0)}`);let c=a.map(async e=>{if(o(e))try{return await s(e)}catch(t){return De(t),e}return e}),l=await Promise.all(c);k(`Agentic search: loaded ${A(l,e=>e.messages?.length>0)}/${a.length} logs with transcripts`);let u=`Sessions:
2
+ ${l.map((e,t)=>{let n=[`${t}:`],r=j(e);if(n.push(r),e.customTitle&&e.customTitle!==r&&n.push(`[custom title: ${e.customTitle}]`),e.tag&&n.push(`[tag: ${e.tag}]`),e.gitBranch&&n.push(`[branch: ${e.gitBranch}]`),e.summary&&n.push(`- Summary: ${e.summary}`),e.firstPrompt&&e.firstPrompt!==`No prompt`&&n.push(`- First message: ${e.firstPrompt.slice(0,300)}`),e.messages&&e.messages.length>0){let t=pt(e.messages);t&&n.push(`- Transcript: ${t}`)}return n.join(` `)}).join(`
3
+ `)}
4
+
5
+ Search query: "${e}"
6
+
7
+ Find the sessions that are most relevant to this query.`;k(`Agentic search prompt (first 500 chars): ${u.slice(0,500)}...`);try{let e=P();k(`Agentic search using model: ${e}`);let t=(await v({model:e,system:vt,messages:[{role:`user`,content:u}],signal:n,querySource:`session_search`})).content.find(e=>e.type===`text`);if(!t||t.type!==`text`)return k(`No text content in agentic search response`),[];k(`Agentic search response: ${t.text}`);let r=t.text.match(/\{[\s\S]*\}/);if(!r)return k(`Could not find JSON in agentic search response`),[];let i=(O(r[0]).relevant_indices||[]).filter(e=>e>=0&&e<l.length).map(e=>l[e]);return k(`Agentic search found ${i.length} relevant sessions`),i}catch(e){return De(e),k(`Agentic search error: ${e}`),[]}}var ht,gt,_t,vt,yt=e((()=>{Ce(),xe(),Ee(),N(),d(),h(),Se(),ht=2e3,gt=100,_t=100,vt=`Your goal is to find relevant sessions based on a user's search query.
8
+
9
+ You will be given a list of sessions with their metadata and a search query. Identify which sessions are most relevant to the query.
10
+
11
+ Each session may include:
12
+ - Title (display name or custom title)
13
+ - Tag (user-assigned category, shown as [tag: name] - users tag sessions with /tag command to categorize them)
14
+ - Branch (git branch name, shown as [branch: name])
15
+ - Summary (AI-generated summary)
16
+ - First message (beginning of the conversation)
17
+ - Transcript (excerpt of conversation content)
18
+
19
+ IMPORTANT: Tags are user-assigned labels that indicate the session's topic or category. If the query matches a tag exactly or partially, those sessions should be highly prioritized.
20
+
21
+ For each session, consider (in order of priority):
22
+ 1. Exact tag matches (highest priority - user explicitly categorized this session)
23
+ 2. Partial tag matches or tag-related terms
24
+ 3. Title matches (custom titles or first message content)
25
+ 4. Branch name matches
26
+ 5. Summary and transcript content matches
27
+ 6. Semantic similarity and related concepts
28
+
29
+ CRITICAL: Be VERY inclusive in your matching. Include sessions that:
30
+ - Contain the query term anywhere in any field
31
+ - Are semantically related to the query (e.g., "testing" matches sessions about "tests", "unit tests", "QA", etc.)
32
+ - Discuss topics that could be related to the query
33
+ - Have transcripts that mention the concept even in passing
34
+
35
+ When in doubt, INCLUDE the session. It's better to return too many results than too few. The user can easily scan through results, but missing relevant sessions is frustrating.
36
+
37
+ Return sessions ordered by relevance (most relevant first). If truly no sessions have ANY connection to the query, return an empty array - but this should be rare.
38
+
39
+ Respond with ONLY the JSON object, no markdown formatting:
40
+ {"relevant_indices": [2, 5, 0]}`}));function bt(e,t){let n=ye();if(!t||!e.projectPath||e.projectPath===n)return{isCrossProject:!1};let r=_(e);return{isCrossProject:!0,isSameRepoWorktree:!1,command:`cd ${Ne([e.projectPath])} && claude --resume ${r}`,projectPath:e.projectPath}}var xt=e((()=>{ve(),Pe(),d()}));export{rt as a,yt as i,xt as n,Q as o,mt as r,bt as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{n as r,t as i}from"./axios-DaWTGg7G.js";import{d as a,h as o}from"./config-9rLTDOYW.js";import{o as s,s as c}from"./log-27kCA_9u.js";import{W as l,_ as u,ai as d,r as f,si as p,z as m}from"./model-CDnVaVDR.js";import{Z as h,et as g}from"./esm-BkOWaWVb.js";import{f as _,p as v}from"./firstPartyEventLogger-aFhcruXA.js";import{createHash as y}from"crypto";function b(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}async function x(){if(N.length===0)return;let e=N;N=[];try{await r.post(E,e,{headers:{"Content-Type":`application/json`,"DD-API-KEY":D},timeout:A})}catch(e){c(e)}}function S(){P||(P=setTimeout(()=>{P=null,x()},T()).unref())}async function C(){P&&(clearTimeout(P),P=null),await x()}async function w(e,t){if(d()!==`firstParty`)return;let n=F;if(n===null&&(n=await I()),!(!n||!j.has(e)))try{let{envContext:n,...r}=await h({model:t.model,betas:t.betas}),i={...r,...n,...t,userBucket:R()};if(typeof i.toolName==`string`&&i.toolName.startsWith(`mcp__`)&&(i.toolName=`mcp`),typeof i.model==`string`){let e=f(i.model.replace(/\[1m]$/i,``));i.model=e in m?e:`other`}if(typeof i.version==`string`&&(i.version=i.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,`$1`)),i.status!==void 0&&i.status!==null){let e=String(i.status);i.http_status=e;let t=e.charAt(0);t>=`1`&&t<=`5`&&(i.http_status_range=`${t}xx`),delete i.status}let a=i,o={ddsource:`nodejs`,ddtags:[`event:${e}`,...M.filter(e=>a[e]!==void 0&&a[e]!==null).map(e=>`${b(e)}:${a[e]}`)].join(`,`),message:e,service:`workmate`,hostname:`workmate`,env:process.env.USER_TYPE};for(let[e,t]of Object.entries(i))t!=null&&(o[b(e)]=t);N.push(o),N.length>=k?(P&&(clearTimeout(P),P=null),x()):S()}catch(e){c(e)}}function T(){return parseInt(process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||``,10)||O}var E,D,O,k,A,j,M,N,P,F,I,L,R,z=e((()=>{i(),n(),o(),s(),u(),p(),l(),_(),g(),E=process.env.DATADOG_LOGS_ENDPOINT??``,D=process.env.DATADOG_API_KEY??``,O=15e3,k=100,A=5e3,j=new Set(`tengu_api_error.tengu_api_success.tengu_cancel.tengu_compact_failed.tengu_exit.tengu_flicker.tengu_init.tengu_model_fallback_triggered.tengu_oauth_error.tengu_oauth_success.tengu_oauth_token_refresh_failure.tengu_oauth_token_refresh_success.tengu_oauth_token_refresh_lock_acquiring.tengu_oauth_token_refresh_lock_acquired.tengu_oauth_token_refresh_starting.tengu_oauth_token_refresh_completed.tengu_oauth_token_refresh_lock_releasing.tengu_oauth_token_refresh_lock_released.tengu_query_error.tengu_session_file_read.tengu_started.tengu_tool_use_error.tengu_tool_use_granted_in_prompt_permanent.tengu_tool_use_granted_in_prompt_temporary.tengu_tool_use_rejected_in_prompt.tengu_tool_use_success.tengu_uncaught_exception.tengu_unhandled_rejection.tengu_voice_recording_started.tengu_voice_toggled.tengu_team_mem_sync_pull.tengu_team_mem_sync_push.tengu_team_mem_sync_started.tengu_team_mem_entries_capped`.split(`.`)),M=[`arch`,`clientType`,`errorType`,`http_status_range`,`http_status`,`model`,`platform`,`provider`,`skillMode`,`subscriptionType`,`toolName`,`userBucket`,`userType`,`version`,`versionBase`],N=[],P=null,F=null,I=t(async()=>{if(v()||!E||!D)return F=!1,!1;try{return F=!0,!0}catch(e){return c(e),F=!1,!1}}),L=30,R=t(()=>{let e=a(),t=y(`sha256`).update(e).digest(`hex`);return parseInt(t.slice(0,8),16)%L})}));export{C as n,w as r,z as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{n as r,t as i}from"./axios-DaWTGg7G.js";import{d as a,h as o}from"./config-9rLTDOYW.js";import{o as s,s as c}from"./log-27kCA_9u.js";import{W as l,_ as u,ai as d,r as f,si as p,z as m}from"./model-C29_32BD.js";import{Z as h,et as g}from"./esm-CtQkOk5D.js";import{f as _,p as v}from"./firstPartyEventLogger-1RTgXHSz.js";import{createHash as y}from"crypto";function b(e){return e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}async function x(){if(N.length===0)return;let e=N;N=[];try{await r.post(E,e,{headers:{"Content-Type":`application/json`,"DD-API-KEY":D},timeout:A})}catch(e){c(e)}}function S(){P||(P=setTimeout(()=>{P=null,x()},T()).unref())}async function C(){P&&(clearTimeout(P),P=null),await x()}async function w(e,t){if(d()!==`firstParty`)return;let n=F;if(n===null&&(n=await I()),!(!n||!j.has(e)))try{let{envContext:n,...r}=await h({model:t.model,betas:t.betas}),i={...r,...n,...t,userBucket:R()};if(typeof i.toolName==`string`&&i.toolName.startsWith(`mcp__`)&&(i.toolName=`mcp`),typeof i.model==`string`){let e=f(i.model.replace(/\[1m]$/i,``));i.model=e in m?e:`other`}if(typeof i.version==`string`&&(i.version=i.version.replace(/^(\d+\.\d+\.\d+-dev\.\d{8})\.t\d+\.sha[a-f0-9]+$/,`$1`)),i.status!==void 0&&i.status!==null){let e=String(i.status);i.http_status=e;let t=e.charAt(0);t>=`1`&&t<=`5`&&(i.http_status_range=`${t}xx`),delete i.status}let a=i,o={ddsource:`nodejs`,ddtags:[`event:${e}`,...M.filter(e=>a[e]!==void 0&&a[e]!==null).map(e=>`${b(e)}:${a[e]}`)].join(`,`),message:e,service:`workmate`,hostname:`workmate`,env:process.env.USER_TYPE};for(let[e,t]of Object.entries(i))t!=null&&(o[b(e)]=t);N.push(o),N.length>=k?(P&&(clearTimeout(P),P=null),x()):S()}catch(e){c(e)}}function T(){return parseInt(process.env.CLAUDE_CODE_DATADOG_FLUSH_INTERVAL_MS||``,10)||O}var E,D,O,k,A,j,M,N,P,F,I,L,R,z=e((()=>{i(),n(),o(),s(),u(),p(),l(),_(),g(),E=process.env.DATADOG_LOGS_ENDPOINT??``,D=process.env.DATADOG_API_KEY??``,O=15e3,k=100,A=5e3,j=new Set(`tengu_api_error.tengu_api_success.tengu_cancel.tengu_compact_failed.tengu_exit.tengu_flicker.tengu_init.tengu_model_fallback_triggered.tengu_oauth_error.tengu_oauth_success.tengu_oauth_token_refresh_failure.tengu_oauth_token_refresh_success.tengu_oauth_token_refresh_lock_acquiring.tengu_oauth_token_refresh_lock_acquired.tengu_oauth_token_refresh_starting.tengu_oauth_token_refresh_completed.tengu_oauth_token_refresh_lock_releasing.tengu_oauth_token_refresh_lock_released.tengu_query_error.tengu_session_file_read.tengu_started.tengu_tool_use_error.tengu_tool_use_granted_in_prompt_permanent.tengu_tool_use_granted_in_prompt_temporary.tengu_tool_use_rejected_in_prompt.tengu_tool_use_success.tengu_uncaught_exception.tengu_unhandled_rejection.tengu_voice_recording_started.tengu_voice_toggled.tengu_team_mem_sync_pull.tengu_team_mem_sync_push.tengu_team_mem_sync_started.tengu_team_mem_entries_capped`.split(`.`)),M=[`arch`,`clientType`,`errorType`,`http_status_range`,`http_status`,`model`,`platform`,`provider`,`skillMode`,`subscriptionType`,`toolName`,`userBucket`,`userType`,`version`,`versionBase`],N=[],P=null,F=null,I=t(async()=>{if(v()||!E||!D)return F=!1,!1;try{return F=!0,!0}catch(e){return c(e),F=!1,!1}}),L=30,R=t(()=>{let e=a(),t=y(`sha256`).update(e).digest(`hex`);return parseInt(t.slice(0,8),16)%L})}));export{C as n,w as r,z as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";var n,r;e((()=>{n=t(),r=async(e,t)=>{let{DiffDialog:r}=await import(`./DiffDialog-CRWtQ1R5.js`);return(0,n.jsx)(r,{messages:t.messages,onDone:e})}}))();export{r as call};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";var n,r;e((()=>{n=t(),r=async(e,t)=>{let{DiffDialog:r}=await import(`./DiffDialog-mQ-5_TSv.js`);return(0,n.jsx)(r,{messages:t.messages,onDone:e})}}))();export{r as call};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Doctor-BC6IuQhd.js";var i,a;e((()=>{n(),i=t(),a=(e,t,n)=>Promise.resolve((0,i.jsx)(r,{onDone:e}))}))();export{a as call};