very-happy-cli 0.2.178 → 0.2.180

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 (217) hide show
  1. package/dist/{AcpBackend-DCQXHRzT.mjs → AcpBackend-B8Zi30Zh.mjs} +135 -16
  2. package/dist/{AcpBackend-CDkAQXYf.cjs → AcpBackend-DfRDtMcG.cjs} +135 -16
  3. package/dist/{AcpSessionManager-DckmUZza.cjs → AcpSessionManager-CASKOnOj.cjs} +38 -4
  4. package/dist/{AcpSessionManager-BXrQcqwC.mjs → AcpSessionManager-i8Rab0xT.mjs} +38 -4
  5. package/dist/{BasePermissionHandler-BVlrEhIi.mjs → BasePermissionHandler-26fKbRCm.mjs} +5 -2
  6. package/dist/{BasePermissionHandler-DyLmKKtO.cjs → BasePermissionHandler-BlM_tfej.cjs} +5 -2
  7. package/dist/acpSessionResume-B9l54P-X.mjs +67 -0
  8. package/dist/acpSessionResume-CR5pmgVo.cjs +74 -0
  9. package/dist/{agentHome-CEp9RMyK.cjs → agentHome-C7Sb7-Tz.cjs} +4 -4
  10. package/dist/{agentHome-C1xi37as.mjs → agentHome-CmGy0NWv.mjs} +4 -4
  11. package/dist/{api-JANhFdZV.cjs → api-DM7b1OKj.cjs} +38 -262
  12. package/dist/{api-Dib0dmqC.mjs → api-Hov8p7CA.mjs} +32 -256
  13. package/dist/{apiMachine-DNTJidYH.mjs → apiMachine-CwGEhQDT.mjs} +62 -15
  14. package/dist/{apiMachine-QhK-sKcr.cjs → apiMachine-DkGRj-Ai.cjs} +64 -17
  15. package/dist/{attachmentContent-bpQTBJ0y.cjs → attachmentContent-CEm13_gF.cjs} +4 -4
  16. package/dist/{attachmentContent-DkkdpSSJ.mjs → attachmentContent-CIn4iPEk.mjs} +2 -2
  17. package/dist/{auth-BRjd2esb.mjs → auth-BG1DY0gj.mjs} +5 -5
  18. package/dist/{auth-DgIV0Cvt.cjs → auth-CBXnm-Mj.cjs} +5 -5
  19. package/dist/{auth-omWDtgR8.cjs → auth-Dawj7pP5.cjs} +8 -8
  20. package/dist/{auth-DNct7VUi.mjs → auth-rggxMpEE.mjs} +8 -8
  21. package/dist/{auto-DKGFOJBo.mjs → auto-CXXLXGeL.mjs} +19 -18
  22. package/dist/{auto-CI16FZmX.cjs → auto-CbYOfoPS.cjs} +19 -18
  23. package/dist/{backgroundTaskActivity-BVwJBl02.mjs → backgroundTaskActivity-8PdPxrvy.mjs} +1 -1
  24. package/dist/{bootstrap-DCQ87Aan.cjs → bootstrap-DoA7okld.cjs} +2 -2
  25. package/dist/{bootstrap-BUagGC_-.mjs → bootstrap-Dt5I1SOl.mjs} +2 -2
  26. package/dist/{browser-Dj_DYQEh.mjs → browser-DUNetFT4.mjs} +1 -1
  27. package/dist/{browser-CSKhc0Bl.cjs → browser-DZ6qRtfH.cjs} +1 -1
  28. package/dist/{claudeCliPath-U4HHmV4r.cjs → claudeCliPath-GaP3UUz1.cjs} +1 -1
  29. package/dist/{claudeLocal-CdIVnOZp.cjs → claudeLocal--DNyMOSv.cjs} +8 -7
  30. package/dist/{claudeLocal-CCCvAeMd.mjs → claudeLocal-OHWQigCl.mjs} +6 -5
  31. package/dist/{claudeLocalLauncher-BmrpaRYJ.mjs → claudeLocalLauncher-BStvfa7M.mjs} +11 -10
  32. package/dist/{claudeLocalLauncher-21-xh5gc.cjs → claudeLocalLauncher-BhvPbcyH.cjs} +13 -12
  33. package/dist/{claudeSessionFork-kYCP1IJB.cjs → claudeSessionFork-Be16vzGc.cjs} +1 -1
  34. package/dist/{claudeSessionFork-DvxMKAmY.mjs → claudeSessionFork-GAVWhiKG.mjs} +1 -1
  35. package/dist/{client-C4zKGjiJ.cjs → client-BWjaHKtj.cjs} +2 -2
  36. package/dist/client-Ca5Pcgy_.mjs +71 -0
  37. package/dist/{client-CnlkkrZO.mjs → client-CnB7kRCT.mjs} +2 -2
  38. package/dist/{client-BTX9hsbr.mjs → client-D4uPb1uu.mjs} +3 -3
  39. package/dist/client-DJplzPjD.cjs +76 -0
  40. package/dist/{client-Dnza1hgN.cjs → client-D_loZ9IK.cjs} +3 -3
  41. package/dist/codex/happyMcpStdioBridge.cjs +24 -15
  42. package/dist/codex/happyMcpStdioBridge.mjs +25 -16
  43. package/dist/{codexAppServerClient-DvkpQgyv.mjs → codexAppServerClient-CO4G6OS4.mjs} +3 -3
  44. package/dist/{codexAppServerClient-CRlBWGn3.cjs → codexAppServerClient-PE-12AsW.cjs} +3 -3
  45. package/dist/{codexCommand-DzxIWXIT.cjs → codexCommand-BNoD1t1C.cjs} +127 -116
  46. package/dist/{codexCommand-BxjogBzU.mjs → codexCommand-B_xUH79E.mjs} +77 -66
  47. package/dist/{codexTermination-C28FzlLb.cjs → codexTermination-BmBbizFK.cjs} +7 -2
  48. package/dist/{codexTermination-ySDNMEhd.mjs → codexTermination-Dx48ma6e.mjs} +7 -2
  49. package/dist/{config-BFB5uJ4t.cjs → config-CtwEUxUP.cjs} +26 -26
  50. package/dist/{config-DwfEpFr3.mjs → config-DSu0Blos.mjs} +3 -3
  51. package/dist/{configuration-4TGMrjul.cjs → configuration-CYO-kPOS.cjs} +1 -1
  52. package/dist/{configuration-DVrb61aY.mjs → configuration-PxzEJumr.mjs} +1 -1
  53. package/dist/{connect-C7FPY0PI.mjs → connect-BQrg3TB6.mjs} +15 -15
  54. package/dist/{connect-QH2VJGBG.cjs → connect-Dq7wndzR.cjs} +28 -28
  55. package/dist/{context-JoKu0V54.cjs → context-6TP-iz_c.cjs} +1 -1
  56. package/dist/{context-B3XPVJlj.mjs → context-CJGRRGWW.mjs} +1 -1
  57. package/dist/{controlClient-BTaZlbC6.cjs → controlClient-Bqv5v5OM.cjs} +3 -3
  58. package/dist/{controlClient-BYKyGyxj.mjs → controlClient-DoeYovwP.mjs} +4 -4
  59. package/dist/{createSessionMetadata-8Fuj2-IV.mjs → createSessionMetadata-DDIChCx8.mjs} +2 -2
  60. package/dist/{createSessionMetadata-B2NynaWZ.cjs → createSessionMetadata-xz767pcG.cjs} +3 -3
  61. package/dist/{defaultPermissionMode-BEWCqJU-.cjs → defaultPermissionMode-PkZGsQDk.cjs} +2 -2
  62. package/dist/{defaultPermissionMode-B8kJG9uI.mjs → defaultPermissionMode-i5KzdK09.mjs} +2 -2
  63. package/dist/{detectCLI-DR9ZaN6B.cjs → detectCLI-BuYR_Qxe.cjs} +4 -4
  64. package/dist/{deterministicJson-C5ZwZ7hu.mjs → deterministicJson-CTEJDqtS.mjs} +217 -12
  65. package/dist/{deterministicJson-BjNQsAjO.cjs → deterministicJson-xqA6DaOm.cjs} +222 -16
  66. package/dist/{doctor-BshRnjLi.cjs → doctor-BrgSlfXn.cjs} +9 -9
  67. package/dist/{doctor-0BiGwJXk.mjs → doctor-IctjVh9T.mjs} +8 -8
  68. package/dist/{doctorReadiness-BCZGcN0a.cjs → doctorReadiness-Dl6yRQCy.cjs} +1 -1
  69. package/dist/{downloadTarget-BN5vZt3K.cjs → downloadTarget-CEb9che-.cjs} +6 -6
  70. package/dist/{downloadTarget-DJPwAZlu.mjs → downloadTarget-jbOz1egC.mjs} +6 -6
  71. package/dist/{ensureDaemonRunning-C5QfToCe.cjs → ensureDaemonRunning-D-HyjGIX.cjs} +6 -6
  72. package/dist/{ensureDaemonRunning-CSmb_mqt.mjs → ensureDaemonRunning-b1e8LCSM.mjs} +5 -5
  73. package/dist/{handleResumeCommand-BwnUZmbo.cjs → handleResumeCommand-BvWVuRwH.cjs} +23 -7
  74. package/dist/{handleResumeCommand-CgjpsdDe.mjs → handleResumeCommand-DpaZvm2c.mjs} +22 -6
  75. package/dist/{index-piJPsTsm.cjs → index-B2p2Mut7.cjs} +259 -53
  76. package/dist/{index-BehVbAsA.mjs → index-BUNnpGFF.mjs} +256 -50
  77. package/dist/{index-Bvldtdny.mjs → index-Bsvbgh9e.mjs} +4 -4
  78. package/dist/{index-BYOZ_8WZ.cjs → index-C64Ufj4D.cjs} +4 -4
  79. package/dist/{index-Clqlu17M.mjs → index-C6Vn5Eac.mjs} +155 -34
  80. package/dist/index-CMf5VbzG.mjs +18 -0
  81. package/dist/index-DmTlDRSL.cjs +24 -0
  82. package/dist/{index-_l1Sdmbi.cjs → index-Dv0Q48P3.cjs} +156 -33
  83. package/dist/{index-BRClDe07.cjs → index-F2UejqYs.cjs} +3 -3
  84. package/dist/{index-BYgfern_.mjs → index-wCbtF4BK.mjs} +3 -3
  85. package/dist/index.cjs +2 -2
  86. package/dist/index.mjs +2 -2
  87. package/dist/{install-BdvKiOQw.mjs → install-BX3lv3NO.mjs} +1 -1
  88. package/dist/{install-Cf6AFSWC.cjs → install-BXvf2E3o.cjs} +1 -1
  89. package/dist/{install-TO4taKW7.cjs → install-C0ANcEAW.cjs} +7 -7
  90. package/dist/{install-fYWHrPcC.mjs → install-CdzSV7qO.mjs} +3 -3
  91. package/dist/{installPiTools-BKnXjrVu.cjs → installPiTools-CL_axh_6.cjs} +1 -1
  92. package/dist/{installTerminalHooks-BQZbvxsZ.cjs → installTerminalHooks-BETLKAtd.cjs} +3 -3
  93. package/dist/lib.cjs +14 -14
  94. package/dist/lib.d.cts +239 -2
  95. package/dist/lib.d.mts +239 -2
  96. package/dist/lib.mjs +14 -14
  97. package/dist/{lidState-BeOwj6eW.cjs → lidState-DWGnm2H4.cjs} +1 -1
  98. package/dist/{lidState-DNMlIhX0.mjs → lidState-bBrmaQd2.mjs} +1 -1
  99. package/dist/{localHappyAgentAuth-Br-mgogg.cjs → localHappyAgentAuth-DZHQnIW9.cjs} +1 -1
  100. package/dist/{localHappyAgentAuth-BezKSFDi.mjs → localHappyAgentAuth-Dn1jYDpt.mjs} +1 -1
  101. package/dist/{logger--vAVtXB_.mjs → logger-BUngm5Xg.mjs} +2 -2
  102. package/dist/{logger-DXTWlPzP.cjs → logger-CphW5nUE.cjs} +2 -2
  103. package/dist/machineMetadata-BQm9YTcI.cjs +79 -0
  104. package/dist/machineMetadata-BXN_bKU3.mjs +68 -0
  105. package/dist/{main-DoMFJ2Cl.cjs → main-B2UV51nK.cjs} +112 -132
  106. package/dist/{main-CshDb5-1.mjs → main-DGkdYfEq.mjs} +106 -126
  107. package/dist/{mcp-pNc1EbQf.cjs → mcp-BFvAEIRz.cjs} +15 -15
  108. package/dist/{mcp-DKT_lrvQ.mjs → mcp-CbTtbs0f.mjs} +15 -15
  109. package/dist/{mirrorProtocol-6IFGPpjJ.mjs → mirrorProtocol-BR4luBC0.mjs} +148 -7
  110. package/dist/{mirrorProtocol-qKflWTX_.cjs → mirrorProtocol-HKPivs5o.cjs} +150 -4
  111. package/dist/{package-B7B03ejW.mjs → package-7Ld1YMhh.mjs} +8 -7
  112. package/dist/{package-DY4zTbKS.cjs → package-KhLqBDX9.cjs} +8 -7
  113. package/dist/panels-C7IVqpJk.mjs +137 -0
  114. package/dist/panels-Njf6GelF.cjs +142 -0
  115. package/dist/{peerTools-3R9RUARX.mjs → peerTools-BOlDRyhi.mjs} +60 -10
  116. package/dist/{peerTools-iy3_6Yc5.cjs → peerTools-DQNlrcqM.cjs} +60 -9
  117. package/dist/{persistence-BfX72dne.cjs → persistence-9BMYspxG.cjs} +2 -2
  118. package/dist/{persistence-DTk4sNpd.mjs → persistence-BFUOHW5h.mjs} +3 -3
  119. package/dist/{piRunnerArgs-CRQVR9o-.cjs → piRunnerArgs-DGaq6VYM.cjs} +8 -2
  120. package/dist/{piRunnerArgs-AT8QJY7x.mjs → piRunnerArgs-H2pgpA5z.mjs} +7 -1
  121. package/dist/{piRuntime-BHRT5MKO.cjs → piRuntime-CT5xv_3h.cjs} +2 -2
  122. package/dist/{piRuntime-E44qTVQ4.mjs → piRuntime-CdN0JAsa.mjs} +2 -2
  123. package/dist/{piTerminal-hI4WFdWm.cjs → piTerminal-0FBtXTHK.cjs} +18 -18
  124. package/dist/{piTerminal-De8nbciM.mjs → piTerminal-C4m9YXAV.mjs} +18 -18
  125. package/dist/processTreeSnapshot-CuLJDNC-.mjs +101 -0
  126. package/dist/processTreeSnapshot-mDbnuojn.cjs +105 -0
  127. package/dist/projectPath-C3ioB4Bu.cjs +13 -0
  128. package/dist/prompt-BOouDaTM.mjs +99 -0
  129. package/dist/prompt-lgF9IE82.cjs +105 -0
  130. package/dist/{attachmentLimits-UyFn8fkQ.mjs → pushNotifications-DCiBEVeC.mjs} +307 -3
  131. package/dist/{attachmentLimits-SqeAHrVC.cjs → pushNotifications-DI92havG.cjs} +308 -2
  132. package/dist/{index-DFPT4HOO.cjs → query-BETKBrnz.cjs} +25 -5
  133. package/dist/{index-CEjJnq05.mjs → query-ywZbQUzR.mjs} +26 -3
  134. package/dist/{rateLimitWindows-XrJiiBpU.mjs → rateLimitWindows-BkfuUB1a.mjs} +1 -1
  135. package/dist/{rateLimitWindows-Czb7_7cK.cjs → rateLimitWindows-YRIYVdo4.cjs} +1 -1
  136. package/dist/{registerCommonHandlers-C0_fyBQ0.cjs → registerCommonHandlers-C7a_dUWs.cjs} +30 -30
  137. package/dist/{registerCommonHandlers-CvIedVRf.mjs → registerCommonHandlers-CTkCvjxt.mjs} +2 -2
  138. package/dist/{registerKillSessionHandler-DYl7l4Ts.cjs → registerKillSessionHandler-CIsvBrVe.cjs} +6 -6
  139. package/dist/{registerKillSessionHandler-gwJ5lTf0.mjs → registerKillSessionHandler-CaqqRYq6.mjs} +6 -6
  140. package/dist/{remoteSessionClient-BRTIOX5b.cjs → remoteSessionClient-D843fkzL.cjs} +5 -5
  141. package/dist/{remoteSessionClient-DRb2Jr5s.mjs → remoteSessionClient-PP-mOKmw.mjs} +5 -5
  142. package/dist/{reportProgressTool-B9nCzbkL.cjs → reportProgressTool-14AXr959.cjs} +84 -2
  143. package/dist/{reportProgressTool-D5tEoXMW.mjs → reportProgressTool-ZOCNjWHr.mjs} +82 -3
  144. package/dist/{resources-JDPugcDq.cjs → resources-CvIlkzpP.cjs} +30 -0
  145. package/dist/{resources-BdFBQi8r.mjs → resources-y9jfyO-_.mjs} +30 -0
  146. package/dist/{run-CKe_WeLW.cjs → run-CAOCYYfT.cjs} +2806 -110
  147. package/dist/{run-BQ_FGaOL.mjs → run-Dajw2E5j.mjs} +2787 -91
  148. package/dist/{runClaude-zrrNcQC_.mjs → runClaude-C6oxWYbp.mjs} +49 -47
  149. package/dist/{runClaude-MHI5IKM-.cjs → runClaude-CRRKt-tm.cjs} +50 -48
  150. package/dist/{runClaudeDeps-RRw-Nusc.cjs → runClaudeDeps-B1ysqTvx.cjs} +310 -237
  151. package/dist/{runClaudeDeps-CVBCokOS.mjs → runClaudeDeps-BcZ68cX3.mjs} +297 -226
  152. package/dist/{runGemini-kipag2ag.mjs → runGemini-D7yKc4wD.mjs} +61 -55
  153. package/dist/{runGemini-D7Lg9yCr.cjs → runGemini-DtKFXqf-.cjs} +89 -83
  154. package/dist/{runOpenClaw-C_lRY3Do.mjs → runOpenClaw-C8ilyLP9.mjs} +19 -19
  155. package/dist/{runOpenClaw-DCcQ0L2N.cjs → runOpenClaw-Cq29mryb.cjs} +20 -20
  156. package/dist/{sandbox-BSyXFVFp.mjs → sandbox-CbCutma4.mjs} +4 -4
  157. package/dist/{sandbox-dMwPTmjm.cjs → sandbox-gIj-EuF4.cjs} +4 -4
  158. package/dist/{selfCheck-DkzDDUsE.cjs → selfCheck-BTGBVthv.cjs} +39 -38
  159. package/dist/selfCheck-Smt-5Xiq.mjs +85 -0
  160. package/dist/{send-dxC0miIA.cjs → send-CZf5lLw_.cjs} +8 -8
  161. package/dist/{send-C-k9nsd3.mjs → send-YZRMQvMJ.mjs} +9 -9
  162. package/dist/{server-DxoTYNlw.mjs → server-BqwXRzFZ.mjs} +4 -4
  163. package/dist/{server-B-W6P7Qr.cjs → server-CknFq6xG.cjs} +6 -6
  164. package/dist/sessionExitLifecycle-CzkLIgNZ.mjs +142 -0
  165. package/dist/sessionExitLifecycle-DFltxXU8.cjs +148 -0
  166. package/dist/{sessionLock-DWX6BbiU.cjs → sessionLock-DRZUcKHT.cjs} +38 -5
  167. package/dist/{sessionLock-DBdtZGOL.mjs → sessionLock-nBXdJxJm.mjs} +36 -5
  168. package/dist/{sessionOps-BAnr7n8t.cjs → sessionOps-BrGiU9-s.cjs} +10 -5
  169. package/dist/{sessionOps-BVoXe12O.mjs → sessionOps-C58iDeD5.mjs} +11 -6
  170. package/dist/{sessionScanner-BtxoeluY.mjs → sessionScanner-Bm57LEXe.mjs} +3 -3
  171. package/dist/{sessionScanner-CDOYsEUD.cjs → sessionScanner-CaO8bLaG.cjs} +3 -3
  172. package/dist/{sessions-C3sZJkzI.mjs → sessions-BXyBHo8n.mjs} +40 -18
  173. package/dist/{sessions-hAitoN-m.cjs → sessions-uzqPCc37.cjs} +39 -16
  174. package/dist/{setupOfflineReconnection-_eD4cuUT.mjs → setupOfflineReconnection-1Qlek3wl.mjs} +2 -2
  175. package/dist/{setupOfflineReconnection-C2EeYTFH.cjs → setupOfflineReconnection-DvvVX3TB.cjs} +2 -2
  176. package/dist/{spawn-Bc9v7pIf.cjs → spawn-DBkodJEO.cjs} +49 -18
  177. package/dist/{spawn-qNrB2CD_.mjs → spawn-vn93PhYL.mjs} +49 -18
  178. package/dist/spawnAgents-CgPMWexP.mjs +79 -0
  179. package/dist/{spawnAgents-BVEaz35W.cjs → spawnAgents-DLNMlhWJ.cjs} +37 -1
  180. package/dist/{spawnHappyCLI-C2stUioM.mjs → spawnHappyCLI-BjFZc_7V.mjs} +1 -1
  181. package/dist/{spawnHappyCLI-fzUagkKV.cjs → spawnHappyCLI-DnUZv0X2.cjs} +2 -2
  182. package/dist/{specialCommands-BJ-nqY4s.cjs → specialCommands-BRufxlqe.cjs} +3 -3
  183. package/dist/{specialCommands-C6W-rVyh.mjs → specialCommands-D3ND9bdg.mjs} +3 -3
  184. package/dist/{startFileWatcher-Bqlqjt93.cjs → startFileWatcher-D9cYzZOq.cjs} +1 -1
  185. package/dist/{startFileWatcher-CR09Snmz.mjs → startFileWatcher-DXJ7yB5v.mjs} +1 -1
  186. package/dist/startupSessionCreate-kdr3m1uX.cjs +26 -0
  187. package/dist/startupSessionCreate-uZ6BM0ty.mjs +24 -0
  188. package/dist/{streamRelay-CJoMk_d2.mjs → streamRelay-DnMCMMfV.mjs} +1 -1
  189. package/dist/{streamRelay-9kBPpbvU.cjs → streamRelay-Dy6amlzx.cjs} +1 -1
  190. package/dist/{sync-Dhmtk66S.cjs → sync-Bn-idAoy.cjs} +1 -1
  191. package/dist/{sync-DbW07iQS.mjs → sync-BvVhDO40.mjs} +1 -1
  192. package/dist/{systemPrompt-CQcuUmVp.mjs → systemPrompt-CIZcJuJF.mjs} +4 -3
  193. package/dist/{systemPrompt-3PYi3EUY.cjs → systemPrompt-DlyEk35T.cjs} +4 -3
  194. package/dist/{teams-DpxLcUU_.cjs → teams-BLeRpDxv.cjs} +8 -8
  195. package/dist/{teams-CwF4Z2fA.mjs → teams-DLY3B5yi.mjs} +8 -8
  196. package/dist/{time-A6zR3Iy6.cjs → time-Cjv0zxQO.cjs} +1 -1
  197. package/dist/{time-BuGWTVP6.mjs → time-D3ETL7Jb.mjs} +1 -1
  198. package/dist/{titleGenerator-D26gvNaS.cjs → titleGenerator-Cgp5ihFb.cjs} +10 -9
  199. package/dist/{titleGenerator-BGEzNWC9.mjs → titleGenerator-Uzbd4utr.mjs} +9 -8
  200. package/dist/{todo-DrZc76H5.mjs → todo-C9Ga-oEM.mjs} +6 -6
  201. package/dist/{todo-73g3NCIO.cjs → todo-pOMcEECE.cjs} +6 -6
  202. package/dist/{tools-CxJp4T1T.cjs → tools-BL7Byl_x.cjs} +1 -1
  203. package/dist/{tools-BtsrQnNS.mjs → tools-Cho7iIWf.mjs} +1 -1
  204. package/dist/{uninstall-DWNYvewQ.cjs → uninstall-CbayEVoV.cjs} +6 -6
  205. package/dist/{uninstall-DOb2mTwV.mjs → uninstall-CvZHVY9C.mjs} +3 -3
  206. package/dist/webPanels-B2_C2-3g.mjs +49 -0
  207. package/dist/webPanels-FCgFKvVe.cjs +53 -0
  208. package/package.json +8 -7
  209. package/dist/machineMetadata-B1H9gNbN.mjs +0 -39
  210. package/dist/machineMetadata-DcUupMje.cjs +0 -42
  211. package/dist/messageBuffer-BWlGgR3A.mjs +0 -71
  212. package/dist/messageBuffer-fJMH6uY8.cjs +0 -73
  213. package/dist/projectPath-ChLhdOyt.cjs +0 -13
  214. package/dist/selfCheck-CF7XGJPb.mjs +0 -84
  215. package/dist/sessionModeFile-ByLbXTbg.mjs +0 -32
  216. package/dist/sessionModeFile-CLLdidiJ.cjs +0 -36
  217. package/dist/spawnAgents-Bw6j4tqz.mjs +0 -45
@@ -1,25 +1,26 @@
1
1
  'use strict';
2
2
 
3
- var mirrorProtocol = require('./mirrorProtocol-qKflWTX_.cjs');
4
- var piRunnerArgs = require('./piRunnerArgs-CRQVR9o-.cjs');
3
+ var mirrorProtocol = require('./mirrorProtocol-HKPivs5o.cjs');
4
+ var piRunnerArgs = require('./piRunnerArgs-DGaq6VYM.cjs');
5
5
  var fs = require('fs/promises');
6
+ var os$1 = require('os');
6
7
  var tmp = require('tmp');
7
8
  var axios = require('axios');
8
- var api = require('./api-JANhFdZV.cjs');
9
- var spawnAgents = require('./spawnAgents-BVEaz35W.cjs');
10
- var logger = require('./logger-DXTWlPzP.cjs');
9
+ var api = require('./api-DM7b1OKj.cjs');
10
+ var spawnAgents = require('./spawnAgents-DLNMlhWJ.cjs');
11
+ var logger = require('./logger-CphW5nUE.cjs');
11
12
  var node_fs = require('node:fs');
12
13
  var path = require('node:path');
13
- var index$2 = require('./index-BRClDe07.cjs');
14
- var auth = require('./auth-DgIV0Cvt.cjs');
15
- var configuration = require('./configuration-4TGMrjul.cjs');
14
+ var index$2 = require('./index-F2UejqYs.cjs');
15
+ var auth = require('./auth-CBXnm-Mj.cjs');
16
+ var configuration = require('./configuration-CYO-kPOS.cjs');
16
17
  var child_process = require('child_process');
17
- var _package = require('./package-DY4zTbKS.cjs');
18
- var doctor = require('./doctor-BshRnjLi.cjs');
19
- var spawnHappyCLI = require('./spawnHappyCLI-fzUagkKV.cjs');
20
- var persistence = require('./persistence-BfX72dne.cjs');
21
- var controlClient = require('./controlClient-BTaZlbC6.cjs');
22
- var sessionOps = require('./sessionOps-BAnr7n8t.cjs');
18
+ var _package = require('./package-KhLqBDX9.cjs');
19
+ var doctor = require('./doctor-BrgSlfXn.cjs');
20
+ var spawnHappyCLI = require('./spawnHappyCLI-DnUZv0X2.cjs');
21
+ var persistence = require('./persistence-9BMYspxG.cjs');
22
+ var controlClient = require('./controlClient-Bqv5v5OM.cjs');
23
+ var sessionOps = require('./sessionOps-BrGiU9-s.cjs');
23
24
  var fastify = require('fastify');
24
25
  var z = require('zod');
25
26
  var fastifyTypeProviderZod = require('fastify-type-provider-zod');
@@ -27,59 +28,61 @@ var authRelay = require('./authRelay-Dy1qU9td.cjs');
27
28
  var node_crypto = require('node:crypto');
28
29
  var previewPath = require('./previewPath-B0rBdhy1.cjs');
29
30
  var backgroundTaskActivity = require('./backgroundTaskActivity-CBvUdj39.cjs');
30
- var rateLimitWindows = require('./rateLimitWindows-Czb7_7cK.cjs');
31
- var peerTools = require('./peerTools-iy3_6Yc5.cjs');
31
+ var rateLimitWindows = require('./rateLimitWindows-YRIYVdo4.cjs');
32
+ var peerTools = require('./peerTools-DQNlrcqM.cjs');
32
33
  var os = require('node:os');
33
- var remoteSessionClient = require('./remoteSessionClient-BRTIOX5b.cjs');
34
- var bootstrap = require('./bootstrap-DCQ87Aan.cjs');
35
- var index$1 = require('./index-BYOZ_8WZ.cjs');
36
- var fs$1 = require('fs');
37
- var path$2 = require('path');
34
+ var remoteSessionClient = require('./remoteSessionClient-D843fkzL.cjs');
35
+ var bootstrap = require('./bootstrap-DoA7okld.cjs');
36
+ var index$1 = require('./index-C64Ufj4D.cjs');
37
+ var require$$0 = require('fs');
38
+ var require$$1 = require('path');
38
39
  var node_child_process = require('node:child_process');
39
- var projectPath = require('./projectPath-ChLhdOyt.cjs');
40
- var doctorReadiness = require('./doctorReadiness-BCZGcN0a.cjs');
41
- var machineMetadata = require('./machineMetadata-DcUupMje.cjs');
42
- var handleResumeCommand = require('./handleResumeCommand-BwnUZmbo.cjs');
43
- var index = require('./index-_l1Sdmbi.cjs');
40
+ var projectPath = require('./projectPath-C3ioB4Bu.cjs');
41
+ var doctorReadiness = require('./doctorReadiness-Dl6yRQCy.cjs');
42
+ var machineMetadata = require('./machineMetadata-BQm9YTcI.cjs');
43
+ var require$$3 = require('crypto');
44
+ var detectCLI = require('./detectCLI-BuYR_Qxe.cjs');
45
+ var handleResumeCommand = require('./handleResumeCommand-BvWVuRwH.cjs');
46
+ var webPanels = require('./webPanels-FCgFKvVe.cjs');
47
+ var index = require('./index-Dv0Q48P3.cjs');
44
48
  var promises = require('node:fs/promises');
45
49
  var cliUpdate = require('./cliUpdate-DsKXPFYp.cjs');
46
- var client = require('./client-C4zKGjiJ.cjs');
50
+ var client = require('./client-DJplzPjD.cjs');
51
+ var client$1 = require('./client-BWjaHKtj.cjs');
47
52
  var module$1 = require('node:module');
48
53
  var path$1 = require('./path-B7zW-WwE.cjs');
49
54
  var editPaths = require('./editPaths-Bqp4OFPw.cjs');
50
- var startFileWatcher = require('./startFileWatcher-Bqlqjt93.cjs');
51
- var sync = require('./sync-Dhmtk66S.cjs');
55
+ var startFileWatcher = require('./startFileWatcher-D9cYzZOq.cjs');
56
+ var sync = require('./sync-Bn-idAoy.cjs');
52
57
  var types = require('./types-CRS-srZK.cjs');
53
58
  var tmuxSocket = require('./tmuxSocket-D-Xt6Vn-.cjs');
54
- var sessionLock = require('./sessionLock-DWX6BbiU.cjs');
59
+ var sessionLock = require('./sessionLock-DRZUcKHT.cjs');
55
60
  var doctor$1 = require('./doctor-u46qYYKX.cjs');
56
- var resources = require('./resources-JDPugcDq.cjs');
61
+ var resources = require('./resources-CvIlkzpP.cjs');
57
62
  var node_util = require('node:util');
58
63
  var template = require('./template-BaHAmH2K.cjs');
59
64
  var daemonSupervisor = require('./daemonSupervisor-B-SPSqhs.cjs');
60
65
  var loginShellEnv = require('./loginShellEnv-BkuYtExZ.cjs');
61
- require('./sessionModeFile-CLLdidiJ.cjs');
62
- require('./lidState-BeOwj6eW.cjs');
63
- require('os');
66
+ require('./acpSessionResume-CR5pmgVo.cjs');
67
+ require('./lidState-DWGnm2H4.cjs');
64
68
  require('node:events');
65
69
  require('socket.io-client');
66
- require('./attachmentLimits-SqeAHrVC.cjs');
70
+ require('./pushNotifications-DI92havG.cjs');
71
+ require('./contentLogMetadata-ZSFk_NjQ.cjs');
67
72
  require('./limits-C-a7gr04.cjs');
68
- require('./time-A6zR3Iy6.cjs');
69
- require('./registerCommonHandlers-C0_fyBQ0.cjs');
73
+ require('./time-Cjv0zxQO.cjs');
74
+ require('./registerCommonHandlers-C7a_dUWs.cjs');
70
75
  require('util');
71
- require('crypto');
72
76
  require('cross-spawn');
73
77
  require('@paralleldrive/cuid2');
74
- require('./contentLogMetadata-ZSFk_NjQ.cjs');
75
78
  require('chalk');
76
79
  require('tweetnacl');
77
- require('./browser-CSKhc0Bl.cjs');
80
+ require('./browser-DZ6qRtfH.cjs');
78
81
  require('open');
79
82
  require('./ids-B6ZC0HGt.cjs');
80
83
  require('url');
81
- require('./detectCLI-DR9ZaN6B.cjs');
82
- require('./localHappyAgentAuth-Br-mgogg.cjs');
84
+ require('./localHappyAgentAuth-DZHQnIW9.cjs');
85
+ require('./processTreeSnapshot-mDbnuojn.cjs');
83
86
  require('ps-list');
84
87
 
85
88
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -187,7 +190,7 @@ function startCaffeinate() {
187
190
  }
188
191
  killOrphanedCaffeinateProcesses();
189
192
  try {
190
- caffeinateProcess = child_process.spawn("caffeinate", ["-im"], {
193
+ caffeinateProcess = child_process.spawn("caffeinate", caffeinateArgs(process.pid), {
191
194
  stdio: "ignore",
192
195
  detached: false
193
196
  });
@@ -254,12 +257,36 @@ function setupCleanupHandlers() {
254
257
  cleanup();
255
258
  });
256
259
  }
260
+ function caffeinateArgs(daemonPid) {
261
+ return ["-im", "-w", String(daemonPid)];
262
+ }
263
+ function orphanedLegacyCaffeinatePids(psOutput) {
264
+ const pids = [];
265
+ for (const line of psOutput.split("\n")) {
266
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*?)\s*$/.exec(line);
267
+ if (!m) continue;
268
+ const [, pid, ppid, command] = m;
269
+ if (ppid !== "1") continue;
270
+ if (!/^(?:\/usr\/bin\/)?caffeinate -im$/.test(command)) continue;
271
+ pids.push(Number(pid));
272
+ }
273
+ return pids;
274
+ }
257
275
  function killOrphanedCaffeinateProcesses() {
258
276
  if (process.platform !== "darwin") return;
277
+ let ps;
259
278
  try {
260
- child_process.execSync('pkill -f "caffeinate -im"', { timeout: 5e3, stdio: "ignore" });
261
- logger.logger.debug("[caffeinate] Killed orphaned caffeinate processes");
262
- } catch {
279
+ ps = child_process.execSync("ps -A -o pid=,ppid=,command=", { timeout: 5e3, encoding: "utf8" });
280
+ } catch (error) {
281
+ logger.logger.debug("[caffeinate] Could not list processes; skipping orphan cleanup:", error);
282
+ return;
283
+ }
284
+ for (const pid of orphanedLegacyCaffeinatePids(ps)) {
285
+ try {
286
+ process.kill(pid, "SIGTERM");
287
+ logger.logger.debug(`[caffeinate] Killed orphaned legacy caffeinate PID ${pid}`);
288
+ } catch {
289
+ }
263
290
  }
264
291
  }
265
292
 
@@ -367,8 +394,28 @@ function formatAssistantReportMessage(title, sessionId, event) {
367
394
  return `[\u7CFB\u7EDF\u901A\u62A5] \u4F1A\u8BDD\u300C${title}\u300D${state}\uFF08${sessionId}\uFF09\u3002\u8BF7\u7528 session_read \u6838\u5B9E\u7ED3\u679C\uFF0C\u5E76\u5411\u7528\u6237\u53E3\u5934\u6C47\u62A5\u4E00\u53E5\u7ED3\u8BBA\uFF1B\u591A\u6761\u901A\u62A5\u63A5\u8FD1\u65F6\u5408\u5E76\u6C47\u62A5\u3002`;
368
395
  }
369
396
 
397
+ const CLAUDE_OUTBOUND_MODES = ["default", "acceptEdits", "plan", "bypassPermissions"];
398
+ function normalizeClaudeOutboundMode(value) {
399
+ if (value === null || value === void 0) return null;
400
+ if (value === "yolo") return "bypassPermissions";
401
+ return CLAUDE_OUTBOUND_MODES.includes(value) ? value : "default";
402
+ }
403
+ function publishedRelaunchPermissionMode(metadata) {
404
+ const published = typeof metadata?.permissionMode === "string" ? metadata.permissionMode : null;
405
+ if ((metadata?.flavor ?? "claude") === "claude") {
406
+ return normalizeClaudeOutboundMode(published) ?? void 0;
407
+ }
408
+ return published ?? void 0;
409
+ }
410
+
370
411
  function resumePrecheck(metadata, fs) {
371
412
  const flavor = metadata.flavor ?? "claude";
413
+ if (flavor === "acp" && metadata.piSessionId) {
414
+ if (!metadata.path || !fs.cwdExists(metadata.path)) {
415
+ return { ok: false, reason: "missing-cwd", detail: `working directory ${metadata.path ?? "(none)"} does not exist` };
416
+ }
417
+ return { ok: true };
418
+ }
372
419
  if (flavor !== "claude" && flavor !== "codex") {
373
420
  return { ok: false, reason: "unsupported-flavor", detail: `flavor "${flavor}" cannot be resumed` };
374
421
  }
@@ -387,6 +434,9 @@ function resumePrecheck(metadata, fs) {
387
434
  }
388
435
  return { ok: true };
389
436
  }
437
+ function resumeStartsFreshConversation(reason) {
438
+ return reason === "conversation-missing" || reason === "no-backend-id";
439
+ }
390
440
  function sanitizeResumeModel(value) {
391
441
  if (typeof value !== "string") return null;
392
442
  return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}(\[1m\])?$/i.test(value) ? value : null;
@@ -744,7 +794,7 @@ function startDaemonControlServer({
744
794
  return { success: false, error: "daemon is still starting up" };
745
795
  }
746
796
  logger.logger.debug(`[CONTROL SERVER] Resume session request: ${sessionId} (model=${model ?? "unset"}, permissionMode=${permissionMode ?? "unset"})`);
747
- const result = await resumeSession(sessionId, { model, permissionMode });
797
+ const result = await resumeSession(sessionId, { model, permissionMode, keepPublishedPermissionMode: true });
748
798
  switch (result.type) {
749
799
  case "success":
750
800
  return { success: true, sessionId: result.sessionId };
@@ -2052,6 +2102,2402 @@ function spawnAgentUnavailableError(agent, availability) {
2052
2102
  return null;
2053
2103
  }
2054
2104
 
2105
+ const MAX_DIFF_LINES = 4e3;
2106
+ function splitLines(text) {
2107
+ if (text === "") return [];
2108
+ const lines = text.split("\n");
2109
+ if (lines[lines.length - 1] === "") lines.pop();
2110
+ return lines;
2111
+ }
2112
+ function diffOps(a, b) {
2113
+ if (a.length > MAX_DIFF_LINES || b.length > MAX_DIFF_LINES) {
2114
+ return [...a.map((text) => ({ kind: "-", text })), ...b.map((text) => ({ kind: "+", text }))];
2115
+ }
2116
+ const n = a.length;
2117
+ const m = b.length;
2118
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
2119
+ for (let i2 = n - 1; i2 >= 0; i2--) {
2120
+ for (let j2 = m - 1; j2 >= 0; j2--) {
2121
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
2122
+ }
2123
+ }
2124
+ const ops = [];
2125
+ let i = 0;
2126
+ let j = 0;
2127
+ while (i < n && j < m) {
2128
+ if (a[i] === b[j]) {
2129
+ ops.push({ kind: " ", text: a[i] });
2130
+ i++;
2131
+ j++;
2132
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
2133
+ ops.push({ kind: "-", text: a[i] });
2134
+ i++;
2135
+ } else {
2136
+ ops.push({ kind: "+", text: b[j] });
2137
+ j++;
2138
+ }
2139
+ }
2140
+ while (i < n) ops.push({ kind: "-", text: a[i++] });
2141
+ while (j < m) ops.push({ kind: "+", text: b[j++] });
2142
+ return ops;
2143
+ }
2144
+ function unifiedDiff(oldText, newText, label, context = 3) {
2145
+ if (oldText === newText) return "";
2146
+ const a = splitLines(oldText);
2147
+ const b = splitLines(newText);
2148
+ const ops = diffOps(a, b);
2149
+ const changed = ops.map((op) => op.kind !== " ");
2150
+ if (!changed.some(Boolean)) {
2151
+ return `--- ${label}
2152
+ +++ ${label}
2153
+ @@ trailing newline changed @@
2154
+ `;
2155
+ }
2156
+ const out = [`--- ${oldText === "" ? "/dev/null" : label}`, `+++ ${label}`];
2157
+ let k = 0;
2158
+ while (k < ops.length) {
2159
+ if (!changed[k]) {
2160
+ k++;
2161
+ continue;
2162
+ }
2163
+ let start = Math.max(0, k - context);
2164
+ let end = k;
2165
+ while (end < ops.length) {
2166
+ if (changed[end]) {
2167
+ end++;
2168
+ continue;
2169
+ }
2170
+ let next = end;
2171
+ while (next < ops.length && !changed[next]) next++;
2172
+ if (next < ops.length && next - end <= context * 2) {
2173
+ end = next;
2174
+ continue;
2175
+ }
2176
+ break;
2177
+ }
2178
+ const stop = Math.min(ops.length, end + context);
2179
+ let oldStart = 1;
2180
+ let newStart = 1;
2181
+ for (let p = 0; p < start; p++) {
2182
+ if (ops[p].kind !== "+") oldStart++;
2183
+ if (ops[p].kind !== "-") newStart++;
2184
+ }
2185
+ const slice = ops.slice(start, stop);
2186
+ const oldCount = slice.filter((op) => op.kind !== "+").length;
2187
+ const newCount = slice.filter((op) => op.kind !== "-").length;
2188
+ out.push(`@@ -${oldCount ? oldStart : oldStart - 1},${oldCount} +${newCount ? newStart : newStart - 1},${newCount} @@`);
2189
+ for (const op of slice) out.push(`${op.kind}${op.text}`);
2190
+ k = stop;
2191
+ start = stop;
2192
+ }
2193
+ return `${out.join("\n")}
2194
+ `;
2195
+ }
2196
+
2197
+ const SECRET_KEY_PATTERN = /(api[_-]?key|apikey|token|secret|password|passwd|authorization|bearer|credential|cookie|private[_-]?key)/i;
2198
+ const EXTRA_SECRET_KEYS = /* @__PURE__ */ new Set(["ANTHROPIC_CUSTOM_HEADERS"]);
2199
+ function isSecretKey(key) {
2200
+ return SECRET_KEY_PATTERN.test(key) || EXTRA_SECRET_KEYS.has(key);
2201
+ }
2202
+ function maskSecret(value) {
2203
+ const v = value.trim();
2204
+ if (!v) return "";
2205
+ if (v.length < 16) return "\u2022\u2022\u2022\u2022";
2206
+ return `${v.slice(0, 4)}\u2026${v.slice(-4)}`;
2207
+ }
2208
+ function collectSecretValues(value, out = /* @__PURE__ */ new Set(), parentKey = "") {
2209
+ if (typeof value === "string") {
2210
+ if (parentKey && isSecretKey(parentKey) && value.length >= 4) out.add(value);
2211
+ return out;
2212
+ }
2213
+ if (Array.isArray(value)) {
2214
+ for (const item of value) collectSecretValues(item, out, parentKey);
2215
+ return out;
2216
+ }
2217
+ if (value && typeof value === "object") {
2218
+ for (const [key, child] of Object.entries(value)) {
2219
+ collectSecretValues(child, out, key);
2220
+ }
2221
+ }
2222
+ return out;
2223
+ }
2224
+ function redactText(text, secrets) {
2225
+ const list = [...new Set(secrets)].filter((s) => s.length >= 4).sort((a, b) => b.length - a.length);
2226
+ let out = text;
2227
+ for (const secret of list) {
2228
+ out = out.split(secret).join(maskSecret(secret));
2229
+ }
2230
+ return out;
2231
+ }
2232
+ const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2233
+ function isValidEnvName(name) {
2234
+ return typeof name === "string" && ENV_NAME_PATTERN.test(name);
2235
+ }
2236
+
2237
+ function parseJsonObject$1(text, label) {
2238
+ if (text.trim() === "") return {};
2239
+ let value;
2240
+ try {
2241
+ value = JSON.parse(text);
2242
+ } catch (error) {
2243
+ const hasComments = /^\s*\/\/|\/\*/m.test(text);
2244
+ throw new mirrorProtocol.ModelConfigError(
2245
+ hasComments ? "json-has-comments" : "invalid-json",
2246
+ hasComments ? `${label} contains comments; Very Happy only edits strict JSON so it never drops them. Edit it by hand or remove the comments.` : `${label} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
2247
+ );
2248
+ }
2249
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2250
+ throw new mirrorProtocol.ModelConfigError("invalid-json", `${label} must contain a JSON object`);
2251
+ }
2252
+ return value;
2253
+ }
2254
+ function detectIndent(text) {
2255
+ const m = /^([ \t]+)"/m.exec(text);
2256
+ return m ? m[1] : 2;
2257
+ }
2258
+ function stringifyLike(original, value) {
2259
+ const compact = original.trim() !== "" && !original.trim().includes("\n");
2260
+ const body = compact ? JSON.stringify(value) : JSON.stringify(value, null, detectIndent(original));
2261
+ const eol = original.includes("\r\n") ? "\r\n" : "\n";
2262
+ const withEol = eol === "\r\n" ? body.replace(/\n/g, "\r\n") : body;
2263
+ return original === "" || /\r?\n$/.test(original) ? withEol + eol : withEol;
2264
+ }
2265
+ function setOrDelete(obj, key, value) {
2266
+ if (value === void 0 || value === null || value === "") delete obj[key];
2267
+ else obj[key] = value;
2268
+ }
2269
+ function childObject(obj, key, label) {
2270
+ const current = obj[key];
2271
+ if (current === void 0) {
2272
+ const created = {};
2273
+ obj[key] = created;
2274
+ return created;
2275
+ }
2276
+ if (!current || typeof current !== "object" || Array.isArray(current)) {
2277
+ throw new mirrorProtocol.ModelConfigError("unexpected-shape", `${label}.${key} is not an object; refusing to overwrite it`);
2278
+ }
2279
+ return current;
2280
+ }
2281
+
2282
+ const MODEL_ID = /^[A-Za-z0-9._:/@+\-[\]]{1,200}$/;
2283
+ const PROVIDER_ID = /^[A-Za-z0-9_-]{1,64}$/;
2284
+ function fail(code, message) {
2285
+ throw new mirrorProtocol.ModelConfigError(code, message);
2286
+ }
2287
+ function normalizeBaseUrl(value, field = "baseUrl") {
2288
+ if (value === void 0) return void 0;
2289
+ if (value === null) return null;
2290
+ if (typeof value !== "string") fail("invalid-input", `${field} must be a string`);
2291
+ const v = value.trim();
2292
+ if (v === "") return null;
2293
+ if (v.length > 2048 || /\s/.test(v)) fail("invalid-input", `${field} is not a valid URL`);
2294
+ let url;
2295
+ try {
2296
+ url = new URL(v);
2297
+ } catch {
2298
+ fail("invalid-input", `${field} is not a valid URL`);
2299
+ }
2300
+ if (url.protocol !== "http:" && url.protocol !== "https:") fail("invalid-input", `${field} must be http(s)`);
2301
+ if (url.username || url.password) fail("invalid-input", `${field} must not embed credentials; use the API key field`);
2302
+ return v;
2303
+ }
2304
+ function normalizeModelId(value, field = "model") {
2305
+ if (value === void 0) return void 0;
2306
+ if (value === null) return null;
2307
+ if (typeof value !== "string") fail("invalid-input", `${field} must be a string`);
2308
+ const v = value.trim();
2309
+ if (v === "") return null;
2310
+ if (!MODEL_ID.test(v)) fail("invalid-input", `${field} contains unsupported characters`);
2311
+ return v;
2312
+ }
2313
+ function normalizeModelList(value, field = "models") {
2314
+ if (value === void 0) return void 0;
2315
+ if (!Array.isArray(value)) fail("invalid-input", `${field} must be an array`);
2316
+ if (value.length > 64) fail("invalid-input", `${field} has too many entries`);
2317
+ const out = [];
2318
+ for (const item of value) {
2319
+ const id = normalizeModelId(item, field);
2320
+ if (id && !out.includes(id)) out.push(id);
2321
+ }
2322
+ return out;
2323
+ }
2324
+ function normalizeProviderId(value, reserved = []) {
2325
+ if (typeof value !== "string" || !PROVIDER_ID.test(value.trim())) fail("invalid-input", "providerId must be 1-64 letters, digits, - or _");
2326
+ const v = value.trim();
2327
+ if (reserved.includes(v)) fail("invalid-input", `providerId "${v}" is reserved by the harness`);
2328
+ return v;
2329
+ }
2330
+ function normalizeSecret(value, allowed = ["keep", "clear", "literal", "env"]) {
2331
+ if (value === void 0) return { mode: "keep" };
2332
+ if (!value || typeof value !== "object") fail("invalid-input", "apiKey must be an object");
2333
+ const v = value;
2334
+ const mode = v.mode;
2335
+ if (typeof mode !== "string" || !allowed.includes(mode)) fail("invalid-input", `apiKey.mode must be one of ${allowed.join(", ")}`);
2336
+ if (mode === "literal") {
2337
+ if (typeof v.value !== "string") fail("invalid-input", "apiKey.value must be a string");
2338
+ const key = v.value.trim();
2339
+ if (!key || key.length > 4096 || /[\s\u0000-\u001f\u007f]/.test(key)) fail("invalid-input", "apiKey.value must be a single line without spaces");
2340
+ return { mode: "literal", value: key };
2341
+ }
2342
+ if (mode === "env") {
2343
+ if (!isValidEnvName(v.name)) fail("invalid-input", "apiKey.name must be an environment variable name");
2344
+ return { mode: "env", name: v.name };
2345
+ }
2346
+ return { mode };
2347
+ }
2348
+ function baseUrlWarnings(url, kind) {
2349
+ if (!url) return [];
2350
+ const path = (() => {
2351
+ try {
2352
+ return new URL(url).pathname.replace(/\/+$/, "");
2353
+ } catch {
2354
+ return "";
2355
+ }
2356
+ })();
2357
+ const out = [];
2358
+ if (/\/(chat\/completions|responses|messages|completions)$/.test(path)) {
2359
+ out.push({ code: "base-url-has-endpoint", message: "The base URL ends with an API endpoint path; harnesses append that themselves." });
2360
+ }
2361
+ if (kind === "anthropic" && /\/v1$/.test(path)) {
2362
+ out.push({ code: "base-url-v1", message: "Claude Code appends /v1/messages; a base URL ending in /v1 usually produces /v1/v1/messages." });
2363
+ }
2364
+ if (kind === "openai" && !/\/v\d/.test(path)) {
2365
+ out.push({ code: "base-url-no-version", message: "OpenAI-compatible base URLs usually end in /v1." });
2366
+ }
2367
+ return out;
2368
+ }
2369
+
2370
+ function getPath$1(obj, path) {
2371
+ let cur = obj;
2372
+ for (const p of path) {
2373
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
2374
+ cur = cur[p];
2375
+ }
2376
+ return cur;
2377
+ }
2378
+ function changedPaths(before, after, paths) {
2379
+ return paths.filter((path) => JSON.stringify(getPath$1(before, path)) !== JSON.stringify(getPath$1(after, path))).map((path) => path.join("."));
2380
+ }
2381
+ function uniq(values) {
2382
+ const out = [];
2383
+ for (const v of values) if (v && !out.includes(v)) out.push(v);
2384
+ return out;
2385
+ }
2386
+
2387
+ const ROLE$1 = "settings";
2388
+ const AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN";
2389
+ const API_KEY$1 = "ANTHROPIC_API_KEY";
2390
+ const ALIAS_VARS = { opusModel: "ANTHROPIC_DEFAULT_OPUS_MODEL", sonnetModel: "ANTHROPIC_DEFAULT_SONNET_MODEL", haikuModel: "ANTHROPIC_DEFAULT_HAIKU_MODEL" };
2391
+ function claudeEnvHelper(name) {
2392
+ return `printf %s "$${name}"`;
2393
+ }
2394
+ const OUR_HELPER = /^printf %s "\$([A-Za-z_][A-Za-z0-9_]*)"$/;
2395
+ const OWNED_PATHS = [
2396
+ ["env", "ANTHROPIC_BASE_URL"],
2397
+ ["env", AUTH_TOKEN],
2398
+ ["env", API_KEY$1],
2399
+ ["env", ALIAS_VARS.opusModel],
2400
+ ["env", ALIAS_VARS.sonnetModel],
2401
+ ["env", ALIAS_VARS.haikuModel],
2402
+ ["model"],
2403
+ ["modelPicker", "options"],
2404
+ ["apiKeyHelper"],
2405
+ ["availableModels"]
2406
+ ];
2407
+ function claudeSettingsPath(ctx) {
2408
+ const dir = ctx.env.CLAUDE_CONFIG_DIR?.trim() || path.join(ctx.home, ".claude");
2409
+ return path.join(dir, "settings.json");
2410
+ }
2411
+ function str$4(v) {
2412
+ return typeof v === "string" && v.trim() ? v : null;
2413
+ }
2414
+ function envOf(settings) {
2415
+ const env = settings.env;
2416
+ return env && typeof env === "object" && !Array.isArray(env) ? env : {};
2417
+ }
2418
+ function pickerOptions(settings) {
2419
+ const picker = settings.modelPicker;
2420
+ if (!picker || typeof picker !== "object" || Array.isArray(picker)) return [];
2421
+ const options = picker.options;
2422
+ return Array.isArray(options) ? options.filter((o) => !!o && typeof o === "object" && typeof o.model === "string") : [];
2423
+ }
2424
+ function secretView$2(settings, ctx) {
2425
+ const env = envOf(settings);
2426
+ const literal = str$4(env[AUTH_TOKEN]) ?? str$4(env[API_KEY$1]);
2427
+ if (literal) return { mode: "literal", masked: maskSecret(literal) };
2428
+ const helper = str$4(settings.apiKeyHelper);
2429
+ if (helper) {
2430
+ const ours = OUR_HELPER.exec(helper.trim());
2431
+ if (ours) return { mode: "env", envName: ours[1], envPresent: !!ctx.env[ours[1]] };
2432
+ return { mode: "command" };
2433
+ }
2434
+ return { mode: "none" };
2435
+ }
2436
+ function currentOf$3(settings, ctx) {
2437
+ const env = envOf(settings);
2438
+ return {
2439
+ baseUrl: str$4(env.ANTHROPIC_BASE_URL),
2440
+ authHeader: !str$4(env[AUTH_TOKEN]) && str$4(env[API_KEY$1]) ? "x-api-key" : "bearer",
2441
+ apiKey: secretView$2(settings, ctx),
2442
+ model: str$4(settings.model),
2443
+ opusModel: str$4(env[ALIAS_VARS.opusModel]),
2444
+ sonnetModel: str$4(env[ALIAS_VARS.sonnetModel]),
2445
+ haikuModel: str$4(env[ALIAS_VARS.haikuModel]),
2446
+ pickerModels: pickerOptions(settings).map((o) => o.model)
2447
+ };
2448
+ }
2449
+ function pickerModelsOf$1(current) {
2450
+ return uniq([current.model, current.opusModel, current.sonnetModel, current.haikuModel, ...current.pickerModels ?? []]);
2451
+ }
2452
+ function warningsOf$3(settings, current, ctx) {
2453
+ const env = envOf(settings);
2454
+ const out = [...baseUrlWarnings(current.baseUrl, "anthropic")];
2455
+ if (str$4(env.ANTHROPIC_MODEL)) {
2456
+ out.push({ code: "env-model-overrides", message: "env.ANTHROPIC_MODEL is set in settings.json and overrides the default model." });
2457
+ }
2458
+ const daemonOther = current.authHeader === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2459
+ if (current.baseUrl && ctx.env[daemonOther]) {
2460
+ out.push({ code: "daemon-env-credential", message: `The daemon's environment also defines ${daemonOther}; sessions inherit it.` });
2461
+ }
2462
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
2463
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
2464
+ }
2465
+ if (Array.isArray(settings.availableModels)) {
2466
+ const allowed = settings.availableModels;
2467
+ const missing = pickerModelsOf$1(current).filter((id) => !allowed.includes(id));
2468
+ if (missing.length) out.push({ code: "available-models-filter", message: `availableModels does not list ${missing.join(", ")}; Claude Code hides them.` });
2469
+ }
2470
+ return out;
2471
+ }
2472
+ function parsePatch$1(raw) {
2473
+ const p = raw;
2474
+ if (p.authHeader !== void 0 && p.authHeader !== "bearer" && p.authHeader !== "x-api-key") fail("invalid-input", "authHeader must be bearer or x-api-key");
2475
+ return {
2476
+ harness: "claude",
2477
+ baseUrl: normalizeBaseUrl(p.baseUrl),
2478
+ authHeader: p.authHeader,
2479
+ apiKey: normalizeSecret(p.apiKey),
2480
+ model: normalizeModelId(p.model),
2481
+ opusModel: normalizeModelId(p.opusModel, "opusModel"),
2482
+ sonnetModel: normalizeModelId(p.sonnetModel, "sonnetModel"),
2483
+ haikuModel: normalizeModelId(p.haikuModel, "haikuModel"),
2484
+ pickerModels: normalizeModelList(p.pickerModels, "pickerModels")
2485
+ };
2486
+ }
2487
+ const claudeAdapter = {
2488
+ id: "claude",
2489
+ binary: "claude",
2490
+ files: (ctx) => [{ role: ROLE$1, path: claudeSettingsPath(ctx) }],
2491
+ view(files, ctx) {
2492
+ const settings = parseJsonObject$1(files[ROLE$1].content, "settings.json");
2493
+ const current = currentOf$3(settings, ctx);
2494
+ return { current, pickerModels: pickerModelsOf$1(current), warnings: warningsOf$3(settings, current, ctx) };
2495
+ },
2496
+ plan(files, raw, ctx) {
2497
+ const patch = parsePatch$1(raw);
2498
+ const original = files[ROLE$1].content;
2499
+ const before = parseJsonObject$1(original, "settings.json");
2500
+ const settings = structuredClone(before);
2501
+ const hadEnv = settings.env !== void 0;
2502
+ const env = childObject(settings, "env", "settings");
2503
+ if (patch.baseUrl !== void 0) setOrDelete(env, "ANTHROPIC_BASE_URL", patch.baseUrl);
2504
+ const currentHeader = !str$4(env[AUTH_TOKEN]) && str$4(env[API_KEY$1]) ? "x-api-key" : "bearer";
2505
+ const header = patch.authHeader ?? currentHeader;
2506
+ const target = header === "bearer" ? AUTH_TOKEN : API_KEY$1;
2507
+ const other = header === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2508
+ const helperIsOurs = typeof settings.apiKeyHelper === "string" && OUR_HELPER.test(settings.apiKeyHelper.trim());
2509
+ const secrets = [];
2510
+ switch (patch.apiKey.mode) {
2511
+ case "literal":
2512
+ env[target] = patch.apiKey.value;
2513
+ delete env[other];
2514
+ if (helperIsOurs) delete settings.apiKeyHelper;
2515
+ secrets.push(patch.apiKey.value);
2516
+ break;
2517
+ case "env":
2518
+ settings.apiKeyHelper = claudeEnvHelper(patch.apiKey.name);
2519
+ delete env[AUTH_TOKEN];
2520
+ delete env[API_KEY$1];
2521
+ break;
2522
+ case "clear":
2523
+ delete env[AUTH_TOKEN];
2524
+ delete env[API_KEY$1];
2525
+ if (helperIsOurs) delete settings.apiKeyHelper;
2526
+ break;
2527
+ case "keep":
2528
+ if (header !== currentHeader && str$4(env[other]) && !str$4(env[target])) {
2529
+ env[target] = env[other];
2530
+ delete env[other];
2531
+ }
2532
+ break;
2533
+ }
2534
+ if (patch.model !== void 0) setOrDelete(settings, "model", patch.model);
2535
+ for (const [field, variable] of Object.entries(ALIAS_VARS)) {
2536
+ if (patch[field] !== void 0) setOrDelete(env, variable, patch[field]);
2537
+ }
2538
+ if (patch.pickerModels !== void 0) {
2539
+ const hadPicker = settings.modelPicker !== void 0;
2540
+ const picker = childObject(settings, "modelPicker", "settings");
2541
+ const existing = pickerOptions(settings);
2542
+ const next = patch.pickerModels.map((id) => existing.find((o) => o.model === id) ?? { model: id });
2543
+ if (next.length) picker.options = next;
2544
+ else delete picker.options;
2545
+ if (!hadPicker && Object.keys(picker).length === 0) delete settings.modelPicker;
2546
+ }
2547
+ if (!hadEnv && Object.keys(env).length === 0) delete settings.env;
2548
+ const current = currentOf$3(settings, ctx);
2549
+ if (Array.isArray(settings.availableModels)) {
2550
+ const allowed = settings.availableModels;
2551
+ const add = pickerModelsOf$1(current).filter((id) => !allowed.includes(id));
2552
+ if (add.length) settings.availableModels = [...allowed, ...add];
2553
+ }
2554
+ const changedKeys = changedPaths(before, settings, OWNED_PATHS);
2555
+ const content = changedKeys.length === 0 ? void 0 : stringifyLike(original, settings);
2556
+ return { contents: { [ROLE$1]: content }, warnings: warningsOf$3(settings, current, ctx), changedKeys, secrets };
2557
+ },
2558
+ secretsIn(_role, content) {
2559
+ try {
2560
+ return collectSecretValues(parseJsonObject$1(content, "settings.json"));
2561
+ } catch {
2562
+ return /* @__PURE__ */ new Set();
2563
+ }
2564
+ }
2565
+ };
2566
+
2567
+ /*!
2568
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2569
+ * SPDX-License-Identifier: BSD-3-Clause
2570
+ *
2571
+ * Redistribution and use in source and binary forms, with or without
2572
+ * modification, are permitted provided that the following conditions are met:
2573
+ *
2574
+ * 1. Redistributions of source code must retain the above copyright notice, this
2575
+ * list of conditions and the following disclaimer.
2576
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2577
+ * this list of conditions and the following disclaimer in the
2578
+ * documentation and/or other materials provided with the distribution.
2579
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2580
+ * may be used to endorse or promote products derived from this software without
2581
+ * specific prior written permission.
2582
+ *
2583
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2584
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2585
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2586
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2587
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2588
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2589
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2590
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2591
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2592
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2593
+ */
2594
+ function getLineColFromPtr(string, ptr) {
2595
+ let lines = string.slice(0, ptr).split(/\r?\n/);
2596
+ return [lines.length, lines.pop().length + 1];
2597
+ }
2598
+ function makeCodeBlock(string, line, column) {
2599
+ let lines = string.split(/\r?\n/);
2600
+ let codeblock = "";
2601
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
2602
+ for (let i = line - 1; i <= line + 1; i++) {
2603
+ let l = lines[i - 1];
2604
+ if (!l)
2605
+ continue;
2606
+ codeblock += i.toString().padEnd(numberLen, " ");
2607
+ codeblock += ": ";
2608
+ codeblock += l;
2609
+ codeblock += "\n";
2610
+ if (i === line) {
2611
+ codeblock += " ".repeat(numberLen + column + 2);
2612
+ codeblock += "^\n";
2613
+ }
2614
+ }
2615
+ return codeblock;
2616
+ }
2617
+ class TomlError extends Error {
2618
+ line;
2619
+ column;
2620
+ codeblock;
2621
+ constructor(message, options) {
2622
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
2623
+ const codeblock = makeCodeBlock(options.toml, line, column);
2624
+ super(`Invalid TOML document: ${message}
2625
+
2626
+ ${codeblock}`, options);
2627
+ this.line = line;
2628
+ this.column = column;
2629
+ this.codeblock = codeblock;
2630
+ }
2631
+ /** @internal */
2632
+ static x(message, ctx, ptr) {
2633
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
2634
+ }
2635
+ }
2636
+
2637
+ function parseString(ctx) {
2638
+ let startPtr = ctx.p;
2639
+ let c = ctx.s.charCodeAt(ctx.p++);
2640
+ let first = c;
2641
+ let isLiteral = c === 39;
2642
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
2643
+ if (isMultiline) {
2644
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
2645
+ ctx.p++;
2646
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
2647
+ ctx.p += 2;
2648
+ }
2649
+ let parsed = "";
2650
+ let sliceStart = ctx.p;
2651
+ let state = 0;
2652
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2653
+ c = ctx.s.charCodeAt(ctx.p);
2654
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
2655
+ state = state && 3;
2656
+ } else if (c < 32 && c !== 9 || c === 127) {
2657
+ TomlError.x("control characters are not allowed in strings", ctx);
2658
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
2659
+ if (isMultiline) {
2660
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2661
+ ctx.p++;
2662
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2663
+ ctx.p++;
2664
+ }
2665
+ if (!state) {
2666
+ let s = ctx.s.slice(sliceStart, ctx.p);
2667
+ parsed = parsed ? parsed + s : s;
2668
+ }
2669
+ ctx.p += isMultiline ? 3 : 1;
2670
+ return parsed;
2671
+ } else if (!state) {
2672
+ if (!isLiteral && c === 92) {
2673
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
2674
+ state = 1;
2675
+ }
2676
+ } else if (state === 1) {
2677
+ if (c === 120 || c === 117 || c === 85) {
2678
+ let errPtr = ctx.p++ - 1;
2679
+ let value = 0;
2680
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
2681
+ for (let j = 0; j < len; j++, ctx.p++) {
2682
+ let hex = ctx.s.charCodeAt(ctx.p);
2683
+ let digit = (
2684
+ /* 0-9 */
2685
+ hex >= 48 && hex <= 57 ? hex - 48 : (
2686
+ /* A-F */
2687
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
2688
+ /* a-f */
2689
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
2690
+ )
2691
+ )
2692
+ );
2693
+ if (digit < 0)
2694
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
2695
+ value = value << 4 | digit;
2696
+ }
2697
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
2698
+ TomlError.x("invalid unicode escape", ctx, errPtr);
2699
+ }
2700
+ parsed += String.fromCodePoint(value);
2701
+ sliceStart = ctx.p--;
2702
+ state = 0;
2703
+ } else if (isMultiline && (c === 32 || c === 9)) {
2704
+ state = 2;
2705
+ } else {
2706
+ if (c === 98)
2707
+ parsed += "\b";
2708
+ else if (c === 116)
2709
+ parsed += " ";
2710
+ else if (c === 110)
2711
+ parsed += "\n";
2712
+ else if (c === 102)
2713
+ parsed += "\f";
2714
+ else if (c === 114)
2715
+ parsed += "\r";
2716
+ else if (c === 101)
2717
+ parsed += "\x1B";
2718
+ else if (c === 34)
2719
+ parsed += '"';
2720
+ else if (c === 92)
2721
+ parsed += "\\";
2722
+ else
2723
+ TomlError.x("unrecognised escape sequence", ctx);
2724
+ sliceStart = ctx.p + 1;
2725
+ state = 0;
2726
+ }
2727
+ } else if (c !== 32 && c !== 9) {
2728
+ if (state === 2)
2729
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
2730
+ state = !isLiteral && c === 92 ? 1 : 0;
2731
+ sliceStart = ctx.p;
2732
+ }
2733
+ }
2734
+ TomlError.x("unfinished string", ctx, startPtr);
2735
+ }
2736
+
2737
+ /*!
2738
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2739
+ * SPDX-License-Identifier: BSD-3-Clause
2740
+ *
2741
+ * Redistribution and use in source and binary forms, with or without
2742
+ * modification, are permitted provided that the following conditions are met:
2743
+ *
2744
+ * 1. Redistributions of source code must retain the above copyright notice, this
2745
+ * list of conditions and the following disclaimer.
2746
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2747
+ * this list of conditions and the following disclaimer in the
2748
+ * documentation and/or other materials provided with the distribution.
2749
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2750
+ * may be used to endorse or promote products derived from this software without
2751
+ * specific prior written permission.
2752
+ *
2753
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2754
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2755
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2756
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2757
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2758
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2759
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2760
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2761
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2762
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2763
+ */
2764
+ let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
2765
+ class TomlDate extends Date {
2766
+ #hasDate = false;
2767
+ #hasTime = false;
2768
+ #offset = null;
2769
+ constructor(date, fasttype, unsafeDelim) {
2770
+ let hasDate = true;
2771
+ let hasTime = true;
2772
+ let offset = "Z";
2773
+ let c;
2774
+ if (typeof date === "string") {
2775
+ if (fasttype)
2776
+ prep: {
2777
+ if (fasttype < 3) {
2778
+ if (+date.slice(11, 13) > 23) {
2779
+ date = "";
2780
+ break prep;
2781
+ }
2782
+ if (fasttype === 2) {
2783
+ offset = null;
2784
+ date += "Z";
2785
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
2786
+ offset = date.slice(date.length - 6);
2787
+ }
2788
+ if (unsafeDelim)
2789
+ date = date.slice(0, 10) + "T" + date.slice(11);
2790
+ } else if (fasttype === 4) {
2791
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
2792
+ }
2793
+ hasDate = fasttype !== 4;
2794
+ hasTime = fasttype !== 3;
2795
+ }
2796
+ else {
2797
+ let match = date.match(DATE_TIME_RE);
2798
+ if (match) {
2799
+ if (!match[1]) {
2800
+ hasDate = false;
2801
+ date = `0000-01-01T${date}`;
2802
+ }
2803
+ hasTime = !!match[2];
2804
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
2805
+ if (match[2] && +match[2] > 23) {
2806
+ date = "";
2807
+ } else {
2808
+ offset = match[3] || null;
2809
+ if (!offset && hasTime)
2810
+ date += "Z";
2811
+ }
2812
+ } else {
2813
+ date = "";
2814
+ }
2815
+ }
2816
+ }
2817
+ super(date);
2818
+ if (!isNaN(this.getTime())) {
2819
+ this.#hasDate = hasDate;
2820
+ this.#hasTime = hasTime;
2821
+ this.#offset = offset;
2822
+ }
2823
+ }
2824
+ isDateTime() {
2825
+ return this.#hasDate && this.#hasTime;
2826
+ }
2827
+ isLocal() {
2828
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
2829
+ }
2830
+ isDate() {
2831
+ return this.#hasDate && !this.#hasTime;
2832
+ }
2833
+ isTime() {
2834
+ return this.#hasTime && !this.#hasDate;
2835
+ }
2836
+ isValid() {
2837
+ return this.#hasDate || this.#hasTime;
2838
+ }
2839
+ toISOString() {
2840
+ let iso = super.toISOString();
2841
+ if (this.isDate())
2842
+ return iso.slice(0, 10);
2843
+ if (this.isTime())
2844
+ return iso.slice(11, 23);
2845
+ if (this.#offset === null)
2846
+ return iso.slice(0, -1);
2847
+ if (this.#offset === "Z" || this.#offset === "z")
2848
+ return iso;
2849
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
2850
+ offset = this.#offset[0] === "-" ? offset : -offset;
2851
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
2852
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
2853
+ }
2854
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
2855
+ let date = new TomlDate(jsDate);
2856
+ date.#offset = offset;
2857
+ return date;
2858
+ }
2859
+ static wrapAsLocalDateTime(jsDate) {
2860
+ let date = new TomlDate(jsDate);
2861
+ date.#offset = null;
2862
+ return date;
2863
+ }
2864
+ static wrapAsLocalDate(jsDate) {
2865
+ let date = new TomlDate(jsDate);
2866
+ date.#hasTime = false;
2867
+ date.#offset = null;
2868
+ return date;
2869
+ }
2870
+ static wrapAsLocalTime(jsDate) {
2871
+ let date = new TomlDate(jsDate);
2872
+ date.#hasDate = false;
2873
+ date.#offset = null;
2874
+ return date;
2875
+ }
2876
+ }
2877
+
2878
+ function isDigit(char, base = 10) {
2879
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
2880
+ }
2881
+ function isEndOfValue(char, delim) {
2882
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
2883
+ delim && (char === delim || char === 44) || // Comment
2884
+ char === 35;
2885
+ }
2886
+ function extractValue(ctx, end) {
2887
+ let errPtr = ctx.p;
2888
+ let c = ctx.s.charCodeAt(ctx.p);
2889
+ if (c === 91 || c === 123) {
2890
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
2891
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
2892
+ ctx.d++;
2893
+ return value;
2894
+ }
2895
+ if (c === 34 || c === 39) {
2896
+ return parseString(ctx);
2897
+ }
2898
+ if (c === 116) {
2899
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
2900
+ TomlError.x("invalid value", ctx, errPtr);
2901
+ return ctx.p++, true;
2902
+ }
2903
+ if (c === 102) {
2904
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
2905
+ TomlError.x("invalid value", ctx, errPtr);
2906
+ return ctx.p++, false;
2907
+ }
2908
+ if (c === 43 || c === 45) {
2909
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
2910
+ }
2911
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
2912
+ return parseDate(ctx, c, end);
2913
+ }
2914
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
2915
+ return parseTime(ctx, c, end);
2916
+ }
2917
+ return parseNumber(ctx, ctx.p, c, 0, end);
2918
+ }
2919
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
2920
+ let c = startChr;
2921
+ let state = 0;
2922
+ let hasUnderscores = false;
2923
+ if (c === 105) {
2924
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
2925
+ TomlError.x("invalid value", ctx, startPtr);
2926
+ return ctx.p++, (sign || 1) / 0;
2927
+ }
2928
+ if (c === 110) {
2929
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
2930
+ TomlError.x("invalid value", ctx, startPtr);
2931
+ return ctx.p++, NaN;
2932
+ }
2933
+ if (c === 48) {
2934
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
2935
+ return ctx.bi === true ? 0n : 0;
2936
+ if (!sign) {
2937
+ if (c === 120)
2938
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
2939
+ else if (c === 98)
2940
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
2941
+ else if (c === 111)
2942
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
2943
+ }
2944
+ if (c === 46)
2945
+ state = 2;
2946
+ else if (c === 101 || c === 69)
2947
+ state = 4;
2948
+ else
2949
+ TomlError.x("illegal leading zero", ctx, startPtr);
2950
+ } else if (!isDigit(c))
2951
+ TomlError.x("invalid value", ctx, startPtr);
2952
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2953
+ if (!state)
2954
+ state = 1;
2955
+ if (c === 95) {
2956
+ if (!(state & 1))
2957
+ TomlError.x("illegal underscore", ctx);
2958
+ state += 11;
2959
+ hasUnderscores = true;
2960
+ } else if (state === 1 && c === 46)
2961
+ state = 2;
2962
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
2963
+ state = 4;
2964
+ else if (state === 4 && (c === 43 || c === 45)) ; else if (!isDigit(c))
2965
+ TomlError.x(`illegal character in numeric literal`, ctx);
2966
+ else if (state > 9)
2967
+ state -= 11;
2968
+ else if (!(state & 1))
2969
+ state++;
2970
+ }
2971
+ if (!state) {
2972
+ let val = (startChr - 48) * (sign || 1);
2973
+ return ctx.bi === true ? BigInt(val) : val;
2974
+ }
2975
+ if (!(state & 1))
2976
+ TomlError.x("unfinished numeric value", ctx, startPtr);
2977
+ let str = ctx.s.slice(startPtr, ctx.p);
2978
+ if (hasUnderscores)
2979
+ str = str.replaceAll("_", "");
2980
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
2981
+ }
2982
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
2983
+ let c, underscore = 1;
2984
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2985
+ if (c === 95) {
2986
+ if (underscore & 1)
2987
+ TomlError.x("illegal underscore", ctx);
2988
+ underscore = 3;
2989
+ } else if (!isDigit(c, base))
2990
+ TomlError.x(`illegal character in numeric literal`, ctx);
2991
+ else if (underscore & 1)
2992
+ underscore--;
2993
+ }
2994
+ if (underscore & 1)
2995
+ TomlError.x("unfinished numeric value", ctx);
2996
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
2997
+ if (underscore)
2998
+ str = str.replaceAll("_", "");
2999
+ return parseInteger(ctx, str, base, startPtr);
3000
+ }
3001
+ function parseInteger(ctx, str, base, startPtr) {
3002
+ if (ctx.bi !== true)
3003
+ int: {
3004
+ let val = parseInt(str, base);
3005
+ if (!Number.isSafeInteger(val)) {
3006
+ if (ctx.bi)
3007
+ break int;
3008
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
3009
+ }
3010
+ return val;
3011
+ }
3012
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
3013
+ }
3014
+ function parseDate(ctx, c, endChr) {
3015
+ let startPtr = ctx.p++, unsafeSeparator;
3016
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
3017
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
3018
+ }
3019
+ ctx.p += 5;
3020
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
3021
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
3022
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
3023
+ let t2 = ctx.s.slice(startPtr, ctx.p);
3024
+ return readDate(ctx, t2, 3, false, startPtr);
3025
+ }
3026
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
3027
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
3028
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
3029
+ ctx.p += 3;
3030
+ if (ctx.s.charCodeAt(ctx.p) === 46)
3031
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
3032
+ ;
3033
+ if (c = ctx.s.charCodeAt(ctx.p)) {
3034
+ if (c === 90 || c === 122) {
3035
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
3036
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
3037
+ }
3038
+ if (c === 43 || c === 45) {
3039
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
3040
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
3041
+ }
3042
+ }
3043
+ let t = ctx.s.slice(startPtr, ctx.p);
3044
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
3045
+ }
3046
+ function parseTime(ctx, c, endChr) {
3047
+ let start = ctx.p;
3048
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
3049
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
3050
+ }
3051
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
3052
+ ctx.p += 3;
3053
+ if (ctx.s.charCodeAt(ctx.p) === 46)
3054
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
3055
+ ;
3056
+ let t = ctx.s.slice(start, ctx.p);
3057
+ return readDate(ctx, t, 4, false, start);
3058
+ }
3059
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
3060
+ if (ctx.ld) {
3061
+ let date = new TomlDate(str, type, unsafeDelim);
3062
+ if (!date.isValid())
3063
+ TomlError.x("invalid date", ctx, errPtr);
3064
+ return date;
3065
+ }
3066
+ try {
3067
+ if (temporalSuffix)
3068
+ str += temporalSuffix;
3069
+ switch (type) {
3070
+ case 1:
3071
+ return Temporal.ZonedDateTime.from(str);
3072
+ case 2:
3073
+ return Temporal.PlainDateTime.from(str);
3074
+ case 3:
3075
+ return Temporal.PlainDate.from(str);
3076
+ case 4:
3077
+ return Temporal.PlainTime.from(str);
3078
+ }
3079
+ } catch (e) {
3080
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
3081
+ }
3082
+ }
3083
+
3084
+ function skipComment(ctx) {
3085
+ for (; ctx.p < ctx.s.length; ctx.p++) {
3086
+ let c = ctx.s.charCodeAt(ctx.p);
3087
+ if (c === 10)
3088
+ break;
3089
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
3090
+ ctx.p++;
3091
+ break;
3092
+ }
3093
+ if (c < 32 && c !== 9 || c === 127) {
3094
+ TomlError.x("control characters are not allowed in comments", ctx);
3095
+ }
3096
+ }
3097
+ }
3098
+ function skipVoid(ctx, banNewLines, banComments) {
3099
+ let c;
3100
+ while (ctx.p < ctx.s.length) {
3101
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
3102
+ ctx.p++;
3103
+ if (banComments || c !== 35)
3104
+ break;
3105
+ skipComment(ctx);
3106
+ }
3107
+ }
3108
+
3109
+ function parseKey(ctx, end = 61) {
3110
+ let startPtr;
3111
+ let state = 0;
3112
+ let parsed = [];
3113
+ let sliceStart;
3114
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
3115
+ do {
3116
+ if (c === end) {
3117
+ if (!state)
3118
+ TomlError.x("unexpected end of key", ctx);
3119
+ if (state === 1)
3120
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3121
+ return ctx.p++, parsed;
3122
+ } else if (c === 46) {
3123
+ if (!state)
3124
+ TomlError.x("illegal empty bare key", ctx);
3125
+ if (state === 1)
3126
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3127
+ state = 0;
3128
+ } else if (!state && (c === 34 || c === 39)) {
3129
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
3130
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
3131
+ parsed.push(parseString(ctx));
3132
+ state = 2;
3133
+ ctx.p--;
3134
+ } else if (c === 32 || c === 9) {
3135
+ if (state === 1) {
3136
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3137
+ state = 2;
3138
+ }
3139
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
3140
+ TomlError.x("illegal character in key", ctx);
3141
+ } else if (!state) {
3142
+ state = 1;
3143
+ sliceStart = ctx.p;
3144
+ }
3145
+ } while (c = ctx.s.charCodeAt(++ctx.p));
3146
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
3147
+ }
3148
+ function parseInlineTable(ctx) {
3149
+ let startPtr = ctx.p++;
3150
+ let res = /* @__PURE__ */ Object.create(null);
3151
+ let seen = /* @__PURE__ */ new Set();
3152
+ let c;
3153
+ while (ctx.p < ctx.s.length) {
3154
+ skipVoid(ctx);
3155
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
3156
+ ctx.p++;
3157
+ return res;
3158
+ }
3159
+ let k;
3160
+ let t = res;
3161
+ let hasOwn = false;
3162
+ let errPtr = ctx.p;
3163
+ let key = parseKey(ctx);
3164
+ for (let i = 0; i < key.length; i++) {
3165
+ if (i)
3166
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3167
+ k = key[i];
3168
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
3169
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3170
+ }
3171
+ let unsafe = k === "__proto__";
3172
+ if (ctx.uk && (unsafe || k === "constructor")) {
3173
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
3174
+ break;
3175
+ }
3176
+ if (!hasOwn && unsafe) {
3177
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3178
+ }
3179
+ }
3180
+ if (hasOwn) {
3181
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3182
+ }
3183
+ skipVoid(ctx, true, true);
3184
+ let value = extractValue(
3185
+ ctx,
3186
+ 125
3187
+ /* } */
3188
+ );
3189
+ if (t && typeof (t[k] = value) === "object")
3190
+ seen.add(value);
3191
+ skipVoid(ctx);
3192
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
3193
+ return res;
3194
+ }
3195
+ if (c !== 44)
3196
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3197
+ }
3198
+ TomlError.x("unfinished table", ctx, startPtr);
3199
+ }
3200
+ function parseArray(ctx) {
3201
+ let startPtr = ctx.p++;
3202
+ let res = [];
3203
+ let c;
3204
+ while (ctx.p < ctx.s.length) {
3205
+ skipVoid(ctx);
3206
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
3207
+ ctx.p++;
3208
+ return res;
3209
+ }
3210
+ res.push(extractValue(
3211
+ ctx,
3212
+ 93
3213
+ /* ] */
3214
+ ));
3215
+ skipVoid(ctx);
3216
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
3217
+ return res;
3218
+ }
3219
+ if (c !== 44)
3220
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3221
+ }
3222
+ TomlError.x("unfinished array", ctx, startPtr);
3223
+ }
3224
+
3225
+ function peekTable(ctx, key, table, meta, type) {
3226
+ let t = table;
3227
+ let m = meta;
3228
+ let k;
3229
+ let hasOwn = false;
3230
+ let state;
3231
+ for (let i = 0; i < key.length; i++) {
3232
+ if (i) {
3233
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3234
+ m = (state = m[k]).c;
3235
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
3236
+ return null;
3237
+ }
3238
+ if (state.t === 2) {
3239
+ let l = t.length - 1;
3240
+ t = t[l];
3241
+ m = m[l].c;
3242
+ }
3243
+ }
3244
+ k = key[i];
3245
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
3246
+ return null;
3247
+ }
3248
+ if (!hasOwn) {
3249
+ let unsafe = k === "__proto__";
3250
+ if (ctx.uk && (unsafe || k === "constructor"))
3251
+ return false;
3252
+ if (unsafe) {
3253
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3254
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
3255
+ }
3256
+ m[k] = {
3257
+ t: i < key.length - 1 && type === 2 ? 3 : type,
3258
+ d: false,
3259
+ i: 0,
3260
+ c: /* @__PURE__ */ Object.create(null)
3261
+ };
3262
+ }
3263
+ }
3264
+ state = m[k];
3265
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
3266
+ return null;
3267
+ }
3268
+ if (type === 2) {
3269
+ if (!state.d) {
3270
+ state.d = true;
3271
+ t[k] = [];
3272
+ }
3273
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
3274
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
3275
+ }
3276
+ if (state.d) {
3277
+ return null;
3278
+ }
3279
+ state.d = true;
3280
+ if (type === 1) {
3281
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3282
+ } else if (type === 0 && hasOwn) {
3283
+ return null;
3284
+ }
3285
+ return [k, t, state.c];
3286
+ }
3287
+ function validateTablePeek(ctx, peek, ptr) {
3288
+ if (peek === null || ctx.uk === 2)
3289
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
3290
+ }
3291
+ function parse(toml, options = {}) {
3292
+ let ctx = {
3293
+ s: toml,
3294
+ p: 0,
3295
+ d: options.maxDepth ?? 1e3,
3296
+ bi: options.integersAsBigInt ?? false,
3297
+ ld: options.useLegacyDate ?? true,
3298
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
3299
+ };
3300
+ let res = /* @__PURE__ */ Object.create(null);
3301
+ let meta = /* @__PURE__ */ Object.create(null);
3302
+ let tmp;
3303
+ let skipping = false;
3304
+ let tbl = res;
3305
+ let m = meta;
3306
+ if (toml.charCodeAt(0) === 65279)
3307
+ ctx.p++;
3308
+ skipVoid(ctx);
3309
+ while (ctx.p < toml.length) {
3310
+ if (toml.charCodeAt(ctx.p) === 91) {
3311
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
3312
+ tmp = ctx.p += +isTableArray;
3313
+ skipping = false;
3314
+ let k = parseKey(
3315
+ ctx,
3316
+ 93
3317
+ /* ] */
3318
+ );
3319
+ if (isTableArray) {
3320
+ if (toml.charCodeAt(ctx.p) !== 93) {
3321
+ TomlError.x("expected end of table array declaration", ctx);
3322
+ }
3323
+ ctx.p++;
3324
+ }
3325
+ let p = peekTable(
3326
+ ctx,
3327
+ k,
3328
+ res,
3329
+ meta,
3330
+ isTableArray ? 2 : 1
3331
+ /* Type.EXPLICIT */
3332
+ );
3333
+ if (!p) {
3334
+ validateTablePeek(ctx, p, tmp);
3335
+ skipping = true;
3336
+ } else {
3337
+ m = p[2];
3338
+ tbl = p[1];
3339
+ }
3340
+ } else {
3341
+ tmp = ctx.p;
3342
+ let k = parseKey(ctx);
3343
+ let p = peekTable(
3344
+ ctx,
3345
+ k,
3346
+ tbl,
3347
+ m,
3348
+ 0
3349
+ /* Type.DOTTED */
3350
+ );
3351
+ if (!p && !skipping)
3352
+ validateTablePeek(ctx, p, tmp);
3353
+ skipVoid(ctx, true, true);
3354
+ let v = extractValue(ctx, void 0);
3355
+ if (p && !skipping)
3356
+ p[1][p[0]] = v;
3357
+ }
3358
+ skipVoid(ctx, true);
3359
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
3360
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
3361
+ }
3362
+ skipVoid(ctx);
3363
+ }
3364
+ return res;
3365
+ }
3366
+
3367
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
3368
+ function formatTomlKey(key) {
3369
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
3370
+ }
3371
+ function formatTomlValue(value) {
3372
+ if (typeof value === "boolean") return value ? "true" : "false";
3373
+ return JSON.stringify(value).replace(/\u007f/g, "\\u007F");
3374
+ }
3375
+ function splitDottedKey(raw) {
3376
+ const parts = [];
3377
+ let i = 0;
3378
+ const s = raw.trim();
3379
+ while (i < s.length) {
3380
+ while (s[i] === " " || s[i] === " ") i++;
3381
+ let part = "";
3382
+ if (s[i] === '"') {
3383
+ let j = i + 1;
3384
+ while (j < s.length && s[j] !== '"') {
3385
+ if (s[j] === "\\") j++;
3386
+ j++;
3387
+ }
3388
+ if (j >= s.length) return null;
3389
+ try {
3390
+ part = JSON.parse(s.slice(i, j + 1));
3391
+ } catch {
3392
+ return null;
3393
+ }
3394
+ i = j + 1;
3395
+ } else if (s[i] === "'") {
3396
+ const j = s.indexOf("'", i + 1);
3397
+ if (j < 0) return null;
3398
+ part = s.slice(i + 1, j);
3399
+ i = j + 1;
3400
+ } else {
3401
+ let j = i;
3402
+ while (j < s.length && /[A-Za-z0-9_-]/.test(s[j])) j++;
3403
+ if (j === i) return null;
3404
+ part = s.slice(i, j);
3405
+ i = j;
3406
+ }
3407
+ parts.push(part);
3408
+ while (s[i] === " " || s[i] === " ") i++;
3409
+ if (i >= s.length) break;
3410
+ if (s[i] !== ".") return null;
3411
+ i++;
3412
+ }
3413
+ return parts.length ? parts : null;
3414
+ }
3415
+ function scan(lines) {
3416
+ const sections = [{ path: null, arrayTable: false, headerLine: -1, start: 0, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: -1 }];
3417
+ let inMulti = null;
3418
+ let depth = 0;
3419
+ for (let n = 0; n < lines.length; n++) {
3420
+ const line = lines[n];
3421
+ const current = sections[sections.length - 1];
3422
+ if (inMulti) {
3423
+ if (line.includes(inMulti)) {
3424
+ inMulti = null;
3425
+ current.lastKeyLine = n;
3426
+ }
3427
+ continue;
3428
+ }
3429
+ const trimmed = line.trim();
3430
+ if (depth === 0) {
3431
+ const header = /^\[(\[)?\s*([^\[\]]+?)\s*\](\])?\s*(#.*)?$/.exec(trimmed);
3432
+ if (header) {
3433
+ current.end = n;
3434
+ const path = splitDottedKey(header[2]);
3435
+ sections.push({ path: path ?? [`\0invalid:${header[2]}`], arrayTable: !!header[1], headerLine: n, start: n + 1, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: n });
3436
+ continue;
3437
+ }
3438
+ const kv = /^((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s"'-])+?)\s*=/.exec(trimmed);
3439
+ if (kv) {
3440
+ const keyPath = splitDottedKey(kv[1]);
3441
+ if (keyPath) current.keys.set(keyPath.join("\0"), n);
3442
+ current.lastKeyLine = n;
3443
+ }
3444
+ } else if (trimmed) {
3445
+ current.lastKeyLine = n;
3446
+ }
3447
+ let i = 0;
3448
+ while (i < line.length) {
3449
+ const ch = line[i];
3450
+ if (ch === "#") break;
3451
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
3452
+ const fence = line.slice(i, i + 3);
3453
+ const close = line.indexOf(fence, i + 3);
3454
+ if (close < 0) {
3455
+ inMulti = fence;
3456
+ break;
3457
+ }
3458
+ i = close + 3;
3459
+ continue;
3460
+ }
3461
+ if (ch === '"') {
3462
+ i++;
3463
+ while (i < line.length && line[i] !== '"') {
3464
+ if (line[i] === "\\") i++;
3465
+ i++;
3466
+ }
3467
+ i++;
3468
+ continue;
3469
+ }
3470
+ if (ch === "'") {
3471
+ const close = line.indexOf("'", i + 1);
3472
+ i = close < 0 ? line.length : close + 1;
3473
+ continue;
3474
+ }
3475
+ if (ch === "[" || ch === "{") depth++;
3476
+ if (ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
3477
+ i++;
3478
+ }
3479
+ }
3480
+ return sections;
3481
+ }
3482
+ function trailingComment(line) {
3483
+ const m = /^\s*[^=]+=\s*("(?:[^"\\]|\\.)*"|'[^']*'|true|false|[0-9][0-9_.eE+-]*)(\s+#.*)$/.exec(line);
3484
+ return m ? m[2] : "";
3485
+ }
3486
+ const samePath = (a, b) => a !== null && a.length === b.length && a.every((p, i) => p === b[i]);
3487
+ const isUnder = (a, prefix) => a !== null && a.length >= prefix.length && prefix.every((p, i) => p === a[i]);
3488
+ function applyOne(text, edit) {
3489
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3490
+ const lines = text.split(/\r?\n/);
3491
+ const sections = scan(lines);
3492
+ if ("removeTable" in edit) {
3493
+ const doomed = sections.filter((s) => !s.arrayTable && isUnder(s.path, edit.table)).sort((a, b) => b.headerLine - a.headerLine);
3494
+ for (const s of doomed) {
3495
+ let end = s.end;
3496
+ while (end > s.start && lines[end - 1]?.trim() === "" && end - 1 > s.lastKeyLine) end--;
3497
+ lines.splice(s.headerLine, end - s.headerLine);
3498
+ }
3499
+ return lines.join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`).replace(/(\r?\n)+$/, eol);
3500
+ }
3501
+ const root = edit.table.length === 0;
3502
+ const section = root ? sections[0] : sections.find((s) => !s.arrayTable && samePath(s.path, edit.table));
3503
+ const keyId = edit.key;
3504
+ const rendered = edit.value === null ? null : `${formatTomlKey(edit.key)} = ${formatTomlValue(edit.value)}`;
3505
+ if (section) {
3506
+ const at = section.keys.get(keyId);
3507
+ if (at !== void 0) {
3508
+ const indent = /^\s*/.exec(lines[at])?.[0] ?? "";
3509
+ if (rendered === null) lines.splice(at, 1);
3510
+ else lines[at] = indent + rendered + trailingComment(lines[at]);
3511
+ return lines.join(eol);
3512
+ }
3513
+ if (rendered === null) return text;
3514
+ if (root) {
3515
+ const anchor = section.lastKeyLine;
3516
+ lines.splice(anchor + 1, 0, rendered);
3517
+ } else {
3518
+ lines.splice(section.lastKeyLine + 1, 0, rendered);
3519
+ }
3520
+ return lines.join(eol);
3521
+ }
3522
+ if (rendered === null) return text;
3523
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
3524
+ const header = `[${edit.table.map(formatTomlKey).join(".")}]`;
3525
+ if (lines.length) lines.push("");
3526
+ lines.push(header, rendered, "");
3527
+ return lines.join(eol);
3528
+ }
3529
+ function parseToml(text) {
3530
+ try {
3531
+ return parse(text);
3532
+ } catch (error) {
3533
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
3534
+ throw new mirrorProtocol.ModelConfigError("invalid-toml", `Not valid TOML: ${message}`);
3535
+ }
3536
+ }
3537
+ function getPath(obj, path) {
3538
+ let cur = obj;
3539
+ for (const p of path) {
3540
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
3541
+ cur = cur[p];
3542
+ }
3543
+ return cur;
3544
+ }
3545
+ function withoutPaths(obj, paths) {
3546
+ const clone = structuredClone(obj);
3547
+ for (const path of paths) {
3548
+ let cur = clone;
3549
+ for (const p of path.slice(0, -1)) {
3550
+ if (!cur || typeof cur !== "object") {
3551
+ cur = null;
3552
+ break;
3553
+ }
3554
+ cur = cur[p];
3555
+ }
3556
+ if (cur && typeof cur === "object") delete cur[path[path.length - 1]];
3557
+ }
3558
+ return clone;
3559
+ }
3560
+ function pruneEmpty(value) {
3561
+ if (!value || typeof value !== "object" || Array.isArray(value) || value instanceof Date) return value;
3562
+ const out = {};
3563
+ for (const [k, v] of Object.entries(value)) {
3564
+ const pruned = pruneEmpty(v);
3565
+ if (pruned && typeof pruned === "object" && !Array.isArray(pruned) && !(pruned instanceof Date) && Object.keys(pruned).length === 0) continue;
3566
+ out[k] = pruned;
3567
+ }
3568
+ return out;
3569
+ }
3570
+ function stableStringify(value) {
3571
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
3572
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
3573
+ if (value && typeof value === "object") {
3574
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
3575
+ }
3576
+ return JSON.stringify(value) ?? "null";
3577
+ }
3578
+ function verifyTomlEdit(oldText, newText, edits) {
3579
+ const before = parseToml(oldText);
3580
+ let after;
3581
+ try {
3582
+ after = parse(newText);
3583
+ } catch (error) {
3584
+ throw new mirrorProtocol.ModelConfigError("unsafe-edit", `Edit would produce invalid TOML (${error instanceof Error ? error.message.split("\n")[0] : String(error)}); the file layout is not one this editor can change safely`);
3585
+ }
3586
+ const owned = edits.map((e) => "removeTable" in e ? e.table : [...e.table, e.key]);
3587
+ for (const edit of edits) {
3588
+ if ("removeTable" in edit) {
3589
+ if (getPath(after, edit.table) !== void 0) throw new mirrorProtocol.ModelConfigError("unsafe-edit", `Table ${edit.table.join(".")} is still present after removal`);
3590
+ continue;
3591
+ }
3592
+ const got = getPath(after, [...edit.table, edit.key]);
3593
+ const want = edit.value === null ? void 0 : edit.value;
3594
+ if (got !== want) throw new mirrorProtocol.ModelConfigError("unsafe-edit", `Key ${[...edit.table, edit.key].join(".")} did not take the requested value`);
3595
+ }
3596
+ if (stableStringify(pruneEmpty(withoutPaths(before, owned))) !== stableStringify(pruneEmpty(withoutPaths(after, owned)))) {
3597
+ throw new mirrorProtocol.ModelConfigError("unsafe-edit", "Edit would change settings outside the keys Very Happy manages");
3598
+ }
3599
+ }
3600
+ function editToml(text, edits) {
3601
+ parseToml(text);
3602
+ let out = text;
3603
+ const ordered = [...edits.filter((e) => e.table.length === 0), ...edits.filter((e) => e.table.length > 0)];
3604
+ for (const edit of ordered) out = applyOne(out, edit);
3605
+ if (out !== text && !out.endsWith("\n")) out += text.includes("\r\n") ? "\r\n" : "\n";
3606
+ verifyTomlEdit(text, out, edits);
3607
+ return out;
3608
+ }
3609
+
3610
+ const ROLE = "config";
3611
+ const CODEX_RESERVED_PROVIDERS = ["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "oss"];
3612
+ function codexConfigPath(ctx) {
3613
+ const dir = ctx.env.CODEX_HOME?.trim() || path.join(ctx.home, ".codex");
3614
+ return path.join(dir, "config.toml");
3615
+ }
3616
+ const str$3 = (v) => typeof v === "string" && v.trim() ? v : null;
3617
+ function providersOf$1(doc) {
3618
+ const table = doc.model_providers;
3619
+ if (!table || typeof table !== "object" || Array.isArray(table)) return {};
3620
+ return Object.fromEntries(Object.entries(table).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
3621
+ }
3622
+ function secretView$1(provider, ctx) {
3623
+ if (!provider) return { mode: "none" };
3624
+ const token = str$3(provider.experimental_bearer_token);
3625
+ if (token) return { mode: "literal", masked: maskSecret(token) };
3626
+ const envKey = str$3(provider.env_key);
3627
+ if (envKey) return { mode: "env", envName: envKey, envPresent: !!ctx.env[envKey] };
3628
+ if (provider.auth && typeof provider.auth === "object") return { mode: "command" };
3629
+ return { mode: "none" };
3630
+ }
3631
+ function selectProvider(doc, requested) {
3632
+ const providers = providersOf$1(doc);
3633
+ if (requested) return requested;
3634
+ const active = str$3(doc.model_provider);
3635
+ if (active && providers[active]) return active;
3636
+ return Object.keys(providers)[0] ?? null;
3637
+ }
3638
+ function currentOf$2(doc, providerId, ctx) {
3639
+ const provider = providerId ? providersOf$1(doc)[providerId] : void 0;
3640
+ const activeProvider = str$3(doc.model_provider);
3641
+ return {
3642
+ providerId,
3643
+ providerName: str$3(provider?.name),
3644
+ baseUrl: str$3(provider?.base_url),
3645
+ apiKey: secretView$1(provider, ctx),
3646
+ model: str$3(doc.model),
3647
+ activeProvider,
3648
+ active: !!providerId && activeProvider === providerId
3649
+ };
3650
+ }
3651
+ function warningsOf$2(doc, current) {
3652
+ const out = [...baseUrlWarnings(current.baseUrl, "openai")];
3653
+ const provider = current.providerId ? providersOf$1(doc)[current.providerId] : void 0;
3654
+ if (provider && str$3(provider.wire_api) && provider.wire_api !== "responses") {
3655
+ out.push({ code: "wire-api-unsupported", message: `wire_api = "${String(provider.wire_api)}" is rejected by current Codex; only "responses" is supported.` });
3656
+ }
3657
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
3658
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
3659
+ }
3660
+ const active = current.activeProvider;
3661
+ if (active && !CODEX_RESERVED_PROVIDERS.includes(active) && !providersOf$1(doc)[active]) {
3662
+ out.push({ code: "active-provider-missing", message: `model_provider = "${active}" has no [model_providers.${active}] table.` });
3663
+ }
3664
+ return out;
3665
+ }
3666
+ function parsePatch(raw) {
3667
+ const p = raw;
3668
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") fail("invalid-input", "activate must be a boolean");
3669
+ if (p.providerName !== void 0 && (typeof p.providerName !== "string" || p.providerName.length > 120 || /[\u0000-\u001f]/.test(p.providerName))) {
3670
+ fail("invalid-input", "providerName must be a short single-line string");
3671
+ }
3672
+ return {
3673
+ providerId: normalizeProviderId(p.providerId, CODEX_RESERVED_PROVIDERS),
3674
+ providerName: p.providerName?.trim(),
3675
+ baseUrl: normalizeBaseUrl(p.baseUrl),
3676
+ apiKey: normalizeSecret(p.apiKey),
3677
+ model: normalizeModelId(p.model),
3678
+ activate: p.activate
3679
+ };
3680
+ }
3681
+ const codexAdapter = {
3682
+ id: "codex",
3683
+ binary: "codex",
3684
+ files: (ctx) => [{ role: ROLE, path: codexConfigPath(ctx) }],
3685
+ view(files, ctx, opts) {
3686
+ const doc = parseToml(files[ROLE].content);
3687
+ const current = currentOf$2(doc, selectProvider(doc, opts.providerId), ctx);
3688
+ return { current, providers: Object.keys(providersOf$1(doc)), pickerModels: uniq([current.model]), warnings: warningsOf$2(doc, current) };
3689
+ },
3690
+ plan(files, raw, ctx) {
3691
+ const patch = parsePatch(raw);
3692
+ const original = files[ROLE].content;
3693
+ const before = parseToml(original);
3694
+ const existing = providersOf$1(before)[patch.providerId];
3695
+ const table = ["model_providers", patch.providerId];
3696
+ const edits = [];
3697
+ const secrets = [];
3698
+ if (!existing && !patch.baseUrl) fail("invalid-input", "A new provider needs a base URL");
3699
+ const name = patch.providerName || str$3(existing?.name) || patch.providerId;
3700
+ if (!existing || patch.providerName && patch.providerName !== existing.name || !str$3(existing.name)) edits.push({ table, key: "name", value: name });
3701
+ if (patch.baseUrl !== void 0) {
3702
+ if (patch.baseUrl === null && existing) fail("invalid-input", "A provider needs a base URL; remove the provider instead");
3703
+ edits.push({ table, key: "base_url", value: patch.baseUrl });
3704
+ }
3705
+ if (!existing || str$3(existing.wire_api) && existing.wire_api !== "responses") edits.push({ table, key: "wire_api", value: "responses" });
3706
+ switch (patch.apiKey.mode) {
3707
+ case "literal":
3708
+ edits.push({ table, key: "experimental_bearer_token", value: patch.apiKey.value }, { table, key: "env_key", value: null });
3709
+ secrets.push(patch.apiKey.value);
3710
+ break;
3711
+ case "env":
3712
+ edits.push({ table, key: "env_key", value: patch.apiKey.name }, { table, key: "experimental_bearer_token", value: null });
3713
+ break;
3714
+ case "clear":
3715
+ edits.push({ table, key: "env_key", value: null }, { table, key: "experimental_bearer_token", value: null });
3716
+ break;
3717
+ }
3718
+ if (patch.model !== void 0) edits.push({ table: [], key: "model", value: patch.model });
3719
+ if (patch.activate === true) edits.push({ table: [], key: "model_provider", value: patch.providerId });
3720
+ if (patch.activate === false && str$3(before.model_provider) === patch.providerId) edits.push({ table: [], key: "model_provider", value: null });
3721
+ const effective = edits.filter((e) => "removeTable" in e || getPath$1(before, [...e.table, e.key]) !== (e.value ?? void 0));
3722
+ const content = effective.length ? editToml(original, effective) : void 0;
3723
+ const after = content === void 0 ? before : parseToml(content);
3724
+ const current = currentOf$2(after, patch.providerId, ctx);
3725
+ const changedKeys = effective.map((e) => [...e.table, "removeTable" in e ? "*" : e.key].join("."));
3726
+ return { contents: { [ROLE]: content }, warnings: warningsOf$2(after, current), changedKeys, secrets };
3727
+ },
3728
+ secretsIn(_role, content) {
3729
+ try {
3730
+ return collectSecretValues(parseToml(content));
3731
+ } catch (error) {
3732
+ if (error instanceof mirrorProtocol.ModelConfigError) return /* @__PURE__ */ new Set();
3733
+ throw error;
3734
+ }
3735
+ }
3736
+ };
3737
+
3738
+ var main = {exports: {}};
3739
+
3740
+ var version = "16.6.1";
3741
+ var require$$4 = {
3742
+ version: version};
3743
+
3744
+ var hasRequiredMain;
3745
+
3746
+ function requireMain () {
3747
+ if (hasRequiredMain) return main.exports;
3748
+ hasRequiredMain = 1;
3749
+ const fs = require$$0;
3750
+ const path = require$$1;
3751
+ const os = os$1;
3752
+ const crypto = require$$3;
3753
+ const packageJson = require$$4;
3754
+ const version = packageJson.version;
3755
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
3756
+ function parse(src) {
3757
+ const obj = {};
3758
+ let lines = src.toString();
3759
+ lines = lines.replace(/\r\n?/mg, "\n");
3760
+ let match;
3761
+ while ((match = LINE.exec(lines)) != null) {
3762
+ const key = match[1];
3763
+ let value = match[2] || "";
3764
+ value = value.trim();
3765
+ const maybeQuote = value[0];
3766
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
3767
+ if (maybeQuote === '"') {
3768
+ value = value.replace(/\\n/g, "\n");
3769
+ value = value.replace(/\\r/g, "\r");
3770
+ }
3771
+ obj[key] = value;
3772
+ }
3773
+ return obj;
3774
+ }
3775
+ function _parseVault(options) {
3776
+ options = options || {};
3777
+ const vaultPath = _vaultPath(options);
3778
+ options.path = vaultPath;
3779
+ const result = DotenvModule.configDotenv(options);
3780
+ if (!result.parsed) {
3781
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
3782
+ err.code = "MISSING_DATA";
3783
+ throw err;
3784
+ }
3785
+ const keys = _dotenvKey(options).split(",");
3786
+ const length = keys.length;
3787
+ let decrypted;
3788
+ for (let i = 0; i < length; i++) {
3789
+ try {
3790
+ const key = keys[i].trim();
3791
+ const attrs = _instructions(result, key);
3792
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
3793
+ break;
3794
+ } catch (error) {
3795
+ if (i + 1 >= length) {
3796
+ throw error;
3797
+ }
3798
+ }
3799
+ }
3800
+ return DotenvModule.parse(decrypted);
3801
+ }
3802
+ function _warn(message) {
3803
+ console.log(`[dotenv@${version}][WARN] ${message}`);
3804
+ }
3805
+ function _debug(message) {
3806
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
3807
+ }
3808
+ function _log(message) {
3809
+ console.log(`[dotenv@${version}] ${message}`);
3810
+ }
3811
+ function _dotenvKey(options) {
3812
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
3813
+ return options.DOTENV_KEY;
3814
+ }
3815
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
3816
+ return process.env.DOTENV_KEY;
3817
+ }
3818
+ return "";
3819
+ }
3820
+ function _instructions(result, dotenvKey) {
3821
+ let uri;
3822
+ try {
3823
+ uri = new URL(dotenvKey);
3824
+ } catch (error) {
3825
+ if (error.code === "ERR_INVALID_URL") {
3826
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
3827
+ err.code = "INVALID_DOTENV_KEY";
3828
+ throw err;
3829
+ }
3830
+ throw error;
3831
+ }
3832
+ const key = uri.password;
3833
+ if (!key) {
3834
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
3835
+ err.code = "INVALID_DOTENV_KEY";
3836
+ throw err;
3837
+ }
3838
+ const environment = uri.searchParams.get("environment");
3839
+ if (!environment) {
3840
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
3841
+ err.code = "INVALID_DOTENV_KEY";
3842
+ throw err;
3843
+ }
3844
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
3845
+ const ciphertext = result.parsed[environmentKey];
3846
+ if (!ciphertext) {
3847
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
3848
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
3849
+ throw err;
3850
+ }
3851
+ return { ciphertext, key };
3852
+ }
3853
+ function _vaultPath(options) {
3854
+ let possibleVaultPath = null;
3855
+ if (options && options.path && options.path.length > 0) {
3856
+ if (Array.isArray(options.path)) {
3857
+ for (const filepath of options.path) {
3858
+ if (fs.existsSync(filepath)) {
3859
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
3860
+ }
3861
+ }
3862
+ } else {
3863
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
3864
+ }
3865
+ } else {
3866
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
3867
+ }
3868
+ if (fs.existsSync(possibleVaultPath)) {
3869
+ return possibleVaultPath;
3870
+ }
3871
+ return null;
3872
+ }
3873
+ function _resolveHome(envPath) {
3874
+ return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
3875
+ }
3876
+ function _configVault(options) {
3877
+ const debug = Boolean(options && options.debug);
3878
+ const quiet = options && "quiet" in options ? options.quiet : true;
3879
+ if (debug || !quiet) {
3880
+ _log("Loading env from encrypted .env.vault");
3881
+ }
3882
+ const parsed = DotenvModule._parseVault(options);
3883
+ let processEnv = process.env;
3884
+ if (options && options.processEnv != null) {
3885
+ processEnv = options.processEnv;
3886
+ }
3887
+ DotenvModule.populate(processEnv, parsed, options);
3888
+ return { parsed };
3889
+ }
3890
+ function configDotenv(options) {
3891
+ const dotenvPath = path.resolve(process.cwd(), ".env");
3892
+ let encoding = "utf8";
3893
+ const debug = Boolean(options && options.debug);
3894
+ const quiet = options && "quiet" in options ? options.quiet : true;
3895
+ if (options && options.encoding) {
3896
+ encoding = options.encoding;
3897
+ } else {
3898
+ if (debug) {
3899
+ _debug("No encoding is specified. UTF-8 is used by default");
3900
+ }
3901
+ }
3902
+ let optionPaths = [dotenvPath];
3903
+ if (options && options.path) {
3904
+ if (!Array.isArray(options.path)) {
3905
+ optionPaths = [_resolveHome(options.path)];
3906
+ } else {
3907
+ optionPaths = [];
3908
+ for (const filepath of options.path) {
3909
+ optionPaths.push(_resolveHome(filepath));
3910
+ }
3911
+ }
3912
+ }
3913
+ let lastError;
3914
+ const parsedAll = {};
3915
+ for (const path2 of optionPaths) {
3916
+ try {
3917
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
3918
+ DotenvModule.populate(parsedAll, parsed, options);
3919
+ } catch (e) {
3920
+ if (debug) {
3921
+ _debug(`Failed to load ${path2} ${e.message}`);
3922
+ }
3923
+ lastError = e;
3924
+ }
3925
+ }
3926
+ let processEnv = process.env;
3927
+ if (options && options.processEnv != null) {
3928
+ processEnv = options.processEnv;
3929
+ }
3930
+ DotenvModule.populate(processEnv, parsedAll, options);
3931
+ if (debug || !quiet) {
3932
+ const keysCount = Object.keys(parsedAll).length;
3933
+ const shortPaths = [];
3934
+ for (const filePath of optionPaths) {
3935
+ try {
3936
+ const relative = path.relative(process.cwd(), filePath);
3937
+ shortPaths.push(relative);
3938
+ } catch (e) {
3939
+ if (debug) {
3940
+ _debug(`Failed to load ${filePath} ${e.message}`);
3941
+ }
3942
+ lastError = e;
3943
+ }
3944
+ }
3945
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
3946
+ }
3947
+ if (lastError) {
3948
+ return { parsed: parsedAll, error: lastError };
3949
+ } else {
3950
+ return { parsed: parsedAll };
3951
+ }
3952
+ }
3953
+ function config(options) {
3954
+ if (_dotenvKey(options).length === 0) {
3955
+ return DotenvModule.configDotenv(options);
3956
+ }
3957
+ const vaultPath = _vaultPath(options);
3958
+ if (!vaultPath) {
3959
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
3960
+ return DotenvModule.configDotenv(options);
3961
+ }
3962
+ return DotenvModule._configVault(options);
3963
+ }
3964
+ function decrypt(encrypted, keyStr) {
3965
+ const key = Buffer.from(keyStr.slice(-64), "hex");
3966
+ let ciphertext = Buffer.from(encrypted, "base64");
3967
+ const nonce = ciphertext.subarray(0, 12);
3968
+ const authTag = ciphertext.subarray(-16);
3969
+ ciphertext = ciphertext.subarray(12, -16);
3970
+ try {
3971
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
3972
+ aesgcm.setAuthTag(authTag);
3973
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
3974
+ } catch (error) {
3975
+ const isRange = error instanceof RangeError;
3976
+ const invalidKeyLength = error.message === "Invalid key length";
3977
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
3978
+ if (isRange || invalidKeyLength) {
3979
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
3980
+ err.code = "INVALID_DOTENV_KEY";
3981
+ throw err;
3982
+ } else if (decryptionFailed) {
3983
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
3984
+ err.code = "DECRYPTION_FAILED";
3985
+ throw err;
3986
+ } else {
3987
+ throw error;
3988
+ }
3989
+ }
3990
+ }
3991
+ function populate(processEnv, parsed, options = {}) {
3992
+ const debug = Boolean(options && options.debug);
3993
+ const override = Boolean(options && options.override);
3994
+ if (typeof parsed !== "object") {
3995
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
3996
+ err.code = "OBJECT_REQUIRED";
3997
+ throw err;
3998
+ }
3999
+ for (const key of Object.keys(parsed)) {
4000
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
4001
+ if (override === true) {
4002
+ processEnv[key] = parsed[key];
4003
+ }
4004
+ if (debug) {
4005
+ if (override === true) {
4006
+ _debug(`"${key}" is already defined and WAS overwritten`);
4007
+ } else {
4008
+ _debug(`"${key}" is already defined and was NOT overwritten`);
4009
+ }
4010
+ }
4011
+ } else {
4012
+ processEnv[key] = parsed[key];
4013
+ }
4014
+ }
4015
+ }
4016
+ const DotenvModule = {
4017
+ configDotenv,
4018
+ _configVault,
4019
+ _parseVault,
4020
+ config,
4021
+ decrypt,
4022
+ parse,
4023
+ populate
4024
+ };
4025
+ main.exports.configDotenv = DotenvModule.configDotenv;
4026
+ main.exports._configVault = DotenvModule._configVault;
4027
+ main.exports._parseVault = DotenvModule._parseVault;
4028
+ main.exports.config = DotenvModule.config;
4029
+ main.exports.decrypt = DotenvModule.decrypt;
4030
+ main.exports.parse = DotenvModule.parse;
4031
+ main.exports.populate = DotenvModule.populate;
4032
+ main.exports = DotenvModule;
4033
+ return main.exports;
4034
+ }
4035
+
4036
+ var mainExports = requireMain();
4037
+
4038
+ const LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
4039
+ function parseDotenv(text) {
4040
+ return mainExports.parse(text);
4041
+ }
4042
+ function formatDotenvValue(value) {
4043
+ if (/^[A-Za-z0-9_./:@+,-]*$/.test(value)) return value;
4044
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
4045
+ }
4046
+ function editDotenv(text, edits) {
4047
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
4048
+ let lines = text === "" ? [] : text.split(/\r?\n/);
4049
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
4050
+ for (const edit of edits) {
4051
+ const at = lines.map((l, i) => LINE.exec(l)?.[1] === edit.key ? i : -1).filter((i) => i >= 0);
4052
+ if (edit.value === null) {
4053
+ lines = lines.filter((_, i) => !at.includes(i));
4054
+ continue;
4055
+ }
4056
+ const rendered = `${edit.key}=${formatDotenvValue(edit.value)}`;
4057
+ if (at.length) {
4058
+ lines[at[0]] = rendered;
4059
+ lines = lines.filter((_, i) => !at.slice(1).includes(i));
4060
+ } else {
4061
+ lines.push(rendered);
4062
+ }
4063
+ }
4064
+ const out = lines.length ? lines.join(eol) + eol : "";
4065
+ const before = mainExports.parse(text);
4066
+ const after = mainExports.parse(out);
4067
+ for (const edit of edits) {
4068
+ if ((after[edit.key] ?? null) !== edit.value) throw new mirrorProtocol.ModelConfigError("unsafe-edit", `.env edit did not produce ${edit.key} as requested`);
4069
+ delete before[edit.key];
4070
+ delete after[edit.key];
4071
+ }
4072
+ if (JSON.stringify(Object.entries(before).sort()) !== JSON.stringify(Object.entries(after).sort())) {
4073
+ throw new mirrorProtocol.ModelConfigError("unsafe-edit", ".env edit would change other variables");
4074
+ }
4075
+ return out;
4076
+ }
4077
+
4078
+ const SETTINGS$1 = "settings";
4079
+ const ENV = "env";
4080
+ const BASE_URL = "GOOGLE_GEMINI_BASE_URL";
4081
+ const API_KEY = "GEMINI_API_KEY";
4082
+ function geminiDir(ctx) {
4083
+ return path.join(ctx.env.GEMINI_CLI_HOME?.trim() || ctx.home, ".gemini");
4084
+ }
4085
+ const str$2 = (v) => typeof v === "string" && v.trim() ? v : null;
4086
+ function currentOf$1(settings, env, ctx) {
4087
+ const literal = str$2(env[API_KEY]);
4088
+ const apiKey = literal ? { mode: "literal", masked: maskSecret(literal) } : ctx.env[API_KEY] ? { mode: "env", envName: API_KEY, envPresent: true } : { mode: "none" };
4089
+ return { baseUrl: str$2(env[BASE_URL]), apiKey, model: str$2(getPath$1(settings, ["model", "name"])) };
4090
+ }
4091
+ function warningsOf$1(settings, current) {
4092
+ const out = [...baseUrlWarnings(current.baseUrl, "gemini")];
4093
+ if (current.baseUrl || current.apiKey?.mode === "literal") {
4094
+ out.push({ code: "project-env-shadows", message: "~/.gemini/.env is used only when the session folder (or a parent) has no .gemini/.env or .env of its own." });
4095
+ }
4096
+ const selected = str$2(getPath$1(settings, ["security", "auth", "selectedType"]));
4097
+ if (current.baseUrl && selected && selected !== "gateway") {
4098
+ out.push({ code: "auth-type-pinned", message: `security.auth.selectedType is "${selected}"; Gemini only uses GOOGLE_GEMINI_BASE_URL with the gateway auth type.` });
4099
+ }
4100
+ if (current.baseUrl && !/^https:/.test(current.baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(current.baseUrl)) {
4101
+ out.push({ code: "gemini-https", message: "Gemini requires an https base URL (localhost excepted)." });
4102
+ }
4103
+ return out;
4104
+ }
4105
+ const geminiAdapter = {
4106
+ id: "gemini",
4107
+ binary: "gemini",
4108
+ files: (ctx) => [{ role: SETTINGS$1, path: path.join(geminiDir(ctx), "settings.json") }, { role: ENV, path: path.join(geminiDir(ctx), ".env") }],
4109
+ view(files, ctx) {
4110
+ const settings = parseJsonObject$1(files[SETTINGS$1].content, "settings.json");
4111
+ const current = currentOf$1(settings, parseDotenv(files[ENV].content), ctx);
4112
+ return { current, pickerModels: uniq([current.model]), warnings: warningsOf$1(settings, current) };
4113
+ },
4114
+ plan(files, raw, ctx) {
4115
+ const p = raw;
4116
+ const baseUrl = normalizeBaseUrl(p.baseUrl);
4117
+ const apiKey = normalizeSecret(p.apiKey, ["keep", "clear", "literal"]);
4118
+ const model = normalizeModelId(p.model);
4119
+ const settingsText = files[SETTINGS$1].content;
4120
+ const before = parseJsonObject$1(settingsText, "settings.json");
4121
+ const settings = structuredClone(before);
4122
+ const changedKeys = [];
4123
+ let settingsOut;
4124
+ if (model !== void 0 && (str$2(getPath$1(before, ["model", "name"])) ?? null) !== model) {
4125
+ const hadModel = settings.model !== void 0;
4126
+ const modelObj = childObject(settings, "model", "settings");
4127
+ setOrDelete(modelObj, "name", model);
4128
+ if (!hadModel && Object.keys(modelObj).length === 0) delete settings.model;
4129
+ settingsOut = stringifyLike(settingsText, settings);
4130
+ changedKeys.push("settings.model.name");
4131
+ }
4132
+ const envText = files[ENV].content;
4133
+ const env = parseDotenv(envText);
4134
+ const edits = [];
4135
+ if (baseUrl !== void 0 && (env[BASE_URL] ?? null) !== baseUrl) edits.push({ key: BASE_URL, value: baseUrl });
4136
+ if (apiKey.mode === "literal" && env[API_KEY] !== apiKey.value) edits.push({ key: API_KEY, value: apiKey.value });
4137
+ if (apiKey.mode === "clear" && env[API_KEY] !== void 0) edits.push({ key: API_KEY, value: null });
4138
+ const envOut = edits.length ? editDotenv(envText, edits) : void 0;
4139
+ changedKeys.push(...edits.map((e) => `.env.${e.key}`));
4140
+ const afterEnv = envOut === void 0 ? env : parseDotenv(envOut);
4141
+ const current = currentOf$1(settings, afterEnv, ctx);
4142
+ return {
4143
+ contents: { [SETTINGS$1]: settingsOut, [ENV]: envOut },
4144
+ warnings: warningsOf$1(settings, current),
4145
+ changedKeys,
4146
+ secrets: apiKey.mode === "literal" ? [apiKey.value] : []
4147
+ };
4148
+ },
4149
+ secretsIn(role, content) {
4150
+ try {
4151
+ return role === ENV ? collectSecretValues(parseDotenv(content)) : collectSecretValues(parseJsonObject$1(content, "settings.json"));
4152
+ } catch {
4153
+ return /* @__PURE__ */ new Set();
4154
+ }
4155
+ }
4156
+ };
4157
+
4158
+ const MODELS = "models";
4159
+ const SETTINGS = "settings";
4160
+ const PI_APIS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai", "mistral-conversations"];
4161
+ const ENV_REF = /^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/;
4162
+ function piAgentDir(ctx) {
4163
+ return ctx.env.PI_CODING_AGENT_DIR?.trim() || path.join(ctx.home, ".pi", "agent");
4164
+ }
4165
+ const str$1 = (v) => typeof v === "string" && v.trim() ? v : null;
4166
+ function providersOf(models) {
4167
+ const p = models.providers;
4168
+ if (!p || typeof p !== "object" || Array.isArray(p)) return {};
4169
+ return Object.fromEntries(Object.entries(p).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
4170
+ }
4171
+ function modelIds(provider) {
4172
+ const list = provider?.models;
4173
+ return Array.isArray(list) ? list.flatMap((m) => m && typeof m === "object" && typeof m.id === "string" ? [m.id] : []) : [];
4174
+ }
4175
+ function secretView(provider, ctx) {
4176
+ const key = str$1(provider?.apiKey);
4177
+ if (!key) return { mode: "none" };
4178
+ const ref = ENV_REF.exec(key.trim());
4179
+ if (ref) return { mode: "env", envName: ref[1], envPresent: !!ctx.env[ref[1]] };
4180
+ if (key.trim().startsWith("!")) return { mode: "command" };
4181
+ return { mode: "literal", masked: maskSecret(key) };
4182
+ }
4183
+ function currentOf(models, settings, providerId, ctx) {
4184
+ const provider = providerId ? providersOf(models)[providerId] : void 0;
4185
+ const activeProvider = str$1(settings.defaultProvider);
4186
+ return {
4187
+ providerId,
4188
+ baseUrl: str$1(provider?.baseUrl),
4189
+ api: str$1(provider?.api),
4190
+ apiKey: secretView(provider, ctx),
4191
+ models: modelIds(provider),
4192
+ activeProvider,
4193
+ defaultModel: str$1(settings.defaultModel),
4194
+ active: !!providerId && activeProvider === providerId
4195
+ };
4196
+ }
4197
+ function pickerModelsOf(models) {
4198
+ return uniq(Object.entries(providersOf(models)).flatMap(([id, p]) => modelIds(p).map((m) => `${id}/${m}`)));
4199
+ }
4200
+ function warningsOf(settings, current) {
4201
+ const out = [...baseUrlWarnings(current.baseUrl, current.api === "anthropic-messages" ? "anthropic" : "openai")].filter((w) => w.code !== "base-url-v1");
4202
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
4203
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment; pi hides models whose key cannot be resolved.` });
4204
+ }
4205
+ if (current.providerId && current.apiKey?.mode === "none") {
4206
+ out.push({ code: "no-key", message: "pi hides models whose provider has no resolvable API key." });
4207
+ }
4208
+ if (Array.isArray(settings.enabledModels) && current.providerId) {
4209
+ const enabled = settings.enabledModels;
4210
+ const hidden = (current.models ?? []).filter((m) => !enabled.includes(`${current.providerId}/${m}`) && !enabled.includes(m));
4211
+ if (hidden.length) out.push({ code: "enabled-models-filter", message: `settings.json enabledModels does not include ${hidden.join(", ")}.` });
4212
+ }
4213
+ return out;
4214
+ }
4215
+ const piAdapter = {
4216
+ id: "pi",
4217
+ binary: "pi",
4218
+ files: (ctx) => [{ role: MODELS, path: path.join(piAgentDir(ctx), "models.json") }, { role: SETTINGS, path: path.join(piAgentDir(ctx), "settings.json") }],
4219
+ view(files, ctx, opts) {
4220
+ const models = parseJsonObject$1(files[MODELS].content, "models.json");
4221
+ const settings = parseJsonObject$1(files[SETTINGS].content, "settings.json");
4222
+ const providers = providersOf(models);
4223
+ const active = str$1(settings.defaultProvider);
4224
+ const selected = opts.providerId ?? (active && providers[active] ? active : Object.keys(providers)[0] ?? null);
4225
+ const current = currentOf(models, settings, selected, ctx);
4226
+ return { current, providers: Object.keys(providers), pickerModels: pickerModelsOf(models), warnings: warningsOf(settings, current) };
4227
+ },
4228
+ plan(files, raw, ctx) {
4229
+ const p = raw;
4230
+ const providerId = normalizeProviderId(p.providerId);
4231
+ const baseUrl = normalizeBaseUrl(p.baseUrl);
4232
+ if (p.api !== void 0 && !PI_APIS.includes(p.api)) fail("invalid-input", `api must be one of ${PI_APIS.join(", ")}`);
4233
+ const apiKey = normalizeSecret(p.apiKey);
4234
+ if (apiKey.mode === "literal" && /^[$!]/.test(apiKey.value)) fail("invalid-input", "pi treats a key starting with $ or ! as an env reference / command; use the environment-variable mode");
4235
+ const ids = normalizeModelList(p.models);
4236
+ const defaultModel = normalizeModelId(p.defaultModel, "defaultModel");
4237
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") fail("invalid-input", "activate must be a boolean");
4238
+ const modelsText = files[MODELS].content;
4239
+ const settingsText = files[SETTINGS].content;
4240
+ const modelsBefore = parseJsonObject$1(modelsText, "models.json");
4241
+ const settingsBefore = parseJsonObject$1(settingsText, "settings.json");
4242
+ const models = structuredClone(modelsBefore);
4243
+ const settings = structuredClone(settingsBefore);
4244
+ const providers = childObject(models, "providers", "models.json");
4245
+ const isNew = providers[providerId] === void 0;
4246
+ if (isNew && !baseUrl) fail("invalid-input", "A new provider needs a base URL");
4247
+ const provider = childObject(providers, providerId, "models.json.providers");
4248
+ if (baseUrl !== void 0) {
4249
+ if (baseUrl === null) fail("invalid-input", "A provider needs a base URL");
4250
+ provider.baseUrl = baseUrl;
4251
+ }
4252
+ if (p.api !== void 0) provider.api = p.api;
4253
+ else if (isNew) provider.api = "openai-completions";
4254
+ const secrets = [];
4255
+ if (apiKey.mode === "literal") {
4256
+ provider.apiKey = apiKey.value;
4257
+ secrets.push(apiKey.value);
4258
+ }
4259
+ if (apiKey.mode === "env") provider.apiKey = `\${${apiKey.name}}`;
4260
+ if (apiKey.mode === "clear") delete provider.apiKey;
4261
+ if (ids !== void 0) {
4262
+ const existing = Array.isArray(provider.models) ? provider.models : [];
4263
+ const next = ids.map((id) => existing.find((m) => m && typeof m === "object" && m.id === id) ?? { id });
4264
+ if (next.length) provider.models = next;
4265
+ else delete provider.models;
4266
+ }
4267
+ const finalIds = modelIds(provider);
4268
+ if (p.activate === true) {
4269
+ settings.defaultProvider = providerId;
4270
+ const chosen = defaultModel ?? (finalIds.includes(str$1(settings.defaultModel) ?? "") ? str$1(settings.defaultModel) : finalIds[0]);
4271
+ setOrDelete(settings, "defaultModel", chosen);
4272
+ } else if (p.activate === false && str$1(settings.defaultProvider) === providerId) {
4273
+ delete settings.defaultProvider;
4274
+ delete settings.defaultModel;
4275
+ } else if (defaultModel !== void 0 && str$1(settings.defaultProvider) === providerId) {
4276
+ setOrDelete(settings, "defaultModel", defaultModel);
4277
+ }
4278
+ if (defaultModel && !finalIds.includes(defaultModel)) fail("invalid-input", "defaultModel must be one of the provider models");
4279
+ const modelKeys = changedPaths(modelsBefore, models, [["providers", providerId, "baseUrl"], ["providers", providerId, "api"], ["providers", providerId, "apiKey"], ["providers", providerId, "models"]]);
4280
+ const settingsKeys = changedPaths(settingsBefore, settings, [["defaultProvider"], ["defaultModel"]]);
4281
+ const current = currentOf(models, settings, providerId, ctx);
4282
+ return {
4283
+ contents: {
4284
+ [MODELS]: modelKeys.length ? stringifyLike(modelsText, models) : void 0,
4285
+ [SETTINGS]: settingsKeys.length ? stringifyLike(settingsText, settings) : void 0
4286
+ },
4287
+ warnings: warningsOf(settings, current),
4288
+ changedKeys: [...modelKeys.map((k) => `models.json.${k}`), ...settingsKeys.map((k) => `settings.json.${k}`)],
4289
+ secrets
4290
+ };
4291
+ },
4292
+ secretsIn(_role, content) {
4293
+ try {
4294
+ return collectSecretValues(parseJsonObject$1(content, "pi config"));
4295
+ } catch {
4296
+ return /* @__PURE__ */ new Set();
4297
+ }
4298
+ }
4299
+ };
4300
+
4301
+ const MODEL_CONFIG_CAPABILITY_VERSION = 1;
4302
+ const HARNESS_IDS = ["claude", "codex", "gemini", "pi"];
4303
+
4304
+ const ADAPTERS = { claude: claudeAdapter, codex: codexAdapter, gemini: geminiAdapter, pi: piAdapter };
4305
+ function harnessOf(value) {
4306
+ if (typeof value !== "string" || !HARNESS_IDS.includes(value)) {
4307
+ throw new mirrorProtocol.ModelConfigError("invalid-harness", `harness must be one of ${HARNESS_IDS.join(", ")}`);
4308
+ }
4309
+ return value;
4310
+ }
4311
+ class ModelConfigService {
4312
+ constructor(opts) {
4313
+ this.opts = opts;
4314
+ this.backups = new mirrorProtocol.BackupStore(path.join(opts.happyHomeDir, "model-config-backups"));
4315
+ this.auditPath = path.join(opts.happyHomeDir, "model-config-audit.jsonl");
4316
+ }
4317
+ backups;
4318
+ auditPath;
4319
+ chain = Promise.resolve();
4320
+ get ctx() {
4321
+ return { home: this.opts.home, env: this.opts.env };
4322
+ }
4323
+ serialize(fn) {
4324
+ const next = this.chain.then(fn, fn);
4325
+ this.chain = next.catch(() => {
4326
+ });
4327
+ return next;
4328
+ }
4329
+ async loadFiles(adapter) {
4330
+ const files = {};
4331
+ for (const { role, path } of adapter.files(this.ctx)) files[role] = await mirrorProtocol.readConfigFile(path);
4332
+ const baseHash = mirrorProtocol.sha256(Object.entries(files).map(([role, f]) => `${role}\0${f.exists ? f.hash : "-"}`).join("\n"));
4333
+ return { files, baseHash };
4334
+ }
4335
+ async readOne(harness, providerId) {
4336
+ const adapter = ADAPTERS[harness];
4337
+ const installed = harness === "claude" || (this.opts.isInstalled?.(adapter.binary) ?? true);
4338
+ const backups = await this.backups.list(harness);
4339
+ let loaded;
4340
+ try {
4341
+ loaded = await this.loadFiles(adapter);
4342
+ } catch (error) {
4343
+ const e = toError(error);
4344
+ return {
4345
+ harness,
4346
+ installed,
4347
+ baseHash: "",
4348
+ current: {},
4349
+ pickerModels: [],
4350
+ backups,
4351
+ warnings: [],
4352
+ files: adapter.files(this.ctx).map((f) => ({ role: f.role, path: f.path, exists: false, error: e }))
4353
+ };
4354
+ }
4355
+ const files = Object.entries(loaded.files).map(([role, f]) => ({ role, path: f.path, exists: f.exists }));
4356
+ try {
4357
+ const view = adapter.view(loaded.files, this.ctx, { providerId });
4358
+ return { harness, installed, files, baseHash: loaded.baseHash, backups, ...view };
4359
+ } catch (error) {
4360
+ const e = toError(error);
4361
+ return { harness, installed, baseHash: loaded.baseHash, current: {}, pickerModels: [], backups, warnings: [], files: files.map((f) => ({ ...f, error: e })) };
4362
+ }
4363
+ }
4364
+ async read(params = {}) {
4365
+ const list = params.harness === void 0 ? [...HARNESS_IDS] : [harnessOf(params.harness)];
4366
+ const providerId = typeof params.providerId === "string" && params.providerId ? params.providerId : void 0;
4367
+ const harnesses = await Promise.all(list.map((h) => this.readOne(h, providerId)));
4368
+ return { version: MODEL_CONFIG_CAPABILITY_VERSION, harnesses };
4369
+ }
4370
+ diffs(adapter, files, next, extraSecrets) {
4371
+ const out = [];
4372
+ for (const [role, file] of Object.entries(files)) {
4373
+ const target = next[role];
4374
+ if (target === void 0) continue;
4375
+ const newText = target ?? "";
4376
+ if (target !== null && file.exists && newText === file.content) continue;
4377
+ if (target === null && !file.exists) continue;
4378
+ const secrets = [...adapter.secretsIn(role, file.content), ...target ? adapter.secretsIn(role, target) : [], ...extraSecrets];
4379
+ const raw = unifiedDiff(file.content, newText, file.path);
4380
+ out.push({ path: file.path, diff: redactText(raw, secrets), created: !file.exists && target !== null, deleted: target === null && file.exists });
4381
+ }
4382
+ return out;
4383
+ }
4384
+ async write(harness, action, files, next, keys, apiKeyMode) {
4385
+ const touched = Object.entries(next).filter(([, v]) => v !== void 0);
4386
+ const snapshot = touched.map(([role]) => ({ path: files[role].path, content: files[role].exists ? files[role].content : null, mode: files[role].mode }));
4387
+ const backup = await this.backups.create(harness, action === "apply" ? "before-apply" : "before-restore", snapshot, this.opts.now?.() ?? Date.now());
4388
+ for (const [role, target] of touched) {
4389
+ const file = files[role];
4390
+ if (target.content === null) await node_fs.promises.rm(file.path, { force: true });
4391
+ else await mirrorProtocol.atomicWriteFile(file.path, target.content, file.mode ?? target.mode);
4392
+ }
4393
+ await this.audit({ at: this.opts.now?.() ?? Date.now(), action, harness, files: touched.map(([role]) => files[role].path), keys, apiKeyMode, backupId: backup.id });
4394
+ this.opts.onChanged?.(harness);
4395
+ return backup;
4396
+ }
4397
+ async audit(record) {
4398
+ try {
4399
+ await node_fs.promises.mkdir(this.opts.happyHomeDir, { recursive: true });
4400
+ await node_fs.promises.appendFile(this.auditPath, `${JSON.stringify(record)}
4401
+ `, { encoding: "utf8", mode: 384 });
4402
+ } catch {
4403
+ }
4404
+ }
4405
+ apply(params) {
4406
+ const run = async () => {
4407
+ const patch = params.patch;
4408
+ if (!patch || typeof patch !== "object") throw new mirrorProtocol.ModelConfigError("invalid-input", "patch is required");
4409
+ const harness = harnessOf(patch.harness);
4410
+ const adapter = ADAPTERS[harness];
4411
+ const { files, baseHash } = await this.loadFiles(adapter);
4412
+ const dryRun = params.dryRun !== false;
4413
+ if (!dryRun && params.baseHash !== baseHash) {
4414
+ throw new mirrorProtocol.ModelConfigError("conflict", "The config files changed since the preview; review the new diff and apply again");
4415
+ }
4416
+ const plan = adapter.plan(files, patch, this.ctx);
4417
+ const diffs = this.diffs(adapter, files, plan.contents, plan.secrets);
4418
+ const changed = diffs.length > 0;
4419
+ if (dryRun || !changed) {
4420
+ return { harness, dryRun, changed, baseHash, files: diffs, warnings: plan.warnings };
4421
+ }
4422
+ const next = Object.fromEntries(Object.entries(plan.contents).map(([role, content]) => [role, content === void 0 ? void 0 : { content, mode: null }]));
4423
+ const apiKeyMode = patch.apiKey?.mode;
4424
+ const backup = await this.write(harness, "apply", files, next, plan.changedKeys, typeof apiKeyMode === "string" ? apiKeyMode : void 0);
4425
+ const config = await this.readOne(harness, patch.providerId);
4426
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: plan.warnings, backup, config };
4427
+ };
4428
+ return params.dryRun === false ? this.serialize(run) : run();
4429
+ }
4430
+ restore(params) {
4431
+ const run = async () => {
4432
+ const harness = harnessOf(params.harness);
4433
+ const adapter = ADAPTERS[harness];
4434
+ if (typeof params.backupId !== "string") throw new mirrorProtocol.ModelConfigError("invalid-input", "backupId is required");
4435
+ const saved = await this.backups.read(harness, params.backupId);
4436
+ const { files, baseHash } = await this.loadFiles(adapter);
4437
+ const dryRun = params.dryRun !== false;
4438
+ if (!dryRun && params.baseHash !== baseHash) {
4439
+ throw new mirrorProtocol.ModelConfigError("conflict", "The config files changed since the preview; review the new diff and restore again");
4440
+ }
4441
+ const allowed = new Map(Object.entries(files).map(([role, f]) => [f.path, role]));
4442
+ const target = {};
4443
+ for (const file of saved) {
4444
+ const role = allowed.get(file.path);
4445
+ if (!role) throw new mirrorProtocol.ModelConfigError("backup-mismatch", "Backup does not belong to the current config location");
4446
+ target[role] = { content: file.content, mode: file.mode };
4447
+ }
4448
+ const diffs = this.diffs(adapter, files, Object.fromEntries(Object.entries(target).map(([r, v]) => [r, v?.content])), []);
4449
+ const changed = diffs.length > 0;
4450
+ if (dryRun || !changed) return { harness, dryRun, changed, baseHash, files: diffs, warnings: [] };
4451
+ const keys = ["*restore*"];
4452
+ const backup = await this.write(harness, "restore", files, target, keys);
4453
+ const config = await this.readOne(harness);
4454
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: [], backup, config };
4455
+ };
4456
+ return params.dryRun === false ? this.serialize(run) : run();
4457
+ }
4458
+ }
4459
+ function toError(error) {
4460
+ if (error instanceof mirrorProtocol.ModelConfigError) return { code: error.code, message: error.message };
4461
+ return { code: "read-failed", message: error instanceof Error ? error.message : String(error) };
4462
+ }
4463
+
4464
+ function startWebPanelsSync(deps) {
4465
+ let lastMtime;
4466
+ let lastProblems = "";
4467
+ let stopped = false;
4468
+ let inflight = null;
4469
+ const run = async () => {
4470
+ try {
4471
+ const mtime = await deps.statMtime();
4472
+ if (mtime === lastMtime) return;
4473
+ lastMtime = mtime;
4474
+ const { panels, problems } = webPanels.normalizeWebPanels(mtime === null ? void 0 : await deps.readRaw());
4475
+ const key = JSON.stringify(problems);
4476
+ if (problems.length > 0 && key !== lastProblems) deps.logProblems(problems);
4477
+ lastProblems = key;
4478
+ await deps.publish(panels);
4479
+ } catch {
4480
+ lastMtime = void 0;
4481
+ }
4482
+ };
4483
+ const tick = () => {
4484
+ if (stopped) return Promise.resolve();
4485
+ inflight ??= run().finally(() => {
4486
+ inflight = null;
4487
+ });
4488
+ return inflight;
4489
+ };
4490
+ void tick();
4491
+ const timer = setInterval(() => {
4492
+ void tick();
4493
+ }, deps.intervalMs ?? 2e3);
4494
+ timer.unref?.();
4495
+ return { stop: () => {
4496
+ stopped = true;
4497
+ clearInterval(timer);
4498
+ }, tick };
4499
+ }
4500
+
2055
4501
  function isAcceptableRelayUrl(url) {
2056
4502
  try {
2057
4503
  const parsed = new URL(url);
@@ -2507,6 +4953,44 @@ function createUpdateController(deps) {
2507
4953
  return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running };
2508
4954
  }
2509
4955
 
4956
+ function buildPresenceBatch(live, previous) {
4957
+ const current = new Set(live.map((s) => s.sessionId));
4958
+ const sessions = live.slice(0, 200).map((s) => ({
4959
+ sessionId: s.sessionId,
4960
+ state: s.running ? "running" : "idle",
4961
+ ...s.flavor ? { agent: s.flavor } : {},
4962
+ ...s.branch ? { branch: s.branch.slice(0, 200) } : {}
4963
+ }));
4964
+ const gone = [...previous].filter((id) => !current.has(id)).slice(0, 200);
4965
+ return { sessions, gone, current };
4966
+ }
4967
+ function createProjectPresenceReporter(deps) {
4968
+ let previous = /* @__PURE__ */ new Set();
4969
+ let running = false;
4970
+ async function tick() {
4971
+ if (running || deps.client.isDisabled()) return;
4972
+ running = true;
4973
+ try {
4974
+ const batch = buildPresenceBatch(deps.live(), previous);
4975
+ if (batch.sessions.length === 0 && batch.gone.length === 0) {
4976
+ previous = batch.current;
4977
+ return;
4978
+ }
4979
+ await deps.client.presence(deps.machineId, batch.sessions, batch.gone);
4980
+ previous = batch.current;
4981
+ } catch (error) {
4982
+ if (!(error instanceof client.ProjectsUnsupportedError)) deps.log(`project presence tick failed: ${String(error)}`);
4983
+ } finally {
4984
+ running = false;
4985
+ }
4986
+ }
4987
+ const timer = setInterval(() => {
4988
+ void tick();
4989
+ }, deps.intervalMs ?? 6e4);
4990
+ timer.unref?.();
4991
+ return { tick, stop: () => clearInterval(timer) };
4992
+ }
4993
+
2510
4994
  const AUTOMATION_BINDINGS_TTL_MS = 10 * 60 * 1e3;
2511
4995
  const HIBERNATION_IN_FLIGHT_MS = 6e4;
2512
4996
  const HIBERNATION_EXIT_WAIT_MS = 15e3;
@@ -2697,7 +5181,7 @@ function parseJsonObject(text) {
2697
5181
  return null;
2698
5182
  }
2699
5183
  }
2700
- function resolveSdkClaudeBinary(platform = process.platform, arch = process.arch, resolver = (s) => module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('run-CKe_WeLW.cjs', document.baseURI).href))).resolve(s)) {
5184
+ function resolveSdkClaudeBinary(platform = process.platform, arch = process.arch, resolver = (s) => module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('run-CAOCYYfT.cjs', document.baseURI).href))).resolve(s)) {
2701
5185
  const platformArch = `${platform}-${arch}`;
2702
5186
  const candidates = [
2703
5187
  `@anthropic-ai/claude-agent-sdk-${platformArch}/claude`,
@@ -3686,6 +6170,57 @@ function withDaemonHeartbeat(state, lastHeartbeat) {
3686
6170
  return { ...state, lastHeartbeat };
3687
6171
  }
3688
6172
 
6173
+ const TAIL_BYTES = 64 * 1024;
6174
+ const MAX_REASON = 300;
6175
+ function extractStartupExitReason(logText) {
6176
+ const lines = logText.split("\n");
6177
+ for (let i = lines.length - 1; i >= 0; i--) {
6178
+ const exit = /\[EXIT\] Exiting with code -?\d+: (.+)$/.exec(lines[i]);
6179
+ if (exit) return clamp(exit[1]);
6180
+ }
6181
+ for (let i = lines.length - 1; i >= 0; i--) {
6182
+ if (!/\[ERROR\]|\[WARN\]/.test(lines[i])) continue;
6183
+ const detail = lines.slice(i, i + 8).join("\n");
6184
+ const message = /message: '([^'\n]+)'/.exec(detail)?.[1];
6185
+ const code = /code: '([A-Z0-9_]+)'/.exec(detail)?.[1];
6186
+ const head = lines[i].replace(/^\[[\d:.]+\]\s*/, "").replace(/\s*\{\s*$/, "").trim();
6187
+ return clamp([head, message, code].filter(Boolean).join(" "));
6188
+ }
6189
+ return void 0;
6190
+ }
6191
+ function describeStartupExit(exit, timeoutMs) {
6192
+ if (exit.timedOut) {
6193
+ const tail = exit.exited ? "and was stopped" : "and could not be confirmed stopped";
6194
+ return `Agent process did not report its session within ${Math.round(timeoutMs / 1e3)}s ${tail}${exit.reason ? `: ${exit.reason}` : ""}`;
6195
+ }
6196
+ const how = exit.signal ? `signal ${exit.signal}` : `code ${exit.code ?? "unknown"}`;
6197
+ return `Agent process exited during startup (${how}): ${exit.reason ?? "no reason found in its log"}`;
6198
+ }
6199
+ function readStartupExitReason(logsDir, pid) {
6200
+ try {
6201
+ const suffix = `-pid-${pid}.log`;
6202
+ const file = node_fs.readdirSync(logsDir).filter((name) => name.endsWith(suffix)).sort().pop();
6203
+ if (!file) return void 0;
6204
+ const path$1 = path.join(logsDir, file);
6205
+ const size = node_fs.statSync(path$1).size;
6206
+ const length = Math.min(size, TAIL_BYTES);
6207
+ const buffer = Buffer.alloc(length);
6208
+ const fd = node_fs.openSync(path$1, "r");
6209
+ try {
6210
+ node_fs.readSync(fd, buffer, 0, length, size - length);
6211
+ } finally {
6212
+ node_fs.closeSync(fd);
6213
+ }
6214
+ return extractStartupExitReason(buffer.toString("utf8"));
6215
+ } catch {
6216
+ return void 0;
6217
+ }
6218
+ }
6219
+ function clamp(value) {
6220
+ const line = value.replace(/\s+/g, " ").trim();
6221
+ return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}\u2026` : line;
6222
+ }
6223
+
3689
6224
  function recoverableSessionPid(metadata, liveHappyPids) {
3690
6225
  const pid = metadata?.hostPid;
3691
6226
  return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && liveHappyPids.has(pid) ? pid : null;
@@ -3779,9 +6314,28 @@ function writeReceipt$1(home, receipt) {
3779
6314
 
3780
6315
  const exec = node_util.promisify(node_child_process.execFile);
3781
6316
  const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
6317
+ const gitRaw = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 64 * 1024 * 1024 })).stdout;
6318
+ function expandHome$1(path$1) {
6319
+ if (path$1 === "~") return os.homedir();
6320
+ if (path$1.startsWith("~/") || process.platform === "win32" && path$1.startsWith("~\\")) return path.join(os.homedir(), path$1.slice(2));
6321
+ return path$1;
6322
+ }
6323
+ async function resolveTeamRepository(home, repository, sourceOf) {
6324
+ const worktrees = path.resolve(home, "teams", "worktrees");
6325
+ let candidate = expandHome$1(repository);
6326
+ for (let hop = 0; hop < 8; hop++) {
6327
+ if (!path.isAbsolute(candidate)) break;
6328
+ const teamWorktree = path.resolve(path.dirname(candidate)) === worktrees;
6329
+ const top = await git(candidate, ["rev-parse", "--show-toplevel"]).catch(() => null);
6330
+ if (top !== null && (!teamWorktree || path.resolve(top) === path.resolve(candidate))) return candidate;
6331
+ const source = teamWorktree ? sourceOf(path.basename(candidate)) : void 0;
6332
+ if (!source) break;
6333
+ candidate = expandHome$1(source);
6334
+ }
6335
+ throw new Error(`Team repository is unavailable: ${repository} is missing or not a Git checkout. Restore the folder or delegate with an existing repository, then choose Retry launch.`);
6336
+ }
3782
6337
  async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3783
- if (repository === "~") repository = os.homedir();
3784
- else if (repository.startsWith("~/") || process.platform === "win32" && repository.startsWith("~\\")) repository = path.join(os.homedir(), repository.slice(2));
6338
+ repository = expandHome$1(repository);
3785
6339
  if (!path.isAbsolute(repository) || !/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new Error("A team task requires an absolute repository path and valid operation id");
3786
6340
  await git(repository, ["rev-parse", "--show-toplevel"]);
3787
6341
  const root = path.join(home, "teams", "worktrees");
@@ -3800,28 +6354,69 @@ async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3800
6354
  }
3801
6355
  return { directory, repository, branch };
3802
6356
  }
6357
+ async function unpreservedCommits(directory, repository, rev) {
6358
+ const sourceHead = await git(repository, ["rev-parse", "HEAD"]).catch(() => "");
6359
+ const pending = (await git(directory, ["rev-list", rev, "--not", "--remotes", ...sourceHead ? [sourceHead] : []])).split("\n").filter(Boolean);
6360
+ if (pending.length === 0) return 0;
6361
+ return await squashMerged(directory, rev) ? 0 : pending.length;
6362
+ }
6363
+ async function squashMerged(directory, rev) {
6364
+ const target = await git(directory, ["rev-parse", "--abbrev-ref", "refs/remotes/origin/HEAD"]).catch(() => "") || await git(directory, ["rev-parse", "--verify", "--quiet", "refs/remotes/origin/main"]).then(() => "origin/main", () => "");
6365
+ if (!target) return false;
6366
+ const base = await git(directory, ["merge-base", rev, target]).catch(() => "");
6367
+ if (!base) return false;
6368
+ const own = patchIds(await gitRaw(directory, ["diff", base, rev]).then((diff) => diff ? patchIdOf(directory, diff) : "", () => ""));
6369
+ if (own.length !== 1) return false;
6370
+ const merged = patchIds(await gitRaw(directory, ["log", "-p", "--no-merges", "--max-count=500", `${base}..${target}`]).then((log) => log ? patchIdOf(directory, log) : "", () => ""));
6371
+ return merged.includes(own[0]);
6372
+ }
6373
+ async function patchIdOf(directory, patch) {
6374
+ return await new Promise((resolvePatch, reject) => {
6375
+ const child = node_child_process.execFile("git", ["-C", directory, "patch-id", "--stable"], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 }, (error, stdout) => error ? reject(error) : resolvePatch(stdout));
6376
+ child.stdin?.end(patch);
6377
+ });
6378
+ }
6379
+ const patchIds = (output) => output.split("\n").filter(Boolean).map((line) => line.split(" ")[0]);
6380
+ async function registeredWorktree(repository, directory) {
6381
+ const list = await git(repository, ["worktree", "list", "--porcelain"]).catch(() => "");
6382
+ return list.split("\n").some((line) => line.startsWith("worktree ") && path.resolve(line.slice("worktree ".length)) === path.resolve(directory));
6383
+ }
6384
+ const describeHead = async (directory) => await git(directory, ["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "") || "a detached HEAD";
3803
6385
  async function removeTeamWorktree(resource) {
3804
6386
  const { directory, repository, branch } = resource;
3805
6387
  if (!directory || !repository || !branch) return;
3806
- if (node_fs.existsSync(directory)) {
3807
- if (await git(directory, ["symbolic-ref", "--short", "HEAD"]) !== branch) throw new Error("Worktree branch changed; preserve for manual reconciliation");
6388
+ let present = node_fs.existsSync(directory);
6389
+ if (present) {
6390
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => "");
6391
+ if (!top || path.resolve(top) !== path.resolve(directory)) {
6392
+ if (await registeredWorktree(repository, directory)) throw new Error(`${directory} is registered as a worktree but its git link is broken; inspect it, then mark this cleanup as handled`);
6393
+ if (node_fs.readdirSync(directory).length === 0) node_fs.rmdirSync(directory);
6394
+ present = false;
6395
+ }
6396
+ }
6397
+ if (present) {
3808
6398
  const actualCommon = await git(directory, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3809
6399
  const expectedCommon = await git(repository, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3810
6400
  if (path.resolve(actualCommon) !== path.resolve(expectedCommon)) throw new Error("Worktree repository changed; preserve for manual reconciliation");
3811
- if (await git(directory, ["status", "--porcelain"])) throw new Error(`Uncommitted work retained at ${directory}`);
3812
- await git(repository, ["merge-base", "--is-ancestor", branch, "HEAD"]).catch(() => {
3813
- throw new Error(`Unmerged work retained on ${branch} at ${directory}`);
3814
- });
3815
- await git(repository, ["worktree", "remove", directory]);
6401
+ const dirty = (await git(directory, ["status", "--porcelain"])).split("\n").filter(Boolean).length;
6402
+ if (dirty) throw new Error(`Uncommitted work retained at ${directory} (${dirty} changed file${dirty === 1 ? "" : "s"}): commit and push it, or discard it, then retry cleanup`);
6403
+ const head = await describeHead(directory);
6404
+ const unsafe = await unpreservedCommits(directory, repository, "HEAD");
6405
+ if (unsafe) throw new Error(`Unmerged work retained on ${head} at ${directory}: ${unsafe} commit${unsafe === 1 ? " is" : "s are"} not pushed or merged; push or merge, then retry cleanup`);
3816
6406
  }
3817
- try {
3818
- await git(repository, ["show-ref", "--verify", `refs/heads/${branch}`]);
3819
- } catch {
3820
- return;
6407
+ const ownBranch = await git(repository, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).then(() => true, () => false);
6408
+ if (ownBranch) {
6409
+ const unsafe = await unpreservedCommits(repository, repository, `refs/heads/${branch}`);
6410
+ if (unsafe) throw new Error(`Unmerged work retained on ${branch}: ${unsafe} commit${unsafe === 1 ? " is" : "s are"} not pushed or merged; push or merge, then retry cleanup`);
3821
6411
  }
3822
- await git(repository, ["branch", "-d", branch]);
6412
+ if (present) await git(repository, ["worktree", "remove", directory]);
6413
+ else await git(repository, ["worktree", "prune"]).catch(() => void 0);
6414
+ if (ownBranch) await git(repository, ["branch", "-D", branch]);
3823
6415
  }
3824
6416
 
6417
+ function persistedSpawnMatches(operationId) {
6418
+ return Object.entries(persistence.readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === operationId);
6419
+ }
3825
6420
  function createTeamWorker(deps) {
3826
6421
  const home = deps.home ?? configuration.configuration.happyHomeDir;
3827
6422
  const server = deps.serverUrl ?? configuration.configuration.serverUrl;
@@ -3855,6 +6450,12 @@ function createTeamWorker(deps) {
3855
6450
  if (receipt.phase === "completed") return;
3856
6451
  try {
3857
6452
  if (op.type === "spawn") {
6453
+ if (machineMetadata.ownerRetryPending(op, receipt) && (receipt.phase === "prepared" || receipt.phase === "spawning" && persistedSpawnMatches(op.id).length === 0)) {
6454
+ receipt = machineMetadata.consumeOwnerRetry(op, receipt);
6455
+ writeReceipt$1(home, receipt);
6456
+ deps.log(`Teams operation ${op.id} relaunch requested by owner`);
6457
+ }
6458
+ if (receipt.phase === "prepared" && machineMetadata.spawnGate(receipt, Date.now()) !== "run") return;
3858
6459
  if (receipt.phase === "prepared") {
3859
6460
  if (!credential) credential = (await action(op.teamId, `claim-${op.id}`, { type: "claim-operation", operationId: op.id, machineId: deps.machineId, ...op.teamLaunchVersion === 1 ? { teamLaunchVersion: 1 } : {} })).credential;
3860
6461
  if (!credential) throw new Error("No scoped credential for worker");
@@ -3867,7 +6468,26 @@ function createTeamWorker(deps) {
3867
6468
  return;
3868
6469
  }
3869
6470
  if (!op.directory) throw new Error("No repository selected for worker");
3870
- const resource = await prepareTeamWorktree(home, op.directory, op.id);
6471
+ let resource;
6472
+ try {
6473
+ const repository = await resolveTeamRepository(home, op.directory, (id) => {
6474
+ try {
6475
+ return readReceipt(home, id)?.repository;
6476
+ } catch {
6477
+ return void 0;
6478
+ }
6479
+ });
6480
+ resource = await prepareTeamWorktree(home, repository, op.id);
6481
+ } catch (error) {
6482
+ const now = Date.now();
6483
+ receipt = machineMetadata.afterStartupFailure(receipt, now);
6484
+ writeReceipt$1(home, receipt);
6485
+ const detail = error instanceof Error ? error.message : "Team worktree could not be prepared";
6486
+ await action(op.teamId, `preflight-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: machineMetadata.startupFailureMessage(detail, receipt, now).slice(0, 1e3) }).catch(() => {
6487
+ });
6488
+ deps.log(`Teams operation ${op.id} preflight failed (${receipt.spawnFailures}/${machineMetadata.TEAM_SPAWN_MAX_ATTEMPTS})`);
6489
+ return;
6490
+ }
3871
6491
  const scopes = path.join(home, "teams", "scopes");
3872
6492
  configuration.ensurePrivateDirectorySync(scopes);
3873
6493
  const scopeFile = path.join(scopes, `${op.id}.json`);
@@ -3875,12 +6495,21 @@ function createTeamWorker(deps) {
3875
6495
  receipt = { ...receipt, ...resource, scopeFile, phase: "spawning" };
3876
6496
  writeReceipt$1(home, receipt);
3877
6497
  const spawned = await deps.spawn({ directory: resource.directory, agent: op.assistant === "pi-acp" ? "pi" : op.assistant, permissionMode: op.permissionMode === "bypassPermissions" ? "bypassPermissions" : "default", spawnedBy: "teams", environmentVariables: { VH_TEAM_SCOPE_FILE: scopeFile, VH_TEAM_OPERATION_ID: op.id } });
6498
+ if (spawned.type === "error" && spawned.startupExit?.exited) {
6499
+ const now = Date.now();
6500
+ receipt = machineMetadata.afterStartupFailure(receipt, now);
6501
+ writeReceipt$1(home, receipt);
6502
+ await action(op.teamId, `startup-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: machineMetadata.startupFailureMessage(spawned.errorMessage, receipt, now).slice(0, 1e3) }).catch(() => {
6503
+ });
6504
+ deps.log(`Teams operation ${op.id} startup failed (${receipt.spawnFailures}/${machineMetadata.TEAM_SPAWN_MAX_ATTEMPTS}); ${receipt.retryAt !== void 0 ? "will relaunch" : "waiting for owner retry"}`);
6505
+ return;
6506
+ }
3878
6507
  if (spawned.type !== "success") throw new Error(spawned.type === "error" ? spawned.errorMessage : "Directory approval required");
3879
6508
  receipt = { ...receipt, sessionId: spawned.sessionId, phase: "spawned" };
3880
6509
  writeReceipt$1(home, receipt);
3881
6510
  }
3882
6511
  if (receipt.phase === "spawning") {
3883
- const matches = Object.entries(persistence.readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === op.id);
6512
+ const matches = persistedSpawnMatches(op.id);
3884
6513
  if (matches.length !== 1) throw new Error("Spawn outcome unknown; reconcile the worker before retrying");
3885
6514
  receipt = { ...receipt, sessionId: matches[0][0], phase: "spawned" };
3886
6515
  writeReceipt$1(home, receipt);
@@ -3902,6 +6531,12 @@ function createTeamWorker(deps) {
3902
6531
  }
3903
6532
  await complete(op, receipt);
3904
6533
  } else {
6534
+ if (machineMetadata.ownerRetryPending(op, receipt)) {
6535
+ const { retryAt: _retryAt, ...rest } = receipt;
6536
+ receipt = { ...rest, retryConsumed: op.retryRequestedAt };
6537
+ writeReceipt$1(home, receipt);
6538
+ deps.log(`Teams operation ${op.id} cleanup retry requested by owner`);
6539
+ } else if (receipt.retryAt !== void 0 && Date.now() < receipt.retryAt) return;
3905
6540
  const team = (await http.get(`/v1/teams/${encodeURIComponent(op.teamId)}`)).data.team;
3906
6541
  const latest = team.operations.find((candidate) => candidate.id === op.id);
3907
6542
  if (latest?.status === "completed") {
@@ -3928,7 +6563,14 @@ function createTeamWorker(deps) {
3928
6563
  } catch (error) {
3929
6564
  const unknown = op.type === "spawn" && receipt.phase === "spawning";
3930
6565
  const detail = error instanceof Error ? error.message : "Team operation failed";
3931
- await action(op.teamId, `failure-${op.id}-${receipt.phase}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: detail.slice(0, 1e3), unknown }).catch(() => {
6566
+ if (op.type === "stop") {
6567
+ receipt = { ...receipt, retryAt: Date.now() + machineMetadata.TEAM_CLEANUP_RETRY_MS };
6568
+ try {
6569
+ writeReceipt$1(home, receipt);
6570
+ } catch {
6571
+ }
6572
+ }
6573
+ await action(op.teamId, `failure-${op.id}-${receipt.phase}-${node_crypto.createHash("sha256").update(detail).digest("hex").slice(0, 12)}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: detail.slice(0, 1e3), unknown }).catch(() => {
3932
6574
  });
3933
6575
  deps.log(`Teams operation ${op.id} ${unknown ? "needs reconciliation" : "will retry"}`);
3934
6576
  }
@@ -4308,7 +6950,7 @@ function expandHome(path$1) {
4308
6950
  return path$1;
4309
6951
  }
4310
6952
  function isSettledByServer(error) {
4311
- if (!(error instanceof client.AutomationsRequestError)) return false;
6953
+ if (!(error instanceof client$1.AutomationsRequestError)) return false;
4312
6954
  if (error.status === 409 && (error.code === "run_finished" || error.code === "claim_mismatch")) return true;
4313
6955
  return error.status === 404 && error.code === "run_not_found";
4314
6956
  }
@@ -4317,7 +6959,7 @@ function scriptAlive(item) {
4317
6959
  }
4318
6960
  function createAutomationRunner(deps) {
4319
6961
  const home = deps.home ?? configuration.configuration.happyHomeDir;
4320
- const client$1 = deps.client ?? client.createAutomationsClient({ serverUrl: deps.serverUrl ?? configuration.configuration.serverUrl, token: deps.token, client: "daemon-auto" });
6962
+ const client = deps.client ?? client$1.createAutomationsClient({ serverUrl: deps.serverUrl ?? configuration.configuration.serverUrl, token: deps.token, client: "daemon-auto" });
4321
6963
  const runScript$1 = deps.runScript ?? runScript;
4322
6964
  const runPrecheck$1 = deps.runPrecheck ?? runPrecheck;
4323
6965
  const readTurn = deps.readTurn ?? defaultReadTurn;
@@ -4337,9 +6979,9 @@ function createAutomationRunner(deps) {
4337
6979
  }
4338
6980
  async function finish(item, report2) {
4339
6981
  try {
4340
- await client$1.report(item.runId, report2);
6982
+ await client.report(item.runId, report2);
4341
6983
  } catch (error) {
4342
- if (report2.status === "skipped" && error instanceof client.AutomationsRequestError && error.status === 400) {
6984
+ if (report2.status === "skipped" && error instanceof client$1.AutomationsRequestError && error.status === 400) {
4343
6985
  await finish(item, { ...report2, status: "failed" });
4344
6986
  return;
4345
6987
  }
@@ -4365,7 +7007,7 @@ function createAutomationRunner(deps) {
4365
7007
  async function reportRunning(item, sessionId, stickyKey) {
4366
7008
  const body = { claimId: item.claimId, status: "running", ...sessionId ? { sessionId } : {}, ...stickyKey ? { stickyKey } : {} };
4367
7009
  try {
4368
- await client$1.report(item.runId, body);
7010
+ await client.report(item.runId, body);
4369
7011
  } catch (error) {
4370
7012
  if (isSettledByServer(error)) {
4371
7013
  settleExternally(item);
@@ -4550,7 +7192,7 @@ ${action.prompt}`, { localId: `automation-${run.id}` });
4550
7192
  await reportRunning(track(claimed, "send", bound.sessionId), bound.sessionId, stickyKey);
4551
7193
  return;
4552
7194
  }
4553
- if (bound) await client$1.deleteSticky(automation.id, stickyKey).catch(() => deps.log(`Automation ${automation.name}: stale sticky ${stickyKey} not cleared`));
7195
+ if (bound) await client.deleteSticky(automation.id, stickyKey).catch(() => deps.log(`Automation ${automation.name}: stale sticky ${stickyKey} not cleared`));
4554
7196
  }
4555
7197
  let directory = expandHome(action.directory);
4556
7198
  if (!path.isAbsolute(directory)) {
@@ -4573,6 +7215,7 @@ ${action.prompt}`, { localId: `automation-${run.id}` });
4573
7215
  }
4574
7216
  persist({ runId: run.id, automationId: automation.id, kind: "spawn", phase: "running", claimId: run.claimId, sessionId: spawned.sessionId, stickyKey, ...action.worktree ? { directory } : {} });
4575
7217
  const item = track(claimed, "spawn", spawned.sessionId);
7218
+ if (automation.projectId && deps.joinProject) await deps.joinProject(spawned.sessionId, automation.projectId).catch(() => void 0);
4576
7219
  try {
4577
7220
  const capabilities = persistence.readPersistedSessions()[spawned.sessionId]?.metadata?.capabilities ?? null;
4578
7221
  const meta = spawnAgents.resolveFirstMessageMeta({ agent, permissionMode, explicitModel: action.model ?? void 0, capabilities });
@@ -4630,7 +7273,7 @@ ${action.prompt}`, { localId: `automation-${run.id}`, ...meta });
4630
7273
  item.lastLeaseAt = at;
4631
7274
  const body = { claimId: item.claimId, leaseMs: index.AUTOMATION_DEFAULT_LEASE_MS, ...item.pendingRunning ? { status: "running", ...item.pendingRunning } : {} };
4632
7275
  try {
4633
- const run = await client$1.report(item.runId, body);
7276
+ const run = await client.report(item.runId, body);
4634
7277
  item.pendingRunning = void 0;
4635
7278
  if (index.isAutomationRunTerminal(run.status)) settleExternally(item);
4636
7279
  } catch (error) {
@@ -4676,10 +7319,10 @@ ${action.prompt}`, { localId: `automation-${run.id}`, ...meta });
4676
7319
  const capacity = AUTOMATION_MAX_CONCURRENT - tracked.size;
4677
7320
  if (now() >= disabledUntil && capacity > 0) {
4678
7321
  try {
4679
- const claimed = await client$1.claim({ machineId: deps.machineId, limit: capacity, leaseMs: index.AUTOMATION_DEFAULT_LEASE_MS, capabilities: [index.AUTOMATION_DAEMON_CAPABILITY_PRECHECK] });
7322
+ const claimed = await client.claim({ machineId: deps.machineId, limit: capacity, leaseMs: index.AUTOMATION_DEFAULT_LEASE_MS, capabilities: [index.AUTOMATION_DAEMON_CAPABILITY_PRECHECK] });
4680
7323
  await Promise.all(claimed.runs.map((entry) => closed ? Promise.resolve() : execute(entry).catch((error) => deps.log(`Automation run ${entry.run.id} failed to start: ${error instanceof Error ? error.message : String(error)}`))));
4681
7324
  } catch (error) {
4682
- if (client.isAutomationsUnavailable(error)) {
7325
+ if (client$1.isAutomationsUnavailable(error)) {
4683
7326
  disabledUntil = now() + 6e4;
4684
7327
  if (now() - lastUnavailableLogAt >= AUTOMATION_UNAVAILABLE_LOG_MS) {
4685
7328
  lastUnavailableLogAt = now();
@@ -4687,7 +7330,7 @@ ${action.prompt}`, { localId: `automation-${run.id}`, ...meta });
4687
7330
  }
4688
7331
  } else {
4689
7332
  disabledUntil = now() + 1e4;
4690
- deps.log(`Automation claim failed${error instanceof client.AutomationsRequestError ? ` (${error.status})` : ""}`);
7333
+ deps.log(`Automation claim failed${error instanceof client$1.AutomationsRequestError ? ` (${error.status})` : ""}`);
4691
7334
  }
4692
7335
  }
4693
7336
  }
@@ -4702,7 +7345,7 @@ ${action.prompt}`, { localId: `automation-${run.id}`, ...meta });
4702
7345
  if (event === "idle") item.attentionReported = false;
4703
7346
  if (event === "blocked" && !item.attentionReported) {
4704
7347
  item.attentionReported = true;
4705
- void client$1.report(item.runId, { claimId: item.claimId, needsAttention: true, attentionReason: "needs_input" }).catch(() => deps.log(`Automation run ${item.runId} attention report failed`));
7348
+ void client.report(item.runId, { claimId: item.claimId, needsAttention: true, attentionReason: "needs_input" }).catch(() => deps.log(`Automation run ${item.runId} attention report failed`));
4706
7349
  }
4707
7350
  }
4708
7351
  }
@@ -4755,7 +7398,7 @@ function sanitizeImportTitle(value) {
4755
7398
  return collapsed.length > 200 ? `${collapsed.slice(0, 199)}\u2026` : collapsed;
4756
7399
  }
4757
7400
  async function preflightNewBundle(bundlePath) {
4758
- const home = fs$1.mkdtempSync(path$2.join(os.tmpdir(), "vh-preflight-"));
7401
+ const home = require$$0.mkdtempSync(require$$1.join(os.tmpdir(), "vh-preflight-"));
4759
7402
  try {
4760
7403
  return await new Promise((resolve) => {
4761
7404
  let stdout = "";
@@ -4796,12 +7439,13 @@ async function preflightNewBundle(bundlePath) {
4796
7439
  });
4797
7440
  } finally {
4798
7441
  try {
4799
- fs$1.rmSync(home, { recursive: true, force: true });
7442
+ require$$0.rmSync(home, { recursive: true, force: true });
4800
7443
  } catch {
4801
7444
  }
4802
7445
  }
4803
7446
  }
4804
7447
  const HANDOVER_PREFLIGHT_TIMEOUT_MS = 3e4;
7448
+ const SPAWN_WEBHOOK_TIMEOUT_MS = 15e3;
4805
7449
  async function startDaemon() {
4806
7450
  const initialMachineMetadata = machineMetadata.getInitialMachineMetadata();
4807
7451
  const startupCliAvailability = machineMetadata.getStartupCliAvailability();
@@ -4896,7 +7540,7 @@ async function startDaemon() {
4896
7540
  const turnActivity = new api.TurnActivityTracker();
4897
7541
  const backgroundTasks = new backgroundTaskActivity.BackgroundTaskTracker();
4898
7542
  const peerCoordinator = createPeerCoordinator({ getChildren: () => Array.from(pidToTrackedSession.values()) });
4899
- const hibernationAutomations = client.createAutomationsClient({ serverUrl: configuration.configuration.serverUrl, token: credentials.token, client: "daemon-hibernate" });
7543
+ const hibernationAutomations = client$1.createAutomationsClient({ serverUrl: configuration.configuration.serverUrl, token: credentials.token, client: "daemon-hibernate" });
4900
7544
  const daemonHibernation = createDaemonHibernation({
4901
7545
  idleMs: () => persistence.resolveIdleMs(agentHibernationSetting),
4902
7546
  checkMs: persistence.resolveCheckMs(),
@@ -4919,7 +7563,7 @@ async function startDaemon() {
4919
7563
  try {
4920
7564
  return await collectAutomationBindings(hibernationAutomations, machineId);
4921
7565
  } catch (error) {
4922
- if (client.isAutomationsUnavailable(error)) return [];
7566
+ if (client$1.isAutomationsUnavailable(error)) return [];
4923
7567
  throw error;
4924
7568
  }
4925
7569
  },
@@ -4933,6 +7577,7 @@ async function startDaemon() {
4933
7577
  const sessionIdToFinishedSession = /* @__PURE__ */ new Map();
4934
7578
  let teamWorker;
4935
7579
  let automationRunner;
7580
+ let projectPresence;
4936
7581
  const persisted = persistence.readPersistedSessions();
4937
7582
  const liveHappyProcesses = await doctor$1.findAllHappyProcesses();
4938
7583
  for (const [id, s] of Object.entries(persisted)) {
@@ -5022,6 +7667,7 @@ async function startDaemon() {
5022
7667
  }
5023
7668
  };
5024
7669
  const assistantSpawnGate = createSpawnGate();
7670
+ const projectsClient = client.createProjectsClient({ token: async () => credentials.token });
5025
7671
  const spawnSession = async (options) => {
5026
7672
  const timer = createSpawnTimer();
5027
7673
  await index$1.refreshAgentHomes(Date.now(), { allowStale: true });
@@ -5033,6 +7679,10 @@ async function startDaemon() {
5033
7679
  result = await (options.forceNew ? assistantSpawnGate.replace(() => spawnSessionImpl(options, timer)) : assistantSpawnGate.join(() => spawnSessionImpl(options, timer)));
5034
7680
  }
5035
7681
  logger.logger.debug(timer.format({ agent: options.agent ?? "claude", outcome: result.type }));
7682
+ if (result.type === "success" && options.parentSessionId) {
7683
+ const outcome = await spawnAgents.joinProject(projectsClient, result.sessionId, { kind: "lineage", parentSessionId: options.parentSessionId });
7684
+ if (outcome.joined) logger.logger.debug(`[DAEMON RUN] fork ${result.sessionId} joined project ${outcome.projectId} (lineage)`);
7685
+ }
5036
7686
  return result;
5037
7687
  };
5038
7688
  const currentCliAvailability = () => apiMachineRef?.getCLIAvailability() ?? startupCliAvailability;
@@ -5179,7 +7829,7 @@ async function startDaemon() {
5179
7829
  if (options.token) {
5180
7830
  if (options.agent === "codex") {
5181
7831
  const codexHomeDir = tmp__namespace.dirSync();
5182
- await fs.writeFile(path$2.join(codexHomeDir.name, "auth.json"), options.token);
7832
+ await fs.writeFile(require$$1.join(codexHomeDir.name, "auth.json"), options.token);
5183
7833
  authEnv.CODEX_HOME = codexHomeDir.name;
5184
7834
  } else {
5185
7835
  authEnv.CLAUDE_CODE_OAUTH_TOKEN = options.token;
@@ -5262,7 +7912,7 @@ async function startDaemon() {
5262
7912
  const sessionDesc = tmuxSessionName || "current/most recent session";
5263
7913
  logger.logger.debug(`[DAEMON RUN] Attempting to spawn session in tmux: ${sessionDesc}`);
5264
7914
  const tmux = getTmuxUtilities(tmuxSessionName);
5265
- const cliPath = path$2.join(projectPath.projectPath(), "dist", "index.mjs");
7915
+ const cliPath = require$$1.join(projectPath.projectPath(), "dist", "index.mjs");
5266
7916
  const agent = options.agent ?? "claude";
5267
7917
  if (!spawnAgents.isSpawnAgent(agent)) {
5268
7918
  return {
@@ -5452,22 +8102,33 @@ async function startDaemon() {
5452
8102
  });
5453
8103
  logger.logger.debug(`[DAEMON RUN] Waiting for session webhook for PID ${happyProcess.pid}`);
5454
8104
  return new Promise((resolve) => {
8105
+ const pid = happyProcess.pid;
8106
+ let settled = false;
8107
+ const fail = (startupExit) => {
8108
+ if (settled) return;
8109
+ settled = true;
8110
+ clearTimeout(timeout);
8111
+ pidToAwaiter.delete(pid);
8112
+ startupExit.reason ??= readStartupExitReason(configuration.configuration.logsDir, pid);
8113
+ const errorMessage = describeStartupExit(startupExit, SPAWN_WEBHOOK_TIMEOUT_MS);
8114
+ logger.logger.debug(`[DAEMON RUN] Spawn of PID ${pid} failed: ${errorMessage}`);
8115
+ resolve({ type: "error", errorMessage, startupExit });
8116
+ };
8117
+ happyProcess.once("exit", (code, signal) => fail({ exited: true, code, signal }));
5455
8118
  const timeout = setTimeout(() => {
5456
- pidToAwaiter.delete(happyProcess.pid);
5457
- logger.logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${happyProcess.pid}`);
5458
- if (happyProcess.pid) {
5459
- try {
5460
- sessionLock.terminateProcess(happyProcess.pid, () => {
5461
- });
5462
- } catch {
5463
- }
8119
+ if (settled) return;
8120
+ pidToAwaiter.delete(pid);
8121
+ logger.logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${pid}`);
8122
+ try {
8123
+ const started = sessionLock.terminateProcess(pid, (stopped) => fail({ exited: stopped, code: null, signal: null, timedOut: true }));
8124
+ if (!started) fail({ exited: false, code: null, signal: null, timedOut: true });
8125
+ } catch {
8126
+ fail({ exited: false, code: null, signal: null, timedOut: true });
5464
8127
  }
5465
- resolve({
5466
- type: "error",
5467
- errorMessage: `Session webhook timeout for PID ${happyProcess.pid}`
5468
- });
5469
- }, 15e3);
5470
- pidToAwaiter.set(happyProcess.pid, (completedSession) => {
8128
+ }, SPAWN_WEBHOOK_TIMEOUT_MS);
8129
+ pidToAwaiter.set(pid, (completedSession) => {
8130
+ if (settled) return;
8131
+ settled = true;
5471
8132
  clearTimeout(timeout);
5472
8133
  logger.logger.debug(`[DAEMON RUN] Session ${completedSession.happySessionId} fully spawned with webhook`);
5473
8134
  resolve({
@@ -5585,15 +8246,15 @@ async function startDaemon() {
5585
8246
  tracked.happySessionMetadataFromLocalWebhook = metadata;
5586
8247
  logger.logger.debug(`[DAEMON RUN] Session ${happySessionId} relaunch metadata from ${relaunch.source}`);
5587
8248
  const precheck = resumePrecheck(metadata, {
5588
- cwdExists: (p) => fs$1.existsSync(p),
8249
+ cwdExists: (p) => require$$0.existsSync(p),
5589
8250
  // B-478: also looks in every other Claude config dir the user's shell
5590
8251
  // or settings point at, not just the one the daemon was started with.
5591
8252
  conversationExists: (cwd, claudeSessionId) => index$1.locateClaudeConversation(cwd, claudeSessionId) !== null
5592
8253
  });
5593
8254
  let freshConversation = false;
5594
8255
  if (!precheck.ok) {
5595
- if (precheck.reason === "conversation-missing") {
5596
- logger.logger.debug(`[DAEMON RUN] resume: transcript for ${happySessionId} is gone (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
8256
+ if (resumeStartsFreshConversation(precheck.reason)) {
8257
+ logger.logger.debug(`[DAEMON RUN] resume: ${precheck.reason} for ${happySessionId} (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
5597
8258
  freshConversation = true;
5598
8259
  } else {
5599
8260
  return { type: "error", errorMessage: `resume-precheck:${precheck.reason}: ${precheck.detail}` };
@@ -5606,9 +8267,10 @@ async function startDaemon() {
5606
8267
  const model = sanitizeResumeModel(options?.model);
5607
8268
  if (model) launch.args.push("--model", model);
5608
8269
  else if (options?.model !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid model ${JSON.stringify(options.model)}`);
5609
- const permissionMode = spawnAgents.sanitizeSpawnPermissionMode(options?.permissionMode);
8270
+ const requestedMode = options?.permissionMode ?? (options?.keepPublishedPermissionMode ? publishedRelaunchPermissionMode(metadata) : void 0);
8271
+ const permissionMode = spawnAgents.sanitizeSpawnPermissionMode(requestedMode);
5610
8272
  if (permissionMode) launch.args.push("--permission-mode", permissionMode);
5611
- else if (options?.permissionMode !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(options.permissionMode)}`);
8273
+ else if (requestedMode !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(requestedMode)}`);
5612
8274
  const result = await spawnTrackedHappyProcess({
5613
8275
  args: launch.args,
5614
8276
  cwd: launch.cwd,
@@ -5663,7 +8325,7 @@ async function startDaemon() {
5663
8325
  resolve();
5664
8326
  }
5665
8327
  };
5666
- const requested = sessionLock.terminateProcess(pid, () => {
8328
+ const requested = sessionLock.terminateProcessTree(pid, () => {
5667
8329
  const tracked = pidToTrackedSession.get(pid);
5668
8330
  if (tracked) {
5669
8331
  if (tracked.happySessionId && tracked.encryption) {
@@ -5717,7 +8379,7 @@ async function startDaemon() {
5717
8379
  tracked.happySessionMetadataFromLocalWebhook = metadata;
5718
8380
  logger.logger.debug(`[DAEMON RUN] Session ${happySessionId} relaunch metadata from ${relaunch.source}`);
5719
8381
  const precheck = resumePrecheck(metadata, {
5720
- cwdExists: (p) => fs$1.existsSync(p),
8382
+ cwdExists: (p) => require$$0.existsSync(p),
5721
8383
  // B-478: also looks in every other Claude config dir the user's shell
5722
8384
  // or settings point at, not just the one the daemon was started with.
5723
8385
  conversationExists: (cwd2, claudeSessionId) => index$1.locateClaudeConversation(cwd2, claudeSessionId) !== null
@@ -5733,7 +8395,7 @@ async function startDaemon() {
5733
8395
  cwd = launch.cwd;
5734
8396
  } else if ((metadata.flavor ?? "claude") === "claude" && typeof metadata.path === "string" && metadata.path.length > 0) {
5735
8397
  cwd = metadata.path;
5736
- if (!fs$1.existsSync(cwd)) {
8398
+ if (!require$$0.existsSync(cwd)) {
5737
8399
  return { type: "error", errorMessage: `restart-precheck:cwd-missing: ${cwd}` };
5738
8400
  }
5739
8401
  args = ["claude", "--happy-starting-mode", "remote", "--started-by", "daemon"];
@@ -5779,7 +8441,7 @@ async function startDaemon() {
5779
8441
  logger.logger.debug(`[DAEMON RUN] Attempting to stop session ${sessionId}`);
5780
8442
  for (const [pid, session] of pidToTrackedSession.entries()) {
5781
8443
  if (session.happySessionId === sessionId || sessionId.startsWith("PID-") && pid === parseInt(sessionId.replace("PID-", ""))) {
5782
- const requested = sessionLock.terminateProcess(pid, (stopped) => {
8444
+ const requested = sessionLock.terminateProcessTree(pid, (stopped) => {
5783
8445
  if (!stopped) {
5784
8446
  logger.logger.debug(`[DAEMON RUN] Session ${sessionId} survived SIGTERM and SIGKILL attempts`);
5785
8447
  return;
@@ -5958,10 +8620,10 @@ async function startDaemon() {
5958
8620
  };
5959
8621
  persistence.writeDaemonState(fileState);
5960
8622
  logger.logger.debug("[DAEMON RUN] Daemon state written");
5961
- const bundlePath = path$2.join(projectPath.projectPath(), "dist", "index.mjs");
8623
+ const bundlePath = require$$1.join(projectPath.projectPath(), "dist", "index.mjs");
5962
8624
  let initialBundleMtimeMs = 0;
5963
8625
  try {
5964
- initialBundleMtimeMs = fs$1.statSync(bundlePath).mtimeMs;
8626
+ initialBundleMtimeMs = require$$0.statSync(bundlePath).mtimeMs;
5965
8627
  } catch {
5966
8628
  logger.logger.debug(`[DAEMON RUN] Bundle at ${bundlePath} not found; self-restart on upgrade disabled`);
5967
8629
  }
@@ -6035,6 +8697,15 @@ async function startDaemon() {
6035
8697
  setStore: (store) => claudeAuthService.setStore(store)
6036
8698
  });
6037
8699
  claudeAuthService.start();
8700
+ apiMachine.setModelConfigService(new ModelConfigService({
8701
+ home: os$1.homedir(),
8702
+ env: process.env,
8703
+ happyHomeDir: configuration.configuration.happyHomeDir,
8704
+ isInstalled: detectCLI.commandOnPath,
8705
+ onChanged: (harness) => {
8706
+ if (harness === "claude") void claudeAuthService.probe("model-config", true);
8707
+ }
8708
+ }));
6038
8709
  apiMachine.setAgentHibernationHandlers(persistence.resolveIdleMs(agentHibernationSetting), async (requested) => {
6039
8710
  const value = requested <= 0 ? 0 : persistence.settingIdleMs(requested);
6040
8711
  await persistence.updateSettings((current) => ({ ...current, agentHibernationIdleMs: value }));
@@ -6042,6 +8713,12 @@ async function startDaemon() {
6042
8713
  daemonHibernation.invalidateBindings();
6043
8714
  return persistence.resolveIdleMs(agentHibernationSetting);
6044
8715
  });
8716
+ const webPanelsSync = startWebPanelsSync({
8717
+ statMtime: async () => (await fs.stat(configuration.configuration.settingsFile).catch(() => null))?.mtimeMs ?? null,
8718
+ readRaw: async () => (await persistence.readSettings()).webPanels,
8719
+ publish: (panels) => apiMachine.setWebPanels(panels),
8720
+ logProblems: (problems) => logger.logger.warn(`[DAEMON RUN] settings.json webPanels: skipped ${problems.length} entr${problems.length === 1 ? "y" : "ies"}: ${problems.map((p) => `#${p.index}${p.id ? ` (${p.id})` : ""} ${p.reason}`).join("; ")}`)
8721
+ });
6045
8722
  apiMachine.connect();
6046
8723
  if (identityConflict?.confidence === "weak") {
6047
8724
  void apiMachine.updateMachineMetadata((current) => ({
@@ -6128,7 +8805,7 @@ async function startDaemon() {
6128
8805
  let bundleReplaced = false;
6129
8806
  if (initialBundleMtimeMs > 0) {
6130
8807
  try {
6131
- const currentMtimeMs = fs$1.statSync(bundlePath).mtimeMs;
8808
+ const currentMtimeMs = require$$0.statSync(bundlePath).mtimeMs;
6132
8809
  bundleReplaced = currentMtimeMs !== initialBundleMtimeMs;
6133
8810
  } catch {
6134
8811
  }
@@ -6149,6 +8826,7 @@ async function startDaemon() {
6149
8826
  logger.logger.debug(relayMove ? `[DAEMON RUN] Relay moved to ${relayMove.serverUrl}; handing off to a new daemon on the new settings` : "[DAEMON RUN] Daemon bundle replaced on disk and verified, handing off to new daemon");
6150
8827
  teamWorker?.stop();
6151
8828
  automationRunner?.stop();
8829
+ projectPresence?.stop();
6152
8830
  clearInterval(restartOnStaleVersionAndHeartbeat);
6153
8831
  clearInterval(cliUpdateInterval);
6154
8832
  stopAgentVersionChecks();
@@ -6218,24 +8896,42 @@ async function startDaemon() {
6218
8896
  return !!record && typeof record.hibernatedAt === "number" && record.hibernatedAt >= record.savedAt;
6219
8897
  },
6220
8898
  wakeHibernated: async (id) => {
6221
- const result = await resumeSession(id);
8899
+ const result = await resumeSession(id, { keepPublishedPermissionMode: true });
6222
8900
  if (result.type !== "success") return false;
6223
8901
  return waitForSessionLive(id, (sid) => [...pidToTrackedSession.values()].some((s) => s.happySessionId === sid && isPidAlive(s.pid)));
6224
8902
  },
8903
+ joinProject: (sessionId, projectId) => spawnAgents.joinProject(projectsClient, sessionId, { kind: "explicit", projectId }, { via: "automation" }),
8904
+ log: (message) => logger.logger.debug(`[DAEMON RUN] ${message}`)
8905
+ });
8906
+ projectPresence = createProjectPresenceReporter({
8907
+ machineId,
8908
+ client: projectsClient,
8909
+ live: () => [...pidToTrackedSession.values()].filter((s) => s.happySessionId && isPidAlive(s.pid)).map((s) => ({
8910
+ sessionId: s.happySessionId,
8911
+ flavor: s.happySessionMetadataFromLocalWebhook?.flavor ?? null,
8912
+ branch: s.happySessionMetadataFromLocalWebhook?.worktree?.branch ?? null,
8913
+ running: turnActivity.activeSessions().includes(s.happySessionId)
8914
+ })),
6225
8915
  log: (message) => logger.logger.debug(`[DAEMON RUN] ${message}`)
6226
8916
  });
6227
8917
  void apiMachine.updateMachineMetadata((current) => ({
6228
8918
  ...current ?? initialMachineMetadata,
6229
8919
  teamsVersion: 1,
6230
8920
  teamLaunchVersion: 1,
8921
+ // B-689: this daemon acts on the owner's retry-operation (web gates「重试启动」).
8922
+ teamRetryVersion: machineMetadata.TEAM_RETRY_CAPABILITY_VERSION,
6231
8923
  // B-586: this daemon serves the worktree-* RPCs (web gates 「在新 worktree 中」 on it).
6232
- worktreeVersion: mirrorProtocol.WORKTREE_CAPABILITY_VERSION
8924
+ worktreeVersion: mirrorProtocol.WORKTREE_CAPABILITY_VERSION,
8925
+ // B-688: this daemon serves the model-config-* RPCs (web gates 「模型与 Provider」 on it).
8926
+ modelConfigVersion: MODEL_CONFIG_CAPABILITY_VERSION
6233
8927
  })).catch(() => logger.logger.debug("[DAEMON RUN] Teams capability publication will retry on reconnect"));
6234
8928
  const cleanupAndShutdown = async (source, errorMessage) => {
8929
+ webPanelsSync.stop();
6235
8930
  logger.logger.debug(`[DAEMON RUN] Starting proper cleanup (source: ${source}, errorMessage: ${errorMessage})...`);
6236
8931
  const scrollbackFlush = apiMachine.flushTerminalScrollback();
6237
8932
  teamWorker?.stop();
6238
8933
  automationRunner?.stop({ killScripts: true });
8934
+ projectPresence?.stop();
6239
8935
  mirrorProtocol.currentWorktreeService()?.stopAll();
6240
8936
  if (restartOnStaleVersionAndHeartbeat) {
6241
8937
  clearInterval(restartOnStaleVersionAndHeartbeat);