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,85 +1,87 @@
1
- import { i as isClaudeSessionId, g as extractCompleteLines, h as decideBackfill, j as parseTerminalHookPayload, k as decideMirrorBinding, M as MIRROR_BACKFILL_LINES_DEFAULT, m as mirrorLineKey, n as mirrorLocalId, o as initializeOwnedWorktree, e as summarizeSpawnSessionForLog, q as startAgentVersionChecks, W as WORKTREE_CAPABILITY_VERSION, t as currentWorktreeService } from './mirrorProtocol-BwYibqry.mjs';
2
- import { P as PI_ADAPTER_INSTALL_HINT, s as sanitizeSpawnModel } from './piRunnerArgs-DwvM_yWA.mjs';
1
+ import { i as isClaudeSessionId, g as extractCompleteLines, h as decideBackfill, j as parseTerminalHookPayload, k as decideMirrorBinding, M as MIRROR_BACKFILL_LINES_DEFAULT, m as mirrorLineKey, n as mirrorLocalId, o as initializeOwnedWorktree, e as summarizeSpawnSessionForLog, q as startAgentVersionChecks, W as WORKTREE_CAPABILITY_VERSION, t as currentWorktreeService } from './mirrorProtocol-CAxOMBkb.mjs';
2
+ import { P as PI_ADAPTER_INSTALL_HINT, s as sanitizeSpawnModel } from './piRunnerArgs-IZLoL7TG.mjs';
3
3
  import fs from 'fs/promises';
4
+ import os from 'os';
4
5
  import * as tmp from 'tmp';
5
6
  import axios from 'axios';
6
- import { T as TurnActivityTracker, A as ApiClient } from './api-CzwFpJQc.mjs';
7
- import { S as SPAWN_AGENTS, i as isSpawnAgent, s as sanitizeSpawnPermissionMode, r as resolveSpawnPermissionMode, a as resolveFirstMessageMeta, j as joinProject } from './spawnAgents-P006Hqio.mjs';
8
- import { l as logger } from './logger-BtVhHnD8.mjs';
9
- import { readdirSync, statSync, unlinkSync, realpathSync, mkdirSync, writeFileSync, accessSync, constants as constants$1, existsSync, readFileSync, openSync, fsyncSync, closeSync, renameSync } from 'node:fs';
7
+ import { readFileSync, openSync, fsyncSync, closeSync, renameSync, existsSync, readdirSync, statSync, unlinkSync, realpathSync, promises, writeFileSync, mkdirSync, accessSync, constants as constants$1, readSync, rmdirSync } from 'node:fs';
10
8
  import { join, isAbsolute, resolve, dirname, sep, basename, delimiter } from 'node:path';
11
- import { p as pruneStaleCompileCaches } from './index-D3bidoG8.mjs';
12
- import { a as authAndSetupMachineIfNeeded } from './auth-BS6PaOOG.mjs';
13
- import { c as configuration, f as ensurePrivateDirectorySync, w as writePrivateFileSync } from './configuration-WMi4idBB.mjs';
9
+ import { f as ensurePrivateDirectorySync, w as writePrivateFileSync, c as configuration } from './configuration-BPrfb17M.mjs';
10
+ import { T as TurnActivityTracker, A as ApiClient } from './api-Dr3wXL_7.mjs';
11
+ import { S as SPAWN_AGENTS, i as isSpawnAgent, s as sanitizeSpawnPermissionMode, r as resolveSpawnPermissionMode, a as resolveFirstMessageMeta, j as joinProject } from './spawnAgents-CCnlq-FI.mjs';
12
+ import { l as logger } from './logger-LFr8iPgl.mjs';
13
+ import { p as pruneStaleCompileCaches } from './index-hQ8LP1C2.mjs';
14
+ import { a as authAndSetupMachineIfNeeded } from './auth-DZsthtSk.mjs';
14
15
  import { spawn, execSync } from 'child_process';
15
- import { p as packageJson } from './package-BPPebGQF.mjs';
16
- import { g as globalPrefixForPackage, a as getEnvironmentInfo } from './doctor-CmtSsR2-.mjs';
17
- import { s as spawnHappyCLI } from './spawnHappyCLI-CCOrEtf9.mjs';
18
- import { c as readPersistedSessions, r as readSettings, l as latchKeepAwake, q as reportSignature, s as decideDaemonHibernation, t as nextCheckDelay, v as persistSession, d as readDaemonState, x as acquireDaemonLock, a as resolveCheckMs, y as resolveIdleMs, z as deletePersistedSessions, A as writeDaemonState, B as writeSettings, C as settingIdleMs, u as updateSettings, D as rewriteCredentialsForRelay, g as readCredentials, E as releaseDaemonLock } from './persistence-Cr-wutZ4.mjs';
19
- import { i as isDaemonRunningCurrentlyInstalledHappyVersion, b as stopDaemon, o as cleanupDaemonState } from './controlClient-BWUJrj3t.mjs';
20
- import { e as sendUserMessage, f as readSessionMetadata, r as readSessionTranscript, l as listAccountSessions, a as listSessions, M as MAX_READ_LIMIT, s as sessionWebUrl, g as waitForSessionKey, d as archiveSession, j as analyzeLatestTurn, k as readSessionLog, m as TURN_WINDOW, n as userPromptText } from './sessionOps-BIGgRube.mjs';
16
+ import { p as packageJson } from './package-DYGwlmXl.mjs';
17
+ import { a as globalPrefixForPackage, N as NPM_SAFE_ARG, g as getEnvironmentInfo } from './doctor-CoOaPq6w.mjs';
18
+ import { s as spawnHappyCLI } from './spawnHappyCLI-Dq3LLXLb.mjs';
19
+ import { c as readPersistedSessions, r as readSettings, l as latchKeepAwake, q as reportSignature, s as decideDaemonHibernation, t as nextCheckDelay, v as persistSession, d as readDaemonState, x as acquireDaemonLock, a as resolveCheckMs, y as resolveIdleMs, z as deletePersistedSessions, A as writeDaemonState, B as writeSettings, C as settingIdleMs, u as updateSettings, D as rewriteCredentialsForRelay, g as readCredentials, E as releaseDaemonLock } from './persistence-D2Djrf7t.mjs';
20
+ import { i as isDaemonRunningCurrentlyInstalledHappyVersion, s as stopDaemon, t as cleanupDaemonState } from './controlClient-CkNpT5zS.mjs';
21
+ import { e as sendUserMessage, f as readSessionMetadata, r as readSessionTranscript, l as listAccountSessions, a as listSessions, M as MAX_READ_LIMIT, s as sessionWebUrl, g as waitForSessionKey, d as archiveSession, j as analyzeLatestTurn, k as readSessionLog, m as TURN_WINDOW, n as userPromptText } from './sessionOps-DqlftXxe.mjs';
21
22
  import fastify from 'fastify';
22
23
  import { z } from 'zod';
23
24
  import { validatorCompiler, serializerCompiler } from 'fastify-type-provider-zod';
24
25
  import { d as decodeBase64, s as sameRelay, e as encodeBase64, h as decrypt } from './authRelay-DhQhkBvX.mjs';
25
26
  import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'node:crypto';
26
27
  import { c as checkPreviewPath } from './previewPath-CXN4Vag0.mjs';
27
- import { a as BACKGROUND_TASKS_MAX, c as BACKGROUND_TASK_DESCRIPTION_MAX, d as BackgroundTaskTracker } from './backgroundTaskActivity-BVwJBl02.mjs';
28
- import { b as sanitizeRateLimitReport } from './rateLimitWindows-CuEqk_0g.mjs';
29
- import { f as formatEditConflictNotice, b as SESSION_PEER_SENT_FROM, s as sendPeerMessage, l as listPeerSessions, C as CLI_PEER_SENDER_ID } from './peerTools-CWKzcQ7u.mjs';
30
- import os, { hostname, homedir, userInfo, tmpdir } from 'node:os';
31
- import { c as RemoteCallBudget, e as REMOTE_WRITE_CALLS_PER_MINUTE, d as deliverToSession, g as guardRemoteSessionOpsRequest, h as remoteError, i as REMOTE_OP_DEADLINE_MS, j as formatRemoteAuditLine, k as REMOTE_SEND_COMMIT_DEADLINE_MS, m as REMOTE_RESUME_WAIT_MS, n as capRemoteTranscript, o as capRemoteText, p as REMOTE_ANSWER_MAX_BYTES, q as REMOTE_TITLE_MAX_BYTES } from './remoteSessionClient-Bn2qu5C5.mjs';
32
- import { assistantHome, bootstrapAssistantHome } from './bootstrap-iuyufnp3.mjs';
33
- import { refreshAgentHomes, locateClaudeConversation, agentHomeSpawnEnv } from './index-CdQI0C9p.mjs';
34
- import { existsSync as existsSync$1, statSync as statSync$1, mkdtempSync, rmSync } from 'fs';
35
- import { join as join$1 } from 'path';
28
+ import { a as BACKGROUND_TASKS_MAX, d as BACKGROUND_TASK_DESCRIPTION_MAX, e as BackgroundTaskTracker } from './backgroundTaskActivity-8PdPxrvy.mjs';
29
+ import { b as sanitizeRateLimitReport } from './rateLimitWindows-ZtHZHe-l.mjs';
30
+ import { f as formatEditConflictNotice, b as SESSION_PEER_SENT_FROM, s as sendPeerMessage, l as listPeerSessions, C as CLI_PEER_SENDER_ID } from './peerTools-CK3JYu1k.mjs';
31
+ import os$1, { hostname, homedir, userInfo, tmpdir } from 'node:os';
32
+ import { c as RemoteCallBudget, e as REMOTE_WRITE_CALLS_PER_MINUTE, d as deliverToSession, g as guardRemoteSessionOpsRequest, h as remoteError, i as REMOTE_OP_DEADLINE_MS, j as formatRemoteAuditLine, k as REMOTE_SEND_COMMIT_DEADLINE_MS, m as REMOTE_RESUME_WAIT_MS, n as capRemoteTranscript, o as capRemoteText, p as REMOTE_ANSWER_MAX_BYTES, q as REMOTE_TITLE_MAX_BYTES } from './remoteSessionClient-B2POSKFT.mjs';
33
+ import { assistantHome, bootstrapAssistantHome } from './bootstrap-B6EkZh4u.mjs';
34
+ import { refreshAgentHomes, locateClaudeConversation, agentHomeSpawnEnv } from './index-CO0n9ue6.mjs';
35
+ import require$$0, { existsSync as existsSync$1, statSync as statSync$1, mkdtempSync, rmSync } from 'fs';
36
+ import require$$1, { join as join$1 } from 'path';
36
37
  import { spawn as spawn$1, execFile, spawnSync } from 'node:child_process';
37
38
  import { p as projectPath } from './projectPath-BTBIMB57.mjs';
38
39
  import { d as daemonEndpointsMatch, r as resolveClaudeCredentialReadiness } from './doctorReadiness-C208SMN9.mjs';
39
- import { g as getInitialMachineMetadata, a as getStartupCliAvailability } from './machineMetadata-D-g--oU_.mjs';
40
- import { buildResumeLaunch } from './handleResumeCommand-C8thKjqf.mjs';
40
+ import { o as ownerRetryPending, c as consumeOwnerRetry, s as spawnGate, a as afterStartupFailure, b as startupFailureMessage, T as TEAM_SPAWN_MAX_ATTEMPTS, d as TEAM_CLEANUP_RETRY_MS, g as getInitialMachineMetadata, e as getStartupCliAvailability, f as TEAM_RETRY_CAPABILITY_VERSION, w as withRunningCliFacts } from './machineMetadata-BglCsfvf.mjs';
41
+ import { M as ModelConfigError, B as BackupStore, r as readConfigFile, s as sha256, a as atomicWriteFile } from './fileStore-5qpetZS0.mjs';
42
+ import { c as collectSecretValues, a as parseJsonObject$1, b as childObject, s as setOrDelete, d as changedPaths, e as stringifyLike, f as fail, n as normalizeModelList, g as normalizeModelId, h as normalizeSecret, i as normalizeBaseUrl, u as uniq, j as baseUrlWarnings, m as maskSecret, k as getPath$1, l as normalizeProviderId, o as piAdapter, r as redactText } from './pi-CqyoZMjI.mjs';
43
+ import require$$3 from 'crypto';
44
+ import { c as commandOnPath } from './detectCLI-CSGMlV51.mjs';
45
+ import { buildResumeLaunch } from './handleResumeCommand-gO8I4keP.mjs';
41
46
  import { n as normalizeWebPanels } from './webPanels-B2_C2-3g.mjs';
42
- import { w as ServerMigrateNoticeSchema, x as AUTOMATION_SUMMARY_MAX_CHARS, y as AUTOMATION_PRECHECK_OUTPUT_MAX_CHARS, z as AUTOMATION_PRECHECK_DEFAULT_TIMEOUT_MS, b as AUTOMATION_PRECHECK_MAX_TIMEOUT_MS, D as AUTOMATION_CLAIM_MAX_RUNS, E as AUTOMATION_DAEMON_CAPABILITY_PRECHECK, F as AUTOMATION_DEFAULT_LEASE_MS, i as isAutomationRunTerminal } from './index-DPOa4NhL.mjs';
47
+ import { v as ServerMigrateNoticeSchema, w as isHarnessInstallId, x as AUTOMATION_SUMMARY_MAX_CHARS, y as AUTOMATION_PRECHECK_OUTPUT_MAX_CHARS, z as AUTOMATION_PRECHECK_DEFAULT_TIMEOUT_MS, b as AUTOMATION_PRECHECK_MAX_TIMEOUT_MS, D as AUTOMATION_CLAIM_MAX_RUNS, E as AUTOMATION_DAEMON_CAPABILITY_PRECHECK, F as AUTOMATION_DEFAULT_LEASE_MS, i as isAutomationRunTerminal, H as HARNESS_INSTALL_CAPABILITY_VERSION } from './index-CeRXrGnH.mjs';
43
48
  import { access, symlink, readFile, rm, unlink, readlink, lstat, constants, stat, open } from 'node:fs/promises';
44
49
  import { p as parseExactVersion, c as compareExactVersions, f as fetchCliUpdateState, r as resolveCliUpdateCheckInterval, D as DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS } from './cliUpdate-Y34VGe9Y.mjs';
45
- import { P as ProjectsUnsupportedError, c as createProjectsClient } from './client-BhoEBnuN.mjs';
46
- import { c as createAutomationsClient, i as isAutomationsUnavailable, d as AutomationsRequestError } from './client-wo9nbxuf.mjs';
50
+ import { P as ProjectsUnsupportedError, c as createProjectsClient } from './client-BKyU66lg.mjs';
51
+ import { c as createAutomationsClient, i as isAutomationsUnavailable, d as AutomationsRequestError } from './client-CXOnzuOy.mjs';
47
52
  import { createRequire } from 'node:module';
48
53
  import { g as getProjectPath } from './path-D2wdaNSk.mjs';
49
54
  import { b as extractClaudeEditPaths } from './editPaths-BVfS_FFL.mjs';
50
- import { s as startFileWatcher } from './startFileWatcher-DghDOCO4.mjs';
51
- import { I as InvalidateSync } from './sync-CSe0Rf45.mjs';
55
+ import { s as startFileWatcher } from './startFileWatcher-4thXDK9d.mjs';
56
+ import { I as InvalidateSync } from './sync-DO-2PU45.mjs';
52
57
  import { R as RawJSONLinesSchema } from './types-CkqAACXx.mjs';
53
58
  import { t as tmuxArgs, a as scrubTmuxClientEnv, s as shellescape } from './tmuxSocket-B8Yx20sT.mjs';
54
- import { p as processIdentityFields, r as readSessionLock, t as terminateProcess, d as terminateProcessTree } from './sessionLock-WYIyaVO4.mjs';
59
+ import { p as processIdentityFields, r as readSessionLock, t as terminateProcess, d as terminateProcessTree } from './sessionLock-JIfwCqMk.mjs';
55
60
  import { findAllHappyProcesses } from './doctor-BPkYWSuq.mjs';
56
- import { T as TEAM_SKILL } from './resources-y9jfyO-_.mjs';
61
+ import { T as TEAM_SKILL, a as TEAM_LEAD_PLAYBOOK, b as TEAM_MEMBER_RULES } from './resources-CH1iP6Cv.mjs';
57
62
  import { promisify } from 'node:util';
58
63
  import { c as clipText, r as renderAction, b as renderTemplate } from './template-CiOPa2rd.mjs';
59
64
  import { d as detectDaemonSupervisor } from './daemonSupervisor-C6urv3_8.mjs';
60
65
  import { d as describeAgentHome } from './loginShellEnv-Dw8M7tkI.mjs';
61
- import './acpSessionResume-DTGmAPLt.mjs';
62
- import './lidState-Bb8fgXg3.mjs';
63
- import 'os';
66
+ import './acpSessionResume-9OLTD6kT.mjs';
67
+ import './lidState-DghbfRbr.mjs';
64
68
  import 'node:events';
65
69
  import 'socket.io-client';
66
- import './pushNotifications-BdFjDjQe.mjs';
70
+ import './pushNotifications-DXGIhE-A.mjs';
67
71
  import './contentLogMetadata-BlWI0egu.mjs';
68
72
  import './limits-DIo7rEBR.mjs';
69
- import './time-65DcU6Jx.mjs';
70
- import './registerCommonHandlers-BAlP7SGc.mjs';
73
+ import './time-BcoJaG8E.mjs';
74
+ import './registerCommonHandlers-DF6bdDtd.mjs';
71
75
  import 'util';
72
- import 'crypto';
73
76
  import 'cross-spawn';
74
77
  import '@paralleldrive/cuid2';
75
78
  import 'chalk';
76
79
  import 'tweetnacl';
77
- import './browser-CSYum7xH.mjs';
80
+ import './browser-C2qhUHSE.mjs';
78
81
  import 'open';
79
82
  import './ids-DU6sLx4C.mjs';
80
83
  import 'url';
81
- import './detectCLI-CSGMlV51.mjs';
82
- import './localHappyAgentAuth-NEU7fax7.mjs';
84
+ import './localHappyAgentAuth-IKmeRpuQ.mjs';
83
85
  import './processTreeSnapshot-CuLJDNC-.mjs';
84
86
  import 'ps-list';
85
87
 
@@ -92,6 +94,87 @@ async function resolveRelaunchMetadata(snapshot, fetchServer) {
92
94
  return { metadata: snapshot, source: "snapshot" };
93
95
  }
94
96
 
97
+ function receiptPath(home, operationId) {
98
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid team operation id");
99
+ return join(home, "teams", "effects", `${operationId}.json`);
100
+ }
101
+ function readReceipt(home, id) {
102
+ try {
103
+ const value = JSON.parse(readFileSync(receiptPath(home, id), "utf8"));
104
+ if (value.operationId !== id || typeof value.claimId !== "string" || !["prepared", "spawning", "spawned", "delivered", "completed"].includes(value.phase)) throw new Error("Invalid team effect receipt");
105
+ return value;
106
+ } catch (error) {
107
+ if (error.code === "ENOENT") return null;
108
+ throw error;
109
+ }
110
+ }
111
+ function writeReceipt$1(home, receipt) {
112
+ ensurePrivateDirectorySync(join(home, "teams", "effects"));
113
+ const target = receiptPath(home, receipt.operationId);
114
+ const tmp = `${target}.${process.pid}.tmp`;
115
+ writePrivateFileSync(tmp, JSON.stringify(receipt));
116
+ const file = openSync(tmp, "r");
117
+ try {
118
+ fsyncSync(file);
119
+ } finally {
120
+ closeSync(file);
121
+ }
122
+ renameSync(tmp, target);
123
+ if (process.platform !== "win32") {
124
+ const directory = openSync(join(home, "teams", "effects"), "r");
125
+ try {
126
+ fsyncSync(directory);
127
+ } finally {
128
+ closeSync(directory);
129
+ }
130
+ }
131
+ }
132
+
133
+ const OPERATION_ID = /^[a-zA-Z0-9_-]{1,128}$/;
134
+ function teamScopeFilePath(home, operationId) {
135
+ if (!OPERATION_ID.test(operationId)) throw new Error("Invalid team operation id");
136
+ return join(home, "teams", "scopes", `${operationId}.json`);
137
+ }
138
+ function relaunchTeamOperationId(home, sessionId, metadata) {
139
+ const fromMetadata = metadata?.teamOperationId;
140
+ if (typeof fromMetadata === "string" && OPERATION_ID.test(fromMetadata)) return fromMetadata;
141
+ let names;
142
+ try {
143
+ names = readdirSync(join(home, "teams", "effects"));
144
+ } catch {
145
+ return null;
146
+ }
147
+ let newest = null;
148
+ for (const name of names) {
149
+ if (!name.endsWith(".json")) continue;
150
+ const id = name.slice(0, -".json".length);
151
+ if (!OPERATION_ID.test(id)) continue;
152
+ try {
153
+ const receipt = readReceipt(home, id);
154
+ if (receipt?.sessionId !== sessionId || !receipt.scopeFile) continue;
155
+ const at = statSync(receiptPath(home, id)).mtimeMs;
156
+ if (!newest || at > newest.at) newest = { id, at };
157
+ } catch {
158
+ }
159
+ }
160
+ return newest?.id ?? null;
161
+ }
162
+ async function teamRelaunchEnv(input) {
163
+ const operationId = relaunchTeamOperationId(input.home, input.sessionId, input.metadata);
164
+ if (!operationId) return {};
165
+ const scopeFile = teamScopeFilePath(input.home, operationId);
166
+ if (!existsSync(scopeFile) && input.recover) {
167
+ try {
168
+ await input.recover(operationId, scopeFile);
169
+ input.log(`Teams scope for ${input.sessionId} rebuilt from operation ${operationId}`);
170
+ } catch (error) {
171
+ input.log(`Teams scope for ${input.sessionId} could not be rebuilt: ${error instanceof Error ? error.message : "unknown error"}`);
172
+ }
173
+ }
174
+ if (!existsSync(scopeFile)) input.log(`Teams scope for ${input.sessionId} is missing; team tools will refuse until the owner restores it`);
175
+ return { VH_TEAM_SCOPE_FILE: scopeFile, VH_TEAM_OPERATION_ID: operationId, HAPPY_SPAWNED_BY: "teams" };
176
+ }
177
+
95
178
  const DEFAULT_LOG_PRUNE_POLICY = {
96
179
  maxAgeMs: 14 * 24 * 60 * 6e4,
97
180
  maxTotalBytes: 200 * 1024 * 1024,
@@ -372,6 +455,20 @@ function formatAssistantReportMessage(title, sessionId, event) {
372
455
  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`;
373
456
  }
374
457
 
458
+ const CLAUDE_OUTBOUND_MODES = ["default", "acceptEdits", "plan", "bypassPermissions"];
459
+ function normalizeClaudeOutboundMode(value) {
460
+ if (value === null || value === void 0) return null;
461
+ if (value === "yolo") return "bypassPermissions";
462
+ return CLAUDE_OUTBOUND_MODES.includes(value) ? value : "default";
463
+ }
464
+ function publishedRelaunchPermissionMode(metadata) {
465
+ const published = typeof metadata?.permissionMode === "string" ? metadata.permissionMode : null;
466
+ if ((metadata?.flavor ?? "claude") === "claude") {
467
+ return normalizeClaudeOutboundMode(published) ?? void 0;
468
+ }
469
+ return published ?? void 0;
470
+ }
471
+
375
472
  function resumePrecheck(metadata, fs) {
376
473
  const flavor = metadata.flavor ?? "claude";
377
474
  if (flavor === "acp" && metadata.piSessionId) {
@@ -398,6 +495,9 @@ function resumePrecheck(metadata, fs) {
398
495
  }
399
496
  return { ok: true };
400
497
  }
498
+ function resumeStartsFreshConversation(reason) {
499
+ return reason === "conversation-missing" || reason === "no-backend-id";
500
+ }
401
501
  function sanitizeResumeModel(value) {
402
502
  if (typeof value !== "string") return null;
403
503
  return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}(\[1m\])?$/i.test(value) ? value : null;
@@ -755,7 +855,7 @@ function startDaemonControlServer({
755
855
  return { success: false, error: "daemon is still starting up" };
756
856
  }
757
857
  logger.debug(`[CONTROL SERVER] Resume session request: ${sessionId} (model=${model ?? "unset"}, permissionMode=${permissionMode ?? "unset"})`);
758
- const result = await resumeSession(sessionId, { model, permissionMode });
858
+ const result = await resumeSession(sessionId, { model, permissionMode, keepPublishedPermissionMode: true });
759
859
  switch (result.type) {
760
860
  case "success":
761
861
  return { success: true, sessionId: result.sessionId };
@@ -2063,6 +2163,2032 @@ function spawnAgentUnavailableError(agent, availability) {
2063
2163
  return null;
2064
2164
  }
2065
2165
 
2166
+ const MAX_DIFF_LINES = 4e3;
2167
+ function splitLines(text) {
2168
+ if (text === "") return [];
2169
+ const lines = text.split("\n");
2170
+ if (lines[lines.length - 1] === "") lines.pop();
2171
+ return lines;
2172
+ }
2173
+ function diffOps(a, b) {
2174
+ if (a.length > MAX_DIFF_LINES || b.length > MAX_DIFF_LINES) {
2175
+ return [...a.map((text) => ({ kind: "-", text })), ...b.map((text) => ({ kind: "+", text }))];
2176
+ }
2177
+ const n = a.length;
2178
+ const m = b.length;
2179
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
2180
+ for (let i2 = n - 1; i2 >= 0; i2--) {
2181
+ for (let j2 = m - 1; j2 >= 0; j2--) {
2182
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
2183
+ }
2184
+ }
2185
+ const ops = [];
2186
+ let i = 0;
2187
+ let j = 0;
2188
+ while (i < n && j < m) {
2189
+ if (a[i] === b[j]) {
2190
+ ops.push({ kind: " ", text: a[i] });
2191
+ i++;
2192
+ j++;
2193
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
2194
+ ops.push({ kind: "-", text: a[i] });
2195
+ i++;
2196
+ } else {
2197
+ ops.push({ kind: "+", text: b[j] });
2198
+ j++;
2199
+ }
2200
+ }
2201
+ while (i < n) ops.push({ kind: "-", text: a[i++] });
2202
+ while (j < m) ops.push({ kind: "+", text: b[j++] });
2203
+ return ops;
2204
+ }
2205
+ function unifiedDiff(oldText, newText, label, context = 3) {
2206
+ if (oldText === newText) return "";
2207
+ const a = splitLines(oldText);
2208
+ const b = splitLines(newText);
2209
+ const ops = diffOps(a, b);
2210
+ const changed = ops.map((op) => op.kind !== " ");
2211
+ if (!changed.some(Boolean)) {
2212
+ return `--- ${label}
2213
+ +++ ${label}
2214
+ @@ trailing newline changed @@
2215
+ `;
2216
+ }
2217
+ const out = [`--- ${oldText === "" ? "/dev/null" : label}`, `+++ ${label}`];
2218
+ let k = 0;
2219
+ while (k < ops.length) {
2220
+ if (!changed[k]) {
2221
+ k++;
2222
+ continue;
2223
+ }
2224
+ let start = Math.max(0, k - context);
2225
+ let end = k;
2226
+ while (end < ops.length) {
2227
+ if (changed[end]) {
2228
+ end++;
2229
+ continue;
2230
+ }
2231
+ let next = end;
2232
+ while (next < ops.length && !changed[next]) next++;
2233
+ if (next < ops.length && next - end <= context * 2) {
2234
+ end = next;
2235
+ continue;
2236
+ }
2237
+ break;
2238
+ }
2239
+ const stop = Math.min(ops.length, end + context);
2240
+ let oldStart = 1;
2241
+ let newStart = 1;
2242
+ for (let p = 0; p < start; p++) {
2243
+ if (ops[p].kind !== "+") oldStart++;
2244
+ if (ops[p].kind !== "-") newStart++;
2245
+ }
2246
+ const slice = ops.slice(start, stop);
2247
+ const oldCount = slice.filter((op) => op.kind !== "+").length;
2248
+ const newCount = slice.filter((op) => op.kind !== "-").length;
2249
+ out.push(`@@ -${oldCount ? oldStart : oldStart - 1},${oldCount} +${newCount ? newStart : newStart - 1},${newCount} @@`);
2250
+ for (const op of slice) out.push(`${op.kind}${op.text}`);
2251
+ k = stop;
2252
+ start = stop;
2253
+ }
2254
+ return `${out.join("\n")}
2255
+ `;
2256
+ }
2257
+
2258
+ const ROLE$1 = "settings";
2259
+ const AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN";
2260
+ const API_KEY$1 = "ANTHROPIC_API_KEY";
2261
+ const ALIAS_VARS = { opusModel: "ANTHROPIC_DEFAULT_OPUS_MODEL", sonnetModel: "ANTHROPIC_DEFAULT_SONNET_MODEL", haikuModel: "ANTHROPIC_DEFAULT_HAIKU_MODEL" };
2262
+ function claudeEnvHelper(name) {
2263
+ return `printf %s "$${name}"`;
2264
+ }
2265
+ const OUR_HELPER = /^printf %s "\$([A-Za-z_][A-Za-z0-9_]*)"$/;
2266
+ const OWNED_PATHS = [
2267
+ ["env", "ANTHROPIC_BASE_URL"],
2268
+ ["env", AUTH_TOKEN],
2269
+ ["env", API_KEY$1],
2270
+ ["env", ALIAS_VARS.opusModel],
2271
+ ["env", ALIAS_VARS.sonnetModel],
2272
+ ["env", ALIAS_VARS.haikuModel],
2273
+ ["model"],
2274
+ ["modelPicker", "options"],
2275
+ ["apiKeyHelper"],
2276
+ ["availableModels"]
2277
+ ];
2278
+ function claudeSettingsPath(ctx) {
2279
+ const dir = ctx.env.CLAUDE_CONFIG_DIR?.trim() || join(ctx.home, ".claude");
2280
+ return join(dir, "settings.json");
2281
+ }
2282
+ function str$3(v) {
2283
+ return typeof v === "string" && v.trim() ? v : null;
2284
+ }
2285
+ function envOf(settings) {
2286
+ const env = settings.env;
2287
+ return env && typeof env === "object" && !Array.isArray(env) ? env : {};
2288
+ }
2289
+ function pickerOptions(settings) {
2290
+ const picker = settings.modelPicker;
2291
+ if (!picker || typeof picker !== "object" || Array.isArray(picker)) return [];
2292
+ const options = picker.options;
2293
+ return Array.isArray(options) ? options.filter((o) => !!o && typeof o === "object" && typeof o.model === "string") : [];
2294
+ }
2295
+ function secretView$1(settings, ctx) {
2296
+ const env = envOf(settings);
2297
+ const literal = str$3(env[AUTH_TOKEN]) ?? str$3(env[API_KEY$1]);
2298
+ if (literal) return { mode: "literal", masked: maskSecret(literal) };
2299
+ const helper = str$3(settings.apiKeyHelper);
2300
+ if (helper) {
2301
+ const ours = OUR_HELPER.exec(helper.trim());
2302
+ if (ours) return { mode: "env", envName: ours[1], envPresent: !!ctx.env[ours[1]] };
2303
+ return { mode: "command" };
2304
+ }
2305
+ return { mode: "none" };
2306
+ }
2307
+ function currentOf$2(settings, ctx) {
2308
+ const env = envOf(settings);
2309
+ return {
2310
+ baseUrl: str$3(env.ANTHROPIC_BASE_URL),
2311
+ authHeader: !str$3(env[AUTH_TOKEN]) && str$3(env[API_KEY$1]) ? "x-api-key" : "bearer",
2312
+ apiKey: secretView$1(settings, ctx),
2313
+ model: str$3(settings.model),
2314
+ opusModel: str$3(env[ALIAS_VARS.opusModel]),
2315
+ sonnetModel: str$3(env[ALIAS_VARS.sonnetModel]),
2316
+ haikuModel: str$3(env[ALIAS_VARS.haikuModel]),
2317
+ pickerModels: pickerOptions(settings).map((o) => o.model)
2318
+ };
2319
+ }
2320
+ function pickerModelsOf(current) {
2321
+ return uniq([current.model, current.opusModel, current.sonnetModel, current.haikuModel, ...current.pickerModels ?? []]);
2322
+ }
2323
+ function warningsOf$2(settings, current, ctx) {
2324
+ const env = envOf(settings);
2325
+ const out = [...baseUrlWarnings(current.baseUrl, "anthropic")];
2326
+ if (str$3(env.ANTHROPIC_MODEL)) {
2327
+ out.push({ code: "env-model-overrides", message: "env.ANTHROPIC_MODEL is set in settings.json and overrides the default model." });
2328
+ }
2329
+ const daemonOther = current.authHeader === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2330
+ if (current.baseUrl && ctx.env[daemonOther]) {
2331
+ out.push({ code: "daemon-env-credential", message: `The daemon's environment also defines ${daemonOther}; sessions inherit it.` });
2332
+ }
2333
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
2334
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
2335
+ }
2336
+ if (Array.isArray(settings.availableModels)) {
2337
+ const allowed = settings.availableModels;
2338
+ const missing = pickerModelsOf(current).filter((id) => !allowed.includes(id));
2339
+ if (missing.length) out.push({ code: "available-models-filter", message: `availableModels does not list ${missing.join(", ")}; Claude Code hides them.` });
2340
+ }
2341
+ return out;
2342
+ }
2343
+ function parsePatch$1(raw) {
2344
+ const p = raw;
2345
+ if (p.authHeader !== void 0 && p.authHeader !== "bearer" && p.authHeader !== "x-api-key") fail("invalid-input", "authHeader must be bearer or x-api-key");
2346
+ return {
2347
+ harness: "claude",
2348
+ baseUrl: normalizeBaseUrl(p.baseUrl),
2349
+ authHeader: p.authHeader,
2350
+ apiKey: normalizeSecret(p.apiKey),
2351
+ model: normalizeModelId(p.model),
2352
+ opusModel: normalizeModelId(p.opusModel, "opusModel"),
2353
+ sonnetModel: normalizeModelId(p.sonnetModel, "sonnetModel"),
2354
+ haikuModel: normalizeModelId(p.haikuModel, "haikuModel"),
2355
+ pickerModels: normalizeModelList(p.pickerModels, "pickerModels")
2356
+ };
2357
+ }
2358
+ const claudeAdapter = {
2359
+ id: "claude",
2360
+ binary: "claude",
2361
+ files: (ctx) => [{ role: ROLE$1, path: claudeSettingsPath(ctx) }],
2362
+ view(files, ctx) {
2363
+ const settings = parseJsonObject$1(files[ROLE$1].content, "settings.json");
2364
+ const current = currentOf$2(settings, ctx);
2365
+ return { current, pickerModels: pickerModelsOf(current), warnings: warningsOf$2(settings, current, ctx) };
2366
+ },
2367
+ plan(files, raw, ctx) {
2368
+ const patch = parsePatch$1(raw);
2369
+ const original = files[ROLE$1].content;
2370
+ const before = parseJsonObject$1(original, "settings.json");
2371
+ const settings = structuredClone(before);
2372
+ const hadEnv = settings.env !== void 0;
2373
+ const env = childObject(settings, "env", "settings");
2374
+ if (patch.baseUrl !== void 0) setOrDelete(env, "ANTHROPIC_BASE_URL", patch.baseUrl);
2375
+ const currentHeader = !str$3(env[AUTH_TOKEN]) && str$3(env[API_KEY$1]) ? "x-api-key" : "bearer";
2376
+ const header = patch.authHeader ?? currentHeader;
2377
+ const target = header === "bearer" ? AUTH_TOKEN : API_KEY$1;
2378
+ const other = header === "bearer" ? API_KEY$1 : AUTH_TOKEN;
2379
+ const helperIsOurs = typeof settings.apiKeyHelper === "string" && OUR_HELPER.test(settings.apiKeyHelper.trim());
2380
+ const secrets = [];
2381
+ switch (patch.apiKey.mode) {
2382
+ case "literal":
2383
+ env[target] = patch.apiKey.value;
2384
+ delete env[other];
2385
+ if (helperIsOurs) delete settings.apiKeyHelper;
2386
+ secrets.push(patch.apiKey.value);
2387
+ break;
2388
+ case "env":
2389
+ settings.apiKeyHelper = claudeEnvHelper(patch.apiKey.name);
2390
+ delete env[AUTH_TOKEN];
2391
+ delete env[API_KEY$1];
2392
+ break;
2393
+ case "clear":
2394
+ delete env[AUTH_TOKEN];
2395
+ delete env[API_KEY$1];
2396
+ if (helperIsOurs) delete settings.apiKeyHelper;
2397
+ break;
2398
+ case "keep":
2399
+ if (header !== currentHeader && str$3(env[other]) && !str$3(env[target])) {
2400
+ env[target] = env[other];
2401
+ delete env[other];
2402
+ }
2403
+ break;
2404
+ }
2405
+ if (patch.model !== void 0) setOrDelete(settings, "model", patch.model);
2406
+ for (const [field, variable] of Object.entries(ALIAS_VARS)) {
2407
+ if (patch[field] !== void 0) setOrDelete(env, variable, patch[field]);
2408
+ }
2409
+ if (patch.pickerModels !== void 0) {
2410
+ const hadPicker = settings.modelPicker !== void 0;
2411
+ const picker = childObject(settings, "modelPicker", "settings");
2412
+ const existing = pickerOptions(settings);
2413
+ const next = patch.pickerModels.map((id) => existing.find((o) => o.model === id) ?? { model: id });
2414
+ if (next.length) picker.options = next;
2415
+ else delete picker.options;
2416
+ if (!hadPicker && Object.keys(picker).length === 0) delete settings.modelPicker;
2417
+ }
2418
+ if (!hadEnv && Object.keys(env).length === 0) delete settings.env;
2419
+ const current = currentOf$2(settings, ctx);
2420
+ if (Array.isArray(settings.availableModels)) {
2421
+ const allowed = settings.availableModels;
2422
+ const add = pickerModelsOf(current).filter((id) => !allowed.includes(id));
2423
+ if (add.length) settings.availableModels = [...allowed, ...add];
2424
+ }
2425
+ const changedKeys = changedPaths(before, settings, OWNED_PATHS);
2426
+ const content = changedKeys.length === 0 ? void 0 : stringifyLike(original, settings);
2427
+ return { contents: { [ROLE$1]: content }, warnings: warningsOf$2(settings, current, ctx), changedKeys, secrets };
2428
+ },
2429
+ secretsIn(_role, content) {
2430
+ try {
2431
+ return collectSecretValues(parseJsonObject$1(content, "settings.json"));
2432
+ } catch {
2433
+ return /* @__PURE__ */ new Set();
2434
+ }
2435
+ }
2436
+ };
2437
+
2438
+ /*!
2439
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2440
+ * SPDX-License-Identifier: BSD-3-Clause
2441
+ *
2442
+ * Redistribution and use in source and binary forms, with or without
2443
+ * modification, are permitted provided that the following conditions are met:
2444
+ *
2445
+ * 1. Redistributions of source code must retain the above copyright notice, this
2446
+ * list of conditions and the following disclaimer.
2447
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2448
+ * this list of conditions and the following disclaimer in the
2449
+ * documentation and/or other materials provided with the distribution.
2450
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2451
+ * may be used to endorse or promote products derived from this software without
2452
+ * specific prior written permission.
2453
+ *
2454
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2455
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2456
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2457
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2458
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2459
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2460
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2461
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2462
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2463
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2464
+ */
2465
+ function getLineColFromPtr(string, ptr) {
2466
+ let lines = string.slice(0, ptr).split(/\r?\n/);
2467
+ return [lines.length, lines.pop().length + 1];
2468
+ }
2469
+ function makeCodeBlock(string, line, column) {
2470
+ let lines = string.split(/\r?\n/);
2471
+ let codeblock = "";
2472
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
2473
+ for (let i = line - 1; i <= line + 1; i++) {
2474
+ let l = lines[i - 1];
2475
+ if (!l)
2476
+ continue;
2477
+ codeblock += i.toString().padEnd(numberLen, " ");
2478
+ codeblock += ": ";
2479
+ codeblock += l;
2480
+ codeblock += "\n";
2481
+ if (i === line) {
2482
+ codeblock += " ".repeat(numberLen + column + 2);
2483
+ codeblock += "^\n";
2484
+ }
2485
+ }
2486
+ return codeblock;
2487
+ }
2488
+ class TomlError extends Error {
2489
+ line;
2490
+ column;
2491
+ codeblock;
2492
+ constructor(message, options) {
2493
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
2494
+ const codeblock = makeCodeBlock(options.toml, line, column);
2495
+ super(`Invalid TOML document: ${message}
2496
+
2497
+ ${codeblock}`, options);
2498
+ this.line = line;
2499
+ this.column = column;
2500
+ this.codeblock = codeblock;
2501
+ }
2502
+ /** @internal */
2503
+ static x(message, ctx, ptr) {
2504
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
2505
+ }
2506
+ }
2507
+
2508
+ function parseString(ctx) {
2509
+ let startPtr = ctx.p;
2510
+ let c = ctx.s.charCodeAt(ctx.p++);
2511
+ let first = c;
2512
+ let isLiteral = c === 39;
2513
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
2514
+ if (isMultiline) {
2515
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
2516
+ ctx.p++;
2517
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
2518
+ ctx.p += 2;
2519
+ }
2520
+ let parsed = "";
2521
+ let sliceStart = ctx.p;
2522
+ let state = 0;
2523
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2524
+ c = ctx.s.charCodeAt(ctx.p);
2525
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
2526
+ state = state && 3;
2527
+ } else if (c < 32 && c !== 9 || c === 127) {
2528
+ TomlError.x("control characters are not allowed in strings", ctx);
2529
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
2530
+ if (isMultiline) {
2531
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2532
+ ctx.p++;
2533
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2534
+ ctx.p++;
2535
+ }
2536
+ if (!state) {
2537
+ let s = ctx.s.slice(sliceStart, ctx.p);
2538
+ parsed = parsed ? parsed + s : s;
2539
+ }
2540
+ ctx.p += isMultiline ? 3 : 1;
2541
+ return parsed;
2542
+ } else if (!state) {
2543
+ if (!isLiteral && c === 92) {
2544
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
2545
+ state = 1;
2546
+ }
2547
+ } else if (state === 1) {
2548
+ if (c === 120 || c === 117 || c === 85) {
2549
+ let errPtr = ctx.p++ - 1;
2550
+ let value = 0;
2551
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
2552
+ for (let j = 0; j < len; j++, ctx.p++) {
2553
+ let hex = ctx.s.charCodeAt(ctx.p);
2554
+ let digit = (
2555
+ /* 0-9 */
2556
+ hex >= 48 && hex <= 57 ? hex - 48 : (
2557
+ /* A-F */
2558
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
2559
+ /* a-f */
2560
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
2561
+ )
2562
+ )
2563
+ );
2564
+ if (digit < 0)
2565
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
2566
+ value = value << 4 | digit;
2567
+ }
2568
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
2569
+ TomlError.x("invalid unicode escape", ctx, errPtr);
2570
+ }
2571
+ parsed += String.fromCodePoint(value);
2572
+ sliceStart = ctx.p--;
2573
+ state = 0;
2574
+ } else if (isMultiline && (c === 32 || c === 9)) {
2575
+ state = 2;
2576
+ } else {
2577
+ if (c === 98)
2578
+ parsed += "\b";
2579
+ else if (c === 116)
2580
+ parsed += " ";
2581
+ else if (c === 110)
2582
+ parsed += "\n";
2583
+ else if (c === 102)
2584
+ parsed += "\f";
2585
+ else if (c === 114)
2586
+ parsed += "\r";
2587
+ else if (c === 101)
2588
+ parsed += "\x1B";
2589
+ else if (c === 34)
2590
+ parsed += '"';
2591
+ else if (c === 92)
2592
+ parsed += "\\";
2593
+ else
2594
+ TomlError.x("unrecognised escape sequence", ctx);
2595
+ sliceStart = ctx.p + 1;
2596
+ state = 0;
2597
+ }
2598
+ } else if (c !== 32 && c !== 9) {
2599
+ if (state === 2)
2600
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
2601
+ state = !isLiteral && c === 92 ? 1 : 0;
2602
+ sliceStart = ctx.p;
2603
+ }
2604
+ }
2605
+ TomlError.x("unfinished string", ctx, startPtr);
2606
+ }
2607
+
2608
+ /*!
2609
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2610
+ * SPDX-License-Identifier: BSD-3-Clause
2611
+ *
2612
+ * Redistribution and use in source and binary forms, with or without
2613
+ * modification, are permitted provided that the following conditions are met:
2614
+ *
2615
+ * 1. Redistributions of source code must retain the above copyright notice, this
2616
+ * list of conditions and the following disclaimer.
2617
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2618
+ * this list of conditions and the following disclaimer in the
2619
+ * documentation and/or other materials provided with the distribution.
2620
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2621
+ * may be used to endorse or promote products derived from this software without
2622
+ * specific prior written permission.
2623
+ *
2624
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2625
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2626
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2627
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2628
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2629
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2630
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2631
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2632
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2633
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2634
+ */
2635
+ 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;
2636
+ class TomlDate extends Date {
2637
+ #hasDate = false;
2638
+ #hasTime = false;
2639
+ #offset = null;
2640
+ constructor(date, fasttype, unsafeDelim) {
2641
+ let hasDate = true;
2642
+ let hasTime = true;
2643
+ let offset = "Z";
2644
+ let c;
2645
+ if (typeof date === "string") {
2646
+ if (fasttype)
2647
+ prep: {
2648
+ if (fasttype < 3) {
2649
+ if (+date.slice(11, 13) > 23) {
2650
+ date = "";
2651
+ break prep;
2652
+ }
2653
+ if (fasttype === 2) {
2654
+ offset = null;
2655
+ date += "Z";
2656
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
2657
+ offset = date.slice(date.length - 6);
2658
+ }
2659
+ if (unsafeDelim)
2660
+ date = date.slice(0, 10) + "T" + date.slice(11);
2661
+ } else if (fasttype === 4) {
2662
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
2663
+ }
2664
+ hasDate = fasttype !== 4;
2665
+ hasTime = fasttype !== 3;
2666
+ }
2667
+ else {
2668
+ let match = date.match(DATE_TIME_RE);
2669
+ if (match) {
2670
+ if (!match[1]) {
2671
+ hasDate = false;
2672
+ date = `0000-01-01T${date}`;
2673
+ }
2674
+ hasTime = !!match[2];
2675
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
2676
+ if (match[2] && +match[2] > 23) {
2677
+ date = "";
2678
+ } else {
2679
+ offset = match[3] || null;
2680
+ if (!offset && hasTime)
2681
+ date += "Z";
2682
+ }
2683
+ } else {
2684
+ date = "";
2685
+ }
2686
+ }
2687
+ }
2688
+ super(date);
2689
+ if (!isNaN(this.getTime())) {
2690
+ this.#hasDate = hasDate;
2691
+ this.#hasTime = hasTime;
2692
+ this.#offset = offset;
2693
+ }
2694
+ }
2695
+ isDateTime() {
2696
+ return this.#hasDate && this.#hasTime;
2697
+ }
2698
+ isLocal() {
2699
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
2700
+ }
2701
+ isDate() {
2702
+ return this.#hasDate && !this.#hasTime;
2703
+ }
2704
+ isTime() {
2705
+ return this.#hasTime && !this.#hasDate;
2706
+ }
2707
+ isValid() {
2708
+ return this.#hasDate || this.#hasTime;
2709
+ }
2710
+ toISOString() {
2711
+ let iso = super.toISOString();
2712
+ if (this.isDate())
2713
+ return iso.slice(0, 10);
2714
+ if (this.isTime())
2715
+ return iso.slice(11, 23);
2716
+ if (this.#offset === null)
2717
+ return iso.slice(0, -1);
2718
+ if (this.#offset === "Z" || this.#offset === "z")
2719
+ return iso;
2720
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
2721
+ offset = this.#offset[0] === "-" ? offset : -offset;
2722
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
2723
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
2724
+ }
2725
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
2726
+ let date = new TomlDate(jsDate);
2727
+ date.#offset = offset;
2728
+ return date;
2729
+ }
2730
+ static wrapAsLocalDateTime(jsDate) {
2731
+ let date = new TomlDate(jsDate);
2732
+ date.#offset = null;
2733
+ return date;
2734
+ }
2735
+ static wrapAsLocalDate(jsDate) {
2736
+ let date = new TomlDate(jsDate);
2737
+ date.#hasTime = false;
2738
+ date.#offset = null;
2739
+ return date;
2740
+ }
2741
+ static wrapAsLocalTime(jsDate) {
2742
+ let date = new TomlDate(jsDate);
2743
+ date.#hasDate = false;
2744
+ date.#offset = null;
2745
+ return date;
2746
+ }
2747
+ }
2748
+
2749
+ function isDigit(char, base = 10) {
2750
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
2751
+ }
2752
+ function isEndOfValue(char, delim) {
2753
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
2754
+ delim && (char === delim || char === 44) || // Comment
2755
+ char === 35;
2756
+ }
2757
+ function extractValue(ctx, end) {
2758
+ let errPtr = ctx.p;
2759
+ let c = ctx.s.charCodeAt(ctx.p);
2760
+ if (c === 91 || c === 123) {
2761
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
2762
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
2763
+ ctx.d++;
2764
+ return value;
2765
+ }
2766
+ if (c === 34 || c === 39) {
2767
+ return parseString(ctx);
2768
+ }
2769
+ if (c === 116) {
2770
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
2771
+ TomlError.x("invalid value", ctx, errPtr);
2772
+ return ctx.p++, true;
2773
+ }
2774
+ if (c === 102) {
2775
+ 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)
2776
+ TomlError.x("invalid value", ctx, errPtr);
2777
+ return ctx.p++, false;
2778
+ }
2779
+ if (c === 43 || c === 45) {
2780
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
2781
+ }
2782
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
2783
+ return parseDate(ctx, c, end);
2784
+ }
2785
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
2786
+ return parseTime(ctx, c, end);
2787
+ }
2788
+ return parseNumber(ctx, ctx.p, c, 0, end);
2789
+ }
2790
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
2791
+ let c = startChr;
2792
+ let state = 0;
2793
+ let hasUnderscores = false;
2794
+ if (c === 105) {
2795
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
2796
+ TomlError.x("invalid value", ctx, startPtr);
2797
+ return ctx.p++, (sign || 1) / 0;
2798
+ }
2799
+ if (c === 110) {
2800
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
2801
+ TomlError.x("invalid value", ctx, startPtr);
2802
+ return ctx.p++, NaN;
2803
+ }
2804
+ if (c === 48) {
2805
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
2806
+ return ctx.bi === true ? 0n : 0;
2807
+ if (!sign) {
2808
+ if (c === 120)
2809
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
2810
+ else if (c === 98)
2811
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
2812
+ else if (c === 111)
2813
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
2814
+ }
2815
+ if (c === 46)
2816
+ state = 2;
2817
+ else if (c === 101 || c === 69)
2818
+ state = 4;
2819
+ else
2820
+ TomlError.x("illegal leading zero", ctx, startPtr);
2821
+ } else if (!isDigit(c))
2822
+ TomlError.x("invalid value", ctx, startPtr);
2823
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2824
+ if (!state)
2825
+ state = 1;
2826
+ if (c === 95) {
2827
+ if (!(state & 1))
2828
+ TomlError.x("illegal underscore", ctx);
2829
+ state += 11;
2830
+ hasUnderscores = true;
2831
+ } else if (state === 1 && c === 46)
2832
+ state = 2;
2833
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
2834
+ state = 4;
2835
+ else if (state === 4 && (c === 43 || c === 45)) ; else if (!isDigit(c))
2836
+ TomlError.x(`illegal character in numeric literal`, ctx);
2837
+ else if (state > 9)
2838
+ state -= 11;
2839
+ else if (!(state & 1))
2840
+ state++;
2841
+ }
2842
+ if (!state) {
2843
+ let val = (startChr - 48) * (sign || 1);
2844
+ return ctx.bi === true ? BigInt(val) : val;
2845
+ }
2846
+ if (!(state & 1))
2847
+ TomlError.x("unfinished numeric value", ctx, startPtr);
2848
+ let str = ctx.s.slice(startPtr, ctx.p);
2849
+ if (hasUnderscores)
2850
+ str = str.replaceAll("_", "");
2851
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
2852
+ }
2853
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
2854
+ let c, underscore = 1;
2855
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2856
+ if (c === 95) {
2857
+ if (underscore & 1)
2858
+ TomlError.x("illegal underscore", ctx);
2859
+ underscore = 3;
2860
+ } else if (!isDigit(c, base))
2861
+ TomlError.x(`illegal character in numeric literal`, ctx);
2862
+ else if (underscore & 1)
2863
+ underscore--;
2864
+ }
2865
+ if (underscore & 1)
2866
+ TomlError.x("unfinished numeric value", ctx);
2867
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
2868
+ if (underscore)
2869
+ str = str.replaceAll("_", "");
2870
+ return parseInteger(ctx, str, base, startPtr);
2871
+ }
2872
+ function parseInteger(ctx, str, base, startPtr) {
2873
+ if (ctx.bi !== true)
2874
+ int: {
2875
+ let val = parseInt(str, base);
2876
+ if (!Number.isSafeInteger(val)) {
2877
+ if (ctx.bi)
2878
+ break int;
2879
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
2880
+ }
2881
+ return val;
2882
+ }
2883
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
2884
+ }
2885
+ function parseDate(ctx, c, endChr) {
2886
+ let startPtr = ctx.p++, unsafeSeparator;
2887
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
2888
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
2889
+ }
2890
+ ctx.p += 5;
2891
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
2892
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
2893
+ 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) {
2894
+ let t2 = ctx.s.slice(startPtr, ctx.p);
2895
+ return readDate(ctx, t2, 3, false, startPtr);
2896
+ }
2897
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
2898
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
2899
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
2900
+ ctx.p += 3;
2901
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2902
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2903
+ ;
2904
+ if (c = ctx.s.charCodeAt(ctx.p)) {
2905
+ if (c === 90 || c === 122) {
2906
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
2907
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
2908
+ }
2909
+ if (c === 43 || c === 45) {
2910
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
2911
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
2912
+ }
2913
+ }
2914
+ let t = ctx.s.slice(startPtr, ctx.p);
2915
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
2916
+ }
2917
+ function parseTime(ctx, c, endChr) {
2918
+ let start = ctx.p;
2919
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
2920
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
2921
+ }
2922
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
2923
+ ctx.p += 3;
2924
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2925
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2926
+ ;
2927
+ let t = ctx.s.slice(start, ctx.p);
2928
+ return readDate(ctx, t, 4, false, start);
2929
+ }
2930
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
2931
+ if (ctx.ld) {
2932
+ let date = new TomlDate(str, type, unsafeDelim);
2933
+ if (!date.isValid())
2934
+ TomlError.x("invalid date", ctx, errPtr);
2935
+ return date;
2936
+ }
2937
+ try {
2938
+ if (temporalSuffix)
2939
+ str += temporalSuffix;
2940
+ switch (type) {
2941
+ case 1:
2942
+ return Temporal.ZonedDateTime.from(str);
2943
+ case 2:
2944
+ return Temporal.PlainDateTime.from(str);
2945
+ case 3:
2946
+ return Temporal.PlainDate.from(str);
2947
+ case 4:
2948
+ return Temporal.PlainTime.from(str);
2949
+ }
2950
+ } catch (e) {
2951
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
2952
+ }
2953
+ }
2954
+
2955
+ function skipComment(ctx) {
2956
+ for (; ctx.p < ctx.s.length; ctx.p++) {
2957
+ let c = ctx.s.charCodeAt(ctx.p);
2958
+ if (c === 10)
2959
+ break;
2960
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
2961
+ ctx.p++;
2962
+ break;
2963
+ }
2964
+ if (c < 32 && c !== 9 || c === 127) {
2965
+ TomlError.x("control characters are not allowed in comments", ctx);
2966
+ }
2967
+ }
2968
+ }
2969
+ function skipVoid(ctx, banNewLines, banComments) {
2970
+ let c;
2971
+ while (ctx.p < ctx.s.length) {
2972
+ 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)))
2973
+ ctx.p++;
2974
+ if (banComments || c !== 35)
2975
+ break;
2976
+ skipComment(ctx);
2977
+ }
2978
+ }
2979
+
2980
+ function parseKey(ctx, end = 61) {
2981
+ let startPtr;
2982
+ let state = 0;
2983
+ let parsed = [];
2984
+ let sliceStart;
2985
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
2986
+ do {
2987
+ if (c === end) {
2988
+ if (!state)
2989
+ TomlError.x("unexpected end of key", ctx);
2990
+ if (state === 1)
2991
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
2992
+ return ctx.p++, parsed;
2993
+ } else if (c === 46) {
2994
+ if (!state)
2995
+ TomlError.x("illegal empty bare key", ctx);
2996
+ if (state === 1)
2997
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
2998
+ state = 0;
2999
+ } else if (!state && (c === 34 || c === 39)) {
3000
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
3001
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
3002
+ parsed.push(parseString(ctx));
3003
+ state = 2;
3004
+ ctx.p--;
3005
+ } else if (c === 32 || c === 9) {
3006
+ if (state === 1) {
3007
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
3008
+ state = 2;
3009
+ }
3010
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
3011
+ TomlError.x("illegal character in key", ctx);
3012
+ } else if (!state) {
3013
+ state = 1;
3014
+ sliceStart = ctx.p;
3015
+ }
3016
+ } while (c = ctx.s.charCodeAt(++ctx.p));
3017
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
3018
+ }
3019
+ function parseInlineTable(ctx) {
3020
+ let startPtr = ctx.p++;
3021
+ let res = /* @__PURE__ */ Object.create(null);
3022
+ let seen = /* @__PURE__ */ new Set();
3023
+ let c;
3024
+ while (ctx.p < ctx.s.length) {
3025
+ skipVoid(ctx);
3026
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
3027
+ ctx.p++;
3028
+ return res;
3029
+ }
3030
+ let k;
3031
+ let t = res;
3032
+ let hasOwn = false;
3033
+ let errPtr = ctx.p;
3034
+ let key = parseKey(ctx);
3035
+ for (let i = 0; i < key.length; i++) {
3036
+ if (i)
3037
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3038
+ k = key[i];
3039
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
3040
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3041
+ }
3042
+ let unsafe = k === "__proto__";
3043
+ if (ctx.uk && (unsafe || k === "constructor")) {
3044
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
3045
+ break;
3046
+ }
3047
+ if (!hasOwn && unsafe) {
3048
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3049
+ }
3050
+ }
3051
+ if (hasOwn) {
3052
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
3053
+ }
3054
+ skipVoid(ctx, true, true);
3055
+ let value = extractValue(
3056
+ ctx,
3057
+ 125
3058
+ /* } */
3059
+ );
3060
+ if (t && typeof (t[k] = value) === "object")
3061
+ seen.add(value);
3062
+ skipVoid(ctx);
3063
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
3064
+ return res;
3065
+ }
3066
+ if (c !== 44)
3067
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3068
+ }
3069
+ TomlError.x("unfinished table", ctx, startPtr);
3070
+ }
3071
+ function parseArray(ctx) {
3072
+ let startPtr = ctx.p++;
3073
+ let res = [];
3074
+ let c;
3075
+ while (ctx.p < ctx.s.length) {
3076
+ skipVoid(ctx);
3077
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
3078
+ ctx.p++;
3079
+ return res;
3080
+ }
3081
+ res.push(extractValue(
3082
+ ctx,
3083
+ 93
3084
+ /* ] */
3085
+ ));
3086
+ skipVoid(ctx);
3087
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
3088
+ return res;
3089
+ }
3090
+ if (c !== 44)
3091
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
3092
+ }
3093
+ TomlError.x("unfinished array", ctx, startPtr);
3094
+ }
3095
+
3096
+ function peekTable(ctx, key, table, meta, type) {
3097
+ let t = table;
3098
+ let m = meta;
3099
+ let k;
3100
+ let hasOwn = false;
3101
+ let state;
3102
+ for (let i = 0; i < key.length; i++) {
3103
+ if (i) {
3104
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3105
+ m = (state = m[k]).c;
3106
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
3107
+ return null;
3108
+ }
3109
+ if (state.t === 2) {
3110
+ let l = t.length - 1;
3111
+ t = t[l];
3112
+ m = m[l].c;
3113
+ }
3114
+ }
3115
+ k = key[i];
3116
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
3117
+ return null;
3118
+ }
3119
+ if (!hasOwn) {
3120
+ let unsafe = k === "__proto__";
3121
+ if (ctx.uk && (unsafe || k === "constructor"))
3122
+ return false;
3123
+ if (unsafe) {
3124
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
3125
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
3126
+ }
3127
+ m[k] = {
3128
+ t: i < key.length - 1 && type === 2 ? 3 : type,
3129
+ d: false,
3130
+ i: 0,
3131
+ c: /* @__PURE__ */ Object.create(null)
3132
+ };
3133
+ }
3134
+ }
3135
+ state = m[k];
3136
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
3137
+ return null;
3138
+ }
3139
+ if (type === 2) {
3140
+ if (!state.d) {
3141
+ state.d = true;
3142
+ t[k] = [];
3143
+ }
3144
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
3145
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
3146
+ }
3147
+ if (state.d) {
3148
+ return null;
3149
+ }
3150
+ state.d = true;
3151
+ if (type === 1) {
3152
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
3153
+ } else if (type === 0 && hasOwn) {
3154
+ return null;
3155
+ }
3156
+ return [k, t, state.c];
3157
+ }
3158
+ function validateTablePeek(ctx, peek, ptr) {
3159
+ if (peek === null || ctx.uk === 2)
3160
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
3161
+ }
3162
+ function parse(toml, options = {}) {
3163
+ let ctx = {
3164
+ s: toml,
3165
+ p: 0,
3166
+ d: options.maxDepth ?? 1e3,
3167
+ bi: options.integersAsBigInt ?? false,
3168
+ ld: options.useLegacyDate ?? true,
3169
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
3170
+ };
3171
+ let res = /* @__PURE__ */ Object.create(null);
3172
+ let meta = /* @__PURE__ */ Object.create(null);
3173
+ let tmp;
3174
+ let skipping = false;
3175
+ let tbl = res;
3176
+ let m = meta;
3177
+ if (toml.charCodeAt(0) === 65279)
3178
+ ctx.p++;
3179
+ skipVoid(ctx);
3180
+ while (ctx.p < toml.length) {
3181
+ if (toml.charCodeAt(ctx.p) === 91) {
3182
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
3183
+ tmp = ctx.p += +isTableArray;
3184
+ skipping = false;
3185
+ let k = parseKey(
3186
+ ctx,
3187
+ 93
3188
+ /* ] */
3189
+ );
3190
+ if (isTableArray) {
3191
+ if (toml.charCodeAt(ctx.p) !== 93) {
3192
+ TomlError.x("expected end of table array declaration", ctx);
3193
+ }
3194
+ ctx.p++;
3195
+ }
3196
+ let p = peekTable(
3197
+ ctx,
3198
+ k,
3199
+ res,
3200
+ meta,
3201
+ isTableArray ? 2 : 1
3202
+ /* Type.EXPLICIT */
3203
+ );
3204
+ if (!p) {
3205
+ validateTablePeek(ctx, p, tmp);
3206
+ skipping = true;
3207
+ } else {
3208
+ m = p[2];
3209
+ tbl = p[1];
3210
+ }
3211
+ } else {
3212
+ tmp = ctx.p;
3213
+ let k = parseKey(ctx);
3214
+ let p = peekTable(
3215
+ ctx,
3216
+ k,
3217
+ tbl,
3218
+ m,
3219
+ 0
3220
+ /* Type.DOTTED */
3221
+ );
3222
+ if (!p && !skipping)
3223
+ validateTablePeek(ctx, p, tmp);
3224
+ skipVoid(ctx, true, true);
3225
+ let v = extractValue(ctx, void 0);
3226
+ if (p && !skipping)
3227
+ p[1][p[0]] = v;
3228
+ }
3229
+ skipVoid(ctx, true);
3230
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
3231
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
3232
+ }
3233
+ skipVoid(ctx);
3234
+ }
3235
+ return res;
3236
+ }
3237
+
3238
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
3239
+ function formatTomlKey(key) {
3240
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
3241
+ }
3242
+ function formatTomlValue(value) {
3243
+ if (typeof value === "boolean") return value ? "true" : "false";
3244
+ return JSON.stringify(value).replace(/\u007f/g, "\\u007F");
3245
+ }
3246
+ function splitDottedKey(raw) {
3247
+ const parts = [];
3248
+ let i = 0;
3249
+ const s = raw.trim();
3250
+ while (i < s.length) {
3251
+ while (s[i] === " " || s[i] === " ") i++;
3252
+ let part = "";
3253
+ if (s[i] === '"') {
3254
+ let j = i + 1;
3255
+ while (j < s.length && s[j] !== '"') {
3256
+ if (s[j] === "\\") j++;
3257
+ j++;
3258
+ }
3259
+ if (j >= s.length) return null;
3260
+ try {
3261
+ part = JSON.parse(s.slice(i, j + 1));
3262
+ } catch {
3263
+ return null;
3264
+ }
3265
+ i = j + 1;
3266
+ } else if (s[i] === "'") {
3267
+ const j = s.indexOf("'", i + 1);
3268
+ if (j < 0) return null;
3269
+ part = s.slice(i + 1, j);
3270
+ i = j + 1;
3271
+ } else {
3272
+ let j = i;
3273
+ while (j < s.length && /[A-Za-z0-9_-]/.test(s[j])) j++;
3274
+ if (j === i) return null;
3275
+ part = s.slice(i, j);
3276
+ i = j;
3277
+ }
3278
+ parts.push(part);
3279
+ while (s[i] === " " || s[i] === " ") i++;
3280
+ if (i >= s.length) break;
3281
+ if (s[i] !== ".") return null;
3282
+ i++;
3283
+ }
3284
+ return parts.length ? parts : null;
3285
+ }
3286
+ function scan(lines) {
3287
+ const sections = [{ path: null, arrayTable: false, headerLine: -1, start: 0, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: -1 }];
3288
+ let inMulti = null;
3289
+ let depth = 0;
3290
+ for (let n = 0; n < lines.length; n++) {
3291
+ const line = lines[n];
3292
+ const current = sections[sections.length - 1];
3293
+ if (inMulti) {
3294
+ if (line.includes(inMulti)) {
3295
+ inMulti = null;
3296
+ current.lastKeyLine = n;
3297
+ }
3298
+ continue;
3299
+ }
3300
+ const trimmed = line.trim();
3301
+ if (depth === 0) {
3302
+ const header = /^\[(\[)?\s*([^\[\]]+?)\s*\](\])?\s*(#.*)?$/.exec(trimmed);
3303
+ if (header) {
3304
+ current.end = n;
3305
+ const path = splitDottedKey(header[2]);
3306
+ sections.push({ path: path ?? [`\0invalid:${header[2]}`], arrayTable: !!header[1], headerLine: n, start: n + 1, end: lines.length, keys: /* @__PURE__ */ new Map(), lastKeyLine: n });
3307
+ continue;
3308
+ }
3309
+ const kv = /^((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s"'-])+?)\s*=/.exec(trimmed);
3310
+ if (kv) {
3311
+ const keyPath = splitDottedKey(kv[1]);
3312
+ if (keyPath) current.keys.set(keyPath.join("\0"), n);
3313
+ current.lastKeyLine = n;
3314
+ }
3315
+ } else if (trimmed) {
3316
+ current.lastKeyLine = n;
3317
+ }
3318
+ let i = 0;
3319
+ while (i < line.length) {
3320
+ const ch = line[i];
3321
+ if (ch === "#") break;
3322
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
3323
+ const fence = line.slice(i, i + 3);
3324
+ const close = line.indexOf(fence, i + 3);
3325
+ if (close < 0) {
3326
+ inMulti = fence;
3327
+ break;
3328
+ }
3329
+ i = close + 3;
3330
+ continue;
3331
+ }
3332
+ if (ch === '"') {
3333
+ i++;
3334
+ while (i < line.length && line[i] !== '"') {
3335
+ if (line[i] === "\\") i++;
3336
+ i++;
3337
+ }
3338
+ i++;
3339
+ continue;
3340
+ }
3341
+ if (ch === "'") {
3342
+ const close = line.indexOf("'", i + 1);
3343
+ i = close < 0 ? line.length : close + 1;
3344
+ continue;
3345
+ }
3346
+ if (ch === "[" || ch === "{") depth++;
3347
+ if (ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
3348
+ i++;
3349
+ }
3350
+ }
3351
+ return sections;
3352
+ }
3353
+ function trailingComment(line) {
3354
+ const m = /^\s*[^=]+=\s*("(?:[^"\\]|\\.)*"|'[^']*'|true|false|[0-9][0-9_.eE+-]*)(\s+#.*)$/.exec(line);
3355
+ return m ? m[2] : "";
3356
+ }
3357
+ const samePath = (a, b) => a !== null && a.length === b.length && a.every((p, i) => p === b[i]);
3358
+ const isUnder = (a, prefix) => a !== null && a.length >= prefix.length && prefix.every((p, i) => p === a[i]);
3359
+ function applyOne(text, edit) {
3360
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3361
+ const lines = text.split(/\r?\n/);
3362
+ const sections = scan(lines);
3363
+ if ("removeTable" in edit) {
3364
+ const doomed = sections.filter((s) => !s.arrayTable && isUnder(s.path, edit.table)).sort((a, b) => b.headerLine - a.headerLine);
3365
+ for (const s of doomed) {
3366
+ let end = s.end;
3367
+ while (end > s.start && lines[end - 1]?.trim() === "" && end - 1 > s.lastKeyLine) end--;
3368
+ lines.splice(s.headerLine, end - s.headerLine);
3369
+ }
3370
+ return lines.join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`).replace(/(\r?\n)+$/, eol);
3371
+ }
3372
+ const root = edit.table.length === 0;
3373
+ const section = root ? sections[0] : sections.find((s) => !s.arrayTable && samePath(s.path, edit.table));
3374
+ const keyId = edit.key;
3375
+ const rendered = edit.value === null ? null : `${formatTomlKey(edit.key)} = ${formatTomlValue(edit.value)}`;
3376
+ if (section) {
3377
+ const at = section.keys.get(keyId);
3378
+ if (at !== void 0) {
3379
+ const indent = /^\s*/.exec(lines[at])?.[0] ?? "";
3380
+ if (rendered === null) lines.splice(at, 1);
3381
+ else lines[at] = indent + rendered + trailingComment(lines[at]);
3382
+ return lines.join(eol);
3383
+ }
3384
+ if (rendered === null) return text;
3385
+ if (root) {
3386
+ const anchor = section.lastKeyLine;
3387
+ lines.splice(anchor + 1, 0, rendered);
3388
+ } else {
3389
+ lines.splice(section.lastKeyLine + 1, 0, rendered);
3390
+ }
3391
+ return lines.join(eol);
3392
+ }
3393
+ if (rendered === null) return text;
3394
+ while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
3395
+ const header = `[${edit.table.map(formatTomlKey).join(".")}]`;
3396
+ if (lines.length) lines.push("");
3397
+ lines.push(header, rendered, "");
3398
+ return lines.join(eol);
3399
+ }
3400
+ function parseToml(text) {
3401
+ try {
3402
+ return parse(text);
3403
+ } catch (error) {
3404
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
3405
+ throw new ModelConfigError("invalid-toml", `Not valid TOML: ${message}`);
3406
+ }
3407
+ }
3408
+ function getPath(obj, path) {
3409
+ let cur = obj;
3410
+ for (const p of path) {
3411
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) return void 0;
3412
+ cur = cur[p];
3413
+ }
3414
+ return cur;
3415
+ }
3416
+ function withoutPaths(obj, paths) {
3417
+ const clone = structuredClone(obj);
3418
+ for (const path of paths) {
3419
+ let cur = clone;
3420
+ for (const p of path.slice(0, -1)) {
3421
+ if (!cur || typeof cur !== "object") {
3422
+ cur = null;
3423
+ break;
3424
+ }
3425
+ cur = cur[p];
3426
+ }
3427
+ if (cur && typeof cur === "object") delete cur[path[path.length - 1]];
3428
+ }
3429
+ return clone;
3430
+ }
3431
+ function pruneEmpty(value) {
3432
+ if (!value || typeof value !== "object" || Array.isArray(value) || value instanceof Date) return value;
3433
+ const out = {};
3434
+ for (const [k, v] of Object.entries(value)) {
3435
+ const pruned = pruneEmpty(v);
3436
+ if (pruned && typeof pruned === "object" && !Array.isArray(pruned) && !(pruned instanceof Date) && Object.keys(pruned).length === 0) continue;
3437
+ out[k] = pruned;
3438
+ }
3439
+ return out;
3440
+ }
3441
+ function stableStringify(value) {
3442
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
3443
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
3444
+ if (value && typeof value === "object") {
3445
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
3446
+ }
3447
+ return JSON.stringify(value) ?? "null";
3448
+ }
3449
+ function verifyTomlEdit(oldText, newText, edits) {
3450
+ const before = parseToml(oldText);
3451
+ let after;
3452
+ try {
3453
+ after = parse(newText);
3454
+ } catch (error) {
3455
+ throw new ModelConfigError("unsafe-edit", `Edit would produce invalid TOML (${error instanceof Error ? error.message.split("\n")[0] : String(error)}); the file layout is not one this editor can change safely`);
3456
+ }
3457
+ const owned = edits.map((e) => "removeTable" in e ? e.table : [...e.table, e.key]);
3458
+ for (const edit of edits) {
3459
+ if ("removeTable" in edit) {
3460
+ if (getPath(after, edit.table) !== void 0) throw new ModelConfigError("unsafe-edit", `Table ${edit.table.join(".")} is still present after removal`);
3461
+ continue;
3462
+ }
3463
+ const got = getPath(after, [...edit.table, edit.key]);
3464
+ const want = edit.value === null ? void 0 : edit.value;
3465
+ if (got !== want) throw new ModelConfigError("unsafe-edit", `Key ${[...edit.table, edit.key].join(".")} did not take the requested value`);
3466
+ }
3467
+ if (stableStringify(pruneEmpty(withoutPaths(before, owned))) !== stableStringify(pruneEmpty(withoutPaths(after, owned)))) {
3468
+ throw new ModelConfigError("unsafe-edit", "Edit would change settings outside the keys Very Happy manages");
3469
+ }
3470
+ }
3471
+ function editToml(text, edits) {
3472
+ parseToml(text);
3473
+ let out = text;
3474
+ const ordered = [...edits.filter((e) => e.table.length === 0), ...edits.filter((e) => e.table.length > 0)];
3475
+ for (const edit of ordered) out = applyOne(out, edit);
3476
+ if (out !== text && !out.endsWith("\n")) out += text.includes("\r\n") ? "\r\n" : "\n";
3477
+ verifyTomlEdit(text, out, edits);
3478
+ return out;
3479
+ }
3480
+
3481
+ const ROLE = "config";
3482
+ const CODEX_RESERVED_PROVIDERS = ["openai", "ollama", "lmstudio", "amazon-bedrock", "amazon-bedrock-runtime", "oss"];
3483
+ function codexConfigPath(ctx) {
3484
+ const dir = ctx.env.CODEX_HOME?.trim() || join(ctx.home, ".codex");
3485
+ return join(dir, "config.toml");
3486
+ }
3487
+ const str$2 = (v) => typeof v === "string" && v.trim() ? v : null;
3488
+ function providersOf(doc) {
3489
+ const table = doc.model_providers;
3490
+ if (!table || typeof table !== "object" || Array.isArray(table)) return {};
3491
+ return Object.fromEntries(Object.entries(table).filter(([, v]) => v && typeof v === "object" && !Array.isArray(v)));
3492
+ }
3493
+ function secretView(provider, ctx) {
3494
+ if (!provider) return { mode: "none" };
3495
+ const token = str$2(provider.experimental_bearer_token);
3496
+ if (token) return { mode: "literal", masked: maskSecret(token) };
3497
+ const envKey = str$2(provider.env_key);
3498
+ if (envKey) return { mode: "env", envName: envKey, envPresent: !!ctx.env[envKey] };
3499
+ if (provider.auth && typeof provider.auth === "object") return { mode: "command" };
3500
+ return { mode: "none" };
3501
+ }
3502
+ function selectProvider(doc, requested) {
3503
+ const providers = providersOf(doc);
3504
+ if (requested) return requested;
3505
+ const active = str$2(doc.model_provider);
3506
+ if (active && providers[active]) return active;
3507
+ return Object.keys(providers)[0] ?? null;
3508
+ }
3509
+ function currentOf$1(doc, providerId, ctx) {
3510
+ const provider = providerId ? providersOf(doc)[providerId] : void 0;
3511
+ const activeProvider = str$2(doc.model_provider);
3512
+ return {
3513
+ providerId,
3514
+ providerName: str$2(provider?.name),
3515
+ baseUrl: str$2(provider?.base_url),
3516
+ apiKey: secretView(provider, ctx),
3517
+ model: str$2(doc.model),
3518
+ activeProvider,
3519
+ active: !!providerId && activeProvider === providerId
3520
+ };
3521
+ }
3522
+ function warningsOf$1(doc, current) {
3523
+ const out = [...baseUrlWarnings(current.baseUrl, "openai")];
3524
+ const provider = current.providerId ? providersOf(doc)[current.providerId] : void 0;
3525
+ if (provider && str$2(provider.wire_api) && provider.wire_api !== "responses") {
3526
+ out.push({ code: "wire-api-unsupported", message: `wire_api = "${String(provider.wire_api)}" is rejected by current Codex; only "responses" is supported.` });
3527
+ }
3528
+ if (current.apiKey?.mode === "env" && !current.apiKey.envPresent) {
3529
+ out.push({ code: "env-missing", message: `${current.apiKey.envName} is not set in the daemon's environment, so sessions will not get a key.` });
3530
+ }
3531
+ const active = current.activeProvider;
3532
+ if (active && !CODEX_RESERVED_PROVIDERS.includes(active) && !providersOf(doc)[active]) {
3533
+ out.push({ code: "active-provider-missing", message: `model_provider = "${active}" has no [model_providers.${active}] table.` });
3534
+ }
3535
+ return out;
3536
+ }
3537
+ function parsePatch(raw) {
3538
+ const p = raw;
3539
+ if (p.activate !== void 0 && typeof p.activate !== "boolean") fail("invalid-input", "activate must be a boolean");
3540
+ if (p.providerName !== void 0 && (typeof p.providerName !== "string" || p.providerName.length > 120 || /[\u0000-\u001f]/.test(p.providerName))) {
3541
+ fail("invalid-input", "providerName must be a short single-line string");
3542
+ }
3543
+ return {
3544
+ providerId: normalizeProviderId(p.providerId, CODEX_RESERVED_PROVIDERS),
3545
+ providerName: p.providerName?.trim(),
3546
+ baseUrl: normalizeBaseUrl(p.baseUrl),
3547
+ apiKey: normalizeSecret(p.apiKey),
3548
+ model: normalizeModelId(p.model),
3549
+ activate: p.activate
3550
+ };
3551
+ }
3552
+ const codexAdapter = {
3553
+ id: "codex",
3554
+ binary: "codex",
3555
+ files: (ctx) => [{ role: ROLE, path: codexConfigPath(ctx) }],
3556
+ view(files, ctx, opts) {
3557
+ const doc = parseToml(files[ROLE].content);
3558
+ const current = currentOf$1(doc, selectProvider(doc, opts.providerId), ctx);
3559
+ return { current, providers: Object.keys(providersOf(doc)), pickerModels: uniq([current.model]), warnings: warningsOf$1(doc, current) };
3560
+ },
3561
+ plan(files, raw, ctx) {
3562
+ const patch = parsePatch(raw);
3563
+ const original = files[ROLE].content;
3564
+ const before = parseToml(original);
3565
+ const existing = providersOf(before)[patch.providerId];
3566
+ const table = ["model_providers", patch.providerId];
3567
+ const edits = [];
3568
+ const secrets = [];
3569
+ if (!existing && !patch.baseUrl) fail("invalid-input", "A new provider needs a base URL");
3570
+ const name = patch.providerName || str$2(existing?.name) || patch.providerId;
3571
+ if (!existing || patch.providerName && patch.providerName !== existing.name || !str$2(existing.name)) edits.push({ table, key: "name", value: name });
3572
+ if (patch.baseUrl !== void 0) {
3573
+ if (patch.baseUrl === null && existing) fail("invalid-input", "A provider needs a base URL; remove the provider instead");
3574
+ edits.push({ table, key: "base_url", value: patch.baseUrl });
3575
+ }
3576
+ if (!existing || str$2(existing.wire_api) && existing.wire_api !== "responses") edits.push({ table, key: "wire_api", value: "responses" });
3577
+ switch (patch.apiKey.mode) {
3578
+ case "literal":
3579
+ edits.push({ table, key: "experimental_bearer_token", value: patch.apiKey.value }, { table, key: "env_key", value: null });
3580
+ secrets.push(patch.apiKey.value);
3581
+ break;
3582
+ case "env":
3583
+ edits.push({ table, key: "env_key", value: patch.apiKey.name }, { table, key: "experimental_bearer_token", value: null });
3584
+ break;
3585
+ case "clear":
3586
+ edits.push({ table, key: "env_key", value: null }, { table, key: "experimental_bearer_token", value: null });
3587
+ break;
3588
+ }
3589
+ if (patch.model !== void 0) edits.push({ table: [], key: "model", value: patch.model });
3590
+ if (patch.activate === true) edits.push({ table: [], key: "model_provider", value: patch.providerId });
3591
+ if (patch.activate === false && str$2(before.model_provider) === patch.providerId) edits.push({ table: [], key: "model_provider", value: null });
3592
+ const effective = edits.filter((e) => "removeTable" in e || getPath$1(before, [...e.table, e.key]) !== (e.value ?? void 0));
3593
+ const content = effective.length ? editToml(original, effective) : void 0;
3594
+ const after = content === void 0 ? before : parseToml(content);
3595
+ const current = currentOf$1(after, patch.providerId, ctx);
3596
+ const changedKeys = effective.map((e) => [...e.table, "removeTable" in e ? "*" : e.key].join("."));
3597
+ return { contents: { [ROLE]: content }, warnings: warningsOf$1(after, current), changedKeys, secrets };
3598
+ },
3599
+ secretsIn(_role, content) {
3600
+ try {
3601
+ return collectSecretValues(parseToml(content));
3602
+ } catch (error) {
3603
+ if (error instanceof ModelConfigError) return /* @__PURE__ */ new Set();
3604
+ throw error;
3605
+ }
3606
+ }
3607
+ };
3608
+
3609
+ var main = {exports: {}};
3610
+
3611
+ var version = "16.6.1";
3612
+ var require$$4 = {
3613
+ version: version};
3614
+
3615
+ var hasRequiredMain;
3616
+
3617
+ function requireMain () {
3618
+ if (hasRequiredMain) return main.exports;
3619
+ hasRequiredMain = 1;
3620
+ const fs = require$$0;
3621
+ const path = require$$1;
3622
+ const os$1 = os;
3623
+ const crypto = require$$3;
3624
+ const packageJson = require$$4;
3625
+ const version = packageJson.version;
3626
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
3627
+ function parse(src) {
3628
+ const obj = {};
3629
+ let lines = src.toString();
3630
+ lines = lines.replace(/\r\n?/mg, "\n");
3631
+ let match;
3632
+ while ((match = LINE.exec(lines)) != null) {
3633
+ const key = match[1];
3634
+ let value = match[2] || "";
3635
+ value = value.trim();
3636
+ const maybeQuote = value[0];
3637
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
3638
+ if (maybeQuote === '"') {
3639
+ value = value.replace(/\\n/g, "\n");
3640
+ value = value.replace(/\\r/g, "\r");
3641
+ }
3642
+ obj[key] = value;
3643
+ }
3644
+ return obj;
3645
+ }
3646
+ function _parseVault(options) {
3647
+ options = options || {};
3648
+ const vaultPath = _vaultPath(options);
3649
+ options.path = vaultPath;
3650
+ const result = DotenvModule.configDotenv(options);
3651
+ if (!result.parsed) {
3652
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
3653
+ err.code = "MISSING_DATA";
3654
+ throw err;
3655
+ }
3656
+ const keys = _dotenvKey(options).split(",");
3657
+ const length = keys.length;
3658
+ let decrypted;
3659
+ for (let i = 0; i < length; i++) {
3660
+ try {
3661
+ const key = keys[i].trim();
3662
+ const attrs = _instructions(result, key);
3663
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
3664
+ break;
3665
+ } catch (error) {
3666
+ if (i + 1 >= length) {
3667
+ throw error;
3668
+ }
3669
+ }
3670
+ }
3671
+ return DotenvModule.parse(decrypted);
3672
+ }
3673
+ function _warn(message) {
3674
+ console.log(`[dotenv@${version}][WARN] ${message}`);
3675
+ }
3676
+ function _debug(message) {
3677
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
3678
+ }
3679
+ function _log(message) {
3680
+ console.log(`[dotenv@${version}] ${message}`);
3681
+ }
3682
+ function _dotenvKey(options) {
3683
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
3684
+ return options.DOTENV_KEY;
3685
+ }
3686
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
3687
+ return process.env.DOTENV_KEY;
3688
+ }
3689
+ return "";
3690
+ }
3691
+ function _instructions(result, dotenvKey) {
3692
+ let uri;
3693
+ try {
3694
+ uri = new URL(dotenvKey);
3695
+ } catch (error) {
3696
+ if (error.code === "ERR_INVALID_URL") {
3697
+ 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");
3698
+ err.code = "INVALID_DOTENV_KEY";
3699
+ throw err;
3700
+ }
3701
+ throw error;
3702
+ }
3703
+ const key = uri.password;
3704
+ if (!key) {
3705
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
3706
+ err.code = "INVALID_DOTENV_KEY";
3707
+ throw err;
3708
+ }
3709
+ const environment = uri.searchParams.get("environment");
3710
+ if (!environment) {
3711
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
3712
+ err.code = "INVALID_DOTENV_KEY";
3713
+ throw err;
3714
+ }
3715
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
3716
+ const ciphertext = result.parsed[environmentKey];
3717
+ if (!ciphertext) {
3718
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
3719
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
3720
+ throw err;
3721
+ }
3722
+ return { ciphertext, key };
3723
+ }
3724
+ function _vaultPath(options) {
3725
+ let possibleVaultPath = null;
3726
+ if (options && options.path && options.path.length > 0) {
3727
+ if (Array.isArray(options.path)) {
3728
+ for (const filepath of options.path) {
3729
+ if (fs.existsSync(filepath)) {
3730
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
3731
+ }
3732
+ }
3733
+ } else {
3734
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
3735
+ }
3736
+ } else {
3737
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
3738
+ }
3739
+ if (fs.existsSync(possibleVaultPath)) {
3740
+ return possibleVaultPath;
3741
+ }
3742
+ return null;
3743
+ }
3744
+ function _resolveHome(envPath) {
3745
+ return envPath[0] === "~" ? path.join(os$1.homedir(), envPath.slice(1)) : envPath;
3746
+ }
3747
+ function _configVault(options) {
3748
+ const debug = Boolean(options && options.debug);
3749
+ const quiet = options && "quiet" in options ? options.quiet : true;
3750
+ if (debug || !quiet) {
3751
+ _log("Loading env from encrypted .env.vault");
3752
+ }
3753
+ const parsed = DotenvModule._parseVault(options);
3754
+ let processEnv = process.env;
3755
+ if (options && options.processEnv != null) {
3756
+ processEnv = options.processEnv;
3757
+ }
3758
+ DotenvModule.populate(processEnv, parsed, options);
3759
+ return { parsed };
3760
+ }
3761
+ function configDotenv(options) {
3762
+ const dotenvPath = path.resolve(process.cwd(), ".env");
3763
+ let encoding = "utf8";
3764
+ const debug = Boolean(options && options.debug);
3765
+ const quiet = options && "quiet" in options ? options.quiet : true;
3766
+ if (options && options.encoding) {
3767
+ encoding = options.encoding;
3768
+ } else {
3769
+ if (debug) {
3770
+ _debug("No encoding is specified. UTF-8 is used by default");
3771
+ }
3772
+ }
3773
+ let optionPaths = [dotenvPath];
3774
+ if (options && options.path) {
3775
+ if (!Array.isArray(options.path)) {
3776
+ optionPaths = [_resolveHome(options.path)];
3777
+ } else {
3778
+ optionPaths = [];
3779
+ for (const filepath of options.path) {
3780
+ optionPaths.push(_resolveHome(filepath));
3781
+ }
3782
+ }
3783
+ }
3784
+ let lastError;
3785
+ const parsedAll = {};
3786
+ for (const path2 of optionPaths) {
3787
+ try {
3788
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
3789
+ DotenvModule.populate(parsedAll, parsed, options);
3790
+ } catch (e) {
3791
+ if (debug) {
3792
+ _debug(`Failed to load ${path2} ${e.message}`);
3793
+ }
3794
+ lastError = e;
3795
+ }
3796
+ }
3797
+ let processEnv = process.env;
3798
+ if (options && options.processEnv != null) {
3799
+ processEnv = options.processEnv;
3800
+ }
3801
+ DotenvModule.populate(processEnv, parsedAll, options);
3802
+ if (debug || !quiet) {
3803
+ const keysCount = Object.keys(parsedAll).length;
3804
+ const shortPaths = [];
3805
+ for (const filePath of optionPaths) {
3806
+ try {
3807
+ const relative = path.relative(process.cwd(), filePath);
3808
+ shortPaths.push(relative);
3809
+ } catch (e) {
3810
+ if (debug) {
3811
+ _debug(`Failed to load ${filePath} ${e.message}`);
3812
+ }
3813
+ lastError = e;
3814
+ }
3815
+ }
3816
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
3817
+ }
3818
+ if (lastError) {
3819
+ return { parsed: parsedAll, error: lastError };
3820
+ } else {
3821
+ return { parsed: parsedAll };
3822
+ }
3823
+ }
3824
+ function config(options) {
3825
+ if (_dotenvKey(options).length === 0) {
3826
+ return DotenvModule.configDotenv(options);
3827
+ }
3828
+ const vaultPath = _vaultPath(options);
3829
+ if (!vaultPath) {
3830
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
3831
+ return DotenvModule.configDotenv(options);
3832
+ }
3833
+ return DotenvModule._configVault(options);
3834
+ }
3835
+ function decrypt(encrypted, keyStr) {
3836
+ const key = Buffer.from(keyStr.slice(-64), "hex");
3837
+ let ciphertext = Buffer.from(encrypted, "base64");
3838
+ const nonce = ciphertext.subarray(0, 12);
3839
+ const authTag = ciphertext.subarray(-16);
3840
+ ciphertext = ciphertext.subarray(12, -16);
3841
+ try {
3842
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
3843
+ aesgcm.setAuthTag(authTag);
3844
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
3845
+ } catch (error) {
3846
+ const isRange = error instanceof RangeError;
3847
+ const invalidKeyLength = error.message === "Invalid key length";
3848
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
3849
+ if (isRange || invalidKeyLength) {
3850
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
3851
+ err.code = "INVALID_DOTENV_KEY";
3852
+ throw err;
3853
+ } else if (decryptionFailed) {
3854
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
3855
+ err.code = "DECRYPTION_FAILED";
3856
+ throw err;
3857
+ } else {
3858
+ throw error;
3859
+ }
3860
+ }
3861
+ }
3862
+ function populate(processEnv, parsed, options = {}) {
3863
+ const debug = Boolean(options && options.debug);
3864
+ const override = Boolean(options && options.override);
3865
+ if (typeof parsed !== "object") {
3866
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
3867
+ err.code = "OBJECT_REQUIRED";
3868
+ throw err;
3869
+ }
3870
+ for (const key of Object.keys(parsed)) {
3871
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
3872
+ if (override === true) {
3873
+ processEnv[key] = parsed[key];
3874
+ }
3875
+ if (debug) {
3876
+ if (override === true) {
3877
+ _debug(`"${key}" is already defined and WAS overwritten`);
3878
+ } else {
3879
+ _debug(`"${key}" is already defined and was NOT overwritten`);
3880
+ }
3881
+ }
3882
+ } else {
3883
+ processEnv[key] = parsed[key];
3884
+ }
3885
+ }
3886
+ }
3887
+ const DotenvModule = {
3888
+ configDotenv,
3889
+ _configVault,
3890
+ _parseVault,
3891
+ config,
3892
+ decrypt,
3893
+ parse,
3894
+ populate
3895
+ };
3896
+ main.exports.configDotenv = DotenvModule.configDotenv;
3897
+ main.exports._configVault = DotenvModule._configVault;
3898
+ main.exports._parseVault = DotenvModule._parseVault;
3899
+ main.exports.config = DotenvModule.config;
3900
+ main.exports.decrypt = DotenvModule.decrypt;
3901
+ main.exports.parse = DotenvModule.parse;
3902
+ main.exports.populate = DotenvModule.populate;
3903
+ main.exports = DotenvModule;
3904
+ return main.exports;
3905
+ }
3906
+
3907
+ var mainExports = requireMain();
3908
+
3909
+ const LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
3910
+ function parseDotenv(text) {
3911
+ return mainExports.parse(text);
3912
+ }
3913
+ function formatDotenvValue(value) {
3914
+ if (/^[A-Za-z0-9_./:@+,-]*$/.test(value)) return value;
3915
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
3916
+ }
3917
+ function editDotenv(text, edits) {
3918
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
3919
+ let lines = text === "" ? [] : text.split(/\r?\n/);
3920
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
3921
+ for (const edit of edits) {
3922
+ const at = lines.map((l, i) => LINE.exec(l)?.[1] === edit.key ? i : -1).filter((i) => i >= 0);
3923
+ if (edit.value === null) {
3924
+ lines = lines.filter((_, i) => !at.includes(i));
3925
+ continue;
3926
+ }
3927
+ const rendered = `${edit.key}=${formatDotenvValue(edit.value)}`;
3928
+ if (at.length) {
3929
+ lines[at[0]] = rendered;
3930
+ lines = lines.filter((_, i) => !at.slice(1).includes(i));
3931
+ } else {
3932
+ lines.push(rendered);
3933
+ }
3934
+ }
3935
+ const out = lines.length ? lines.join(eol) + eol : "";
3936
+ const before = mainExports.parse(text);
3937
+ const after = mainExports.parse(out);
3938
+ for (const edit of edits) {
3939
+ if ((after[edit.key] ?? null) !== edit.value) throw new ModelConfigError("unsafe-edit", `.env edit did not produce ${edit.key} as requested`);
3940
+ delete before[edit.key];
3941
+ delete after[edit.key];
3942
+ }
3943
+ if (JSON.stringify(Object.entries(before).sort()) !== JSON.stringify(Object.entries(after).sort())) {
3944
+ throw new ModelConfigError("unsafe-edit", ".env edit would change other variables");
3945
+ }
3946
+ return out;
3947
+ }
3948
+
3949
+ const SETTINGS = "settings";
3950
+ const ENV = "env";
3951
+ const BASE_URL = "GOOGLE_GEMINI_BASE_URL";
3952
+ const API_KEY = "GEMINI_API_KEY";
3953
+ function geminiDir(ctx) {
3954
+ return join(ctx.env.GEMINI_CLI_HOME?.trim() || ctx.home, ".gemini");
3955
+ }
3956
+ const str$1 = (v) => typeof v === "string" && v.trim() ? v : null;
3957
+ function currentOf(settings, env, ctx) {
3958
+ const literal = str$1(env[API_KEY]);
3959
+ const apiKey = literal ? { mode: "literal", masked: maskSecret(literal) } : ctx.env[API_KEY] ? { mode: "env", envName: API_KEY, envPresent: true } : { mode: "none" };
3960
+ return { baseUrl: str$1(env[BASE_URL]), apiKey, model: str$1(getPath$1(settings, ["model", "name"])) };
3961
+ }
3962
+ function warningsOf(settings, current) {
3963
+ const out = [...baseUrlWarnings(current.baseUrl, "gemini")];
3964
+ if (current.baseUrl || current.apiKey?.mode === "literal") {
3965
+ 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." });
3966
+ }
3967
+ const selected = str$1(getPath$1(settings, ["security", "auth", "selectedType"]));
3968
+ if (current.baseUrl && selected && selected !== "gateway") {
3969
+ out.push({ code: "auth-type-pinned", message: `security.auth.selectedType is "${selected}"; Gemini only uses GOOGLE_GEMINI_BASE_URL with the gateway auth type.` });
3970
+ }
3971
+ if (current.baseUrl && !/^https:/.test(current.baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(current.baseUrl)) {
3972
+ out.push({ code: "gemini-https", message: "Gemini requires an https base URL (localhost excepted)." });
3973
+ }
3974
+ return out;
3975
+ }
3976
+ const geminiAdapter = {
3977
+ id: "gemini",
3978
+ binary: "gemini",
3979
+ files: (ctx) => [{ role: SETTINGS, path: join(geminiDir(ctx), "settings.json") }, { role: ENV, path: join(geminiDir(ctx), ".env") }],
3980
+ view(files, ctx) {
3981
+ const settings = parseJsonObject$1(files[SETTINGS].content, "settings.json");
3982
+ const current = currentOf(settings, parseDotenv(files[ENV].content), ctx);
3983
+ return { current, pickerModels: uniq([current.model]), warnings: warningsOf(settings, current) };
3984
+ },
3985
+ plan(files, raw, ctx) {
3986
+ const p = raw;
3987
+ const baseUrl = normalizeBaseUrl(p.baseUrl);
3988
+ const apiKey = normalizeSecret(p.apiKey, ["keep", "clear", "literal"]);
3989
+ const model = normalizeModelId(p.model);
3990
+ const settingsText = files[SETTINGS].content;
3991
+ const before = parseJsonObject$1(settingsText, "settings.json");
3992
+ const settings = structuredClone(before);
3993
+ const changedKeys = [];
3994
+ let settingsOut;
3995
+ if (model !== void 0 && (str$1(getPath$1(before, ["model", "name"])) ?? null) !== model) {
3996
+ const hadModel = settings.model !== void 0;
3997
+ const modelObj = childObject(settings, "model", "settings");
3998
+ setOrDelete(modelObj, "name", model);
3999
+ if (!hadModel && Object.keys(modelObj).length === 0) delete settings.model;
4000
+ settingsOut = stringifyLike(settingsText, settings);
4001
+ changedKeys.push("settings.model.name");
4002
+ }
4003
+ const envText = files[ENV].content;
4004
+ const env = parseDotenv(envText);
4005
+ const edits = [];
4006
+ if (baseUrl !== void 0 && (env[BASE_URL] ?? null) !== baseUrl) edits.push({ key: BASE_URL, value: baseUrl });
4007
+ if (apiKey.mode === "literal" && env[API_KEY] !== apiKey.value) edits.push({ key: API_KEY, value: apiKey.value });
4008
+ if (apiKey.mode === "clear" && env[API_KEY] !== void 0) edits.push({ key: API_KEY, value: null });
4009
+ const envOut = edits.length ? editDotenv(envText, edits) : void 0;
4010
+ changedKeys.push(...edits.map((e) => `.env.${e.key}`));
4011
+ const afterEnv = envOut === void 0 ? env : parseDotenv(envOut);
4012
+ const current = currentOf(settings, afterEnv, ctx);
4013
+ return {
4014
+ contents: { [SETTINGS]: settingsOut, [ENV]: envOut },
4015
+ warnings: warningsOf(settings, current),
4016
+ changedKeys,
4017
+ secrets: apiKey.mode === "literal" ? [apiKey.value] : []
4018
+ };
4019
+ },
4020
+ secretsIn(role, content) {
4021
+ try {
4022
+ return role === ENV ? collectSecretValues(parseDotenv(content)) : collectSecretValues(parseJsonObject$1(content, "settings.json"));
4023
+ } catch {
4024
+ return /* @__PURE__ */ new Set();
4025
+ }
4026
+ }
4027
+ };
4028
+
4029
+ const MODEL_CONFIG_CAPABILITY_VERSION = 1;
4030
+ const HARNESS_IDS = ["claude", "codex", "gemini", "pi"];
4031
+
4032
+ const ADAPTERS = { claude: claudeAdapter, codex: codexAdapter, gemini: geminiAdapter, pi: piAdapter };
4033
+ function harnessOf(value) {
4034
+ if (typeof value !== "string" || !HARNESS_IDS.includes(value)) {
4035
+ throw new ModelConfigError("invalid-harness", `harness must be one of ${HARNESS_IDS.join(", ")}`);
4036
+ }
4037
+ return value;
4038
+ }
4039
+ class ModelConfigService {
4040
+ constructor(opts) {
4041
+ this.opts = opts;
4042
+ this.backups = new BackupStore(join(opts.happyHomeDir, "model-config-backups"));
4043
+ this.auditPath = join(opts.happyHomeDir, "model-config-audit.jsonl");
4044
+ }
4045
+ backups;
4046
+ auditPath;
4047
+ chain = Promise.resolve();
4048
+ get ctx() {
4049
+ return { home: this.opts.home, env: this.opts.env };
4050
+ }
4051
+ serialize(fn) {
4052
+ const next = this.chain.then(fn, fn);
4053
+ this.chain = next.catch(() => {
4054
+ });
4055
+ return next;
4056
+ }
4057
+ async loadFiles(adapter) {
4058
+ const files = {};
4059
+ for (const { role, path } of adapter.files(this.ctx)) files[role] = await readConfigFile(path);
4060
+ const baseHash = sha256(Object.entries(files).map(([role, f]) => `${role}\0${f.exists ? f.hash : "-"}`).join("\n"));
4061
+ return { files, baseHash };
4062
+ }
4063
+ async readOne(harness, providerId) {
4064
+ const adapter = ADAPTERS[harness];
4065
+ const installed = harness === "claude" || (this.opts.isInstalled?.(adapter.binary) ?? true);
4066
+ const backups = await this.backups.list(harness);
4067
+ let loaded;
4068
+ try {
4069
+ loaded = await this.loadFiles(adapter);
4070
+ } catch (error) {
4071
+ const e = toError(error);
4072
+ return {
4073
+ harness,
4074
+ installed,
4075
+ baseHash: "",
4076
+ current: {},
4077
+ pickerModels: [],
4078
+ backups,
4079
+ warnings: [],
4080
+ files: adapter.files(this.ctx).map((f) => ({ role: f.role, path: f.path, exists: false, error: e }))
4081
+ };
4082
+ }
4083
+ const files = Object.entries(loaded.files).map(([role, f]) => ({ role, path: f.path, exists: f.exists }));
4084
+ try {
4085
+ const view = adapter.view(loaded.files, this.ctx, { providerId });
4086
+ return { harness, installed, files, baseHash: loaded.baseHash, backups, ...view };
4087
+ } catch (error) {
4088
+ const e = toError(error);
4089
+ return { harness, installed, baseHash: loaded.baseHash, current: {}, pickerModels: [], backups, warnings: [], files: files.map((f) => ({ ...f, error: e })) };
4090
+ }
4091
+ }
4092
+ async read(params = {}) {
4093
+ const list = params.harness === void 0 ? [...HARNESS_IDS] : [harnessOf(params.harness)];
4094
+ const providerId = typeof params.providerId === "string" && params.providerId ? params.providerId : void 0;
4095
+ const harnesses = await Promise.all(list.map((h) => this.readOne(h, providerId)));
4096
+ return { version: MODEL_CONFIG_CAPABILITY_VERSION, harnesses };
4097
+ }
4098
+ diffs(adapter, files, next, extraSecrets) {
4099
+ const out = [];
4100
+ for (const [role, file] of Object.entries(files)) {
4101
+ const target = next[role];
4102
+ if (target === void 0) continue;
4103
+ const newText = target ?? "";
4104
+ if (target !== null && file.exists && newText === file.content) continue;
4105
+ if (target === null && !file.exists) continue;
4106
+ const secrets = [...adapter.secretsIn(role, file.content), ...target ? adapter.secretsIn(role, target) : [], ...extraSecrets];
4107
+ const raw = unifiedDiff(file.content, newText, file.path);
4108
+ out.push({ path: file.path, diff: redactText(raw, secrets), created: !file.exists && target !== null, deleted: target === null && file.exists });
4109
+ }
4110
+ return out;
4111
+ }
4112
+ async write(harness, action, files, next, keys, apiKeyMode) {
4113
+ const touched = Object.entries(next).filter(([, v]) => v !== void 0);
4114
+ const snapshot = touched.map(([role]) => ({ path: files[role].path, content: files[role].exists ? files[role].content : null, mode: files[role].mode }));
4115
+ const backup = await this.backups.create(harness, action === "apply" ? "before-apply" : "before-restore", snapshot, this.opts.now?.() ?? Date.now());
4116
+ for (const [role, target] of touched) {
4117
+ const file = files[role];
4118
+ if (target.content === null) await promises.rm(file.path, { force: true });
4119
+ else await atomicWriteFile(file.path, target.content, file.mode ?? target.mode);
4120
+ }
4121
+ await this.audit({ at: this.opts.now?.() ?? Date.now(), action, harness, files: touched.map(([role]) => files[role].path), keys, apiKeyMode, backupId: backup.id });
4122
+ this.opts.onChanged?.(harness);
4123
+ return backup;
4124
+ }
4125
+ async audit(record) {
4126
+ try {
4127
+ await promises.mkdir(this.opts.happyHomeDir, { recursive: true });
4128
+ await promises.appendFile(this.auditPath, `${JSON.stringify(record)}
4129
+ `, { encoding: "utf8", mode: 384 });
4130
+ } catch {
4131
+ }
4132
+ }
4133
+ apply(params) {
4134
+ const run = async () => {
4135
+ const patch = params.patch;
4136
+ if (!patch || typeof patch !== "object") throw new ModelConfigError("invalid-input", "patch is required");
4137
+ const harness = harnessOf(patch.harness);
4138
+ const adapter = ADAPTERS[harness];
4139
+ const { files, baseHash } = await this.loadFiles(adapter);
4140
+ const dryRun = params.dryRun !== false;
4141
+ if (!dryRun && params.baseHash !== baseHash) {
4142
+ throw new ModelConfigError("conflict", "The config files changed since the preview; review the new diff and apply again");
4143
+ }
4144
+ const plan = adapter.plan(files, patch, this.ctx);
4145
+ const diffs = this.diffs(adapter, files, plan.contents, plan.secrets);
4146
+ const changed = diffs.length > 0;
4147
+ if (dryRun || !changed) {
4148
+ return { harness, dryRun, changed, baseHash, files: diffs, warnings: plan.warnings };
4149
+ }
4150
+ const next = Object.fromEntries(Object.entries(plan.contents).map(([role, content]) => [role, content === void 0 ? void 0 : { content, mode: null }]));
4151
+ const apiKeyMode = patch.apiKey?.mode;
4152
+ const backup = await this.write(harness, "apply", files, next, plan.changedKeys, typeof apiKeyMode === "string" ? apiKeyMode : void 0);
4153
+ const config = await this.readOne(harness, patch.providerId);
4154
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: plan.warnings, backup, config };
4155
+ };
4156
+ return params.dryRun === false ? this.serialize(run) : run();
4157
+ }
4158
+ restore(params) {
4159
+ const run = async () => {
4160
+ const harness = harnessOf(params.harness);
4161
+ const adapter = ADAPTERS[harness];
4162
+ if (typeof params.backupId !== "string") throw new ModelConfigError("invalid-input", "backupId is required");
4163
+ const saved = await this.backups.read(harness, params.backupId);
4164
+ const { files, baseHash } = await this.loadFiles(adapter);
4165
+ const dryRun = params.dryRun !== false;
4166
+ if (!dryRun && params.baseHash !== baseHash) {
4167
+ throw new ModelConfigError("conflict", "The config files changed since the preview; review the new diff and restore again");
4168
+ }
4169
+ const allowed = new Map(Object.entries(files).map(([role, f]) => [f.path, role]));
4170
+ const target = {};
4171
+ for (const file of saved) {
4172
+ const role = allowed.get(file.path);
4173
+ if (!role) throw new ModelConfigError("backup-mismatch", "Backup does not belong to the current config location");
4174
+ target[role] = { content: file.content, mode: file.mode };
4175
+ }
4176
+ const diffs = this.diffs(adapter, files, Object.fromEntries(Object.entries(target).map(([r, v]) => [r, v?.content])), []);
4177
+ const changed = diffs.length > 0;
4178
+ if (dryRun || !changed) return { harness, dryRun, changed, baseHash, files: diffs, warnings: [] };
4179
+ const keys = ["*restore*"];
4180
+ const backup = await this.write(harness, "restore", files, target, keys);
4181
+ const config = await this.readOne(harness);
4182
+ return { harness, dryRun, changed, baseHash: config.baseHash, files: diffs, warnings: [], backup, config };
4183
+ };
4184
+ return params.dryRun === false ? this.serialize(run) : run();
4185
+ }
4186
+ }
4187
+ function toError(error) {
4188
+ if (error instanceof ModelConfigError) return { code: error.code, message: error.message };
4189
+ return { code: "read-failed", message: error instanceof Error ? error.message : String(error) };
4190
+ }
4191
+
2066
4192
  function startWebPanelsSync(deps) {
2067
4193
  let lastMtime;
2068
4194
  let lastProblems = "";
@@ -2392,26 +4518,45 @@ function createUpdateController(deps) {
2392
4518
  let blocked = false;
2393
4519
  let handoverHold;
2394
4520
  let lastPublished = "";
4521
+ let autoUpdateEnabled;
4522
+ let lastInstall = (() => {
4523
+ try {
4524
+ return deps.lastInstall?.read() ?? null;
4525
+ } catch {
4526
+ return null;
4527
+ }
4528
+ })();
2395
4529
  const now = deps.now ?? Date.now;
4530
+ function snapshot() {
4531
+ return {
4532
+ ...policy,
4533
+ retrySupported: !blocked,
4534
+ manualUpdateSupported: !blocked,
4535
+ handoverHold,
4536
+ autoUpdate: outcome,
4537
+ ...autoUpdateEnabled === void 0 ? {} : { autoUpdateEnabled },
4538
+ ...lastInstall ? { lastInstall } : {}
4539
+ };
4540
+ }
2396
4541
  function validManualTarget(next, version) {
2397
4542
  return version === next.recommendedVersion && Number.isFinite(next.checkedAt) && now() - next.checkedAt <= 65 * 6e4 && next.checkedAt <= now() + 6e4 && compareExactVersions(next.currentVersion, version) === -1 && (!next.minimumVersion || [0, 1].includes(compareExactVersions(version, next.minimumVersion) ?? -1));
2398
4543
  }
2399
4544
  function publish(state, version, detail) {
2400
4545
  if (!policy) return;
2401
- const fingerprint = JSON.stringify([policy.checkedAt, state, version, detail, manualVersion]);
4546
+ const fingerprint = JSON.stringify([policy.checkedAt, state, version, detail, manualVersion, autoUpdateEnabled]);
2402
4547
  if (fingerprint === lastPublished) return;
2403
4548
  lastPublished = fingerprint;
2404
4549
  outcome = { state, version, detail, at: now(), ...manualVersion ? { source: "manual" } : {} };
2405
- deps.publish({ ...policy, retrySupported: !blocked, manualUpdateSupported: !blocked, handoverHold, autoUpdate: outcome });
4550
+ deps.publish(snapshot());
2406
4551
  }
2407
4552
  async function evaluate() {
2408
4553
  if (!policy || running) return;
2409
4554
  const target = manualVersion ?? policy.autoUpdateVersion ?? null;
2410
4555
  if (outcome?.version === target && ["failed", "installed", "manual_required"].includes(outcome.state)) {
2411
- const fingerprint = JSON.stringify([policy.checkedAt, outcome.state, outcome.version, outcome.detail, manualVersion]);
4556
+ const fingerprint = JSON.stringify([policy.checkedAt, outcome.state, outcome.version, outcome.detail, manualVersion, autoUpdateEnabled]);
2412
4557
  if (fingerprint !== lastPublished) {
2413
4558
  lastPublished = fingerprint;
2414
- deps.publish({ ...policy, retrySupported: !blocked, manualUpdateSupported: !blocked, handoverHold, autoUpdate: outcome });
4559
+ deps.publish(snapshot());
2415
4560
  }
2416
4561
  return;
2417
4562
  }
@@ -2419,9 +4564,12 @@ function createUpdateController(deps) {
2419
4564
  publish("policy_stale", target);
2420
4565
  return;
2421
4566
  }
2422
- if (!manualVersion && !await deps.enabled()) {
2423
- publish("disabled", target);
2424
- return;
4567
+ if (!manualVersion) {
4568
+ autoUpdateEnabled = await deps.enabled();
4569
+ if (!autoUpdateEnabled) {
4570
+ publish("disabled", target);
4571
+ return;
4572
+ }
2425
4573
  }
2426
4574
  if (running) return;
2427
4575
  if (now() - policy.checkedAt > 65 * 6e4) {
@@ -2451,6 +4599,13 @@ function createUpdateController(deps) {
2451
4599
  return;
2452
4600
  }
2453
4601
  blocked = code === "blocked";
4602
+ if (code === 0) {
4603
+ lastInstall = { from: policy.currentVersion, to: target, at: now(), source: manualVersion ? "manual" : "auto" };
4604
+ try {
4605
+ deps.lastInstall?.write(lastInstall);
4606
+ } catch {
4607
+ }
4608
+ }
2454
4609
  publish(
2455
4610
  blocked ? "manual_required" : code === 0 ? "installed" : "failed",
2456
4611
  target,
@@ -2552,7 +4707,224 @@ function createUpdateController(deps) {
2552
4707
  handoverHold = { reason, at: now() };
2553
4708
  publish("failed", manualVersion ?? policy?.autoUpdateVersion ?? null, "handover_preflight_failed");
2554
4709
  }
2555
- return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running };
4710
+ return { refresh, retry, request, tick, withHandover, holdHandover, isRunning: () => running, currentTarget: () => policy?.autoUpdateVersion ?? null };
4711
+ }
4712
+
4713
+ function parseLastInstall(raw) {
4714
+ if (!raw || typeof raw !== "object") return null;
4715
+ const { from, to, at, source } = raw;
4716
+ if (typeof from !== "string" || typeof to !== "string" || !parseExactVersion(from) || !parseExactVersion(to)) return null;
4717
+ if (typeof at !== "number" || !Number.isFinite(at) || source !== "auto" && source !== "manual") return null;
4718
+ return { from, to, at, source };
4719
+ }
4720
+ function lastInstallStore(homeDir) {
4721
+ const file = join(homeDir, "cli-update-last.json");
4722
+ return {
4723
+ read() {
4724
+ try {
4725
+ return parseLastInstall(JSON.parse(readFileSync(file, "utf8")));
4726
+ } catch {
4727
+ return null;
4728
+ }
4729
+ },
4730
+ write(record) {
4731
+ const tmp = `${file}.${process.pid}.tmp`;
4732
+ writeFileSync(tmp, JSON.stringify(record));
4733
+ renameSync(tmp, file);
4734
+ }
4735
+ };
4736
+ }
4737
+
4738
+ const ANNOUNCE_FIRST_DELAY_MS = 9e4;
4739
+ const ANNOUNCE_JITTER_MS = 6e4;
4740
+ const ANNOUNCE_FOLLOW_UP_MS = 5 * 6e4;
4741
+ function announcedVersion(payload) {
4742
+ if (!payload || typeof payload !== "object") return null;
4743
+ const raw = payload.autoUpdateVersion;
4744
+ if (typeof raw !== "string" || raw.length > 64) return null;
4745
+ return parseExactVersion(raw)?.exact ?? null;
4746
+ }
4747
+ function createPolicyAnnouncementHandler(deps) {
4748
+ const random = deps.random ?? Math.random;
4749
+ const setTimer = deps.setTimer ?? ((fn, ms) => {
4750
+ const t = setTimeout(fn, ms);
4751
+ t.unref?.();
4752
+ return t;
4753
+ });
4754
+ const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
4755
+ let timer = null;
4756
+ let pending = null;
4757
+ let stopped = false;
4758
+ function schedule(version, ms, followUp) {
4759
+ if (timer !== null) clearTimer(timer);
4760
+ pending = version;
4761
+ timer = setTimer(() => {
4762
+ timer = null;
4763
+ void deps.refresh().catch(() => void 0).finally(() => {
4764
+ if (stopped || pending !== version) return;
4765
+ if (deps.currentTarget() === version || !followUp) {
4766
+ pending = null;
4767
+ return;
4768
+ }
4769
+ schedule(version, ANNOUNCE_FOLLOW_UP_MS, false);
4770
+ });
4771
+ }, ms);
4772
+ }
4773
+ return {
4774
+ /** Socket handler. Returns the scheduled delay (ms) or null when ignored — for logs and tests. */
4775
+ onAnnouncement(payload) {
4776
+ if (stopped) return null;
4777
+ const version = announcedVersion(payload);
4778
+ if (!version || version === deps.currentTarget() || version === pending) return null;
4779
+ const delay = ANNOUNCE_FIRST_DELAY_MS + Math.floor(random() * ANNOUNCE_JITTER_MS);
4780
+ schedule(version, delay, true);
4781
+ return delay;
4782
+ },
4783
+ stop() {
4784
+ stopped = true;
4785
+ if (timer !== null) clearTimer(timer);
4786
+ timer = null;
4787
+ }
4788
+ };
4789
+ }
4790
+
4791
+ const HARNESS_INSTALL_CATALOG = Object.freeze({
4792
+ claude: Object.freeze({ packages: [{ name: "@anthropic-ai/claude-code", spec: "latest" }], commands: ["claude"], minNode: "22.0.0", scripts: true }),
4793
+ codex: Object.freeze({ packages: [{ name: "@openai/codex", spec: "latest" }], commands: ["codex"], minNode: "16.0.0", scripts: false }),
4794
+ gemini: Object.freeze({ packages: [{ name: "@google/gemini-cli", spec: "latest" }], commands: ["gemini"], minNode: "20.0.0", scripts: false }),
4795
+ pi: Object.freeze({
4796
+ packages: [{ name: "@earendil-works/pi-coding-agent", spec: "latest" }, { name: "pi-acp", spec: "0.0.33" }],
4797
+ commands: ["pi", "pi-acp"],
4798
+ minNode: "22.19.0",
4799
+ scripts: false
4800
+ })
4801
+ });
4802
+ function harnessInstallArgs(id, prefix) {
4803
+ const entry = HARNESS_INSTALL_CATALOG[id];
4804
+ if (!entry) throw new Error("Unknown harness");
4805
+ const args = ["i", "-g", `--prefix=${prefix}`, "--no-fund", "--no-audit", ...entry.scripts ? [] : ["--ignore-scripts"], ...entry.packages.map((p) => `${p.name}@${p.spec}`)];
4806
+ if (args.some((arg) => !NPM_SAFE_ARG.test(arg))) throw new Error("Unsafe npm argument");
4807
+ return args;
4808
+ }
4809
+ function parseNode(version) {
4810
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
4811
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
4812
+ }
4813
+ function nodeSatisfies(current, minimum) {
4814
+ const a = parseNode(current);
4815
+ const b = parseNode(minimum);
4816
+ if (!a || !b) return false;
4817
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
4818
+ return true;
4819
+ }
4820
+
4821
+ async function defaultCanWrite(path) {
4822
+ try {
4823
+ await access(path, constants.W_OK);
4824
+ return true;
4825
+ } catch {
4826
+ return false;
4827
+ }
4828
+ }
4829
+ async function defaultIsPlainDirectory(path) {
4830
+ try {
4831
+ const s = await lstat(path);
4832
+ return s.isDirectory() && !s.isSymbolicLink();
4833
+ } catch {
4834
+ return false;
4835
+ }
4836
+ }
4837
+ function redactNpmText(text) {
4838
+ 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, "~");
4839
+ }
4840
+ function summarizeNpmFailure(result) {
4841
+ const tail = `${result.stderr ?? ""}
4842
+ ${result.stdout ?? ""}`.trim().split("\n").filter((line) => /npm (error|ERR!)|EACCES|ENOTFOUND|ETARGET|E404|engine/i.test(line)).slice(-3).join(" | ");
4843
+ const code = result.code === null ? "npm_timeout" : `npm_exit_${result.code}`;
4844
+ const safe = redactNpmText(tail).slice(0, 300);
4845
+ return safe ? `${code}: ${safe}` : code;
4846
+ }
4847
+ function createHarnessInstaller(deps) {
4848
+ const now = deps.now ?? Date.now;
4849
+ const canWrite = deps.canWrite ?? defaultCanWrite;
4850
+ const isPlainDirectory = deps.isPlainDirectory ?? defaultIsPlainDirectory;
4851
+ let running = null;
4852
+ let blocked = false;
4853
+ const nodeVersion = deps.nodeVersion ?? process.versions.node;
4854
+ async function installPrefix() {
4855
+ const prefix = globalPrefixForPackage(deps.runningPackageDir);
4856
+ if (!prefix || !await isPlainDirectory(deps.runningPackageDir)) return { error: "install_location_unverified" };
4857
+ for (const path of [dirname(deps.runningPackageDir), join(prefix, "bin")]) {
4858
+ if (!await canWrite(path)) return { error: "install_location_not_writable" };
4859
+ }
4860
+ return { prefix };
4861
+ }
4862
+ async function run(harness, prefix, startedAt) {
4863
+ const publish = (state, detail) => deps.publish({ harness, state, ...detail ? { detail } : {}, startedAt, at: now() });
4864
+ try {
4865
+ const args = harnessInstallArgs(harness, prefix);
4866
+ deps.log(`[HARNESS] installing ${harness}: npm ${args.join(" ")}`);
4867
+ const result = await deps.npm(args);
4868
+ if (result.terminationConfirmed === false) {
4869
+ blocked = true;
4870
+ deps.log(`[HARNESS] ${harness} install timed out and npm could not be confirmed stopped; holding the npm tree until the daemon restarts`);
4871
+ publish("failed", "installer_termination_unconfirmed");
4872
+ return;
4873
+ }
4874
+ if (result.code !== 0) {
4875
+ const detail = summarizeNpmFailure(result);
4876
+ deps.log(`[HARNESS] ${harness} install failed: ${detail}`);
4877
+ publish("failed", detail);
4878
+ return;
4879
+ }
4880
+ const missing = HARNESS_INSTALL_CATALOG[harness].commands.filter((command) => !deps.commandOnPath(command));
4881
+ if (missing.length > 0) {
4882
+ const detail = `not_on_path: ${missing.join(", ")}`;
4883
+ deps.log(`[HARNESS] ${harness} installed into ${prefix} but ${detail}`);
4884
+ publish("failed", detail);
4885
+ return;
4886
+ }
4887
+ await deps.afterInstall().catch((error) => deps.log(`[HARNESS] refresh after ${harness} install failed: ${String(error)}`));
4888
+ deps.log(`[HARNESS] ${harness} installed`);
4889
+ publish("installed");
4890
+ } catch (error) {
4891
+ deps.log(`[HARNESS] ${harness} install error: ${String(error)}`);
4892
+ publish("failed", "install_error");
4893
+ } finally {
4894
+ if (!blocked) running = null;
4895
+ }
4896
+ }
4897
+ return {
4898
+ /** True while npm may be writing the prefix — including after an unconfirmed kill. */
4899
+ isRunning: () => running !== null || blocked,
4900
+ async request(params) {
4901
+ const harness = params && typeof params === "object" ? params.harness : void 0;
4902
+ if (!isHarnessInstallId(harness)) {
4903
+ deps.log(`[HARNESS] refused install request for an unknown harness`);
4904
+ return { error: "unknown_harness" };
4905
+ }
4906
+ if (blocked) return { error: "installer_blocked" };
4907
+ if (running) return { error: "install_in_progress" };
4908
+ if (deps.cliUpdateBusy()) return { error: "cli_update_in_progress" };
4909
+ const minNode = HARNESS_INSTALL_CATALOG[harness].minNode;
4910
+ if (!nodeSatisfies(nodeVersion, minNode)) {
4911
+ deps.log(`[HARNESS] ${harness} install refused: needs Node ${minNode}+, daemon runs ${nodeVersion}`);
4912
+ return { error: "node_too_old", required: minNode, current: nodeVersion };
4913
+ }
4914
+ running = harness;
4915
+ const location = await installPrefix();
4916
+ if ("error" in location) {
4917
+ running = null;
4918
+ deps.log(`[HARNESS] ${harness} install refused: ${location.error}`);
4919
+ return location;
4920
+ }
4921
+ const startedAt = now();
4922
+ deps.log(`[HARNESS] owner requested ${harness} install`);
4923
+ deps.publish({ harness, state: "installing", startedAt, at: startedAt });
4924
+ void run(harness, location.prefix, startedAt);
4925
+ return { accepted: true, harness };
4926
+ }
4927
+ };
2556
4928
  }
2557
4929
 
2558
4930
  function buildPresenceBatch(live, previous) {
@@ -3505,12 +5877,12 @@ function createMirrorManager(deps) {
3505
5877
  await teardownBinding(replaces, "superseded by a fresh conversation");
3506
5878
  }
3507
5879
  const metadata = {
3508
- path: event.cwd ?? os.homedir(),
3509
- host: os.hostname(),
5880
+ path: event.cwd ?? os$1.homedir(),
5881
+ host: os$1.hostname(),
3510
5882
  version: packageJson.version,
3511
- os: os.platform(),
5883
+ os: os$1.platform(),
3512
5884
  machineId: deps.machineId,
3513
- homeDir: os.homedir(),
5885
+ homeDir: os$1.homedir(),
3514
5886
  happyHomeDir: configuration.happyHomeDir,
3515
5887
  happyLibDir: projectPath(),
3516
5888
  happyToolsDir: resolve(projectPath(), "tools", "unpacked"),
@@ -3772,6 +6144,57 @@ function withDaemonHeartbeat(state, lastHeartbeat) {
3772
6144
  return { ...state, lastHeartbeat };
3773
6145
  }
3774
6146
 
6147
+ const TAIL_BYTES = 64 * 1024;
6148
+ const MAX_REASON = 300;
6149
+ function extractStartupExitReason(logText) {
6150
+ const lines = logText.split("\n");
6151
+ for (let i = lines.length - 1; i >= 0; i--) {
6152
+ const exit = /\[EXIT\] Exiting with code -?\d+: (.+)$/.exec(lines[i]);
6153
+ if (exit) return clamp(exit[1]);
6154
+ }
6155
+ for (let i = lines.length - 1; i >= 0; i--) {
6156
+ if (!/\[ERROR\]|\[WARN\]/.test(lines[i])) continue;
6157
+ const detail = lines.slice(i, i + 8).join("\n");
6158
+ const message = /message: '([^'\n]+)'/.exec(detail)?.[1];
6159
+ const code = /code: '([A-Z0-9_]+)'/.exec(detail)?.[1];
6160
+ const head = lines[i].replace(/^\[[\d:.]+\]\s*/, "").replace(/\s*\{\s*$/, "").trim();
6161
+ return clamp([head, message, code].filter(Boolean).join(" "));
6162
+ }
6163
+ return void 0;
6164
+ }
6165
+ function describeStartupExit(exit, timeoutMs) {
6166
+ if (exit.timedOut) {
6167
+ const tail = exit.exited ? "and was stopped" : "and could not be confirmed stopped";
6168
+ return `Agent process did not report its session within ${Math.round(timeoutMs / 1e3)}s ${tail}${exit.reason ? `: ${exit.reason}` : ""}`;
6169
+ }
6170
+ const how = exit.signal ? `signal ${exit.signal}` : `code ${exit.code ?? "unknown"}`;
6171
+ return `Agent process exited during startup (${how}): ${exit.reason ?? "no reason found in its log"}`;
6172
+ }
6173
+ function readStartupExitReason(logsDir, pid) {
6174
+ try {
6175
+ const suffix = `-pid-${pid}.log`;
6176
+ const file = readdirSync(logsDir).filter((name) => name.endsWith(suffix)).sort().pop();
6177
+ if (!file) return void 0;
6178
+ const path = join(logsDir, file);
6179
+ const size = statSync(path).size;
6180
+ const length = Math.min(size, TAIL_BYTES);
6181
+ const buffer = Buffer.alloc(length);
6182
+ const fd = openSync(path, "r");
6183
+ try {
6184
+ readSync(fd, buffer, 0, length, size - length);
6185
+ } finally {
6186
+ closeSync(fd);
6187
+ }
6188
+ return extractStartupExitReason(buffer.toString("utf8"));
6189
+ } catch {
6190
+ return void 0;
6191
+ }
6192
+ }
6193
+ function clamp(value) {
6194
+ const line = value.replace(/\s+/g, " ").trim();
6195
+ return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}\u2026` : line;
6196
+ }
6197
+
3775
6198
  function recoverableSessionPid(metadata, liveHappyPids) {
3776
6199
  const pid = metadata?.hostPid;
3777
6200
  return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && liveHappyPids.has(pid) ? pid : null;
@@ -3813,7 +6236,10 @@ function mergeRestoreMetadata(stale, reported) {
3813
6236
  }
3814
6237
 
3815
6238
  function teamInitialPrompt(goal, root, directory) {
3816
- 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.";
6239
+ 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.
6240
+
6241
+ ${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.
6242
+ ${TEAM_MEMBER_RULES}`;
3817
6243
  return `${TEAM_SKILL}
3818
6244
 
3819
6245
  ## Your role
@@ -3827,47 +6253,30 @@ Delegate from this working directory unless a different repository was explicitl
3827
6253
  ${goal}`;
3828
6254
  }
3829
6255
 
3830
- function receiptPath(home, operationId) {
3831
- if (!/^[a-zA-Z0-9_-]{1,128}$/.test(operationId)) throw new Error("Invalid team operation id");
3832
- return join(home, "teams", "effects", `${operationId}.json`);
3833
- }
3834
- function readReceipt(home, id) {
3835
- try {
3836
- const value = JSON.parse(readFileSync(receiptPath(home, id), "utf8"));
3837
- if (value.operationId !== id || typeof value.claimId !== "string" || !["prepared", "spawning", "spawned", "delivered", "completed"].includes(value.phase)) throw new Error("Invalid team effect receipt");
3838
- return value;
3839
- } catch (error) {
3840
- if (error.code === "ENOENT") return null;
3841
- throw error;
3842
- }
6256
+ const exec = promisify(execFile);
6257
+ const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
6258
+ const gitRaw = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 64 * 1024 * 1024 })).stdout;
6259
+ function expandHome$1(path) {
6260
+ if (path === "~") return homedir();
6261
+ if (path.startsWith("~/") || process.platform === "win32" && path.startsWith("~\\")) return join(homedir(), path.slice(2));
6262
+ return path;
3843
6263
  }
3844
- function writeReceipt$1(home, receipt) {
3845
- ensurePrivateDirectorySync(join(home, "teams", "effects"));
3846
- const target = receiptPath(home, receipt.operationId);
3847
- const tmp = `${target}.${process.pid}.tmp`;
3848
- writePrivateFileSync(tmp, JSON.stringify(receipt));
3849
- const file = openSync(tmp, "r");
3850
- try {
3851
- fsyncSync(file);
3852
- } finally {
3853
- closeSync(file);
3854
- }
3855
- renameSync(tmp, target);
3856
- if (process.platform !== "win32") {
3857
- const directory = openSync(join(home, "teams", "effects"), "r");
3858
- try {
3859
- fsyncSync(directory);
3860
- } finally {
3861
- closeSync(directory);
3862
- }
6264
+ async function resolveTeamRepository(home, repository, sourceOf) {
6265
+ const worktrees = resolve(home, "teams", "worktrees");
6266
+ let candidate = expandHome$1(repository);
6267
+ for (let hop = 0; hop < 8; hop++) {
6268
+ if (!isAbsolute(candidate)) break;
6269
+ const teamWorktree = resolve(dirname(candidate)) === worktrees;
6270
+ const top = await git(candidate, ["rev-parse", "--show-toplevel"]).catch(() => null);
6271
+ if (top !== null && (!teamWorktree || resolve(top) === resolve(candidate))) return candidate;
6272
+ const source = teamWorktree ? sourceOf(basename(candidate)) : void 0;
6273
+ if (!source) break;
6274
+ candidate = expandHome$1(source);
3863
6275
  }
6276
+ 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.`);
3864
6277
  }
3865
-
3866
- const exec = promisify(execFile);
3867
- const git = async (directory, args) => (await exec("git", ["-C", directory, ...args], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
3868
6278
  async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3869
- if (repository === "~") repository = homedir();
3870
- else if (repository.startsWith("~/") || process.platform === "win32" && repository.startsWith("~\\")) repository = join(homedir(), repository.slice(2));
6279
+ repository = expandHome$1(repository);
3871
6280
  if (!isAbsolute(repository) || !/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new Error("A team task requires an absolute repository path and valid operation id");
3872
6281
  await git(repository, ["rev-parse", "--show-toplevel"]);
3873
6282
  const root = join(home, "teams", "worktrees");
@@ -3886,28 +6295,69 @@ async function prepareTeamWorktree(home, repository, id, origin = "teams") {
3886
6295
  }
3887
6296
  return { directory, repository, branch };
3888
6297
  }
6298
+ async function unpreservedCommits(directory, repository, rev) {
6299
+ const sourceHead = await git(repository, ["rev-parse", "HEAD"]).catch(() => "");
6300
+ const pending = (await git(directory, ["rev-list", rev, "--not", "--remotes", ...sourceHead ? [sourceHead] : []])).split("\n").filter(Boolean);
6301
+ if (pending.length === 0) return 0;
6302
+ return await squashMerged(directory, rev) ? 0 : pending.length;
6303
+ }
6304
+ async function squashMerged(directory, rev) {
6305
+ 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", () => "");
6306
+ if (!target) return false;
6307
+ const base = await git(directory, ["merge-base", rev, target]).catch(() => "");
6308
+ if (!base) return false;
6309
+ const own = patchIds(await gitRaw(directory, ["diff", base, rev]).then((diff) => diff ? patchIdOf(directory, diff) : "", () => ""));
6310
+ if (own.length !== 1) return false;
6311
+ const merged = patchIds(await gitRaw(directory, ["log", "-p", "--no-merges", "--max-count=500", `${base}..${target}`]).then((log) => log ? patchIdOf(directory, log) : "", () => ""));
6312
+ return merged.includes(own[0]);
6313
+ }
6314
+ async function patchIdOf(directory, patch) {
6315
+ return await new Promise((resolvePatch, reject) => {
6316
+ const child = execFile("git", ["-C", directory, "patch-id", "--stable"], { timeout: 3e4, maxBuffer: 2 * 1024 * 1024 }, (error, stdout) => error ? reject(error) : resolvePatch(stdout));
6317
+ child.stdin?.end(patch);
6318
+ });
6319
+ }
6320
+ const patchIds = (output) => output.split("\n").filter(Boolean).map((line) => line.split(" ")[0]);
6321
+ async function registeredWorktree(repository, directory) {
6322
+ const list = await git(repository, ["worktree", "list", "--porcelain"]).catch(() => "");
6323
+ return list.split("\n").some((line) => line.startsWith("worktree ") && resolve(line.slice("worktree ".length)) === resolve(directory));
6324
+ }
6325
+ const describeHead = async (directory) => await git(directory, ["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "") || "a detached HEAD";
3889
6326
  async function removeTeamWorktree(resource) {
3890
6327
  const { directory, repository, branch } = resource;
3891
6328
  if (!directory || !repository || !branch) return;
3892
- if (existsSync(directory)) {
3893
- if (await git(directory, ["symbolic-ref", "--short", "HEAD"]) !== branch) throw new Error("Worktree branch changed; preserve for manual reconciliation");
6329
+ let present = existsSync(directory);
6330
+ if (present) {
6331
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => "");
6332
+ if (!top || resolve(top) !== resolve(directory)) {
6333
+ 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`);
6334
+ if (readdirSync(directory).length === 0) rmdirSync(directory);
6335
+ present = false;
6336
+ }
6337
+ }
6338
+ if (present) {
3894
6339
  const actualCommon = await git(directory, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3895
6340
  const expectedCommon = await git(repository, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
3896
6341
  if (resolve(actualCommon) !== resolve(expectedCommon)) throw new Error("Worktree repository changed; preserve for manual reconciliation");
3897
- if (await git(directory, ["status", "--porcelain"])) throw new Error(`Uncommitted work retained at ${directory}`);
3898
- await git(repository, ["merge-base", "--is-ancestor", branch, "HEAD"]).catch(() => {
3899
- throw new Error(`Unmerged work retained on ${branch} at ${directory}`);
3900
- });
3901
- await git(repository, ["worktree", "remove", directory]);
6342
+ const dirty = (await git(directory, ["status", "--porcelain"])).split("\n").filter(Boolean).length;
6343
+ 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`);
6344
+ const head = await describeHead(directory);
6345
+ const unsafe = await unpreservedCommits(directory, repository, "HEAD");
6346
+ 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`);
3902
6347
  }
3903
- try {
3904
- await git(repository, ["show-ref", "--verify", `refs/heads/${branch}`]);
3905
- } catch {
3906
- return;
6348
+ const ownBranch = await git(repository, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).then(() => true, () => false);
6349
+ if (ownBranch) {
6350
+ const unsafe = await unpreservedCommits(repository, repository, `refs/heads/${branch}`);
6351
+ 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`);
3907
6352
  }
3908
- await git(repository, ["branch", "-d", branch]);
6353
+ if (present) await git(repository, ["worktree", "remove", directory]);
6354
+ else await git(repository, ["worktree", "prune"]).catch(() => void 0);
6355
+ if (ownBranch) await git(repository, ["branch", "-D", branch]);
3909
6356
  }
3910
6357
 
6358
+ function persistedSpawnMatches(operationId) {
6359
+ return Object.entries(readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === operationId);
6360
+ }
3911
6361
  function createTeamWorker(deps) {
3912
6362
  const home = deps.home ?? configuration.happyHomeDir;
3913
6363
  const server = deps.serverUrl ?? configuration.serverUrl;
@@ -3941,6 +6391,12 @@ function createTeamWorker(deps) {
3941
6391
  if (receipt.phase === "completed") return;
3942
6392
  try {
3943
6393
  if (op.type === "spawn") {
6394
+ if (ownerRetryPending(op, receipt) && (receipt.phase === "prepared" || receipt.phase === "spawning" && persistedSpawnMatches(op.id).length === 0)) {
6395
+ receipt = consumeOwnerRetry(op, receipt);
6396
+ writeReceipt$1(home, receipt);
6397
+ deps.log(`Teams operation ${op.id} relaunch requested by owner`);
6398
+ }
6399
+ if (receipt.phase === "prepared" && spawnGate(receipt, Date.now()) !== "run") return;
3944
6400
  if (receipt.phase === "prepared") {
3945
6401
  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;
3946
6402
  if (!credential) throw new Error("No scoped credential for worker");
@@ -3953,7 +6409,26 @@ function createTeamWorker(deps) {
3953
6409
  return;
3954
6410
  }
3955
6411
  if (!op.directory) throw new Error("No repository selected for worker");
3956
- const resource = await prepareTeamWorktree(home, op.directory, op.id);
6412
+ let resource;
6413
+ try {
6414
+ const repository = await resolveTeamRepository(home, op.directory, (id) => {
6415
+ try {
6416
+ return readReceipt(home, id)?.repository;
6417
+ } catch {
6418
+ return void 0;
6419
+ }
6420
+ });
6421
+ resource = await prepareTeamWorktree(home, repository, op.id);
6422
+ } catch (error) {
6423
+ const now = Date.now();
6424
+ receipt = afterStartupFailure(receipt, now);
6425
+ writeReceipt$1(home, receipt);
6426
+ const detail = error instanceof Error ? error.message : "Team worktree could not be prepared";
6427
+ await action(op.teamId, `preflight-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: startupFailureMessage(detail, receipt, now).slice(0, 1e3) }).catch(() => {
6428
+ });
6429
+ deps.log(`Teams operation ${op.id} preflight failed (${receipt.spawnFailures}/${TEAM_SPAWN_MAX_ATTEMPTS})`);
6430
+ return;
6431
+ }
3957
6432
  const scopes = join(home, "teams", "scopes");
3958
6433
  ensurePrivateDirectorySync(scopes);
3959
6434
  const scopeFile = join(scopes, `${op.id}.json`);
@@ -3961,12 +6436,21 @@ function createTeamWorker(deps) {
3961
6436
  receipt = { ...receipt, ...resource, scopeFile, phase: "spawning" };
3962
6437
  writeReceipt$1(home, receipt);
3963
6438
  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 } });
6439
+ if (spawned.type === "error" && spawned.startupExit?.exited) {
6440
+ const now = Date.now();
6441
+ receipt = afterStartupFailure(receipt, now);
6442
+ writeReceipt$1(home, receipt);
6443
+ await action(op.teamId, `startup-failure-${op.id}-${receipt.retryConsumed ?? 0}-${receipt.spawnFailures}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: startupFailureMessage(spawned.errorMessage, receipt, now).slice(0, 1e3) }).catch(() => {
6444
+ });
6445
+ deps.log(`Teams operation ${op.id} startup failed (${receipt.spawnFailures}/${TEAM_SPAWN_MAX_ATTEMPTS}); ${receipt.retryAt !== void 0 ? "will relaunch" : "waiting for owner retry"}`);
6446
+ return;
6447
+ }
3964
6448
  if (spawned.type !== "success") throw new Error(spawned.type === "error" ? spawned.errorMessage : "Directory approval required");
3965
6449
  receipt = { ...receipt, sessionId: spawned.sessionId, phase: "spawned" };
3966
6450
  writeReceipt$1(home, receipt);
3967
6451
  }
3968
6452
  if (receipt.phase === "spawning") {
3969
- const matches = Object.entries(readPersistedSessions()).filter(([, entry]) => entry.metadata?.teamOperationId === op.id);
6453
+ const matches = persistedSpawnMatches(op.id);
3970
6454
  if (matches.length !== 1) throw new Error("Spawn outcome unknown; reconcile the worker before retrying");
3971
6455
  receipt = { ...receipt, sessionId: matches[0][0], phase: "spawned" };
3972
6456
  writeReceipt$1(home, receipt);
@@ -3988,6 +6472,12 @@ function createTeamWorker(deps) {
3988
6472
  }
3989
6473
  await complete(op, receipt);
3990
6474
  } else {
6475
+ if (ownerRetryPending(op, receipt)) {
6476
+ const { retryAt: _retryAt, ...rest } = receipt;
6477
+ receipt = { ...rest, retryConsumed: op.retryRequestedAt };
6478
+ writeReceipt$1(home, receipt);
6479
+ deps.log(`Teams operation ${op.id} cleanup retry requested by owner`);
6480
+ } else if (receipt.retryAt !== void 0 && Date.now() < receipt.retryAt) return;
3991
6481
  const team = (await http.get(`/v1/teams/${encodeURIComponent(op.teamId)}`)).data.team;
3992
6482
  const latest = team.operations.find((candidate) => candidate.id === op.id);
3993
6483
  if (latest?.status === "completed") {
@@ -4014,7 +6504,14 @@ function createTeamWorker(deps) {
4014
6504
  } catch (error) {
4015
6505
  const unknown = op.type === "spawn" && receipt.phase === "spawning";
4016
6506
  const detail = error instanceof Error ? error.message : "Team operation failed";
4017
- 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(() => {
6507
+ if (op.type === "stop") {
6508
+ receipt = { ...receipt, retryAt: Date.now() + TEAM_CLEANUP_RETRY_MS };
6509
+ try {
6510
+ writeReceipt$1(home, receipt);
6511
+ } catch {
6512
+ }
6513
+ }
6514
+ await action(op.teamId, `failure-${op.id}-${receipt.phase}-${createHash("sha256").update(detail).digest("hex").slice(0, 12)}`, { type: "fail-operation", operationId: op.id, machineId: deps.machineId, claimId: receipt.claimId, error: detail.slice(0, 1e3), unknown }).catch(() => {
4018
6515
  });
4019
6516
  deps.log(`Teams operation ${op.id} ${unknown ? "needs reconciliation" : "will retry"}`);
4020
6517
  }
@@ -4113,7 +6610,19 @@ Use the teams tools to inspect current task state before acting. This message is
4113
6610
  }, 5e3);
4114
6611
  timer.unref();
4115
6612
  void tick();
4116
- return { tick, report, hasSession: (id) => knownSessionIds.has(id), get busy() {
6613
+ async function recoverScope(operationId, sessionId, scopeFile) {
6614
+ const teams = (await http.get("/v1/teams")).data.teams ?? [];
6615
+ const team = teams.find((candidate) => candidate.archivedAt === void 0 && candidate.operations.some((op2) => op2.id === operationId));
6616
+ const op = team?.operations.find((candidate) => candidate.id === operationId);
6617
+ if (!team || !op || op.type !== "spawn" || op.machineId !== deps.machineId) throw new Error("No live team launch for this session");
6618
+ const bot = team.bots.find((candidate) => candidate.id === op.botId);
6619
+ if (!bot || bot.sessionId !== sessionId || bot.generation !== op.generation) throw new Error("Team binding changed; not restoring its scope");
6620
+ const claimed = await action(op.teamId, `claim-${op.id}`, { type: "claim-operation", operationId: op.id, machineId: deps.machineId, ...op.teamLaunchVersion === 1 ? { teamLaunchVersion: 1 } : {} });
6621
+ if (!claimed.credential?.token || claimed.credential.botId !== op.botId) throw new Error("Team did not reissue the member credential");
6622
+ ensurePrivateDirectorySync(join(home, "teams", "scopes"));
6623
+ writePrivateFileSync(scopeFile, JSON.stringify({ serverUrl: server, scopeToken: claimed.credential.token, teamId: op.teamId, botId: op.botId, taskId: op.taskId, attemptId: op.attemptId }));
6624
+ }
6625
+ return { tick, report, recoverScope, hasSession: (id) => knownSessionIds.has(id), get busy() {
4117
6626
  return running;
4118
6627
  }, stop: () => {
4119
6628
  closed = true;
@@ -4889,6 +7398,7 @@ async function preflightNewBundle(bundlePath) {
4889
7398
  }
4890
7399
  }
4891
7400
  const HANDOVER_PREFLIGHT_TIMEOUT_MS = 3e4;
7401
+ const SPAWN_WEBHOOK_TIMEOUT_MS = 15e3;
4892
7402
  async function startDaemon() {
4893
7403
  const initialMachineMetadata = getInitialMachineMetadata();
4894
7404
  const startupCliAvailability = getStartupCliAvailability();
@@ -5545,22 +8055,33 @@ async function startDaemon() {
5545
8055
  });
5546
8056
  logger.debug(`[DAEMON RUN] Waiting for session webhook for PID ${happyProcess.pid}`);
5547
8057
  return new Promise((resolve) => {
8058
+ const pid = happyProcess.pid;
8059
+ let settled = false;
8060
+ const fail = (startupExit) => {
8061
+ if (settled) return;
8062
+ settled = true;
8063
+ clearTimeout(timeout);
8064
+ pidToAwaiter.delete(pid);
8065
+ startupExit.reason ??= readStartupExitReason(configuration.logsDir, pid);
8066
+ const errorMessage = describeStartupExit(startupExit, SPAWN_WEBHOOK_TIMEOUT_MS);
8067
+ logger.debug(`[DAEMON RUN] Spawn of PID ${pid} failed: ${errorMessage}`);
8068
+ resolve({ type: "error", errorMessage, startupExit });
8069
+ };
8070
+ happyProcess.once("exit", (code, signal) => fail({ exited: true, code, signal }));
5548
8071
  const timeout = setTimeout(() => {
5549
- pidToAwaiter.delete(happyProcess.pid);
5550
- logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${happyProcess.pid}`);
5551
- if (happyProcess.pid) {
5552
- try {
5553
- terminateProcess(happyProcess.pid, () => {
5554
- });
5555
- } catch {
5556
- }
8072
+ if (settled) return;
8073
+ pidToAwaiter.delete(pid);
8074
+ logger.debug(`[DAEMON RUN] Session webhook timeout for PID ${pid}`);
8075
+ try {
8076
+ const started = terminateProcess(pid, (stopped) => fail({ exited: stopped, code: null, signal: null, timedOut: true }));
8077
+ if (!started) fail({ exited: false, code: null, signal: null, timedOut: true });
8078
+ } catch {
8079
+ fail({ exited: false, code: null, signal: null, timedOut: true });
5557
8080
  }
5558
- resolve({
5559
- type: "error",
5560
- errorMessage: `Session webhook timeout for PID ${happyProcess.pid}`
5561
- });
5562
- }, 15e3);
5563
- pidToAwaiter.set(happyProcess.pid, (completedSession) => {
8081
+ }, SPAWN_WEBHOOK_TIMEOUT_MS);
8082
+ pidToAwaiter.set(pid, (completedSession) => {
8083
+ if (settled) return;
8084
+ settled = true;
5564
8085
  clearTimeout(timeout);
5565
8086
  logger.debug(`[DAEMON RUN] Session ${completedSession.happySessionId} fully spawned with webhook`);
5566
8087
  resolve({
@@ -5621,6 +8142,13 @@ async function startDaemon() {
5621
8142
  }
5622
8143
  };
5623
8144
  const resumeGates = /* @__PURE__ */ new Map();
8145
+ const teamRelaunchEnvFor = (happySessionId, metadata) => teamRelaunchEnv({
8146
+ home: configuration.happyHomeDir,
8147
+ sessionId: happySessionId,
8148
+ metadata,
8149
+ recover: teamWorker ? (operationId, scopeFile) => teamWorker.recoverScope(operationId, happySessionId, scopeFile) : void 0,
8150
+ log: (message) => logger.debug(`[DAEMON RUN] ${message}`)
8151
+ });
5624
8152
  const resumeSession = async (happySessionId, options) => {
5625
8153
  let gate = resumeGates.get(happySessionId);
5626
8154
  if (!gate) {
@@ -5685,8 +8213,8 @@ async function startDaemon() {
5685
8213
  });
5686
8214
  let freshConversation = false;
5687
8215
  if (!precheck.ok) {
5688
- if (precheck.reason === "conversation-missing") {
5689
- logger.debug(`[DAEMON RUN] resume: transcript for ${happySessionId} is gone (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
8216
+ if (resumeStartsFreshConversation(precheck.reason)) {
8217
+ logger.debug(`[DAEMON RUN] resume: ${precheck.reason} for ${happySessionId} (${precheck.detail}); starting a fresh conversation in ${metadata.path}`);
5690
8218
  freshConversation = true;
5691
8219
  } else {
5692
8220
  return { type: "error", errorMessage: `resume-precheck:${precheck.reason}: ${precheck.detail}` };
@@ -5699,12 +8227,15 @@ async function startDaemon() {
5699
8227
  const model = sanitizeResumeModel(options?.model);
5700
8228
  if (model) launch.args.push("--model", model);
5701
8229
  else if (options?.model !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid model ${JSON.stringify(options.model)}`);
5702
- const permissionMode = sanitizeSpawnPermissionMode(options?.permissionMode);
8230
+ const requestedMode = options?.permissionMode ?? (options?.keepPublishedPermissionMode ? publishedRelaunchPermissionMode(metadata) : void 0);
8231
+ const permissionMode = sanitizeSpawnPermissionMode(requestedMode);
5703
8232
  if (permissionMode) launch.args.push("--permission-mode", permissionMode);
5704
- else if (options?.permissionMode !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(options.permissionMode)}`);
8233
+ else if (requestedMode !== void 0) logger.debug(`[DAEMON RUN] resume: ignoring invalid permission mode ${JSON.stringify(requestedMode)}`);
8234
+ const teamEnv = await teamRelaunchEnvFor(happySessionId, metadata);
5705
8235
  const result = await spawnTrackedHappyProcess({
5706
8236
  args: launch.args,
5707
8237
  cwd: launch.cwd,
8238
+ ...teamEnv.VH_TEAM_SCOPE_FILE ? { spawnedBy: "teams" } : {},
5708
8239
  env: {
5709
8240
  ...process.env,
5710
8241
  // B-297: the credentialStore=file shim must ride every spawn path,
@@ -5720,7 +8251,8 @@ async function startDaemon() {
5720
8251
  HAPPY_RECONNECT_ENCRYPTION_VARIANT: tracked.encryption.encryptionVariant,
5721
8252
  HAPPY_RECONNECT_SEQ: String(tracked.encryption.seq),
5722
8253
  HAPPY_RECONNECT_METADATA_VERSION: String(tracked.encryption.metadataVersion),
5723
- HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion)
8254
+ HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion),
8255
+ ...teamEnv
5724
8256
  }
5725
8257
  });
5726
8258
  if (result.type === "success") {
@@ -5838,9 +8370,11 @@ async function startDaemon() {
5838
8370
  const permissionMode = sanitizeSpawnPermissionMode(options?.permissionMode);
5839
8371
  if (permissionMode) args.push("--permission-mode", permissionMode);
5840
8372
  restartCounts.set(happySessionId, recordRestartAttempt(prior));
8373
+ const teamEnv = await teamRelaunchEnvFor(happySessionId, metadata);
5841
8374
  const result = await spawnTrackedHappyProcess({
5842
8375
  args,
5843
8376
  cwd,
8377
+ ...teamEnv.VH_TEAM_SCOPE_FILE ? { spawnedBy: "teams" } : {},
5844
8378
  env: {
5845
8379
  ...process.env,
5846
8380
  // B-297: the credentialStore=file shim must ride every spawn path,
@@ -5855,7 +8389,8 @@ async function startDaemon() {
5855
8389
  HAPPY_RECONNECT_ENCRYPTION_VARIANT: tracked.encryption.encryptionVariant,
5856
8390
  HAPPY_RECONNECT_SEQ: String(tracked.encryption.seq),
5857
8391
  HAPPY_RECONNECT_METADATA_VERSION: String(tracked.encryption.metadataVersion),
5858
- HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion)
8392
+ HAPPY_RECONNECT_AGENT_STATE_VERSION: String(tracked.encryption.agentStateVersion),
8393
+ ...teamEnv
5859
8394
  }
5860
8395
  });
5861
8396
  if (result.type === "success") {
@@ -6128,6 +8663,15 @@ async function startDaemon() {
6128
8663
  setStore: (store) => claudeAuthService.setStore(store)
6129
8664
  });
6130
8665
  claudeAuthService.start();
8666
+ apiMachine.setModelConfigService(new ModelConfigService({
8667
+ home: os.homedir(),
8668
+ env: process.env,
8669
+ happyHomeDir: configuration.happyHomeDir,
8670
+ isInstalled: commandOnPath,
8671
+ onChanged: (harness) => {
8672
+ if (harness === "claude") void claudeAuthService.probe("model-config", true);
8673
+ }
8674
+ }));
6131
8675
  apiMachine.setAgentHibernationHandlers(resolveIdleMs(agentHibernationSetting), async (requested) => {
6132
8676
  const value = requested <= 0 ? 0 : settingIdleMs(requested);
6133
8677
  await updateSettings((current) => ({ ...current, agentHibernationIdleMs: value }));
@@ -6149,6 +8693,8 @@ async function startDaemon() {
6149
8693
  })).then(() => logger.debug(`[DAEMON RUN] claimed the machine record for host ${initialMachineMetadata.host}`)).catch((error) => logger.debug("[DAEMON RUN] could not refresh the recorded host:", error));
6150
8694
  }
6151
8695
  let lastUpdateLog = "";
8696
+ let harnessInstaller = null;
8697
+ let handoverInFlight = false;
6152
8698
  const updateController = createUpdateController({
6153
8699
  policy: () => fetchCliUpdateState(configuration.serverUrl, packageJson.version),
6154
8700
  enabled: async () => ((await readSettings()).cliAutoUpdate ?? "idle") !== "off",
@@ -6156,8 +8702,9 @@ async function startDaemon() {
6156
8702
  // handover (they talk to the server themselves) and web terminals live
6157
8703
  // in tmux, so neither is a reason to hold an update. B-507: a session
6158
8704
  // whose turn ended but still has background tasks is busy too.
6159
- idle: () => !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny(),
8705
+ idle: () => !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny() && !harnessInstaller?.isRunning(),
6160
8706
  install: installCliSafely,
8707
+ lastInstall: lastInstallStore(configuration.happyHomeDir),
6161
8708
  publish: (state) => {
6162
8709
  cliUpdateStateRef = state;
6163
8710
  fileState = { ...fileState, cliUpdate: state };
@@ -6204,10 +8751,33 @@ async function startDaemon() {
6204
8751
  logger.warn(`[DAEMON RUN] Ignoring invalid HAPPY_CLI_UPDATE_CHECK_INTERVAL; using ${DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS}ms`);
6205
8752
  }
6206
8753
  const cliUpdateInterval = setInterval(() => void refreshCliUpdate(), cliUpdateIntervalMs);
8754
+ const policyAnnouncements = createPolicyAnnouncementHandler({
8755
+ refresh: refreshCliUpdate,
8756
+ currentTarget: updateController.currentTarget
8757
+ });
8758
+ apiMachine.setCliUpdatePolicyHandler((payload) => {
8759
+ const delay = policyAnnouncements.onAnnouncement(payload);
8760
+ if (delay !== null) logger.warn(`[DAEMON RUN] CLI update policy announced; re-checking in ${Math.round(delay / 1e3)}s`);
8761
+ });
6207
8762
  const stopAgentVersionChecks = startAgentVersionChecks(
6208
8763
  (snapshot) => apiMachine.updateDaemonState((state) => ({ ...state, status: state?.status ?? "running", agentVersions: snapshot })),
6209
8764
  (error) => logger.debug("[DAEMON RUN] Agent version check failed", error)
6210
8765
  );
8766
+ harnessInstaller = createHarnessInstaller({
8767
+ npm: runNpm,
8768
+ runningPackageDir: projectPath(),
8769
+ commandOnPath,
8770
+ cliUpdateBusy: () => updateController.isRunning() || handoverInFlight,
8771
+ publish: (state) => {
8772
+ void apiMachine.updateDaemonState((current) => ({ ...current, status: current?.status ?? "running", harnessInstall: state })).catch((error) => logger.debug("[DAEMON RUN] harness install state publish failed", error));
8773
+ },
8774
+ afterInstall: async () => {
8775
+ apiMachine.recheckCliAvailability();
8776
+ await stopAgentVersionChecks.refresh();
8777
+ },
8778
+ log: (message) => logger.warn(`[DAEMON RUN] ${message}`)
8779
+ });
8780
+ apiMachine.setHarnessInstallHandler((params) => harnessInstaller.request(params));
6211
8781
  const heartbeatIntervalMs = parseInt(process.env.HAPPY_DAEMON_HEARTBEAT_INTERVAL || "60000");
6212
8782
  const restartOnStaleVersionAndHeartbeat = setInterval(serialTask(async () => {
6213
8783
  try {
@@ -6224,53 +8794,59 @@ async function startDaemon() {
6224
8794
  }
6225
8795
  await updateController.tick();
6226
8796
  await updateController.withHandover(async () => {
6227
- let bundleReplaced = false;
6228
- if (initialBundleMtimeMs > 0) {
6229
- try {
6230
- const currentMtimeMs = statSync$1(bundlePath).mtimeMs;
6231
- bundleReplaced = currentMtimeMs !== initialBundleMtimeMs;
6232
- } catch {
6233
- }
6234
- }
6235
- const relayMove = pendingRelayMove;
6236
- if ((bundleReplaced || relayMove) && !teamWorker?.busy && !automationRunner?.busy && !updateController.isRunning() && !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny()) {
6237
- const preflight = bundleReplaced ? await preflightNewBundle(bundlePath) : { action: "proceed" };
6238
- if (preflight.action === "hold") {
6239
- if (lastHandoverHold !== preflight.reason) {
6240
- lastHandoverHold = preflight.reason;
6241
- logger.warn(`[DAEMON RUN] holding handover: ${preflight.reason}`);
8797
+ handoverInFlight = true;
8798
+ try {
8799
+ let bundleReplaced = false;
8800
+ if (initialBundleMtimeMs > 0) {
8801
+ try {
8802
+ const currentMtimeMs = statSync$1(bundlePath).mtimeMs;
8803
+ bundleReplaced = currentMtimeMs !== initialBundleMtimeMs;
8804
+ } catch {
6242
8805
  }
6243
- updateController.holdHandover(preflight.reason);
6244
- return;
6245
8806
  }
6246
- if (teamWorker?.busy || automationRunner?.busy || updateController.isRunning() || turnActivity.hasActiveTurn() || backgroundTasks.hasAny()) return;
6247
- lastHandoverHold = null;
6248
- 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");
6249
- teamWorker?.stop();
6250
- automationRunner?.stop();
6251
- projectPresence?.stop();
6252
- clearInterval(restartOnStaleVersionAndHeartbeat);
6253
- clearInterval(cliUpdateInterval);
6254
- stopAgentVersionChecks();
6255
- claudeAuthService.stop();
6256
- apiMachine.shutdown();
6257
- await stopControlServer();
6258
- await cleanupDaemonState();
6259
- await releaseDaemonLock(daemonLockHandle);
6260
- await stopCaffeinate();
6261
- if (daemonSupervisor === "systemd") {
6262
- logger.debug(`[DAEMON RUN] systemd-supervised: exiting ${HANDOVER_EXIT_CODE} for the unit to restart on the new bundle`);
6263
- process.exit(HANDOVER_EXIT_CODE);
6264
- }
6265
- try {
6266
- spawnHappyCLI(["daemon", "start"], {
6267
- detached: true,
6268
- stdio: "ignore"
6269
- });
6270
- } catch (error) {
6271
- 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);
8807
+ const relayMove = pendingRelayMove;
8808
+ if ((bundleReplaced || relayMove) && !teamWorker?.busy && !automationRunner?.busy && !updateController.isRunning() && !harnessInstaller?.isRunning() && !turnActivity.hasActiveTurn() && !backgroundTasks.hasAny()) {
8809
+ const preflight = bundleReplaced ? await preflightNewBundle(bundlePath) : { action: "proceed" };
8810
+ if (preflight.action === "hold") {
8811
+ if (lastHandoverHold !== preflight.reason) {
8812
+ lastHandoverHold = preflight.reason;
8813
+ logger.warn(`[DAEMON RUN] holding handover: ${preflight.reason}`);
8814
+ }
8815
+ updateController.holdHandover(preflight.reason);
8816
+ return;
8817
+ }
8818
+ if (teamWorker?.busy || automationRunner?.busy || updateController.isRunning() || harnessInstaller?.isRunning() || turnActivity.hasActiveTurn() || backgroundTasks.hasAny()) return;
8819
+ lastHandoverHold = null;
8820
+ 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");
8821
+ teamWorker?.stop();
8822
+ automationRunner?.stop();
8823
+ projectPresence?.stop();
8824
+ clearInterval(restartOnStaleVersionAndHeartbeat);
8825
+ clearInterval(cliUpdateInterval);
8826
+ policyAnnouncements.stop();
8827
+ stopAgentVersionChecks();
8828
+ claudeAuthService.stop();
8829
+ apiMachine.shutdown();
8830
+ await stopControlServer();
8831
+ await cleanupDaemonState();
8832
+ await releaseDaemonLock(daemonLockHandle);
8833
+ await stopCaffeinate();
8834
+ if (daemonSupervisor === "systemd") {
8835
+ logger.debug(`[DAEMON RUN] systemd-supervised: exiting ${HANDOVER_EXIT_CODE} for the unit to restart on the new bundle`);
8836
+ process.exit(HANDOVER_EXIT_CODE);
8837
+ }
8838
+ try {
8839
+ spawnHappyCLI(["daemon", "start"], {
8840
+ detached: true,
8841
+ stdio: "ignore"
8842
+ });
8843
+ } catch (error) {
8844
+ 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);
8845
+ }
8846
+ process.exit(0);
6272
8847
  }
6273
- process.exit(0);
8848
+ } finally {
8849
+ handoverInFlight = false;
6274
8850
  }
6275
8851
  });
6276
8852
  const daemonState = await readDaemonState();
@@ -6318,7 +8894,7 @@ async function startDaemon() {
6318
8894
  return !!record && typeof record.hibernatedAt === "number" && record.hibernatedAt >= record.savedAt;
6319
8895
  },
6320
8896
  wakeHibernated: async (id) => {
6321
- const result = await resumeSession(id);
8897
+ const result = await resumeSession(id, { keepPublishedPermissionMode: true });
6322
8898
  if (result.type !== "success") return false;
6323
8899
  return waitForSessionLive(id, (sid) => [...pidToTrackedSession.values()].some((s) => s.happySessionId === sid && isPidAlive(s.pid)));
6324
8900
  },
@@ -6337,11 +8913,18 @@ async function startDaemon() {
6337
8913
  log: (message) => logger.debug(`[DAEMON RUN] ${message}`)
6338
8914
  });
6339
8915
  void apiMachine.updateMachineMetadata((current) => ({
6340
- ...current ?? initialMachineMetadata,
8916
+ // B-718: the running CLI version, not the one that first registered the row.
8917
+ ...withRunningCliFacts(current, initialMachineMetadata),
6341
8918
  teamsVersion: 1,
6342
8919
  teamLaunchVersion: 1,
8920
+ // B-689: this daemon acts on the owner's retry-operation (web gates「重试启动」).
8921
+ teamRetryVersion: TEAM_RETRY_CAPABILITY_VERSION,
6343
8922
  // B-586: this daemon serves the worktree-* RPCs (web gates 「在新 worktree 中」 on it).
6344
- worktreeVersion: WORKTREE_CAPABILITY_VERSION
8923
+ worktreeVersion: WORKTREE_CAPABILITY_VERSION,
8924
+ // B-688: this daemon serves the model-config-* RPCs (web gates 「模型与 Provider」 on it).
8925
+ modelConfigVersion: MODEL_CONFIG_CAPABILITY_VERSION,
8926
+ // B-719: this daemon serves `harness-install` (web gates the Install / Update buttons on it).
8927
+ harnessInstallVersion: HARNESS_INSTALL_CAPABILITY_VERSION
6345
8928
  })).catch(() => logger.debug("[DAEMON RUN] Teams capability publication will retry on reconnect"));
6346
8929
  const cleanupAndShutdown = async (source, errorMessage) => {
6347
8930
  webPanelsSync.stop();
@@ -6356,6 +8939,7 @@ async function startDaemon() {
6356
8939
  logger.debug("[DAEMON RUN] Health check interval cleared");
6357
8940
  }
6358
8941
  clearInterval(cliUpdateInterval);
8942
+ policyAnnouncements.stop();
6359
8943
  stopAgentVersionChecks();
6360
8944
  await apiMachine.updateDaemonState((state) => ({
6361
8945
  ...state,