very-happy-cli 0.2.179 → 0.2.181

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 (214) hide show
  1. package/dist/{AcpBackend-DFipFF7-.cjs → AcpBackend-CgHb_ya5.cjs} +3 -3
  2. package/dist/{AcpBackend-CHp3y7cb.mjs → AcpBackend-DZGCSuXF.mjs} +3 -3
  3. package/dist/{AcpSessionManager-0zpvRJXc.cjs → AcpSessionManager-CacC2EVn.cjs} +1 -1
  4. package/dist/{AcpSessionManager-d2-rKWWa.mjs → AcpSessionManager-DwuPzWBh.mjs} +1 -1
  5. package/dist/{BasePermissionHandler-CH3zuEkA.cjs → BasePermissionHandler-DCP8ZEB4.cjs} +1 -1
  6. package/dist/{BasePermissionHandler-DdZBYIR4.mjs → BasePermissionHandler-Uo-GUjbb.mjs} +1 -1
  7. package/dist/{acpSessionResume-DTGmAPLt.mjs → acpSessionResume-9OLTD6kT.mjs} +1 -1
  8. package/dist/{acpSessionResume-oiCBnAVA.cjs → acpSessionResume-BaVMD80f.cjs} +1 -1
  9. package/dist/{agentHome-CghLvL_1.mjs → agentHome-B1BsKeqD.mjs} +4 -4
  10. package/dist/{agentHome-BWcz8mz0.cjs → agentHome-BtUmGcPX.cjs} +4 -4
  11. package/dist/{api-Cmjfr8Z7.cjs → api-COHFAkb_.cjs} +20 -12
  12. package/dist/{api-CzwFpJQc.mjs → api-Dr3wXL_7.mjs} +21 -13
  13. package/dist/{apiMachine-DJkTEiqy.mjs → apiMachine-CHEzPQdS.mjs} +73 -32
  14. package/dist/{apiMachine-G6OogT08.cjs → apiMachine-D8H7CXaz.cjs} +75 -34
  15. package/dist/{attachmentContent-B2os4HbA.mjs → attachmentContent-1YwtKgWl.mjs} +2 -2
  16. package/dist/{attachmentContent-Bo0UAsSu.cjs → attachmentContent-mIhbtRKl.cjs} +2 -2
  17. package/dist/{auth-DMX0xPNK.mjs → auth-CbZkcMAb.mjs} +8 -8
  18. package/dist/{auth-D6bBUwZa.cjs → auth-CgQP7d0q.cjs} +5 -5
  19. package/dist/{auth-BS6PaOOG.mjs → auth-DZsthtSk.mjs} +5 -5
  20. package/dist/{auth-HEhRaNgL.cjs → auth-Fg8fLadK.cjs} +8 -8
  21. package/dist/{auto-C6I55iOh.cjs → auto-BB7kqSh5.cjs} +19 -19
  22. package/dist/{auto-Cl1SEDcD.mjs → auto-_T-Ud-z5.mjs} +19 -19
  23. package/dist/{backgroundTaskActivity-BVwJBl02.mjs → backgroundTaskActivity-8PdPxrvy.mjs} +1 -1
  24. package/dist/{bootstrap-iuyufnp3.mjs → bootstrap-B6EkZh4u.mjs} +2 -2
  25. package/dist/{bootstrap-exVucYav.cjs → bootstrap-CYtOtbi7.cjs} +2 -2
  26. package/dist/{browser-CSYum7xH.mjs → browser-C2qhUHSE.mjs} +1 -1
  27. package/dist/{browser-BohJK12g.cjs → browser-DjNNQQk2.cjs} +1 -1
  28. package/dist/{claudeCliPath-U4HHmV4r.cjs → claudeCliPath-GaP3UUz1.cjs} +1 -1
  29. package/dist/{claudeLocal-Dq_R3Ax_.mjs → claudeLocal-BAFjWhZ8.mjs} +6 -6
  30. package/dist/{claudeLocal-re4yjSTx.cjs → claudeLocal-O_w7-fBh.cjs} +8 -8
  31. package/dist/{claudeLocalLauncher-CN67lN7-.mjs → claudeLocalLauncher-CWn30LZR.mjs} +11 -11
  32. package/dist/{claudeLocalLauncher-B4hJHpCA.cjs → claudeLocalLauncher-Df3zg1q0.cjs} +13 -13
  33. package/dist/{claudeSessionFork-BihfD0Ik.mjs → claudeSessionFork-2ZkSTOGn.mjs} +1 -1
  34. package/dist/{claudeSessionFork-DiSMYerV.cjs → claudeSessionFork-pwcKqB-e.cjs} +1 -1
  35. package/dist/{client-BhoEBnuN.mjs → client-BKyU66lg.mjs} +2 -2
  36. package/dist/{client-BKcK1Bi-.cjs → client-CUO3ItoB.cjs} +34 -8
  37. package/dist/{client-wo9nbxuf.mjs → client-CXOnzuOy.mjs} +2 -2
  38. package/dist/{client-ZjOsn6nZ.cjs → client-DWs6k041.cjs} +2 -2
  39. package/dist/{client-CuVdN6PP.cjs → client-D_U2VjO3.cjs} +2 -2
  40. package/dist/{client-DuTDwWSQ.mjs → client-DsQcxVUV.mjs} +34 -9
  41. package/dist/codex/happyMcpStdioBridge.cjs +17 -17
  42. package/dist/codex/happyMcpStdioBridge.mjs +18 -18
  43. package/dist/{codexAppServerClient-Dt5zxrun.cjs → codexAppServerClient-BRX3JZ_5.cjs} +3 -3
  44. package/dist/{codexAppServerClient-BK3zra_1.mjs → codexAppServerClient-C3JO3pwM.mjs} +3 -3
  45. package/dist/{codexCommand-B6pY7CMh.mjs → codexCommand-BZIAAqKS.mjs} +59 -51
  46. package/dist/{codexCommand-CAZ1SLjg.cjs → codexCommand-dKOc5iQl.cjs} +85 -77
  47. package/dist/{codexTermination-DmGbHxcD.cjs → codexTermination-BVR9HeVI.cjs} +7 -2
  48. package/dist/{codexTermination-Cd1Eon_4.mjs → codexTermination-ztFkwHrG.mjs} +7 -2
  49. package/dist/{config-2oMG_fEI.mjs → config-NbHjx8ge.mjs} +3 -3
  50. package/dist/{config-B0uK6K7n.cjs → config-cftYxLC7.cjs} +26 -26
  51. package/dist/{configuration-WMi4idBB.mjs → configuration-BPrfb17M.mjs} +1 -1
  52. package/dist/{configuration-CMHZnp6G.cjs → configuration-C8JgseHy.cjs} +1 -1
  53. package/dist/{connect-uaglGrde.cjs → connect-Br8VMrK1.cjs} +27 -27
  54. package/dist/{connect-BLVHhHzA.mjs → connect-CLD1ai0k.mjs} +14 -14
  55. package/dist/{context-DXzU5bFM.cjs → context-D1lgQTJC.cjs} +1 -1
  56. package/dist/{context-DploEcoN.mjs → context-_YGq8xdH.mjs} +1 -1
  57. package/dist/{controlClient-BWUJrj3t.mjs → controlClient-CkNpT5zS.mjs} +4 -4
  58. package/dist/{controlClient-C-5qCt8W.cjs → controlClient-D68Zj7Q-.cjs} +3 -3
  59. package/dist/{createSessionMetadata-3uXrJgOW.mjs → createSessionMetadata-3WAj3_xl.mjs} +2 -2
  60. package/dist/{createSessionMetadata-BkIzHALd.cjs → createSessionMetadata-DNIbKLHg.cjs} +3 -3
  61. package/dist/{defaultPermissionMode-pS3vmiSg.cjs → defaultPermissionMode-BmvjP32v.cjs} +2 -2
  62. package/dist/{defaultPermissionMode-BzxLh20a.mjs → defaultPermissionMode-DXMznl8v.mjs} +2 -2
  63. package/dist/{detectCLI-DR9ZaN6B.cjs → detectCLI-BuYR_Qxe.cjs} +4 -4
  64. package/dist/{deterministicJson-B8z2GPi9.cjs → deterministicJson-BS7D7URE.cjs} +89 -24
  65. package/dist/{deterministicJson-D_whDMFd.mjs → deterministicJson-BcBIKKf1.mjs} +87 -24
  66. package/dist/{doctor-Br1Kcy2J.cjs → doctor-Be7zC0AF.cjs} +10 -9
  67. package/dist/{doctor-CmtSsR2-.mjs → doctor-CoOaPq6w.mjs} +8 -8
  68. package/dist/{doctorReadiness-BCZGcN0a.cjs → doctorReadiness-Dl6yRQCy.cjs} +1 -1
  69. package/dist/{downloadTarget-BoNwTIH_.mjs → downloadTarget-CeaAXdJj.mjs} +6 -6
  70. package/dist/{downloadTarget-BQJK_6oH.cjs → downloadTarget-LyOiucn_.cjs} +6 -6
  71. package/dist/{ensureDaemonRunning-Czo9IHJQ.mjs → ensureDaemonRunning--98j7-17.mjs} +5 -5
  72. package/dist/{ensureDaemonRunning-BRUmsq6J.cjs → ensureDaemonRunning-B8z37VKD.cjs} +6 -6
  73. package/dist/fileStore-5qpetZS0.mjs +146 -0
  74. package/dist/fileStore-7qhnbs6N.cjs +152 -0
  75. package/dist/{handleResumeCommand-tKD_Hpxc.cjs → handleResumeCommand-BFZlrFVH.cjs} +7 -7
  76. package/dist/{handleResumeCommand-C8thKjqf.mjs → handleResumeCommand-gO8I4keP.mjs} +6 -6
  77. package/dist/{index-DMqDMT1Q.cjs → index-B5PXbZjW.cjs} +80 -62
  78. package/dist/{index-D09T1m8Y.cjs → index-BRMq9gOe.cjs} +3 -3
  79. package/dist/{index-B0UjHlAe.cjs → index-BkluinoS.cjs} +4 -4
  80. package/dist/{index-CdQI0C9p.mjs → index-CO0n9ue6.mjs} +4 -4
  81. package/dist/{index-DPOa4NhL.mjs → index-CeRXrGnH.mjs} +41 -6
  82. package/dist/{index-C6O2vVjm.cjs → index-Df2eHm3O.cjs} +42 -6
  83. package/dist/{index-BTxHphpV.mjs → index-DneHoQXf.mjs} +80 -62
  84. package/dist/{index-BiyC7cZ3.mjs → index-WUj3954m.mjs} +4 -4
  85. package/dist/{index-D3bidoG8.mjs → index-hQ8LP1C2.mjs} +3 -3
  86. package/dist/{index-CUuc6iCn.cjs → index-jF2t3ACW.cjs} +4 -4
  87. package/dist/index.cjs +2 -2
  88. package/dist/index.mjs +2 -2
  89. package/dist/{install-BX3lv3NO.mjs → install-D0inLCv-.mjs} +1 -1
  90. package/dist/{install-BXvf2E3o.cjs → install-D2NCbeJ-.cjs} +1 -1
  91. package/dist/{install-hnve_9vq.mjs → install-DkYFiVK4.mjs} +3 -3
  92. package/dist/{install-CYRZxS87.cjs → install-FqkSUjPC.cjs} +7 -7
  93. package/dist/{installPiTools-BKnXjrVu.cjs → installPiTools-CL_axh_6.cjs} +1 -1
  94. package/dist/{installTerminalHooks-BQZbvxsZ.cjs → installTerminalHooks-BETLKAtd.cjs} +3 -3
  95. package/dist/lib.cjs +13 -13
  96. package/dist/lib.d.cts +216 -2
  97. package/dist/lib.d.mts +216 -2
  98. package/dist/lib.mjs +13 -13
  99. package/dist/{lidState-Bb8fgXg3.mjs → lidState-DghbfRbr.mjs} +1 -1
  100. package/dist/{lidState-Dv2wwFTj.cjs → lidState-x8cJ8J_9.cjs} +1 -1
  101. package/dist/{localHappyAgentAuth-DjYvkXvV.cjs → localHappyAgentAuth-DZ2kb9uq.cjs} +1 -1
  102. package/dist/{localHappyAgentAuth-NEU7fax7.mjs → localHappyAgentAuth-IKmeRpuQ.mjs} +1 -1
  103. package/dist/{logger-C1GWx3gi.cjs → logger-DgBwUSgS.cjs} +2 -2
  104. package/dist/{logger-BtVhHnD8.mjs → logger-LFr8iPgl.mjs} +2 -2
  105. package/dist/machineMetadata-BglCsfvf.mjs +75 -0
  106. package/dist/machineMetadata-DB03ez4K.cjs +87 -0
  107. package/dist/{main-CWhSsbtU.cjs → main-YQ-Vkakw.cjs} +99 -132
  108. package/dist/{main-B2LWV8DI.mjs → main-_1LSzlLv.mjs} +93 -126
  109. package/dist/{mcp-CARUsXHV.cjs → mcp-BIY80jSc.cjs} +15 -15
  110. package/dist/{mcp-ext92q3Y.mjs → mcp-Csj-mT5Y.mjs} +15 -15
  111. package/dist/{mirrorProtocol-DEy2g1CB.cjs → mirrorProtocol-BphKIAK9.cjs} +15 -6
  112. package/dist/{mirrorProtocol-BwYibqry.mjs → mirrorProtocol-CAxOMBkb.mjs} +15 -6
  113. package/dist/{package-BPPebGQF.mjs → package-DYGwlmXl.mjs} +9 -8
  114. package/dist/{package-SgqTYsjn.cjs → package-NoD8QOOM.cjs} +9 -8
  115. package/dist/{panels-BZ0_Tt7B.mjs → panels-B8zRm7_d.mjs} +5 -5
  116. package/dist/{panels-D1c7q2dD.cjs → panels-DYEc1NyQ.cjs} +5 -5
  117. package/dist/{peerTools-CWKzcQ7u.mjs → peerTools-CK3JYu1k.mjs} +5 -5
  118. package/dist/{peerTools-DRQETXaz.cjs → peerTools-CP-x-Peu.cjs} +5 -5
  119. package/dist/{persistence-BegE7NPa.cjs → persistence-BY-D00wT.cjs} +2 -2
  120. package/dist/{persistence-Cr-wutZ4.mjs → persistence-D2Djrf7t.mjs} +2 -2
  121. package/dist/pi-CqyoZMjI.mjs +380 -0
  122. package/dist/pi-DlsrPCTa.cjs +400 -0
  123. package/dist/{piRunnerArgs-DwvM_yWA.mjs → piRunnerArgs-IZLoL7TG.mjs} +1 -1
  124. package/dist/{piRunnerArgs-Cs-378Vz.cjs → piRunnerArgs-gxLYIZH4.cjs} +1 -1
  125. package/dist/{piRuntime-Bue5mnlc.mjs → piRuntime-D7Y4oHVL.mjs} +2 -2
  126. package/dist/{piRuntime-BG-1td_n.cjs → piRuntime-o5L8uX-W.cjs} +2 -2
  127. package/dist/{piTerminal-G4z-xVyy.cjs → piTerminal-C_-JDkLN.cjs} +18 -18
  128. package/dist/{piTerminal-B5x9X5yV.mjs → piTerminal-Kphx8Uhw.mjs} +18 -18
  129. package/dist/projectPath-C3ioB4Bu.cjs +13 -0
  130. package/dist/{prompt-lgF9IE82.cjs → prompt-Bof2aQkI.cjs} +7 -2
  131. package/dist/{prompt-BOouDaTM.mjs → prompt-QHuFx9j6.mjs} +7 -2
  132. package/dist/{pushNotifications-DaLQUyi0.cjs → pushNotifications-BXoOSq_G.cjs} +14 -4
  133. package/dist/{pushNotifications-BdFjDjQe.mjs → pushNotifications-DXGIhE-A.mjs} +14 -4
  134. package/dist/{query-DYP_W1wp.mjs → query-CcA6DVZK.mjs} +1 -1
  135. package/dist/{query-Ctfg-5gy.cjs → query-CdCxzuaB.cjs} +1 -1
  136. package/dist/{rateLimitWindows-Dj_8voBK.cjs → rateLimitWindows-OpAmdOtC.cjs} +1 -1
  137. package/dist/{rateLimitWindows-CuEqk_0g.mjs → rateLimitWindows-ZtHZHe-l.mjs} +1 -1
  138. package/dist/{registerCommonHandlers-Cj084Sg7.cjs → registerCommonHandlers-CRjBoJLK.cjs} +30 -30
  139. package/dist/{registerCommonHandlers-BAlP7SGc.mjs → registerCommonHandlers-DF6bdDtd.mjs} +2 -2
  140. package/dist/{registerKillSessionHandler-qMju0ZfF.cjs → registerKillSessionHandler-7fOm6ooh.cjs} +6 -6
  141. package/dist/{registerKillSessionHandler-PD0jWtQo.mjs → registerKillSessionHandler-DDCKL3wf.mjs} +6 -6
  142. package/dist/{remoteSessionClient-Bn2qu5C5.mjs → remoteSessionClient-B2POSKFT.mjs} +5 -5
  143. package/dist/{remoteSessionClient-B7i7MkYV.cjs → remoteSessionClient-CFCn42bs.cjs} +5 -5
  144. package/dist/{reportProgressTool-gHItlSzz.mjs → reportProgressTool-tPxEvh6x.mjs} +4 -4
  145. package/dist/{reportProgressTool-CM1JFAHg.cjs → reportProgressTool-th4trcET.cjs} +4 -4
  146. package/dist/{resources-CvIlkzpP.cjs → resources-BPyN59Iv.cjs} +23 -2
  147. package/dist/{resources-y9jfyO-_.mjs → resources-CH1iP6Cv.mjs} +22 -3
  148. package/dist/{run-CNXwIe0A.cjs → run-C_FumCQk.cjs} +2767 -183
  149. package/dist/{run-BM4TxiyN.mjs → run-cKQBbVi4.mjs} +2762 -178
  150. package/dist/{runClaude-C_3I8hvR.mjs → runClaude-CYnM6krL.mjs} +34 -28
  151. package/dist/{runClaude-CWhj2V4Q.cjs → runClaude-z_2YC_aa.cjs} +35 -29
  152. package/dist/{runClaudeDeps-B81cOKnH.cjs → runClaudeDeps-CLubzWnA.cjs} +59 -122
  153. package/dist/{runClaudeDeps-QGrOeDe2.mjs → runClaudeDeps-duS06Pb4.mjs} +52 -114
  154. package/dist/{runGemini-BEdWEZLR.mjs → runGemini-C_Pc2EhH.mjs} +39 -37
  155. package/dist/{runGemini-CgRLYbt5.cjs → runGemini-vEoXV6qT.cjs} +67 -65
  156. package/dist/{runOpenClaw-C1NVmzOL.cjs → runOpenClaw-CXJCtMgB.cjs} +20 -20
  157. package/dist/{runOpenClaw-DdQZAYj1.mjs → runOpenClaw-Cxun1qLC.mjs} +19 -19
  158. package/dist/{sandbox-nocIjliq.cjs → sandbox-CO46H2tK.cjs} +4 -4
  159. package/dist/{sandbox-DjQUdCMG.mjs → sandbox-CsvPnTmz.mjs} +4 -4
  160. package/dist/{selfCheck-DCt4Uzbq.cjs → selfCheck-DIr7Gc0i.cjs} +39 -39
  161. package/dist/selfCheck-NamtBHVB.mjs +85 -0
  162. package/dist/{send-Ct7X4pPU.mjs → send-DMoFg6F1.mjs} +9 -9
  163. package/dist/{send-Dydf_hwZ.cjs → send-X2mfVEyr.cjs} +8 -8
  164. package/dist/{server-CosABFbd.cjs → server-BwTEdbkr.cjs} +6 -6
  165. package/dist/{server-DTQGZMxh.mjs → server-CkqQ0sRH.mjs} +4 -4
  166. package/dist/sessionExitLifecycle-CzkLIgNZ.mjs +142 -0
  167. package/dist/sessionExitLifecycle-DFltxXU8.cjs +148 -0
  168. package/dist/{sessionLock-DokGab2R.cjs → sessionLock-CdIRJlHH.cjs} +25 -5
  169. package/dist/{sessionLock-WYIyaVO4.mjs → sessionLock-JIfwCqMk.mjs} +24 -5
  170. package/dist/{sessionOps-S-qPBLFf.cjs → sessionOps-DVA-00nR.cjs} +4 -4
  171. package/dist/{sessionOps-BIGgRube.mjs → sessionOps-DqlftXxe.mjs} +5 -5
  172. package/dist/{sessionScanner-o5hnMi5e.mjs → sessionScanner-BI0Vo1xT.mjs} +3 -3
  173. package/dist/{sessionScanner-CIMM2hvZ.cjs → sessionScanner-BMwgGAhY.cjs} +3 -3
  174. package/dist/{sessions-BJHEZpi2.mjs → sessions-D6IimX7b.mjs} +11 -11
  175. package/dist/{sessions-JchI1w3z.cjs → sessions-DjgEcHaT.cjs} +10 -10
  176. package/dist/{setupOfflineReconnection-CNiAt5ZP.cjs → setupOfflineReconnection-CjuCiKY3.cjs} +2 -2
  177. package/dist/{setupOfflineReconnection-DMiBO2y9.mjs → setupOfflineReconnection-DgJK_4m1.mjs} +2 -2
  178. package/dist/{spawn-DgvUNYEo.mjs → spawn-Dvzy-tzc.mjs} +15 -15
  179. package/dist/{spawn-6PD7nnoC.cjs → spawn-rhF28shY.cjs} +15 -15
  180. package/dist/{spawnAgents-P006Hqio.mjs → spawnAgents-CCnlq-FI.mjs} +1 -1
  181. package/dist/{spawnAgents-DsXgegHM.cjs → spawnAgents-iwuqrgR9.cjs} +1 -1
  182. package/dist/{spawnHappyCLI-Dywezwk6.cjs → spawnHappyCLI-DnKmIsEt.cjs} +2 -2
  183. package/dist/{spawnHappyCLI-CCOrEtf9.mjs → spawnHappyCLI-Dq3LLXLb.mjs} +1 -1
  184. package/dist/{specialCommands-DPcd9edP.mjs → specialCommands-CcyZ1hGA.mjs} +3 -3
  185. package/dist/{specialCommands-QxPpkGKf.cjs → specialCommands-Zwr2C6A2.cjs} +3 -3
  186. package/dist/{startFileWatcher-DghDOCO4.mjs → startFileWatcher-4thXDK9d.mjs} +1 -1
  187. package/dist/{startFileWatcher-RECH5qY8.cjs → startFileWatcher-K6hJSyiR.cjs} +1 -1
  188. package/dist/startupSessionCreate-BfByJ16A.mjs +24 -0
  189. package/dist/startupSessionCreate-CKEbq0tL.cjs +26 -0
  190. package/dist/{streamRelay-DlUWKUpo.cjs → streamRelay-Gy8Xfnon.cjs} +1 -1
  191. package/dist/{streamRelay-DMV_TXfS.mjs → streamRelay-LcDvyEjK.mjs} +1 -1
  192. package/dist/{sync-D23jbqVa.cjs → sync-1hQ5KHpL.cjs} +1 -1
  193. package/dist/{sync-CSe0Rf45.mjs → sync-DO-2PU45.mjs} +1 -1
  194. package/dist/{systemPrompt-CFNKnh65.mjs → systemPrompt-BctLfMZs.mjs} +3 -3
  195. package/dist/{systemPrompt-BOy4kU4P.cjs → systemPrompt-Dj7pgkMK.cjs} +3 -3
  196. package/dist/{teams-DyY669f0.mjs → teams-Bu8YeOoF.mjs} +8 -8
  197. package/dist/{teams-Ov2BDT-A.cjs → teams-uQxUlyyz.cjs} +8 -8
  198. package/dist/{time-65DcU6Jx.mjs → time-BcoJaG8E.mjs} +1 -1
  199. package/dist/{time-CrwIMHta.cjs → time-nqa9shu8.cjs} +1 -1
  200. package/dist/{titleGenerator-CS_rh2_J.cjs → titleGenerator-D09XyYYG.cjs} +3 -3
  201. package/dist/{titleGenerator-CiAMxf7s.mjs → titleGenerator-D5r06bhf.mjs} +1 -1
  202. package/dist/{todo-KY-okGii.cjs → todo-CCOnL7pT.cjs} +6 -6
  203. package/dist/{todo-BDONw0sK.mjs → todo-D1q8146q.mjs} +6 -6
  204. package/dist/{tools-D8-PnZEG.mjs → tools-D2E--n1x.mjs} +3 -3
  205. package/dist/{tools-_w52DZG6.cjs → tools-DiCXnAC5.cjs} +3 -3
  206. package/dist/{uninstall-8vnLN-IE.cjs → uninstall-BrNwwwSD.cjs} +6 -6
  207. package/dist/{uninstall-_fjGRP9b.mjs → uninstall-CtwXi1Rt.mjs} +3 -3
  208. package/package.json +9 -8
  209. package/dist/machineMetadata-CLHS9sv_.cjs +0 -42
  210. package/dist/machineMetadata-D-g--oU_.mjs +0 -39
  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-CjCF4C3v.mjs +0 -85
@@ -1,25 +1,26 @@
1
1
  'use strict';
2
2
 
3
- var mirrorProtocol = require('./mirrorProtocol-DEy2g1CB.cjs');
4
- var piRunnerArgs = require('./piRunnerArgs-Cs-378Vz.cjs');
3
+ var mirrorProtocol = require('./mirrorProtocol-BphKIAK9.cjs');
4
+ var piRunnerArgs = require('./piRunnerArgs-gxLYIZH4.cjs');
5
5
  var fs = require('fs/promises');
6
+ var os$1 = require('os');
6
7
  var tmp = require('tmp');
7
8
  var axios = require('axios');
8
- var api = require('./api-Cmjfr8Z7.cjs');
9
- var spawnAgents = require('./spawnAgents-DsXgegHM.cjs');
10
- var logger = require('./logger-C1GWx3gi.cjs');
11
9
  var node_fs = require('node:fs');
12
10
  var path = require('node:path');
13
- var index$2 = require('./index-D09T1m8Y.cjs');
14
- var auth = require('./auth-D6bBUwZa.cjs');
15
- var configuration = require('./configuration-CMHZnp6G.cjs');
11
+ var configuration = require('./configuration-C8JgseHy.cjs');
12
+ var api = require('./api-COHFAkb_.cjs');
13
+ var spawnAgents = require('./spawnAgents-iwuqrgR9.cjs');
14
+ var logger = require('./logger-DgBwUSgS.cjs');
15
+ var index$2 = require('./index-BRMq9gOe.cjs');
16
+ var auth = require('./auth-CgQP7d0q.cjs');
16
17
  var child_process = require('child_process');
17
- var _package = require('./package-SgqTYsjn.cjs');
18
- var doctor = require('./doctor-Br1Kcy2J.cjs');
19
- var spawnHappyCLI = require('./spawnHappyCLI-Dywezwk6.cjs');
20
- var persistence = require('./persistence-BegE7NPa.cjs');
21
- var controlClient = require('./controlClient-C-5qCt8W.cjs');
22
- var sessionOps = require('./sessionOps-S-qPBLFf.cjs');
18
+ var _package = require('./package-NoD8QOOM.cjs');
19
+ var doctor = require('./doctor-Be7zC0AF.cjs');
20
+ var spawnHappyCLI = require('./spawnHappyCLI-DnKmIsEt.cjs');
21
+ var persistence = require('./persistence-BY-D00wT.cjs');
22
+ var controlClient = require('./controlClient-D68Zj7Q-.cjs');
23
+ var sessionOps = require('./sessionOps-DVA-00nR.cjs');
23
24
  var fastify = require('fastify');
24
25
  var z = require('zod');
25
26
  var fastifyTypeProviderZod = require('fastify-type-provider-zod');
@@ -27,61 +28,62 @@ var authRelay = require('./authRelay-Dy1qU9td.cjs');
27
28
  var node_crypto = require('node:crypto');
28
29
  var previewPath = require('./previewPath-B0rBdhy1.cjs');
29
30
  var backgroundTaskActivity = require('./backgroundTaskActivity-CBvUdj39.cjs');
30
- var rateLimitWindows = require('./rateLimitWindows-Dj_8voBK.cjs');
31
- var peerTools = require('./peerTools-DRQETXaz.cjs');
31
+ var rateLimitWindows = require('./rateLimitWindows-OpAmdOtC.cjs');
32
+ var peerTools = require('./peerTools-CP-x-Peu.cjs');
32
33
  var os = require('node:os');
33
- var remoteSessionClient = require('./remoteSessionClient-B7i7MkYV.cjs');
34
- var bootstrap = require('./bootstrap-exVucYav.cjs');
35
- var index$1 = require('./index-B0UjHlAe.cjs');
36
- var fs$1 = require('fs');
37
- var path$2 = require('path');
34
+ var remoteSessionClient = require('./remoteSessionClient-CFCn42bs.cjs');
35
+ var bootstrap = require('./bootstrap-CYtOtbi7.cjs');
36
+ var index$1 = require('./index-BkluinoS.cjs');
37
+ var require$$0 = require('fs');
38
+ var require$$1 = require('path');
38
39
  var node_child_process = require('node:child_process');
39
- var projectPath = require('./projectPath-ChLhdOyt.cjs');
40
- var doctorReadiness = require('./doctorReadiness-BCZGcN0a.cjs');
41
- var machineMetadata = require('./machineMetadata-CLHS9sv_.cjs');
42
- var handleResumeCommand = require('./handleResumeCommand-tKD_Hpxc.cjs');
40
+ var projectPath = require('./projectPath-C3ioB4Bu.cjs');
41
+ var doctorReadiness = require('./doctorReadiness-Dl6yRQCy.cjs');
42
+ var machineMetadata = require('./machineMetadata-DB03ez4K.cjs');
43
+ var fileStore = require('./fileStore-7qhnbs6N.cjs');
44
+ var pi = require('./pi-DlsrPCTa.cjs');
45
+ var require$$3 = require('crypto');
46
+ var detectCLI = require('./detectCLI-BuYR_Qxe.cjs');
47
+ var handleResumeCommand = require('./handleResumeCommand-BFZlrFVH.cjs');
43
48
  var webPanels = require('./webPanels-FCgFKvVe.cjs');
44
- var index = require('./index-C6O2vVjm.cjs');
49
+ var index = require('./index-Df2eHm3O.cjs');
45
50
  var promises = require('node:fs/promises');
46
51
  var cliUpdate = require('./cliUpdate-DsKXPFYp.cjs');
47
- var client = require('./client-ZjOsn6nZ.cjs');
48
- var client$1 = require('./client-CuVdN6PP.cjs');
52
+ var client = require('./client-DWs6k041.cjs');
53
+ var client$1 = require('./client-D_U2VjO3.cjs');
49
54
  var module$1 = require('node:module');
50
55
  var path$1 = require('./path-B7zW-WwE.cjs');
51
56
  var editPaths = require('./editPaths-Bqp4OFPw.cjs');
52
- var startFileWatcher = require('./startFileWatcher-RECH5qY8.cjs');
53
- var sync = require('./sync-D23jbqVa.cjs');
57
+ var startFileWatcher = require('./startFileWatcher-K6hJSyiR.cjs');
58
+ var sync = require('./sync-1hQ5KHpL.cjs');
54
59
  var types = require('./types-CRS-srZK.cjs');
55
60
  var tmuxSocket = require('./tmuxSocket-D-Xt6Vn-.cjs');
56
- var sessionLock = require('./sessionLock-DokGab2R.cjs');
61
+ var sessionLock = require('./sessionLock-CdIRJlHH.cjs');
57
62
  var doctor$1 = require('./doctor-u46qYYKX.cjs');
58
- var resources = require('./resources-CvIlkzpP.cjs');
63
+ var resources = require('./resources-BPyN59Iv.cjs');
59
64
  var node_util = require('node:util');
60
65
  var template = require('./template-BaHAmH2K.cjs');
61
66
  var daemonSupervisor = require('./daemonSupervisor-B-SPSqhs.cjs');
62
67
  var loginShellEnv = require('./loginShellEnv-BkuYtExZ.cjs');
63
- require('./acpSessionResume-oiCBnAVA.cjs');
64
- require('./lidState-Dv2wwFTj.cjs');
65
- require('os');
68
+ require('./acpSessionResume-BaVMD80f.cjs');
69
+ require('./lidState-x8cJ8J_9.cjs');
66
70
  require('node:events');
67
71
  require('socket.io-client');
68
- require('./pushNotifications-DaLQUyi0.cjs');
72
+ require('./pushNotifications-BXoOSq_G.cjs');
69
73
  require('./contentLogMetadata-ZSFk_NjQ.cjs');
70
74
  require('./limits-C-a7gr04.cjs');
71
- require('./time-CrwIMHta.cjs');
72
- require('./registerCommonHandlers-Cj084Sg7.cjs');
75
+ require('./time-nqa9shu8.cjs');
76
+ require('./registerCommonHandlers-CRjBoJLK.cjs');
73
77
  require('util');
74
- require('crypto');
75
78
  require('cross-spawn');
76
79
  require('@paralleldrive/cuid2');
77
80
  require('chalk');
78
81
  require('tweetnacl');
79
- require('./browser-BohJK12g.cjs');
82
+ require('./browser-DjNNQQk2.cjs');
80
83
  require('open');
81
84
  require('./ids-B6ZC0HGt.cjs');
82
85
  require('url');
83
- require('./detectCLI-DR9ZaN6B.cjs');
84
- require('./localHappyAgentAuth-DjYvkXvV.cjs');
86
+ require('./localHappyAgentAuth-DZ2kb9uq.cjs');
85
87
  require('./processTreeSnapshot-mDbnuojn.cjs');
86
88
  require('ps-list');
87
89
 
@@ -114,6 +116,87 @@ async function resolveRelaunchMetadata(snapshot, fetchServer) {
114
116
  return { metadata: snapshot, source: "snapshot" };
115
117
  }
116
118
 
119
+ function receiptPath(home, operationId) {
120
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid team operation id");
121
+ return path.join(home, "teams", "effects", `${operationId}.json`);
122
+ }
123
+ function readReceipt(home, id) {
124
+ try {
125
+ const value = JSON.parse(node_fs.readFileSync(receiptPath(home, id), "utf8"));
126
+ if (value.operationId !== id || typeof value.claimId !== "string" || !["prepared", "spawning", "spawned", "delivered", "completed"].includes(value.phase)) throw new Error("Invalid team effect receipt");
127
+ return value;
128
+ } catch (error) {
129
+ if (error.code === "ENOENT") return null;
130
+ throw error;
131
+ }
132
+ }
133
+ function writeReceipt$1(home, receipt) {
134
+ configuration.ensurePrivateDirectorySync(path.join(home, "teams", "effects"));
135
+ const target = receiptPath(home, receipt.operationId);
136
+ const tmp = `${target}.${process.pid}.tmp`;
137
+ configuration.writePrivateFileSync(tmp, JSON.stringify(receipt));
138
+ const file = node_fs.openSync(tmp, "r");
139
+ try {
140
+ node_fs.fsyncSync(file);
141
+ } finally {
142
+ node_fs.closeSync(file);
143
+ }
144
+ node_fs.renameSync(tmp, target);
145
+ if (process.platform !== "win32") {
146
+ const directory = node_fs.openSync(path.join(home, "teams", "effects"), "r");
147
+ try {
148
+ node_fs.fsyncSync(directory);
149
+ } finally {
150
+ node_fs.closeSync(directory);
151
+ }
152
+ }
153
+ }
154
+
155
+ const OPERATION_ID = /^[a-zA-Z0-9_-]{1,128}$/;
156
+ function teamScopeFilePath(home, operationId) {
157
+ if (!OPERATION_ID.test(operationId)) throw new Error("Invalid team operation id");
158
+ return path.join(home, "teams", "scopes", `${operationId}.json`);
159
+ }
160
+ function relaunchTeamOperationId(home, sessionId, metadata) {
161
+ const fromMetadata = metadata?.teamOperationId;
162
+ if (typeof fromMetadata === "string" && OPERATION_ID.test(fromMetadata)) return fromMetadata;
163
+ let names;
164
+ try {
165
+ names = node_fs.readdirSync(path.join(home, "teams", "effects"));
166
+ } catch {
167
+ return null;
168
+ }
169
+ let newest = null;
170
+ for (const name of names) {
171
+ if (!name.endsWith(".json")) continue;
172
+ const id = name.slice(0, -".json".length);
173
+ if (!OPERATION_ID.test(id)) continue;
174
+ try {
175
+ const receipt = readReceipt(home, id);
176
+ if (receipt?.sessionId !== sessionId || !receipt.scopeFile) continue;
177
+ const at = node_fs.statSync(receiptPath(home, id)).mtimeMs;
178
+ if (!newest || at > newest.at) newest = { id, at };
179
+ } catch {
180
+ }
181
+ }
182
+ return newest?.id ?? null;
183
+ }
184
+ async function teamRelaunchEnv(input) {
185
+ const operationId = relaunchTeamOperationId(input.home, input.sessionId, input.metadata);
186
+ if (!operationId) return {};
187
+ const scopeFile = teamScopeFilePath(input.home, operationId);
188
+ if (!node_fs.existsSync(scopeFile) && input.recover) {
189
+ try {
190
+ await input.recover(operationId, scopeFile);
191
+ input.log(`Teams scope for ${input.sessionId} rebuilt from operation ${operationId}`);
192
+ } catch (error) {
193
+ input.log(`Teams scope for ${input.sessionId} could not be rebuilt: ${error instanceof Error ? error.message : "unknown error"}`);
194
+ }
195
+ }
196
+ if (!node_fs.existsSync(scopeFile)) input.log(`Teams scope for ${input.sessionId} is missing; team tools will refuse until the owner restores it`);
197
+ return { VH_TEAM_SCOPE_FILE: scopeFile, VH_TEAM_OPERATION_ID: operationId, HAPPY_SPAWNED_BY: "teams" };
198
+ }
199
+
117
200
  const DEFAULT_LOG_PRUNE_POLICY = {
118
201
  maxAgeMs: 14 * 24 * 60 * 6e4,
119
202
  maxTotalBytes: 200 * 1024 * 1024,
@@ -394,6 +477,20 @@ function formatAssistantReportMessage(title, sessionId, event) {
394
477
  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`;
395
478
  }
396
479
 
480
+ const CLAUDE_OUTBOUND_MODES = ["default", "acceptEdits", "plan", "bypassPermissions"];
481
+ function normalizeClaudeOutboundMode(value) {
482
+ if (value === null || value === void 0) return null;
483
+ if (value === "yolo") return "bypassPermissions";
484
+ return CLAUDE_OUTBOUND_MODES.includes(value) ? value : "default";
485
+ }
486
+ function publishedRelaunchPermissionMode(metadata) {
487
+ const published = typeof metadata?.permissionMode === "string" ? metadata.permissionMode : null;
488
+ if ((metadata?.flavor ?? "claude") === "claude") {
489
+ return normalizeClaudeOutboundMode(published) ?? void 0;
490
+ }
491
+ return published ?? void 0;
492
+ }
493
+
397
494
  function resumePrecheck(metadata, fs) {
398
495
  const flavor = metadata.flavor ?? "claude";
399
496
  if (flavor === "acp" && metadata.piSessionId) {
@@ -420,6 +517,9 @@ function resumePrecheck(metadata, fs) {
420
517
  }
421
518
  return { ok: true };
422
519
  }
520
+ function resumeStartsFreshConversation(reason) {
521
+ return reason === "conversation-missing" || reason === "no-backend-id";
522
+ }
423
523
  function sanitizeResumeModel(value) {
424
524
  if (typeof value !== "string") return null;
425
525
  return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}(\[1m\])?$/i.test(value) ? value : null;
@@ -777,7 +877,7 @@ function startDaemonControlServer({
777
877
  return { success: false, error: "daemon is still starting up" };
778
878
  }
779
879
  logger.logger.debug(`[CONTROL SERVER] Resume session request: ${sessionId} (model=${model ?? "unset"}, permissionMode=${permissionMode ?? "unset"})`);
780
- const result = await resumeSession(sessionId, { model, permissionMode });
880
+ const result = await resumeSession(sessionId, { model, permissionMode, keepPublishedPermissionMode: true });
781
881
  switch (result.type) {
782
882
  case "success":
783
883
  return { success: true, sessionId: result.sessionId };
@@ -2085,6 +2185,2032 @@ function spawnAgentUnavailableError(agent, availability) {
2085
2185
  return null;
2086
2186
  }
2087
2187
 
2188
+ const MAX_DIFF_LINES = 4e3;
2189
+ function splitLines(text) {
2190
+ if (text === "") return [];
2191
+ const lines = text.split("\n");
2192
+ if (lines[lines.length - 1] === "") lines.pop();
2193
+ return lines;
2194
+ }
2195
+ function diffOps(a, b) {
2196
+ if (a.length > MAX_DIFF_LINES || b.length > MAX_DIFF_LINES) {
2197
+ return [...a.map((text) => ({ kind: "-", text })), ...b.map((text) => ({ kind: "+", text }))];
2198
+ }
2199
+ const n = a.length;
2200
+ const m = b.length;
2201
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
2202
+ for (let i2 = n - 1; i2 >= 0; i2--) {
2203
+ for (let j2 = m - 1; j2 >= 0; j2--) {
2204
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
2205
+ }
2206
+ }
2207
+ const ops = [];
2208
+ let i = 0;
2209
+ let j = 0;
2210
+ while (i < n && j < m) {
2211
+ if (a[i] === b[j]) {
2212
+ ops.push({ kind: " ", text: a[i] });
2213
+ i++;
2214
+ j++;
2215
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
2216
+ ops.push({ kind: "-", text: a[i] });
2217
+ i++;
2218
+ } else {
2219
+ ops.push({ kind: "+", text: b[j] });
2220
+ j++;
2221
+ }
2222
+ }
2223
+ while (i < n) ops.push({ kind: "-", text: a[i++] });
2224
+ while (j < m) ops.push({ kind: "+", text: b[j++] });
2225
+ return ops;
2226
+ }
2227
+ function unifiedDiff(oldText, newText, label, context = 3) {
2228
+ if (oldText === newText) return "";
2229
+ const a = splitLines(oldText);
2230
+ const b = splitLines(newText);
2231
+ const ops = diffOps(a, b);
2232
+ const changed = ops.map((op) => op.kind !== " ");
2233
+ if (!changed.some(Boolean)) {
2234
+ return `--- ${label}
2235
+ +++ ${label}
2236
+ @@ trailing newline changed @@
2237
+ `;
2238
+ }
2239
+ const out = [`--- ${oldText === "" ? "/dev/null" : label}`, `+++ ${label}`];
2240
+ let k = 0;
2241
+ while (k < ops.length) {
2242
+ if (!changed[k]) {
2243
+ k++;
2244
+ continue;
2245
+ }
2246
+ let start = Math.max(0, k - context);
2247
+ let end = k;
2248
+ while (end < ops.length) {
2249
+ if (changed[end]) {
2250
+ end++;
2251
+ continue;
2252
+ }
2253
+ let next = end;
2254
+ while (next < ops.length && !changed[next]) next++;
2255
+ if (next < ops.length && next - end <= context * 2) {
2256
+ end = next;
2257
+ continue;
2258
+ }
2259
+ break;
2260
+ }
2261
+ const stop = Math.min(ops.length, end + context);
2262
+ let oldStart = 1;
2263
+ let newStart = 1;
2264
+ for (let p = 0; p < start; p++) {
2265
+ if (ops[p].kind !== "+") oldStart++;
2266
+ if (ops[p].kind !== "-") newStart++;
2267
+ }
2268
+ const slice = ops.slice(start, stop);
2269
+ const oldCount = slice.filter((op) => op.kind !== "+").length;
2270
+ const newCount = slice.filter((op) => op.kind !== "-").length;
2271
+ out.push(`@@ -${oldCount ? oldStart : oldStart - 1},${oldCount} +${newCount ? newStart : newStart - 1},${newCount} @@`);
2272
+ for (const op of slice) out.push(`${op.kind}${op.text}`);
2273
+ k = stop;
2274
+ start = stop;
2275
+ }
2276
+ return `${out.join("\n")}
2277
+ `;
2278
+ }
2279
+
2280
+ const ROLE$1 = "settings";
2281
+ const AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN";
2282
+ const API_KEY$1 = "ANTHROPIC_API_KEY";
2283
+ const ALIAS_VARS = { opusModel: "ANTHROPIC_DEFAULT_OPUS_MODEL", sonnetModel: "ANTHROPIC_DEFAULT_SONNET_MODEL", haikuModel: "ANTHROPIC_DEFAULT_HAIKU_MODEL" };
2284
+ function claudeEnvHelper(name) {
2285
+ return `printf %s "$${name}"`;
2286
+ }
2287
+ const OUR_HELPER = /^printf %s "\$([A-Za-z_][A-Za-z0-9_]*)"$/;
2288
+ const OWNED_PATHS = [
2289
+ ["env", "ANTHROPIC_BASE_URL"],
2290
+ ["env", AUTH_TOKEN],
2291
+ ["env", API_KEY$1],
2292
+ ["env", ALIAS_VARS.opusModel],
2293
+ ["env", ALIAS_VARS.sonnetModel],
2294
+ ["env", ALIAS_VARS.haikuModel],
2295
+ ["model"],
2296
+ ["modelPicker", "options"],
2297
+ ["apiKeyHelper"],
2298
+ ["availableModels"]
2299
+ ];
2300
+ function claudeSettingsPath(ctx) {
2301
+ const dir = ctx.env.CLAUDE_CONFIG_DIR?.trim() || path.join(ctx.home, ".claude");
2302
+ return path.join(dir, "settings.json");
2303
+ }
2304
+ function str$3(v) {
2305
+ return typeof v === "string" && v.trim() ? v : null;
2306
+ }
2307
+ function envOf(settings) {
2308
+ const env = settings.env;
2309
+ return env && typeof env === "object" && !Array.isArray(env) ? env : {};
2310
+ }
2311
+ function pickerOptions(settings) {
2312
+ const picker = settings.modelPicker;
2313
+ if (!picker || typeof picker !== "object" || Array.isArray(picker)) return [];
2314
+ const options = picker.options;
2315
+ return Array.isArray(options) ? options.filter((o) => !!o && typeof o === "object" && typeof o.model === "string") : [];
2316
+ }
2317
+ function secretView$1(settings, ctx) {
2318
+ const env = envOf(settings);
2319
+ const literal = str$3(env[AUTH_TOKEN]) ?? str$3(env[API_KEY$1]);
2320
+ if (literal) return { mode: "literal", masked: pi.maskSecret(literal) };
2321
+ const helper = str$3(settings.apiKeyHelper);
2322
+ if (helper) {
2323
+ const ours = OUR_HELPER.exec(helper.trim());
2324
+ if (ours) return { mode: "env", envName: ours[1], envPresent: !!ctx.env[ours[1]] };
2325
+ return { mode: "command" };
2326
+ }
2327
+ return { mode: "none" };
2328
+ }
2329
+ function currentOf$2(settings, ctx) {
2330
+ const env = envOf(settings);
2331
+ return {
2332
+ baseUrl: str$3(env.ANTHROPIC_BASE_URL),
2333
+ authHeader: !str$3(env[AUTH_TOKEN]) && str$3(env[API_KEY$1]) ? "x-api-key" : "bearer",
2334
+ apiKey: secretView$1(settings, ctx),
2335
+ model: str$3(settings.model),
2336
+ opusModel: str$3(env[ALIAS_VARS.opusModel]),
2337
+ sonnetModel: str$3(env[ALIAS_VARS.sonnetModel]),
2338
+ haikuModel: str$3(env[ALIAS_VARS.haikuModel]),
2339
+ pickerModels: pickerOptions(settings).map((o) => o.model)
2340
+ };
2341
+ }
2342
+ function pickerModelsOf(current) {
2343
+ return pi.uniq([current.model, current.opusModel, current.sonnetModel, current.haikuModel, ...current.pickerModels ?? []]);
2344
+ }
2345
+ function warningsOf$2(settings, current, ctx) {
2346
+ const env = envOf(settings);
2347
+ const out = [...pi.baseUrlWarnings(current.baseUrl, "anthropic")];
2348
+ if (str$3(env.ANTHROPIC_MODEL)) {
2349
+ out.push({ code: "env-model-overrides", message: "env.ANTHROPIC_MODEL is set in settings.json and overrides the default model." });
2350
+ }
2351
+ const daemonOther = current.authHeader === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2352
+ if (current.baseUrl && ctx.env[daemonOther]) {
2353
+ out.push({ code: "daemon-env-credential", message: `The daemon's environment also defines ${daemonOther}; sessions inherit it.` });
2354
+ }
2355
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
2356
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
2357
+ }
2358
+ if (Array.isArray(settings.availableModels)) {
2359
+ const allowed = settings.availableModels;
2360
+ const missing = pickerModelsOf(current).filter((id) => !allowed.includes(id));
2361
+ if (missing.length) out.push({ code: "available-models-filter", message: `availableModels does not list ${missing.join(", ")}; Claude Code hides them.` });
2362
+ }
2363
+ return out;
2364
+ }
2365
+ function parsePatch$1(raw) {
2366
+ const p = raw;
2367
+ if (p.authHeader !== void 0 && p.authHeader !== "bearer" && p.authHeader !== "x-api-key") pi.fail("invalid-input", "authHeader must be bearer or x-api-key");
2368
+ return {
2369
+ harness: "claude",
2370
+ baseUrl: pi.normalizeBaseUrl(p.baseUrl),
2371
+ authHeader: p.authHeader,
2372
+ apiKey: pi.normalizeSecret(p.apiKey),
2373
+ model: pi.normalizeModelId(p.model),
2374
+ opusModel: pi.normalizeModelId(p.opusModel, "opusModel"),
2375
+ sonnetModel: pi.normalizeModelId(p.sonnetModel, "sonnetModel"),
2376
+ haikuModel: pi.normalizeModelId(p.haikuModel, "haikuModel"),
2377
+ pickerModels: pi.normalizeModelList(p.pickerModels, "pickerModels")
2378
+ };
2379
+ }
2380
+ const claudeAdapter = {
2381
+ id: "claude",
2382
+ binary: "claude",
2383
+ files: (ctx) => [{ role: ROLE$1, path: claudeSettingsPath(ctx) }],
2384
+ view(files, ctx) {
2385
+ const settings = pi.parseJsonObject(files[ROLE$1].content, "settings.json");
2386
+ const current = currentOf$2(settings, ctx);
2387
+ return { current, pickerModels: pickerModelsOf(current), warnings: warningsOf$2(settings, current, ctx) };
2388
+ },
2389
+ plan(files, raw, ctx) {
2390
+ const patch = parsePatch$1(raw);
2391
+ const original = files[ROLE$1].content;
2392
+ const before = pi.parseJsonObject(original, "settings.json");
2393
+ const settings = structuredClone(before);
2394
+ const hadEnv = settings.env !== void 0;
2395
+ const env = pi.childObject(settings, "env", "settings");
2396
+ if (patch.baseUrl !== void 0) pi.setOrDelete(env, "ANTHROPIC_BASE_URL", patch.baseUrl);
2397
+ const currentHeader = !str$3(env[AUTH_TOKEN]) && str$3(env[API_KEY$1]) ? "x-api-key" : "bearer";
2398
+ const header = patch.authHeader ?? currentHeader;
2399
+ const target = header === "bearer" ? AUTH_TOKEN : API_KEY$1;
2400
+ const other = header === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2401
+ const helperIsOurs = typeof settings.apiKeyHelper === "string" && OUR_HELPER.test(settings.apiKeyHelper.trim());
2402
+ const secrets = [];
2403
+ switch (patch.apiKey.mode) {
2404
+ case "literal":
2405
+ env[target] = patch.apiKey.value;
2406
+ delete env[other];
2407
+ if (helperIsOurs) delete settings.apiKeyHelper;
2408
+ secrets.push(patch.apiKey.value);
2409
+ break;
2410
+ case "env":
2411
+ settings.apiKeyHelper = claudeEnvHelper(patch.apiKey.name);
2412
+ delete env[AUTH_TOKEN];
2413
+ delete env[API_KEY$1];
2414
+ break;
2415
+ case "clear":
2416
+ delete env[AUTH_TOKEN];
2417
+ delete env[API_KEY$1];
2418
+ if (helperIsOurs) delete settings.apiKeyHelper;
2419
+ break;
2420
+ case "keep":
2421
+ if (header !== currentHeader && str$3(env[other]) && !str$3(env[target])) {
2422
+ env[target] = env[other];
2423
+ delete env[other];
2424
+ }
2425
+ break;
2426
+ }
2427
+ if (patch.model !== void 0) pi.setOrDelete(settings, "model", patch.model);
2428
+ for (const [field, variable] of Object.entries(ALIAS_VARS)) {
2429
+ if (patch[field] !== void 0) pi.setOrDelete(env, variable, patch[field]);
2430
+ }
2431
+ if (patch.pickerModels !== void 0) {
2432
+ const hadPicker = settings.modelPicker !== void 0;
2433
+ const picker = pi.childObject(settings, "modelPicker", "settings");
2434
+ const existing = pickerOptions(settings);
2435
+ const next = patch.pickerModels.map((id) => existing.find((o) => o.model === id) ?? { model: id });
2436
+ if (next.length) picker.options = next;
2437
+ else delete picker.options;
2438
+ if (!hadPicker && Object.keys(picker).length === 0) delete settings.modelPicker;
2439
+ }
2440
+ if (!hadEnv && Object.keys(env).length === 0) delete settings.env;
2441
+ const current = currentOf$2(settings, ctx);
2442
+ if (Array.isArray(settings.availableModels)) {
2443
+ const allowed = settings.availableModels;
2444
+ const add = pickerModelsOf(current).filter((id) => !allowed.includes(id));
2445
+ if (add.length) settings.availableModels = [...allowed, ...add];
2446
+ }
2447
+ const changedKeys = pi.changedPaths(before, settings, OWNED_PATHS);
2448
+ const content = changedKeys.length === 0 ? void 0 : pi.stringifyLike(original, settings);
2449
+ return { contents: { [ROLE$1]: content }, warnings: warningsOf$2(settings, current, ctx), changedKeys, secrets };
2450
+ },
2451
+ secretsIn(_role, content) {
2452
+ try {
2453
+ return pi.collectSecretValues(pi.parseJsonObject(content, "settings.json"));
2454
+ } catch {
2455
+ return /* @__PURE__ */ new Set();
2456
+ }
2457
+ }
2458
+ };
2459
+
2460
+ /*!
2461
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2462
+ * SPDX-License-Identifier: BSD-3-Clause
2463
+ *
2464
+ * Redistribution and use in source and binary forms, with or without
2465
+ * modification, are permitted provided that the following conditions are met:
2466
+ *
2467
+ * 1. Redistributions of source code must retain the above copyright notice, this
2468
+ * list of conditions and the following disclaimer.
2469
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2470
+ * this list of conditions and the following disclaimer in the
2471
+ * documentation and/or other materials provided with the distribution.
2472
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2473
+ * may be used to endorse or promote products derived from this software without
2474
+ * specific prior written permission.
2475
+ *
2476
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2477
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2478
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2479
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2480
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2481
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2482
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2483
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2484
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2485
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2486
+ */
2487
+ function getLineColFromPtr(string, ptr) {
2488
+ let lines = string.slice(0, ptr).split(/\r?\n/);
2489
+ return [lines.length, lines.pop().length + 1];
2490
+ }
2491
+ function makeCodeBlock(string, line, column) {
2492
+ let lines = string.split(/\r?\n/);
2493
+ let codeblock = "";
2494
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
2495
+ for (let i = line - 1; i <= line + 1; i++) {
2496
+ let l = lines[i - 1];
2497
+ if (!l)
2498
+ continue;
2499
+ codeblock += i.toString().padEnd(numberLen, " ");
2500
+ codeblock += ": ";
2501
+ codeblock += l;
2502
+ codeblock += "\n";
2503
+ if (i === line) {
2504
+ codeblock += " ".repeat(numberLen + column + 2);
2505
+ codeblock += "^\n";
2506
+ }
2507
+ }
2508
+ return codeblock;
2509
+ }
2510
+ class TomlError extends Error {
2511
+ line;
2512
+ column;
2513
+ codeblock;
2514
+ constructor(message, options) {
2515
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
2516
+ const codeblock = makeCodeBlock(options.toml, line, column);
2517
+ super(`Invalid TOML document: ${message}
2518
+
2519
+ ${codeblock}`, options);
2520
+ this.line = line;
2521
+ this.column = column;
2522
+ this.codeblock = codeblock;
2523
+ }
2524
+ /** @internal */
2525
+ static x(message, ctx, ptr) {
2526
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
2527
+ }
2528
+ }
2529
+
2530
+ function parseString(ctx) {
2531
+ let startPtr = ctx.p;
2532
+ let c = ctx.s.charCodeAt(ctx.p++);
2533
+ let first = c;
2534
+ let isLiteral = c === 39;
2535
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
2536
+ if (isMultiline) {
2537
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
2538
+ ctx.p++;
2539
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
2540
+ ctx.p += 2;
2541
+ }
2542
+ let parsed = "";
2543
+ let sliceStart = ctx.p;
2544
+ let state = 0;
2545
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2546
+ c = ctx.s.charCodeAt(ctx.p);
2547
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
2548
+ state = state && 3;
2549
+ } else if (c < 32 && c !== 9 || c === 127) {
2550
+ TomlError.x("control characters are not allowed in strings", ctx);
2551
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
2552
+ if (isMultiline) {
2553
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2554
+ ctx.p++;
2555
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2556
+ ctx.p++;
2557
+ }
2558
+ if (!state) {
2559
+ let s = ctx.s.slice(sliceStart, ctx.p);
2560
+ parsed = parsed ? parsed + s : s;
2561
+ }
2562
+ ctx.p += isMultiline ? 3 : 1;
2563
+ return parsed;
2564
+ } else if (!state) {
2565
+ if (!isLiteral && c === 92) {
2566
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
2567
+ state = 1;
2568
+ }
2569
+ } else if (state === 1) {
2570
+ if (c === 120 || c === 117 || c === 85) {
2571
+ let errPtr = ctx.p++ - 1;
2572
+ let value = 0;
2573
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
2574
+ for (let j = 0; j < len; j++, ctx.p++) {
2575
+ let hex = ctx.s.charCodeAt(ctx.p);
2576
+ let digit = (
2577
+ /* 0-9 */
2578
+ hex >= 48 && hex <= 57 ? hex - 48 : (
2579
+ /* A-F */
2580
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
2581
+ /* a-f */
2582
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
2583
+ )
2584
+ )
2585
+ );
2586
+ if (digit < 0)
2587
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
2588
+ value = value << 4 | digit;
2589
+ }
2590
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
2591
+ TomlError.x("invalid unicode escape", ctx, errPtr);
2592
+ }
2593
+ parsed += String.fromCodePoint(value);
2594
+ sliceStart = ctx.p--;
2595
+ state = 0;
2596
+ } else if (isMultiline && (c === 32 || c === 9)) {
2597
+ state = 2;
2598
+ } else {
2599
+ if (c === 98)
2600
+ parsed += "\b";
2601
+ else if (c === 116)
2602
+ parsed += " ";
2603
+ else if (c === 110)
2604
+ parsed += "\n";
2605
+ else if (c === 102)
2606
+ parsed += "\f";
2607
+ else if (c === 114)
2608
+ parsed += "\r";
2609
+ else if (c === 101)
2610
+ parsed += "\x1B";
2611
+ else if (c === 34)
2612
+ parsed += '"';
2613
+ else if (c === 92)
2614
+ parsed += "\\";
2615
+ else
2616
+ TomlError.x("unrecognised escape sequence", ctx);
2617
+ sliceStart = ctx.p + 1;
2618
+ state = 0;
2619
+ }
2620
+ } else if (c !== 32 && c !== 9) {
2621
+ if (state === 2)
2622
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
2623
+ state = !isLiteral && c === 92 ? 1 : 0;
2624
+ sliceStart = ctx.p;
2625
+ }
2626
+ }
2627
+ TomlError.x("unfinished string", ctx, startPtr);
2628
+ }
2629
+
2630
+ /*!
2631
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2632
+ * SPDX-License-Identifier: BSD-3-Clause
2633
+ *
2634
+ * Redistribution and use in source and binary forms, with or without
2635
+ * modification, are permitted provided that the following conditions are met:
2636
+ *
2637
+ * 1. Redistributions of source code must retain the above copyright notice, this
2638
+ * list of conditions and the following disclaimer.
2639
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2640
+ * this list of conditions and the following disclaimer in the
2641
+ * documentation and/or other materials provided with the distribution.
2642
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2643
+ * may be used to endorse or promote products derived from this software without
2644
+ * specific prior written permission.
2645
+ *
2646
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2647
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2648
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2649
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2650
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2651
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2652
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2653
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2654
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2655
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2656
+ */
2657
+ 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;
2658
+ class TomlDate extends Date {
2659
+ #hasDate = false;
2660
+ #hasTime = false;
2661
+ #offset = null;
2662
+ constructor(date, fasttype, unsafeDelim) {
2663
+ let hasDate = true;
2664
+ let hasTime = true;
2665
+ let offset = "Z";
2666
+ let c;
2667
+ if (typeof date === "string") {
2668
+ if (fasttype)
2669
+ prep: {
2670
+ if (fasttype < 3) {
2671
+ if (+date.slice(11, 13) > 23) {
2672
+ date = "";
2673
+ break prep;
2674
+ }
2675
+ if (fasttype === 2) {
2676
+ offset = null;
2677
+ date += "Z";
2678
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
2679
+ offset = date.slice(date.length - 6);
2680
+ }
2681
+ if (unsafeDelim)
2682
+ date = date.slice(0, 10) + "T" + date.slice(11);
2683
+ } else if (fasttype === 4) {
2684
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
2685
+ }
2686
+ hasDate = fasttype !== 4;
2687
+ hasTime = fasttype !== 3;
2688
+ }
2689
+ else {
2690
+ let match = date.match(DATE_TIME_RE);
2691
+ if (match) {
2692
+ if (!match[1]) {
2693
+ hasDate = false;
2694
+ date = `0000-01-01T${date}`;
2695
+ }
2696
+ hasTime = !!match[2];
2697
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
2698
+ if (match[2] && +match[2] > 23) {
2699
+ date = "";
2700
+ } else {
2701
+ offset = match[3] || null;
2702
+ if (!offset && hasTime)
2703
+ date += "Z";
2704
+ }
2705
+ } else {
2706
+ date = "";
2707
+ }
2708
+ }
2709
+ }
2710
+ super(date);
2711
+ if (!isNaN(this.getTime())) {
2712
+ this.#hasDate = hasDate;
2713
+ this.#hasTime = hasTime;
2714
+ this.#offset = offset;
2715
+ }
2716
+ }
2717
+ isDateTime() {
2718
+ return this.#hasDate && this.#hasTime;
2719
+ }
2720
+ isLocal() {
2721
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
2722
+ }
2723
+ isDate() {
2724
+ return this.#hasDate && !this.#hasTime;
2725
+ }
2726
+ isTime() {
2727
+ return this.#hasTime && !this.#hasDate;
2728
+ }
2729
+ isValid() {
2730
+ return this.#hasDate || this.#hasTime;
2731
+ }
2732
+ toISOString() {
2733
+ let iso = super.toISOString();
2734
+ if (this.isDate())
2735
+ return iso.slice(0, 10);
2736
+ if (this.isTime())
2737
+ return iso.slice(11, 23);
2738
+ if (this.#offset === null)
2739
+ return iso.slice(0, -1);
2740
+ if (this.#offset === "Z" || this.#offset === "z")
2741
+ return iso;
2742
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
2743
+ offset = this.#offset[0] === "-" ? offset : -offset;
2744
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
2745
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
2746
+ }
2747
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
2748
+ let date = new TomlDate(jsDate);
2749
+ date.#offset = offset;
2750
+ return date;
2751
+ }
2752
+ static wrapAsLocalDateTime(jsDate) {
2753
+ let date = new TomlDate(jsDate);
2754
+ date.#offset = null;
2755
+ return date;
2756
+ }
2757
+ static wrapAsLocalDate(jsDate) {
2758
+ let date = new TomlDate(jsDate);
2759
+ date.#hasTime = false;
2760
+ date.#offset = null;
2761
+ return date;
2762
+ }
2763
+ static wrapAsLocalTime(jsDate) {
2764
+ let date = new TomlDate(jsDate);
2765
+ date.#hasDate = false;
2766
+ date.#offset = null;
2767
+ return date;
2768
+ }
2769
+ }
2770
+
2771
+ function isDigit(char, base = 10) {
2772
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
2773
+ }
2774
+ function isEndOfValue(char, delim) {
2775
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
2776
+ delim && (char === delim || char === 44) || // Comment
2777
+ char === 35;
2778
+ }
2779
+ function extractValue(ctx, end) {
2780
+ let errPtr = ctx.p;
2781
+ let c = ctx.s.charCodeAt(ctx.p);
2782
+ if (c === 91 || c === 123) {
2783
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
2784
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
2785
+ ctx.d++;
2786
+ return value;
2787
+ }
2788
+ if (c === 34 || c === 39) {
2789
+ return parseString(ctx);
2790
+ }
2791
+ if (c === 116) {
2792
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
2793
+ TomlError.x("invalid value", ctx, errPtr);
2794
+ return ctx.p++, true;
2795
+ }
2796
+ if (c === 102) {
2797
+ 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)
2798
+ TomlError.x("invalid value", ctx, errPtr);
2799
+ return ctx.p++, false;
2800
+ }
2801
+ if (c === 43 || c === 45) {
2802
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
2803
+ }
2804
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
2805
+ return parseDate(ctx, c, end);
2806
+ }
2807
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
2808
+ return parseTime(ctx, c, end);
2809
+ }
2810
+ return parseNumber(ctx, ctx.p, c, 0, end);
2811
+ }
2812
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
2813
+ let c = startChr;
2814
+ let state = 0;
2815
+ let hasUnderscores = false;
2816
+ if (c === 105) {
2817
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
2818
+ TomlError.x("invalid value", ctx, startPtr);
2819
+ return ctx.p++, (sign || 1) / 0;
2820
+ }
2821
+ if (c === 110) {
2822
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
2823
+ TomlError.x("invalid value", ctx, startPtr);
2824
+ return ctx.p++, NaN;
2825
+ }
2826
+ if (c === 48) {
2827
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
2828
+ return ctx.bi === true ? 0n : 0;
2829
+ if (!sign) {
2830
+ if (c === 120)
2831
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
2832
+ else if (c === 98)
2833
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
2834
+ else if (c === 111)
2835
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
2836
+ }
2837
+ if (c === 46)
2838
+ state = 2;
2839
+ else if (c === 101 || c === 69)
2840
+ state = 4;
2841
+ else
2842
+ TomlError.x("illegal leading zero", ctx, startPtr);
2843
+ } else if (!isDigit(c))
2844
+ TomlError.x("invalid value", ctx, startPtr);
2845
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2846
+ if (!state)
2847
+ state = 1;
2848
+ if (c === 95) {
2849
+ if (!(state & 1))
2850
+ TomlError.x("illegal underscore", ctx);
2851
+ state += 11;
2852
+ hasUnderscores = true;
2853
+ } else if (state === 1 && c === 46)
2854
+ state = 2;
2855
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
2856
+ state = 4;
2857
+ else if (state === 4 && (c === 43 || c === 45)) ; else if (!isDigit(c))
2858
+ TomlError.x(`illegal character in numeric literal`, ctx);
2859
+ else if (state > 9)
2860
+ state -= 11;
2861
+ else if (!(state & 1))
2862
+ state++;
2863
+ }
2864
+ if (!state) {
2865
+ let val = (startChr - 48) * (sign || 1);
2866
+ return ctx.bi === true ? BigInt(val) : val;
2867
+ }
2868
+ if (!(state & 1))
2869
+ TomlError.x("unfinished numeric value", ctx, startPtr);
2870
+ let str = ctx.s.slice(startPtr, ctx.p);
2871
+ if (hasUnderscores)
2872
+ str = str.replaceAll("_", "");
2873
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
2874
+ }
2875
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
2876
+ let c, underscore = 1;
2877
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2878
+ if (c === 95) {
2879
+ if (underscore & 1)
2880
+ TomlError.x("illegal underscore", ctx);
2881
+ underscore = 3;
2882
+ } else if (!isDigit(c, base))
2883
+ TomlError.x(`illegal character in numeric literal`, ctx);
2884
+ else if (underscore & 1)
2885
+ underscore--;
2886
+ }
2887
+ if (underscore & 1)
2888
+ TomlError.x("unfinished numeric value", ctx);
2889
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
2890
+ if (underscore)
2891
+ str = str.replaceAll("_", "");
2892
+ return parseInteger(ctx, str, base, startPtr);
2893
+ }
2894
+ function parseInteger(ctx, str, base, startPtr) {
2895
+ if (ctx.bi !== true)
2896
+ int: {
2897
+ let val = parseInt(str, base);
2898
+ if (!Number.isSafeInteger(val)) {
2899
+ if (ctx.bi)
2900
+ break int;
2901
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
2902
+ }
2903
+ return val;
2904
+ }
2905
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
2906
+ }
2907
+ function parseDate(ctx, c, endChr) {
2908
+ let startPtr = ctx.p++, unsafeSeparator;
2909
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
2910
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
2911
+ }
2912
+ ctx.p += 5;
2913
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
2914
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
2915
+ 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) {
2916
+ let t2 = ctx.s.slice(startPtr, ctx.p);
2917
+ return readDate(ctx, t2, 3, false, startPtr);
2918
+ }
2919
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
2920
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
2921
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
2922
+ ctx.p += 3;
2923
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2924
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2925
+ ;
2926
+ if (c = ctx.s.charCodeAt(ctx.p)) {
2927
+ if (c === 90 || c === 122) {
2928
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
2929
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
2930
+ }
2931
+ if (c === 43 || c === 45) {
2932
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
2933
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
2934
+ }
2935
+ }
2936
+ let t = ctx.s.slice(startPtr, ctx.p);
2937
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
2938
+ }
2939
+ function parseTime(ctx, c, endChr) {
2940
+ let start = ctx.p;
2941
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
2942
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
2943
+ }
2944
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
2945
+ ctx.p += 3;
2946
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2947
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2948
+ ;
2949
+ let t = ctx.s.slice(start, ctx.p);
2950
+ return readDate(ctx, t, 4, false, start);
2951
+ }
2952
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
2953
+ if (ctx.ld) {
2954
+ let date = new TomlDate(str, type, unsafeDelim);
2955
+ if (!date.isValid())
2956
+ TomlError.x("invalid date", ctx, errPtr);
2957
+ return date;
2958
+ }
2959
+ try {
2960
+ if (temporalSuffix)
2961
+ str += temporalSuffix;
2962
+ switch (type) {
2963
+ case 1:
2964
+ return Temporal.ZonedDateTime.from(str);
2965
+ case 2:
2966
+ return Temporal.PlainDateTime.from(str);
2967
+ case 3:
2968
+ return Temporal.PlainDate.from(str);
2969
+ case 4:
2970
+ return Temporal.PlainTime.from(str);
2971
+ }
2972
+ } catch (e) {
2973
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
2974
+ }
2975
+ }
2976
+
2977
+ function skipComment(ctx) {
2978
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2979
+ let c = ctx.s.charCodeAt(ctx.p);
2980
+ if (c === 10)
2981
+ break;
2982
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
2983
+ ctx.p++;
2984
+ break;
2985
+ }
2986
+ if (c < 32 && c !== 9 || c === 127) {
2987
+ TomlError.x("control characters are not allowed in comments", ctx);
2988
+ }
2989
+ }
2990
+ }
2991
+ function skipVoid(ctx, banNewLines, banComments) {
2992
+ let c;
2993
+ while (ctx.p < ctx.s.length) {
2994
+ 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)))
2995
+ ctx.p++;
2996
+ if (banComments || c !== 35)
2997
+ break;
2998
+ skipComment(ctx);
2999
+ }
3000
+ }
3001
+
3002
+ function parseKey(ctx, end = 61) {
3003
+ let startPtr;
3004
+ let state = 0;
3005
+ let parsed = [];
3006
+ let sliceStart;
3007
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
3008
+ do {
3009
+ if (c === end) {
3010
+ if (!state)
3011
+ TomlError.x("unexpected end of key", ctx);
3012
+ if (state === 1)
3013
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3014
+ return ctx.p++, parsed;
3015
+ } else if (c === 46) {
3016
+ if (!state)
3017
+ TomlError.x("illegal empty bare key", ctx);
3018
+ if (state === 1)
3019
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3020
+ state = 0;
3021
+ } else if (!state && (c === 34 || c === 39)) {
3022
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
3023
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
3024
+ parsed.push(parseString(ctx));
3025
+ state = 2;
3026
+ ctx.p--;
3027
+ } else if (c === 32 || c === 9) {
3028
+ if (state === 1) {
3029
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3030
+ state = 2;
3031
+ }
3032
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
3033
+ TomlError.x("illegal character in key", ctx);
3034
+ } else if (!state) {
3035
+ state = 1;
3036
+ sliceStart = ctx.p;
3037
+ }
3038
+ } while (c = ctx.s.charCodeAt(++ctx.p));
3039
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
3040
+ }
3041
+ function parseInlineTable(ctx) {
3042
+ let startPtr = ctx.p++;
3043
+ let res = /* @__PURE__ */ Object.create(null);
3044
+ let seen = /* @__PURE__ */ new Set();
3045
+ let c;
3046
+ while (ctx.p < ctx.s.length) {
3047
+ skipVoid(ctx);
3048
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
3049
+ ctx.p++;
3050
+ return res;
3051
+ }
3052
+ let k;
3053
+ let t = res;
3054
+ let hasOwn = false;
3055
+ let errPtr = ctx.p;
3056
+ let key = parseKey(ctx);
3057
+ for (let i = 0; i < key.length; i++) {
3058
+ if (i)
3059
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3060
+ k = key[i];
3061
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
3062
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3063
+ }
3064
+ let unsafe = k === "__proto__";
3065
+ if (ctx.uk && (unsafe || k === "constructor")) {
3066
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
3067
+ break;
3068
+ }
3069
+ if (!hasOwn && unsafe) {
3070
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3071
+ }
3072
+ }
3073
+ if (hasOwn) {
3074
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3075
+ }
3076
+ skipVoid(ctx, true, true);
3077
+ let value = extractValue(
3078
+ ctx,
3079
+ 125
3080
+ /* } */
3081
+ );
3082
+ if (t && typeof (t[k] = value) === "object")
3083
+ seen.add(value);
3084
+ skipVoid(ctx);
3085
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
3086
+ return res;
3087
+ }
3088
+ if (c !== 44)
3089
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3090
+ }
3091
+ TomlError.x("unfinished table", ctx, startPtr);
3092
+ }
3093
+ function parseArray(ctx) {
3094
+ let startPtr = ctx.p++;
3095
+ let res = [];
3096
+ let c;
3097
+ while (ctx.p < ctx.s.length) {
3098
+ skipVoid(ctx);
3099
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
3100
+ ctx.p++;
3101
+ return res;
3102
+ }
3103
+ res.push(extractValue(
3104
+ ctx,
3105
+ 93
3106
+ /* ] */
3107
+ ));
3108
+ skipVoid(ctx);
3109
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
3110
+ return res;
3111
+ }
3112
+ if (c !== 44)
3113
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3114
+ }
3115
+ TomlError.x("unfinished array", ctx, startPtr);
3116
+ }
3117
+
3118
+ function peekTable(ctx, key, table, meta, type) {
3119
+ let t = table;
3120
+ let m = meta;
3121
+ let k;
3122
+ let hasOwn = false;
3123
+ let state;
3124
+ for (let i = 0; i < key.length; i++) {
3125
+ if (i) {
3126
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3127
+ m = (state = m[k]).c;
3128
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
3129
+ return null;
3130
+ }
3131
+ if (state.t === 2) {
3132
+ let l = t.length - 1;
3133
+ t = t[l];
3134
+ m = m[l].c;
3135
+ }
3136
+ }
3137
+ k = key[i];
3138
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
3139
+ return null;
3140
+ }
3141
+ if (!hasOwn) {
3142
+ let unsafe = k === "__proto__";
3143
+ if (ctx.uk && (unsafe || k === "constructor"))
3144
+ return false;
3145
+ if (unsafe) {
3146
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3147
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
3148
+ }
3149
+ m[k] = {
3150
+ t: i < key.length - 1 && type === 2 ? 3 : type,
3151
+ d: false,
3152
+ i: 0,
3153
+ c: /* @__PURE__ */ Object.create(null)
3154
+ };
3155
+ }
3156
+ }
3157
+ state = m[k];
3158
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
3159
+ return null;
3160
+ }
3161
+ if (type === 2) {
3162
+ if (!state.d) {
3163
+ state.d = true;
3164
+ t[k] = [];
3165
+ }
3166
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
3167
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
3168
+ }
3169
+ if (state.d) {
3170
+ return null;
3171
+ }
3172
+ state.d = true;
3173
+ if (type === 1) {
3174
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3175
+ } else if (type === 0 && hasOwn) {
3176
+ return null;
3177
+ }
3178
+ return [k, t, state.c];
3179
+ }
3180
+ function validateTablePeek(ctx, peek, ptr) {
3181
+ if (peek === null || ctx.uk === 2)
3182
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
3183
+ }
3184
+ function parse(toml, options = {}) {
3185
+ let ctx = {
3186
+ s: toml,
3187
+ p: 0,
3188
+ d: options.maxDepth ?? 1e3,
3189
+ bi: options.integersAsBigInt ?? false,
3190
+ ld: options.useLegacyDate ?? true,
3191
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
3192
+ };
3193
+ let res = /* @__PURE__ */ Object.create(null);
3194
+ let meta = /* @__PURE__ */ Object.create(null);
3195
+ let tmp;
3196
+ let skipping = false;
3197
+ let tbl = res;
3198
+ let m = meta;
3199
+ if (toml.charCodeAt(0) === 65279)
3200
+ ctx.p++;
3201
+ skipVoid(ctx);
3202
+ while (ctx.p < toml.length) {
3203
+ if (toml.charCodeAt(ctx.p) === 91) {
3204
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
3205
+ tmp = ctx.p += +isTableArray;
3206
+ skipping = false;
3207
+ let k = parseKey(
3208
+ ctx,
3209
+ 93
3210
+ /* ] */
3211
+ );
3212
+ if (isTableArray) {
3213
+ if (toml.charCodeAt(ctx.p) !== 93) {
3214
+ TomlError.x("expected end of table array declaration", ctx);
3215
+ }
3216
+ ctx.p++;
3217
+ }
3218
+ let p = peekTable(
3219
+ ctx,
3220
+ k,
3221
+ res,
3222
+ meta,
3223
+ isTableArray ? 2 : 1
3224
+ /* Type.EXPLICIT */
3225
+ );
3226
+ if (!p) {
3227
+ validateTablePeek(ctx, p, tmp);
3228
+ skipping = true;
3229
+ } else {
3230
+ m = p[2];
3231
+ tbl = p[1];
3232
+ }
3233
+ } else {
3234
+ tmp = ctx.p;
3235
+ let k = parseKey(ctx);
3236
+ let p = peekTable(
3237
+ ctx,
3238
+ k,
3239
+ tbl,
3240
+ m,
3241
+ 0
3242
+ /* Type.DOTTED */
3243
+ );
3244
+ if (!p && !skipping)
3245
+ validateTablePeek(ctx, p, tmp);
3246
+ skipVoid(ctx, true, true);
3247
+ let v = extractValue(ctx, void 0);
3248
+ if (p && !skipping)
3249
+ p[1][p[0]] = v;
3250
+ }
3251
+ skipVoid(ctx, true);
3252
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
3253
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
3254
+ }
3255
+ skipVoid(ctx);
3256
+ }
3257
+ return res;
3258
+ }
3259
+
3260
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
3261
+ function formatTomlKey(key) {
3262
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
3263
+ }
3264
+ function formatTomlValue(value) {
3265
+ if (typeof value === "boolean") return value ? "true" : "false";
3266
+ return JSON.stringify(value).replace(/\u007f/g, "\\u007F");
3267
+ }
3268
+ function splitDottedKey(raw) {
3269
+ const parts = [];
3270
+ let i = 0;
3271
+ const s = raw.trim();
3272
+ while (i < s.length) {
3273
+ while (s[i] === " " || s[i] === " ") i++;
3274
+ let part = "";
3275
+ if (s[i] === '"') {
3276
+ let j = i + 1;
3277
+ while (j < s.length && s[j] !== '"') {
3278
+ if (s[j] === "\\") j++;
3279
+ j++;
3280
+ }
3281
+ if (j >= s.length) return null;
3282
+ try {
3283
+ part = JSON.parse(s.slice(i, j + 1));
3284
+ } catch {
3285
+ return null;
3286
+ }
3287
+ i = j + 1;
3288
+ } else if (s[i] === "'") {
3289
+ const j = s.indexOf("'", i + 1);
3290
+ if (j < 0) return null;
3291
+ part = s.slice(i + 1, j);
3292
+ i = j + 1;
3293
+ } else {
3294
+ let j = i;
3295
+ while (j < s.length && /[A-Za-z0-9_-]/.test(s[j])) j++;
3296
+ if (j === i) return null;
3297
+ part = s.slice(i, j);
3298
+ i = j;
3299
+ }
3300
+ parts.push(part);
3301
+ while (s[i] === " " || s[i] === " ") i++;
3302
+ if (i >= s.length) break;
3303
+ if (s[i] !== ".") return null;
3304
+ i++;
3305
+ }
3306
+ return parts.length ? parts : null;
3307
+ }
3308
+ function scan(lines) {
3309
+ const sections = [{ path: null, arrayTable: false, headerLine: -1, start: 0, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: -1 }];
3310
+ let inMulti = null;
3311
+ let depth = 0;
3312
+ for (let n = 0; n < lines.length; n++) {
3313
+ const line = lines[n];
3314
+ const current = sections[sections.length - 1];
3315
+ if (inMulti) {
3316
+ if (line.includes(inMulti)) {
3317
+ inMulti = null;
3318
+ current.lastKeyLine = n;
3319
+ }
3320
+ continue;
3321
+ }
3322
+ const trimmed = line.trim();
3323
+ if (depth === 0) {
3324
+ const header = /^\[(\[)?\s*([^\[\]]+?)\s*\](\])?\s*(#.*)?$/.exec(trimmed);
3325
+ if (header) {
3326
+ current.end = n;
3327
+ const path = splitDottedKey(header[2]);
3328
+ sections.push({ path: path ?? [`\0invalid:${header[2]}`], arrayTable: !!header[1], headerLine: n, start: n + 1, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: n });
3329
+ continue;
3330
+ }
3331
+ const kv = /^((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s"'-])+?)\s*=/.exec(trimmed);
3332
+ if (kv) {
3333
+ const keyPath = splitDottedKey(kv[1]);
3334
+ if (keyPath) current.keys.set(keyPath.join("\0"), n);
3335
+ current.lastKeyLine = n;
3336
+ }
3337
+ } else if (trimmed) {
3338
+ current.lastKeyLine = n;
3339
+ }
3340
+ let i = 0;
3341
+ while (i < line.length) {
3342
+ const ch = line[i];
3343
+ if (ch === "#") break;
3344
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
3345
+ const fence = line.slice(i, i + 3);
3346
+ const close = line.indexOf(fence, i + 3);
3347
+ if (close < 0) {
3348
+ inMulti = fence;
3349
+ break;
3350
+ }
3351
+ i = close + 3;
3352
+ continue;
3353
+ }
3354
+ if (ch === '"') {
3355
+ i++;
3356
+ while (i < line.length && line[i] !== '"') {
3357
+ if (line[i] === "\\") i++;
3358
+ i++;
3359
+ }
3360
+ i++;
3361
+ continue;
3362
+ }
3363
+ if (ch === "'") {
3364
+ const close = line.indexOf("'", i + 1);
3365
+ i = close < 0 ? line.length : close + 1;
3366
+ continue;
3367
+ }
3368
+ if (ch === "[" || ch === "{") depth++;
3369
+ if (ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
3370
+ i++;
3371
+ }
3372
+ }
3373
+ return sections;
3374
+ }
3375
+ function trailingComment(line) {
3376
+ const m = /^\s*[^=]+=\s*("(?:[^"\\]|\\.)*"|'[^']*'|true|false|[0-9][0-9_.eE+-]*)(\s+#.*)$/.exec(line);
3377
+ return m ? m[2] : "";
3378
+ }
3379
+ const samePath = (a, b) => a !== null && a.length === b.length && a.every((p, i) => p === b[i]);
3380
+ const isUnder = (a, prefix) => a !== null && a.length >= prefix.length && prefix.every((p, i) => p === a[i]);
3381
+ function applyOne(text, edit) {
3382
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3383
+ const lines = text.split(/\r?\n/);
3384
+ const sections = scan(lines);
3385
+ if ("removeTable" in edit) {
3386
+ const doomed = sections.filter((s) => !s.arrayTable && isUnder(s.path, edit.table)).sort((a, b) => b.headerLine - a.headerLine);
3387
+ for (const s of doomed) {
3388
+ let end = s.end;
3389
+ while (end > s.start && lines[end - 1]?.trim() === "" && end - 1 > s.lastKeyLine) end--;
3390
+ lines.splice(s.headerLine, end - s.headerLine);
3391
+ }
3392
+ return lines.join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`).replace(/(\r?\n)+$/, eol);
3393
+ }
3394
+ const root = edit.table.length === 0;
3395
+ const section = root ? sections[0] : sections.find((s) => !s.arrayTable && samePath(s.path, edit.table));
3396
+ const keyId = edit.key;
3397
+ const rendered = edit.value === null ? null : `${formatTomlKey(edit.key)} = ${formatTomlValue(edit.value)}`;
3398
+ if (section) {
3399
+ const at = section.keys.get(keyId);
3400
+ if (at !== void 0) {
3401
+ const indent = /^\s*/.exec(lines[at])?.[0] ?? "";
3402
+ if (rendered === null) lines.splice(at, 1);
3403
+ else lines[at] = indent + rendered + trailingComment(lines[at]);
3404
+ return lines.join(eol);
3405
+ }
3406
+ if (rendered === null) return text;
3407
+ if (root) {
3408
+ const anchor = section.lastKeyLine;
3409
+ lines.splice(anchor + 1, 0, rendered);
3410
+ } else {
3411
+ lines.splice(section.lastKeyLine + 1, 0, rendered);
3412
+ }
3413
+ return lines.join(eol);
3414
+ }
3415
+ if (rendered === null) return text;
3416
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
3417
+ const header = `[${edit.table.map(formatTomlKey).join(".")}]`;
3418
+ if (lines.length) lines.push("");
3419
+ lines.push(header, rendered, "");
3420
+ return lines.join(eol);
3421
+ }
3422
+ function parseToml(text) {
3423
+ try {
3424
+ return parse(text);
3425
+ } catch (error) {
3426
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
3427
+ throw new fileStore.ModelConfigError("invalid-toml", `Not valid TOML: ${message}`);
3428
+ }
3429
+ }
3430
+ function getPath(obj, path) {
3431
+ let cur = obj;
3432
+ for (const p of path) {
3433
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
3434
+ cur = cur[p];
3435
+ }
3436
+ return cur;
3437
+ }
3438
+ function withoutPaths(obj, paths) {
3439
+ const clone = structuredClone(obj);
3440
+ for (const path of paths) {
3441
+ let cur = clone;
3442
+ for (const p of path.slice(0, -1)) {
3443
+ if (!cur || typeof cur !== "object") {
3444
+ cur = null;
3445
+ break;
3446
+ }
3447
+ cur = cur[p];
3448
+ }
3449
+ if (cur && typeof cur === "object") delete cur[path[path.length - 1]];
3450
+ }
3451
+ return clone;
3452
+ }
3453
+ function pruneEmpty(value) {
3454
+ if (!value || typeof value !== "object" || Array.isArray(value) || value instanceof Date) return value;
3455
+ const out = {};
3456
+ for (const [k, v] of Object.entries(value)) {
3457
+ const pruned = pruneEmpty(v);
3458
+ if (pruned && typeof pruned === "object" && !Array.isArray(pruned) && !(pruned instanceof Date) && Object.keys(pruned).length === 0) continue;
3459
+ out[k] = pruned;
3460
+ }
3461
+ return out;
3462
+ }
3463
+ function stableStringify(value) {
3464
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
3465
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
3466
+ if (value && typeof value === "object") {
3467
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
3468
+ }
3469
+ return JSON.stringify(value) ?? "null";
3470
+ }
3471
+ function verifyTomlEdit(oldText, newText, edits) {
3472
+ const before = parseToml(oldText);
3473
+ let after;
3474
+ try {
3475
+ after = parse(newText);
3476
+ } catch (error) {
3477
+ throw new fileStore.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`);
3478
+ }
3479
+ const owned = edits.map((e) => "removeTable" in e ? e.table : [...e.table, e.key]);
3480
+ for (const edit of edits) {
3481
+ if ("removeTable" in edit) {
3482
+ if (getPath(after, edit.table) !== void 0) throw new fileStore.ModelConfigError("unsafe-edit", `Table ${edit.table.join(".")} is still present after removal`);
3483
+ continue;
3484
+ }
3485
+ const got = getPath(after, [...edit.table, edit.key]);
3486
+ const want = edit.value === null ? void 0 : edit.value;
3487
+ if (got !== want) throw new fileStore.ModelConfigError("unsafe-edit", `Key ${[...edit.table, edit.key].join(".")} did not take the requested value`);
3488
+ }
3489
+ if (stableStringify(pruneEmpty(withoutPaths(before, owned))) !== stableStringify(pruneEmpty(withoutPaths(after, owned)))) {
3490
+ throw new fileStore.ModelConfigError("unsafe-edit", "Edit would change settings outside the keys Very Happy manages");
3491
+ }
3492
+ }
3493
+ function editToml(text, edits) {
3494
+ parseToml(text);
3495
+ let out = text;
3496
+ const ordered = [...edits.filter((e) => e.table.length === 0), ...edits.filter((e) => e.table.length > 0)];
3497
+ for (const edit of ordered) out = applyOne(out, edit);
3498
+ if (out !== text && !out.endsWith("\n")) out += text.includes("\r\n") ? "\r\n" : "\n";
3499
+ verifyTomlEdit(text, out, edits);
3500
+ return out;
3501
+ }
3502
+
3503
+ const ROLE = "config";
3504
+ const CODEX_RESERVED_PROVIDERS = ["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "oss"];
3505
+ function codexConfigPath(ctx) {
3506
+ const dir = ctx.env.CODEX_HOME?.trim() || path.join(ctx.home, ".codex");
3507
+ return path.join(dir, "config.toml");
3508
+ }
3509
+ const str$2 = (v) => typeof v === "string" && v.trim() ? v : null;
3510
+ function providersOf(doc) {
3511
+ const table = doc.model_providers;
3512
+ if (!table || typeof table !== "object" || Array.isArray(table)) return {};
3513
+ return Object.fromEntries(Object.entries(table).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
3514
+ }
3515
+ function secretView(provider, ctx) {
3516
+ if (!provider) return { mode: "none" };
3517
+ const token = str$2(provider.experimental_bearer_token);
3518
+ if (token) return { mode: "literal", masked: pi.maskSecret(token) };
3519
+ const envKey = str$2(provider.env_key);
3520
+ if (envKey) return { mode: "env", envName: envKey, envPresent: !!ctx.env[envKey] };
3521
+ if (provider.auth && typeof provider.auth === "object") return { mode: "command" };
3522
+ return { mode: "none" };
3523
+ }
3524
+ function selectProvider(doc, requested) {
3525
+ const providers = providersOf(doc);
3526
+ if (requested) return requested;
3527
+ const active = str$2(doc.model_provider);
3528
+ if (active && providers[active]) return active;
3529
+ return Object.keys(providers)[0] ?? null;
3530
+ }
3531
+ function currentOf$1(doc, providerId, ctx) {
3532
+ const provider = providerId ? providersOf(doc)[providerId] : void 0;
3533
+ const activeProvider = str$2(doc.model_provider);
3534
+ return {
3535
+ providerId,
3536
+ providerName: str$2(provider?.name),
3537
+ baseUrl: str$2(provider?.base_url),
3538
+ apiKey: secretView(provider, ctx),
3539
+ model: str$2(doc.model),
3540
+ activeProvider,
3541
+ active: !!providerId && activeProvider === providerId
3542
+ };
3543
+ }
3544
+ function warningsOf$1(doc, current) {
3545
+ const out = [...pi.baseUrlWarnings(current.baseUrl, "openai")];
3546
+ const provider = current.providerId ? providersOf(doc)[current.providerId] : void 0;
3547
+ if (provider && str$2(provider.wire_api) && provider.wire_api !== "responses") {
3548
+ out.push({ code: "wire-api-unsupported", message: `wire_api = "${String(provider.wire_api)}" is rejected by current Codex; only "responses" is supported.` });
3549
+ }
3550
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
3551
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
3552
+ }
3553
+ const active = current.activeProvider;
3554
+ if (active && !CODEX_RESERVED_PROVIDERS.includes(active) && !providersOf(doc)[active]) {
3555
+ out.push({ code: "active-provider-missing", message: `model_provider = "${active}" has no [model_providers.${active}] table.` });
3556
+ }
3557
+ return out;
3558
+ }
3559
+ function parsePatch(raw) {
3560
+ const p = raw;
3561
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") pi.fail("invalid-input", "activate must be a boolean");
3562
+ if (p.providerName !== void 0 && (typeof p.providerName !== "string" || p.providerName.length > 120 || /[\u0000-\u001f]/.test(p.providerName))) {
3563
+ pi.fail("invalid-input", "providerName must be a short single-line string");
3564
+ }
3565
+ return {
3566
+ providerId: pi.normalizeProviderId(p.providerId, CODEX_RESERVED_PROVIDERS),
3567
+ providerName: p.providerName?.trim(),
3568
+ baseUrl: pi.normalizeBaseUrl(p.baseUrl),
3569
+ apiKey: pi.normalizeSecret(p.apiKey),
3570
+ model: pi.normalizeModelId(p.model),
3571
+ activate: p.activate
3572
+ };
3573
+ }
3574
+ const codexAdapter = {
3575
+ id: "codex",
3576
+ binary: "codex",
3577
+ files: (ctx) => [{ role: ROLE, path: codexConfigPath(ctx) }],
3578
+ view(files, ctx, opts) {
3579
+ const doc = parseToml(files[ROLE].content);
3580
+ const current = currentOf$1(doc, selectProvider(doc, opts.providerId), ctx);
3581
+ return { current, providers: Object.keys(providersOf(doc)), pickerModels: pi.uniq([current.model]), warnings: warningsOf$1(doc, current) };
3582
+ },
3583
+ plan(files, raw, ctx) {
3584
+ const patch = parsePatch(raw);
3585
+ const original = files[ROLE].content;
3586
+ const before = parseToml(original);
3587
+ const existing = providersOf(before)[patch.providerId];
3588
+ const table = ["model_providers", patch.providerId];
3589
+ const edits = [];
3590
+ const secrets = [];
3591
+ if (!existing && !patch.baseUrl) pi.fail("invalid-input", "A new provider needs a base URL");
3592
+ const name = patch.providerName || str$2(existing?.name) || patch.providerId;
3593
+ if (!existing || patch.providerName && patch.providerName !== existing.name || !str$2(existing.name)) edits.push({ table, key: "name", value: name });
3594
+ if (patch.baseUrl !== void 0) {
3595
+ if (patch.baseUrl === null && existing) pi.fail("invalid-input", "A provider needs a base URL; remove the provider instead");
3596
+ edits.push({ table, key: "base_url", value: patch.baseUrl });
3597
+ }
3598
+ if (!existing || str$2(existing.wire_api) && existing.wire_api !== "responses") edits.push({ table, key: "wire_api", value: "responses" });
3599
+ switch (patch.apiKey.mode) {
3600
+ case "literal":
3601
+ edits.push({ table, key: "experimental_bearer_token", value: patch.apiKey.value }, { table, key: "env_key", value: null });
3602
+ secrets.push(patch.apiKey.value);
3603
+ break;
3604
+ case "env":
3605
+ edits.push({ table, key: "env_key", value: patch.apiKey.name }, { table, key: "experimental_bearer_token", value: null });
3606
+ break;
3607
+ case "clear":
3608
+ edits.push({ table, key: "env_key", value: null }, { table, key: "experimental_bearer_token", value: null });
3609
+ break;
3610
+ }
3611
+ if (patch.model !== void 0) edits.push({ table: [], key: "model", value: patch.model });
3612
+ if (patch.activate === true) edits.push({ table: [], key: "model_provider", value: patch.providerId });
3613
+ if (patch.activate === false && str$2(before.model_provider) === patch.providerId) edits.push({ table: [], key: "model_provider", value: null });
3614
+ const effective = edits.filter((e) => "removeTable" in e || pi.getPath(before, [...e.table, e.key]) !== (e.value ?? void 0));
3615
+ const content = effective.length ? editToml(original, effective) : void 0;
3616
+ const after = content === void 0 ? before : parseToml(content);
3617
+ const current = currentOf$1(after, patch.providerId, ctx);
3618
+ const changedKeys = effective.map((e) => [...e.table, "removeTable" in e ? "*" : e.key].join("."));
3619
+ return { contents: { [ROLE]: content }, warnings: warningsOf$1(after, current), changedKeys, secrets };
3620
+ },
3621
+ secretsIn(_role, content) {
3622
+ try {
3623
+ return pi.collectSecretValues(parseToml(content));
3624
+ } catch (error) {
3625
+ if (error instanceof fileStore.ModelConfigError) return /* @__PURE__ */ new Set();
3626
+ throw error;
3627
+ }
3628
+ }
3629
+ };
3630
+
3631
+ var main = {exports: {}};
3632
+
3633
+ var version = "16.6.1";
3634
+ var require$$4 = {
3635
+ version: version};
3636
+
3637
+ var hasRequiredMain;
3638
+
3639
+ function requireMain () {
3640
+ if (hasRequiredMain) return main.exports;
3641
+ hasRequiredMain = 1;
3642
+ const fs = require$$0;
3643
+ const path = require$$1;
3644
+ const os = os$1;
3645
+ const crypto = require$$3;
3646
+ const packageJson = require$$4;
3647
+ const version = packageJson.version;
3648
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
3649
+ function parse(src) {
3650
+ const obj = {};
3651
+ let lines = src.toString();
3652
+ lines = lines.replace(/\r\n?/mg, "\n");
3653
+ let match;
3654
+ while ((match = LINE.exec(lines)) != null) {
3655
+ const key = match[1];
3656
+ let value = match[2] || "";
3657
+ value = value.trim();
3658
+ const maybeQuote = value[0];
3659
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
3660
+ if (maybeQuote === '"') {
3661
+ value = value.replace(/\\n/g, "\n");
3662
+ value = value.replace(/\\r/g, "\r");
3663
+ }
3664
+ obj[key] = value;
3665
+ }
3666
+ return obj;
3667
+ }
3668
+ function _parseVault(options) {
3669
+ options = options || {};
3670
+ const vaultPath = _vaultPath(options);
3671
+ options.path = vaultPath;
3672
+ const result = DotenvModule.configDotenv(options);
3673
+ if (!result.parsed) {
3674
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
3675
+ err.code = "MISSING_DATA";
3676
+ throw err;
3677
+ }
3678
+ const keys = _dotenvKey(options).split(",");
3679
+ const length = keys.length;
3680
+ let decrypted;
3681
+ for (let i = 0; i < length; i++) {
3682
+ try {
3683
+ const key = keys[i].trim();
3684
+ const attrs = _instructions(result, key);
3685
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
3686
+ break;
3687
+ } catch (error) {
3688
+ if (i + 1 >= length) {
3689
+ throw error;
3690
+ }
3691
+ }
3692
+ }
3693
+ return DotenvModule.parse(decrypted);
3694
+ }
3695
+ function _warn(message) {
3696
+ console.log(`[dotenv@${version}][WARN] ${message}`);
3697
+ }
3698
+ function _debug(message) {
3699
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
3700
+ }
3701
+ function _log(message) {
3702
+ console.log(`[dotenv@${version}] ${message}`);
3703
+ }
3704
+ function _dotenvKey(options) {
3705
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
3706
+ return options.DOTENV_KEY;
3707
+ }
3708
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
3709
+ return process.env.DOTENV_KEY;
3710
+ }
3711
+ return "";
3712
+ }
3713
+ function _instructions(result, dotenvKey) {
3714
+ let uri;
3715
+ try {
3716
+ uri = new URL(dotenvKey);
3717
+ } catch (error) {
3718
+ if (error.code === "ERR_INVALID_URL") {
3719
+ 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");
3720
+ err.code = "INVALID_DOTENV_KEY";
3721
+ throw err;
3722
+ }
3723
+ throw error;
3724
+ }
3725
+ const key = uri.password;
3726
+ if (!key) {
3727
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
3728
+ err.code = "INVALID_DOTENV_KEY";
3729
+ throw err;
3730
+ }
3731
+ const environment = uri.searchParams.get("environment");
3732
+ if (!environment) {
3733
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
3734
+ err.code = "INVALID_DOTENV_KEY";
3735
+ throw err;
3736
+ }
3737
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
3738
+ const ciphertext = result.parsed[environmentKey];
3739
+ if (!ciphertext) {
3740
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
3741
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
3742
+ throw err;
3743
+ }
3744
+ return { ciphertext, key };
3745
+ }
3746
+ function _vaultPath(options) {
3747
+ let possibleVaultPath = null;
3748
+ if (options && options.path && options.path.length > 0) {
3749
+ if (Array.isArray(options.path)) {
3750
+ for (const filepath of options.path) {
3751
+ if (fs.existsSync(filepath)) {
3752
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
3753
+ }
3754
+ }
3755
+ } else {
3756
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
3757
+ }
3758
+ } else {
3759
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
3760
+ }
3761
+ if (fs.existsSync(possibleVaultPath)) {
3762
+ return possibleVaultPath;
3763
+ }
3764
+ return null;
3765
+ }
3766
+ function _resolveHome(envPath) {
3767
+ return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
3768
+ }
3769
+ function _configVault(options) {
3770
+ const debug = Boolean(options && options.debug);
3771
+ const quiet = options && "quiet" in options ? options.quiet : true;
3772
+ if (debug || !quiet) {
3773
+ _log("Loading env from encrypted .env.vault");
3774
+ }
3775
+ const parsed = DotenvModule._parseVault(options);
3776
+ let processEnv = process.env;
3777
+ if (options && options.processEnv != null) {
3778
+ processEnv = options.processEnv;
3779
+ }
3780
+ DotenvModule.populate(processEnv, parsed, options);
3781
+ return { parsed };
3782
+ }
3783
+ function configDotenv(options) {
3784
+ const dotenvPath = path.resolve(process.cwd(), ".env");
3785
+ let encoding = "utf8";
3786
+ const debug = Boolean(options && options.debug);
3787
+ const quiet = options && "quiet" in options ? options.quiet : true;
3788
+ if (options && options.encoding) {
3789
+ encoding = options.encoding;
3790
+ } else {
3791
+ if (debug) {
3792
+ _debug("No encoding is specified. UTF-8 is used by default");
3793
+ }
3794
+ }
3795
+ let optionPaths = [dotenvPath];
3796
+ if (options && options.path) {
3797
+ if (!Array.isArray(options.path)) {
3798
+ optionPaths = [_resolveHome(options.path)];
3799
+ } else {
3800
+ optionPaths = [];
3801
+ for (const filepath of options.path) {
3802
+ optionPaths.push(_resolveHome(filepath));
3803
+ }
3804
+ }
3805
+ }
3806
+ let lastError;
3807
+ const parsedAll = {};
3808
+ for (const path2 of optionPaths) {
3809
+ try {
3810
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
3811
+ DotenvModule.populate(parsedAll, parsed, options);
3812
+ } catch (e) {
3813
+ if (debug) {
3814
+ _debug(`Failed to load ${path2} ${e.message}`);
3815
+ }
3816
+ lastError = e;
3817
+ }
3818
+ }
3819
+ let processEnv = process.env;
3820
+ if (options && options.processEnv != null) {
3821
+ processEnv = options.processEnv;
3822
+ }
3823
+ DotenvModule.populate(processEnv, parsedAll, options);
3824
+ if (debug || !quiet) {
3825
+ const keysCount = Object.keys(parsedAll).length;
3826
+ const shortPaths = [];
3827
+ for (const filePath of optionPaths) {
3828
+ try {
3829
+ const relative = path.relative(process.cwd(), filePath);
3830
+ shortPaths.push(relative);
3831
+ } catch (e) {
3832
+ if (debug) {
3833
+ _debug(`Failed to load ${filePath} ${e.message}`);
3834
+ }
3835
+ lastError = e;
3836
+ }
3837
+ }
3838
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
3839
+ }
3840
+ if (lastError) {
3841
+ return { parsed: parsedAll, error: lastError };
3842
+ } else {
3843
+ return { parsed: parsedAll };
3844
+ }
3845
+ }
3846
+ function config(options) {
3847
+ if (_dotenvKey(options).length === 0) {
3848
+ return DotenvModule.configDotenv(options);
3849
+ }
3850
+ const vaultPath = _vaultPath(options);
3851
+ if (!vaultPath) {
3852
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
3853
+ return DotenvModule.configDotenv(options);
3854
+ }
3855
+ return DotenvModule._configVault(options);
3856
+ }
3857
+ function decrypt(encrypted, keyStr) {
3858
+ const key = Buffer.from(keyStr.slice(-64), "hex");
3859
+ let ciphertext = Buffer.from(encrypted, "base64");
3860
+ const nonce = ciphertext.subarray(0, 12);
3861
+ const authTag = ciphertext.subarray(-16);
3862
+ ciphertext = ciphertext.subarray(12, -16);
3863
+ try {
3864
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
3865
+ aesgcm.setAuthTag(authTag);
3866
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
3867
+ } catch (error) {
3868
+ const isRange = error instanceof RangeError;
3869
+ const invalidKeyLength = error.message === "Invalid key length";
3870
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
3871
+ if (isRange || invalidKeyLength) {
3872
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
3873
+ err.code = "INVALID_DOTENV_KEY";
3874
+ throw err;
3875
+ } else if (decryptionFailed) {
3876
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
3877
+ err.code = "DECRYPTION_FAILED";
3878
+ throw err;
3879
+ } else {
3880
+ throw error;
3881
+ }
3882
+ }
3883
+ }
3884
+ function populate(processEnv, parsed, options = {}) {
3885
+ const debug = Boolean(options && options.debug);
3886
+ const override = Boolean(options && options.override);
3887
+ if (typeof parsed !== "object") {
3888
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
3889
+ err.code = "OBJECT_REQUIRED";
3890
+ throw err;
3891
+ }
3892
+ for (const key of Object.keys(parsed)) {
3893
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
3894
+ if (override === true) {
3895
+ processEnv[key] = parsed[key];
3896
+ }
3897
+ if (debug) {
3898
+ if (override === true) {
3899
+ _debug(`"${key}" is already defined and WAS overwritten`);
3900
+ } else {
3901
+ _debug(`"${key}" is already defined and was NOT overwritten`);
3902
+ }
3903
+ }
3904
+ } else {
3905
+ processEnv[key] = parsed[key];
3906
+ }
3907
+ }
3908
+ }
3909
+ const DotenvModule = {
3910
+ configDotenv,
3911
+ _configVault,
3912
+ _parseVault,
3913
+ config,
3914
+ decrypt,
3915
+ parse,
3916
+ populate
3917
+ };
3918
+ main.exports.configDotenv = DotenvModule.configDotenv;
3919
+ main.exports._configVault = DotenvModule._configVault;
3920
+ main.exports._parseVault = DotenvModule._parseVault;
3921
+ main.exports.config = DotenvModule.config;
3922
+ main.exports.decrypt = DotenvModule.decrypt;
3923
+ main.exports.parse = DotenvModule.parse;
3924
+ main.exports.populate = DotenvModule.populate;
3925
+ main.exports = DotenvModule;
3926
+ return main.exports;
3927
+ }
3928
+
3929
+ var mainExports = requireMain();
3930
+
3931
+ const LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
3932
+ function parseDotenv(text) {
3933
+ return mainExports.parse(text);
3934
+ }
3935
+ function formatDotenvValue(value) {
3936
+ if (/^[A-Za-z0-9_./:@+,-]*$/.test(value)) return value;
3937
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
3938
+ }
3939
+ function editDotenv(text, edits) {
3940
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3941
+ let lines = text === "" ? [] : text.split(/\r?\n/);
3942
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
3943
+ for (const edit of edits) {
3944
+ const at = lines.map((l, i) => LINE.exec(l)?.[1] === edit.key ? i : -1).filter((i) => i >= 0);
3945
+ if (edit.value === null) {
3946
+ lines = lines.filter((_, i) => !at.includes(i));
3947
+ continue;
3948
+ }
3949
+ const rendered = `${edit.key}=${formatDotenvValue(edit.value)}`;
3950
+ if (at.length) {
3951
+ lines[at[0]] = rendered;
3952
+ lines = lines.filter((_, i) => !at.slice(1).includes(i));
3953
+ } else {
3954
+ lines.push(rendered);
3955
+ }
3956
+ }
3957
+ const out = lines.length ? lines.join(eol) + eol : "";
3958
+ const before = mainExports.parse(text);
3959
+ const after = mainExports.parse(out);
3960
+ for (const edit of edits) {
3961
+ if ((after[edit.key] ?? null) !== edit.value) throw new fileStore.ModelConfigError("unsafe-edit", `.env edit did not produce ${edit.key} as requested`);
3962
+ delete before[edit.key];
3963
+ delete after[edit.key];
3964
+ }
3965
+ if (JSON.stringify(Object.entries(before).sort()) !== JSON.stringify(Object.entries(after).sort())) {
3966
+ throw new fileStore.ModelConfigError("unsafe-edit", ".env edit would change other variables");
3967
+ }
3968
+ return out;
3969
+ }
3970
+
3971
+ const SETTINGS = "settings";
3972
+ const ENV = "env";
3973
+ const BASE_URL = "GOOGLE_GEMINI_BASE_URL";
3974
+ const API_KEY = "GEMINI_API_KEY";
3975
+ function geminiDir(ctx) {
3976
+ return path.join(ctx.env.GEMINI_CLI_HOME?.trim() || ctx.home, ".gemini");
3977
+ }
3978
+ const str$1 = (v) => typeof v === "string" && v.trim() ? v : null;
3979
+ function currentOf(settings, env, ctx) {
3980
+ const literal = str$1(env[API_KEY]);
3981
+ const apiKey = literal ? { mode: "literal", masked: pi.maskSecret(literal) } : ctx.env[API_KEY] ? { mode: "env", envName: API_KEY, envPresent: true } : { mode: "none" };
3982
+ return { baseUrl: str$1(env[BASE_URL]), apiKey, model: str$1(pi.getPath(settings, ["model", "name"])) };
3983
+ }
3984
+ function warningsOf(settings, current) {
3985
+ const out = [...pi.baseUrlWarnings(current.baseUrl, "gemini")];
3986
+ if (current.baseUrl || current.apiKey?.mode === "literal") {
3987
+ 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." });
3988
+ }
3989
+ const selected = str$1(pi.getPath(settings, ["security", "auth", "selectedType"]));
3990
+ if (current.baseUrl && selected && selected !== "gateway") {
3991
+ out.push({ code: "auth-type-pinned", message: `security.auth.selectedType is "${selected}"; Gemini only uses GOOGLE_GEMINI_BASE_URL with the gateway auth type.` });
3992
+ }
3993
+ if (current.baseUrl && !/^https:/.test(current.baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(current.baseUrl)) {
3994
+ out.push({ code: "gemini-https", message: "Gemini requires an https base URL (localhost excepted)." });
3995
+ }
3996
+ return out;
3997
+ }
3998
+ const geminiAdapter = {
3999
+ id: "gemini",
4000
+ binary: "gemini",
4001
+ files: (ctx) => [{ role: SETTINGS, path: path.join(geminiDir(ctx), "settings.json") }, { role: ENV, path: path.join(geminiDir(ctx), ".env") }],
4002
+ view(files, ctx) {
4003
+ const settings = pi.parseJsonObject(files[SETTINGS].content, "settings.json");
4004
+ const current = currentOf(settings, parseDotenv(files[ENV].content), ctx);
4005
+ return { current, pickerModels: pi.uniq([current.model]), warnings: warningsOf(settings, current) };
4006
+ },
4007
+ plan(files, raw, ctx) {
4008
+ const p = raw;
4009
+ const baseUrl = pi.normalizeBaseUrl(p.baseUrl);
4010
+ const apiKey = pi.normalizeSecret(p.apiKey, ["keep", "clear", "literal"]);
4011
+ const model = pi.normalizeModelId(p.model);
4012
+ const settingsText = files[SETTINGS].content;
4013
+ const before = pi.parseJsonObject(settingsText, "settings.json");
4014
+ const settings = structuredClone(before);
4015
+ const changedKeys = [];
4016
+ let settingsOut;
4017
+ if (model !== void 0 && (str$1(pi.getPath(before, ["model", "name"])) ?? null) !== model) {
4018
+ const hadModel = settings.model !== void 0;
4019
+ const modelObj = pi.childObject(settings, "model", "settings");
4020
+ pi.setOrDelete(modelObj, "name", model);
4021
+ if (!hadModel && Object.keys(modelObj).length === 0) delete settings.model;
4022
+ settingsOut = pi.stringifyLike(settingsText, settings);
4023
+ changedKeys.push("settings.model.name");
4024
+ }
4025
+ const envText = files[ENV].content;
4026
+ const env = parseDotenv(envText);
4027
+ const edits = [];
4028
+ if (baseUrl !== void 0 && (env[BASE_URL] ?? null) !== baseUrl) edits.push({ key: BASE_URL, value: baseUrl });
4029
+ if (apiKey.mode === "literal" && env[API_KEY] !== apiKey.value) edits.push({ key: API_KEY, value: apiKey.value });
4030
+ if (apiKey.mode === "clear" && env[API_KEY] !== void 0) edits.push({ key: API_KEY, value: null });
4031
+ const envOut = edits.length ? editDotenv(envText, edits) : void 0;
4032
+ changedKeys.push(...edits.map((e) => `.env.${e.key}`));
4033
+ const afterEnv = envOut === void 0 ? env : parseDotenv(envOut);
4034
+ const current = currentOf(settings, afterEnv, ctx);
4035
+ return {
4036
+ contents: { [SETTINGS]: settingsOut, [ENV]: envOut },
4037
+ warnings: warningsOf(settings, current),
4038
+ changedKeys,
4039
+ secrets: apiKey.mode === "literal" ? [apiKey.value] : []
4040
+ };
4041
+ },
4042
+ secretsIn(role, content) {
4043
+ try {
4044
+ return role === ENV ? pi.collectSecretValues(parseDotenv(content)) : pi.collectSecretValues(pi.parseJsonObject(content, "settings.json"));
4045
+ } catch {
4046
+ return /* @__PURE__ */ new Set();
4047
+ }
4048
+ }
4049
+ };
4050
+
4051
+ const MODEL_CONFIG_CAPABILITY_VERSION = 1;
4052
+ const HARNESS_IDS = ["claude", "codex", "gemini", "pi"];
4053
+
4054
+ const ADAPTERS = { claude: claudeAdapter, codex: codexAdapter, gemini: geminiAdapter, pi: pi.piAdapter };
4055
+ function harnessOf(value) {
4056
+ if (typeof value !== "string" || !HARNESS_IDS.includes(value)) {
4057
+ throw new fileStore.ModelConfigError("invalid-harness", `harness must be one of ${HARNESS_IDS.join(", ")}`);
4058
+ }
4059
+ return value;
4060
+ }
4061
+ class ModelConfigService {
4062
+ constructor(opts) {
4063
+ this.opts = opts;
4064
+ this.backups = new fileStore.BackupStore(path.join(opts.happyHomeDir, "model-config-backups"));
4065
+ this.auditPath = path.join(opts.happyHomeDir, "model-config-audit.jsonl");
4066
+ }
4067
+ backups;
4068
+ auditPath;
4069
+ chain = Promise.resolve();
4070
+ get ctx() {
4071
+ return { home: this.opts.home, env: this.opts.env };
4072
+ }
4073
+ serialize(fn) {
4074
+ const next = this.chain.then(fn, fn);
4075
+ this.chain = next.catch(() => {
4076
+ });
4077
+ return next;
4078
+ }
4079
+ async loadFiles(adapter) {
4080
+ const files = {};
4081
+ for (const { role, path } of adapter.files(this.ctx)) files[role] = await fileStore.readConfigFile(path);
4082
+ const baseHash = fileStore.sha256(Object.entries(files).map(([role, f]) => `${role}\0${f.exists ? f.hash : "-"}`).join("\n"));
4083
+ return { files, baseHash };
4084
+ }
4085
+ async readOne(harness, providerId) {
4086
+ const adapter = ADAPTERS[harness];
4087
+ const installed = harness === "claude" || (this.opts.isInstalled?.(adapter.binary) ?? true);
4088
+ const backups = await this.backups.list(harness);
4089
+ let loaded;
4090
+ try {
4091
+ loaded = await this.loadFiles(adapter);
4092
+ } catch (error) {
4093
+ const e = toError(error);
4094
+ return {
4095
+ harness,
4096
+ installed,
4097
+ baseHash: "",
4098
+ current: {},
4099
+ pickerModels: [],
4100
+ backups,
4101
+ warnings: [],
4102
+ files: adapter.files(this.ctx).map((f) => ({ role: f.role, path: f.path, exists: false, error: e }))
4103
+ };
4104
+ }
4105
+ const files = Object.entries(loaded.files).map(([role, f]) => ({ role, path: f.path, exists: f.exists }));
4106
+ try {
4107
+ const view = adapter.view(loaded.files, this.ctx, { providerId });
4108
+ return { harness, installed, files, baseHash: loaded.baseHash, backups, ...view };
4109
+ } catch (error) {
4110
+ const e = toError(error);
4111
+ return { harness, installed, baseHash: loaded.baseHash, current: {}, pickerModels: [], backups, warnings: [], files: files.map((f) => ({ ...f, error: e })) };
4112
+ }
4113
+ }
4114
+ async read(params = {}) {
4115
+ const list = params.harness === void 0 ? [...HARNESS_IDS] : [harnessOf(params.harness)];
4116
+ const providerId = typeof params.providerId === "string" && params.providerId ? params.providerId : void 0;
4117
+ const harnesses = await Promise.all(list.map((h) => this.readOne(h, providerId)));
4118
+ return { version: MODEL_CONFIG_CAPABILITY_VERSION, harnesses };
4119
+ }
4120
+ diffs(adapter, files, next, extraSecrets) {
4121
+ const out = [];
4122
+ for (const [role, file] of Object.entries(files)) {
4123
+ const target = next[role];
4124
+ if (target === void 0) continue;
4125
+ const newText = target ?? "";
4126
+ if (target !== null && file.exists && newText === file.content) continue;
4127
+ if (target === null && !file.exists) continue;
4128
+ const secrets = [...adapter.secretsIn(role, file.content), ...target ? adapter.secretsIn(role, target) : [], ...extraSecrets];
4129
+ const raw = unifiedDiff(file.content, newText, file.path);
4130
+ out.push({ path: file.path, diff: pi.redactText(raw, secrets), created: !file.exists && target !== null, deleted: target === null && file.exists });
4131
+ }
4132
+ return out;
4133
+ }
4134
+ async write(harness, action, files, next, keys, apiKeyMode) {
4135
+ const touched = Object.entries(next).filter(([, v]) => v !== void 0);
4136
+ const snapshot = touched.map(([role]) => ({ path: files[role].path, content: files[role].exists ? files[role].content : null, mode: files[role].mode }));
4137
+ const backup = await this.backups.create(harness, action === "apply" ? "before-apply" : "before-restore", snapshot, this.opts.now?.() ?? Date.now());
4138
+ for (const [role, target] of touched) {
4139
+ const file = files[role];
4140
+ if (target.content === null) await node_fs.promises.rm(file.path, { force: true });
4141
+ else await fileStore.atomicWriteFile(file.path, target.content, file.mode ?? target.mode);
4142
+ }
4143
+ await this.audit({ at: this.opts.now?.() ?? Date.now(), action, harness, files: touched.map(([role]) => files[role].path), keys, apiKeyMode, backupId: backup.id });
4144
+ this.opts.onChanged?.(harness);
4145
+ return backup;
4146
+ }
4147
+ async audit(record) {
4148
+ try {
4149
+ await node_fs.promises.mkdir(this.opts.happyHomeDir, { recursive: true });
4150
+ await node_fs.promises.appendFile(this.auditPath, `${JSON.stringify(record)}
4151
+ `, { encoding: "utf8", mode: 384 });
4152
+ } catch {
4153
+ }
4154
+ }
4155
+ apply(params) {
4156
+ const run = async () => {
4157
+ const patch = params.patch;
4158
+ if (!patch || typeof patch !== "object") throw new fileStore.ModelConfigError("invalid-input", "patch is required");
4159
+ const harness = harnessOf(patch.harness);
4160
+ const adapter = ADAPTERS[harness];
4161
+ const { files, baseHash } = await this.loadFiles(adapter);
4162
+ const dryRun = params.dryRun !== false;
4163
+ if (!dryRun && params.baseHash !== baseHash) {
4164
+ throw new fileStore.ModelConfigError("conflict", "The config files changed since the preview; review the new diff and apply again");
4165
+ }
4166
+ const plan = adapter.plan(files, patch, this.ctx);
4167
+ const diffs = this.diffs(adapter, files, plan.contents, plan.secrets);
4168
+ const changed = diffs.length > 0;
4169
+ if (dryRun || !changed) {
4170
+ return { harness, dryRun, changed, baseHash, files: diffs, warnings: plan.warnings };
4171
+ }
4172
+ const next = Object.fromEntries(Object.entries(plan.contents).map(([role, content]) => [role, content === void 0 ? void 0 : { content, mode: null }]));
4173
+ const apiKeyMode = patch.apiKey?.mode;
4174
+ const backup = await this.write(harness, "apply", files, next, plan.changedKeys, typeof apiKeyMode === "string" ? apiKeyMode : void 0);
4175
+ const config = await this.readOne(harness, patch.providerId);
4176
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: plan.warnings, backup, config };
4177
+ };
4178
+ return params.dryRun === false ? this.serialize(run) : run();
4179
+ }
4180
+ restore(params) {
4181
+ const run = async () => {
4182
+ const harness = harnessOf(params.harness);
4183
+ const adapter = ADAPTERS[harness];
4184
+ if (typeof params.backupId !== "string") throw new fileStore.ModelConfigError("invalid-input", "backupId is required");
4185
+ const saved = await this.backups.read(harness, params.backupId);
4186
+ const { files, baseHash } = await this.loadFiles(adapter);
4187
+ const dryRun = params.dryRun !== false;
4188
+ if (!dryRun && params.baseHash !== baseHash) {
4189
+ throw new fileStore.ModelConfigError("conflict", "The config files changed since the preview; review the new diff and restore again");
4190
+ }
4191
+ const allowed = new Map(Object.entries(files).map(([role, f]) => [f.path, role]));
4192
+ const target = {};
4193
+ for (const file of saved) {
4194
+ const role = allowed.get(file.path);
4195
+ if (!role) throw new fileStore.ModelConfigError("backup-mismatch", "Backup does not belong to the current config location");
4196
+ target[role] = { content: file.content, mode: file.mode };
4197
+ }
4198
+ const diffs = this.diffs(adapter, files, Object.fromEntries(Object.entries(target).map(([r, v]) => [r, v?.content])), []);
4199
+ const changed = diffs.length > 0;
4200
+ if (dryRun || !changed) return { harness, dryRun, changed, baseHash, files: diffs, warnings: [] };
4201
+ const keys = ["*restore*"];
4202
+ const backup = await this.write(harness, "restore", files, target, keys);
4203
+ const config = await this.readOne(harness);
4204
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: [], backup, config };
4205
+ };
4206
+ return params.dryRun === false ? this.serialize(run) : run();
4207
+ }
4208
+ }
4209
+ function toError(error) {
4210
+ if (error instanceof fileStore.ModelConfigError) return { code: error.code, message: error.message };
4211
+ return { code: "read-failed", message: error instanceof Error ? error.message : String(error) };
4212
+ }
4213
+
2088
4214
  function startWebPanelsSync(deps) {
2089
4215
  let lastMtime;
2090
4216
  let lastProblems = "";
@@ -2414,26 +4540,45 @@ function createUpdateController(deps) {
2414
4540
  let blocked = false;
2415
4541
  let handoverHold;
2416
4542
  let lastPublished = "";
4543
+ let autoUpdateEnabled;
4544
+ let lastInstall = (() => {
4545
+ try {
4546
+ return deps.lastInstall?.read() ?? null;
4547
+ } catch {
4548
+ return null;
4549
+ }
4550
+ })();
2417
4551
  const now = deps.now ?? Date.now;
4552
+ function snapshot() {
4553
+ return {
4554
+ ...policy,
4555
+ retrySupported: !blocked,
4556
+ manualUpdateSupported: !blocked,
4557
+ handoverHold,
4558
+ autoUpdate: outcome,
4559
+ ...autoUpdateEnabled === void 0 ? {} : { autoUpdateEnabled },
4560
+ ...lastInstall ? { lastInstall } : {}
4561
+ };
4562
+ }
2418
4563
  function validManualTarget(next, version) {
2419
4564
  return version === next.recommendedVersion && Number.isFinite(next.checkedAt) && now() - next.checkedAt <= 65 * 6e4 && next.checkedAt <= now() + 6e4 && cliUpdate.compareExactVersions(next.currentVersion, version) === -1 && (!next.minimumVersion || [0, 1].includes(cliUpdate.compareExactVersions(version, next.minimumVersion) ?? -1));
2420
4565
  }
2421
4566
  function publish(state, version, detail) {
2422
4567
  if (!policy) return;
2423
- const fingerprint = JSON.stringify([policy.checkedAt, state, version, detail, manualVersion]);
4568
+ const fingerprint = JSON.stringify([policy.checkedAt, state, version, detail, manualVersion, autoUpdateEnabled]);
2424
4569
  if (fingerprint === lastPublished) return;
2425
4570
  lastPublished = fingerprint;
2426
4571
  outcome = { state, version, detail, at: now(), ...manualVersion ? { source: "manual" } : {} };
2427
- deps.publish({ ...policy, retrySupported: !blocked, manualUpdateSupported: !blocked, handoverHold, autoUpdate: outcome });
4572
+ deps.publish(snapshot());
2428
4573
  }
2429
4574
  async function evaluate() {
2430
4575
  if (!policy || running) return;
2431
4576
  const target = manualVersion ?? policy.autoUpdateVersion ?? null;
2432
4577
  if (outcome?.version === target && ["failed", "installed", "manual_required"].includes(outcome.state)) {
2433
- const fingerprint = JSON.stringify([policy.checkedAt, outcome.state, outcome.version, outcome.detail, manualVersion]);
4578
+ const fingerprint = JSON.stringify([policy.checkedAt, outcome.state, outcome.version, outcome.detail, manualVersion, autoUpdateEnabled]);
2434
4579
  if (fingerprint !== lastPublished) {
2435
4580
  lastPublished = fingerprint;
2436
- deps.publish({ ...policy, retrySupported: !blocked, manualUpdateSupported: !blocked, handoverHold, autoUpdate: outcome });
4581
+ deps.publish(snapshot());
2437
4582
  }
2438
4583
  return;
2439
4584
  }
@@ -2441,9 +4586,12 @@ function createUpdateController(deps) {
2441
4586
  publish("policy_stale", target);
2442
4587
  return;
2443
4588
  }
2444
- if (!manualVersion && !await deps.enabled()) {
2445
- publish("disabled", target);
2446
- return;
4589
+ if (!manualVersion) {
4590
+ autoUpdateEnabled = await deps.enabled();
4591
+ if (!autoUpdateEnabled) {
4592
+ publish("disabled", target);
4593
+ return;
4594
+ }
2447
4595
  }
2448
4596
  if (running) return;
2449
4597
  if (now() - policy.checkedAt > 65 * 6e4) {
@@ -2473,6 +4621,13 @@ function createUpdateController(deps) {
2473
4621
  return;
2474
4622
  }
2475
4623
  blocked = code === "blocked";
4624
+ if (code === 0) {
4625
+ lastInstall = { from: policy.currentVersion, to: target, at: now(), source: manualVersion ? "manual" : "auto" };
4626
+ try {
4627
+ deps.lastInstall?.write(lastInstall);
4628
+ } catch {
4629
+ }
4630
+ }
2476
4631
  publish(
2477
4632
  blocked ? "manual_required" : code === 0 ? "installed" : "failed",
2478
4633
  target,
@@ -2574,7 +4729,224 @@ function createUpdateController(deps) {
2574
4729
  handoverHold = { reason, at: now() };
2575
4730
  publish("failed", manualVersion ?? policy?.autoUpdateVersion ?? null, "handover_preflight_failed");
2576
4731
  }
2577
- return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running };
4732
+ return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running, currentTarget: () => policy?.autoUpdateVersion ?? null };
4733
+ }
4734
+
4735
+ function parseLastInstall(raw) {
4736
+ if (!raw || typeof raw !== "object") return null;
4737
+ const { from, to, at, source } = raw;
4738
+ if (typeof from !== "string" || typeof to !== "string" || !cliUpdate.parseExactVersion(from) || !cliUpdate.parseExactVersion(to)) return null;
4739
+ if (typeof at !== "number" || !Number.isFinite(at) || source !== "auto" && source !== "manual") return null;
4740
+ return { from, to, at, source };
4741
+ }
4742
+ function lastInstallStore(homeDir) {
4743
+ const file = path.join(homeDir, "cli-update-last.json");
4744
+ return {
4745
+ read() {
4746
+ try {
4747
+ return parseLastInstall(JSON.parse(node_fs.readFileSync(file, "utf8")));
4748
+ } catch {
4749
+ return null;
4750
+ }
4751
+ },
4752
+ write(record) {
4753
+ const tmp = `${file}.${process.pid}.tmp`;
4754
+ node_fs.writeFileSync(tmp, JSON.stringify(record));
4755
+ node_fs.renameSync(tmp, file);
4756
+ }
4757
+ };
4758
+ }
4759
+
4760
+ const ANNOUNCE_FIRST_DELAY_MS = 9e4;
4761
+ const ANNOUNCE_JITTER_MS = 6e4;
4762
+ const ANNOUNCE_FOLLOW_UP_MS = 5 * 6e4;
4763
+ function announcedVersion(payload) {
4764
+ if (!payload || typeof payload !== "object") return null;
4765
+ const raw = payload.autoUpdateVersion;
4766
+ if (typeof raw !== "string" || raw.length > 64) return null;
4767
+ return cliUpdate.parseExactVersion(raw)?.exact ?? null;
4768
+ }
4769
+ function createPolicyAnnouncementHandler(deps) {
4770
+ const random = deps.random ?? Math.random;
4771
+ const setTimer = deps.setTimer ?? ((fn, ms) => {
4772
+ const t = setTimeout(fn, ms);
4773
+ t.unref?.();
4774
+ return t;
4775
+ });
4776
+ const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
4777
+ let timer = null;
4778
+ let pending = null;
4779
+ let stopped = false;
4780
+ function schedule(version, ms, followUp) {
4781
+ if (timer !== null) clearTimer(timer);
4782
+ pending = version;
4783
+ timer = setTimer(() => {
4784
+ timer = null;
4785
+ void deps.refresh().catch(() => void 0).finally(() => {
4786
+ if (stopped || pending !== version) return;
4787
+ if (deps.currentTarget() === version || !followUp) {
4788
+ pending = null;
4789
+ return;
4790
+ }
4791
+ schedule(version, ANNOUNCE_FOLLOW_UP_MS, false);
4792
+ });
4793
+ }, ms);
4794
+ }
4795
+ return {
4796
+ /** Socket handler. Returns the scheduled delay (ms) or null when ignored — for logs and tests. */
4797
+ onAnnouncement(payload) {
4798
+ if (stopped) return null;
4799
+ const version = announcedVersion(payload);
4800
+ if (!version || version === deps.currentTarget() || version === pending) return null;
4801
+ const delay = ANNOUNCE_FIRST_DELAY_MS + Math.floor(random() * ANNOUNCE_JITTER_MS);
4802
+ schedule(version, delay, true);
4803
+ return delay;
4804
+ },
4805
+ stop() {
4806
+ stopped = true;
4807
+ if (timer !== null) clearTimer(timer);
4808
+ timer = null;
4809
+ }
4810
+ };
4811
+ }
4812
+
4813
+ const HARNESS_INSTALL_CATALOG = Object.freeze({
4814
+ claude: Object.freeze({ packages: [{ name: "@anthropic-ai/claude-code", spec: "latest" }], commands: ["claude"], minNode: "22.0.0", scripts: true }),
4815
+ codex: Object.freeze({ packages: [{ name: "@openai/codex", spec: "latest" }], commands: ["codex"], minNode: "16.0.0", scripts: false }),
4816
+ gemini: Object.freeze({ packages: [{ name: "@google/gemini-cli", spec: "latest" }], commands: ["gemini"], minNode: "20.0.0", scripts: false }),
4817
+ pi: Object.freeze({
4818
+ packages: [{ name: "@earendil-works/pi-coding-agent", spec: "latest" }, { name: "pi-acp", spec: "0.0.33" }],
4819
+ commands: ["pi", "pi-acp"],
4820
+ minNode: "22.19.0",
4821
+ scripts: false
4822
+ })
4823
+ });
4824
+ function harnessInstallArgs(id, prefix) {
4825
+ const entry = HARNESS_INSTALL_CATALOG[id];
4826
+ if (!entry) throw new Error("Unknown harness");
4827
+ const args = ["i", "-g", `--prefix=${prefix}`, "--no-fund", "--no-audit", ...entry.scripts ? [] : ["--ignore-scripts"], ...entry.packages.map((p) => `${p.name}@${p.spec}`)];
4828
+ if (args.some((arg) => !doctor.NPM_SAFE_ARG.test(arg))) throw new Error("Unsafe npm argument");
4829
+ return args;
4830
+ }
4831
+ function parseNode(version) {
4832
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
4833
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
4834
+ }
4835
+ function nodeSatisfies(current, minimum) {
4836
+ const a = parseNode(current);
4837
+ const b = parseNode(minimum);
4838
+ if (!a || !b) return false;
4839
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
4840
+ return true;
4841
+ }
4842
+
4843
+ async function defaultCanWrite(path) {
4844
+ try {
4845
+ await promises.access(path, promises.constants.W_OK);
4846
+ return true;
4847
+ } catch {
4848
+ return false;
4849
+ }
4850
+ }
4851
+ async function defaultIsPlainDirectory(path) {
4852
+ try {
4853
+ const s = await promises.lstat(path);
4854
+ return s.isDirectory() && !s.isSymbolicLink();
4855
+ } catch {
4856
+ return false;
4857
+ }
4858
+ }
4859
+ function redactNpmText(text) {
4860
+ return text.replace(/(_authToken|_auth|_password|token|password)\s*=\s*\S+/gi, "$1=***").replace(/Bearer\s+\S+/gi, "Bearer ***").replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+(:[^\s/@]*)?@/gi, "$1***@").replace(/\/(home|Users)\/[^/\s]+/g, "~").replace(/\/root(?=\/|\s|$)/g, "~");
4861
+ }
4862
+ function summarizeNpmFailure(result) {
4863
+ const tail = `${result.stderr ?? ""}
4864
+ ${result.stdout ?? ""}`.trim().split("\n").filter((line) => /npm (error|ERR!)|EACCES|ENOTFOUND|ETARGET|E404|engine/i.test(line)).slice(-3).join(" | ");
4865
+ const code = result.code === null ? "npm_timeout" : `npm_exit_${result.code}`;
4866
+ const safe = redactNpmText(tail).slice(0, 300);
4867
+ return safe ? `${code}: ${safe}` : code;
4868
+ }
4869
+ function createHarnessInstaller(deps) {
4870
+ const now = deps.now ?? Date.now;
4871
+ const canWrite = deps.canWrite ?? defaultCanWrite;
4872
+ const isPlainDirectory = deps.isPlainDirectory ?? defaultIsPlainDirectory;
4873
+ let running = null;
4874
+ let blocked = false;
4875
+ const nodeVersion = deps.nodeVersion ?? process.versions.node;
4876
+ async function installPrefix() {
4877
+ const prefix = doctor.globalPrefixForPackage(deps.runningPackageDir);
4878
+ if (!prefix || !await isPlainDirectory(deps.runningPackageDir)) return { error: "install_location_unverified" };
4879
+ for (const path$1 of [path.dirname(deps.runningPackageDir), path.join(prefix, "bin")]) {
4880
+ if (!await canWrite(path$1)) return { error: "install_location_not_writable" };
4881
+ }
4882
+ return { prefix };
4883
+ }
4884
+ async function run(harness, prefix, startedAt) {
4885
+ const publish = (state, detail) => deps.publish({ harness, state, ...detail ? { detail } : {}, startedAt, at: now() });
4886
+ try {
4887
+ const args = harnessInstallArgs(harness, prefix);
4888
+ deps.log(`[HARNESS] installing ${harness}: npm ${args.join(" ")}`);
4889
+ const result = await deps.npm(args);
4890
+ if (result.terminationConfirmed === false) {
4891
+ blocked = true;
4892
+ deps.log(`[HARNESS] ${harness} install timed out and npm could not be confirmed stopped; holding the npm tree until the daemon restarts`);
4893
+ publish("failed", "installer_termination_unconfirmed");
4894
+ return;
4895
+ }
4896
+ if (result.code !== 0) {
4897
+ const detail = summarizeNpmFailure(result);
4898
+ deps.log(`[HARNESS] ${harness} install failed: ${detail}`);
4899
+ publish("failed", detail);
4900
+ return;
4901
+ }
4902
+ const missing = HARNESS_INSTALL_CATALOG[harness].commands.filter((command) => !deps.commandOnPath(command));
4903
+ if (missing.length > 0) {
4904
+ const detail = `not_on_path: ${missing.join(", ")}`;
4905
+ deps.log(`[HARNESS] ${harness} installed into ${prefix} but ${detail}`);
4906
+ publish("failed", detail);
4907
+ return;
4908
+ }
4909
+ await deps.afterInstall().catch((error) => deps.log(`[HARNESS] refresh after ${harness} install failed: ${String(error)}`));
4910
+ deps.log(`[HARNESS] ${harness} installed`);
4911
+ publish("installed");
4912
+ } catch (error) {
4913
+ deps.log(`[HARNESS] ${harness} install error: ${String(error)}`);
4914
+ publish("failed", "install_error");
4915
+ } finally {
4916
+ if (!blocked) running = null;
4917
+ }
4918
+ }
4919
+ return {
4920
+ /** True while npm may be writing the prefix — including after an unconfirmed kill. */
4921
+ isRunning: () => running !== null || blocked,
4922
+ async request(params) {
4923
+ const harness = params && typeof params === "object" ? params.harness : void 0;
4924
+ if (!index.isHarnessInstallId(harness)) {
4925
+ deps.log(`[HARNESS] refused install request for an unknown harness`);
4926
+ return { error: "unknown_harness" };
4927
+ }
4928
+ if (blocked) return { error: "installer_blocked" };
4929
+ if (running) return { error: "install_in_progress" };
4930
+ if (deps.cliUpdateBusy()) return { error: "cli_update_in_progress" };
4931
+ const minNode = HARNESS_INSTALL_CATALOG[harness].minNode;
4932
+ if (!nodeSatisfies(nodeVersion, minNode)) {
4933
+ deps.log(`[HARNESS] ${harness} install refused: needs Node ${minNode}+, daemon runs ${nodeVersion}`);
4934
+ return { error: "node_too_old", required: minNode, current: nodeVersion };
4935
+ }
4936
+ running = harness;
4937
+ const location = await installPrefix();
4938
+ if ("error" in location) {
4939
+ running = null;
4940
+ deps.log(`[HARNESS] ${harness} install refused: ${location.error}`);
4941
+ return location;
4942
+ }
4943
+ const startedAt = now();
4944
+ deps.log(`[HARNESS] owner requested ${harness} install`);
4945
+ deps.publish({ harness, state: "installing", startedAt, at: startedAt });
4946
+ void run(harness, location.prefix, startedAt);
4947
+ return { accepted: true, harness };
4948
+ }
4949
+ };
2578
4950
  }
2579
4951
 
2580
4952
  function buildPresenceBatch(live, previous) {
@@ -2805,7 +5177,7 @@ function parseJsonObject(text) {
2805
5177
  return null;
2806
5178
  }
2807
5179
  }
2808
- function resolveSdkClaudeBinary(platform = process.platform, arch = process.arch, resolver = (s) => module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('run-CNXwIe0A.cjs', document.baseURI).href))).resolve(s)) {
5180
+ function resolveSdkClaudeBinary(platform = process.platform, arch = process.arch, resolver = (s) => module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('run-C_FumCQk.cjs', document.baseURI).href))).resolve(s)) {
2809
5181
  const platformArch = `${platform}-${arch}`;
2810
5182
  const candidates = [
2811
5183
  `@anthropic-ai/claude-agent-sdk-${platformArch}/claude`,
@@ -3794,6 +6166,57 @@ function withDaemonHeartbeat(state, lastHeartbeat) {
3794
6166
  return { ...state, lastHeartbeat };
3795
6167
  }
3796
6168
 
6169
+ const TAIL_BYTES = 64 * 1024;
6170
+ const MAX_REASON = 300;
6171
+ function extractStartupExitReason(logText) {
6172
+ const lines = logText.split("\n");
6173
+ for (let i = lines.length - 1; i >= 0; i--) {
6174
+ const exit = /\[EXIT\] Exiting with code -?\d+: (.+)$/.exec(lines[i]);
6175
+ if (exit) return clamp(exit[1]);
6176
+ }
6177
+ for (let i = lines.length - 1; i >= 0; i--) {
6178
+ if (!/\[ERROR\]|\[WARN\]/.test(lines[i])) continue;
6179
+ const detail = lines.slice(i, i + 8).join("\n");
6180
+ const message = /message: '([^'\n]+)'/.exec(detail)?.[1];
6181
+ const code = /code: '([A-Z0-9_]+)'/.exec(detail)?.[1];
6182
+ const head = lines[i].replace(/^\[[\d:.]+\]\s*/, "").replace(/\s*\{\s*$/, "").trim();
6183
+ return clamp([head, message, code].filter(Boolean).join(" "));
6184
+ }
6185
+ return void 0;
6186
+ }
6187
+ function describeStartupExit(exit, timeoutMs) {
6188
+ if (exit.timedOut) {
6189
+ const tail = exit.exited ? "and was stopped" : "and could not be confirmed stopped";
6190
+ return `Agent process did not report its session within ${Math.round(timeoutMs / 1e3)}s ${tail}${exit.reason ? `: ${exit.reason}` : ""}`;
6191
+ }
6192
+ const how = exit.signal ? `signal ${exit.signal}` : `code ${exit.code ?? "unknown"}`;
6193
+ return `Agent process exited during startup (${how}): ${exit.reason ?? "no reason found in its log"}`;
6194
+ }
6195
+ function readStartupExitReason(logsDir, pid) {
6196
+ try {
6197
+ const suffix = `-pid-${pid}.log`;
6198
+ const file = node_fs.readdirSync(logsDir).filter((name) => name.endsWith(suffix)).sort().pop();
6199
+ if (!file) return void 0;
6200
+ const path$1 = path.join(logsDir, file);
6201
+ const size = node_fs.statSync(path$1).size;
6202
+ const length = Math.min(size, TAIL_BYTES);
6203
+ const buffer = Buffer.alloc(length);
6204
+ const fd = node_fs.openSync(path$1, "r");
6205
+ try {
6206
+ node_fs.readSync(fd, buffer, 0, length, size - length);
6207
+ } finally {
6208
+ node_fs.closeSync(fd);
6209
+ }
6210
+ return extractStartupExitReason(buffer.toString("utf8"));
6211
+ } catch {
6212
+ return void 0;
6213
+ }
6214
+ }
6215
+ function clamp(value) {
6216
+ const line = value.replace(/\s+/g, " ").trim();
6217
+ return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}\u2026` : line;
6218
+ }
6219
+
3797
6220
  function recoverableSessionPid(metadata, liveHappyPids) {
3798
6221
  const pid = metadata?.hostPid;
3799
6222
  return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && liveHappyPids.has(pid) ? pid : null;
@@ -3835,7 +6258,10 @@ function mergeRestoreMetadata(stale, reported) {
3835
6258
  }
3836
6259
 
3837
6260
  function teamInitialPrompt(goal, root, directory) {
3838
- const role = root ? "You are the team lead. Inspect your assigned goal, arrange independent work when useful, review member results, integrate changes, and submit the final result for the user to accept. Delegate under your assigned goal using parentTaskId. You must not accept your own root goal." : "You are a team member. Inspect your assigned task and work in your assigned worktree. Delegate within your task when useful, then submit evidence for the lead to review.";
6261
+ const role = root ? `You are the team lead. Inspect your assigned goal, arrange independent work when useful, review member results, integrate changes, and submit the final result for the user to accept. Delegate under your assigned goal using parentTaskId. You must not accept your own root goal.
6262
+
6263
+ ${resources.TEAM_LEAD_PLAYBOOK}` : `You are a team member. Inspect your assigned task and work in your assigned worktree. Delegate within your task when useful, then submit evidence for the lead to review.
6264
+ ${resources.TEAM_MEMBER_RULES}`;
3839
6265
  return `${resources.TEAM_SKILL}
3840
6266
 
3841
6267
  ## Your role
@@ -3849,47 +6275,30 @@ Delegate from this working directory unless a different repository was explicitl
3849
6275
  ${goal}`;
3850
6276
  }
3851
6277
 
3852
- function receiptPath(home, operationId) {
3853
- if (!/^[a-zA-Z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid team operation id");
3854
- return path.join(home, "teams", "effects", `${operationId}.json`);
3855
- }
3856
- function readReceipt(home, id) {
3857
- try {
3858
- const value = JSON.parse(node_fs.readFileSync(receiptPath(home, id), "utf8"));
3859
- if (value.operationId !== id || typeof value.claimId !== "string" || !["prepared", "spawning", "spawned", "delivered", "completed"].includes(value.phase)) throw new Error("Invalid team effect receipt");
3860
- return value;
3861
- } catch (error) {
3862
- if (error.code === "ENOENT") return null;
3863
- throw error;
3864
- }
6278
+ const exec = node_util.promisify(node_child_process.execFile);
6279
+ const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
6280
+ const gitRaw = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 64 * 1024 * 1024 })).stdout;
6281
+ function expandHome$1(path$1) {
6282
+ if (path$1 === "~") return os.homedir();
6283
+ if (path$1.startsWith("~/") || process.platform === "win32" && path$1.startsWith("~\\")) return path.join(os.homedir(), path$1.slice(2));
6284
+ return path$1;
3865
6285
  }
3866
- function writeReceipt$1(home, receipt) {
3867
- configuration.ensurePrivateDirectorySync(path.join(home, "teams", "effects"));
3868
- const target = receiptPath(home, receipt.operationId);
3869
- const tmp = `${target}.${process.pid}.tmp`;
3870
- configuration.writePrivateFileSync(tmp, JSON.stringify(receipt));
3871
- const file = node_fs.openSync(tmp, "r");
3872
- try {
3873
- node_fs.fsyncSync(file);
3874
- } finally {
3875
- node_fs.closeSync(file);
3876
- }
3877
- node_fs.renameSync(tmp, target);
3878
- if (process.platform !== "win32") {
3879
- const directory = node_fs.openSync(path.join(home, "teams", "effects"), "r");
3880
- try {
3881
- node_fs.fsyncSync(directory);
3882
- } finally {
3883
- node_fs.closeSync(directory);
3884
- }
6286
+ async function resolveTeamRepository(home, repository, sourceOf) {
6287
+ const worktrees = path.resolve(home, "teams", "worktrees");
6288
+ let candidate = expandHome$1(repository);
6289
+ for (let hop = 0; hop < 8; hop++) {
6290
+ if (!path.isAbsolute(candidate)) break;
6291
+ const teamWorktree = path.resolve(path.dirname(candidate)) === worktrees;
6292
+ const top = await git(candidate, ["rev-parse", "--show-toplevel"]).catch(() => null);
6293
+ if (top !== null && (!teamWorktree || path.resolve(top) === path.resolve(candidate))) return candidate;
6294
+ const source = teamWorktree ? sourceOf(path.basename(candidate)) : void 0;
6295
+ if (!source) break;
6296
+ candidate = expandHome$1(source);
3885
6297
  }
6298
+ 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.`);
3886
6299
  }
3887
-
3888
- const exec = node_util.promisify(node_child_process.execFile);
3889
- const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
3890
6300
  async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3891
- if (repository === "~") repository = os.homedir();
3892
- else if (repository.startsWith("~/") || process.platform === "win32" && repository.startsWith("~\\")) repository = path.join(os.homedir(), repository.slice(2));
6301
+ repository = expandHome$1(repository);
3893
6302
  if (!path.isAbsolute(repository) || !/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new Error("A team task requires an absolute repository path and valid operation id");
3894
6303
  await git(repository, ["rev-parse", "--show-toplevel"]);
3895
6304
  const root = path.join(home, "teams", "worktrees");
@@ -3908,28 +6317,69 @@ async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3908
6317
  }
3909
6318
  return { directory, repository, branch };
3910
6319
  }
6320
+ async function unpreservedCommits(directory, repository, rev) {
6321
+ const sourceHead = await git(repository, ["rev-parse", "HEAD"]).catch(() => "");
6322
+ const pending = (await git(directory, ["rev-list", rev, "--not", "--remotes", ...sourceHead ? [sourceHead] : []])).split("\n").filter(Boolean);
6323
+ if (pending.length === 0) return 0;
6324
+ return await squashMerged(directory, rev) ? 0 : pending.length;
6325
+ }
6326
+ async function squashMerged(directory, rev) {
6327
+ 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", () => "");
6328
+ if (!target) return false;
6329
+ const base = await git(directory, ["merge-base", rev, target]).catch(() => "");
6330
+ if (!base) return false;
6331
+ const own = patchIds(await gitRaw(directory, ["diff", base, rev]).then((diff) => diff ? patchIdOf(directory, diff) : "", () => ""));
6332
+ if (own.length !== 1) return false;
6333
+ const merged = patchIds(await gitRaw(directory, ["log", "-p", "--no-merges", "--max-count=500", `${base}..${target}`]).then((log) => log ? patchIdOf(directory, log) : "", () => ""));
6334
+ return merged.includes(own[0]);
6335
+ }
6336
+ async function patchIdOf(directory, patch) {
6337
+ return await new Promise((resolvePatch, reject) => {
6338
+ const child = node_child_process.execFile("git", ["-C", directory, "patch-id", "--stable"], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 }, (error, stdout) => error ? reject(error) : resolvePatch(stdout));
6339
+ child.stdin?.end(patch);
6340
+ });
6341
+ }
6342
+ const patchIds = (output) => output.split("\n").filter(Boolean).map((line) => line.split(" ")[0]);
6343
+ async function registeredWorktree(repository, directory) {
6344
+ const list = await git(repository, ["worktree", "list", "--porcelain"]).catch(() => "");
6345
+ return list.split("\n").some((line) => line.startsWith("worktree ") && path.resolve(line.slice("worktree ".length)) === path.resolve(directory));
6346
+ }
6347
+ const describeHead = async (directory) => await git(directory, ["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "") || "a detached HEAD";
3911
6348
  async function removeTeamWorktree(resource) {
3912
6349
  const { directory, repository, branch } = resource;
3913
6350
  if (!directory || !repository || !branch) return;
3914
- if (node_fs.existsSync(directory)) {
3915
- if (await git(directory, ["symbolic-ref", "--short", "HEAD"]) !== branch) throw new Error("Worktree branch changed; preserve for manual reconciliation");
6351
+ let present = node_fs.existsSync(directory);
6352
+ if (present) {
6353
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => "");
6354
+ if (!top || path.resolve(top) !== path.resolve(directory)) {
6355
+ 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`);
6356
+ if (node_fs.readdirSync(directory).length === 0) node_fs.rmdirSync(directory);
6357
+ present = false;
6358
+ }
6359
+ }
6360
+ if (present) {
3916
6361
  const actualCommon = await git(directory, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3917
6362
  const expectedCommon = await git(repository, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3918
6363
  if (path.resolve(actualCommon) !== path.resolve(expectedCommon)) throw new Error("Worktree repository changed; preserve for manual reconciliation");
3919
- if (await git(directory, ["status", "--porcelain"])) throw new Error(`Uncommitted work retained at ${directory}`);
3920
- await git(repository, ["merge-base", "--is-ancestor", branch, "HEAD"]).catch(() => {
3921
- throw new Error(`Unmerged work retained on ${branch} at ${directory}`);
3922
- });
3923
- await git(repository, ["worktree", "remove", directory]);
6364
+ const dirty = (await git(directory, ["status", "--porcelain"])).split("\n").filter(Boolean).length;
6365
+ 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`);
6366
+ const head = await describeHead(directory);
6367
+ const unsafe = await unpreservedCommits(directory, repository, "HEAD");
6368
+ 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`);
3924
6369
  }
3925
- try {
3926
- await git(repository, ["show-ref", "--verify", `refs/heads/${branch}`]);
3927
- } catch {
3928
- return;
6370
+ const ownBranch = await git(repository, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).then(() => true, () => false);
6371
+ if (ownBranch) {
6372
+ const unsafe = await unpreservedCommits(repository, repository, `refs/heads/${branch}`);
6373
+ 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`);
3929
6374
  }
3930
- await git(repository, ["branch", "-d", branch]);
6375
+ if (present) await git(repository, ["worktree", "remove", directory]);
6376
+ else await git(repository, ["worktree", "prune"]).catch(() => void 0);
6377
+ if (ownBranch) await git(repository, ["branch", "-D", branch]);
3931
6378
  }
3932
6379
 
6380
+ function persistedSpawnMatches(operationId) {
6381
+ return Object.entries(persistence.readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === operationId);
6382
+ }
3933
6383
  function createTeamWorker(deps) {
3934
6384
  const home = deps.home ?? configuration.configuration.happyHomeDir;
3935
6385
  const server = deps.serverUrl ?? configuration.configuration.serverUrl;
@@ -3963,6 +6413,12 @@ function createTeamWorker(deps) {
3963
6413
  if (receipt.phase === "completed") return;
3964
6414
  try {
3965
6415
  if (op.type === "spawn") {
6416
+ if (machineMetadata.ownerRetryPending(op, receipt) && (receipt.phase === "prepared" || receipt.phase === "spawning" && persistedSpawnMatches(op.id).length === 0)) {
6417
+ receipt = machineMetadata.consumeOwnerRetry(op, receipt);
6418
+ writeReceipt$1(home, receipt);
6419
+ deps.log(`Teams operation ${op.id} relaunch requested by owner`);
6420
+ }
6421
+ if (receipt.phase === "prepared" && machineMetadata.spawnGate(receipt, Date.now()) !== "run") return;
3966
6422
  if (receipt.phase === "prepared") {
3967
6423
  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;
3968
6424
  if (!credential) throw new Error("No scoped credential for worker");
@@ -3975,7 +6431,26 @@ function createTeamWorker(deps) {
3975
6431
  return;
3976
6432
  }
3977
6433
  if (!op.directory) throw new Error("No repository selected for worker");
3978
- const resource = await prepareTeamWorktree(home, op.directory, op.id);
6434
+ let resource;
6435
+ try {
6436
+ const repository = await resolveTeamRepository(home, op.directory, (id) => {
6437
+ try {
6438
+ return readReceipt(home, id)?.repository;
6439
+ } catch {
6440
+ return void 0;
6441
+ }
6442
+ });
6443
+ resource = await prepareTeamWorktree(home, repository, op.id);
6444
+ } catch (error) {
6445
+ const now = Date.now();
6446
+ receipt = machineMetadata.afterStartupFailure(receipt, now);
6447
+ writeReceipt$1(home, receipt);
6448
+ const detail = error instanceof Error ? error.message : "Team worktree could not be prepared";
6449
+ await action(op.teamId, `preflight-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: machineMetadata.startupFailureMessage(detail, receipt, now).slice(0, 1e3) }).catch(() => {
6450
+ });
6451
+ deps.log(`Teams operation ${op.id} preflight failed (${receipt.spawnFailures}/${machineMetadata.TEAM_SPAWN_MAX_ATTEMPTS})`);
6452
+ return;
6453
+ }
3979
6454
  const scopes = path.join(home, "teams", "scopes");
3980
6455
  configuration.ensurePrivateDirectorySync(scopes);
3981
6456
  const scopeFile = path.join(scopes, `${op.id}.json`);
@@ -3983,12 +6458,21 @@ function createTeamWorker(deps) {
3983
6458
  receipt = { ...receipt, ...resource, scopeFile, phase: "spawning" };
3984
6459
  writeReceipt$1(home, receipt);
3985
6460
  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 } });
6461
+ if (spawned.type === "error" && spawned.startupExit?.exited) {
6462
+ const now = Date.now();
6463
+ receipt = machineMetadata.afterStartupFailure(receipt, now);
6464
+ writeReceipt$1(home, receipt);
6465
+ await action(op.teamId, `startup-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: machineMetadata.startupFailureMessage(spawned.errorMessage, receipt, now).slice(0, 1e3) }).catch(() => {
6466
+ });
6467
+ deps.log(`Teams operation ${op.id} startup failed (${receipt.spawnFailures}/${machineMetadata.TEAM_SPAWN_MAX_ATTEMPTS}); ${receipt.retryAt !== void 0 ? "will relaunch" : "waiting for owner retry"}`);
6468
+ return;
6469
+ }
3986
6470
  if (spawned.type !== "success") throw new Error(spawned.type === "error" ? spawned.errorMessage : "Directory approval required");
3987
6471
  receipt = { ...receipt, sessionId: spawned.sessionId, phase: "spawned" };
3988
6472
  writeReceipt$1(home, receipt);
3989
6473
  }
3990
6474
  if (receipt.phase === "spawning") {
3991
- const matches = Object.entries(persistence.readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === op.id);
6475
+ const matches = persistedSpawnMatches(op.id);
3992
6476
  if (matches.length !== 1) throw new Error("Spawn outcome unknown; reconcile the worker before retrying");
3993
6477
  receipt = { ...receipt, sessionId: matches[0][0], phase: "spawned" };
3994
6478
  writeReceipt$1(home, receipt);
@@ -4010,6 +6494,12 @@ function createTeamWorker(deps) {
4010
6494
  }
4011
6495
  await complete(op, receipt);
4012
6496
  } else {
6497
+ if (machineMetadata.ownerRetryPending(op, receipt)) {
6498
+ const { retryAt: _retryAt, ...rest } = receipt;
6499
+ receipt = { ...rest, retryConsumed: op.retryRequestedAt };
6500
+ writeReceipt$1(home, receipt);
6501
+ deps.log(`Teams operation ${op.id} cleanup retry requested by owner`);
6502
+ } else if (receipt.retryAt !== void 0 && Date.now() < receipt.retryAt) return;
4013
6503
  const team = (await http.get(`/v1/teams/${encodeURIComponent(op.teamId)}`)).data.team;
4014
6504
  const latest = team.operations.find((candidate) => candidate.id === op.id);
4015
6505
  if (latest?.status === "completed") {
@@ -4036,7 +6526,14 @@ function createTeamWorker(deps) {
4036
6526
  } catch (error) {
4037
6527
  const unknown = op.type === "spawn" && receipt.phase === "spawning";
4038
6528
  const detail = error instanceof Error ? error.message : "Team operation failed";
4039
- 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(() => {
6529
+ if (op.type === "stop") {
6530
+ receipt = { ...receipt, retryAt: Date.now() + machineMetadata.TEAM_CLEANUP_RETRY_MS };
6531
+ try {
6532
+ writeReceipt$1(home, receipt);
6533
+ } catch {
6534
+ }
6535
+ }
6536
+ await action(op.teamId, `failure-${op.id}-${receipt.phase}-${node_crypto.createHash("sha256").update(detail).digest("hex").slice(0, 12)}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: detail.slice(0, 1e3), unknown }).catch(() => {
4040
6537
  });
4041
6538
  deps.log(`Teams operation ${op.id} ${unknown ? "needs reconciliation" : "will retry"}`);
4042
6539
  }
@@ -4135,7 +6632,19 @@ Use the teams tools to inspect current task state before acting. This message is
4135
6632
  }, 5e3);
4136
6633
  timer.unref();
4137
6634
  void tick();
4138
- return { tick, report, hasSession: (id) => knownSessionIds.has(id), get busy() {
6635
+ async function recoverScope(operationId, sessionId, scopeFile) {
6636
+ const teams = (await http.get("/v1/teams")).data.teams ?? [];
6637
+ const team = teams.find((candidate) => candidate.archivedAt === void 0 && candidate.operations.some((op2) => op2.id === operationId));
6638
+ const op = team?.operations.find((candidate) => candidate.id === operationId);
6639
+ if (!team || !op || op.type !== "spawn" || op.machineId !== deps.machineId) throw new Error("No live team launch for this session");
6640
+ const bot = team.bots.find((candidate) => candidate.id === op.botId);
6641
+ if (!bot || bot.sessionId !== sessionId || bot.generation !== op.generation) throw new Error("Team binding changed; not restoring its scope");
6642
+ const claimed = await action(op.teamId, `claim-${op.id}`, { type: "claim-operation", operationId: op.id, machineId: deps.machineId, ...op.teamLaunchVersion === 1 ? { teamLaunchVersion: 1 } : {} });
6643
+ if (!claimed.credential?.token || claimed.credential.botId !== op.botId) throw new Error("Team did not reissue the member credential");
6644
+ configuration.ensurePrivateDirectorySync(path.join(home, "teams", "scopes"));
6645
+ configuration.writePrivateFileSync(scopeFile, JSON.stringify({ serverUrl: server, scopeToken: claimed.credential.token, teamId: op.teamId, botId: op.botId, taskId: op.taskId, attemptId: op.attemptId }));
6646
+ }
6647
+ return { tick, report, recoverScope, hasSession: (id) => knownSessionIds.has(id), get busy() {
4139
6648
  return running;
4140
6649
  }, stop: () => {
4141
6650
  closed = true;
@@ -4864,7 +7373,7 @@ function sanitizeImportTitle(value) {
4864
7373
  return collapsed.length > 200 ? `${collapsed.slice(0, 199)}\u2026` : collapsed;
4865
7374
  }
4866
7375
  async function preflightNewBundle(bundlePath) {
4867
- const home = fs$1.mkdtempSync(path$2.join(os.tmpdir(), "vh-preflight-"));
7376
+ const home = require$$0.mkdtempSync(require$$1.join(os.tmpdir(), "vh-preflight-"));
4868
7377
  try {
4869
7378
  return await new Promise((resolve) => {
4870
7379
  let stdout = "";
@@ -4905,12 +7414,13 @@ async function preflightNewBundle(bundlePath) {
4905
7414
  });
4906
7415
  } finally {
4907
7416
  try {
4908
- fs$1.rmSync(home, { recursive: true, force: true });
7417
+ require$$0.rmSync(home, { recursive: true, force: true });
4909
7418
  } catch {
4910
7419
  }
4911
7420
  }
4912
7421
  }
4913
7422
  const HANDOVER_PREFLIGHT_TIMEOUT_MS = 3e4;
7423
+ const SPAWN_WEBHOOK_TIMEOUT_MS = 15e3;
4914
7424
  async function startDaemon() {
4915
7425
  const initialMachineMetadata = machineMetadata.getInitialMachineMetadata();
4916
7426
  const startupCliAvailability = machineMetadata.getStartupCliAvailability();
@@ -5294,7 +7804,7 @@ async function startDaemon() {
5294
7804
  if (options.token) {
5295
7805
  if (options.agent === "codex") {
5296
7806
  const codexHomeDir = tmp__namespace.dirSync();
5297
- await fs.writeFile(path$2.join(codexHomeDir.name, "auth.json"), options.token);
7807
+ await fs.writeFile(require$$1.join(codexHomeDir.name, "auth.json"), options.token);
5298
7808
  authEnv.CODEX_HOME = codexHomeDir.name;
5299
7809
  } else {
5300
7810
  authEnv.CLAUDE_CODE_OAUTH_TOKEN = options.token;
@@ -5377,7 +7887,7 @@ async function startDaemon() {
5377
7887
  const sessionDesc = tmuxSessionName || "current/most recent session";
5378
7888
  logger.logger.debug(`[DAEMON RUN] Attempting to spawn session in tmux: ${sessionDesc}`);
5379
7889
  const tmux = getTmuxUtilities(tmuxSessionName);
5380
- const cliPath = path$2.join(projectPath.projectPath(), "dist", "index.mjs");
7890
+ const cliPath = require$$1.join(projectPath.projectPath(), "dist", "index.mjs");
5381
7891
  const agent = options.agent ?? "claude";
5382
7892
  if (!spawnAgents.isSpawnAgent(agent)) {
5383
7893
  return {
@@ -5567,22 +8077,33 @@ async function startDaemon() {
5567
8077
  });
5568
8078
  logger.logger.debug(`[DAEMON RUN] Waiting for session webhook for PID ${happyProcess.pid}`);
5569
8079
  return new Promise((resolve) => {
8080
+ const pid = happyProcess.pid;
8081
+ let settled = false;
8082
+ const fail = (startupExit) => {
8083
+ if (settled) return;
8084
+ settled = true;
8085
+ clearTimeout(timeout);
8086
+ pidToAwaiter.delete(pid);
8087
+ startupExit.reason ??= readStartupExitReason(configuration.configuration.logsDir, pid);
8088
+ const errorMessage = describeStartupExit(startupExit, SPAWN_WEBHOOK_TIMEOUT_MS);
8089
+ logger.logger.debug(`[DAEMON RUN] Spawn of PID ${pid} failed: ${errorMessage}`);
8090
+ resolve({ type: "error", errorMessage, startupExit });
8091
+ };
8092
+ happyProcess.once("exit", (code, signal) => fail({ exited: true, code, signal }));
5570
8093
  const timeout = setTimeout(() => {
5571
- pidToAwaiter.delete(happyProcess.pid);
5572
- logger.logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${happyProcess.pid}`);
5573
- if (happyProcess.pid) {
5574
- try {
5575
- sessionLock.terminateProcess(happyProcess.pid, () => {
5576
- });
5577
- } catch {
5578
- }
8094
+ if (settled) return;
8095
+ pidToAwaiter.delete(pid);
8096
+ logger.logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${pid}`);
8097
+ try {
8098
+ const started = sessionLock.terminateProcess(pid, (stopped) => fail({ exited: stopped, code: null, signal: null, timedOut: true }));
8099
+ if (!started) fail({ exited: false, code: null, signal: null, timedOut: true });
8100
+ } catch {
8101
+ fail({ exited: false, code: null, signal: null, timedOut: true });
5579
8102
  }
5580
- resolve({
5581
- type: "error",
5582
- errorMessage: `Session webhook timeout for PID ${happyProcess.pid}`
5583
- });
5584
- }, 15e3);
5585
- pidToAwaiter.set(happyProcess.pid, (completedSession) => {
8103
+ }, SPAWN_WEBHOOK_TIMEOUT_MS);
8104
+ pidToAwaiter.set(pid, (completedSession) => {
8105
+ if (settled) return;
8106
+ settled = true;
5586
8107
  clearTimeout(timeout);
5587
8108
  logger.logger.debug(`[DAEMON RUN] Session ${completedSession.happySessionId} fully spawned with webhook`);
5588
8109
  resolve({
@@ -5643,6 +8164,13 @@ async function startDaemon() {
5643
8164
  }
5644
8165
  };
5645
8166
  const resumeGates = /* @__PURE__ */ new Map();
8167
+ const teamRelaunchEnvFor = (happySessionId, metadata) => teamRelaunchEnv({
8168
+ home: configuration.configuration.happyHomeDir,
8169
+ sessionId: happySessionId,
8170
+ metadata,
8171
+ recover: teamWorker ? (operationId, scopeFile) => teamWorker.recoverScope(operationId, happySessionId, scopeFile) : void 0,
8172
+ log: (message) => logger.logger.debug(`[DAEMON RUN] ${message}`)
8173
+ });
5646
8174
  const resumeSession = async (happySessionId, options) => {
5647
8175
  let gate = resumeGates.get(happySessionId);
5648
8176
  if (!gate) {
@@ -5700,15 +8228,15 @@ async function startDaemon() {
5700
8228
  tracked.happySessionMetadataFromLocalWebhook = metadata;
5701
8229
  logger.logger.debug(`[DAEMON RUN] Session ${happySessionId} relaunch metadata from ${relaunch.source}`);
5702
8230
  const precheck = resumePrecheck(metadata, {
5703
- cwdExists: (p) => fs$1.existsSync(p),
8231
+ cwdExists: (p) => require$$0.existsSync(p),
5704
8232
  // B-478: also looks in every other Claude config dir the user's shell
5705
8233
  // or settings point at, not just the one the daemon was started with.
5706
8234
  conversationExists: (cwd, claudeSessionId) => index$1.locateClaudeConversation(cwd, claudeSessionId) !== null
5707
8235
  });
5708
8236
  let freshConversation = false;
5709
8237
  if (!precheck.ok) {
5710
- if (precheck.reason === "conversation-missing") {
5711
- logger.logger.debug(`[DAEMON RUN] resume: transcript for ${happySessionId} is gone (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
8238
+ if (resumeStartsFreshConversation(precheck.reason)) {
8239
+ logger.logger.debug(`[DAEMON RUN] resume: ${precheck.reason} for ${happySessionId} (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
5712
8240
  freshConversation = true;
5713
8241
  } else {
5714
8242
  return { type: "error", errorMessage: `resume-precheck:${precheck.reason}: ${precheck.detail}` };
@@ -5721,12 +8249,15 @@ async function startDaemon() {
5721
8249
  const model = sanitizeResumeModel(options?.model);
5722
8250
  if (model) launch.args.push("--model", model);
5723
8251
  else if (options?.model !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid model ${JSON.stringify(options.model)}`);
5724
- const permissionMode = spawnAgents.sanitizeSpawnPermissionMode(options?.permissionMode);
8252
+ const requestedMode = options?.permissionMode ?? (options?.keepPublishedPermissionMode ? publishedRelaunchPermissionMode(metadata) : void 0);
8253
+ const permissionMode = spawnAgents.sanitizeSpawnPermissionMode(requestedMode);
5725
8254
  if (permissionMode) launch.args.push("--permission-mode", permissionMode);
5726
- else if (options?.permissionMode !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(options.permissionMode)}`);
8255
+ else if (requestedMode !== void 0) logger.logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(requestedMode)}`);
8256
+ const teamEnv = await teamRelaunchEnvFor(happySessionId, metadata);
5727
8257
  const result = await spawnTrackedHappyProcess({
5728
8258
  args: launch.args,
5729
8259
  cwd: launch.cwd,
8260
+ ...teamEnv.VH_TEAM_SCOPE_FILE ? { spawnedBy: "teams" } : {},
5730
8261
  env: {
5731
8262
  ...process.env,
5732
8263
  // B-297: the credentialStore=file shim must ride every spawn path,
@@ -5742,7 +8273,8 @@ async function startDaemon() {
5742
8273
  HAPPY_RECONNECT_ENCRYPTION_VARIANT: tracked.encryption.encryptionVariant,
5743
8274
  HAPPY_RECONNECT_SEQ: String(tracked.encryption.seq),
5744
8275
  HAPPY_RECONNECT_METADATA_VERSION: String(tracked.encryption.metadataVersion),
5745
- HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion)
8276
+ HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion),
8277
+ ...teamEnv
5746
8278
  }
5747
8279
  });
5748
8280
  if (result.type === "success") {
@@ -5832,7 +8364,7 @@ async function startDaemon() {
5832
8364
  tracked.happySessionMetadataFromLocalWebhook = metadata;
5833
8365
  logger.logger.debug(`[DAEMON RUN] Session ${happySessionId} relaunch metadata from ${relaunch.source}`);
5834
8366
  const precheck = resumePrecheck(metadata, {
5835
- cwdExists: (p) => fs$1.existsSync(p),
8367
+ cwdExists: (p) => require$$0.existsSync(p),
5836
8368
  // B-478: also looks in every other Claude config dir the user's shell
5837
8369
  // or settings point at, not just the one the daemon was started with.
5838
8370
  conversationExists: (cwd2, claudeSessionId) => index$1.locateClaudeConversation(cwd2, claudeSessionId) !== null
@@ -5848,7 +8380,7 @@ async function startDaemon() {
5848
8380
  cwd = launch.cwd;
5849
8381
  } else if ((metadata.flavor ?? "claude") === "claude" && typeof metadata.path === "string" && metadata.path.length > 0) {
5850
8382
  cwd = metadata.path;
5851
- if (!fs$1.existsSync(cwd)) {
8383
+ if (!require$$0.existsSync(cwd)) {
5852
8384
  return { type: "error", errorMessage: `restart-precheck:cwd-missing: ${cwd}` };
5853
8385
  }
5854
8386
  args = ["claude", "--happy-starting-mode", "remote", "--started-by", "daemon"];
@@ -5860,9 +8392,11 @@ async function startDaemon() {
5860
8392
  const permissionMode = spawnAgents.sanitizeSpawnPermissionMode(options?.permissionMode);
5861
8393
  if (permissionMode) args.push("--permission-mode", permissionMode);
5862
8394
  restartCounts.set(happySessionId, recordRestartAttempt(prior));
8395
+ const teamEnv = await teamRelaunchEnvFor(happySessionId, metadata);
5863
8396
  const result = await spawnTrackedHappyProcess({
5864
8397
  args,
5865
8398
  cwd,
8399
+ ...teamEnv.VH_TEAM_SCOPE_FILE ? { spawnedBy: "teams" } : {},
5866
8400
  env: {
5867
8401
  ...process.env,
5868
8402
  // B-297: the credentialStore=file shim must ride every spawn path,
@@ -5877,7 +8411,8 @@ async function startDaemon() {
5877
8411
  HAPPY_RECONNECT_ENCRYPTION_VARIANT: tracked.encryption.encryptionVariant,
5878
8412
  HAPPY_RECONNECT_SEQ: String(tracked.encryption.seq),
5879
8413
  HAPPY_RECONNECT_METADATA_VERSION: String(tracked.encryption.metadataVersion),
5880
- HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion)
8414
+ HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion),
8415
+ ...teamEnv
5881
8416
  }
5882
8417
  });
5883
8418
  if (result.type === "success") {
@@ -6073,10 +8608,10 @@ async function startDaemon() {
6073
8608
  };
6074
8609
  persistence.writeDaemonState(fileState);
6075
8610
  logger.logger.debug("[DAEMON RUN] Daemon state written");
6076
- const bundlePath = path$2.join(projectPath.projectPath(), "dist", "index.mjs");
8611
+ const bundlePath = require$$1.join(projectPath.projectPath(), "dist", "index.mjs");
6077
8612
  let initialBundleMtimeMs = 0;
6078
8613
  try {
6079
- initialBundleMtimeMs = fs$1.statSync(bundlePath).mtimeMs;
8614
+ initialBundleMtimeMs = require$$0.statSync(bundlePath).mtimeMs;
6080
8615
  } catch {
6081
8616
  logger.logger.debug(`[DAEMON RUN] Bundle at ${bundlePath} not found; self-restart on upgrade disabled`);
6082
8617
  }
@@ -6150,6 +8685,15 @@ async function startDaemon() {
6150
8685
  setStore: (store) => claudeAuthService.setStore(store)
6151
8686
  });
6152
8687
  claudeAuthService.start();
8688
+ apiMachine.setModelConfigService(new ModelConfigService({
8689
+ home: os$1.homedir(),
8690
+ env: process.env,
8691
+ happyHomeDir: configuration.configuration.happyHomeDir,
8692
+ isInstalled: detectCLI.commandOnPath,
8693
+ onChanged: (harness) => {
8694
+ if (harness === "claude") void claudeAuthService.probe("model-config", true);
8695
+ }
8696
+ }));
6153
8697
  apiMachine.setAgentHibernationHandlers(persistence.resolveIdleMs(agentHibernationSetting), async (requested) => {
6154
8698
  const value = requested <= 0 ? 0 : persistence.settingIdleMs(requested);
6155
8699
  await persistence.updateSettings((current) => ({ ...current, agentHibernationIdleMs: value }));
@@ -6171,6 +8715,8 @@ async function startDaemon() {
6171
8715
  })).then(() => logger.logger.debug(`[DAEMON RUN] claimed the machine record for host ${initialMachineMetadata.host}`)).catch((error) => logger.logger.debug("[DAEMON RUN] could not refresh the recorded host:", error));
6172
8716
  }
6173
8717
  let lastUpdateLog = "";
8718
+ let harnessInstaller = null;
8719
+ let handoverInFlight = false;
6174
8720
  const updateController = createUpdateController({
6175
8721
  policy: () => cliUpdate.fetchCliUpdateState(configuration.configuration.serverUrl, _package.packageJson.version),
6176
8722
  enabled: async () => ((await persistence.readSettings()).cliAutoUpdate ?? "idle") !== "off",
@@ -6178,8 +8724,9 @@ async function startDaemon() {
6178
8724
  // handover (they talk to the server themselves) and web terminals live
6179
8725
  // in tmux, so neither is a reason to hold an update. B-507: a session
6180
8726
  // whose turn ended but still has background tasks is busy too.
6181
- idle: () => !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny(),
8727
+ idle: () => !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny() && !harnessInstaller?.isRunning(),
6182
8728
  install: installCliSafely,
8729
+ lastInstall: lastInstallStore(configuration.configuration.happyHomeDir),
6183
8730
  publish: (state) => {
6184
8731
  cliUpdateStateRef = state;
6185
8732
  fileState = { ...fileState, cliUpdate: state };
@@ -6226,10 +8773,33 @@ async function startDaemon() {
6226
8773
  logger.logger.warn(`[DAEMON RUN] Ignoring invalid HAPPY_CLI_UPDATE_CHECK_INTERVAL; using ${cliUpdate.DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS}ms`);
6227
8774
  }
6228
8775
  const cliUpdateInterval = setInterval(() => void refreshCliUpdate(), cliUpdateIntervalMs);
8776
+ const policyAnnouncements = createPolicyAnnouncementHandler({
8777
+ refresh: refreshCliUpdate,
8778
+ currentTarget: updateController.currentTarget
8779
+ });
8780
+ apiMachine.setCliUpdatePolicyHandler((payload) => {
8781
+ const delay = policyAnnouncements.onAnnouncement(payload);
8782
+ if (delay !== null) logger.logger.warn(`[DAEMON RUN] CLI update policy announced; re-checking in ${Math.round(delay / 1e3)}s`);
8783
+ });
6229
8784
  const stopAgentVersionChecks = mirrorProtocol.startAgentVersionChecks(
6230
8785
  (snapshot) => apiMachine.updateDaemonState((state) => ({ ...state, status: state?.status ?? "running", agentVersions: snapshot })),
6231
8786
  (error) => logger.logger.debug("[DAEMON RUN] Agent version check failed", error)
6232
8787
  );
8788
+ harnessInstaller = createHarnessInstaller({
8789
+ npm: runNpm,
8790
+ runningPackageDir: projectPath.projectPath(),
8791
+ commandOnPath: detectCLI.commandOnPath,
8792
+ cliUpdateBusy: () => updateController.isRunning() || handoverInFlight,
8793
+ publish: (state) => {
8794
+ void apiMachine.updateDaemonState((current) => ({ ...current, status: current?.status ?? "running", harnessInstall: state })).catch((error) => logger.logger.debug("[DAEMON RUN] harness install state publish failed", error));
8795
+ },
8796
+ afterInstall: async () => {
8797
+ apiMachine.recheckCliAvailability();
8798
+ await stopAgentVersionChecks.refresh();
8799
+ },
8800
+ log: (message) => logger.logger.warn(`[DAEMON RUN] ${message}`)
8801
+ });
8802
+ apiMachine.setHarnessInstallHandler((params) => harnessInstaller.request(params));
6233
8803
  const heartbeatIntervalMs = parseInt(process.env.HAPPY_DAEMON_HEARTBEAT_INTERVAL || "60000");
6234
8804
  const restartOnStaleVersionAndHeartbeat = setInterval(serialTask(async () => {
6235
8805
  try {
@@ -6246,53 +8816,59 @@ async function startDaemon() {
6246
8816
  }
6247
8817
  await updateController.tick();
6248
8818
  await updateController.withHandover(async () => {
6249
- let bundleReplaced = false;
6250
- if (initialBundleMtimeMs > 0) {
6251
- try {
6252
- const currentMtimeMs = fs$1.statSync(bundlePath).mtimeMs;
6253
- bundleReplaced = currentMtimeMs !== initialBundleMtimeMs;
6254
- } catch {
6255
- }
6256
- }
6257
- const relayMove = pendingRelayMove;
6258
- if ((bundleReplaced || relayMove) && !teamWorker?.busy && !automationRunner?.busy && !updateController.isRunning() && !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny()) {
6259
- const preflight = bundleReplaced ? await preflightNewBundle(bundlePath) : { action: "proceed" };
6260
- if (preflight.action === "hold") {
6261
- if (lastHandoverHold !== preflight.reason) {
6262
- lastHandoverHold = preflight.reason;
6263
- logger.logger.warn(`[DAEMON RUN] holding handover: ${preflight.reason}`);
8819
+ handoverInFlight = true;
8820
+ try {
8821
+ let bundleReplaced = false;
8822
+ if (initialBundleMtimeMs > 0) {
8823
+ try {
8824
+ const currentMtimeMs = require$$0.statSync(bundlePath).mtimeMs;
8825
+ bundleReplaced = currentMtimeMs !== initialBundleMtimeMs;
8826
+ } catch {
6264
8827
  }
6265
- updateController.holdHandover(preflight.reason);
6266
- return;
6267
8828
  }
6268
- if (teamWorker?.busy || automationRunner?.busy || updateController.isRunning() || turnActivity.hasActiveTurn() || backgroundTasks.hasAny()) return;
6269
- lastHandoverHold = null;
6270
- logger.logger.debug(relayMove ? `[DAEMON RUN] Relay moved to ${relayMove.serverUrl}; handing off to a new daemon on the new settings` : "[DAEMON RUN] Daemon bundle replaced on disk and verified, handing off to new daemon");
6271
- teamWorker?.stop();
6272
- automationRunner?.stop();
6273
- projectPresence?.stop();
6274
- clearInterval(restartOnStaleVersionAndHeartbeat);
6275
- clearInterval(cliUpdateInterval);
6276
- stopAgentVersionChecks();
6277
- claudeAuthService.stop();
6278
- apiMachine.shutdown();
6279
- await stopControlServer();
6280
- await controlClient.cleanupDaemonState();
6281
- await persistence.releaseDaemonLock(daemonLockHandle);
6282
- await stopCaffeinate();
6283
- if (daemonSupervisor$1 === "systemd") {
6284
- logger.logger.debug(`[DAEMON RUN] systemd-supervised: exiting ${HANDOVER_EXIT_CODE} for the unit to restart on the new bundle`);
6285
- process.exit(HANDOVER_EXIT_CODE);
6286
- }
6287
- try {
6288
- spawnHappyCLI.spawnHappyCLI(["daemon", "start"], {
6289
- detached: true,
6290
- stdio: "ignore"
6291
- });
6292
- } catch (error) {
6293
- logger.logger.debug("[DAEMON RUN] Failed to spawn new daemon, this is quite likely to happen during integration tests as we are cleaning out dist/ directory", error);
8829
+ const relayMove = pendingRelayMove;
8830
+ if ((bundleReplaced || relayMove) && !teamWorker?.busy && !automationRunner?.busy && !updateController.isRunning() && !harnessInstaller?.isRunning() && !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny()) {
8831
+ const preflight = bundleReplaced ? await preflightNewBundle(bundlePath) : { action: "proceed" };
8832
+ if (preflight.action === "hold") {
8833
+ if (lastHandoverHold !== preflight.reason) {
8834
+ lastHandoverHold = preflight.reason;
8835
+ logger.logger.warn(`[DAEMON RUN] holding handover: ${preflight.reason}`);
8836
+ }
8837
+ updateController.holdHandover(preflight.reason);
8838
+ return;
8839
+ }
8840
+ if (teamWorker?.busy || automationRunner?.busy || updateController.isRunning() || harnessInstaller?.isRunning() || turnActivity.hasActiveTurn() || backgroundTasks.hasAny()) return;
8841
+ lastHandoverHold = null;
8842
+ logger.logger.debug(relayMove ? `[DAEMON RUN] Relay moved to ${relayMove.serverUrl}; handing off to a new daemon on the new settings` : "[DAEMON RUN] Daemon bundle replaced on disk and verified, handing off to new daemon");
8843
+ teamWorker?.stop();
8844
+ automationRunner?.stop();
8845
+ projectPresence?.stop();
8846
+ clearInterval(restartOnStaleVersionAndHeartbeat);
8847
+ clearInterval(cliUpdateInterval);
8848
+ policyAnnouncements.stop();
8849
+ stopAgentVersionChecks();
8850
+ claudeAuthService.stop();
8851
+ apiMachine.shutdown();
8852
+ await stopControlServer();
8853
+ await controlClient.cleanupDaemonState();
8854
+ await persistence.releaseDaemonLock(daemonLockHandle);
8855
+ await stopCaffeinate();
8856
+ if (daemonSupervisor$1 === "systemd") {
8857
+ logger.logger.debug(`[DAEMON RUN] systemd-supervised: exiting ${HANDOVER_EXIT_CODE} for the unit to restart on the new bundle`);
8858
+ process.exit(HANDOVER_EXIT_CODE);
8859
+ }
8860
+ try {
8861
+ spawnHappyCLI.spawnHappyCLI(["daemon", "start"], {
8862
+ detached: true,
8863
+ stdio: "ignore"
8864
+ });
8865
+ } catch (error) {
8866
+ logger.logger.debug("[DAEMON RUN] Failed to spawn new daemon, this is quite likely to happen during integration tests as we are cleaning out dist/ directory", error);
8867
+ }
8868
+ process.exit(0);
6294
8869
  }
6295
- process.exit(0);
8870
+ } finally {
8871
+ handoverInFlight = false;
6296
8872
  }
6297
8873
  });
6298
8874
  const daemonState = await persistence.readDaemonState();
@@ -6340,7 +8916,7 @@ async function startDaemon() {
6340
8916
  return !!record && typeof record.hibernatedAt === "number" && record.hibernatedAt >= record.savedAt;
6341
8917
  },
6342
8918
  wakeHibernated: async (id) => {
6343
- const result = await resumeSession(id);
8919
+ const result = await resumeSession(id, { keepPublishedPermissionMode: true });
6344
8920
  if (result.type !== "success") return false;
6345
8921
  return waitForSessionLive(id, (sid) => [...pidToTrackedSession.values()].some((s) => s.happySessionId === sid && isPidAlive(s.pid)));
6346
8922
  },
@@ -6359,11 +8935,18 @@ async function startDaemon() {
6359
8935
  log: (message) => logger.logger.debug(`[DAEMON RUN] ${message}`)
6360
8936
  });
6361
8937
  void apiMachine.updateMachineMetadata((current) => ({
6362
- ...current ?? initialMachineMetadata,
8938
+ // B-718: the running CLI version, not the one that first registered the row.
8939
+ ...machineMetadata.withRunningCliFacts(current, initialMachineMetadata),
6363
8940
  teamsVersion: 1,
6364
8941
  teamLaunchVersion: 1,
8942
+ // B-689: this daemon acts on the owner's retry-operation (web gates「重试启动」).
8943
+ teamRetryVersion: machineMetadata.TEAM_RETRY_CAPABILITY_VERSION,
6365
8944
  // B-586: this daemon serves the worktree-* RPCs (web gates 「在新 worktree 中」 on it).
6366
- worktreeVersion: mirrorProtocol.WORKTREE_CAPABILITY_VERSION
8945
+ worktreeVersion: mirrorProtocol.WORKTREE_CAPABILITY_VERSION,
8946
+ // B-688: this daemon serves the model-config-* RPCs (web gates 「模型与 Provider」 on it).
8947
+ modelConfigVersion: MODEL_CONFIG_CAPABILITY_VERSION,
8948
+ // B-719: this daemon serves `harness-install` (web gates the Install / Update buttons on it).
8949
+ harnessInstallVersion: index.HARNESS_INSTALL_CAPABILITY_VERSION
6367
8950
  })).catch(() => logger.logger.debug("[DAEMON RUN] Teams capability publication will retry on reconnect"));
6368
8951
  const cleanupAndShutdown = async (source, errorMessage) => {
6369
8952
  webPanelsSync.stop();
@@ -6378,6 +8961,7 @@ async function startDaemon() {
6378
8961
  logger.logger.debug("[DAEMON RUN] Health check interval cleared");
6379
8962
  }
6380
8963
  clearInterval(cliUpdateInterval);
8964
+ policyAnnouncements.stop();
6381
8965
  stopAgentVersionChecks();
6382
8966
  await apiMachine.updateDaemonState((state) => ({
6383
8967
  ...state,