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,83 +1,86 @@
1
- import { i as isClaudeSessionId, g as extractCompleteLines, h as decideBackfill, j as parseTerminalHookPayload, k as decideMirrorBinding, M as MIRROR_BACKFILL_LINES_DEFAULT, m as mirrorLineKey, n as mirrorLocalId, o as initializeOwnedWorktree, e as summarizeSpawnSessionForLog, q as startAgentVersionChecks, W as WORKTREE_CAPABILITY_VERSION, t as currentWorktreeService } from './mirrorProtocol-6IFGPpjJ.mjs';
2
- import { P as PI_ADAPTER_INSTALL_HINT, s as sanitizeSpawnModel } from './piRunnerArgs-AT8QJY7x.mjs';
1
+ import { i as isClaudeSessionId, M as ModelConfigError, B as BackupStore, g as readConfigFile, h as sha256, j as atomicWriteFile, k as extractCompleteLines, m as decideBackfill, n as parseTerminalHookPayload, o as decideMirrorBinding, q as MIRROR_BACKFILL_LINES_DEFAULT, t as mirrorLineKey, u as mirrorLocalId, v as initializeOwnedWorktree, e as summarizeSpawnSessionForLog, w as startAgentVersionChecks, W as WORKTREE_CAPABILITY_VERSION, x as currentWorktreeService } from './mirrorProtocol-BR4luBC0.mjs';
2
+ import { P as PI_ADAPTER_INSTALL_HINT, s as sanitizeSpawnModel } from './piRunnerArgs-H2pgpA5z.mjs';
3
3
  import fs from 'fs/promises';
4
+ import os from 'os';
4
5
  import * as tmp from 'tmp';
5
6
  import axios from 'axios';
6
- import { T as TurnActivityTracker, A as ApiClient } from './api-Dib0dmqC.mjs';
7
- import { S as SPAWN_AGENTS, i as isSpawnAgent, s as sanitizeSpawnPermissionMode, r as resolveSpawnPermissionMode, a as resolveFirstMessageMeta } from './spawnAgents-Bw6j4tqz.mjs';
8
- import { l as logger } from './logger--vAVtXB_.mjs';
9
- import { readdirSync, statSync, unlinkSync, realpathSync, mkdirSync, writeFileSync, accessSync, constants as constants$1, existsSync, readFileSync, openSync, fsyncSync, closeSync, renameSync } from 'node:fs';
7
+ import { T as TurnActivityTracker, A as ApiClient } from './api-Hov8p7CA.mjs';
8
+ import { S as SPAWN_AGENTS, i as isSpawnAgent, s as sanitizeSpawnPermissionMode, r as resolveSpawnPermissionMode, a as resolveFirstMessageMeta, j as joinProject } from './spawnAgents-CgPMWexP.mjs';
9
+ import { l as logger } from './logger-BUngm5Xg.mjs';
10
+ import { readdirSync, statSync, unlinkSync, realpathSync, promises, mkdirSync, writeFileSync, accessSync, constants as constants$1, existsSync, readFileSync, openSync, readSync, closeSync, fsyncSync, renameSync, rmdirSync } from 'node:fs';
10
11
  import { join, isAbsolute, resolve, dirname, sep, basename, delimiter } from 'node:path';
11
- import { p as pruneStaleCompileCaches } from './index-BYgfern_.mjs';
12
- import { a as authAndSetupMachineIfNeeded } from './auth-BRjd2esb.mjs';
13
- import { c as configuration, f as ensurePrivateDirectorySync, w as writePrivateFileSync } from './configuration-DVrb61aY.mjs';
12
+ import { p as pruneStaleCompileCaches } from './index-wCbtF4BK.mjs';
13
+ import { a as authAndSetupMachineIfNeeded } from './auth-BG1DY0gj.mjs';
14
+ import { c as configuration, f as ensurePrivateDirectorySync, w as writePrivateFileSync } from './configuration-PxzEJumr.mjs';
14
15
  import { spawn, execSync } from 'child_process';
15
- import { p as packageJson } from './package-B7B03ejW.mjs';
16
- import { g as globalPrefixForPackage, a as getEnvironmentInfo } from './doctor-0BiGwJXk.mjs';
17
- import { s as spawnHappyCLI } from './spawnHappyCLI-C2stUioM.mjs';
18
- import { b as readPersistedSessions, r as readSettings, l as latchKeepAwake, q as reportSignature, s as decideDaemonHibernation, t as nextCheckDelay, v as persistSession, d as readDaemonState, x as acquireDaemonLock, a as resolveCheckMs, y as resolveIdleMs, z as deletePersistedSessions, A as writeDaemonState, B as writeSettings, C as settingIdleMs, u as updateSettings, D as rewriteCredentialsForRelay, g as readCredentials, E as releaseDaemonLock } from './persistence-DTk4sNpd.mjs';
19
- import { i as isDaemonRunningCurrentlyInstalledHappyVersion, b as stopDaemon, o as cleanupDaemonState } from './controlClient-BYKyGyxj.mjs';
20
- import { e as sendUserMessage, f as readSessionMetadata, r as readSessionTranscript, l as listAccountSessions, a as listSessions, M as MAX_READ_LIMIT, s as sessionWebUrl, g as waitForSessionKey, d as archiveSession, j as analyzeLatestTurn, k as readSessionLog, m as TURN_WINDOW, n as userPromptText } from './sessionOps-BVoXe12O.mjs';
16
+ import { p as packageJson } from './package-7Ld1YMhh.mjs';
17
+ import { a as globalPrefixForPackage, g as getEnvironmentInfo } from './doctor-IctjVh9T.mjs';
18
+ import { s as spawnHappyCLI } from './spawnHappyCLI-BjFZc_7V.mjs';
19
+ import { c as readPersistedSessions, r as readSettings, l as latchKeepAwake, q as reportSignature, s as decideDaemonHibernation, t as nextCheckDelay, v as persistSession, d as readDaemonState, x as acquireDaemonLock, a as resolveCheckMs, y as resolveIdleMs, z as deletePersistedSessions, A as writeDaemonState, B as writeSettings, C as settingIdleMs, u as updateSettings, D as rewriteCredentialsForRelay, g as readCredentials, E as releaseDaemonLock } from './persistence-BFUOHW5h.mjs';
20
+ import { i as isDaemonRunningCurrentlyInstalledHappyVersion, s as stopDaemon, t as cleanupDaemonState } from './controlClient-DoeYovwP.mjs';
21
+ import { e as sendUserMessage, f as readSessionMetadata, r as readSessionTranscript, l as listAccountSessions, a as listSessions, M as MAX_READ_LIMIT, s as sessionWebUrl, g as waitForSessionKey, d as archiveSession, j as analyzeLatestTurn, k as readSessionLog, m as TURN_WINDOW, n as userPromptText } from './sessionOps-C58iDeD5.mjs';
21
22
  import fastify from 'fastify';
22
23
  import { z } from 'zod';
23
24
  import { validatorCompiler, serializerCompiler } from 'fastify-type-provider-zod';
24
25
  import { d as decodeBase64, s as sameRelay, e as encodeBase64, h as decrypt } from './authRelay-DhQhkBvX.mjs';
25
26
  import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'node:crypto';
26
27
  import { c as checkPreviewPath } from './previewPath-CXN4Vag0.mjs';
27
- import { a as BACKGROUND_TASKS_MAX, c as BACKGROUND_TASK_DESCRIPTION_MAX, d as BackgroundTaskTracker } from './backgroundTaskActivity-BVwJBl02.mjs';
28
- import { b as sanitizeRateLimitReport } from './rateLimitWindows-XrJiiBpU.mjs';
29
- import { f as formatEditConflictNotice, b as SESSION_PEER_SENT_FROM, s as sendPeerMessage, l as listPeerSessions, C as CLI_PEER_SENDER_ID } from './peerTools-3R9RUARX.mjs';
30
- import os, { hostname, homedir, userInfo, tmpdir } from 'node:os';
31
- import { c as RemoteCallBudget, e as REMOTE_WRITE_CALLS_PER_MINUTE, d as deliverToSession, g as guardRemoteSessionOpsRequest, h as remoteError, i as REMOTE_OP_DEADLINE_MS, j as formatRemoteAuditLine, k as REMOTE_SEND_COMMIT_DEADLINE_MS, m as REMOTE_RESUME_WAIT_MS, n as capRemoteTranscript, o as capRemoteText, p as REMOTE_ANSWER_MAX_BYTES, q as REMOTE_TITLE_MAX_BYTES } from './remoteSessionClient-DRb2Jr5s.mjs';
32
- import { assistantHome, bootstrapAssistantHome } from './bootstrap-BUagGC_-.mjs';
33
- import { refreshAgentHomes, locateClaudeConversation, agentHomeSpawnEnv } from './index-Bvldtdny.mjs';
34
- import { existsSync as existsSync$1, statSync as statSync$1, mkdtempSync, rmSync } from 'fs';
35
- import { join as join$1 } from 'path';
28
+ import { a as BACKGROUND_TASKS_MAX, d as BACKGROUND_TASK_DESCRIPTION_MAX, e as BackgroundTaskTracker } from './backgroundTaskActivity-8PdPxrvy.mjs';
29
+ import { b as sanitizeRateLimitReport } from './rateLimitWindows-BkfuUB1a.mjs';
30
+ import { f as formatEditConflictNotice, b as SESSION_PEER_SENT_FROM, s as sendPeerMessage, l as listPeerSessions, C as CLI_PEER_SENDER_ID } from './peerTools-BOlDRyhi.mjs';
31
+ import os$1, { hostname, homedir, userInfo, tmpdir } from 'node:os';
32
+ import { c as RemoteCallBudget, e as REMOTE_WRITE_CALLS_PER_MINUTE, d as deliverToSession, g as guardRemoteSessionOpsRequest, h as remoteError, i as REMOTE_OP_DEADLINE_MS, j as formatRemoteAuditLine, k as REMOTE_SEND_COMMIT_DEADLINE_MS, m as REMOTE_RESUME_WAIT_MS, n as capRemoteTranscript, o as capRemoteText, p as REMOTE_ANSWER_MAX_BYTES, q as REMOTE_TITLE_MAX_BYTES } from './remoteSessionClient-PP-mOKmw.mjs';
33
+ import { assistantHome, bootstrapAssistantHome } from './bootstrap-Dt5I1SOl.mjs';
34
+ import { refreshAgentHomes, locateClaudeConversation, agentHomeSpawnEnv } from './index-Bsvbgh9e.mjs';
35
+ import require$$0, { existsSync as existsSync$1, statSync as statSync$1, mkdtempSync, rmSync } from 'fs';
36
+ import require$$1, { join as join$1 } from 'path';
36
37
  import { spawn as spawn$1, execFile, spawnSync } from 'node:child_process';
37
38
  import { p as projectPath } from './projectPath-BTBIMB57.mjs';
38
39
  import { d as daemonEndpointsMatch, r as resolveClaudeCredentialReadiness } from './doctorReadiness-C208SMN9.mjs';
39
- import { g as getInitialMachineMetadata, a as getStartupCliAvailability } from './machineMetadata-B1H9gNbN.mjs';
40
- import { buildResumeLaunch } from './handleResumeCommand-CgjpsdDe.mjs';
41
- import { u as ServerMigrateNoticeSchema, v as AUTOMATION_SUMMARY_MAX_CHARS, w as AUTOMATION_PRECHECK_OUTPUT_MAX_CHARS, x as AUTOMATION_PRECHECK_DEFAULT_TIMEOUT_MS, a as AUTOMATION_PRECHECK_MAX_TIMEOUT_MS, y as AUTOMATION_CLAIM_MAX_RUNS, z as AUTOMATION_DAEMON_CAPABILITY_PRECHECK, D as AUTOMATION_DEFAULT_LEASE_MS, i as isAutomationRunTerminal } from './index-Clqlu17M.mjs';
40
+ import { o as ownerRetryPending, c as consumeOwnerRetry, s as spawnGate, a as afterStartupFailure, b as startupFailureMessage, T as TEAM_SPAWN_MAX_ATTEMPTS, d as TEAM_CLEANUP_RETRY_MS, g as getInitialMachineMetadata, e as getStartupCliAvailability, f as TEAM_RETRY_CAPABILITY_VERSION } from './machineMetadata-BXN_bKU3.mjs';
41
+ import require$$3 from 'crypto';
42
+ import { c as commandOnPath } from './detectCLI-CSGMlV51.mjs';
43
+ import { buildResumeLaunch } from './handleResumeCommand-DpaZvm2c.mjs';
44
+ import { n as normalizeWebPanels } from './webPanels-B2_C2-3g.mjs';
45
+ import { w as ServerMigrateNoticeSchema, x as AUTOMATION_SUMMARY_MAX_CHARS, y as AUTOMATION_PRECHECK_OUTPUT_MAX_CHARS, z as AUTOMATION_PRECHECK_DEFAULT_TIMEOUT_MS, b as AUTOMATION_PRECHECK_MAX_TIMEOUT_MS, D as AUTOMATION_CLAIM_MAX_RUNS, E as AUTOMATION_DAEMON_CAPABILITY_PRECHECK, F as AUTOMATION_DEFAULT_LEASE_MS, i as isAutomationRunTerminal } from './index-C6Vn5Eac.mjs';
42
46
  import { access, symlink, readFile, rm, unlink, readlink, lstat, constants, stat, open } from 'node:fs/promises';
43
47
  import { p as parseExactVersion, c as compareExactVersions, f as fetchCliUpdateState, r as resolveCliUpdateCheckInterval, D as DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS } from './cliUpdate-Y34VGe9Y.mjs';
44
- import { c as createAutomationsClient, i as isAutomationsUnavailable, d as AutomationsRequestError } from './client-CnlkkrZO.mjs';
48
+ import { P as ProjectsUnsupportedError, c as createProjectsClient } from './client-Ca5Pcgy_.mjs';
49
+ import { c as createAutomationsClient, i as isAutomationsUnavailable, d as AutomationsRequestError } from './client-CnB7kRCT.mjs';
45
50
  import { createRequire } from 'node:module';
46
51
  import { g as getProjectPath } from './path-D2wdaNSk.mjs';
47
52
  import { b as extractClaudeEditPaths } from './editPaths-BVfS_FFL.mjs';
48
- import { s as startFileWatcher } from './startFileWatcher-CR09Snmz.mjs';
49
- import { I as InvalidateSync } from './sync-DbW07iQS.mjs';
53
+ import { s as startFileWatcher } from './startFileWatcher-DXJ7yB5v.mjs';
54
+ import { I as InvalidateSync } from './sync-BvVhDO40.mjs';
50
55
  import { R as RawJSONLinesSchema } from './types-CkqAACXx.mjs';
51
56
  import { t as tmuxArgs, a as scrubTmuxClientEnv, s as shellescape } from './tmuxSocket-B8Yx20sT.mjs';
52
- import { p as processIdentityFields, r as readSessionLock, t as terminateProcess } from './sessionLock-DBdtZGOL.mjs';
57
+ import { p as processIdentityFields, r as readSessionLock, t as terminateProcess, d as terminateProcessTree } from './sessionLock-nBXdJxJm.mjs';
53
58
  import { findAllHappyProcesses } from './doctor-BPkYWSuq.mjs';
54
- import { T as TEAM_SKILL } from './resources-BdFBQi8r.mjs';
59
+ import { T as TEAM_SKILL } from './resources-y9jfyO-_.mjs';
55
60
  import { promisify } from 'node:util';
56
61
  import { c as clipText, r as renderAction, b as renderTemplate } from './template-CiOPa2rd.mjs';
57
62
  import { d as detectDaemonSupervisor } from './daemonSupervisor-C6urv3_8.mjs';
58
63
  import { d as describeAgentHome } from './loginShellEnv-Dw8M7tkI.mjs';
59
- import './sessionModeFile-ByLbXTbg.mjs';
60
- import './lidState-DNMlIhX0.mjs';
61
- import 'os';
64
+ import './acpSessionResume-B9l54P-X.mjs';
65
+ import './lidState-bBrmaQd2.mjs';
62
66
  import 'node:events';
63
67
  import 'socket.io-client';
64
- import './attachmentLimits-UyFn8fkQ.mjs';
68
+ import './pushNotifications-DCiBEVeC.mjs';
69
+ import './contentLogMetadata-BlWI0egu.mjs';
65
70
  import './limits-DIo7rEBR.mjs';
66
- import './time-BuGWTVP6.mjs';
67
- import './registerCommonHandlers-CvIedVRf.mjs';
71
+ import './time-D3ETL7Jb.mjs';
72
+ import './registerCommonHandlers-CTkCvjxt.mjs';
68
73
  import 'util';
69
- import 'crypto';
70
74
  import 'cross-spawn';
71
75
  import '@paralleldrive/cuid2';
72
- import './contentLogMetadata-BlWI0egu.mjs';
73
76
  import 'chalk';
74
77
  import 'tweetnacl';
75
- import './browser-Dj_DYQEh.mjs';
78
+ import './browser-DUNetFT4.mjs';
76
79
  import 'open';
77
80
  import './ids-DU6sLx4C.mjs';
78
81
  import 'url';
79
- import './detectCLI-CSGMlV51.mjs';
80
- import './localHappyAgentAuth-BezKSFDi.mjs';
82
+ import './localHappyAgentAuth-Dn1jYDpt.mjs';
83
+ import './processTreeSnapshot-CuLJDNC-.mjs';
81
84
  import 'ps-list';
82
85
 
83
86
  async function resolveRelaunchMetadata(snapshot, fetchServer) {
@@ -165,7 +168,7 @@ function startCaffeinate() {
165
168
  }
166
169
  killOrphanedCaffeinateProcesses();
167
170
  try {
168
- caffeinateProcess = spawn("caffeinate", ["-im"], {
171
+ caffeinateProcess = spawn("caffeinate", caffeinateArgs(process.pid), {
169
172
  stdio: "ignore",
170
173
  detached: false
171
174
  });
@@ -232,12 +235,36 @@ function setupCleanupHandlers() {
232
235
  cleanup();
233
236
  });
234
237
  }
238
+ function caffeinateArgs(daemonPid) {
239
+ return ["-im", "-w", String(daemonPid)];
240
+ }
241
+ function orphanedLegacyCaffeinatePids(psOutput) {
242
+ const pids = [];
243
+ for (const line of psOutput.split("\n")) {
244
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*?)\s*$/.exec(line);
245
+ if (!m) continue;
246
+ const [, pid, ppid, command] = m;
247
+ if (ppid !== "1") continue;
248
+ if (!/^(?:\/usr\/bin\/)?caffeinate -im$/.test(command)) continue;
249
+ pids.push(Number(pid));
250
+ }
251
+ return pids;
252
+ }
235
253
  function killOrphanedCaffeinateProcesses() {
236
254
  if (process.platform !== "darwin") return;
255
+ let ps;
237
256
  try {
238
- execSync('pkill -f "caffeinate -im"', { timeout: 5e3, stdio: "ignore" });
239
- logger.debug("[caffeinate] Killed orphaned caffeinate processes");
240
- } catch {
257
+ ps = execSync("ps -A -o pid=,ppid=,command=", { timeout: 5e3, encoding: "utf8" });
258
+ } catch (error) {
259
+ logger.debug("[caffeinate] Could not list processes; skipping orphan cleanup:", error);
260
+ return;
261
+ }
262
+ for (const pid of orphanedLegacyCaffeinatePids(ps)) {
263
+ try {
264
+ process.kill(pid, "SIGTERM");
265
+ logger.debug(`[caffeinate] Killed orphaned legacy caffeinate PID ${pid}`);
266
+ } catch {
267
+ }
241
268
  }
242
269
  }
243
270
 
@@ -345,8 +372,28 @@ function formatAssistantReportMessage(title, sessionId, event) {
345
372
  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`;
346
373
  }
347
374
 
375
+ const CLAUDE_OUTBOUND_MODES = ["default", "acceptEdits", "plan", "bypassPermissions"];
376
+ function normalizeClaudeOutboundMode(value) {
377
+ if (value === null || value === void 0) return null;
378
+ if (value === "yolo") return "bypassPermissions";
379
+ return CLAUDE_OUTBOUND_MODES.includes(value) ? value : "default";
380
+ }
381
+ function publishedRelaunchPermissionMode(metadata) {
382
+ const published = typeof metadata?.permissionMode === "string" ? metadata.permissionMode : null;
383
+ if ((metadata?.flavor ?? "claude") === "claude") {
384
+ return normalizeClaudeOutboundMode(published) ?? void 0;
385
+ }
386
+ return published ?? void 0;
387
+ }
388
+
348
389
  function resumePrecheck(metadata, fs) {
349
390
  const flavor = metadata.flavor ?? "claude";
391
+ if (flavor === "acp" && metadata.piSessionId) {
392
+ if (!metadata.path || !fs.cwdExists(metadata.path)) {
393
+ return { ok: false, reason: "missing-cwd", detail: `working directory ${metadata.path ?? "(none)"} does not exist` };
394
+ }
395
+ return { ok: true };
396
+ }
350
397
  if (flavor !== "claude" && flavor !== "codex") {
351
398
  return { ok: false, reason: "unsupported-flavor", detail: `flavor "${flavor}" cannot be resumed` };
352
399
  }
@@ -365,6 +412,9 @@ function resumePrecheck(metadata, fs) {
365
412
  }
366
413
  return { ok: true };
367
414
  }
415
+ function resumeStartsFreshConversation(reason) {
416
+ return reason === "conversation-missing" || reason === "no-backend-id";
417
+ }
368
418
  function sanitizeResumeModel(value) {
369
419
  if (typeof value !== "string") return null;
370
420
  return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}(\[1m\])?$/i.test(value) ? value : null;
@@ -722,7 +772,7 @@ function startDaemonControlServer({
722
772
  return { success: false, error: "daemon is still starting up" };
723
773
  }
724
774
  logger.debug(`[CONTROL SERVER] Resume session request: ${sessionId} (model=${model ?? "unset"}, permissionMode=${permissionMode ?? "unset"})`);
725
- const result = await resumeSession(sessionId, { model, permissionMode });
775
+ const result = await resumeSession(sessionId, { model, permissionMode, keepPublishedPermissionMode: true });
726
776
  switch (result.type) {
727
777
  case "success":
728
778
  return { success: true, sessionId: result.sessionId };
@@ -2030,6 +2080,2402 @@ function spawnAgentUnavailableError(agent, availability) {
2030
2080
  return null;
2031
2081
  }
2032
2082
 
2083
+ const MAX_DIFF_LINES = 4e3;
2084
+ function splitLines(text) {
2085
+ if (text === "") return [];
2086
+ const lines = text.split("\n");
2087
+ if (lines[lines.length - 1] === "") lines.pop();
2088
+ return lines;
2089
+ }
2090
+ function diffOps(a, b) {
2091
+ if (a.length > MAX_DIFF_LINES || b.length > MAX_DIFF_LINES) {
2092
+ return [...a.map((text) => ({ kind: "-", text })), ...b.map((text) => ({ kind: "+", text }))];
2093
+ }
2094
+ const n = a.length;
2095
+ const m = b.length;
2096
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
2097
+ for (let i2 = n - 1; i2 >= 0; i2--) {
2098
+ for (let j2 = m - 1; j2 >= 0; j2--) {
2099
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
2100
+ }
2101
+ }
2102
+ const ops = [];
2103
+ let i = 0;
2104
+ let j = 0;
2105
+ while (i < n && j < m) {
2106
+ if (a[i] === b[j]) {
2107
+ ops.push({ kind: " ", text: a[i] });
2108
+ i++;
2109
+ j++;
2110
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
2111
+ ops.push({ kind: "-", text: a[i] });
2112
+ i++;
2113
+ } else {
2114
+ ops.push({ kind: "+", text: b[j] });
2115
+ j++;
2116
+ }
2117
+ }
2118
+ while (i < n) ops.push({ kind: "-", text: a[i++] });
2119
+ while (j < m) ops.push({ kind: "+", text: b[j++] });
2120
+ return ops;
2121
+ }
2122
+ function unifiedDiff(oldText, newText, label, context = 3) {
2123
+ if (oldText === newText) return "";
2124
+ const a = splitLines(oldText);
2125
+ const b = splitLines(newText);
2126
+ const ops = diffOps(a, b);
2127
+ const changed = ops.map((op) => op.kind !== " ");
2128
+ if (!changed.some(Boolean)) {
2129
+ return `--- ${label}
2130
+ +++ ${label}
2131
+ @@ trailing newline changed @@
2132
+ `;
2133
+ }
2134
+ const out = [`--- ${oldText === "" ? "/dev/null" : label}`, `+++ ${label}`];
2135
+ let k = 0;
2136
+ while (k < ops.length) {
2137
+ if (!changed[k]) {
2138
+ k++;
2139
+ continue;
2140
+ }
2141
+ let start = Math.max(0, k - context);
2142
+ let end = k;
2143
+ while (end < ops.length) {
2144
+ if (changed[end]) {
2145
+ end++;
2146
+ continue;
2147
+ }
2148
+ let next = end;
2149
+ while (next < ops.length && !changed[next]) next++;
2150
+ if (next < ops.length && next - end <= context * 2) {
2151
+ end = next;
2152
+ continue;
2153
+ }
2154
+ break;
2155
+ }
2156
+ const stop = Math.min(ops.length, end + context);
2157
+ let oldStart = 1;
2158
+ let newStart = 1;
2159
+ for (let p = 0; p < start; p++) {
2160
+ if (ops[p].kind !== "+") oldStart++;
2161
+ if (ops[p].kind !== "-") newStart++;
2162
+ }
2163
+ const slice = ops.slice(start, stop);
2164
+ const oldCount = slice.filter((op) => op.kind !== "+").length;
2165
+ const newCount = slice.filter((op) => op.kind !== "-").length;
2166
+ out.push(`@@ -${oldCount ? oldStart : oldStart - 1},${oldCount} +${newCount ? newStart : newStart - 1},${newCount} @@`);
2167
+ for (const op of slice) out.push(`${op.kind}${op.text}`);
2168
+ k = stop;
2169
+ start = stop;
2170
+ }
2171
+ return `${out.join("\n")}
2172
+ `;
2173
+ }
2174
+
2175
+ const SECRET_KEY_PATTERN = /(api[_-]?key|apikey|token|secret|password|passwd|authorization|bearer|credential|cookie|private[_-]?key)/i;
2176
+ const EXTRA_SECRET_KEYS = /* @__PURE__ */ new Set(["ANTHROPIC_CUSTOM_HEADERS"]);
2177
+ function isSecretKey(key) {
2178
+ return SECRET_KEY_PATTERN.test(key) || EXTRA_SECRET_KEYS.has(key);
2179
+ }
2180
+ function maskSecret(value) {
2181
+ const v = value.trim();
2182
+ if (!v) return "";
2183
+ if (v.length < 16) return "\u2022\u2022\u2022\u2022";
2184
+ return `${v.slice(0, 4)}\u2026${v.slice(-4)}`;
2185
+ }
2186
+ function collectSecretValues(value, out = /* @__PURE__ */ new Set(), parentKey = "") {
2187
+ if (typeof value === "string") {
2188
+ if (parentKey && isSecretKey(parentKey) && value.length >= 4) out.add(value);
2189
+ return out;
2190
+ }
2191
+ if (Array.isArray(value)) {
2192
+ for (const item of value) collectSecretValues(item, out, parentKey);
2193
+ return out;
2194
+ }
2195
+ if (value && typeof value === "object") {
2196
+ for (const [key, child] of Object.entries(value)) {
2197
+ collectSecretValues(child, out, key);
2198
+ }
2199
+ }
2200
+ return out;
2201
+ }
2202
+ function redactText(text, secrets) {
2203
+ const list = [...new Set(secrets)].filter((s) => s.length >= 4).sort((a, b) => b.length - a.length);
2204
+ let out = text;
2205
+ for (const secret of list) {
2206
+ out = out.split(secret).join(maskSecret(secret));
2207
+ }
2208
+ return out;
2209
+ }
2210
+ const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
2211
+ function isValidEnvName(name) {
2212
+ return typeof name === "string" && ENV_NAME_PATTERN.test(name);
2213
+ }
2214
+
2215
+ function parseJsonObject$1(text, label) {
2216
+ if (text.trim() === "") return {};
2217
+ let value;
2218
+ try {
2219
+ value = JSON.parse(text);
2220
+ } catch (error) {
2221
+ const hasComments = /^\s*\/\/|\/\*/m.test(text);
2222
+ throw new ModelConfigError(
2223
+ hasComments ? "json-has-comments" : "invalid-json",
2224
+ 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)}`
2225
+ );
2226
+ }
2227
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2228
+ throw new ModelConfigError("invalid-json", `${label} must contain a JSON object`);
2229
+ }
2230
+ return value;
2231
+ }
2232
+ function detectIndent(text) {
2233
+ const m = /^([ \t]+)"/m.exec(text);
2234
+ return m ? m[1] : 2;
2235
+ }
2236
+ function stringifyLike(original, value) {
2237
+ const compact = original.trim() !== "" && !original.trim().includes("\n");
2238
+ const body = compact ? JSON.stringify(value) : JSON.stringify(value, null, detectIndent(original));
2239
+ const eol = original.includes("\r\n") ? "\r\n" : "\n";
2240
+ const withEol = eol === "\r\n" ? body.replace(/\n/g, "\r\n") : body;
2241
+ return original === "" || /\r?\n$/.test(original) ? withEol + eol : withEol;
2242
+ }
2243
+ function setOrDelete(obj, key, value) {
2244
+ if (value === void 0 || value === null || value === "") delete obj[key];
2245
+ else obj[key] = value;
2246
+ }
2247
+ function childObject(obj, key, label) {
2248
+ const current = obj[key];
2249
+ if (current === void 0) {
2250
+ const created = {};
2251
+ obj[key] = created;
2252
+ return created;
2253
+ }
2254
+ if (!current || typeof current !== "object" || Array.isArray(current)) {
2255
+ throw new ModelConfigError("unexpected-shape", `${label}.${key} is not an object; refusing to overwrite it`);
2256
+ }
2257
+ return current;
2258
+ }
2259
+
2260
+ const MODEL_ID = /^[A-Za-z0-9._:/@+\-[\]]{1,200}$/;
2261
+ const PROVIDER_ID = /^[A-Za-z0-9_-]{1,64}$/;
2262
+ function fail(code, message) {
2263
+ throw new ModelConfigError(code, message);
2264
+ }
2265
+ function normalizeBaseUrl(value, field = "baseUrl") {
2266
+ if (value === void 0) return void 0;
2267
+ if (value === null) return null;
2268
+ if (typeof value !== "string") fail("invalid-input", `${field} must be a string`);
2269
+ const v = value.trim();
2270
+ if (v === "") return null;
2271
+ if (v.length > 2048 || /\s/.test(v)) fail("invalid-input", `${field} is not a valid URL`);
2272
+ let url;
2273
+ try {
2274
+ url = new URL(v);
2275
+ } catch {
2276
+ fail("invalid-input", `${field} is not a valid URL`);
2277
+ }
2278
+ if (url.protocol !== "http:" && url.protocol !== "https:") fail("invalid-input", `${field} must be http(s)`);
2279
+ if (url.username || url.password) fail("invalid-input", `${field} must not embed credentials; use the API key field`);
2280
+ return v;
2281
+ }
2282
+ function normalizeModelId(value, field = "model") {
2283
+ if (value === void 0) return void 0;
2284
+ if (value === null) return null;
2285
+ if (typeof value !== "string") fail("invalid-input", `${field} must be a string`);
2286
+ const v = value.trim();
2287
+ if (v === "") return null;
2288
+ if (!MODEL_ID.test(v)) fail("invalid-input", `${field} contains unsupported characters`);
2289
+ return v;
2290
+ }
2291
+ function normalizeModelList(value, field = "models") {
2292
+ if (value === void 0) return void 0;
2293
+ if (!Array.isArray(value)) fail("invalid-input", `${field} must be an array`);
2294
+ if (value.length > 64) fail("invalid-input", `${field} has too many entries`);
2295
+ const out = [];
2296
+ for (const item of value) {
2297
+ const id = normalizeModelId(item, field);
2298
+ if (id && !out.includes(id)) out.push(id);
2299
+ }
2300
+ return out;
2301
+ }
2302
+ function normalizeProviderId(value, reserved = []) {
2303
+ if (typeof value !== "string" || !PROVIDER_ID.test(value.trim())) fail("invalid-input", "providerId must be 1-64 letters, digits, - or _");
2304
+ const v = value.trim();
2305
+ if (reserved.includes(v)) fail("invalid-input", `providerId "${v}" is reserved by the harness`);
2306
+ return v;
2307
+ }
2308
+ function normalizeSecret(value, allowed = ["keep", "clear", "literal", "env"]) {
2309
+ if (value === void 0) return { mode: "keep" };
2310
+ if (!value || typeof value !== "object") fail("invalid-input", "apiKey must be an object");
2311
+ const v = value;
2312
+ const mode = v.mode;
2313
+ if (typeof mode !== "string" || !allowed.includes(mode)) fail("invalid-input", `apiKey.mode must be one of ${allowed.join(", ")}`);
2314
+ if (mode === "literal") {
2315
+ if (typeof v.value !== "string") fail("invalid-input", "apiKey.value must be a string");
2316
+ const key = v.value.trim();
2317
+ if (!key || key.length > 4096 || /[\s\u0000-\u001f\u007f]/.test(key)) fail("invalid-input", "apiKey.value must be a single line without spaces");
2318
+ return { mode: "literal", value: key };
2319
+ }
2320
+ if (mode === "env") {
2321
+ if (!isValidEnvName(v.name)) fail("invalid-input", "apiKey.name must be an environment variable name");
2322
+ return { mode: "env", name: v.name };
2323
+ }
2324
+ return { mode };
2325
+ }
2326
+ function baseUrlWarnings(url, kind) {
2327
+ if (!url) return [];
2328
+ const path = (() => {
2329
+ try {
2330
+ return new URL(url).pathname.replace(/\/+$/, "");
2331
+ } catch {
2332
+ return "";
2333
+ }
2334
+ })();
2335
+ const out = [];
2336
+ if (/\/(chat\/completions|responses|messages|completions)$/.test(path)) {
2337
+ out.push({ code: "base-url-has-endpoint", message: "The base URL ends with an API endpoint path; harnesses append that themselves." });
2338
+ }
2339
+ if (kind === "anthropic" && /\/v1$/.test(path)) {
2340
+ out.push({ code: "base-url-v1", message: "Claude Code appends /v1/messages; a base URL ending in /v1 usually produces /v1/v1/messages." });
2341
+ }
2342
+ if (kind === "openai" && !/\/v\d/.test(path)) {
2343
+ out.push({ code: "base-url-no-version", message: "OpenAI-compatible base URLs usually end in /v1." });
2344
+ }
2345
+ return out;
2346
+ }
2347
+
2348
+ function getPath$1(obj, path) {
2349
+ let cur = obj;
2350
+ for (const p of path) {
2351
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
2352
+ cur = cur[p];
2353
+ }
2354
+ return cur;
2355
+ }
2356
+ function changedPaths(before, after, paths) {
2357
+ return paths.filter((path) => JSON.stringify(getPath$1(before, path)) !== JSON.stringify(getPath$1(after, path))).map((path) => path.join("."));
2358
+ }
2359
+ function uniq(values) {
2360
+ const out = [];
2361
+ for (const v of values) if (v && !out.includes(v)) out.push(v);
2362
+ return out;
2363
+ }
2364
+
2365
+ const ROLE$1 = "settings";
2366
+ const AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN";
2367
+ const API_KEY$1 = "ANTHROPIC_API_KEY";
2368
+ const ALIAS_VARS = { opusModel: "ANTHROPIC_DEFAULT_OPUS_MODEL", sonnetModel: "ANTHROPIC_DEFAULT_SONNET_MODEL", haikuModel: "ANTHROPIC_DEFAULT_HAIKU_MODEL" };
2369
+ function claudeEnvHelper(name) {
2370
+ return `printf %s "$${name}"`;
2371
+ }
2372
+ const OUR_HELPER = /^printf %s "\$([A-Za-z_][A-Za-z0-9_]*)"$/;
2373
+ const OWNED_PATHS = [
2374
+ ["env", "ANTHROPIC_BASE_URL"],
2375
+ ["env", AUTH_TOKEN],
2376
+ ["env", API_KEY$1],
2377
+ ["env", ALIAS_VARS.opusModel],
2378
+ ["env", ALIAS_VARS.sonnetModel],
2379
+ ["env", ALIAS_VARS.haikuModel],
2380
+ ["model"],
2381
+ ["modelPicker", "options"],
2382
+ ["apiKeyHelper"],
2383
+ ["availableModels"]
2384
+ ];
2385
+ function claudeSettingsPath(ctx) {
2386
+ const dir = ctx.env.CLAUDE_CONFIG_DIR?.trim() || join(ctx.home, ".claude");
2387
+ return join(dir, "settings.json");
2388
+ }
2389
+ function str$4(v) {
2390
+ return typeof v === "string" && v.trim() ? v : null;
2391
+ }
2392
+ function envOf(settings) {
2393
+ const env = settings.env;
2394
+ return env && typeof env === "object" && !Array.isArray(env) ? env : {};
2395
+ }
2396
+ function pickerOptions(settings) {
2397
+ const picker = settings.modelPicker;
2398
+ if (!picker || typeof picker !== "object" || Array.isArray(picker)) return [];
2399
+ const options = picker.options;
2400
+ return Array.isArray(options) ? options.filter((o) => !!o && typeof o === "object" && typeof o.model === "string") : [];
2401
+ }
2402
+ function secretView$2(settings, ctx) {
2403
+ const env = envOf(settings);
2404
+ const literal = str$4(env[AUTH_TOKEN]) ?? str$4(env[API_KEY$1]);
2405
+ if (literal) return { mode: "literal", masked: maskSecret(literal) };
2406
+ const helper = str$4(settings.apiKeyHelper);
2407
+ if (helper) {
2408
+ const ours = OUR_HELPER.exec(helper.trim());
2409
+ if (ours) return { mode: "env", envName: ours[1], envPresent: !!ctx.env[ours[1]] };
2410
+ return { mode: "command" };
2411
+ }
2412
+ return { mode: "none" };
2413
+ }
2414
+ function currentOf$3(settings, ctx) {
2415
+ const env = envOf(settings);
2416
+ return {
2417
+ baseUrl: str$4(env.ANTHROPIC_BASE_URL),
2418
+ authHeader: !str$4(env[AUTH_TOKEN]) && str$4(env[API_KEY$1]) ? "x-api-key" : "bearer",
2419
+ apiKey: secretView$2(settings, ctx),
2420
+ model: str$4(settings.model),
2421
+ opusModel: str$4(env[ALIAS_VARS.opusModel]),
2422
+ sonnetModel: str$4(env[ALIAS_VARS.sonnetModel]),
2423
+ haikuModel: str$4(env[ALIAS_VARS.haikuModel]),
2424
+ pickerModels: pickerOptions(settings).map((o) => o.model)
2425
+ };
2426
+ }
2427
+ function pickerModelsOf$1(current) {
2428
+ return uniq([current.model, current.opusModel, current.sonnetModel, current.haikuModel, ...current.pickerModels ?? []]);
2429
+ }
2430
+ function warningsOf$3(settings, current, ctx) {
2431
+ const env = envOf(settings);
2432
+ const out = [...baseUrlWarnings(current.baseUrl, "anthropic")];
2433
+ if (str$4(env.ANTHROPIC_MODEL)) {
2434
+ out.push({ code: "env-model-overrides", message: "env.ANTHROPIC_MODEL is set in settings.json and overrides the default model." });
2435
+ }
2436
+ const daemonOther = current.authHeader === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2437
+ if (current.baseUrl && ctx.env[daemonOther]) {
2438
+ out.push({ code: "daemon-env-credential", message: `The daemon's environment also defines ${daemonOther}; sessions inherit it.` });
2439
+ }
2440
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
2441
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
2442
+ }
2443
+ if (Array.isArray(settings.availableModels)) {
2444
+ const allowed = settings.availableModels;
2445
+ const missing = pickerModelsOf$1(current).filter((id) => !allowed.includes(id));
2446
+ if (missing.length) out.push({ code: "available-models-filter", message: `availableModels does not list ${missing.join(", ")}; Claude Code hides them.` });
2447
+ }
2448
+ return out;
2449
+ }
2450
+ function parsePatch$1(raw) {
2451
+ const p = raw;
2452
+ if (p.authHeader !== void 0 && p.authHeader !== "bearer" && p.authHeader !== "x-api-key") fail("invalid-input", "authHeader must be bearer or x-api-key");
2453
+ return {
2454
+ harness: "claude",
2455
+ baseUrl: normalizeBaseUrl(p.baseUrl),
2456
+ authHeader: p.authHeader,
2457
+ apiKey: normalizeSecret(p.apiKey),
2458
+ model: normalizeModelId(p.model),
2459
+ opusModel: normalizeModelId(p.opusModel, "opusModel"),
2460
+ sonnetModel: normalizeModelId(p.sonnetModel, "sonnetModel"),
2461
+ haikuModel: normalizeModelId(p.haikuModel, "haikuModel"),
2462
+ pickerModels: normalizeModelList(p.pickerModels, "pickerModels")
2463
+ };
2464
+ }
2465
+ const claudeAdapter = {
2466
+ id: "claude",
2467
+ binary: "claude",
2468
+ files: (ctx) => [{ role: ROLE$1, path: claudeSettingsPath(ctx) }],
2469
+ view(files, ctx) {
2470
+ const settings = parseJsonObject$1(files[ROLE$1].content, "settings.json");
2471
+ const current = currentOf$3(settings, ctx);
2472
+ return { current, pickerModels: pickerModelsOf$1(current), warnings: warningsOf$3(settings, current, ctx) };
2473
+ },
2474
+ plan(files, raw, ctx) {
2475
+ const patch = parsePatch$1(raw);
2476
+ const original = files[ROLE$1].content;
2477
+ const before = parseJsonObject$1(original, "settings.json");
2478
+ const settings = structuredClone(before);
2479
+ const hadEnv = settings.env !== void 0;
2480
+ const env = childObject(settings, "env", "settings");
2481
+ if (patch.baseUrl !== void 0) setOrDelete(env, "ANTHROPIC_BASE_URL", patch.baseUrl);
2482
+ const currentHeader = !str$4(env[AUTH_TOKEN]) && str$4(env[API_KEY$1]) ? "x-api-key" : "bearer";
2483
+ const header = patch.authHeader ?? currentHeader;
2484
+ const target = header === "bearer" ? AUTH_TOKEN : API_KEY$1;
2485
+ const other = header === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2486
+ const helperIsOurs = typeof settings.apiKeyHelper === "string" && OUR_HELPER.test(settings.apiKeyHelper.trim());
2487
+ const secrets = [];
2488
+ switch (patch.apiKey.mode) {
2489
+ case "literal":
2490
+ env[target] = patch.apiKey.value;
2491
+ delete env[other];
2492
+ if (helperIsOurs) delete settings.apiKeyHelper;
2493
+ secrets.push(patch.apiKey.value);
2494
+ break;
2495
+ case "env":
2496
+ settings.apiKeyHelper = claudeEnvHelper(patch.apiKey.name);
2497
+ delete env[AUTH_TOKEN];
2498
+ delete env[API_KEY$1];
2499
+ break;
2500
+ case "clear":
2501
+ delete env[AUTH_TOKEN];
2502
+ delete env[API_KEY$1];
2503
+ if (helperIsOurs) delete settings.apiKeyHelper;
2504
+ break;
2505
+ case "keep":
2506
+ if (header !== currentHeader && str$4(env[other]) && !str$4(env[target])) {
2507
+ env[target] = env[other];
2508
+ delete env[other];
2509
+ }
2510
+ break;
2511
+ }
2512
+ if (patch.model !== void 0) setOrDelete(settings, "model", patch.model);
2513
+ for (const [field, variable] of Object.entries(ALIAS_VARS)) {
2514
+ if (patch[field] !== void 0) setOrDelete(env, variable, patch[field]);
2515
+ }
2516
+ if (patch.pickerModels !== void 0) {
2517
+ const hadPicker = settings.modelPicker !== void 0;
2518
+ const picker = childObject(settings, "modelPicker", "settings");
2519
+ const existing = pickerOptions(settings);
2520
+ const next = patch.pickerModels.map((id) => existing.find((o) => o.model === id) ?? { model: id });
2521
+ if (next.length) picker.options = next;
2522
+ else delete picker.options;
2523
+ if (!hadPicker && Object.keys(picker).length === 0) delete settings.modelPicker;
2524
+ }
2525
+ if (!hadEnv && Object.keys(env).length === 0) delete settings.env;
2526
+ const current = currentOf$3(settings, ctx);
2527
+ if (Array.isArray(settings.availableModels)) {
2528
+ const allowed = settings.availableModels;
2529
+ const add = pickerModelsOf$1(current).filter((id) => !allowed.includes(id));
2530
+ if (add.length) settings.availableModels = [...allowed, ...add];
2531
+ }
2532
+ const changedKeys = changedPaths(before, settings, OWNED_PATHS);
2533
+ const content = changedKeys.length === 0 ? void 0 : stringifyLike(original, settings);
2534
+ return { contents: { [ROLE$1]: content }, warnings: warningsOf$3(settings, current, ctx), changedKeys, secrets };
2535
+ },
2536
+ secretsIn(_role, content) {
2537
+ try {
2538
+ return collectSecretValues(parseJsonObject$1(content, "settings.json"));
2539
+ } catch {
2540
+ return /* @__PURE__ */ new Set();
2541
+ }
2542
+ }
2543
+ };
2544
+
2545
+ /*!
2546
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2547
+ * SPDX-License-Identifier: BSD-3-Clause
2548
+ *
2549
+ * Redistribution and use in source and binary forms, with or without
2550
+ * modification, are permitted provided that the following conditions are met:
2551
+ *
2552
+ * 1. Redistributions of source code must retain the above copyright notice, this
2553
+ * list of conditions and the following disclaimer.
2554
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2555
+ * this list of conditions and the following disclaimer in the
2556
+ * documentation and/or other materials provided with the distribution.
2557
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2558
+ * may be used to endorse or promote products derived from this software without
2559
+ * specific prior written permission.
2560
+ *
2561
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2562
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2563
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2564
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2565
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2566
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2567
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2568
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2569
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2570
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2571
+ */
2572
+ function getLineColFromPtr(string, ptr) {
2573
+ let lines = string.slice(0, ptr).split(/\r?\n/);
2574
+ return [lines.length, lines.pop().length + 1];
2575
+ }
2576
+ function makeCodeBlock(string, line, column) {
2577
+ let lines = string.split(/\r?\n/);
2578
+ let codeblock = "";
2579
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
2580
+ for (let i = line - 1; i <= line + 1; i++) {
2581
+ let l = lines[i - 1];
2582
+ if (!l)
2583
+ continue;
2584
+ codeblock += i.toString().padEnd(numberLen, " ");
2585
+ codeblock += ": ";
2586
+ codeblock += l;
2587
+ codeblock += "\n";
2588
+ if (i === line) {
2589
+ codeblock += " ".repeat(numberLen + column + 2);
2590
+ codeblock += "^\n";
2591
+ }
2592
+ }
2593
+ return codeblock;
2594
+ }
2595
+ class TomlError extends Error {
2596
+ line;
2597
+ column;
2598
+ codeblock;
2599
+ constructor(message, options) {
2600
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
2601
+ const codeblock = makeCodeBlock(options.toml, line, column);
2602
+ super(`Invalid TOML document: ${message}
2603
+
2604
+ ${codeblock}`, options);
2605
+ this.line = line;
2606
+ this.column = column;
2607
+ this.codeblock = codeblock;
2608
+ }
2609
+ /** @internal */
2610
+ static x(message, ctx, ptr) {
2611
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
2612
+ }
2613
+ }
2614
+
2615
+ function parseString(ctx) {
2616
+ let startPtr = ctx.p;
2617
+ let c = ctx.s.charCodeAt(ctx.p++);
2618
+ let first = c;
2619
+ let isLiteral = c === 39;
2620
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
2621
+ if (isMultiline) {
2622
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
2623
+ ctx.p++;
2624
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
2625
+ ctx.p += 2;
2626
+ }
2627
+ let parsed = "";
2628
+ let sliceStart = ctx.p;
2629
+ let state = 0;
2630
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2631
+ c = ctx.s.charCodeAt(ctx.p);
2632
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
2633
+ state = state && 3;
2634
+ } else if (c < 32 && c !== 9 || c === 127) {
2635
+ TomlError.x("control characters are not allowed in strings", ctx);
2636
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
2637
+ if (isMultiline) {
2638
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2639
+ ctx.p++;
2640
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2641
+ ctx.p++;
2642
+ }
2643
+ if (!state) {
2644
+ let s = ctx.s.slice(sliceStart, ctx.p);
2645
+ parsed = parsed ? parsed + s : s;
2646
+ }
2647
+ ctx.p += isMultiline ? 3 : 1;
2648
+ return parsed;
2649
+ } else if (!state) {
2650
+ if (!isLiteral && c === 92) {
2651
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
2652
+ state = 1;
2653
+ }
2654
+ } else if (state === 1) {
2655
+ if (c === 120 || c === 117 || c === 85) {
2656
+ let errPtr = ctx.p++ - 1;
2657
+ let value = 0;
2658
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
2659
+ for (let j = 0; j < len; j++, ctx.p++) {
2660
+ let hex = ctx.s.charCodeAt(ctx.p);
2661
+ let digit = (
2662
+ /* 0-9 */
2663
+ hex >= 48 && hex <= 57 ? hex - 48 : (
2664
+ /* A-F */
2665
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
2666
+ /* a-f */
2667
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
2668
+ )
2669
+ )
2670
+ );
2671
+ if (digit < 0)
2672
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
2673
+ value = value << 4 | digit;
2674
+ }
2675
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
2676
+ TomlError.x("invalid unicode escape", ctx, errPtr);
2677
+ }
2678
+ parsed += String.fromCodePoint(value);
2679
+ sliceStart = ctx.p--;
2680
+ state = 0;
2681
+ } else if (isMultiline && (c === 32 || c === 9)) {
2682
+ state = 2;
2683
+ } else {
2684
+ if (c === 98)
2685
+ parsed += "\b";
2686
+ else if (c === 116)
2687
+ parsed += " ";
2688
+ else if (c === 110)
2689
+ parsed += "\n";
2690
+ else if (c === 102)
2691
+ parsed += "\f";
2692
+ else if (c === 114)
2693
+ parsed += "\r";
2694
+ else if (c === 101)
2695
+ parsed += "\x1B";
2696
+ else if (c === 34)
2697
+ parsed += '"';
2698
+ else if (c === 92)
2699
+ parsed += "\\";
2700
+ else
2701
+ TomlError.x("unrecognised escape sequence", ctx);
2702
+ sliceStart = ctx.p + 1;
2703
+ state = 0;
2704
+ }
2705
+ } else if (c !== 32 && c !== 9) {
2706
+ if (state === 2)
2707
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
2708
+ state = !isLiteral && c === 92 ? 1 : 0;
2709
+ sliceStart = ctx.p;
2710
+ }
2711
+ }
2712
+ TomlError.x("unfinished string", ctx, startPtr);
2713
+ }
2714
+
2715
+ /*!
2716
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2717
+ * SPDX-License-Identifier: BSD-3-Clause
2718
+ *
2719
+ * Redistribution and use in source and binary forms, with or without
2720
+ * modification, are permitted provided that the following conditions are met:
2721
+ *
2722
+ * 1. Redistributions of source code must retain the above copyright notice, this
2723
+ * list of conditions and the following disclaimer.
2724
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2725
+ * this list of conditions and the following disclaimer in the
2726
+ * documentation and/or other materials provided with the distribution.
2727
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2728
+ * may be used to endorse or promote products derived from this software without
2729
+ * specific prior written permission.
2730
+ *
2731
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2732
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2733
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2734
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2735
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2736
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2737
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2738
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2739
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2740
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2741
+ */
2742
+ 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;
2743
+ class TomlDate extends Date {
2744
+ #hasDate = false;
2745
+ #hasTime = false;
2746
+ #offset = null;
2747
+ constructor(date, fasttype, unsafeDelim) {
2748
+ let hasDate = true;
2749
+ let hasTime = true;
2750
+ let offset = "Z";
2751
+ let c;
2752
+ if (typeof date === "string") {
2753
+ if (fasttype)
2754
+ prep: {
2755
+ if (fasttype < 3) {
2756
+ if (+date.slice(11, 13) > 23) {
2757
+ date = "";
2758
+ break prep;
2759
+ }
2760
+ if (fasttype === 2) {
2761
+ offset = null;
2762
+ date += "Z";
2763
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
2764
+ offset = date.slice(date.length - 6);
2765
+ }
2766
+ if (unsafeDelim)
2767
+ date = date.slice(0, 10) + "T" + date.slice(11);
2768
+ } else if (fasttype === 4) {
2769
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
2770
+ }
2771
+ hasDate = fasttype !== 4;
2772
+ hasTime = fasttype !== 3;
2773
+ }
2774
+ else {
2775
+ let match = date.match(DATE_TIME_RE);
2776
+ if (match) {
2777
+ if (!match[1]) {
2778
+ hasDate = false;
2779
+ date = `0000-01-01T${date}`;
2780
+ }
2781
+ hasTime = !!match[2];
2782
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
2783
+ if (match[2] && +match[2] > 23) {
2784
+ date = "";
2785
+ } else {
2786
+ offset = match[3] || null;
2787
+ if (!offset && hasTime)
2788
+ date += "Z";
2789
+ }
2790
+ } else {
2791
+ date = "";
2792
+ }
2793
+ }
2794
+ }
2795
+ super(date);
2796
+ if (!isNaN(this.getTime())) {
2797
+ this.#hasDate = hasDate;
2798
+ this.#hasTime = hasTime;
2799
+ this.#offset = offset;
2800
+ }
2801
+ }
2802
+ isDateTime() {
2803
+ return this.#hasDate && this.#hasTime;
2804
+ }
2805
+ isLocal() {
2806
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
2807
+ }
2808
+ isDate() {
2809
+ return this.#hasDate && !this.#hasTime;
2810
+ }
2811
+ isTime() {
2812
+ return this.#hasTime && !this.#hasDate;
2813
+ }
2814
+ isValid() {
2815
+ return this.#hasDate || this.#hasTime;
2816
+ }
2817
+ toISOString() {
2818
+ let iso = super.toISOString();
2819
+ if (this.isDate())
2820
+ return iso.slice(0, 10);
2821
+ if (this.isTime())
2822
+ return iso.slice(11, 23);
2823
+ if (this.#offset === null)
2824
+ return iso.slice(0, -1);
2825
+ if (this.#offset === "Z" || this.#offset === "z")
2826
+ return iso;
2827
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
2828
+ offset = this.#offset[0] === "-" ? offset : -offset;
2829
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
2830
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
2831
+ }
2832
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
2833
+ let date = new TomlDate(jsDate);
2834
+ date.#offset = offset;
2835
+ return date;
2836
+ }
2837
+ static wrapAsLocalDateTime(jsDate) {
2838
+ let date = new TomlDate(jsDate);
2839
+ date.#offset = null;
2840
+ return date;
2841
+ }
2842
+ static wrapAsLocalDate(jsDate) {
2843
+ let date = new TomlDate(jsDate);
2844
+ date.#hasTime = false;
2845
+ date.#offset = null;
2846
+ return date;
2847
+ }
2848
+ static wrapAsLocalTime(jsDate) {
2849
+ let date = new TomlDate(jsDate);
2850
+ date.#hasDate = false;
2851
+ date.#offset = null;
2852
+ return date;
2853
+ }
2854
+ }
2855
+
2856
+ function isDigit(char, base = 10) {
2857
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
2858
+ }
2859
+ function isEndOfValue(char, delim) {
2860
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
2861
+ delim && (char === delim || char === 44) || // Comment
2862
+ char === 35;
2863
+ }
2864
+ function extractValue(ctx, end) {
2865
+ let errPtr = ctx.p;
2866
+ let c = ctx.s.charCodeAt(ctx.p);
2867
+ if (c === 91 || c === 123) {
2868
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
2869
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
2870
+ ctx.d++;
2871
+ return value;
2872
+ }
2873
+ if (c === 34 || c === 39) {
2874
+ return parseString(ctx);
2875
+ }
2876
+ if (c === 116) {
2877
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
2878
+ TomlError.x("invalid value", ctx, errPtr);
2879
+ return ctx.p++, true;
2880
+ }
2881
+ if (c === 102) {
2882
+ 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)
2883
+ TomlError.x("invalid value", ctx, errPtr);
2884
+ return ctx.p++, false;
2885
+ }
2886
+ if (c === 43 || c === 45) {
2887
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
2888
+ }
2889
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
2890
+ return parseDate(ctx, c, end);
2891
+ }
2892
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
2893
+ return parseTime(ctx, c, end);
2894
+ }
2895
+ return parseNumber(ctx, ctx.p, c, 0, end);
2896
+ }
2897
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
2898
+ let c = startChr;
2899
+ let state = 0;
2900
+ let hasUnderscores = false;
2901
+ if (c === 105) {
2902
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
2903
+ TomlError.x("invalid value", ctx, startPtr);
2904
+ return ctx.p++, (sign || 1) / 0;
2905
+ }
2906
+ if (c === 110) {
2907
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
2908
+ TomlError.x("invalid value", ctx, startPtr);
2909
+ return ctx.p++, NaN;
2910
+ }
2911
+ if (c === 48) {
2912
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
2913
+ return ctx.bi === true ? 0n : 0;
2914
+ if (!sign) {
2915
+ if (c === 120)
2916
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
2917
+ else if (c === 98)
2918
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
2919
+ else if (c === 111)
2920
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
2921
+ }
2922
+ if (c === 46)
2923
+ state = 2;
2924
+ else if (c === 101 || c === 69)
2925
+ state = 4;
2926
+ else
2927
+ TomlError.x("illegal leading zero", ctx, startPtr);
2928
+ } else if (!isDigit(c))
2929
+ TomlError.x("invalid value", ctx, startPtr);
2930
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2931
+ if (!state)
2932
+ state = 1;
2933
+ if (c === 95) {
2934
+ if (!(state & 1))
2935
+ TomlError.x("illegal underscore", ctx);
2936
+ state += 11;
2937
+ hasUnderscores = true;
2938
+ } else if (state === 1 && c === 46)
2939
+ state = 2;
2940
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
2941
+ state = 4;
2942
+ else if (state === 4 && (c === 43 || c === 45)) ; else if (!isDigit(c))
2943
+ TomlError.x(`illegal character in numeric literal`, ctx);
2944
+ else if (state > 9)
2945
+ state -= 11;
2946
+ else if (!(state & 1))
2947
+ state++;
2948
+ }
2949
+ if (!state) {
2950
+ let val = (startChr - 48) * (sign || 1);
2951
+ return ctx.bi === true ? BigInt(val) : val;
2952
+ }
2953
+ if (!(state & 1))
2954
+ TomlError.x("unfinished numeric value", ctx, startPtr);
2955
+ let str = ctx.s.slice(startPtr, ctx.p);
2956
+ if (hasUnderscores)
2957
+ str = str.replaceAll("_", "");
2958
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
2959
+ }
2960
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
2961
+ let c, underscore = 1;
2962
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2963
+ if (c === 95) {
2964
+ if (underscore & 1)
2965
+ TomlError.x("illegal underscore", ctx);
2966
+ underscore = 3;
2967
+ } else if (!isDigit(c, base))
2968
+ TomlError.x(`illegal character in numeric literal`, ctx);
2969
+ else if (underscore & 1)
2970
+ underscore--;
2971
+ }
2972
+ if (underscore & 1)
2973
+ TomlError.x("unfinished numeric value", ctx);
2974
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
2975
+ if (underscore)
2976
+ str = str.replaceAll("_", "");
2977
+ return parseInteger(ctx, str, base, startPtr);
2978
+ }
2979
+ function parseInteger(ctx, str, base, startPtr) {
2980
+ if (ctx.bi !== true)
2981
+ int: {
2982
+ let val = parseInt(str, base);
2983
+ if (!Number.isSafeInteger(val)) {
2984
+ if (ctx.bi)
2985
+ break int;
2986
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
2987
+ }
2988
+ return val;
2989
+ }
2990
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
2991
+ }
2992
+ function parseDate(ctx, c, endChr) {
2993
+ let startPtr = ctx.p++, unsafeSeparator;
2994
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
2995
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
2996
+ }
2997
+ ctx.p += 5;
2998
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
2999
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
3000
+ 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) {
3001
+ let t2 = ctx.s.slice(startPtr, ctx.p);
3002
+ return readDate(ctx, t2, 3, false, startPtr);
3003
+ }
3004
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
3005
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
3006
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
3007
+ ctx.p += 3;
3008
+ if (ctx.s.charCodeAt(ctx.p) === 46)
3009
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
3010
+ ;
3011
+ if (c = ctx.s.charCodeAt(ctx.p)) {
3012
+ if (c === 90 || c === 122) {
3013
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
3014
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
3015
+ }
3016
+ if (c === 43 || c === 45) {
3017
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
3018
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
3019
+ }
3020
+ }
3021
+ let t = ctx.s.slice(startPtr, ctx.p);
3022
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
3023
+ }
3024
+ function parseTime(ctx, c, endChr) {
3025
+ let start = ctx.p;
3026
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
3027
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
3028
+ }
3029
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
3030
+ ctx.p += 3;
3031
+ if (ctx.s.charCodeAt(ctx.p) === 46)
3032
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
3033
+ ;
3034
+ let t = ctx.s.slice(start, ctx.p);
3035
+ return readDate(ctx, t, 4, false, start);
3036
+ }
3037
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
3038
+ if (ctx.ld) {
3039
+ let date = new TomlDate(str, type, unsafeDelim);
3040
+ if (!date.isValid())
3041
+ TomlError.x("invalid date", ctx, errPtr);
3042
+ return date;
3043
+ }
3044
+ try {
3045
+ if (temporalSuffix)
3046
+ str += temporalSuffix;
3047
+ switch (type) {
3048
+ case 1:
3049
+ return Temporal.ZonedDateTime.from(str);
3050
+ case 2:
3051
+ return Temporal.PlainDateTime.from(str);
3052
+ case 3:
3053
+ return Temporal.PlainDate.from(str);
3054
+ case 4:
3055
+ return Temporal.PlainTime.from(str);
3056
+ }
3057
+ } catch (e) {
3058
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
3059
+ }
3060
+ }
3061
+
3062
+ function skipComment(ctx) {
3063
+ for (; ctx.p < ctx.s.length; ctx.p++) {
3064
+ let c = ctx.s.charCodeAt(ctx.p);
3065
+ if (c === 10)
3066
+ break;
3067
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
3068
+ ctx.p++;
3069
+ break;
3070
+ }
3071
+ if (c < 32 && c !== 9 || c === 127) {
3072
+ TomlError.x("control characters are not allowed in comments", ctx);
3073
+ }
3074
+ }
3075
+ }
3076
+ function skipVoid(ctx, banNewLines, banComments) {
3077
+ let c;
3078
+ while (ctx.p < ctx.s.length) {
3079
+ 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)))
3080
+ ctx.p++;
3081
+ if (banComments || c !== 35)
3082
+ break;
3083
+ skipComment(ctx);
3084
+ }
3085
+ }
3086
+
3087
+ function parseKey(ctx, end = 61) {
3088
+ let startPtr;
3089
+ let state = 0;
3090
+ let parsed = [];
3091
+ let sliceStart;
3092
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
3093
+ do {
3094
+ if (c === end) {
3095
+ if (!state)
3096
+ TomlError.x("unexpected end of key", ctx);
3097
+ if (state === 1)
3098
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3099
+ return ctx.p++, parsed;
3100
+ } else if (c === 46) {
3101
+ if (!state)
3102
+ TomlError.x("illegal empty bare key", ctx);
3103
+ if (state === 1)
3104
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3105
+ state = 0;
3106
+ } else if (!state && (c === 34 || c === 39)) {
3107
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
3108
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
3109
+ parsed.push(parseString(ctx));
3110
+ state = 2;
3111
+ ctx.p--;
3112
+ } else if (c === 32 || c === 9) {
3113
+ if (state === 1) {
3114
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3115
+ state = 2;
3116
+ }
3117
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
3118
+ TomlError.x("illegal character in key", ctx);
3119
+ } else if (!state) {
3120
+ state = 1;
3121
+ sliceStart = ctx.p;
3122
+ }
3123
+ } while (c = ctx.s.charCodeAt(++ctx.p));
3124
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
3125
+ }
3126
+ function parseInlineTable(ctx) {
3127
+ let startPtr = ctx.p++;
3128
+ let res = /* @__PURE__ */ Object.create(null);
3129
+ let seen = /* @__PURE__ */ new Set();
3130
+ let c;
3131
+ while (ctx.p < ctx.s.length) {
3132
+ skipVoid(ctx);
3133
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
3134
+ ctx.p++;
3135
+ return res;
3136
+ }
3137
+ let k;
3138
+ let t = res;
3139
+ let hasOwn = false;
3140
+ let errPtr = ctx.p;
3141
+ let key = parseKey(ctx);
3142
+ for (let i = 0; i < key.length; i++) {
3143
+ if (i)
3144
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3145
+ k = key[i];
3146
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
3147
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3148
+ }
3149
+ let unsafe = k === "__proto__";
3150
+ if (ctx.uk && (unsafe || k === "constructor")) {
3151
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
3152
+ break;
3153
+ }
3154
+ if (!hasOwn && unsafe) {
3155
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3156
+ }
3157
+ }
3158
+ if (hasOwn) {
3159
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3160
+ }
3161
+ skipVoid(ctx, true, true);
3162
+ let value = extractValue(
3163
+ ctx,
3164
+ 125
3165
+ /* } */
3166
+ );
3167
+ if (t && typeof (t[k] = value) === "object")
3168
+ seen.add(value);
3169
+ skipVoid(ctx);
3170
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
3171
+ return res;
3172
+ }
3173
+ if (c !== 44)
3174
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3175
+ }
3176
+ TomlError.x("unfinished table", ctx, startPtr);
3177
+ }
3178
+ function parseArray(ctx) {
3179
+ let startPtr = ctx.p++;
3180
+ let res = [];
3181
+ let c;
3182
+ while (ctx.p < ctx.s.length) {
3183
+ skipVoid(ctx);
3184
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
3185
+ ctx.p++;
3186
+ return res;
3187
+ }
3188
+ res.push(extractValue(
3189
+ ctx,
3190
+ 93
3191
+ /* ] */
3192
+ ));
3193
+ skipVoid(ctx);
3194
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
3195
+ return res;
3196
+ }
3197
+ if (c !== 44)
3198
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3199
+ }
3200
+ TomlError.x("unfinished array", ctx, startPtr);
3201
+ }
3202
+
3203
+ function peekTable(ctx, key, table, meta, type) {
3204
+ let t = table;
3205
+ let m = meta;
3206
+ let k;
3207
+ let hasOwn = false;
3208
+ let state;
3209
+ for (let i = 0; i < key.length; i++) {
3210
+ if (i) {
3211
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3212
+ m = (state = m[k]).c;
3213
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
3214
+ return null;
3215
+ }
3216
+ if (state.t === 2) {
3217
+ let l = t.length - 1;
3218
+ t = t[l];
3219
+ m = m[l].c;
3220
+ }
3221
+ }
3222
+ k = key[i];
3223
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
3224
+ return null;
3225
+ }
3226
+ if (!hasOwn) {
3227
+ let unsafe = k === "__proto__";
3228
+ if (ctx.uk && (unsafe || k === "constructor"))
3229
+ return false;
3230
+ if (unsafe) {
3231
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3232
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
3233
+ }
3234
+ m[k] = {
3235
+ t: i < key.length - 1 && type === 2 ? 3 : type,
3236
+ d: false,
3237
+ i: 0,
3238
+ c: /* @__PURE__ */ Object.create(null)
3239
+ };
3240
+ }
3241
+ }
3242
+ state = m[k];
3243
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
3244
+ return null;
3245
+ }
3246
+ if (type === 2) {
3247
+ if (!state.d) {
3248
+ state.d = true;
3249
+ t[k] = [];
3250
+ }
3251
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
3252
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
3253
+ }
3254
+ if (state.d) {
3255
+ return null;
3256
+ }
3257
+ state.d = true;
3258
+ if (type === 1) {
3259
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3260
+ } else if (type === 0 && hasOwn) {
3261
+ return null;
3262
+ }
3263
+ return [k, t, state.c];
3264
+ }
3265
+ function validateTablePeek(ctx, peek, ptr) {
3266
+ if (peek === null || ctx.uk === 2)
3267
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
3268
+ }
3269
+ function parse(toml, options = {}) {
3270
+ let ctx = {
3271
+ s: toml,
3272
+ p: 0,
3273
+ d: options.maxDepth ?? 1e3,
3274
+ bi: options.integersAsBigInt ?? false,
3275
+ ld: options.useLegacyDate ?? true,
3276
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
3277
+ };
3278
+ let res = /* @__PURE__ */ Object.create(null);
3279
+ let meta = /* @__PURE__ */ Object.create(null);
3280
+ let tmp;
3281
+ let skipping = false;
3282
+ let tbl = res;
3283
+ let m = meta;
3284
+ if (toml.charCodeAt(0) === 65279)
3285
+ ctx.p++;
3286
+ skipVoid(ctx);
3287
+ while (ctx.p < toml.length) {
3288
+ if (toml.charCodeAt(ctx.p) === 91) {
3289
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
3290
+ tmp = ctx.p += +isTableArray;
3291
+ skipping = false;
3292
+ let k = parseKey(
3293
+ ctx,
3294
+ 93
3295
+ /* ] */
3296
+ );
3297
+ if (isTableArray) {
3298
+ if (toml.charCodeAt(ctx.p) !== 93) {
3299
+ TomlError.x("expected end of table array declaration", ctx);
3300
+ }
3301
+ ctx.p++;
3302
+ }
3303
+ let p = peekTable(
3304
+ ctx,
3305
+ k,
3306
+ res,
3307
+ meta,
3308
+ isTableArray ? 2 : 1
3309
+ /* Type.EXPLICIT */
3310
+ );
3311
+ if (!p) {
3312
+ validateTablePeek(ctx, p, tmp);
3313
+ skipping = true;
3314
+ } else {
3315
+ m = p[2];
3316
+ tbl = p[1];
3317
+ }
3318
+ } else {
3319
+ tmp = ctx.p;
3320
+ let k = parseKey(ctx);
3321
+ let p = peekTable(
3322
+ ctx,
3323
+ k,
3324
+ tbl,
3325
+ m,
3326
+ 0
3327
+ /* Type.DOTTED */
3328
+ );
3329
+ if (!p && !skipping)
3330
+ validateTablePeek(ctx, p, tmp);
3331
+ skipVoid(ctx, true, true);
3332
+ let v = extractValue(ctx, void 0);
3333
+ if (p && !skipping)
3334
+ p[1][p[0]] = v;
3335
+ }
3336
+ skipVoid(ctx, true);
3337
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
3338
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
3339
+ }
3340
+ skipVoid(ctx);
3341
+ }
3342
+ return res;
3343
+ }
3344
+
3345
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
3346
+ function formatTomlKey(key) {
3347
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
3348
+ }
3349
+ function formatTomlValue(value) {
3350
+ if (typeof value === "boolean") return value ? "true" : "false";
3351
+ return JSON.stringify(value).replace(/\u007f/g, "\\u007F");
3352
+ }
3353
+ function splitDottedKey(raw) {
3354
+ const parts = [];
3355
+ let i = 0;
3356
+ const s = raw.trim();
3357
+ while (i < s.length) {
3358
+ while (s[i] === " " || s[i] === " ") i++;
3359
+ let part = "";
3360
+ if (s[i] === '"') {
3361
+ let j = i + 1;
3362
+ while (j < s.length && s[j] !== '"') {
3363
+ if (s[j] === "\\") j++;
3364
+ j++;
3365
+ }
3366
+ if (j >= s.length) return null;
3367
+ try {
3368
+ part = JSON.parse(s.slice(i, j + 1));
3369
+ } catch {
3370
+ return null;
3371
+ }
3372
+ i = j + 1;
3373
+ } else if (s[i] === "'") {
3374
+ const j = s.indexOf("'", i + 1);
3375
+ if (j < 0) return null;
3376
+ part = s.slice(i + 1, j);
3377
+ i = j + 1;
3378
+ } else {
3379
+ let j = i;
3380
+ while (j < s.length && /[A-Za-z0-9_-]/.test(s[j])) j++;
3381
+ if (j === i) return null;
3382
+ part = s.slice(i, j);
3383
+ i = j;
3384
+ }
3385
+ parts.push(part);
3386
+ while (s[i] === " " || s[i] === " ") i++;
3387
+ if (i >= s.length) break;
3388
+ if (s[i] !== ".") return null;
3389
+ i++;
3390
+ }
3391
+ return parts.length ? parts : null;
3392
+ }
3393
+ function scan(lines) {
3394
+ const sections = [{ path: null, arrayTable: false, headerLine: -1, start: 0, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: -1 }];
3395
+ let inMulti = null;
3396
+ let depth = 0;
3397
+ for (let n = 0; n < lines.length; n++) {
3398
+ const line = lines[n];
3399
+ const current = sections[sections.length - 1];
3400
+ if (inMulti) {
3401
+ if (line.includes(inMulti)) {
3402
+ inMulti = null;
3403
+ current.lastKeyLine = n;
3404
+ }
3405
+ continue;
3406
+ }
3407
+ const trimmed = line.trim();
3408
+ if (depth === 0) {
3409
+ const header = /^\[(\[)?\s*([^\[\]]+?)\s*\](\])?\s*(#.*)?$/.exec(trimmed);
3410
+ if (header) {
3411
+ current.end = n;
3412
+ const path = splitDottedKey(header[2]);
3413
+ sections.push({ path: path ?? [`\0invalid:${header[2]}`], arrayTable: !!header[1], headerLine: n, start: n + 1, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: n });
3414
+ continue;
3415
+ }
3416
+ const kv = /^((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s"'-])+?)\s*=/.exec(trimmed);
3417
+ if (kv) {
3418
+ const keyPath = splitDottedKey(kv[1]);
3419
+ if (keyPath) current.keys.set(keyPath.join("\0"), n);
3420
+ current.lastKeyLine = n;
3421
+ }
3422
+ } else if (trimmed) {
3423
+ current.lastKeyLine = n;
3424
+ }
3425
+ let i = 0;
3426
+ while (i < line.length) {
3427
+ const ch = line[i];
3428
+ if (ch === "#") break;
3429
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
3430
+ const fence = line.slice(i, i + 3);
3431
+ const close = line.indexOf(fence, i + 3);
3432
+ if (close < 0) {
3433
+ inMulti = fence;
3434
+ break;
3435
+ }
3436
+ i = close + 3;
3437
+ continue;
3438
+ }
3439
+ if (ch === '"') {
3440
+ i++;
3441
+ while (i < line.length && line[i] !== '"') {
3442
+ if (line[i] === "\\") i++;
3443
+ i++;
3444
+ }
3445
+ i++;
3446
+ continue;
3447
+ }
3448
+ if (ch === "'") {
3449
+ const close = line.indexOf("'", i + 1);
3450
+ i = close < 0 ? line.length : close + 1;
3451
+ continue;
3452
+ }
3453
+ if (ch === "[" || ch === "{") depth++;
3454
+ if (ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
3455
+ i++;
3456
+ }
3457
+ }
3458
+ return sections;
3459
+ }
3460
+ function trailingComment(line) {
3461
+ const m = /^\s*[^=]+=\s*("(?:[^"\\]|\\.)*"|'[^']*'|true|false|[0-9][0-9_.eE+-]*)(\s+#.*)$/.exec(line);
3462
+ return m ? m[2] : "";
3463
+ }
3464
+ const samePath = (a, b) => a !== null && a.length === b.length && a.every((p, i) => p === b[i]);
3465
+ const isUnder = (a, prefix) => a !== null && a.length >= prefix.length && prefix.every((p, i) => p === a[i]);
3466
+ function applyOne(text, edit) {
3467
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3468
+ const lines = text.split(/\r?\n/);
3469
+ const sections = scan(lines);
3470
+ if ("removeTable" in edit) {
3471
+ const doomed = sections.filter((s) => !s.arrayTable && isUnder(s.path, edit.table)).sort((a, b) => b.headerLine - a.headerLine);
3472
+ for (const s of doomed) {
3473
+ let end = s.end;
3474
+ while (end > s.start && lines[end - 1]?.trim() === "" && end - 1 > s.lastKeyLine) end--;
3475
+ lines.splice(s.headerLine, end - s.headerLine);
3476
+ }
3477
+ return lines.join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`).replace(/(\r?\n)+$/, eol);
3478
+ }
3479
+ const root = edit.table.length === 0;
3480
+ const section = root ? sections[0] : sections.find((s) => !s.arrayTable && samePath(s.path, edit.table));
3481
+ const keyId = edit.key;
3482
+ const rendered = edit.value === null ? null : `${formatTomlKey(edit.key)} = ${formatTomlValue(edit.value)}`;
3483
+ if (section) {
3484
+ const at = section.keys.get(keyId);
3485
+ if (at !== void 0) {
3486
+ const indent = /^\s*/.exec(lines[at])?.[0] ?? "";
3487
+ if (rendered === null) lines.splice(at, 1);
3488
+ else lines[at] = indent + rendered + trailingComment(lines[at]);
3489
+ return lines.join(eol);
3490
+ }
3491
+ if (rendered === null) return text;
3492
+ if (root) {
3493
+ const anchor = section.lastKeyLine;
3494
+ lines.splice(anchor + 1, 0, rendered);
3495
+ } else {
3496
+ lines.splice(section.lastKeyLine + 1, 0, rendered);
3497
+ }
3498
+ return lines.join(eol);
3499
+ }
3500
+ if (rendered === null) return text;
3501
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
3502
+ const header = `[${edit.table.map(formatTomlKey).join(".")}]`;
3503
+ if (lines.length) lines.push("");
3504
+ lines.push(header, rendered, "");
3505
+ return lines.join(eol);
3506
+ }
3507
+ function parseToml(text) {
3508
+ try {
3509
+ return parse(text);
3510
+ } catch (error) {
3511
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
3512
+ throw new ModelConfigError("invalid-toml", `Not valid TOML: ${message}`);
3513
+ }
3514
+ }
3515
+ function getPath(obj, path) {
3516
+ let cur = obj;
3517
+ for (const p of path) {
3518
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
3519
+ cur = cur[p];
3520
+ }
3521
+ return cur;
3522
+ }
3523
+ function withoutPaths(obj, paths) {
3524
+ const clone = structuredClone(obj);
3525
+ for (const path of paths) {
3526
+ let cur = clone;
3527
+ for (const p of path.slice(0, -1)) {
3528
+ if (!cur || typeof cur !== "object") {
3529
+ cur = null;
3530
+ break;
3531
+ }
3532
+ cur = cur[p];
3533
+ }
3534
+ if (cur && typeof cur === "object") delete cur[path[path.length - 1]];
3535
+ }
3536
+ return clone;
3537
+ }
3538
+ function pruneEmpty(value) {
3539
+ if (!value || typeof value !== "object" || Array.isArray(value) || value instanceof Date) return value;
3540
+ const out = {};
3541
+ for (const [k, v] of Object.entries(value)) {
3542
+ const pruned = pruneEmpty(v);
3543
+ if (pruned && typeof pruned === "object" && !Array.isArray(pruned) && !(pruned instanceof Date) && Object.keys(pruned).length === 0) continue;
3544
+ out[k] = pruned;
3545
+ }
3546
+ return out;
3547
+ }
3548
+ function stableStringify(value) {
3549
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
3550
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
3551
+ if (value && typeof value === "object") {
3552
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
3553
+ }
3554
+ return JSON.stringify(value) ?? "null";
3555
+ }
3556
+ function verifyTomlEdit(oldText, newText, edits) {
3557
+ const before = parseToml(oldText);
3558
+ let after;
3559
+ try {
3560
+ after = parse(newText);
3561
+ } catch (error) {
3562
+ throw new 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`);
3563
+ }
3564
+ const owned = edits.map((e) => "removeTable" in e ? e.table : [...e.table, e.key]);
3565
+ for (const edit of edits) {
3566
+ if ("removeTable" in edit) {
3567
+ if (getPath(after, edit.table) !== void 0) throw new ModelConfigError("unsafe-edit", `Table ${edit.table.join(".")} is still present after removal`);
3568
+ continue;
3569
+ }
3570
+ const got = getPath(after, [...edit.table, edit.key]);
3571
+ const want = edit.value === null ? void 0 : edit.value;
3572
+ if (got !== want) throw new ModelConfigError("unsafe-edit", `Key ${[...edit.table, edit.key].join(".")} did not take the requested value`);
3573
+ }
3574
+ if (stableStringify(pruneEmpty(withoutPaths(before, owned))) !== stableStringify(pruneEmpty(withoutPaths(after, owned)))) {
3575
+ throw new ModelConfigError("unsafe-edit", "Edit would change settings outside the keys Very Happy manages");
3576
+ }
3577
+ }
3578
+ function editToml(text, edits) {
3579
+ parseToml(text);
3580
+ let out = text;
3581
+ const ordered = [...edits.filter((e) => e.table.length === 0), ...edits.filter((e) => e.table.length > 0)];
3582
+ for (const edit of ordered) out = applyOne(out, edit);
3583
+ if (out !== text && !out.endsWith("\n")) out += text.includes("\r\n") ? "\r\n" : "\n";
3584
+ verifyTomlEdit(text, out, edits);
3585
+ return out;
3586
+ }
3587
+
3588
+ const ROLE = "config";
3589
+ const CODEX_RESERVED_PROVIDERS = ["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "oss"];
3590
+ function codexConfigPath(ctx) {
3591
+ const dir = ctx.env.CODEX_HOME?.trim() || join(ctx.home, ".codex");
3592
+ return join(dir, "config.toml");
3593
+ }
3594
+ const str$3 = (v) => typeof v === "string" && v.trim() ? v : null;
3595
+ function providersOf$1(doc) {
3596
+ const table = doc.model_providers;
3597
+ if (!table || typeof table !== "object" || Array.isArray(table)) return {};
3598
+ return Object.fromEntries(Object.entries(table).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
3599
+ }
3600
+ function secretView$1(provider, ctx) {
3601
+ if (!provider) return { mode: "none" };
3602
+ const token = str$3(provider.experimental_bearer_token);
3603
+ if (token) return { mode: "literal", masked: maskSecret(token) };
3604
+ const envKey = str$3(provider.env_key);
3605
+ if (envKey) return { mode: "env", envName: envKey, envPresent: !!ctx.env[envKey] };
3606
+ if (provider.auth && typeof provider.auth === "object") return { mode: "command" };
3607
+ return { mode: "none" };
3608
+ }
3609
+ function selectProvider(doc, requested) {
3610
+ const providers = providersOf$1(doc);
3611
+ if (requested) return requested;
3612
+ const active = str$3(doc.model_provider);
3613
+ if (active && providers[active]) return active;
3614
+ return Object.keys(providers)[0] ?? null;
3615
+ }
3616
+ function currentOf$2(doc, providerId, ctx) {
3617
+ const provider = providerId ? providersOf$1(doc)[providerId] : void 0;
3618
+ const activeProvider = str$3(doc.model_provider);
3619
+ return {
3620
+ providerId,
3621
+ providerName: str$3(provider?.name),
3622
+ baseUrl: str$3(provider?.base_url),
3623
+ apiKey: secretView$1(provider, ctx),
3624
+ model: str$3(doc.model),
3625
+ activeProvider,
3626
+ active: !!providerId && activeProvider === providerId
3627
+ };
3628
+ }
3629
+ function warningsOf$2(doc, current) {
3630
+ const out = [...baseUrlWarnings(current.baseUrl, "openai")];
3631
+ const provider = current.providerId ? providersOf$1(doc)[current.providerId] : void 0;
3632
+ if (provider && str$3(provider.wire_api) && provider.wire_api !== "responses") {
3633
+ out.push({ code: "wire-api-unsupported", message: `wire_api = "${String(provider.wire_api)}" is rejected by current Codex; only "responses" is supported.` });
3634
+ }
3635
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
3636
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
3637
+ }
3638
+ const active = current.activeProvider;
3639
+ if (active && !CODEX_RESERVED_PROVIDERS.includes(active) && !providersOf$1(doc)[active]) {
3640
+ out.push({ code: "active-provider-missing", message: `model_provider = "${active}" has no [model_providers.${active}] table.` });
3641
+ }
3642
+ return out;
3643
+ }
3644
+ function parsePatch(raw) {
3645
+ const p = raw;
3646
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") fail("invalid-input", "activate must be a boolean");
3647
+ if (p.providerName !== void 0 && (typeof p.providerName !== "string" || p.providerName.length > 120 || /[\u0000-\u001f]/.test(p.providerName))) {
3648
+ fail("invalid-input", "providerName must be a short single-line string");
3649
+ }
3650
+ return {
3651
+ providerId: normalizeProviderId(p.providerId, CODEX_RESERVED_PROVIDERS),
3652
+ providerName: p.providerName?.trim(),
3653
+ baseUrl: normalizeBaseUrl(p.baseUrl),
3654
+ apiKey: normalizeSecret(p.apiKey),
3655
+ model: normalizeModelId(p.model),
3656
+ activate: p.activate
3657
+ };
3658
+ }
3659
+ const codexAdapter = {
3660
+ id: "codex",
3661
+ binary: "codex",
3662
+ files: (ctx) => [{ role: ROLE, path: codexConfigPath(ctx) }],
3663
+ view(files, ctx, opts) {
3664
+ const doc = parseToml(files[ROLE].content);
3665
+ const current = currentOf$2(doc, selectProvider(doc, opts.providerId), ctx);
3666
+ return { current, providers: Object.keys(providersOf$1(doc)), pickerModels: uniq([current.model]), warnings: warningsOf$2(doc, current) };
3667
+ },
3668
+ plan(files, raw, ctx) {
3669
+ const patch = parsePatch(raw);
3670
+ const original = files[ROLE].content;
3671
+ const before = parseToml(original);
3672
+ const existing = providersOf$1(before)[patch.providerId];
3673
+ const table = ["model_providers", patch.providerId];
3674
+ const edits = [];
3675
+ const secrets = [];
3676
+ if (!existing && !patch.baseUrl) fail("invalid-input", "A new provider needs a base URL");
3677
+ const name = patch.providerName || str$3(existing?.name) || patch.providerId;
3678
+ if (!existing || patch.providerName && patch.providerName !== existing.name || !str$3(existing.name)) edits.push({ table, key: "name", value: name });
3679
+ if (patch.baseUrl !== void 0) {
3680
+ if (patch.baseUrl === null && existing) fail("invalid-input", "A provider needs a base URL; remove the provider instead");
3681
+ edits.push({ table, key: "base_url", value: patch.baseUrl });
3682
+ }
3683
+ if (!existing || str$3(existing.wire_api) && existing.wire_api !== "responses") edits.push({ table, key: "wire_api", value: "responses" });
3684
+ switch (patch.apiKey.mode) {
3685
+ case "literal":
3686
+ edits.push({ table, key: "experimental_bearer_token", value: patch.apiKey.value }, { table, key: "env_key", value: null });
3687
+ secrets.push(patch.apiKey.value);
3688
+ break;
3689
+ case "env":
3690
+ edits.push({ table, key: "env_key", value: patch.apiKey.name }, { table, key: "experimental_bearer_token", value: null });
3691
+ break;
3692
+ case "clear":
3693
+ edits.push({ table, key: "env_key", value: null }, { table, key: "experimental_bearer_token", value: null });
3694
+ break;
3695
+ }
3696
+ if (patch.model !== void 0) edits.push({ table: [], key: "model", value: patch.model });
3697
+ if (patch.activate === true) edits.push({ table: [], key: "model_provider", value: patch.providerId });
3698
+ if (patch.activate === false && str$3(before.model_provider) === patch.providerId) edits.push({ table: [], key: "model_provider", value: null });
3699
+ const effective = edits.filter((e) => "removeTable" in e || getPath$1(before, [...e.table, e.key]) !== (e.value ?? void 0));
3700
+ const content = effective.length ? editToml(original, effective) : void 0;
3701
+ const after = content === void 0 ? before : parseToml(content);
3702
+ const current = currentOf$2(after, patch.providerId, ctx);
3703
+ const changedKeys = effective.map((e) => [...e.table, "removeTable" in e ? "*" : e.key].join("."));
3704
+ return { contents: { [ROLE]: content }, warnings: warningsOf$2(after, current), changedKeys, secrets };
3705
+ },
3706
+ secretsIn(_role, content) {
3707
+ try {
3708
+ return collectSecretValues(parseToml(content));
3709
+ } catch (error) {
3710
+ if (error instanceof ModelConfigError) return /* @__PURE__ */ new Set();
3711
+ throw error;
3712
+ }
3713
+ }
3714
+ };
3715
+
3716
+ var main = {exports: {}};
3717
+
3718
+ var version = "16.6.1";
3719
+ var require$$4 = {
3720
+ version: version};
3721
+
3722
+ var hasRequiredMain;
3723
+
3724
+ function requireMain () {
3725
+ if (hasRequiredMain) return main.exports;
3726
+ hasRequiredMain = 1;
3727
+ const fs = require$$0;
3728
+ const path = require$$1;
3729
+ const os$1 = os;
3730
+ const crypto = require$$3;
3731
+ const packageJson = require$$4;
3732
+ const version = packageJson.version;
3733
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
3734
+ function parse(src) {
3735
+ const obj = {};
3736
+ let lines = src.toString();
3737
+ lines = lines.replace(/\r\n?/mg, "\n");
3738
+ let match;
3739
+ while ((match = LINE.exec(lines)) != null) {
3740
+ const key = match[1];
3741
+ let value = match[2] || "";
3742
+ value = value.trim();
3743
+ const maybeQuote = value[0];
3744
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
3745
+ if (maybeQuote === '"') {
3746
+ value = value.replace(/\\n/g, "\n");
3747
+ value = value.replace(/\\r/g, "\r");
3748
+ }
3749
+ obj[key] = value;
3750
+ }
3751
+ return obj;
3752
+ }
3753
+ function _parseVault(options) {
3754
+ options = options || {};
3755
+ const vaultPath = _vaultPath(options);
3756
+ options.path = vaultPath;
3757
+ const result = DotenvModule.configDotenv(options);
3758
+ if (!result.parsed) {
3759
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
3760
+ err.code = "MISSING_DATA";
3761
+ throw err;
3762
+ }
3763
+ const keys = _dotenvKey(options).split(",");
3764
+ const length = keys.length;
3765
+ let decrypted;
3766
+ for (let i = 0; i < length; i++) {
3767
+ try {
3768
+ const key = keys[i].trim();
3769
+ const attrs = _instructions(result, key);
3770
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
3771
+ break;
3772
+ } catch (error) {
3773
+ if (i + 1 >= length) {
3774
+ throw error;
3775
+ }
3776
+ }
3777
+ }
3778
+ return DotenvModule.parse(decrypted);
3779
+ }
3780
+ function _warn(message) {
3781
+ console.log(`[dotenv@${version}][WARN] ${message}`);
3782
+ }
3783
+ function _debug(message) {
3784
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
3785
+ }
3786
+ function _log(message) {
3787
+ console.log(`[dotenv@${version}] ${message}`);
3788
+ }
3789
+ function _dotenvKey(options) {
3790
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
3791
+ return options.DOTENV_KEY;
3792
+ }
3793
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
3794
+ return process.env.DOTENV_KEY;
3795
+ }
3796
+ return "";
3797
+ }
3798
+ function _instructions(result, dotenvKey) {
3799
+ let uri;
3800
+ try {
3801
+ uri = new URL(dotenvKey);
3802
+ } catch (error) {
3803
+ if (error.code === "ERR_INVALID_URL") {
3804
+ 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");
3805
+ err.code = "INVALID_DOTENV_KEY";
3806
+ throw err;
3807
+ }
3808
+ throw error;
3809
+ }
3810
+ const key = uri.password;
3811
+ if (!key) {
3812
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
3813
+ err.code = "INVALID_DOTENV_KEY";
3814
+ throw err;
3815
+ }
3816
+ const environment = uri.searchParams.get("environment");
3817
+ if (!environment) {
3818
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
3819
+ err.code = "INVALID_DOTENV_KEY";
3820
+ throw err;
3821
+ }
3822
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
3823
+ const ciphertext = result.parsed[environmentKey];
3824
+ if (!ciphertext) {
3825
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
3826
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
3827
+ throw err;
3828
+ }
3829
+ return { ciphertext, key };
3830
+ }
3831
+ function _vaultPath(options) {
3832
+ let possibleVaultPath = null;
3833
+ if (options && options.path && options.path.length > 0) {
3834
+ if (Array.isArray(options.path)) {
3835
+ for (const filepath of options.path) {
3836
+ if (fs.existsSync(filepath)) {
3837
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
3838
+ }
3839
+ }
3840
+ } else {
3841
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
3842
+ }
3843
+ } else {
3844
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
3845
+ }
3846
+ if (fs.existsSync(possibleVaultPath)) {
3847
+ return possibleVaultPath;
3848
+ }
3849
+ return null;
3850
+ }
3851
+ function _resolveHome(envPath) {
3852
+ return envPath[0] === "~" ? path.join(os$1.homedir(), envPath.slice(1)) : envPath;
3853
+ }
3854
+ function _configVault(options) {
3855
+ const debug = Boolean(options && options.debug);
3856
+ const quiet = options && "quiet" in options ? options.quiet : true;
3857
+ if (debug || !quiet) {
3858
+ _log("Loading env from encrypted .env.vault");
3859
+ }
3860
+ const parsed = DotenvModule._parseVault(options);
3861
+ let processEnv = process.env;
3862
+ if (options && options.processEnv != null) {
3863
+ processEnv = options.processEnv;
3864
+ }
3865
+ DotenvModule.populate(processEnv, parsed, options);
3866
+ return { parsed };
3867
+ }
3868
+ function configDotenv(options) {
3869
+ const dotenvPath = path.resolve(process.cwd(), ".env");
3870
+ let encoding = "utf8";
3871
+ const debug = Boolean(options && options.debug);
3872
+ const quiet = options && "quiet" in options ? options.quiet : true;
3873
+ if (options && options.encoding) {
3874
+ encoding = options.encoding;
3875
+ } else {
3876
+ if (debug) {
3877
+ _debug("No encoding is specified. UTF-8 is used by default");
3878
+ }
3879
+ }
3880
+ let optionPaths = [dotenvPath];
3881
+ if (options && options.path) {
3882
+ if (!Array.isArray(options.path)) {
3883
+ optionPaths = [_resolveHome(options.path)];
3884
+ } else {
3885
+ optionPaths = [];
3886
+ for (const filepath of options.path) {
3887
+ optionPaths.push(_resolveHome(filepath));
3888
+ }
3889
+ }
3890
+ }
3891
+ let lastError;
3892
+ const parsedAll = {};
3893
+ for (const path2 of optionPaths) {
3894
+ try {
3895
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
3896
+ DotenvModule.populate(parsedAll, parsed, options);
3897
+ } catch (e) {
3898
+ if (debug) {
3899
+ _debug(`Failed to load ${path2} ${e.message}`);
3900
+ }
3901
+ lastError = e;
3902
+ }
3903
+ }
3904
+ let processEnv = process.env;
3905
+ if (options && options.processEnv != null) {
3906
+ processEnv = options.processEnv;
3907
+ }
3908
+ DotenvModule.populate(processEnv, parsedAll, options);
3909
+ if (debug || !quiet) {
3910
+ const keysCount = Object.keys(parsedAll).length;
3911
+ const shortPaths = [];
3912
+ for (const filePath of optionPaths) {
3913
+ try {
3914
+ const relative = path.relative(process.cwd(), filePath);
3915
+ shortPaths.push(relative);
3916
+ } catch (e) {
3917
+ if (debug) {
3918
+ _debug(`Failed to load ${filePath} ${e.message}`);
3919
+ }
3920
+ lastError = e;
3921
+ }
3922
+ }
3923
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
3924
+ }
3925
+ if (lastError) {
3926
+ return { parsed: parsedAll, error: lastError };
3927
+ } else {
3928
+ return { parsed: parsedAll };
3929
+ }
3930
+ }
3931
+ function config(options) {
3932
+ if (_dotenvKey(options).length === 0) {
3933
+ return DotenvModule.configDotenv(options);
3934
+ }
3935
+ const vaultPath = _vaultPath(options);
3936
+ if (!vaultPath) {
3937
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
3938
+ return DotenvModule.configDotenv(options);
3939
+ }
3940
+ return DotenvModule._configVault(options);
3941
+ }
3942
+ function decrypt(encrypted, keyStr) {
3943
+ const key = Buffer.from(keyStr.slice(-64), "hex");
3944
+ let ciphertext = Buffer.from(encrypted, "base64");
3945
+ const nonce = ciphertext.subarray(0, 12);
3946
+ const authTag = ciphertext.subarray(-16);
3947
+ ciphertext = ciphertext.subarray(12, -16);
3948
+ try {
3949
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
3950
+ aesgcm.setAuthTag(authTag);
3951
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
3952
+ } catch (error) {
3953
+ const isRange = error instanceof RangeError;
3954
+ const invalidKeyLength = error.message === "Invalid key length";
3955
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
3956
+ if (isRange || invalidKeyLength) {
3957
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
3958
+ err.code = "INVALID_DOTENV_KEY";
3959
+ throw err;
3960
+ } else if (decryptionFailed) {
3961
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
3962
+ err.code = "DECRYPTION_FAILED";
3963
+ throw err;
3964
+ } else {
3965
+ throw error;
3966
+ }
3967
+ }
3968
+ }
3969
+ function populate(processEnv, parsed, options = {}) {
3970
+ const debug = Boolean(options && options.debug);
3971
+ const override = Boolean(options && options.override);
3972
+ if (typeof parsed !== "object") {
3973
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
3974
+ err.code = "OBJECT_REQUIRED";
3975
+ throw err;
3976
+ }
3977
+ for (const key of Object.keys(parsed)) {
3978
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
3979
+ if (override === true) {
3980
+ processEnv[key] = parsed[key];
3981
+ }
3982
+ if (debug) {
3983
+ if (override === true) {
3984
+ _debug(`"${key}" is already defined and WAS overwritten`);
3985
+ } else {
3986
+ _debug(`"${key}" is already defined and was NOT overwritten`);
3987
+ }
3988
+ }
3989
+ } else {
3990
+ processEnv[key] = parsed[key];
3991
+ }
3992
+ }
3993
+ }
3994
+ const DotenvModule = {
3995
+ configDotenv,
3996
+ _configVault,
3997
+ _parseVault,
3998
+ config,
3999
+ decrypt,
4000
+ parse,
4001
+ populate
4002
+ };
4003
+ main.exports.configDotenv = DotenvModule.configDotenv;
4004
+ main.exports._configVault = DotenvModule._configVault;
4005
+ main.exports._parseVault = DotenvModule._parseVault;
4006
+ main.exports.config = DotenvModule.config;
4007
+ main.exports.decrypt = DotenvModule.decrypt;
4008
+ main.exports.parse = DotenvModule.parse;
4009
+ main.exports.populate = DotenvModule.populate;
4010
+ main.exports = DotenvModule;
4011
+ return main.exports;
4012
+ }
4013
+
4014
+ var mainExports = requireMain();
4015
+
4016
+ const LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
4017
+ function parseDotenv(text) {
4018
+ return mainExports.parse(text);
4019
+ }
4020
+ function formatDotenvValue(value) {
4021
+ if (/^[A-Za-z0-9_./:@+,-]*$/.test(value)) return value;
4022
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
4023
+ }
4024
+ function editDotenv(text, edits) {
4025
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
4026
+ let lines = text === "" ? [] : text.split(/\r?\n/);
4027
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
4028
+ for (const edit of edits) {
4029
+ const at = lines.map((l, i) => LINE.exec(l)?.[1] === edit.key ? i : -1).filter((i) => i >= 0);
4030
+ if (edit.value === null) {
4031
+ lines = lines.filter((_, i) => !at.includes(i));
4032
+ continue;
4033
+ }
4034
+ const rendered = `${edit.key}=${formatDotenvValue(edit.value)}`;
4035
+ if (at.length) {
4036
+ lines[at[0]] = rendered;
4037
+ lines = lines.filter((_, i) => !at.slice(1).includes(i));
4038
+ } else {
4039
+ lines.push(rendered);
4040
+ }
4041
+ }
4042
+ const out = lines.length ? lines.join(eol) + eol : "";
4043
+ const before = mainExports.parse(text);
4044
+ const after = mainExports.parse(out);
4045
+ for (const edit of edits) {
4046
+ if ((after[edit.key] ?? null) !== edit.value) throw new ModelConfigError("unsafe-edit", `.env edit did not produce ${edit.key} as requested`);
4047
+ delete before[edit.key];
4048
+ delete after[edit.key];
4049
+ }
4050
+ if (JSON.stringify(Object.entries(before).sort()) !== JSON.stringify(Object.entries(after).sort())) {
4051
+ throw new ModelConfigError("unsafe-edit", ".env edit would change other variables");
4052
+ }
4053
+ return out;
4054
+ }
4055
+
4056
+ const SETTINGS$1 = "settings";
4057
+ const ENV = "env";
4058
+ const BASE_URL = "GOOGLE_GEMINI_BASE_URL";
4059
+ const API_KEY = "GEMINI_API_KEY";
4060
+ function geminiDir(ctx) {
4061
+ return join(ctx.env.GEMINI_CLI_HOME?.trim() || ctx.home, ".gemini");
4062
+ }
4063
+ const str$2 = (v) => typeof v === "string" && v.trim() ? v : null;
4064
+ function currentOf$1(settings, env, ctx) {
4065
+ const literal = str$2(env[API_KEY]);
4066
+ const apiKey = literal ? { mode: "literal", masked: maskSecret(literal) } : ctx.env[API_KEY] ? { mode: "env", envName: API_KEY, envPresent: true } : { mode: "none" };
4067
+ return { baseUrl: str$2(env[BASE_URL]), apiKey, model: str$2(getPath$1(settings, ["model", "name"])) };
4068
+ }
4069
+ function warningsOf$1(settings, current) {
4070
+ const out = [...baseUrlWarnings(current.baseUrl, "gemini")];
4071
+ if (current.baseUrl || current.apiKey?.mode === "literal") {
4072
+ 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." });
4073
+ }
4074
+ const selected = str$2(getPath$1(settings, ["security", "auth", "selectedType"]));
4075
+ if (current.baseUrl && selected && selected !== "gateway") {
4076
+ out.push({ code: "auth-type-pinned", message: `security.auth.selectedType is "${selected}"; Gemini only uses GOOGLE_GEMINI_BASE_URL with the gateway auth type.` });
4077
+ }
4078
+ if (current.baseUrl && !/^https:/.test(current.baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(current.baseUrl)) {
4079
+ out.push({ code: "gemini-https", message: "Gemini requires an https base URL (localhost excepted)." });
4080
+ }
4081
+ return out;
4082
+ }
4083
+ const geminiAdapter = {
4084
+ id: "gemini",
4085
+ binary: "gemini",
4086
+ files: (ctx) => [{ role: SETTINGS$1, path: join(geminiDir(ctx), "settings.json") }, { role: ENV, path: join(geminiDir(ctx), ".env") }],
4087
+ view(files, ctx) {
4088
+ const settings = parseJsonObject$1(files[SETTINGS$1].content, "settings.json");
4089
+ const current = currentOf$1(settings, parseDotenv(files[ENV].content), ctx);
4090
+ return { current, pickerModels: uniq([current.model]), warnings: warningsOf$1(settings, current) };
4091
+ },
4092
+ plan(files, raw, ctx) {
4093
+ const p = raw;
4094
+ const baseUrl = normalizeBaseUrl(p.baseUrl);
4095
+ const apiKey = normalizeSecret(p.apiKey, ["keep", "clear", "literal"]);
4096
+ const model = normalizeModelId(p.model);
4097
+ const settingsText = files[SETTINGS$1].content;
4098
+ const before = parseJsonObject$1(settingsText, "settings.json");
4099
+ const settings = structuredClone(before);
4100
+ const changedKeys = [];
4101
+ let settingsOut;
4102
+ if (model !== void 0 && (str$2(getPath$1(before, ["model", "name"])) ?? null) !== model) {
4103
+ const hadModel = settings.model !== void 0;
4104
+ const modelObj = childObject(settings, "model", "settings");
4105
+ setOrDelete(modelObj, "name", model);
4106
+ if (!hadModel && Object.keys(modelObj).length === 0) delete settings.model;
4107
+ settingsOut = stringifyLike(settingsText, settings);
4108
+ changedKeys.push("settings.model.name");
4109
+ }
4110
+ const envText = files[ENV].content;
4111
+ const env = parseDotenv(envText);
4112
+ const edits = [];
4113
+ if (baseUrl !== void 0 && (env[BASE_URL] ?? null) !== baseUrl) edits.push({ key: BASE_URL, value: baseUrl });
4114
+ if (apiKey.mode === "literal" && env[API_KEY] !== apiKey.value) edits.push({ key: API_KEY, value: apiKey.value });
4115
+ if (apiKey.mode === "clear" && env[API_KEY] !== void 0) edits.push({ key: API_KEY, value: null });
4116
+ const envOut = edits.length ? editDotenv(envText, edits) : void 0;
4117
+ changedKeys.push(...edits.map((e) => `.env.${e.key}`));
4118
+ const afterEnv = envOut === void 0 ? env : parseDotenv(envOut);
4119
+ const current = currentOf$1(settings, afterEnv, ctx);
4120
+ return {
4121
+ contents: { [SETTINGS$1]: settingsOut, [ENV]: envOut },
4122
+ warnings: warningsOf$1(settings, current),
4123
+ changedKeys,
4124
+ secrets: apiKey.mode === "literal" ? [apiKey.value] : []
4125
+ };
4126
+ },
4127
+ secretsIn(role, content) {
4128
+ try {
4129
+ return role === ENV ? collectSecretValues(parseDotenv(content)) : collectSecretValues(parseJsonObject$1(content, "settings.json"));
4130
+ } catch {
4131
+ return /* @__PURE__ */ new Set();
4132
+ }
4133
+ }
4134
+ };
4135
+
4136
+ const MODELS = "models";
4137
+ const SETTINGS = "settings";
4138
+ const PI_APIS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai", "mistral-conversations"];
4139
+ const ENV_REF = /^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/;
4140
+ function piAgentDir(ctx) {
4141
+ return ctx.env.PI_CODING_AGENT_DIR?.trim() || join(ctx.home, ".pi", "agent");
4142
+ }
4143
+ const str$1 = (v) => typeof v === "string" && v.trim() ? v : null;
4144
+ function providersOf(models) {
4145
+ const p = models.providers;
4146
+ if (!p || typeof p !== "object" || Array.isArray(p)) return {};
4147
+ return Object.fromEntries(Object.entries(p).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
4148
+ }
4149
+ function modelIds(provider) {
4150
+ const list = provider?.models;
4151
+ return Array.isArray(list) ? list.flatMap((m) => m && typeof m === "object" && typeof m.id === "string" ? [m.id] : []) : [];
4152
+ }
4153
+ function secretView(provider, ctx) {
4154
+ const key = str$1(provider?.apiKey);
4155
+ if (!key) return { mode: "none" };
4156
+ const ref = ENV_REF.exec(key.trim());
4157
+ if (ref) return { mode: "env", envName: ref[1], envPresent: !!ctx.env[ref[1]] };
4158
+ if (key.trim().startsWith("!")) return { mode: "command" };
4159
+ return { mode: "literal", masked: maskSecret(key) };
4160
+ }
4161
+ function currentOf(models, settings, providerId, ctx) {
4162
+ const provider = providerId ? providersOf(models)[providerId] : void 0;
4163
+ const activeProvider = str$1(settings.defaultProvider);
4164
+ return {
4165
+ providerId,
4166
+ baseUrl: str$1(provider?.baseUrl),
4167
+ api: str$1(provider?.api),
4168
+ apiKey: secretView(provider, ctx),
4169
+ models: modelIds(provider),
4170
+ activeProvider,
4171
+ defaultModel: str$1(settings.defaultModel),
4172
+ active: !!providerId && activeProvider === providerId
4173
+ };
4174
+ }
4175
+ function pickerModelsOf(models) {
4176
+ return uniq(Object.entries(providersOf(models)).flatMap(([id, p]) => modelIds(p).map((m) => `${id}/${m}`)));
4177
+ }
4178
+ function warningsOf(settings, current) {
4179
+ const out = [...baseUrlWarnings(current.baseUrl, current.api === "anthropic-messages" ? "anthropic" : "openai")].filter((w) => w.code !== "base-url-v1");
4180
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
4181
+ 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.` });
4182
+ }
4183
+ if (current.providerId && current.apiKey?.mode === "none") {
4184
+ out.push({ code: "no-key", message: "pi hides models whose provider has no resolvable API key." });
4185
+ }
4186
+ if (Array.isArray(settings.enabledModels) && current.providerId) {
4187
+ const enabled = settings.enabledModels;
4188
+ const hidden = (current.models ?? []).filter((m) => !enabled.includes(`${current.providerId}/${m}`) && !enabled.includes(m));
4189
+ if (hidden.length) out.push({ code: "enabled-models-filter", message: `settings.json enabledModels does not include ${hidden.join(", ")}.` });
4190
+ }
4191
+ return out;
4192
+ }
4193
+ const piAdapter = {
4194
+ id: "pi",
4195
+ binary: "pi",
4196
+ files: (ctx) => [{ role: MODELS, path: join(piAgentDir(ctx), "models.json") }, { role: SETTINGS, path: join(piAgentDir(ctx), "settings.json") }],
4197
+ view(files, ctx, opts) {
4198
+ const models = parseJsonObject$1(files[MODELS].content, "models.json");
4199
+ const settings = parseJsonObject$1(files[SETTINGS].content, "settings.json");
4200
+ const providers = providersOf(models);
4201
+ const active = str$1(settings.defaultProvider);
4202
+ const selected = opts.providerId ?? (active && providers[active] ? active : Object.keys(providers)[0] ?? null);
4203
+ const current = currentOf(models, settings, selected, ctx);
4204
+ return { current, providers: Object.keys(providers), pickerModels: pickerModelsOf(models), warnings: warningsOf(settings, current) };
4205
+ },
4206
+ plan(files, raw, ctx) {
4207
+ const p = raw;
4208
+ const providerId = normalizeProviderId(p.providerId);
4209
+ const baseUrl = normalizeBaseUrl(p.baseUrl);
4210
+ if (p.api !== void 0 && !PI_APIS.includes(p.api)) fail("invalid-input", `api must be one of ${PI_APIS.join(", ")}`);
4211
+ const apiKey = normalizeSecret(p.apiKey);
4212
+ 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");
4213
+ const ids = normalizeModelList(p.models);
4214
+ const defaultModel = normalizeModelId(p.defaultModel, "defaultModel");
4215
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") fail("invalid-input", "activate must be a boolean");
4216
+ const modelsText = files[MODELS].content;
4217
+ const settingsText = files[SETTINGS].content;
4218
+ const modelsBefore = parseJsonObject$1(modelsText, "models.json");
4219
+ const settingsBefore = parseJsonObject$1(settingsText, "settings.json");
4220
+ const models = structuredClone(modelsBefore);
4221
+ const settings = structuredClone(settingsBefore);
4222
+ const providers = childObject(models, "providers", "models.json");
4223
+ const isNew = providers[providerId] === void 0;
4224
+ if (isNew && !baseUrl) fail("invalid-input", "A new provider needs a base URL");
4225
+ const provider = childObject(providers, providerId, "models.json.providers");
4226
+ if (baseUrl !== void 0) {
4227
+ if (baseUrl === null) fail("invalid-input", "A provider needs a base URL");
4228
+ provider.baseUrl = baseUrl;
4229
+ }
4230
+ if (p.api !== void 0) provider.api = p.api;
4231
+ else if (isNew) provider.api = "openai-completions";
4232
+ const secrets = [];
4233
+ if (apiKey.mode === "literal") {
4234
+ provider.apiKey = apiKey.value;
4235
+ secrets.push(apiKey.value);
4236
+ }
4237
+ if (apiKey.mode === "env") provider.apiKey = `\${${apiKey.name}}`;
4238
+ if (apiKey.mode === "clear") delete provider.apiKey;
4239
+ if (ids !== void 0) {
4240
+ const existing = Array.isArray(provider.models) ? provider.models : [];
4241
+ const next = ids.map((id) => existing.find((m) => m && typeof m === "object" && m.id === id) ?? { id });
4242
+ if (next.length) provider.models = next;
4243
+ else delete provider.models;
4244
+ }
4245
+ const finalIds = modelIds(provider);
4246
+ if (p.activate === true) {
4247
+ settings.defaultProvider = providerId;
4248
+ const chosen = defaultModel ?? (finalIds.includes(str$1(settings.defaultModel) ?? "") ? str$1(settings.defaultModel) : finalIds[0]);
4249
+ setOrDelete(settings, "defaultModel", chosen);
4250
+ } else if (p.activate === false && str$1(settings.defaultProvider) === providerId) {
4251
+ delete settings.defaultProvider;
4252
+ delete settings.defaultModel;
4253
+ } else if (defaultModel !== void 0 && str$1(settings.defaultProvider) === providerId) {
4254
+ setOrDelete(settings, "defaultModel", defaultModel);
4255
+ }
4256
+ if (defaultModel && !finalIds.includes(defaultModel)) fail("invalid-input", "defaultModel must be one of the provider models");
4257
+ const modelKeys = changedPaths(modelsBefore, models, [["providers", providerId, "baseUrl"], ["providers", providerId, "api"], ["providers", providerId, "apiKey"], ["providers", providerId, "models"]]);
4258
+ const settingsKeys = changedPaths(settingsBefore, settings, [["defaultProvider"], ["defaultModel"]]);
4259
+ const current = currentOf(models, settings, providerId, ctx);
4260
+ return {
4261
+ contents: {
4262
+ [MODELS]: modelKeys.length ? stringifyLike(modelsText, models) : void 0,
4263
+ [SETTINGS]: settingsKeys.length ? stringifyLike(settingsText, settings) : void 0
4264
+ },
4265
+ warnings: warningsOf(settings, current),
4266
+ changedKeys: [...modelKeys.map((k) => `models.json.${k}`), ...settingsKeys.map((k) => `settings.json.${k}`)],
4267
+ secrets
4268
+ };
4269
+ },
4270
+ secretsIn(_role, content) {
4271
+ try {
4272
+ return collectSecretValues(parseJsonObject$1(content, "pi config"));
4273
+ } catch {
4274
+ return /* @__PURE__ */ new Set();
4275
+ }
4276
+ }
4277
+ };
4278
+
4279
+ const MODEL_CONFIG_CAPABILITY_VERSION = 1;
4280
+ const HARNESS_IDS = ["claude", "codex", "gemini", "pi"];
4281
+
4282
+ const ADAPTERS = { claude: claudeAdapter, codex: codexAdapter, gemini: geminiAdapter, pi: piAdapter };
4283
+ function harnessOf(value) {
4284
+ if (typeof value !== "string" || !HARNESS_IDS.includes(value)) {
4285
+ throw new ModelConfigError("invalid-harness", `harness must be one of ${HARNESS_IDS.join(", ")}`);
4286
+ }
4287
+ return value;
4288
+ }
4289
+ class ModelConfigService {
4290
+ constructor(opts) {
4291
+ this.opts = opts;
4292
+ this.backups = new BackupStore(join(opts.happyHomeDir, "model-config-backups"));
4293
+ this.auditPath = join(opts.happyHomeDir, "model-config-audit.jsonl");
4294
+ }
4295
+ backups;
4296
+ auditPath;
4297
+ chain = Promise.resolve();
4298
+ get ctx() {
4299
+ return { home: this.opts.home, env: this.opts.env };
4300
+ }
4301
+ serialize(fn) {
4302
+ const next = this.chain.then(fn, fn);
4303
+ this.chain = next.catch(() => {
4304
+ });
4305
+ return next;
4306
+ }
4307
+ async loadFiles(adapter) {
4308
+ const files = {};
4309
+ for (const { role, path } of adapter.files(this.ctx)) files[role] = await readConfigFile(path);
4310
+ const baseHash = sha256(Object.entries(files).map(([role, f]) => `${role}\0${f.exists ? f.hash : "-"}`).join("\n"));
4311
+ return { files, baseHash };
4312
+ }
4313
+ async readOne(harness, providerId) {
4314
+ const adapter = ADAPTERS[harness];
4315
+ const installed = harness === "claude" || (this.opts.isInstalled?.(adapter.binary) ?? true);
4316
+ const backups = await this.backups.list(harness);
4317
+ let loaded;
4318
+ try {
4319
+ loaded = await this.loadFiles(adapter);
4320
+ } catch (error) {
4321
+ const e = toError(error);
4322
+ return {
4323
+ harness,
4324
+ installed,
4325
+ baseHash: "",
4326
+ current: {},
4327
+ pickerModels: [],
4328
+ backups,
4329
+ warnings: [],
4330
+ files: adapter.files(this.ctx).map((f) => ({ role: f.role, path: f.path, exists: false, error: e }))
4331
+ };
4332
+ }
4333
+ const files = Object.entries(loaded.files).map(([role, f]) => ({ role, path: f.path, exists: f.exists }));
4334
+ try {
4335
+ const view = adapter.view(loaded.files, this.ctx, { providerId });
4336
+ return { harness, installed, files, baseHash: loaded.baseHash, backups, ...view };
4337
+ } catch (error) {
4338
+ const e = toError(error);
4339
+ return { harness, installed, baseHash: loaded.baseHash, current: {}, pickerModels: [], backups, warnings: [], files: files.map((f) => ({ ...f, error: e })) };
4340
+ }
4341
+ }
4342
+ async read(params = {}) {
4343
+ const list = params.harness === void 0 ? [...HARNESS_IDS] : [harnessOf(params.harness)];
4344
+ const providerId = typeof params.providerId === "string" && params.providerId ? params.providerId : void 0;
4345
+ const harnesses = await Promise.all(list.map((h) => this.readOne(h, providerId)));
4346
+ return { version: MODEL_CONFIG_CAPABILITY_VERSION, harnesses };
4347
+ }
4348
+ diffs(adapter, files, next, extraSecrets) {
4349
+ const out = [];
4350
+ for (const [role, file] of Object.entries(files)) {
4351
+ const target = next[role];
4352
+ if (target === void 0) continue;
4353
+ const newText = target ?? "";
4354
+ if (target !== null && file.exists && newText === file.content) continue;
4355
+ if (target === null && !file.exists) continue;
4356
+ const secrets = [...adapter.secretsIn(role, file.content), ...target ? adapter.secretsIn(role, target) : [], ...extraSecrets];
4357
+ const raw = unifiedDiff(file.content, newText, file.path);
4358
+ out.push({ path: file.path, diff: redactText(raw, secrets), created: !file.exists && target !== null, deleted: target === null && file.exists });
4359
+ }
4360
+ return out;
4361
+ }
4362
+ async write(harness, action, files, next, keys, apiKeyMode) {
4363
+ const touched = Object.entries(next).filter(([, v]) => v !== void 0);
4364
+ const snapshot = touched.map(([role]) => ({ path: files[role].path, content: files[role].exists ? files[role].content : null, mode: files[role].mode }));
4365
+ const backup = await this.backups.create(harness, action === "apply" ? "before-apply" : "before-restore", snapshot, this.opts.now?.() ?? Date.now());
4366
+ for (const [role, target] of touched) {
4367
+ const file = files[role];
4368
+ if (target.content === null) await promises.rm(file.path, { force: true });
4369
+ else await atomicWriteFile(file.path, target.content, file.mode ?? target.mode);
4370
+ }
4371
+ await this.audit({ at: this.opts.now?.() ?? Date.now(), action, harness, files: touched.map(([role]) => files[role].path), keys, apiKeyMode, backupId: backup.id });
4372
+ this.opts.onChanged?.(harness);
4373
+ return backup;
4374
+ }
4375
+ async audit(record) {
4376
+ try {
4377
+ await promises.mkdir(this.opts.happyHomeDir, { recursive: true });
4378
+ await promises.appendFile(this.auditPath, `${JSON.stringify(record)}
4379
+ `, { encoding: "utf8", mode: 384 });
4380
+ } catch {
4381
+ }
4382
+ }
4383
+ apply(params) {
4384
+ const run = async () => {
4385
+ const patch = params.patch;
4386
+ if (!patch || typeof patch !== "object") throw new ModelConfigError("invalid-input", "patch is required");
4387
+ const harness = harnessOf(patch.harness);
4388
+ const adapter = ADAPTERS[harness];
4389
+ const { files, baseHash } = await this.loadFiles(adapter);
4390
+ const dryRun = params.dryRun !== false;
4391
+ if (!dryRun && params.baseHash !== baseHash) {
4392
+ throw new ModelConfigError("conflict", "The config files changed since the preview; review the new diff and apply again");
4393
+ }
4394
+ const plan = adapter.plan(files, patch, this.ctx);
4395
+ const diffs = this.diffs(adapter, files, plan.contents, plan.secrets);
4396
+ const changed = diffs.length > 0;
4397
+ if (dryRun || !changed) {
4398
+ return { harness, dryRun, changed, baseHash, files: diffs, warnings: plan.warnings };
4399
+ }
4400
+ const next = Object.fromEntries(Object.entries(plan.contents).map(([role, content]) => [role, content === void 0 ? void 0 : { content, mode: null }]));
4401
+ const apiKeyMode = patch.apiKey?.mode;
4402
+ const backup = await this.write(harness, "apply", files, next, plan.changedKeys, typeof apiKeyMode === "string" ? apiKeyMode : void 0);
4403
+ const config = await this.readOne(harness, patch.providerId);
4404
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: plan.warnings, backup, config };
4405
+ };
4406
+ return params.dryRun === false ? this.serialize(run) : run();
4407
+ }
4408
+ restore(params) {
4409
+ const run = async () => {
4410
+ const harness = harnessOf(params.harness);
4411
+ const adapter = ADAPTERS[harness];
4412
+ if (typeof params.backupId !== "string") throw new ModelConfigError("invalid-input", "backupId is required");
4413
+ const saved = await this.backups.read(harness, params.backupId);
4414
+ const { files, baseHash } = await this.loadFiles(adapter);
4415
+ const dryRun = params.dryRun !== false;
4416
+ if (!dryRun && params.baseHash !== baseHash) {
4417
+ throw new ModelConfigError("conflict", "The config files changed since the preview; review the new diff and restore again");
4418
+ }
4419
+ const allowed = new Map(Object.entries(files).map(([role, f]) => [f.path, role]));
4420
+ const target = {};
4421
+ for (const file of saved) {
4422
+ const role = allowed.get(file.path);
4423
+ if (!role) throw new ModelConfigError("backup-mismatch", "Backup does not belong to the current config location");
4424
+ target[role] = { content: file.content, mode: file.mode };
4425
+ }
4426
+ const diffs = this.diffs(adapter, files, Object.fromEntries(Object.entries(target).map(([r, v]) => [r, v?.content])), []);
4427
+ const changed = diffs.length > 0;
4428
+ if (dryRun || !changed) return { harness, dryRun, changed, baseHash, files: diffs, warnings: [] };
4429
+ const keys = ["*restore*"];
4430
+ const backup = await this.write(harness, "restore", files, target, keys);
4431
+ const config = await this.readOne(harness);
4432
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: [], backup, config };
4433
+ };
4434
+ return params.dryRun === false ? this.serialize(run) : run();
4435
+ }
4436
+ }
4437
+ function toError(error) {
4438
+ if (error instanceof ModelConfigError) return { code: error.code, message: error.message };
4439
+ return { code: "read-failed", message: error instanceof Error ? error.message : String(error) };
4440
+ }
4441
+
4442
+ function startWebPanelsSync(deps) {
4443
+ let lastMtime;
4444
+ let lastProblems = "";
4445
+ let stopped = false;
4446
+ let inflight = null;
4447
+ const run = async () => {
4448
+ try {
4449
+ const mtime = await deps.statMtime();
4450
+ if (mtime === lastMtime) return;
4451
+ lastMtime = mtime;
4452
+ const { panels, problems } = normalizeWebPanels(mtime === null ? void 0 : await deps.readRaw());
4453
+ const key = JSON.stringify(problems);
4454
+ if (problems.length > 0 && key !== lastProblems) deps.logProblems(problems);
4455
+ lastProblems = key;
4456
+ await deps.publish(panels);
4457
+ } catch {
4458
+ lastMtime = void 0;
4459
+ }
4460
+ };
4461
+ const tick = () => {
4462
+ if (stopped) return Promise.resolve();
4463
+ inflight ??= run().finally(() => {
4464
+ inflight = null;
4465
+ });
4466
+ return inflight;
4467
+ };
4468
+ void tick();
4469
+ const timer = setInterval(() => {
4470
+ void tick();
4471
+ }, deps.intervalMs ?? 2e3);
4472
+ timer.unref?.();
4473
+ return { stop: () => {
4474
+ stopped = true;
4475
+ clearInterval(timer);
4476
+ }, tick };
4477
+ }
4478
+
2033
4479
  function isAcceptableRelayUrl(url) {
2034
4480
  try {
2035
4481
  const parsed = new URL(url);
@@ -2485,6 +4931,44 @@ function createUpdateController(deps) {
2485
4931
  return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running };
2486
4932
  }
2487
4933
 
4934
+ function buildPresenceBatch(live, previous) {
4935
+ const current = new Set(live.map((s) => s.sessionId));
4936
+ const sessions = live.slice(0, 200).map((s) => ({
4937
+ sessionId: s.sessionId,
4938
+ state: s.running ? "running" : "idle",
4939
+ ...s.flavor ? { agent: s.flavor } : {},
4940
+ ...s.branch ? { branch: s.branch.slice(0, 200) } : {}
4941
+ }));
4942
+ const gone = [...previous].filter((id) => !current.has(id)).slice(0, 200);
4943
+ return { sessions, gone, current };
4944
+ }
4945
+ function createProjectPresenceReporter(deps) {
4946
+ let previous = /* @__PURE__ */ new Set();
4947
+ let running = false;
4948
+ async function tick() {
4949
+ if (running || deps.client.isDisabled()) return;
4950
+ running = true;
4951
+ try {
4952
+ const batch = buildPresenceBatch(deps.live(), previous);
4953
+ if (batch.sessions.length === 0 && batch.gone.length === 0) {
4954
+ previous = batch.current;
4955
+ return;
4956
+ }
4957
+ await deps.client.presence(deps.machineId, batch.sessions, batch.gone);
4958
+ previous = batch.current;
4959
+ } catch (error) {
4960
+ if (!(error instanceof ProjectsUnsupportedError)) deps.log(`project presence tick failed: ${String(error)}`);
4961
+ } finally {
4962
+ running = false;
4963
+ }
4964
+ }
4965
+ const timer = setInterval(() => {
4966
+ void tick();
4967
+ }, deps.intervalMs ?? 6e4);
4968
+ timer.unref?.();
4969
+ return { tick, stop: () => clearInterval(timer) };
4970
+ }
4971
+
2488
4972
  const AUTOMATION_BINDINGS_TTL_MS = 10 * 60 * 1e3;
2489
4973
  const HIBERNATION_IN_FLIGHT_MS = 6e4;
2490
4974
  const HIBERNATION_EXIT_WAIT_MS = 15e3;
@@ -3397,12 +5881,12 @@ function createMirrorManager(deps) {
3397
5881
  await teardownBinding(replaces, "superseded by a fresh conversation");
3398
5882
  }
3399
5883
  const metadata = {
3400
- path: event.cwd ?? os.homedir(),
3401
- host: os.hostname(),
5884
+ path: event.cwd ?? os$1.homedir(),
5885
+ host: os$1.hostname(),
3402
5886
  version: packageJson.version,
3403
- os: os.platform(),
5887
+ os: os$1.platform(),
3404
5888
  machineId: deps.machineId,
3405
- homeDir: os.homedir(),
5889
+ homeDir: os$1.homedir(),
3406
5890
  happyHomeDir: configuration.happyHomeDir,
3407
5891
  happyLibDir: projectPath(),
3408
5892
  happyToolsDir: resolve(projectPath(), "tools", "unpacked"),
@@ -3664,6 +6148,57 @@ function withDaemonHeartbeat(state, lastHeartbeat) {
3664
6148
  return { ...state, lastHeartbeat };
3665
6149
  }
3666
6150
 
6151
+ const TAIL_BYTES = 64 * 1024;
6152
+ const MAX_REASON = 300;
6153
+ function extractStartupExitReason(logText) {
6154
+ const lines = logText.split("\n");
6155
+ for (let i = lines.length - 1; i >= 0; i--) {
6156
+ const exit = /\[EXIT\] Exiting with code -?\d+: (.+)$/.exec(lines[i]);
6157
+ if (exit) return clamp(exit[1]);
6158
+ }
6159
+ for (let i = lines.length - 1; i >= 0; i--) {
6160
+ if (!/\[ERROR\]|\[WARN\]/.test(lines[i])) continue;
6161
+ const detail = lines.slice(i, i + 8).join("\n");
6162
+ const message = /message: '([^'\n]+)'/.exec(detail)?.[1];
6163
+ const code = /code: '([A-Z0-9_]+)'/.exec(detail)?.[1];
6164
+ const head = lines[i].replace(/^\[[\d:.]+\]\s*/, "").replace(/\s*\{\s*$/, "").trim();
6165
+ return clamp([head, message, code].filter(Boolean).join(" "));
6166
+ }
6167
+ return void 0;
6168
+ }
6169
+ function describeStartupExit(exit, timeoutMs) {
6170
+ if (exit.timedOut) {
6171
+ const tail = exit.exited ? "and was stopped" : "and could not be confirmed stopped";
6172
+ return `Agent process did not report its session within ${Math.round(timeoutMs / 1e3)}s ${tail}${exit.reason ? `: ${exit.reason}` : ""}`;
6173
+ }
6174
+ const how = exit.signal ? `signal ${exit.signal}` : `code ${exit.code ?? "unknown"}`;
6175
+ return `Agent process exited during startup (${how}): ${exit.reason ?? "no reason found in its log"}`;
6176
+ }
6177
+ function readStartupExitReason(logsDir, pid) {
6178
+ try {
6179
+ const suffix = `-pid-${pid}.log`;
6180
+ const file = readdirSync(logsDir).filter((name) => name.endsWith(suffix)).sort().pop();
6181
+ if (!file) return void 0;
6182
+ const path = join(logsDir, file);
6183
+ const size = statSync(path).size;
6184
+ const length = Math.min(size, TAIL_BYTES);
6185
+ const buffer = Buffer.alloc(length);
6186
+ const fd = openSync(path, "r");
6187
+ try {
6188
+ readSync(fd, buffer, 0, length, size - length);
6189
+ } finally {
6190
+ closeSync(fd);
6191
+ }
6192
+ return extractStartupExitReason(buffer.toString("utf8"));
6193
+ } catch {
6194
+ return void 0;
6195
+ }
6196
+ }
6197
+ function clamp(value) {
6198
+ const line = value.replace(/\s+/g, " ").trim();
6199
+ return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}\u2026` : line;
6200
+ }
6201
+
3667
6202
  function recoverableSessionPid(metadata, liveHappyPids) {
3668
6203
  const pid = metadata?.hostPid;
3669
6204
  return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && liveHappyPids.has(pid) ? pid : null;
@@ -3757,9 +6292,28 @@ function writeReceipt$1(home, receipt) {
3757
6292
 
3758
6293
  const exec = promisify(execFile);
3759
6294
  const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
6295
+ const gitRaw = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 64 * 1024 * 1024 })).stdout;
6296
+ function expandHome$1(path) {
6297
+ if (path === "~") return homedir();
6298
+ if (path.startsWith("~/") || process.platform === "win32" && path.startsWith("~\\")) return join(homedir(), path.slice(2));
6299
+ return path;
6300
+ }
6301
+ async function resolveTeamRepository(home, repository, sourceOf) {
6302
+ const worktrees = resolve(home, "teams", "worktrees");
6303
+ let candidate = expandHome$1(repository);
6304
+ for (let hop = 0; hop < 8; hop++) {
6305
+ if (!isAbsolute(candidate)) break;
6306
+ const teamWorktree = resolve(dirname(candidate)) === worktrees;
6307
+ const top = await git(candidate, ["rev-parse", "--show-toplevel"]).catch(() => null);
6308
+ if (top !== null && (!teamWorktree || resolve(top) === resolve(candidate))) return candidate;
6309
+ const source = teamWorktree ? sourceOf(basename(candidate)) : void 0;
6310
+ if (!source) break;
6311
+ candidate = expandHome$1(source);
6312
+ }
6313
+ 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.`);
6314
+ }
3760
6315
  async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3761
- if (repository === "~") repository = homedir();
3762
- else if (repository.startsWith("~/") || process.platform === "win32" && repository.startsWith("~\\")) repository = join(homedir(), repository.slice(2));
6316
+ repository = expandHome$1(repository);
3763
6317
  if (!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");
3764
6318
  await git(repository, ["rev-parse", "--show-toplevel"]);
3765
6319
  const root = join(home, "teams", "worktrees");
@@ -3778,28 +6332,69 @@ async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3778
6332
  }
3779
6333
  return { directory, repository, branch };
3780
6334
  }
6335
+ async function unpreservedCommits(directory, repository, rev) {
6336
+ const sourceHead = await git(repository, ["rev-parse", "HEAD"]).catch(() => "");
6337
+ const pending = (await git(directory, ["rev-list", rev, "--not", "--remotes", ...sourceHead ? [sourceHead] : []])).split("\n").filter(Boolean);
6338
+ if (pending.length === 0) return 0;
6339
+ return await squashMerged(directory, rev) ? 0 : pending.length;
6340
+ }
6341
+ async function squashMerged(directory, rev) {
6342
+ 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", () => "");
6343
+ if (!target) return false;
6344
+ const base = await git(directory, ["merge-base", rev, target]).catch(() => "");
6345
+ if (!base) return false;
6346
+ const own = patchIds(await gitRaw(directory, ["diff", base, rev]).then((diff) => diff ? patchIdOf(directory, diff) : "", () => ""));
6347
+ if (own.length !== 1) return false;
6348
+ const merged = patchIds(await gitRaw(directory, ["log", "-p", "--no-merges", "--max-count=500", `${base}..${target}`]).then((log) => log ? patchIdOf(directory, log) : "", () => ""));
6349
+ return merged.includes(own[0]);
6350
+ }
6351
+ async function patchIdOf(directory, patch) {
6352
+ return await new Promise((resolvePatch, reject) => {
6353
+ const child = execFile("git", ["-C", directory, "patch-id", "--stable"], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 }, (error, stdout) => error ? reject(error) : resolvePatch(stdout));
6354
+ child.stdin?.end(patch);
6355
+ });
6356
+ }
6357
+ const patchIds = (output) => output.split("\n").filter(Boolean).map((line) => line.split(" ")[0]);
6358
+ async function registeredWorktree(repository, directory) {
6359
+ const list = await git(repository, ["worktree", "list", "--porcelain"]).catch(() => "");
6360
+ return list.split("\n").some((line) => line.startsWith("worktree ") && resolve(line.slice("worktree ".length)) === resolve(directory));
6361
+ }
6362
+ const describeHead = async (directory) => await git(directory, ["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "") || "a detached HEAD";
3781
6363
  async function removeTeamWorktree(resource) {
3782
6364
  const { directory, repository, branch } = resource;
3783
6365
  if (!directory || !repository || !branch) return;
3784
- if (existsSync(directory)) {
3785
- if (await git(directory, ["symbolic-ref", "--short", "HEAD"]) !== branch) throw new Error("Worktree branch changed; preserve for manual reconciliation");
6366
+ let present = existsSync(directory);
6367
+ if (present) {
6368
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => "");
6369
+ if (!top || resolve(top) !== resolve(directory)) {
6370
+ 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`);
6371
+ if (readdirSync(directory).length === 0) rmdirSync(directory);
6372
+ present = false;
6373
+ }
6374
+ }
6375
+ if (present) {
3786
6376
  const actualCommon = await git(directory, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3787
6377
  const expectedCommon = await git(repository, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3788
6378
  if (resolve(actualCommon) !== resolve(expectedCommon)) throw new Error("Worktree repository changed; preserve for manual reconciliation");
3789
- if (await git(directory, ["status", "--porcelain"])) throw new Error(`Uncommitted work retained at ${directory}`);
3790
- await git(repository, ["merge-base", "--is-ancestor", branch, "HEAD"]).catch(() => {
3791
- throw new Error(`Unmerged work retained on ${branch} at ${directory}`);
3792
- });
3793
- await git(repository, ["worktree", "remove", directory]);
6379
+ const dirty = (await git(directory, ["status", "--porcelain"])).split("\n").filter(Boolean).length;
6380
+ 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`);
6381
+ const head = await describeHead(directory);
6382
+ const unsafe = await unpreservedCommits(directory, repository, "HEAD");
6383
+ 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`);
3794
6384
  }
3795
- try {
3796
- await git(repository, ["show-ref", "--verify", `refs/heads/${branch}`]);
3797
- } catch {
3798
- return;
6385
+ const ownBranch = await git(repository, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).then(() => true, () => false);
6386
+ if (ownBranch) {
6387
+ const unsafe = await unpreservedCommits(repository, repository, `refs/heads/${branch}`);
6388
+ 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`);
3799
6389
  }
3800
- await git(repository, ["branch", "-d", branch]);
6390
+ if (present) await git(repository, ["worktree", "remove", directory]);
6391
+ else await git(repository, ["worktree", "prune"]).catch(() => void 0);
6392
+ if (ownBranch) await git(repository, ["branch", "-D", branch]);
3801
6393
  }
3802
6394
 
6395
+ function persistedSpawnMatches(operationId) {
6396
+ return Object.entries(readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === operationId);
6397
+ }
3803
6398
  function createTeamWorker(deps) {
3804
6399
  const home = deps.home ?? configuration.happyHomeDir;
3805
6400
  const server = deps.serverUrl ?? configuration.serverUrl;
@@ -3833,6 +6428,12 @@ function createTeamWorker(deps) {
3833
6428
  if (receipt.phase === "completed") return;
3834
6429
  try {
3835
6430
  if (op.type === "spawn") {
6431
+ if (ownerRetryPending(op, receipt) && (receipt.phase === "prepared" || receipt.phase === "spawning" && persistedSpawnMatches(op.id).length === 0)) {
6432
+ receipt = consumeOwnerRetry(op, receipt);
6433
+ writeReceipt$1(home, receipt);
6434
+ deps.log(`Teams operation ${op.id} relaunch requested by owner`);
6435
+ }
6436
+ if (receipt.phase === "prepared" && spawnGate(receipt, Date.now()) !== "run") return;
3836
6437
  if (receipt.phase === "prepared") {
3837
6438
  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;
3838
6439
  if (!credential) throw new Error("No scoped credential for worker");
@@ -3845,7 +6446,26 @@ function createTeamWorker(deps) {
3845
6446
  return;
3846
6447
  }
3847
6448
  if (!op.directory) throw new Error("No repository selected for worker");
3848
- const resource = await prepareTeamWorktree(home, op.directory, op.id);
6449
+ let resource;
6450
+ try {
6451
+ const repository = await resolveTeamRepository(home, op.directory, (id) => {
6452
+ try {
6453
+ return readReceipt(home, id)?.repository;
6454
+ } catch {
6455
+ return void 0;
6456
+ }
6457
+ });
6458
+ resource = await prepareTeamWorktree(home, repository, op.id);
6459
+ } catch (error) {
6460
+ const now = Date.now();
6461
+ receipt = afterStartupFailure(receipt, now);
6462
+ writeReceipt$1(home, receipt);
6463
+ const detail = error instanceof Error ? error.message : "Team worktree could not be prepared";
6464
+ 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: startupFailureMessage(detail, receipt, now).slice(0, 1e3) }).catch(() => {
6465
+ });
6466
+ deps.log(`Teams operation ${op.id} preflight failed (${receipt.spawnFailures}/${TEAM_SPAWN_MAX_ATTEMPTS})`);
6467
+ return;
6468
+ }
3849
6469
  const scopes = join(home, "teams", "scopes");
3850
6470
  ensurePrivateDirectorySync(scopes);
3851
6471
  const scopeFile = join(scopes, `${op.id}.json`);
@@ -3853,12 +6473,21 @@ function createTeamWorker(deps) {
3853
6473
  receipt = { ...receipt, ...resource, scopeFile, phase: "spawning" };
3854
6474
  writeReceipt$1(home, receipt);
3855
6475
  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 } });
6476
+ if (spawned.type === "error" && spawned.startupExit?.exited) {
6477
+ const now = Date.now();
6478
+ receipt = afterStartupFailure(receipt, now);
6479
+ writeReceipt$1(home, receipt);
6480
+ 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: startupFailureMessage(spawned.errorMessage, receipt, now).slice(0, 1e3) }).catch(() => {
6481
+ });
6482
+ deps.log(`Teams operation ${op.id} startup failed (${receipt.spawnFailures}/${TEAM_SPAWN_MAX_ATTEMPTS}); ${receipt.retryAt !== void 0 ? "will relaunch" : "waiting for owner retry"}`);
6483
+ return;
6484
+ }
3856
6485
  if (spawned.type !== "success") throw new Error(spawned.type === "error" ? spawned.errorMessage : "Directory approval required");
3857
6486
  receipt = { ...receipt, sessionId: spawned.sessionId, phase: "spawned" };
3858
6487
  writeReceipt$1(home, receipt);
3859
6488
  }
3860
6489
  if (receipt.phase === "spawning") {
3861
- const matches = Object.entries(readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === op.id);
6490
+ const matches = persistedSpawnMatches(op.id);
3862
6491
  if (matches.length !== 1) throw new Error("Spawn outcome unknown; reconcile the worker before retrying");
3863
6492
  receipt = { ...receipt, sessionId: matches[0][0], phase: "spawned" };
3864
6493
  writeReceipt$1(home, receipt);
@@ -3880,6 +6509,12 @@ function createTeamWorker(deps) {
3880
6509
  }
3881
6510
  await complete(op, receipt);
3882
6511
  } else {
6512
+ if (ownerRetryPending(op, receipt)) {
6513
+ const { retryAt: _retryAt, ...rest } = receipt;
6514
+ receipt = { ...rest, retryConsumed: op.retryRequestedAt };
6515
+ writeReceipt$1(home, receipt);
6516
+ deps.log(`Teams operation ${op.id} cleanup retry requested by owner`);
6517
+ } else if (receipt.retryAt !== void 0 && Date.now() < receipt.retryAt) return;
3883
6518
  const team = (await http.get(`/v1/teams/${encodeURIComponent(op.teamId)}`)).data.team;
3884
6519
  const latest = team.operations.find((candidate) => candidate.id === op.id);
3885
6520
  if (latest?.status === "completed") {
@@ -3906,7 +6541,14 @@ function createTeamWorker(deps) {
3906
6541
  } catch (error) {
3907
6542
  const unknown = op.type === "spawn" && receipt.phase === "spawning";
3908
6543
  const detail = error instanceof Error ? error.message : "Team operation failed";
3909
- 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(() => {
6544
+ if (op.type === "stop") {
6545
+ receipt = { ...receipt, retryAt: Date.now() + TEAM_CLEANUP_RETRY_MS };
6546
+ try {
6547
+ writeReceipt$1(home, receipt);
6548
+ } catch {
6549
+ }
6550
+ }
6551
+ await action(op.teamId, `failure-${op.id}-${receipt.phase}-${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(() => {
3910
6552
  });
3911
6553
  deps.log(`Teams operation ${op.id} ${unknown ? "needs reconciliation" : "will retry"}`);
3912
6554
  }
@@ -4551,6 +7193,7 @@ ${action.prompt}`, { localId: `automation-${run.id}` });
4551
7193
  }
4552
7194
  persist({ runId: run.id, automationId: automation.id, kind: "spawn", phase: "running", claimId: run.claimId, sessionId: spawned.sessionId, stickyKey, ...action.worktree ? { directory } : {} });
4553
7195
  const item = track(claimed, "spawn", spawned.sessionId);
7196
+ if (automation.projectId && deps.joinProject) await deps.joinProject(spawned.sessionId, automation.projectId).catch(() => void 0);
4554
7197
  try {
4555
7198
  const capabilities = readPersistedSessions()[spawned.sessionId]?.metadata?.capabilities ?? null;
4556
7199
  const meta = resolveFirstMessageMeta({ agent, permissionMode, explicitModel: action.model ?? void 0, capabilities });
@@ -4780,6 +7423,7 @@ async function preflightNewBundle(bundlePath) {
4780
7423
  }
4781
7424
  }
4782
7425
  const HANDOVER_PREFLIGHT_TIMEOUT_MS = 3e4;
7426
+ const SPAWN_WEBHOOK_TIMEOUT_MS = 15e3;
4783
7427
  async function startDaemon() {
4784
7428
  const initialMachineMetadata = getInitialMachineMetadata();
4785
7429
  const startupCliAvailability = getStartupCliAvailability();
@@ -4911,6 +7555,7 @@ async function startDaemon() {
4911
7555
  const sessionIdToFinishedSession = /* @__PURE__ */ new Map();
4912
7556
  let teamWorker;
4913
7557
  let automationRunner;
7558
+ let projectPresence;
4914
7559
  const persisted = readPersistedSessions();
4915
7560
  const liveHappyProcesses = await findAllHappyProcesses();
4916
7561
  for (const [id, s] of Object.entries(persisted)) {
@@ -5000,6 +7645,7 @@ async function startDaemon() {
5000
7645
  }
5001
7646
  };
5002
7647
  const assistantSpawnGate = createSpawnGate();
7648
+ const projectsClient = createProjectsClient({ token: async () => credentials.token });
5003
7649
  const spawnSession = async (options) => {
5004
7650
  const timer = createSpawnTimer();
5005
7651
  await refreshAgentHomes(Date.now(), { allowStale: true });
@@ -5011,6 +7657,10 @@ async function startDaemon() {
5011
7657
  result = await (options.forceNew ? assistantSpawnGate.replace(() => spawnSessionImpl(options, timer)) : assistantSpawnGate.join(() => spawnSessionImpl(options, timer)));
5012
7658
  }
5013
7659
  logger.debug(timer.format({ agent: options.agent ?? "claude", outcome: result.type }));
7660
+ if (result.type === "success" && options.parentSessionId) {
7661
+ const outcome = await joinProject(projectsClient, result.sessionId, { kind: "lineage", parentSessionId: options.parentSessionId });
7662
+ if (outcome.joined) logger.debug(`[DAEMON RUN] fork ${result.sessionId} joined project ${outcome.projectId} (lineage)`);
7663
+ }
5014
7664
  return result;
5015
7665
  };
5016
7666
  const currentCliAvailability = () => apiMachineRef?.getCLIAvailability() ?? startupCliAvailability;
@@ -5430,22 +8080,33 @@ async function startDaemon() {
5430
8080
  });
5431
8081
  logger.debug(`[DAEMON RUN] Waiting for session webhook for PID ${happyProcess.pid}`);
5432
8082
  return new Promise((resolve) => {
8083
+ const pid = happyProcess.pid;
8084
+ let settled = false;
8085
+ const fail = (startupExit) => {
8086
+ if (settled) return;
8087
+ settled = true;
8088
+ clearTimeout(timeout);
8089
+ pidToAwaiter.delete(pid);
8090
+ startupExit.reason ??= readStartupExitReason(configuration.logsDir, pid);
8091
+ const errorMessage = describeStartupExit(startupExit, SPAWN_WEBHOOK_TIMEOUT_MS);
8092
+ logger.debug(`[DAEMON RUN] Spawn of PID ${pid} failed: ${errorMessage}`);
8093
+ resolve({ type: "error", errorMessage, startupExit });
8094
+ };
8095
+ happyProcess.once("exit", (code, signal) => fail({ exited: true, code, signal }));
5433
8096
  const timeout = setTimeout(() => {
5434
- pidToAwaiter.delete(happyProcess.pid);
5435
- logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${happyProcess.pid}`);
5436
- if (happyProcess.pid) {
5437
- try {
5438
- terminateProcess(happyProcess.pid, () => {
5439
- });
5440
- } catch {
5441
- }
8097
+ if (settled) return;
8098
+ pidToAwaiter.delete(pid);
8099
+ logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${pid}`);
8100
+ try {
8101
+ const started = terminateProcess(pid, (stopped) => fail({ exited: stopped, code: null, signal: null, timedOut: true }));
8102
+ if (!started) fail({ exited: false, code: null, signal: null, timedOut: true });
8103
+ } catch {
8104
+ fail({ exited: false, code: null, signal: null, timedOut: true });
5442
8105
  }
5443
- resolve({
5444
- type: "error",
5445
- errorMessage: `Session webhook timeout for PID ${happyProcess.pid}`
5446
- });
5447
- }, 15e3);
5448
- pidToAwaiter.set(happyProcess.pid, (completedSession) => {
8106
+ }, SPAWN_WEBHOOK_TIMEOUT_MS);
8107
+ pidToAwaiter.set(pid, (completedSession) => {
8108
+ if (settled) return;
8109
+ settled = true;
5449
8110
  clearTimeout(timeout);
5450
8111
  logger.debug(`[DAEMON RUN] Session ${completedSession.happySessionId} fully spawned with webhook`);
5451
8112
  resolve({
@@ -5570,8 +8231,8 @@ async function startDaemon() {
5570
8231
  });
5571
8232
  let freshConversation = false;
5572
8233
  if (!precheck.ok) {
5573
- if (precheck.reason === "conversation-missing") {
5574
- logger.debug(`[DAEMON RUN] resume: transcript for ${happySessionId} is gone (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
8234
+ if (resumeStartsFreshConversation(precheck.reason)) {
8235
+ logger.debug(`[DAEMON RUN] resume: ${precheck.reason} for ${happySessionId} (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
5575
8236
  freshConversation = true;
5576
8237
  } else {
5577
8238
  return { type: "error", errorMessage: `resume-precheck:${precheck.reason}: ${precheck.detail}` };
@@ -5584,9 +8245,10 @@ async function startDaemon() {
5584
8245
  const model = sanitizeResumeModel(options?.model);
5585
8246
  if (model) launch.args.push("--model", model);
5586
8247
  else if (options?.model !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid model ${JSON.stringify(options.model)}`);
5587
- const permissionMode = sanitizeSpawnPermissionMode(options?.permissionMode);
8248
+ const requestedMode = options?.permissionMode ?? (options?.keepPublishedPermissionMode ? publishedRelaunchPermissionMode(metadata) : void 0);
8249
+ const permissionMode = sanitizeSpawnPermissionMode(requestedMode);
5588
8250
  if (permissionMode) launch.args.push("--permission-mode", permissionMode);
5589
- else if (options?.permissionMode !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(options.permissionMode)}`);
8251
+ else if (requestedMode !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(requestedMode)}`);
5590
8252
  const result = await spawnTrackedHappyProcess({
5591
8253
  args: launch.args,
5592
8254
  cwd: launch.cwd,
@@ -5641,7 +8303,7 @@ async function startDaemon() {
5641
8303
  resolve();
5642
8304
  }
5643
8305
  };
5644
- const requested = terminateProcess(pid, () => {
8306
+ const requested = terminateProcessTree(pid, () => {
5645
8307
  const tracked = pidToTrackedSession.get(pid);
5646
8308
  if (tracked) {
5647
8309
  if (tracked.happySessionId && tracked.encryption) {
@@ -5757,7 +8419,7 @@ async function startDaemon() {
5757
8419
  logger.debug(`[DAEMON RUN] Attempting to stop session ${sessionId}`);
5758
8420
  for (const [pid, session] of pidToTrackedSession.entries()) {
5759
8421
  if (session.happySessionId === sessionId || sessionId.startsWith("PID-") && pid === parseInt(sessionId.replace("PID-", ""))) {
5760
- const requested = terminateProcess(pid, (stopped) => {
8422
+ const requested = terminateProcessTree(pid, (stopped) => {
5761
8423
  if (!stopped) {
5762
8424
  logger.debug(`[DAEMON RUN] Session ${sessionId} survived SIGTERM and SIGKILL attempts`);
5763
8425
  return;
@@ -6013,6 +8675,15 @@ async function startDaemon() {
6013
8675
  setStore: (store) => claudeAuthService.setStore(store)
6014
8676
  });
6015
8677
  claudeAuthService.start();
8678
+ apiMachine.setModelConfigService(new ModelConfigService({
8679
+ home: os.homedir(),
8680
+ env: process.env,
8681
+ happyHomeDir: configuration.happyHomeDir,
8682
+ isInstalled: commandOnPath,
8683
+ onChanged: (harness) => {
8684
+ if (harness === "claude") void claudeAuthService.probe("model-config", true);
8685
+ }
8686
+ }));
6016
8687
  apiMachine.setAgentHibernationHandlers(resolveIdleMs(agentHibernationSetting), async (requested) => {
6017
8688
  const value = requested <= 0 ? 0 : settingIdleMs(requested);
6018
8689
  await updateSettings((current) => ({ ...current, agentHibernationIdleMs: value }));
@@ -6020,6 +8691,12 @@ async function startDaemon() {
6020
8691
  daemonHibernation.invalidateBindings();
6021
8692
  return resolveIdleMs(agentHibernationSetting);
6022
8693
  });
8694
+ const webPanelsSync = startWebPanelsSync({
8695
+ statMtime: async () => (await fs.stat(configuration.settingsFile).catch(() => null))?.mtimeMs ?? null,
8696
+ readRaw: async () => (await readSettings()).webPanels,
8697
+ publish: (panels) => apiMachine.setWebPanels(panels),
8698
+ logProblems: (problems) => 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("; ")}`)
8699
+ });
6023
8700
  apiMachine.connect();
6024
8701
  if (identityConflict?.confidence === "weak") {
6025
8702
  void apiMachine.updateMachineMetadata((current) => ({
@@ -6127,6 +8804,7 @@ async function startDaemon() {
6127
8804
  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");
6128
8805
  teamWorker?.stop();
6129
8806
  automationRunner?.stop();
8807
+ projectPresence?.stop();
6130
8808
  clearInterval(restartOnStaleVersionAndHeartbeat);
6131
8809
  clearInterval(cliUpdateInterval);
6132
8810
  stopAgentVersionChecks();
@@ -6196,24 +8874,42 @@ async function startDaemon() {
6196
8874
  return !!record && typeof record.hibernatedAt === "number" && record.hibernatedAt >= record.savedAt;
6197
8875
  },
6198
8876
  wakeHibernated: async (id) => {
6199
- const result = await resumeSession(id);
8877
+ const result = await resumeSession(id, { keepPublishedPermissionMode: true });
6200
8878
  if (result.type !== "success") return false;
6201
8879
  return waitForSessionLive(id, (sid) => [...pidToTrackedSession.values()].some((s) => s.happySessionId === sid && isPidAlive(s.pid)));
6202
8880
  },
8881
+ joinProject: (sessionId, projectId) => joinProject(projectsClient, sessionId, { kind: "explicit", projectId }, { via: "automation" }),
8882
+ log: (message) => logger.debug(`[DAEMON RUN] ${message}`)
8883
+ });
8884
+ projectPresence = createProjectPresenceReporter({
8885
+ machineId,
8886
+ client: projectsClient,
8887
+ live: () => [...pidToTrackedSession.values()].filter((s) => s.happySessionId && isPidAlive(s.pid)).map((s) => ({
8888
+ sessionId: s.happySessionId,
8889
+ flavor: s.happySessionMetadataFromLocalWebhook?.flavor ?? null,
8890
+ branch: s.happySessionMetadataFromLocalWebhook?.worktree?.branch ?? null,
8891
+ running: turnActivity.activeSessions().includes(s.happySessionId)
8892
+ })),
6203
8893
  log: (message) => logger.debug(`[DAEMON RUN] ${message}`)
6204
8894
  });
6205
8895
  void apiMachine.updateMachineMetadata((current) => ({
6206
8896
  ...current ?? initialMachineMetadata,
6207
8897
  teamsVersion: 1,
6208
8898
  teamLaunchVersion: 1,
8899
+ // B-689: this daemon acts on the owner's retry-operation (web gates「重试启动」).
8900
+ teamRetryVersion: TEAM_RETRY_CAPABILITY_VERSION,
6209
8901
  // B-586: this daemon serves the worktree-* RPCs (web gates 「在新 worktree 中」 on it).
6210
- worktreeVersion: WORKTREE_CAPABILITY_VERSION
8902
+ worktreeVersion: WORKTREE_CAPABILITY_VERSION,
8903
+ // B-688: this daemon serves the model-config-* RPCs (web gates 「模型与 Provider」 on it).
8904
+ modelConfigVersion: MODEL_CONFIG_CAPABILITY_VERSION
6211
8905
  })).catch(() => logger.debug("[DAEMON RUN] Teams capability publication will retry on reconnect"));
6212
8906
  const cleanupAndShutdown = async (source, errorMessage) => {
8907
+ webPanelsSync.stop();
6213
8908
  logger.debug(`[DAEMON RUN] Starting proper cleanup (source: ${source}, errorMessage: ${errorMessage})...`);
6214
8909
  const scrollbackFlush = apiMachine.flushTerminalScrollback();
6215
8910
  teamWorker?.stop();
6216
8911
  automationRunner?.stop({ killScripts: true });
8912
+ projectPresence?.stop();
6217
8913
  currentWorktreeService()?.stopAll();
6218
8914
  if (restartOnStaleVersionAndHeartbeat) {
6219
8915
  clearInterval(restartOnStaleVersionAndHeartbeat);