openpond 0.2.54 → 0.2.56

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 (432) hide show
  1. package/dist/app-server.d.ts +10823 -9118
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/actions-command-QU4H53OG.js +2 -0
  4. package/dist/chunks/{app-layer-I7MZYVLL.js → app-layer-NSTE5HIT.js} +1 -1
  5. package/dist/chunks/app-server-connected-apps-JHGWLBXT.js +2 -0
  6. package/dist/chunks/app-server-evaluations-GJPFWIDA.js +2 -0
  7. package/dist/chunks/app-server-harness-services-IH4G6POY.js +2 -0
  8. package/dist/chunks/app-server-runtime-DVKOZ5B6.js +2 -0
  9. package/dist/chunks/apps-BKTOR4F7.js +2 -0
  10. package/dist/chunks/chunk-25MBPJVY.js +2 -0
  11. package/dist/chunks/chunk-2D4Y3HNW.js +2 -0
  12. package/dist/chunks/chunk-2IHO4GDJ.js +2 -0
  13. package/dist/chunks/chunk-2QUCCP6Z.js +2 -0
  14. package/dist/chunks/chunk-3K4VVB7S.js +6 -0
  15. package/dist/chunks/chunk-3QIB5FXI.js +10 -0
  16. package/dist/chunks/chunk-3RCRSMWZ.js +17 -0
  17. package/dist/chunks/chunk-3VUATFZD.js +2 -0
  18. package/dist/chunks/chunk-3Z47M3YY.js +2 -0
  19. package/dist/chunks/{chunk-GXSTZBM6.js → chunk-4D7HWVWD.js} +1 -1
  20. package/dist/chunks/chunk-4EPSHPZL.js +2 -0
  21. package/dist/chunks/chunk-4NESNOK5.js +2 -0
  22. package/dist/chunks/chunk-523TE4BI.js +2 -0
  23. package/dist/chunks/chunk-5MCNZCVQ.js +2 -0
  24. package/dist/chunks/chunk-6QSSIT62.js +2 -0
  25. package/dist/chunks/chunk-6ZFPQYHG.js +2 -0
  26. package/dist/chunks/chunk-74IIXVAE.js +2 -0
  27. package/dist/chunks/chunk-74ZXXBGN.js +6 -0
  28. package/dist/chunks/chunk-773TH7FN.js +2 -0
  29. package/dist/chunks/chunk-7E6T7GP5.js +2 -0
  30. package/dist/chunks/chunk-7ED24PP6.js +2 -0
  31. package/dist/chunks/chunk-7HPDGZOR.js +86 -0
  32. package/dist/chunks/chunk-7KWD2I6W.js +2 -0
  33. package/dist/chunks/chunk-7PXZ4X4P.js +2 -0
  34. package/dist/chunks/chunk-A6USMRWK.js +2 -0
  35. package/dist/chunks/chunk-ABD5M2D2.js +2 -0
  36. package/dist/chunks/chunk-ACYFMLWG.js +10 -0
  37. package/dist/chunks/chunk-AN525SPP.js +6 -0
  38. package/dist/chunks/chunk-APB2STJK.js +2 -0
  39. package/dist/chunks/chunk-AY64VY4E.js +2 -0
  40. package/dist/chunks/{chunk-UJ5EFSEC.js → chunk-B7RFL4N2.js} +1 -1
  41. package/dist/chunks/chunk-BFKYRQMA.js +2 -0
  42. package/dist/chunks/chunk-BLXEAZCQ.js +12 -0
  43. package/dist/chunks/chunk-D74JEERO.js +5 -0
  44. package/dist/chunks/{chunk-PA7XP42P.js → chunk-DARVPBZ4.js} +1 -1
  45. package/dist/chunks/chunk-DBK66CJP.js +8 -0
  46. package/dist/chunks/chunk-DDMZSZFL.js +1 -0
  47. package/dist/chunks/chunk-DIO5CB6U.js +2 -0
  48. package/dist/chunks/chunk-DMFUEUAZ.js +5 -0
  49. package/dist/chunks/chunk-DMVD2RFZ.js +2 -0
  50. package/dist/chunks/chunk-DUURYZOI.js +2 -0
  51. package/dist/chunks/chunk-DZUAT3TP.js +1 -0
  52. package/dist/chunks/chunk-EIEZHFIW.js +6 -0
  53. package/dist/chunks/chunk-EIRYMSEG.js +19 -0
  54. package/dist/chunks/{chunk-JDLAHVAJ.js → chunk-EKM2D7JU.js} +1 -1
  55. package/dist/chunks/chunk-EQFGBL3O.js +2 -0
  56. package/dist/chunks/chunk-EYPCBBMS.js +2 -0
  57. package/dist/chunks/chunk-F4KOGISR.js +10 -0
  58. package/dist/chunks/chunk-F74GBN6K.js +2 -0
  59. package/dist/chunks/chunk-FEAKTSRS.js +2 -0
  60. package/dist/chunks/chunk-FFRFSDBM.js +2 -0
  61. package/dist/chunks/chunk-FTEOCCPB.js +23 -0
  62. package/dist/chunks/chunk-FUOEIDMA.js +8 -0
  63. package/dist/chunks/{chunk-AH22RHPS.js → chunk-FV2R5RUN.js} +2 -2
  64. package/dist/chunks/chunk-FWIPHEVA.js +12 -0
  65. package/dist/chunks/chunk-FY5KHLMW.js +2 -0
  66. package/dist/chunks/chunk-G3RXYI2L.js +6 -0
  67. package/dist/chunks/chunk-GJ2ZJFDD.js +2 -0
  68. package/dist/chunks/chunk-GLDYJM7O.js +1 -0
  69. package/dist/chunks/chunk-GPVCOEUH.js +2 -0
  70. package/dist/chunks/chunk-GW766ZSO.js +5 -0
  71. package/dist/chunks/chunk-GWCHDF2C.js +4 -0
  72. package/dist/chunks/chunk-GZ7M5XBP.js +2 -0
  73. package/dist/chunks/chunk-H6IW2R22.js +140 -0
  74. package/dist/chunks/chunk-HCYX6RHP.js +2 -0
  75. package/dist/chunks/chunk-HDL5YSAA.js +2 -0
  76. package/dist/chunks/chunk-HIOKCIL7.js +2 -0
  77. package/dist/chunks/chunk-HY3GOBFJ.js +58 -0
  78. package/dist/chunks/chunk-HZEIRHEB.js +2 -0
  79. package/dist/chunks/chunk-I2NXNMRZ.js +2 -0
  80. package/dist/chunks/chunk-I7AQMAQI.js +33 -0
  81. package/dist/chunks/chunk-IZ6DLEVY.js +2 -0
  82. package/dist/chunks/chunk-J2TWKFML.js +1871 -0
  83. package/dist/chunks/chunk-JDEEWOD7.js +2 -0
  84. package/dist/chunks/chunk-JFXWI3EN.js +6 -0
  85. package/dist/chunks/chunk-JYKRR7E5.js +5 -0
  86. package/dist/chunks/chunk-KCJVFLBB.js +2 -0
  87. package/dist/chunks/{chunk-5CMKGD43.js → chunk-KG325WTN.js} +1 -1
  88. package/dist/chunks/chunk-KGNCKIFP.js +3 -0
  89. package/dist/chunks/chunk-KUERKVEU.js +3 -0
  90. package/dist/chunks/chunk-KVTBX2UP.js +2 -0
  91. package/dist/chunks/chunk-L6K7ERG5.js +2 -0
  92. package/dist/chunks/{chunk-N5QNXMIS.js → chunk-LQQNBVEB.js} +1 -1
  93. package/dist/chunks/{chunk-YJ4PNAST.js → chunk-M4JWQSV7.js} +1 -1
  94. package/dist/chunks/chunk-MQULU465.js +2 -0
  95. package/dist/chunks/chunk-N4FFQPLR.js +2 -0
  96. package/dist/chunks/chunk-N73MU2C3.js +2 -0
  97. package/dist/chunks/chunk-NHQ36THU.js +3 -0
  98. package/dist/chunks/{chunk-4SHKI3BH.js → chunk-O6ULLQJ6.js} +1 -1
  99. package/dist/chunks/chunk-O72BSKSO.js +2 -0
  100. package/dist/chunks/chunk-OGDADQGH.js +143 -0
  101. package/dist/chunks/chunk-OIUTWU6K.js +2 -0
  102. package/dist/chunks/chunk-OLLLZVHF.js +2 -0
  103. package/dist/chunks/{chunk-XM26DGML.js → chunk-OPNRWESL.js} +1 -1
  104. package/dist/chunks/chunk-OQKJGTTO.js +4 -0
  105. package/dist/chunks/chunk-OQPJ7FJF.js +9 -0
  106. package/dist/chunks/{chunk-R3XFY7VL.js → chunk-OS3LO5J3.js} +1 -1
  107. package/dist/chunks/{chunk-T5LE6R5S.js → chunk-OSIO7PLX.js} +1 -1
  108. package/dist/chunks/chunk-OUVIWDL2.js +2 -0
  109. package/dist/chunks/chunk-PCSIOUHF.js +7 -0
  110. package/dist/chunks/chunk-PF5R6CMP.js +21 -0
  111. package/dist/chunks/chunk-PPAPVGJP.js +3 -0
  112. package/dist/chunks/chunk-PRGBLQVH.js +2 -0
  113. package/dist/chunks/chunk-PSGGOZFM.js +2 -0
  114. package/dist/chunks/chunk-PUZQU66L.js +2 -0
  115. package/dist/chunks/{chunk-WITSXYEW.js → chunk-Q2QL6UWN.js} +1 -1
  116. package/dist/chunks/chunk-Q4TBTRIG.js +2 -0
  117. package/dist/chunks/chunk-Q5LEXXJG.js +16 -0
  118. package/dist/chunks/{chunk-YL6VFJ4P.js → chunk-QDC4OW3S.js} +1 -1
  119. package/dist/chunks/chunk-QEFHOJFE.js +7 -0
  120. package/dist/chunks/chunk-QHWGQ3A4.js +5 -0
  121. package/dist/chunks/chunk-QIKWJ2AA.js +11 -0
  122. package/dist/chunks/chunk-QNG27G3T.js +6 -0
  123. package/dist/chunks/chunk-QOGJAQDO.js +3 -0
  124. package/dist/chunks/chunk-QOTVNQDI.js +4 -0
  125. package/dist/chunks/{chunk-N3DEA6PG.js → chunk-RAXOSUSW.js} +1 -1
  126. package/dist/chunks/chunk-RNIAFXMB.js +50 -0
  127. package/dist/chunks/chunk-S5ESN275.js +42 -0
  128. package/dist/chunks/chunk-SDAUS5PY.js +2 -0
  129. package/dist/chunks/chunk-SDXFLO7J.js +5 -0
  130. package/dist/chunks/chunk-SH5CBAFC.js +2 -0
  131. package/dist/chunks/chunk-SWUEFLOH.js +2 -0
  132. package/dist/chunks/chunk-SYUKES6H.js +3 -0
  133. package/dist/chunks/chunk-T5AACNJI.js +2 -0
  134. package/dist/chunks/chunk-TRQQNFMO.js +4 -0
  135. package/dist/chunks/chunk-TVQAPBLZ.js +2 -0
  136. package/dist/chunks/chunk-UCPGRPWY.js +2 -0
  137. package/dist/chunks/chunk-UGL7WF3W.js +2 -0
  138. package/dist/chunks/chunk-UHFZHBGW.js +2 -0
  139. package/dist/chunks/chunk-UKMA4R6X.js +6 -0
  140. package/dist/chunks/{chunk-7ZG3IT7C.js → chunk-VRIEKBBH.js} +6 -6
  141. package/dist/chunks/chunk-VYLGI3IH.js +13 -0
  142. package/dist/chunks/chunk-W45RKGM6.js +1 -0
  143. package/dist/chunks/chunk-WJ43MJ3F.js +2 -0
  144. package/dist/chunks/chunk-WMKYHXVM.js +3 -0
  145. package/dist/chunks/chunk-WN3V6KDN.js +3 -0
  146. package/dist/chunks/chunk-X4OSOOSU.js +3 -0
  147. package/dist/chunks/chunk-XDQMGUWL.js +2 -0
  148. package/dist/chunks/chunk-XTFPDQMH.js +3 -0
  149. package/dist/chunks/chunk-XVDFJ3ZF.js +2 -0
  150. package/dist/chunks/chunk-XW6HGSIT.js +8 -0
  151. package/dist/chunks/chunk-XXYGGNVM.js +2 -0
  152. package/dist/chunks/chunk-Y4OWBBDD.js +184 -0
  153. package/dist/chunks/chunk-YBT2NB32.js +2 -0
  154. package/dist/chunks/chunk-YCJO3YVD.js +10 -0
  155. package/dist/chunks/{chunk-YD55Z5H3.js → chunk-YOBN7KTF.js} +11 -11
  156. package/dist/chunks/chunk-YOQRYNLP.js +2 -0
  157. package/dist/chunks/chunk-YR5ID2SS.js +2 -0
  158. package/dist/chunks/chunk-YY7LEQGP.js +2 -0
  159. package/dist/chunks/chunk-Z4Z5UOZM.js +22 -0
  160. package/dist/chunks/chunk-Z54O534A.js +3 -0
  161. package/dist/chunks/chunk-ZCHXGRRU.js +2 -0
  162. package/dist/chunks/chunk-ZFSHBFG5.js +40 -0
  163. package/dist/chunks/chunk-ZGTOK7ZK.js +12 -0
  164. package/dist/chunks/{chunk-NAZ26IZL.js → chunk-ZRDGQDZL.js} +1 -1
  165. package/dist/chunks/chunk-ZUJ3XUCP.js +2 -0
  166. package/dist/chunks/chunk-ZZWAQBA2.js +2 -0
  167. package/dist/chunks/cli-X25RSO2X.js +2 -0
  168. package/dist/chunks/configuration-command-6C5UO7GE.js +2 -0
  169. package/dist/chunks/connected-app-executor-IVLGQP65.js +2 -0
  170. package/dist/chunks/connected-evidence-GH2ATNEX.js +2 -0
  171. package/dist/chunks/connection-HTF6CC7M.js +2 -0
  172. package/dist/chunks/{continual-PKK2BOTB.js → continual-6CQAMTTR.js} +3 -3
  173. package/dist/chunks/core-commands-A2DGGIPS.js +2 -0
  174. package/dist/chunks/datasets-7BNMVJOY.js +2 -0
  175. package/dist/chunks/desktop-test-3CUHVLXV.js +3 -0
  176. package/dist/chunks/dist-OMGUJYPD.js +2 -0
  177. package/dist/chunks/{chunk-6VF3Q6QJ.js → dist-SKYG5LZO.js} +2 -4
  178. package/dist/chunks/dist-VYC5VMQB.js +2 -0
  179. package/dist/chunks/dist-ZVJPJLXR.js +2 -0
  180. package/dist/chunks/enclave-QS4BUNDU.js +2 -0
  181. package/dist/chunks/evaluation-coordination-XEF5L7KZ.js +2 -0
  182. package/dist/chunks/experiment-improvements-KRX2DP27.js +2 -0
  183. package/dist/chunks/experiments-DFGQYA4O.js +2 -0
  184. package/dist/chunks/experiments-VFQGE4HC.js +2 -0
  185. package/dist/chunks/extension-XKXXOP5N.js +4 -0
  186. package/dist/chunks/{help-WLKSACLZ.js → help-S7THC6IE.js} +1 -1
  187. package/dist/chunks/host-profile-evaluation-tools-JJQWJUBT.js +2 -0
  188. package/dist/chunks/host-profile-external-dataset-K3ICDHIP.js +2 -0
  189. package/dist/chunks/hosted-app-server-composition-BCOO5ANF.js +2 -0
  190. package/dist/chunks/hosted-experiment-improvement-NFSVS5TU.js +3 -0
  191. package/dist/chunks/hosted-harness-runtime-723S5ZSH.js +2 -0
  192. package/dist/chunks/hosted-profile-candidate-2S5LFUWD.js +3 -0
  193. package/dist/chunks/hosted-profile-compiler-2DQIFSXW.js +2 -0
  194. package/dist/chunks/hosted-profile-evaluation-control-76BTRTYD.js +2 -0
  195. package/dist/chunks/hosted-profile-evaluation-inspection-V6Z3A5XJ.js +3 -0
  196. package/dist/chunks/hosted-profile-evaluation-preparation-IDJYREW3.js +3 -0
  197. package/dist/chunks/hosted-tasksets-ANAE2PIW.js +2 -0
  198. package/dist/chunks/human-review-WR777ODH.js +2 -0
  199. package/dist/chunks/import-MLZUHITH.js +4 -0
  200. package/dist/chunks/javascript-isolate-process-source-ZPQKKLR4.js +2 -0
  201. package/dist/chunks/javascript-verifier-worker-source-F3LSGPOY.js +2 -0
  202. package/dist/chunks/learning-ACEVFL5M.js +2 -0
  203. package/dist/chunks/local-harness-improvement-runtime-JIQ6ZVDW.js +2 -0
  204. package/dist/chunks/local-harness-taskset-review-XVYTGAGK.js +2 -0
  205. package/dist/chunks/local-scope-HVF2GZ5W.js +2 -0
  206. package/dist/chunks/model-projects-QPO22JPA.js +2 -0
  207. package/dist/chunks/opchat-T4QTNEIY.js +3 -0
  208. package/dist/chunks/organizations-75L5DZDV.js +2 -0
  209. package/dist/chunks/profile-TFZMUEDR.js +3 -0
  210. package/dist/chunks/profile-training-source-6GOT7AHM.js +2 -0
  211. package/dist/chunks/project-action-payload-7VGL7OER.js +2 -0
  212. package/dist/chunks/project-agent-6RRO233B.js +2 -0
  213. package/dist/chunks/published-experiment-source-DZFENAQA.js +2 -0
  214. package/dist/chunks/refiner-profile-service-UUIWFJVT.js +2 -0
  215. package/dist/chunks/runtime-A7OZXM43.js +6 -0
  216. package/dist/chunks/sandbox-command-IU5XFTJP.js +2 -0
  217. package/dist/chunks/{sandbox-template-BBGGPJMI.js → sandbox-template-C4V6T36U.js} +1 -1
  218. package/dist/chunks/saved-work-6BMBFP43.js +2 -0
  219. package/dist/chunks/send-turn-XTAIS2JN.js +2 -0
  220. package/dist/chunks/sql-execution-process-source-B4HQM6ZV.js +2 -0
  221. package/dist/chunks/src-CJM6HY5Y.js +326 -0
  222. package/dist/chunks/{src-CR6UZYTX.js → src-LMC3K6LH.js} +1 -1
  223. package/dist/chunks/standalone-experiment-turn-owner-JCY5LL5R.js +2 -0
  224. package/dist/chunks/store-chat-workflows-S72HZXQR.js +18 -0
  225. package/dist/chunks/store-continual-support-reviews-HHA6NX7K.js +7 -0
  226. package/dist/chunks/store-conversation-serving-KPC62UEY.js +2 -0
  227. package/dist/chunks/store-create-improve-QV54XIZW.js +40 -0
  228. package/dist/chunks/store-datasets-RXJ33SUN.js +86 -0
  229. package/dist/chunks/store-evaluation-results-3F3P527G.js +7 -0
  230. package/dist/chunks/store-harness-evaluation-review-settings-I2R3HPO3.js +29 -0
  231. package/dist/chunks/store-harness-memory-VINCZ4GK.js +17 -0
  232. package/dist/chunks/store-harness-refinement-candidates-EA5KFQPH.js +21 -0
  233. package/dist/chunks/store-harness-workspaces-XUM4Z66X.js +2 -0
  234. package/dist/chunks/store-human-review-RAH7WMIP.js +7 -0
  235. package/dist/chunks/store-learned-preference-migration-validation-4CI2IRUF.js +2 -0
  236. package/dist/chunks/store-learning-WLG6KFIO.js +2 -0
  237. package/dist/chunks/store-learning-credentials-WZQJ4HPJ.js +2 -0
  238. package/dist/chunks/store-local-experiments-5LUJR7GI.js +97 -0
  239. package/dist/chunks/store-model-batch-review-YEGX327M.js +2 -0
  240. package/dist/chunks/store-model-configuration-5ZURQATB.js +3 -0
  241. package/dist/chunks/store-preference-comparison-LV32MHVL.js +6 -0
  242. package/dist/chunks/store-schedules-VGTEQVKH.js +53 -0
  243. package/dist/chunks/store-sidebar-file-bookmarks-VB5GTLFY.js +18 -0
  244. package/dist/chunks/store-sidebar-preferences-GWIOG2NH.js +16 -0
  245. package/dist/chunks/store-subagents-T7R2Z6TB.js +67 -0
  246. package/dist/chunks/store-task-inbox-JJTBW76C.js +33 -0
  247. package/dist/chunks/store-task-inventory-OB3F2APC.js +10 -0
  248. package/dist/chunks/store-taskset-drafts-EKQWWFYQ.js +9 -0
  249. package/dist/chunks/store-training-G6YLFSIR.js +70 -0
  250. package/dist/chunks/store-training-jobs-RC46YBF6.js +19 -0
  251. package/dist/chunks/store-training-models-6BA43IPP.js +49 -0
  252. package/dist/chunks/store-usage-IE2U2FD3.js +63 -0
  253. package/dist/chunks/store-work-evidence-QQDKM5AQ.js +8 -0
  254. package/dist/chunks/taskset-EQRFQBYM.js +2 -0
  255. package/dist/chunks/taskset-packages-XC6HEE3K.js +2 -0
  256. package/dist/chunks/{teams-bot-7I4BAUVO.js → teams-bot-EAPGPTHZ.js} +1 -1
  257. package/dist/chunks/training-UF6RPI4T.js +2 -0
  258. package/dist/chunks/web-search-CZ3NCLPY.js +2 -0
  259. package/dist/chunks/workspaces-EKKE5NAC.js +2 -0
  260. package/dist/cli.js +1 -1
  261. package/dist/index.js +1 -1
  262. package/dist/web/assets/App-CaRMZoxo.css +1 -0
  263. package/dist/web/assets/App-s-CJswyt.js +154 -0
  264. package/dist/web/assets/{AppDialog-BdusXgU0.js → AppDialog-t2Fx5tK3.js} +1 -1
  265. package/dist/web/assets/{AppTerminalPanel-C4uRpnBz.js → AppTerminalPanel-Dj1Y32oI.js} +2 -2
  266. package/dist/web/assets/AppsView-BYE5EBDJ.js +1 -0
  267. package/dist/web/assets/{BrowserSidebar-Bl7V6YO2.js → BrowserSidebar-jhWi4rVm.js} +1 -1
  268. package/dist/web/assets/{CartesianChart-BstFbsdn.js → CartesianChart-C1DIx0Ia.js} +1 -1
  269. package/dist/web/assets/{CollaborationTabs-B8YAf0c1.js → CollaborationTabs-Bdr-HmOL.js} +1 -1
  270. package/dist/web/assets/{CommandMenu-DZct7zUJ.js → CommandMenu-Ux2yOHAc.js} +1 -1
  271. package/dist/web/assets/{CommunityView-CR0-W-uG.js → CommunityView-DPEeVKFn.js} +1 -1
  272. package/dist/web/assets/{ComposerCreateImproveStrip-DR-Qo7b4.js → ComposerCreateImproveStrip-CEgh4OtN.js} +1 -1
  273. package/dist/web/assets/{GetStartedView-xqQoMMei.js → GetStartedView-CFHP0AaI.js} +1 -1
  274. package/dist/web/assets/HostedModelLearningReview-D8BGTPVN.js +1 -0
  275. package/dist/web/assets/{HostedModelLearningSettings-De3i9wF4.js → HostedModelLearningSettings-JS1S7vNO.js} +1 -1
  276. package/dist/web/assets/{LabModelVersionDetailPage-DAY1MmqP.js → LabModelVersionDetailPage-Dx5Q3xV2.js} +1 -1
  277. package/dist/web/assets/{LabSkillSidebar-DLnIgnry.js → LabSkillSidebar-BxffN-pN.js} +1 -1
  278. package/dist/web/assets/LabsRoute-CyYF8-dw.js +99 -0
  279. package/dist/web/assets/MainChatThread-DZpcFRFl.js +2 -0
  280. package/dist/web/assets/MainPane-5DTtwVCk.js +65 -0
  281. package/dist/web/assets/MainPane-BIM_UJ3q.css +1 -0
  282. package/dist/web/assets/{MarkdownText-gJMuefaJ.js → MarkdownText-BR4V6lNO.js} +24 -24
  283. package/dist/web/assets/{NativeSkillSidebar-Dlxb8iOC.js → NativeSkillSidebar-DU9IEgIO.js} +1 -1
  284. package/dist/web/assets/{NewExperienceSwitcher-DM-cqJ-K.js → NewExperienceSwitcher-mIy6FzCj.js} +1 -1
  285. package/dist/web/assets/{NewProjectDialog-Cu1q75gq.js → NewProjectDialog-RfTZTHxl.js} +1 -1
  286. package/dist/web/assets/{OutputsPage-DiXMkasl.js → OutputsPage-Cr1Spf7S.js} +1 -1
  287. package/dist/web/assets/{ProjectsPage-DqiBHiCB.js → ProjectsPage-CE6QUB-b.js} +1 -1
  288. package/dist/web/assets/RightChatPanelStack-T6VRWuHo.js +1 -0
  289. package/dist/web/assets/RightSidebarHomePanel-CK0rP3WT.js +1 -0
  290. package/dist/web/assets/ScheduledWorkPage-vOrYv8pp.js +1 -0
  291. package/dist/web/assets/SettingsView-DCKVrfjj.js +5 -0
  292. package/dist/web/assets/SettingsView-Dulr_xlq.css +1 -0
  293. package/dist/web/assets/{TeamChatView-DM0adMtj.js → TeamChatView-Bwrjr-vk.js} +2 -2
  294. package/dist/web/assets/{TerminalOverlay-CFlH51DD.js → TerminalOverlay-DhPoKZAq.js} +1 -1
  295. package/dist/web/assets/TrainingCreationPanel-BXHfohNm.js +1 -0
  296. package/dist/web/assets/{TrainingDraftPanel-Bbo3RRie.js → TrainingDraftPanel-C9cRX5qf.js} +1 -1
  297. package/dist/web/assets/{UsageSettingsSection-CSRjJUSa.js → UsageSettingsSection-CrdcSGeW.js} +1 -1
  298. package/dist/web/assets/{WorkSidebarPanel-DwlEMEoG.js → WorkSidebarPanel-DSSikNFQ.js} +1 -1
  299. package/dist/web/assets/WorkspaceDiffPanel-BAFo0CPN.js +14 -0
  300. package/dist/web/assets/WorkspaceEnvironmentMenu-BVHAhwnJ.js +63 -0
  301. package/dist/web/assets/WorkspaceGitDialogs-CwVoiDQ2.js +1 -0
  302. package/dist/web/assets/{WorkspaceMonacoEditor-BR4qxMgU.js → WorkspaceMonacoEditor-TxLyhzNp.js} +3 -3
  303. package/dist/web/assets/arrow-up-right-C9aE8Mfz.js +1 -0
  304. package/dist/web/assets/chunk-P3BRSSRD-DUGfuKA8.js +1 -0
  305. package/dist/web/assets/{clipboard-BZzZ82Bk.js → clipboard-Dk158Qp4.js} +1 -1
  306. package/dist/web/assets/{cloud-upload-CJPYPVl8.js → cloud-upload-k9eqBsHr.js} +1 -1
  307. package/dist/web/assets/{cssMode-WC4Rg1l-.js → cssMode-CO35ARZp.js} +1 -1
  308. package/dist/web/assets/{folder-open-sLZJxLQy.js → folder-open-sYgceW_f.js} +1 -1
  309. package/dist/web/assets/folder-plus-CS0R49m9.js +1 -0
  310. package/dist/web/assets/{git-commit-horizontal-Cotm7KEC.js → git-commit-horizontal-DrGxH2h4.js} +1 -1
  311. package/dist/web/assets/{htmlMode-C6oZGeaB.js → htmlMode-REMmzdfq.js} +1 -1
  312. package/dist/web/assets/index-3iPNbbER.css +1 -0
  313. package/dist/web/assets/{index-BxWTVKtn.js → index-C8aCGagb.js} +2 -2
  314. package/dist/web/assets/info-DLdbiUrh.js +1 -0
  315. package/dist/web/assets/{jsonMode-BET4LQIn.js → jsonMode-KEdMfkIf.js} +1 -1
  316. package/dist/web/assets/{lspLanguageFeatures-BPxA_-Kg.js → lspLanguageFeatures-5KZwEoxW.js} +1 -1
  317. package/dist/web/assets/minimize-2-CqcI4zcM.js +1 -0
  318. package/dist/web/assets/{monaco.contribution-DFzEyaHi.js → monaco.contribution-BJGj65F9.js} +2 -2
  319. package/dist/web/assets/{monaco.contribution-DXzyQfVi.js → monaco.contribution-Cly9Wt7L.js} +2 -2
  320. package/dist/web/assets/{monaco.contribution-BH6kkO4b.js → monaco.contribution-DO10L0zW.js} +2 -2
  321. package/dist/web/assets/{monaco.contribution-7AUuf2NS.js → monaco.contribution-omszXBEj.js} +2 -2
  322. package/dist/web/assets/monitor-BFVCcbxp.js +1 -0
  323. package/dist/web/assets/play-C469pVZq.js +1 -0
  324. package/dist/web/assets/{python-PzBkTjWx.js → python-Dw0YcVy9.js} +1 -1
  325. package/dist/web/assets/{save-DpezrtH2.js → save-CtSjPydi.js} +1 -1
  326. package/dist/web/assets/square-BuImvLhT.js +1 -0
  327. package/dist/web/assets/{toggleHighContrast-Cto-fOXm.js → toggleHighContrast-DjCO9lIP.js} +1 -1
  328. package/dist/web/assets/{tsMode-BYA4LNc6.js → tsMode-BAOnxKd6.js} +1 -1
  329. package/dist/web/assets/{upload-C5YFNgtS.js → upload-2JkFZo3h.js} +1 -1
  330. package/dist/web/assets/{useLocalAgentSchedules-CnyTsqlf.js → useLocalAgentSchedules-BNqAisfS.js} +1 -1
  331. package/dist/web/assets/useProviderSettings-C4L4wDoh.js +5 -0
  332. package/dist/web/assets/{useProviderSettings-Bw-csWbH.css → useProviderSettings-CmL_BaxP.css} +1 -1
  333. package/dist/web/assets/{useSessionTurnCache-DICuJSJW.js → useSessionTurnCache-BHU2-Jmz.js} +1 -1
  334. package/dist/web/assets/{wifi-off-nzHj7JXp.js → wifi-off-CpOAH62M.js} +1 -1
  335. package/dist/web/assets/{workers-Dboaw6f_.js → workers-0QvlA2T5.js} +1 -1
  336. package/dist/web/assets/{yaml-uuY5JmO8.js → yaml-BK3qxo7D.js} +1 -1
  337. package/dist/web/index.html +2 -2
  338. package/package.json +3 -3
  339. package/dist/chunks/actions-command-DSO6YOEE.js +0 -2
  340. package/dist/chunks/app-server-runtime-7AXV6JZI.js +0 -2
  341. package/dist/chunks/apps-TM74FFQB.js +0 -2
  342. package/dist/chunks/chunk-2JO2KWT3.js +0 -5
  343. package/dist/chunks/chunk-2SPZYBDN.js +0 -16
  344. package/dist/chunks/chunk-37DXASQL.js +0 -191
  345. package/dist/chunks/chunk-4EEH7MEC.js +0 -2
  346. package/dist/chunks/chunk-4TZHH5FC.js +0 -2409
  347. package/dist/chunks/chunk-5TNDPNS3.js +0 -2
  348. package/dist/chunks/chunk-6JAN4RMN.js +0 -42
  349. package/dist/chunks/chunk-7QEE4PBI.js +0 -8
  350. package/dist/chunks/chunk-BX4J2VDU.js +0 -2
  351. package/dist/chunks/chunk-DALJMSJG.js +0 -33
  352. package/dist/chunks/chunk-EMKZVP7Z.js +0 -2
  353. package/dist/chunks/chunk-FPUUZQUP.js +0 -6
  354. package/dist/chunks/chunk-GCOUYYHG.js +0 -5
  355. package/dist/chunks/chunk-GS2NKNKG.js +0 -4
  356. package/dist/chunks/chunk-H2VT22JK.js +0 -2
  357. package/dist/chunks/chunk-HA7EFTPF.js +0 -23
  358. package/dist/chunks/chunk-IKWDL3RB.js +0 -17
  359. package/dist/chunks/chunk-NHFGEVVH.js +0 -518
  360. package/dist/chunks/chunk-NNF6KCHD.js +0 -3
  361. package/dist/chunks/chunk-PJM2G7SG.js +0 -21
  362. package/dist/chunks/chunk-PQHTZ5CP.js +0 -2
  363. package/dist/chunks/chunk-PYABBF53.js +0 -53
  364. package/dist/chunks/chunk-QRWPEW3Z.js +0 -24
  365. package/dist/chunks/chunk-QXVIIM4T.js +0 -2
  366. package/dist/chunks/chunk-SDEDAHV6.js +0 -160
  367. package/dist/chunks/chunk-TGIB24K4.js +0 -22
  368. package/dist/chunks/chunk-UE3DMPGM.js +0 -3
  369. package/dist/chunks/chunk-USKE34VR.js +0 -9
  370. package/dist/chunks/chunk-USMZT5FZ.js +0 -18
  371. package/dist/chunks/chunk-WV2APYWG.js +0 -2
  372. package/dist/chunks/chunk-YIB3J4RC.js +0 -2
  373. package/dist/chunks/chunk-Z3D4C7BG.js +0 -12
  374. package/dist/chunks/cli-JVB345H2.js +0 -2
  375. package/dist/chunks/configuration-command-MATM4XR5.js +0 -2
  376. package/dist/chunks/connected-evidence-YDPGNHLP.js +0 -2
  377. package/dist/chunks/core-commands-MTV4EKXY.js +0 -2
  378. package/dist/chunks/datasets-CP3IT47T.js +0 -2
  379. package/dist/chunks/desktop-test-IAZC5MAH.js +0 -3
  380. package/dist/chunks/dist-4HV2W6V4.js +0 -2
  381. package/dist/chunks/dist-SAABJU5F.js +0 -2
  382. package/dist/chunks/evaluation-coordination-EPHLZXYM.js +0 -2
  383. package/dist/chunks/experiment-improvements-6JTOPA74.js +0 -2
  384. package/dist/chunks/experiments-XHPFGECH.js +0 -2
  385. package/dist/chunks/extension-GX7DLW2X.js +0 -4
  386. package/dist/chunks/hosted-experiment-improvement-HAB3UE6A.js +0 -3
  387. package/dist/chunks/hosted-harness-runtime-YM23QNDK.js +0 -2
  388. package/dist/chunks/hosted-profile-candidate-EOBGKQAS.js +0 -3
  389. package/dist/chunks/hosted-profile-compiler-SCVJI2CP.js +0 -2
  390. package/dist/chunks/hosted-profile-evaluation-control-RJ6XJZCS.js +0 -2
  391. package/dist/chunks/hosted-profile-evaluation-inspection-OC4XNGL2.js +0 -3
  392. package/dist/chunks/hosted-profile-evaluation-preparation-ZD4FM3FD.js +0 -3
  393. package/dist/chunks/human-review-AAVMISBF.js +0 -2
  394. package/dist/chunks/import-V3HUGRHR.js +0 -4
  395. package/dist/chunks/learning-FNBEIAY6.js +0 -2
  396. package/dist/chunks/opchat-QK43DXTY.js +0 -3
  397. package/dist/chunks/organizations-SRPAWKC7.js +0 -2
  398. package/dist/chunks/profile-C6CQNVYE.js +0 -3
  399. package/dist/chunks/project-agent-GZV5HNYI.js +0 -2
  400. package/dist/chunks/sandbox-command-4TJXQTKT.js +0 -2
  401. package/dist/chunks/src-NE6R4XC6.js +0 -329
  402. package/dist/chunks/taskset-LUG3ZU6J.js +0 -2
  403. package/dist/chunks/training-XHE6FVII.js +0 -2
  404. package/dist/chunks/workspaces-MFZ3OO6O.js +0 -2
  405. package/dist/web/assets/App-CO2F717V.css +0 -1
  406. package/dist/web/assets/App-CuhaCsfb.js +0 -235
  407. package/dist/web/assets/AppsView-BS1czXUP.js +0 -1
  408. package/dist/web/assets/HostedModelLearningReview-CHxxf_Lu.js +0 -1
  409. package/dist/web/assets/LabsRoute-CXJRJMhr.js +0 -99
  410. package/dist/web/assets/MainChatThread-BwAla81W.js +0 -2
  411. package/dist/web/assets/MainPane-CakOBCHw.js +0 -19
  412. package/dist/web/assets/MainPane-DOWsSew1.css +0 -1
  413. package/dist/web/assets/RightChatPanelStack-VaOOmxwd.js +0 -1
  414. package/dist/web/assets/RightSidebarHomePanel-CeSFJM5s.js +0 -1
  415. package/dist/web/assets/ScheduledWorkPage-D1jRQxFs.js +0 -1
  416. package/dist/web/assets/SettingsView-BnANbPLS.css +0 -1
  417. package/dist/web/assets/SettingsView-RA9OXgcu.js +0 -5
  418. package/dist/web/assets/TrainingCreationPanel-CgIBVGha.js +0 -1
  419. package/dist/web/assets/WorkspaceDiffPanel-pGVezNMw.js +0 -14
  420. package/dist/web/assets/WorkspaceEnvironmentMenu-Byjngd9V.js +0 -32
  421. package/dist/web/assets/WorkspaceGitDialogs-Dgmg-6XG.js +0 -1
  422. package/dist/web/assets/arrow-up-right-H0pvnH2s.js +0 -1
  423. package/dist/web/assets/chunk-UHVJOMWN-BqXRe639.js +0 -1
  424. package/dist/web/assets/folder-plus-C84wrpt_.js +0 -1
  425. package/dist/web/assets/index-dSmk3FLJ.css +0 -1
  426. package/dist/web/assets/info-Dc81lEfw.js +0 -1
  427. package/dist/web/assets/minimize-2-Bs7MVN3C.js +0 -1
  428. package/dist/web/assets/monitor-DXL019Wf.js +0 -1
  429. package/dist/web/assets/play-CXkxUZeU.js +0 -1
  430. package/dist/web/assets/square-oy7f5Ce6.js +0 -1
  431. package/dist/web/assets/useProviderSettings-B_KeQjE5.js +0 -5
  432. /package/dist/chunks/{chunk-OGPHXXCD.js → chunk-BT5YNE5U.js} +0 -0
@@ -1,33 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{C as Sr,G as vr,J as Ir,K as Lr,L as Or,U as ee,W as nt,i as yr,p as wr,q as Tr,r as Er,s as Ar,t as br}from"./chunk-TGIB24K4.js";import{q as fr}from"./chunk-NNF6KCHD.js";import{b as u}from"./chunk-ES2ISFJC.js";import{c as y,d as mr,e as P,f as hr,g as gr,h as _,i as Fe,j as _r,k as Rt,l as Le,m as Cr,n as D,o as fe,p as H,r as B}from"./chunk-H7IWJN7L.js";import{a as c}from"./chunk-FTQLQJQV.js";import{randomUUID as Mt,createHash as ro}from"node:crypto";import{promises as V,constants as Pt}from"node:fs";import je from"node:path";var no="missing";function $(e){return e===null?no:ro("sha256").update(e).digest("hex")}c($,"fileRevision");async function A(e){Le(je.dirname(e));try{let t=await V.lstat(e);if(!t.isFile()||t.isSymbolicLink())throw new y({code:"UNSAFE_STORAGE_PATH",path:e,message:"Storage must be a regular file, not a symbolic link.",action:"Use a regular file in the OpenPond home."});return await V.readFile(e,"utf8")}catch(t){if(P(t))return null;throw t}}c(A,"readOptionalFile");async function U(e){if(Le(e),await V.mkdir(e,{recursive:!0,mode:448}),(await V.lstat(e)).isSymbolicLink())throw new y({code:"UNSAFE_STORAGE_PATH",path:e,message:"Managed storage directories cannot be symbolic links.",action:"Select a regular local storage folder."});Rt(e)}c(U,"privateDirectory");async function I(e,t,r={}){let n=je.dirname(e);r.privateParent===!1?await V.mkdir(n,{recursive:!0,mode:448}):await U(n);let o=await V.lstat(e).catch(a=>{if(P(a))return null;throw a});if(o&&(!o.isFile()||o.isSymbolicLink()))throw new y({code:"UNSAFE_STORAGE_PATH",path:e,message:"Cannot replace a non-regular storage file.",action:"Use a regular file in the OpenPond home."});let i=je.join(n,`.${je.basename(e)}.${process.pid}.${Mt()}.tmp`);try{let a=await V.open(i,Pt.O_CREAT|Pt.O_EXCL|Pt.O_WRONLY,384);try{await a.writeFile(t),await a.sync()}finally{await a.close()}if(await V.rename(i,e),process.platform!=="win32"){let s=await V.open(n,"r");try{await s.sync()}finally{await s.close()}}}finally{await V.rm(i,{force:!0})}}c(I,"atomicWriteFile");async function L(e,t,r=1e4){let n=await _e(e,r);try{return await t()}finally{await n()}}c(L,"withFileLock");async function oo(e,t){let r=`${e}.${process.pid}.${Mt()}.candidate`;try{let n=await V.open(r,"wx",384);try{await n.writeFile(t),await n.sync()}finally{await n.close()}await V.link(r,e)}finally{await V.rm(r,{force:!0})}}c(oo,"publishLock");async function _e(e,t=1e4){await U(je.dirname(e));let r=`${e}.lock`,n={pid:process.pid,nonce:Mt()},o=JSON.stringify(n),i=Date.now()+t;for(;;)try{await oo(r,o);break}catch(a){if(a.code!=="EEXIST")throw a;let s=await A(r);if(s){let l;try{l=JSON.parse(s).pid}catch{}if(typeof l=="number"&&Number.isInteger(l)&&l>0&&io(l)){let f=await _e(`${r}.reclaim`,Math.max(0,i-Date.now()));try{await A(r)===s&&await V.unlink(r).catch(p=>{if(!P(p))throw p})}finally{await f()}}}if(Date.now()>=i)throw new y({code:"STORAGE_BUSY",path:e,message:"Another OpenPond process is updating this storage.",action:"Wait for that process to finish, then retry. Do not delete a live process lock."});await new Promise(l=>setTimeout(l,25))}return async()=>{await A(r)===o&&await V.unlink(r)}}c(_e,"acquireFileLock");function io(e){try{return process.kill(e,0),!1}catch(t){return t.code==="ESRCH"}}c(io,"processIsDead");async function M(e,t){let r=await A(e);if(r===null)return t();try{return JSON.parse(r)}catch(n){throw new y({code:"INVALID_STORAGE_JSON",path:e,message:"A storage file contains invalid JSON.",action:"Restore a verified backup or correct the file, then retry."},{cause:n})}}c(M,"readJsonFile");async function aa(e,t,r){return L(e,async()=>{let n=await r(await M(e,t));return await I(e,`${JSON.stringify(n,null,2)}
3
- `),n})}c(aa,"updateJsonFile");var G=u.string().trim().min(1),ot=u.string().trim().max(4096),it=G.max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Reserved identifier"),at=G.max(2048).refine(e=>{try{let t=new URL(e);return["http:","https:"].includes(t.protocol)&&!t.username&&!t.password&&!t.hash&&![...t.searchParams.keys()].some(r=>/(?:token|secret|password|authorization|api[_-]?key|credential)/i.test(r))}catch{return!1}},"Use an HTTP endpoint without embedded credentials; configure authentication through a credential reference."),xr=u.strictObject({provider_id:fr,model_id:G.max(300)}),Ut=u.discriminatedUnion("mode",[u.strictObject({mode:u.literal("inherit")}),u.strictObject({mode:u.literal("custom"),ref:xr})]),kr=u.discriminatedUnion("source",[u.strictObject({source:u.literal("secret"),id:it}),u.strictObject({source:u.literal("env"),name:G.regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(160)})]),ao=u.strictObject({handle:G,base_url:at.optional(),api_base_url:at.optional(),chat_api_base_url:at.optional(),environment:G.optional(),credential:kr.optional(),enabled:u.boolean().optional()}),so=u.strictObject({enabled:u.boolean().optional(),binary_path:G.max(4096).optional(),source_home:G.max(4096).optional(),native_mode:G.max(200).optional(),native_options:u.record(u.string().max(200),u.string().max(300)).optional(),base_url:at.optional(),default_model:G.max(300).optional(),model_overrides:u.array(G.max(300)).max(500).optional(),credential:kr.optional()}),Dt=u.strictObject({mode:u.enum(["auto","disabled","custom"]).optional(),custom_command:ot.optional()}),Nr=u.union([u.number().int().min(1).max(32),u.literal("unlimited")]),co=u.strictObject({enabled:u.boolean().optional(),model:Ut.optional(),isolation_mode:Tr.optional(),max_concurrent_runs:u.number().int().min(1).max(16).optional(),tool_policy:Er.optional(),background:u.boolean().optional(),peer_messages:Ar.optional()}),lo=u.strictObject({source:u.enum(["local","github","openpond_git"]),repository_id:G,profile_id:G}),Ft=u.strictObject({schema_version:u.literal(1),chat:u.strictObject({model:xr.optional(),steer_active_responses:u.boolean().optional()}).optional(),codex:u.strictObject({reasoning_effort:Or.optional()}).optional(),permissions:u.strictObject({command_access:Lr.optional(),codex_mode:Ir.optional()}).optional(),context_compaction:u.strictObject({auto_enabled:u.boolean().optional(),trigger_percent:u.number().int().min(50).max(95).optional(),summary_model:u.literal("same_model").optional()}).optional(),subagents:u.strictObject({enabled:u.boolean().optional(),delegation_mode:br.optional(),default_model:Ut.optional(),max_concurrent_runs:u.number().int().min(1).max(32).optional(),max_concurrent_runs_per_provider:Nr.optional(),max_concurrent_runs_per_workspace_target:Nr.optional(),roles:u.record(wr,co).refine(e=>Object.keys(e).length<=64,"At most 64 roles").optional()}).optional(),projects:u.strictObject({branch_prefix:u.string().trim().max(48).optional(),new_project_directory:ot.optional()}).optional(),defaults:u.strictObject({account_id:it.optional(),team_id:G.max(191).optional(),profile_ref:lo.optional()}).optional(),editor:u.strictObject({language_servers:u.enum(["auto","off"]).optional(),diagnostics_while_editing:u.boolean().optional(),check_on_save:u.boolean().optional(),languages:u.strictObject({typescript:Dt.optional(),python:Dt.optional(),rust:Dt.optional()}).optional()}).optional(),training:u.strictObject({default_model:Ut.optional(),creation_mode:u.enum(["defaults","customize"]).optional(),auto_approve_evidence:u.boolean().optional()}).optional(),notifications:u.strictObject({team_chat:u.enum(["all","direct_mentions","none"]).optional()}).optional(),ui:u.strictObject({advanced_workspace_controls:u.boolean().optional()}).optional(),runtime:u.strictObject({execution_mode:u.enum(["local","hosted"]).optional(),mode:u.enum(["general","builder"]).optional()}).optional(),personalization:u.strictObject({active:G.regex(/^(builtin|custom):[a-zA-Z0-9_-]+$/).optional(),mode:u.enum(["enabled","disabled"]).optional(),user_instructions:ot.optional()}).optional(),storage:u.strictObject({datasets_dir:ot.optional()}).optional(),accounts:u.record(it,ao).optional(),providers:u.record(it,so).optional()});function oe(e,t="user"){let r=Ft.parse(e);if(t==="project"){let n=new Set(["schema_version","chat","codex","permissions","context_compaction","subagents","projects","editor"]);for(let o of Object.keys(r))if(!n.has(o))throw new Error(`Setting ${o} is not permitted in project configuration.`);if(r.projects?.new_project_directory!==void 0)throw new Error("projects.new_project_directory is a user-only setting.");for(let o of Object.values(r.editor?.languages??{}))if(o.custom_command!==void 0)throw new Error("Custom editor commands must be configured in user settings.");if(r.permissions?.command_access==="full-access"||r.permissions?.codex_mode==="full-access"||r.permissions?.codex_mode==="auto-review")throw new Error("Project configuration can restrict permissions but cannot grant additional access.");for(let o of Object.values(r.subagents?.roles??{}))if(o.tool_policy&&o.tool_policy!=="read_only")throw new Error("Project roles cannot grant additional tool access.")}return r}c(oe,"validateConfigDocument");import{promises as Wt}from"node:fs";import Oe from"node:path";var st={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExperimentalRestProperty:["argument"],ExperimentalSpreadProperty:["argument"],ExportAllDeclaration:["exported","source","attributes"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source","attributes"],ExportSpecifier:["local","exported"],ExpressionStatement:["expression"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportAttribute:["key","value"],ImportDeclaration:["specifiers","source","attributes"],ImportDefaultSpecifier:["local"],ImportExpression:["source","options"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXClosingFragment:[],JSXElement:["openingElement","children","closingElement"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXFragment:["openingFragment","children","closingFragment"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXOpeningFragment:[],JSXSpreadAttribute:["argument"],JSXSpreadChild:["expression"],JSXText:[],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],StaticBlock:["body"],Super:[],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},uo=Object.keys(st);for(let e of uo)Object.freeze(st[e]);Object.freeze(st);var Rr=st;function Pr(e){let t=Object.assign({},Rr);for(let r of Object.keys(e))if(Object.hasOwn(t,r)){let n=new Set(e[r]);for(let o of t[r])n.add(o);t[r]=Object.freeze(Array.from(n))}else t[r]=Object.freeze(Array.from(e[r]));return Object.freeze(t)}c(Pr,"unionWith");function ye(e){return e[e.length-1]??null}c(ye,"last");function Gt(e){return e.type==="TOMLBare"?e.name:e.value}c(Gt,"toKeyName");var Hr=class{static{c(this,"TOMLVerImpl")}constructor(e,t){this.major=e,this.minor=t}lt(e,t){return this.major<e||this.major===e&&this.minor<t}gte(e,t){return this.major>e||this.major===e&&this.minor>=t}},Mr=new Hr(1,0),He=new Hr(1,1),po=He,fo={"1.0":Mr,"1.0.0":Mr,"1.1":He,"1.1.0":He,latest:He,next:He};function Jr(e){return e&&fo[e]||po}c(Jr,"getTOMLVer");var Dr={"unterminated-string":"Unterminated string constant","unterminated-table-key":"Unterminated table-key","unterminated-array":"Unterminated array","unterminated-inline-table":"Unterminated inline table","missing-key":"Empty bare keys are not allowed","missing-newline":"Must be a newline","missing-equals-sign":"Expected equal (=) token","missing-value":"Unspecified values are invalid","missing-comma":"Expected comma (,) token","dupe-keys":"Defining a key multiple times is invalid","unexpected-char":"Unexpected character","unexpected-token":"Unexpected token","invalid-control-character":"Control characters (codes < 0x1f and 0x7f) are not allowed","invalid-comment-character":"Invalid code point {{cp}} within comments","invalid-key-value-newline":"The key, equals sign, and value must be on the same line","invalid-inline-table-newline":"No newlines are allowed between the curly braces unless they are valid within a value","invalid-underscore":"Underscores are allowed between digits","invalid-space":"Unexpected spaces","invalid-three-quotes":"Three or more quotes are not permitted","invalid-date":"Unexpected invalid date","invalid-time":"Unexpected invalid time","invalid-leading-zero":"Leading zeros are not allowed","invalid-trailing-comma-in-inline-table":"Trailing comma is not permitted in an inline table","invalid-char-in-escape-sequence":"Invalid character in escape sequence","invalid-consecutive-dots-in-key":"Consecutive dots are not permitted in keys","invalid-code-point":"Invalid code point {{cp}}","invalid-trailing-dot-in-key":"Keys cannot end with a dot","invalid-leading-dot-in-key":"Keys cannot start with a dot"};function mo(e,t){return t?Dr[e].replace(/\{\{(.*?)\}\}/gu,(r,n)=>n in t?t[n]:`{{${n}}}`):Dr[e]}c(mo,"getMessage");var zr=class extends SyntaxError{static{c(this,"ParseError")}constructor(e,t,r,n,o){super(mo(e,o)),this.index=t,this.lineNumber=r,this.column=n}},d={EOF:-1,NULL:0,SOH:1,BACKSPACE:8,TABULATION:9,LINE_FEED:10,FORM_FEED:12,CARRIAGE_RETURN:13,ESCAPE:27,SO:14,US:31,SPACE:32,QUOTATION_MARK:34,HASH:35,SINGLE_QUOTE:39,PLUS_SIGN:43,COMMA:44,DASH:45,DOT:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_7:55,DIGIT_9:57,COLON:58,EQUALS_SIGN:61,LATIN_CAPITAL_A:65,LATIN_CAPITAL_E:69,LATIN_CAPITAL_F:70,LATIN_CAPITAL_T:84,LATIN_CAPITAL_U:85,LATIN_CAPITAL_Z:90,LEFT_BRACKET:91,BACKSLASH:92,RIGHT_BRACKET:93,UNDERSCORE:95,LATIN_SMALL_A:97,LATIN_SMALL_B:98,LATIN_SMALL_E:101,LATIN_SMALL_F:102,LATIN_SMALL_I:105,LATIN_SMALL_L:108,LATIN_SMALL_N:110,LATIN_SMALL_O:111,LATIN_SMALL_R:114,LATIN_SMALL_S:115,LATIN_SMALL_T:116,LATIN_SMALL_U:117,LATIN_SMALL_X:120,LATIN_SMALL_Z:122,LEFT_BRACE:123,RIGHT_BRACE:125,TILDE:126,DELETE:127,PAD:128,SUPERSCRIPT_TWO:178,SUPERSCRIPT_THREE:179,SUPERSCRIPT_ONE:185,VULGAR_FRACTION_ONE_QUARTER:188,VULGAR_FRACTION_THREE_QUARTERS:190,LATIN_CAPITAL_LETTER_A_WITH_GRAVE:192,LATIN_CAPITAL_LETTER_O_WITH_DIAERESIS:214,LATIN_CAPITAL_LETTER_O_WITH_STROKE:216,LATIN_SMALL_LETTER_O_WITH_DIAERESIS:246,LATIN_SMALL_LETTER_O_WITH_STROKE:248,GREEK_SMALL_REVERSED_DOTTED_LUNATE_SIGMA_SYMBOL:891,GREEK_CAPITAL_LETTER_YOT:895,CP_1FFF:8191,ZERO_WIDTH_NON_JOINER:8204,ZERO_WIDTH_JOINER:8205,UNDERTIE:8255,CHARACTER_TIE:8256,SUPERSCRIPT_ZERO:8304,CP_218F:8591,CIRCLED_DIGIT_ONE:9312,NEGATIVE_CIRCLED_DIGIT_ZERO:9471,GLAGOLITIC_CAPITAL_LETTER_AZU:11264,CP_2FEF:12271,IDEOGRAPHIC_COMMA:12289,CP_D7FF:55295,CP_E000:57344,CJK_COMPATIBILITY_IDEOGRAPH_F900:63744,ARABIC_LIGATURE_SALAAMUHU_ALAYNAA:64975,ARABIC_LIGATURE_SALLA_USED_AS_KORANIC_STOP_SIGN_ISOLATED_FORM:65008,REPLACEMENT_CHARACTER:65533,LINEAR_B_SYLLABLE_B008_A:65536,CP_EFFFF:983039,CP_10FFFF:1114111};function ho(e){return e>=d.NULL&&e<=d.US}c(ho,"isControl");function Be(e){return e===d.TABULATION||e===d.SPACE}c(Be,"isWhitespace");function Ur(e){return e===d.LINE_FEED||e===d.CARRIAGE_RETURN}c(Ur,"isEOL");function go(e){return e>=d.LATIN_CAPITAL_A&&e<=d.LATIN_CAPITAL_Z}c(go,"isUpperLetter");function _o(e){return e>=d.LATIN_SMALL_A&&e<=d.LATIN_SMALL_Z}c(_o,"isLowerLetter");function yo(e){return _o(e)||go(e)}c(yo,"isLetter");function x(e){return e>=d.DIGIT_0&&e<=d.DIGIT_9}c(x,"isDigit");function Fr(e){return x(e)||e>=d.LATIN_SMALL_A&&e<=d.LATIN_SMALL_F||e>=d.LATIN_CAPITAL_A&&e<=d.LATIN_CAPITAL_F}c(Fr,"isHexDig");function wo(e){return e>=d.DIGIT_0&&e<=d.DIGIT_7}c(wo,"isOctalDig");function To(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}c(To,"isUnicodeScalarValue");function Eo(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>>1,i=e[o];if(i===t)return o+1;i<t?r=o+1:n=o}return r}c(Eo,"sortedLastIndex");var Ao=class{static{c(this,"Locations")}constructor(){this.offsets=[]}addOffset(e){for(let t=this.offsets.length-1;t>=0;t--){let r=this.offsets[t];if(r===e)return;if(r<e)break}this.offsets.push(e)}getLocFromIndex(e){let t=Eo(this.offsets,e)+1;return{line:t,column:e-(t===1?0:this.offsets[t-2])}}},bo=class{static{c(this,"CodePointIterator")}constructor(e){this.locs=new Ao,this.lastCodePoint=d.NULL,this.start=-1,this.end=0,this.text=e}next(){return this.lastCodePoint===d.EOF?d.EOF:this.lastCodePoint=this.moveAt(this.end)}getLocFromIndex(e){return this.locs.getLocFromIndex(e)}eat(e){return this.text.codePointAt(this.end)===e?(this.next(),!0):!1}moveAt(e){this.start=this.end=e;let t=this.text.codePointAt(this.start)??d.EOF;if(t===d.EOF)return this.end=this.start,t;if(this.end+=t>=65536?2:1,t===d.LINE_FEED)this.locs.addOffset(this.end);else if(t===d.CARRIAGE_RETURN)return this.text.codePointAt(this.end)===d.LINE_FEED&&(this.end++,this.locs.addOffset(this.end)),d.LINE_FEED;return t}},So=typeof BigInt<"u",vo={16:"0x",10:"",8:"0o",2:"0b"},Wr={[d.QUOTATION_MARK]:d.QUOTATION_MARK,[d.BACKSLASH]:d.BACKSLASH,[d.LATIN_SMALL_B]:d.BACKSPACE,[d.LATIN_SMALL_F]:d.FORM_FEED,[d.LATIN_SMALL_N]:d.LINE_FEED,[d.LATIN_SMALL_R]:d.CARRIAGE_RETURN,[d.LATIN_SMALL_T]:d.TABULATION},Io={...Wr,[d.LATIN_SMALL_E]:d.ESCAPE},Lo=class{static{c(this,"Tokenizer")}constructor(e,t){this.backCode=!1,this.lastCodePoint=d.NULL,this.state="DATA",this.token=null,this.tokenStart=-1,this.valuesEnabled=!1,this.text=e,this.parserOptions=t||{},this.codePointIterator=new bo(e),this.tomlVersion=Jr(this.parserOptions.tomlVersion),this.ESCAPES=this.tomlVersion.gte(1,1)?Io:Wr}get start(){return this.codePointIterator.start}get end(){return this.codePointIterator.end}getLocFromIndex(e){return this.codePointIterator.getLocFromIndex(e)}reportParseError(e,t){let r=this.codePointIterator.start,n=this.codePointIterator.getLocFromIndex(r);throw new zr(e,r,n.line,n.column,t)}nextToken(){let e=this.token;if(e!=null)return this.token=null,e;let t=this.lastCodePoint;for(;t!==d.EOF&&!this.token;){t=this.nextCode();let r=this[this.state](t);if(!r)throw new Error(`Unknown error: pre state=${this.state}`);this.state=r}return e=this.token,this.token=null,e}nextCode(){return this.lastCodePoint===d.EOF?d.EOF:this.backCode?(this.backCode=!1,this.lastCodePoint):this.lastCodePoint=this.codePointIterator.next()}eatCode(e){return this.lastCodePoint===d.EOF?!1:this.backCode?this.lastCodePoint===e?(this.backCode=!1,!0):!1:this.codePointIterator.eat(e)}moveAt(e){this.backCode&&(this.backCode=!1),this.lastCodePoint=this.codePointIterator.moveAt(e)}back(e){return this.backCode=!0,e}punctuatorToken(){this.startToken(),this.endToken("Punctuator","end")}startToken(){this.tokenStart=this.codePointIterator.start}endToken(e,t,r,n){let{tokenStart:o}=this,i=this.codePointIterator[t],a=[o,i],s={start:this.codePointIterator.getLocFromIndex(o),end:this.codePointIterator.getLocFromIndex(i)};if(e==="Block")this.token={type:e,value:this.text.slice(o+1,i),range:a,loc:s};else{let l,f=this.text.slice(o,i);if(e==="BasicString"||e==="LiteralString"||e==="MultiLineBasicString"||e==="MultiLineLiteralString")l={type:e,value:f,string:r,range:a,loc:s};else if(e==="Integer"){let p=r;l={type:e,value:f,number:parseInt(p,n),bigint:So?BigInt(vo[n]+p):null,range:a,loc:s}}else e==="Float"?l={type:e,value:f,number:r,range:a,loc:s}:e==="Boolean"?l={type:e,value:f,boolean:r,range:a,loc:s}:e==="LocalDate"||e==="LocalTime"||e==="LocalDateTime"||e==="OffsetDateTime"?l={type:e,value:f,date:r,range:a,loc:s}:l={type:e,value:f,range:a,loc:s};this.token=l}}DATA(e){for(;Be(e)||Ur(e);)e=this.nextCode();if(e===d.HASH)return this.startToken(),"COMMENT";if(e===d.QUOTATION_MARK)return this.startToken(),"BASIC_STRING";if(e===d.SINGLE_QUOTE)return this.startToken(),"LITERAL_STRING";if(e===d.DOT||e===d.EQUALS_SIGN||e===d.LEFT_BRACKET||e===d.RIGHT_BRACKET||e===d.LEFT_BRACE||e===d.RIGHT_BRACE||e===d.COMMA)return this.punctuatorToken(),"DATA";if(this.valuesEnabled){if(e===d.DASH||e===d.PLUS_SIGN)return this.startToken(),"SIGN";if(e===d.LATIN_SMALL_N||e===d.LATIN_SMALL_I)return this.startToken(),this.back("NAN_OR_INF");if(x(e))return this.startToken(),this.back("NUMBER");if(e===d.LATIN_SMALL_T||e===d.LATIN_SMALL_F)return this.startToken(),this.back("BOOLEAN")}else if(jr(e,this.tomlVersion))return this.startToken(),"BARE";return e===d.EOF?"DATA":this.reportParseError("unexpected-char")}COMMENT(e){let t=this.tomlVersion.gte(1,1)?r=>{Oo(r)||this.reportParseError("invalid-comment-character",{cp:JSON.stringify(String.fromCodePoint(r)).slice(1,-1)})}:r=>{Ve(r)&&this.reportParseErrorControlChar()};for(;!Ur(e)&&e!==d.EOF;)t(e),e=this.nextCode();return this.endToken("Block","start"),"DATA"}BARE(e){for(;jr(e,this.tomlVersion);)e=this.nextCode();return this.endToken("Bare","start"),this.back("DATA")}BASIC_STRING(e){if(e===d.QUOTATION_MARK)return e=this.nextCode(),e===d.QUOTATION_MARK?"MULTI_LINE_BASIC_STRING":(this.endToken("BasicString","start",""),this.back("DATA"));let t=[];for(;e!==d.QUOTATION_MARK&&e!==d.EOF&&e!==d.LINE_FEED;){if(Ve(e))return this.reportParseErrorControlChar();if(e===d.BACKSLASH){e=this.nextCode();let r=this.ESCAPES[e];if(r){t.push(r),e=this.nextCode();continue}else if(e===d.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}else if(e===d.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}else if(e===d.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}return this.reportParseError("invalid-char-in-escape-sequence")}t.push(e),e=this.nextCode()}return e!==d.QUOTATION_MARK?this.reportParseError("unterminated-string"):(this.endToken("BasicString","end",String.fromCodePoint(...t)),"DATA")}MULTI_LINE_BASIC_STRING(e){let t=[];for(e===d.LINE_FEED&&(e=this.nextCode());e!==d.EOF;){if(e!==d.LINE_FEED&&Ve(e))return this.reportParseErrorControlChar();if(e===d.QUOTATION_MARK){let r=this.codePointIterator.start;if(this.eatCode(d.QUOTATION_MARK)&&this.eatCode(d.QUOTATION_MARK))return this.eatCode(d.QUOTATION_MARK)&&(t.push(d.QUOTATION_MARK),this.eatCode(d.QUOTATION_MARK)&&(t.push(d.QUOTATION_MARK),this.eatCode(d.QUOTATION_MARK)))?(this.moveAt(r),this.reportParseError("invalid-three-quotes")):(this.endToken("MultiLineBasicString","end",String.fromCodePoint(...t)),"DATA");this.moveAt(r)}if(e===d.BACKSLASH){e=this.nextCode();let r=this.ESCAPES[e];if(r){t.push(r),e=this.nextCode();continue}else if(e===d.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}else if(e===d.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}else if(e===d.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}else if(e===d.LINE_FEED){for(e=this.nextCode();Be(e)||e===d.LINE_FEED;)e=this.nextCode();continue}else if(Be(e)){let n=!0,o=this.codePointIterator.start,i;for(;(i=this.nextCode())!==d.EOF&&i!==d.LINE_FEED;)if(!Be(i)){this.moveAt(o),n=!1;break}if(n){for(e=this.nextCode();Be(e)||e===d.LINE_FEED;)e=this.nextCode();continue}}return this.reportParseError("invalid-char-in-escape-sequence")}t.push(e),e=this.nextCode()}return this.reportParseError("unterminated-string")}LITERAL_STRING(e){if(e===d.SINGLE_QUOTE)return e=this.nextCode(),e===d.SINGLE_QUOTE?"MULTI_LINE_LITERAL_STRING":(this.endToken("LiteralString","start",""),this.back("DATA"));let t=[];for(;e!==d.SINGLE_QUOTE&&e!==d.EOF&&e!==d.LINE_FEED;){if(Ve(e))return this.reportParseErrorControlChar();t.push(e),e=this.nextCode()}return e!==d.SINGLE_QUOTE?this.reportParseError("unterminated-string"):(this.endToken("LiteralString","end",String.fromCodePoint(...t)),"DATA")}MULTI_LINE_LITERAL_STRING(e){let t=[];for(e===d.LINE_FEED&&(e=this.nextCode());e!==d.EOF;){if(e!==d.LINE_FEED&&Ve(e))return this.reportParseErrorControlChar();if(e===d.SINGLE_QUOTE){let r=this.codePointIterator.start;if(this.eatCode(d.SINGLE_QUOTE)&&this.eatCode(d.SINGLE_QUOTE))return this.eatCode(d.SINGLE_QUOTE)&&(t.push(d.SINGLE_QUOTE),this.eatCode(d.SINGLE_QUOTE)&&(t.push(d.SINGLE_QUOTE),this.eatCode(d.SINGLE_QUOTE)))?(this.moveAt(r),this.reportParseError("invalid-three-quotes")):(this.endToken("MultiLineLiteralString","end",String.fromCodePoint(...t)),"DATA");this.moveAt(r)}t.push(e),e=this.nextCode()}return this.reportParseError("unterminated-string")}SIGN(e){return e===d.LATIN_SMALL_N||e===d.LATIN_SMALL_I?this.back("NAN_OR_INF"):x(e)?this.back("NUMBER"):this.reportParseError("unexpected-char")}NAN_OR_INF(e){if(e===d.LATIN_SMALL_N){let t=this.codePointIterator.start;if(this.eatCode(d.LATIN_SMALL_A)&&this.eatCode(d.LATIN_SMALL_N))return this.endToken("Float","end",NaN),"DATA";this.moveAt(t)}else if(e===d.LATIN_SMALL_I){let t=this.codePointIterator.start;if(this.eatCode(d.LATIN_SMALL_N)&&this.eatCode(d.LATIN_SMALL_F))return this.endToken("Float","end",this.text[this.tokenStart]==="-"?-1/0:1/0),"DATA";this.moveAt(t)}return this.reportParseError("unexpected-char")}NUMBER(e){let t=this.text[this.tokenStart],r=t==="+"?d.PLUS_SIGN:t==="-"?d.DASH:d.NULL;if(e===d.DIGIT_0){if(r===d.NULL){let a=this.codePointIterator.start,s=this.nextCode();if(x(s)){let l=this.nextCode();if(l===d.COLON)return this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(d.DIGIT_0,s)),minute:0,second:0},"TIME_MINUTE";if(x(l)){let f=this.nextCode();if(x(f)&&this.eatCode(d.DASH))return this.data={hasDate:!0,year:Number(String.fromCodePoint(d.DIGIT_0,s,l,f)),month:0,day:0,hour:0,minute:0,second:0},"DATE_MONTH"}return this.moveAt(a),this.reportParseError("invalid-leading-zero")}this.moveAt(a)}return e=this.nextCode(),e===d.LATIN_SMALL_X||e===d.LATIN_SMALL_O||e===d.LATIN_SMALL_B?r!==d.NULL?this.reportParseError("unexpected-char"):e===d.LATIN_SMALL_X?"HEX":e===d.LATIN_SMALL_O?"OCTAL":"BINARY":e===d.LATIN_SMALL_E||e===d.LATIN_CAPITAL_E?(this.data={minus:r===d.DASH,left:[d.DIGIT_0]},"EXPONENT_RIGHT"):e===d.DOT?(this.data={minus:r===d.DASH,absInt:[d.DIGIT_0]},"FRACTIONAL_RIGHT"):(this.endToken("Integer","start","0",10),this.back("DATA"))}let{out:n,nextCp:o,hasUnderscore:i}=this.parseDigits(e,x);return o===d.DASH&&r===d.NULL&&!i&&n.length===4?(this.data={hasDate:!0,year:Number(String.fromCodePoint(...n)),month:0,day:0,hour:0,minute:0,second:0},"DATE_MONTH"):o===d.COLON&&r===d.NULL&&!i&&n.length===2?(this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(...n)),minute:0,second:0},"TIME_MINUTE"):o===d.LATIN_SMALL_E||o===d.LATIN_CAPITAL_E?(this.data={minus:r===d.DASH,left:n},"EXPONENT_RIGHT"):o===d.DOT?(this.data={minus:r===d.DASH,absInt:n},"FRACTIONAL_RIGHT"):(this.endToken("Integer","start",r===d.DASH?String.fromCodePoint(d.DASH,...n):String.fromCodePoint(...n),10),this.back("DATA"))}HEX(e){let{out:t}=this.parseDigits(e,Fr);return this.endToken("Integer","start",String.fromCodePoint(...t),16),this.back("DATA")}OCTAL(e){let{out:t}=this.parseDigits(e,wo);return this.endToken("Integer","start",String.fromCodePoint(...t),8),this.back("DATA")}BINARY(e){let{out:t}=this.parseDigits(e,r=>r===d.DIGIT_0||r===d.DIGIT_1);return this.endToken("Integer","start",String.fromCodePoint(...t),2),this.back("DATA")}FRACTIONAL_RIGHT(e){let{minus:t,absInt:r}=this.data,{out:n,nextCp:o}=this.parseDigits(e,x),i=[...r,d.DOT,...n];if(o===d.LATIN_SMALL_E||o===d.LATIN_CAPITAL_E)return this.data={minus:t,left:i},"EXPONENT_RIGHT";let a=Number(t?String.fromCodePoint(d.DASH,...i):String.fromCodePoint(...i));return this.endToken("Float","start",a),this.back("DATA")}EXPONENT_RIGHT(e){let{left:t,minus:r}=this.data,n=!1;(e===d.DASH||e===d.PLUS_SIGN)&&(n=e===d.DASH,e=this.nextCode());let{out:o}=this.parseDigits(e,x),i=o;n&&i.unshift(d.DASH);let a=Number(r?String.fromCodePoint(d.DASH,...t,d.LATIN_SMALL_E,...i):String.fromCodePoint(...t,d.LATIN_SMALL_E,...i));return this.endToken("Float","start",a),this.back("DATA")}BOOLEAN(e){if(e===d.LATIN_SMALL_T){let t=this.codePointIterator.start;if(this.eatCode(d.LATIN_SMALL_R)&&this.eatCode(d.LATIN_SMALL_U)&&this.eatCode(d.LATIN_SMALL_E))return this.endToken("Boolean","end",!0),"DATA";this.moveAt(t)}else if(e===d.LATIN_SMALL_F){let t=this.codePointIterator.start;if(this.eatCode(d.LATIN_SMALL_A)&&this.eatCode(d.LATIN_SMALL_L)&&this.eatCode(d.LATIN_SMALL_S)&&this.eatCode(d.LATIN_SMALL_E))return this.endToken("Boolean","end",!1),"DATA";this.moveAt(t)}return this.reportParseError("unexpected-char")}DATE_MONTH(e){let t=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),e!==d.DASH)return this.reportParseError("unexpected-char");let r=this.codePointIterator.start,n=this.data;return n.month=Number(this.text.slice(t,r)),"DATE_DAY"}DATE_DAY(e){let t=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");let r=this.codePointIterator.end,n=this.data;if(n.day=Number(this.text.slice(t,r)),!No(n.year,n.month,n.day))return this.reportParseError("invalid-date");if(e=this.nextCode(),e===d.LATIN_CAPITAL_T||e===d.LATIN_SMALL_T)return"TIME_HOUR";if(e===d.SPACE){let i=this.codePointIterator.start;if(x(this.nextCode())&&x(this.nextCode()))return this.moveAt(i),"TIME_HOUR";this.moveAt(i)}let o=$e(n,"");return this.endToken("LocalDate","start",o),this.back("DATA")}TIME_HOUR(e){let t=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),e!==d.COLON)return this.reportParseError("unexpected-char");let r=this.codePointIterator.start,n=this.data;return n.hour=Number(this.text.slice(t,r)),"TIME_MINUTE"}TIME_MINUTE(e){let t=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");let r=this.codePointIterator.end,n=this.data;return n.minute=Number(this.text.slice(t,r)),e=this.nextCode(),e===d.COLON?"TIME_SECOND":this.tomlVersion.lt(1,1)?this.reportParseError("unexpected-char"):jt(n.hour,n.minute,n.second)?this.processTimeEnd(e,n):this.reportParseError("invalid-time")}TIME_SECOND(e){let t=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");let r=this.codePointIterator.end,n=this.data;return n.second=Number(this.text.slice(t,r)),jt(n.hour,n.minute,n.second)?(e=this.nextCode(),e===d.DOT?"TIME_SEC_FRAC":this.processTimeEnd(e,n)):this.reportParseError("invalid-time")}TIME_SEC_FRAC(e){if(!x(e))return this.reportParseError("unexpected-char");let t=this.codePointIterator.start;for(;x(e);)e=this.nextCode();let r=this.codePointIterator.start,n=this.data;return n.frac=this.text.slice(t,r),this.processTimeEnd(e,n)}processTimeEnd(e,t){if(t.hasDate){if(e===d.DASH||e===d.PLUS_SIGN)return t.offsetSign=e,"TIME_OFFSET";if(e===d.LATIN_CAPITAL_Z||e===d.LATIN_SMALL_Z){let o=$e(t,"Z");return this.endToken("OffsetDateTime","end",o),"DATA"}let n=$e(t,"");return this.endToken("LocalDateTime","start",n),this.back("DATA")}let r=$e(t,"");return this.endToken("LocalTime","start",r),this.back("DATA")}TIME_OFFSET(e){if(!x(e))return this.reportParseError("unexpected-char");let t=this.codePointIterator.start;if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),e!==d.COLON)return this.reportParseError("unexpected-char");let r=this.codePointIterator.start;e=this.nextCode();let n=this.codePointIterator.start;if(!x(e))return this.reportParseError("unexpected-char");if(e=this.nextCode(),!x(e))return this.reportParseError("unexpected-char");let o=this.codePointIterator.end,i=Number(this.text.slice(t,r)),a=Number(this.text.slice(n,o));if(!jt(i,a,0))return this.reportParseError("invalid-time");let s=this.data,l=$e(s,`${String.fromCodePoint(s.offsetSign)}${me(i,2)}:${me(a,2)}`);return this.endToken("OffsetDateTime","end",l),"DATA"}parseDigits(e,t){if(e===d.UNDERSCORE)return this.reportParseError("invalid-underscore");if(!t(e))return this.reportParseError("unexpected-char");let r=[],n=d.NULL,o=!1;for(;t(e)||e===d.UNDERSCORE;){if(e===d.UNDERSCORE){if(o=!0,n===d.UNDERSCORE)return this.reportParseError("invalid-underscore")}else r.push(e);n=e,e=this.nextCode()}return n===d.UNDERSCORE?this.reportParseError("invalid-underscore"):{out:r,nextCp:e,hasUnderscore:o}}parseUnicode(e){let t=this.codePointIterator.start,r=this.codePointIterator.end,n=0,o;for(;(o=this.nextCode())!==d.EOF;){if(!Fr(o))return this.moveAt(t),this.reportParseError("invalid-char-in-escape-sequence");if(n++,n>=e)break}let i=this.codePointIterator.end,a=this.text.slice(r,i),s=parseInt(a,16);return To(s)?s:this.reportParseError("invalid-code-point",{cp:a})}reportParseErrorControlChar(){return this.reportParseError("invalid-control-character")}};function jr(e,t){return yo(e)||x(e)||e===d.UNDERSCORE||e===d.DASH?!0:(t.lt(1,1),!1)}c(jr,"isUnquotedKeyChar");function Ve(e){return ho(e)&&e!==d.TABULATION||e===d.DELETE}c(Ve,"isControlOtherThanTab");function Oo(e){return e===d.TABULATION||d.SPACE<=e&&e<=d.TILDE||Co(e)}c(Oo,"isNonEOL");function Co(e){return d.PAD<=e&&e<=d.CP_D7FF||d.CP_E000<=e&&e<=d.CP_10FFFF}c(Co,"isNonAscii");function No(e,t,r){return e>=0&&t<=12&&t>=1&&r>=1?r<=(t===2?e&3||!(e%25)&&e&15?28:29:30+(t+(t>>3)&1)):!1}c(No,"isValidDate");function jt(e,t,r){return!(e>=24||e<0||t>59||t<0||r>60||r<0)}c(jt,"isValidTime");function $e(e,t){let r=me(e.year,4),n=e.month?me(e.month,2):"01",o=e.day?me(e.day,2):"01",i=me(e.hour,2),a=me(e.minute,2),s=me(e.second,2),l=`${r}-${n}-${o}`,f=e.frac?`.${e.frac}`:"",p=new Date(`${l}T${i}:${a}:${s}${f}${t}`);return!isNaN(p.getTime())||e.second!==60?p:new Date(`${l}T${i}:${a}:59${f}${t}`)}c($e,"getDateFromDateTimeData");function me(e,t){return String(e).padStart(t,"0")}c(me,"padStart");var Kt=Symbol("VALUE_KIND_VALUE"),Br=Symbol("VALUE_KIND_INTERMEDIATE"),xo=class{static{c(this,"KeysResolver")}constructor(e){this.rootKeys=new Map,this.tables=[],this.ctx=e}applyResolveKeyForTable(e){let t=this.rootKeys,r=e.key.keys.length-1;for(let a=0;a<r;a++){let s=e.key.keys[a],l=Gt(s);e.resolvedKey.push(l);let f=t.get(l);if(!f)f={node:s,keys:new Map},t.set(l,f);else if(f.table==="array"){let p=f.peekIndex;e.resolvedKey.push(p),f=f.keys.get(p)}t=f.keys}let n=e.key.keys[r],o=Gt(n);e.resolvedKey.push(o);let i=t.get(o);if(i)if(i.table)if(i.table==="array")if(e.kind==="array"){let a={node:n,keys:new Map},s=i.peekIndex+1;e.resolvedKey.push(s),i.keys.set(s,a),i.peekIndex=s,this.tables.push({node:e,keys:a.keys})}else this.ctx.reportParseError("dupe-keys",n);else this.ctx.reportParseError("dupe-keys",n);else if(e.kind==="array")this.ctx.reportParseError("dupe-keys",n);else{let a={table:e.kind,node:n,keys:i.keys};t.set(o,a),this.tables.push({node:e,keys:a.keys})}else if(e.kind==="array"){e.resolvedKey.push(0);let a={node:n,keys:new Map};t.set(o,{table:e.kind,node:n,keys:new Map([[0,a]]),peekIndex:0}),this.tables.push({node:e,keys:a.keys})}else{let a={table:e.kind,node:n,keys:new Map};t.set(o,a),this.tables.push({node:e,keys:a.keys})}}verifyDuplicateKeys(e){for(let t of e.body)t.type==="TOMLKeyValue"&&Ht(this.ctx,this.rootKeys,t);for(let{node:t,keys:r}of this.tables)for(let n of t.body)Ht(this.ctx,r,n)}};function Ht(e,t,r){let n=t,o=ye(r.key.keys);for(let i of r.key.keys){let a=Gt(i),s=n.get(a);s?((s.value===Kt||o===i||s.table)&&e.reportParseError("dupe-keys",lt(i,s.node)),s.value=Br):(o===i?s={value:Kt,node:i,keys:new Map}:s={value:Br,node:i,keys:new Map},n.set(a,s)),n=s.keys}r.value.type==="TOMLInlineTable"?Xr(e,n,r.value):r.value.type==="TOMLArray"&&qr(e,n,r.value)}c(Ht,"verifyDuplicateKeysForKeyValue");function Xr(e,t,r){for(let n of r.body)Ht(e,t,n)}c(Xr,"verifyDuplicateKeysForInlineTable");function qr(e,t,r){let n=t;for(let o=0;o<r.elements.length;o++){let i=r.elements[o],a=n.get(o);a?e.reportParseError("dupe-keys",lt(i,a.node)):(a={value:Kt,node:i,keys:new Map},t.set(o,a),i.type==="TOMLInlineTable"?Xr(e,a.keys,i):i.type==="TOMLArray"&&qr(e,a.keys,i))}}c(qr,"verifyDuplicateKeysForArray");function lt(e,t){return e.range[0]<=t.range[0]?t:e}c(lt,"getAfterNode");var ko=class{static{c(this,"Context")}constructor(e){this.tokens=[],this.comments=[],this.back=null,this.stateStack=[],this.needNewLine=!1,this.needSameLine=!1,this.currToken=null,this.prevToken=null,this.valueContainerStack=[],this.tokenizer=new Lo(e.text,e.parserOptions),this.topLevelTable=e.topLevelTable,this.table=e.topLevelTable,this.keysResolver=new xo(this)}nextToken(e){if(this.prevToken=this.currToken,this.back?(this.currToken=this.back,this.back=null):this.currToken=this._nextTokenFromTokenizer(e),(this.needNewLine||this.needSameLine||e?.needSameLine)&&this.prevToken&&this.currToken)if(this.prevToken.loc.end.line===this.currToken.loc.start.line){if(this.needNewLine)return this.reportParseError("missing-newline",this.currToken)}else{let t=this.needSameLine||e?.needSameLine;if(t)return this.reportParseError(t,this.currToken)}return this.needNewLine=!1,this.needSameLine=!1,this.currToken}_nextTokenFromTokenizer(e){let t=this.tokenizer.valuesEnabled;e?.valuesEnabled&&(this.tokenizer.valuesEnabled=e.valuesEnabled);let r=this.tokenizer.nextToken();for(;r&&r.type==="Block";)this.comments.push(r),r=this.tokenizer.nextToken();return r&&this.tokens.push(r),this.tokenizer.valuesEnabled=t,r}backToken(){if(this.back)throw new Error("Illegal state");this.back=this.currToken,this.currToken=this.prevToken}addValueContainer(e){this.valueContainerStack.push(e),this.tokenizer.valuesEnabled=!0}consumeValueContainer(){let e=this.valueContainerStack.pop();return this.tokenizer.valuesEnabled=this.valueContainerStack.length>0,e}applyResolveKeyForTable(e){this.keysResolver.applyResolveKeyForTable(e)}verifyDuplicateKeys(){this.keysResolver.verifyDuplicateKeys(this.topLevelTable)}reportParseError(e,t){let r,n,o;if(t)r=t.range[0],n=t.loc.start.line,o=t.loc.start.column;else{r=this.tokenizer.start;let i=this.tokenizer.getLocFromIndex(r);n=i.line,o=i.column}throw new zr(e,r,n,o)}},Vr={VALUE:"missing-value"},Ro={BasicString:"basic",MultiLineBasicString:"basic",LiteralString:"literal",MultiLineLiteralString:"literal"},Po={BasicString:"basic",LiteralString:"literal"},Mo={OffsetDateTime:"offset-date-time",LocalDateTime:"local-date-time",LocalDate:"local-date",LocalTime:"local-time"},Do=class{static{c(this,"TOMLParser")}constructor(e,t){this.text=e,this.parserOptions=t||{},this.tomlVersion=Jr(this.parserOptions.tomlVersion)}parse(){let e={type:"Program",body:[],sourceType:"module",tokens:[],comments:[],parent:null,range:[0,0],loc:{start:{line:1,column:0},end:{line:1,column:0}}},t={type:"TOMLTopLevelTable",body:[],parent:e,range:J(e.range),loc:z(e.loc)};e.body=[t];let r=new ko({text:this.text,parserOptions:this.parserOptions,topLevelTable:t}),n=r.nextToken();if(n){for(t.range[0]=n.range[0],t.loc.start=ut(n.loc.start);n;){let s=r.stateStack.pop()||"TABLE";r.stateStack.push(...this[s](n,r)),n=r.nextToken()}let a=r.stateStack.pop()||"TABLE";if(a in Vr)return r.reportParseError(Vr[a],null);r.table.type==="TOMLTable"&&ie(r.table,ye(r.table.body)),ie(t,ye(t.body))}r.verifyDuplicateKeys(),e.tokens=r.tokens,e.comments=r.comments;let o=r.tokenizer.end,i=r.tokenizer.getLocFromIndex(o);return e.range[1]=o,e.loc.end={line:i.line,column:i.column},e}TABLE(e,t){return ct(e)||Ke(e)?this.processKeyValue(e,t.table,t):Vt(e)?this.processTable(e,t.topLevelTable,t):t.reportParseError("unexpected-token",e)}VALUE(e,t){return Ke(e)||Kr(e)?this.processStringValue(e,t):Fo(e)?this.processNumberValue(e,t):jo(e)?this.processBooleanValue(e,t):Bo(e)?this.processDateTimeValue(e,t):Vt(e)?this.processArray(e,t):Uo(e)?this.processInlineTable(e,t):t.reportParseError("unexpected-token",e)}processTable(e,t,r){let n={type:"TOMLTable",kind:"standard",key:null,resolvedKey:[],body:[],parent:t,range:J(e.range),loc:z(e.loc)};r.table.type==="TOMLTable"&&ie(r.table,ye(r.table.body)),t.body.push(n),r.table=n;let o=r.nextToken({needSameLine:"invalid-key-value-newline"});if(Vt(o)){if(e.range[1]<o.range[0])return r.reportParseError("invalid-space",o);n.kind="array",o=r.nextToken({needSameLine:"invalid-key-value-newline"})}if(Ge(o))return r.reportParseError("missing-key",o);if(!o)return r.reportParseError("unterminated-table-key",null);if(o=this.processKeyNode(o,n,r).nextToken,!Ge(o))return r.reportParseError("unterminated-table-key",o);if(n.kind==="array"){let i=o;if(o=r.nextToken({needSameLine:"invalid-key-value-newline"}),!Ge(o))return r.reportParseError("unterminated-table-key",o);if(i.range[1]<o.range[0])return r.reportParseError("invalid-space",o)}return ie(n,o),r.applyResolveKeyForTable(n),r.needNewLine=!0,[]}processKeyValue(e,t,r){let n={type:"TOMLKeyValue",key:null,value:null,parent:t,range:J(e.range),loc:z(e.loc)};t.body.push(n);let{nextToken:o}=this.processKeyNode(e,n,r);return $r(o)?(r.addValueContainer({parent:n,set:c(i=>(n.value=i,ie(n,i),r.needNewLine=!0,[]),"set")}),r.needSameLine="invalid-key-value-newline",["VALUE"]):r.reportParseError("missing-equals-sign",o)}processKeyNode(e,t,r){Bt(e)&&r.reportParseError("invalid-leading-dot-in-key",e);let n={type:"TOMLKey",keys:[],parent:t,range:J(e.range),loc:z(e.loc)};t.key=n;let o=e,i=null;do{if(ct(o))this.processBareKey(o,n);else if(Ke(o))this.processStringKey(o,n);else break;if(i=null,o=r.nextToken({needSameLine:"invalid-key-value-newline"}),!Bt(o))break;i=o,o=r.nextToken({needSameLine:"invalid-key-value-newline"})}while(o);return i&&r.reportParseError(Bt(o)?"invalid-consecutive-dots-in-key":"invalid-trailing-dot-in-key",i),ie(n,ye(n.keys)),{keyNode:n,nextToken:o}}processBareKey(e,t){let r={type:"TOMLBare",name:e.value,parent:t,range:J(e.range),loc:z(e.loc)};t.keys.push(r)}processStringKey(e,t){let r={type:"TOMLQuoted",kind:"string",value:e.string,style:Po[e.type],multiline:!1,parent:t,range:J(e.range),loc:z(e.loc)};t.keys.push(r)}processStringValue(e,t){let r=t.consumeValueContainer(),n={type:"TOMLValue",kind:"string",value:e.string,style:Ro[e.type],multiline:Kr(e),parent:r.parent,range:J(e.range),loc:z(e.loc)};return r.set(n)}processNumberValue(e,t){let r=t.consumeValueContainer(),n=this.text,[o,i]=e.range,a=null,s=c(()=>a??(a=n.slice(o,i).replace(/_/g,"")),"getNumberText"),l;return e.type==="Integer"?l={type:"TOMLValue",kind:"integer",value:e.number,bigint:e.bigint,get number(){return s()},parent:r.parent,range:J(e.range),loc:z(e.loc)}:l={type:"TOMLValue",kind:"float",value:e.number,get number(){return s()},parent:r.parent,range:J(e.range),loc:z(e.loc)},r.set(l)}processBooleanValue(e,t){let r=t.consumeValueContainer(),n={type:"TOMLValue",kind:"boolean",value:e.boolean,parent:r.parent,range:J(e.range),loc:z(e.loc)};return r.set(n)}processDateTimeValue(e,t){let r=t.consumeValueContainer(),n={type:"TOMLValue",kind:Mo[e.type],value:e.date,datetime:e.value,parent:r.parent,range:J(e.range),loc:z(e.loc)};return r.set(n)}processArray(e,t){let r=t.consumeValueContainer(),n={type:"TOMLArray",elements:[],parent:r.parent,range:J(e.range),loc:z(e.loc)},o=t.nextToken({valuesEnabled:!0});return Ge(o)?(ie(n,o),r.set(n)):(t.backToken(),this.processArrayValue(n,r,t))}processArrayValue(e,t,r){return r.addValueContainer({parent:e,set:c(n=>{e.elements.push(n);let o=r.nextToken({valuesEnabled:!0}),i=Gr(o);return i&&(o=r.nextToken({valuesEnabled:!0})),Ge(o)?(ie(e,o),t.set(e)):i?(r.backToken(),this.processArrayValue(e,t,r)):r.reportParseError(o?"missing-comma":"unterminated-array",o)},"set")}),["VALUE"]}processInlineTable(e,t){let r=t.consumeValueContainer(),n={type:"TOMLInlineTable",body:[],parent:r.parent,range:J(e.range),loc:z(e.loc)},o=this.tomlVersion.gte(1,1)?void 0:"invalid-inline-table-newline",i=t.nextToken({needSameLine:o});if(i){if(ct(i)||Ke(i))return this.processInlineTableKeyValue(i,n,r,t);if($t(i))return ie(n,i),r.set(n)}return t.reportParseError("unexpected-token",i)}processInlineTableKeyValue(e,t,r,n){let o={type:"TOMLKeyValue",key:null,value:null,parent:t,range:J(e.range),loc:z(e.loc)};t.body.push(o);let{nextToken:i}=this.processKeyNode(e,o,n);if(!$r(i))return n.reportParseError("missing-equals-sign",i);let a=this.tomlVersion.gte(1,1)?void 0:"invalid-inline-table-newline";return n.addValueContainer({parent:o,set:c(s=>{o.value=s,ie(o,s);let l=n.nextToken({needSameLine:a});if(Gr(l)){if(l=n.nextToken({needSameLine:a}),l&&(ct(l)||Ke(l)))return this.processInlineTableKeyValue(l,t,r,n);if($t(l)){if(this.tomlVersion.lt(1,1))return n.reportParseError("invalid-trailing-comma-in-inline-table",l)}else return n.reportParseError(l?"unexpected-token":"unterminated-inline-table",l)}return $t(l)?(ie(t,l),r.set(t)):n.reportParseError(l?"missing-comma":"unterminated-inline-table",l)},"set")}),n.needSameLine="invalid-key-value-newline",["VALUE"]}};function Bt(e){return we(e)&&e.value==="."}c(Bt,"isDot");function $r(e){return we(e)&&e.value==="="}c($r,"isEq");function Vt(e){return we(e)&&e.value==="["}c(Vt,"isLeftBracket");function Ge(e){return we(e)&&e.value==="]"}c(Ge,"isRightBracket");function Uo(e){return we(e)&&e.value==="{"}c(Uo,"isLeftBrace");function $t(e){return we(e)&&e.value==="}"}c($t,"isRightBrace");function Gr(e){return we(e)&&e.value===","}c(Gr,"isComma");function we(e){return!!(e&&e.type==="Punctuator")}c(we,"isPunctuator");function ct(e){return e.type==="Bare"}c(ct,"isBare");function Ke(e){return e.type==="BasicString"||e.type==="LiteralString"}c(Ke,"isString");function Kr(e){return e.type==="MultiLineBasicString"||e.type==="MultiLineLiteralString"}c(Kr,"isMultiLineString");function Fo(e){return e.type==="Integer"||e.type==="Float"}c(Fo,"isNumber");function jo(e){return e.type==="Boolean"}c(jo,"isBoolean");function Bo(e){return e.type==="OffsetDateTime"||e.type==="LocalDateTime"||e.type==="LocalDate"||e.type==="LocalTime"}c(Bo,"isDateTime");function ie(e,t){t&&(e.range[1]=t.range[1],e.loc.end=ut(t.loc.end))}c(ie,"applyEndLoc");function J(e){return[e[0],e[1]]}c(J,"cloneRange");function z(e){return{start:ut(e.start),end:ut(e.end)}}c(z,"cloneLoc");function ut(e){return{line:e.line,column:e.column}}c(ut,"clonePos");var Vo={Program:["body"],TOMLTopLevelTable:["body"],TOMLTable:["key","body"],TOMLKeyValue:["key","value"],TOMLKey:["keys"],TOMLArray:["elements"],TOMLInlineTable:["body"],TOMLBare:[],TOMLQuoted:[],TOMLValue:[]},$o=Pr(Vo);function Go(e,t){return{ast:new Do(e,t).parse(),visitorKeys:$o,services:{isTOML:!0}}}c(Go,"parseForESLint");var Jt=Ko(e=>e.value);function Ko(e){function t(n,o){return r[n.type](n,o)}c(t,"resolveValue");let r={Program(n,o={}){return t(n.body[0],o)},TOMLTopLevelTable(n,o={}){for(let i of n.body)t(i,o);return o},TOMLKeyValue(n,o={}){let i=t(n.value);return Jo(o,t(n.key),i),o},TOMLTable(n,o={}){let i=Ho(o,t(n.key),n.kind==="array");for(let a of n.body)t(a,i);return o},TOMLArray(n){return n.elements.map(o=>t(o))},TOMLInlineTable(n){let o={};for(let i of n.body)t(i,o);return o},TOMLKey(n){return n.keys.map(o=>t(o))},TOMLBare(n){return n.name},TOMLQuoted(n){return n.value},TOMLValue(n){return e(n)}};return n=>t(n)}c(Ko,"generateConvertTOMLValue");function Ho(e,t,r){let n=e;for(let l=0;l<t.length-1;l++){let f=t[l];n=s(n,f)}let o=ye(t),i=n[o];if(i==null){let l={};return n[o]=r?[l]:l,l}if(dt(i)){let l={};return n[o]=r?[l]:l,l}if(!r){if(Array.isArray(i)){let l={};return n[o]=l,l}return i}if(Array.isArray(i)){let l={};return i.push(l),l}let a={};return n[o]=[a],a;function s(l,f){let p=l[f];if(p==null){let m={};return l[f]=m,m}if(dt(p)){let m={};return l[f]=m,m}let g=p;for(;Array.isArray(g);){let m=g.length-1,h=g[m];if(dt(h)){let w={};return g[m]=w,w}g=h}return g}c(s,"getNextTargetFromKey")}c(Ho,"getTable");function Jo(e,t,r){let n=e;for(let o=0;o<t.length-1;o++){let i=t[o],a=n[i];if(a==null){let s={};n[i]=s,n=s}else if(dt(a)||Array.isArray(a)){let s={};n[i]=s,n=s}else n=a}n[ye(t)]=r}c(Jo,"set");function dt(e){return typeof e!="object"||e instanceof Date}c(dt,"isValue");function Qr(e,t){return Go(e,t).ast}c(Qr,"parseTOML");function re(e,t){try{let r=Qr(e,{tomlVersion:"1.0"}),n=Jt(r);return en(n),{ast:r,value:n}}catch(r){let n=r;throw new y({code:"INVALID_CONFIG",path:t,message:"Configuration contains invalid TOML or an unsupported value.",line:n.lineNumber,column:n.column===void 0?void 0:n.column+1,action:"Open config.toml, correct the indicated value, and retry."},{cause:r})}}c(re,"parseToml");function en(e){if(e instanceof Date||typeof e=="bigint"||typeof e=="number"&&(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)))throw new Error("Unsupported TOML value");if(e&&typeof e=="object")for(let[t,r]of Object.entries(e)){if(["__proto__","prototype","constructor"].includes(t))throw new Error("Reserved key");en(r)}}c(en,"assertJsonValue");function he(e){if(typeof e=="string")return JSON.stringify(e).replace(/\\u([0-9a-f]{4})/gi,"\\u$1");if(typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e);if(Array.isArray(e))return`[${e.map(he).join(", ")}]`;if(se(e))return`{ ${Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>`${Te(t)} = ${he(r)}`).join(", ")} }`;throw new Error("Configuration cannot contain null or unsupported values.")}c(he,"tomlValue");var Te=c(e=>/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e),"tomlKey"),Yr=c(e=>e.keys.map(t=>t.type==="TOMLBare"?t.name:t.value),"keyPath"),zo=c((e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),"samePath"),pt=c((e,t)=>e.length<=t.length&&e.every((r,n)=>r===t[n]),"prefix");function se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date)}c(se,"isRecord");function Je(e,t,r){let n=e;for(let o of t)n=tn(n,o,r);return re(n,r),n.endsWith(`
4
- `)?n:`${n}
5
- `}c(Je,"editToml");function tn(e,t,r){if(!t.path.length||t.path.some(m=>!m||["__proto__","prototype","constructor"].includes(m)))throw new Error("Invalid configuration key path.");let{ast:n}=re(e,r),o=[],i=[];for(let m of n.body[0].body)if(m.type==="TOMLKeyValue")o.push({path:Yr(m.key),node:m});else{if(i.push(m),m.kind!=="standard")continue;for(let h of m.body)o.push({path:[...m.resolvedKey.map(String),...Yr(h.key)],node:h})}let a=o.find(m=>zo(m.path,t.path));if(a){let m=a.node;if(t.op==="set")return ft(e,m.value.range,Zr(e,n,m.value.range,he(t.value)));let h=n.comments.filter(w=>w.range[0]>=m.range[0]&&w.range[1]<=m.range[1]).map(w=>e.slice(...w.range)).join(`
6
- `);return ft(e,m.range,h)}let s=o.find(m=>pt(m.path,t.path));if(s){let m=structuredClone(Jt(s.node.value));if(!se(m))throw new Error("Cannot edit a key below a scalar or array.");return Wo(m,{...t,path:t.path.slice(s.path.length)}),ft(e,s.node.value.range,Zr(e,n,s.node.value.range,he(m)))}let l=o.filter(m=>pt(t.path,m.path)),f=i.filter(m=>pt(t.path,m.resolvedKey.map(String)));if(l.length||f.length){let m=[...l.map(h=>h.node.range),...f.map(h=>[h.range[0],h.key.range[1]+1])];for(let h of m.sort((w,T)=>T[0]-w[0])){let w=n.comments.filter(T=>T.range[0]>=h[0]&&T.range[1]<=h[1]).map(T=>e.slice(...T.range)).join(`
7
- `);e=ft(e,h,w)}return t.op==="unset"?e:tn(e,t,r)}if(t.op==="unset")return e;if(se(t.value)&&!("mode"in t.value)&&!("source"in t.value)&&!("provider_id"in t.value))return`${e.replace(/\n?$/,`
8
- `)}
9
- ${zt(t.value,t.path)}`;let p=i.filter(m=>m.kind==="standard"&&pt(m.resolvedKey,t.path)&&m.resolvedKey.length<t.path.length).sort((m,h)=>h.resolvedKey.length-m.resolvedKey.length)[0];if(p){let m=t.path.slice(p.resolvedKey.length).map(Te).join("."),w=i.find(T=>T.range[0]>p.range[0])?.range[0]??e.length;return`${e.slice(0,w).replace(/\n?$/,`
10
- `)}${m} = ${he(t.value)}
11
- ${e.slice(w)}`}if(t.path.length===1){let m=i[0]?.range[0]??e.length;return`${e.slice(0,m).replace(/\n?$/,`
12
- `)}${Te(t.path[0])} = ${he(t.value)}
13
- ${e.slice(m)}`}let g=t.path.slice(0,-1).map(Te).join(".");return`${e.replace(/\n?$/,`
14
- `)}
15
- [${g}]
16
- ${Te(t.path.at(-1))} = ${he(t.value)}
17
- `}c(tn,"editOne");function ft(e,t,r){return e.slice(0,t[0])+r+e.slice(t[1])}c(ft,"replace");function Zr(e,t,r,n){if(t.comments.filter(i=>i.range[0]>=r[0]&&i.range[1]<=r[1]).length)throw new y({code:"CONFIG_EDIT_REQUIRES_TEXT",path:"config.toml",message:"This value contains comments that cannot be preserved by a structured edit.",action:"Edit this value directly in the configuration file."});return n}c(Zr,"preserveInnerComments");function Wo(e,t){let r=e;for(let o of t.path.slice(0,-1)){if(["__proto__","prototype","constructor"].includes(o))throw new Error("Reserved key");se(r[o])||(r[o]={}),r=r[o]}let n=t.path.at(-1);if(["__proto__","prototype","constructor"].includes(n))throw new Error("Reserved key");t.op==="set"?r[n]=t.value:delete r[n]}c(Wo,"applyObjectOperation");function ae(e,t,r=[]){let n=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)])){let i=e[o],a=t[o];if(JSON.stringify(i)===JSON.stringify(a))continue;let s=[...r,o];a===void 0?n.push({op:"unset",path:s}):se(i)&&se(a)&&!("mode"in a)&&!("source"in a)&&!("provider_id"in a)?n.push(...ae(i,a,s)):n.push({op:"set",path:s,value:a})}return n}c(ae,"diffConfig");function zt(e,t){let r=[],n=[];for(let[o,i]of Object.entries(e))i!==void 0&&(se(i)&&!("mode"in i)&&!("source"in i)&&!("provider_id"in i)?n.push(zt(i,[...t,o])):r.push(`${Te(o)} = ${he(i)}`));return[...t.length?[`[${t.map(Te).join(".")}]`]:[],...r].join(`
18
- `)+`
19
- `+(n.length?`
20
- `+n.join(`
21
- `):"")}c(zt,"renderTable");function Xo(e){let t=zt(e,[]);return re(t,"config.toml"),t}c(Xo,"serializeConfig");function Xt(e,t="config.toml",r="user"){return oe(re(e,t).value,r)}c(Xt,"validateConfigText");async function mt(e,t){if(t===null)return;try{Xt(t)}catch{return}let r=Oe.join(e,"backups","config"),n=Oe.join(r,`${$(t)}.toml`);await A(n)===null&&await I(n,t);let o=await qo(e);for(let i of o.slice(32))await Wt.rm(Oe.join(r,`${i.revision}.toml`))}c(mt,"rememberValidConfig");async function qo(e){let t=Oe.join(e,"backups","config"),r=await Wt.readdir(t).catch(o=>{if(P(o))return[];throw o}),n=[];for(let o of r){if(!/^[a-f0-9]{64}\.toml$/.test(o))continue;let i=Oe.join(t,o),a=await A(i);if(!(!a||$(a)!==o.slice(0,-5))){try{Xt(a,i)}catch{continue}n.push({revision:o.slice(0,-5),createdAt:(await Wt.stat(i)).mtime.toISOString()})}}return n.sort((o,i)=>i.createdAt.localeCompare(o.createdAt))}c(qo,"configRecoveryRevisions");async function Qo(e,t,r){let n=_(e).config;return Xt(r,n),L(n,async()=>{let o=await A(n);if(o){let i;try{i=re(o,n).value}catch{}if(i&&typeof i=="object"&&"schema_version"in i&&typeof i.schema_version=="number"&&i.schema_version>1)throw new y({code:"UNSUPPORTED_CONFIG_VERSION",path:n,message:"This configuration was written for a newer OpenPond version.",action:"Update OpenPond or restore a compatible backup into a separate home."})}if($(o)!==t)throw new y({code:"CONFIG_CONFLICT",path:n,message:"Configuration changed since you opened it.",action:"Reload the file before saving."});if(await mt(e,o),$(await A(n))!==t)throw new y({code:"CONFIG_CONFLICT",path:n,message:"Configuration changed while saving.",action:"Reload the file before saving."});return await I(n,r),{rawRevision:$(r)}})}c(Qo,"replaceConfigText");async function Ja(e,t,r){if(!/^[a-f0-9]{64}$/.test(t))throw new Error("Invalid configuration revision.");let n=Oe.join(e,"backups","config",`${t}.toml`),o=await A(n);if(!o||$(o)!==t)throw new y({code:"INVALID_CONFIG_BACKUP",path:n,message:"This configuration backup is unavailable or changed.",action:"Select another verified revision."});return Qo(e,r,o)}c(Ja,"restoreConfigRevision");function za(){return u.toJSONSchema(Ft)}c(za,"configEditorSchema");import{realpathSync as Yo,watch as Zo}from"node:fs";import ei from"node:path";async function O(e=hr(),t={}){let r=t.path??_(e).config,n=await A(r);return{path:r,rawRevision:$(n),document:ht(n===null?{schema_version:1}:re(n,r).value,r,t.scope)}}c(O,"readConfig");function ht(e,t,r){try{return oe(e,r)}catch(n){let o=n instanceof u.ZodError?n.issues.map(i=>`${i.path.join(".")||"config"}: ${i.message}`).join("; "):n instanceof Error?n.message:"Invalid configuration";throw new y({code:"INVALID_CONFIG",path:t,message:o,action:"Open the configuration file and correct the indicated setting."},{cause:n})}}c(ht,"validate");async function is(e,t,r,n={}){let o=n.path??_(e).config;return L(o,async()=>{let i=await A(o);if($(i)!==t||(await O(e,n)).rawRevision!==t)throw Ce(o);let s=Je(i??`schema_version = 1
22
- `,r,o),l=ht(re(s,o).value,o,n.scope);if($(await A(o))!==t)throw Ce(o);return s!==i&&(await mt(e,i),await I(o,s)),{path:o,rawRevision:$(s),document:l}})}c(is,"patchConfig");async function W(e,t,r){let n=_(e).config;return L(n,async()=>{let o=await O(e);if(r!==void 0&&o.rawRevision!==r)throw Ce(n);let i=ht(await t(structuredClone(o.document)),n),a=ae(o.document,i);if(!a.length)return o;let s=await A(n);if($(s)!==o.rawRevision)throw Ce(n);let l=Je(s??`schema_version = 1
23
- `,a,n);if(ht(re(l,n).value,n),$(await A(n))!==o.rawRevision)throw Ce(n);return await mt(e,s),await I(n,l),{path:n,rawRevision:$(l),document:i}})}c(W,"updateConfig");function Ce(e){return new y({code:"CONFIG_CONFLICT",path:e,message:"Configuration changed since this edit began.",action:"Reload the latest settings and apply your change again."})}c(Ce,"conflict");function gt(e,t){return rn(e,t)}c(gt,"mergeConfig");function rn(e,t){let r={...e};for(let[n,o]of Object.entries(t))o!==void 0&&(se(o)&&se(r[n])&&!("mode"in o)&&!("source"in o)&&!("provider_id"in o)?r[n]=rn(r[n],o):r[n]=structuredClone(o));return r}c(rn,"mergeTable");function as(e,t){let r,n=Zo(Yo.native(ei.dirname(_(e).config)),{persistent:!1},(o,i)=>{i&&String(i)!=="config.toml"||(r&&clearTimeout(r),r=setTimeout(t,100),r.unref())});return n.on("error",t),()=>{r&&clearTimeout(r),n.close()}}c(as,"watchConfig");var ds=["sidebarWidth","diffPanelWidth","sidebarSectionsCollapsed"],nn=c(e=>({provider_id:e.providerId,model_id:e.modelId}),"modelToConfig"),_t=c(e=>({providerId:e.provider_id,modelId:e.model_id}),"modelFromConfig"),qt=c(e=>e?{mode:"custom",ref:nn(e)}:{mode:"inherit"},"modelOverride");function Ee(e){let t=ee.parse(e);return{schema_version:1,chat:{model:nn(t.defaultChatModelRef??{providerId:t.defaultChatProvider,modelId:t.defaultChatModel}),steer_active_responses:t.steerActiveResponses},codex:{reasoning_effort:t.codexReasoningEffort},permissions:{command_access:t.openPondCommandAccessMode,codex_mode:t.codexPermissionMode},context_compaction:{auto_enabled:t.contextCompaction.autoEnabled,trigger_percent:t.contextCompaction.triggerPercent,summary_model:t.contextCompaction.summaryModel},projects:{branch_prefix:t.defaultBranchPrefix,new_project_directory:t.defaultNewProjectDirectory},defaults:{...t.defaultTeamId?{team_id:t.defaultTeamId}:{}},ui:{advanced_workspace_controls:t.advancedWorkspaceControls},editor:{language_servers:t.editor.languageServers,diagnostics_while_editing:t.editor.diagnosticsWhileEditing,check_on_save:t.editor.checkOnSave,languages:Object.fromEntries(Object.entries(t.editor.languages).map(([r,n])=>[r,{mode:n.mode,custom_command:n.customCommand}]))},training:{default_model:qt(t.training.defaultModelRef),creation_mode:t.training.creationMode,auto_approve_evidence:t.training.autoApproveEvidence},subagents:{enabled:t.subagents.enabled,delegation_mode:t.subagents.delegationMode,default_model:qt(t.subagents.defaultModelRef),max_concurrent_runs:t.subagents.maxConcurrentRuns,max_concurrent_runs_per_provider:t.subagents.maxConcurrentRunsPerProvider??"unlimited",max_concurrent_runs_per_workspace_target:t.subagents.maxConcurrentRunsPerWorkspaceTarget??"unlimited",roles:Object.fromEntries(t.subagents.roles.map(r=>[r.id,{enabled:r.enabled,model:qt(r.modelRef),isolation_mode:r.isolationMode,max_concurrent_runs:r.maxConcurrentRuns,tool_policy:r.toolPolicy,background:r.background,peer_messages:r.peerMessages}]))}}}c(Ee,"preferencesToConfig");function ze(e,t={}){let r=ee.parse({}),n=e.chat?.model?_t(e.chat.model):{providerId:r.defaultChatProvider,modelId:r.defaultChatModel},o=e.subagents,i=new Map(r.subagents.roles.map(a=>[a.id,a]));for(let[a,s]of Object.entries(o?.roles??{})){let l=i.get(a);i.set(a,{id:a,enabled:s.enabled??l?.enabled??!0,modelRef:s.model?s.model.mode==="custom"?_t(s.model.ref):null:l?.modelRef??null,isolationMode:s.isolation_mode??l?.isolationMode??"none",maxConcurrentRuns:s.max_concurrent_runs??l?.maxConcurrentRuns??1,toolPolicy:s.tool_policy??l?.toolPolicy??"read_only",background:s.background??l?.background??!0,peerMessages:s.peer_messages??l?.peerMessages??"parent_scoped"})}return ee.parse({...r,...t,defaultChatProvider:n.providerId,defaultChatModel:n.modelId,defaultChatModelRef:n,codexReasoningEffort:e.codex?.reasoning_effort??r.codexReasoningEffort,codexPermissionMode:e.permissions?.codex_mode??r.codexPermissionMode,openPondCommandAccessMode:e.permissions?.command_access??r.openPondCommandAccessMode,defaultBranchPrefix:e.projects?.branch_prefix??r.defaultBranchPrefix,defaultNewProjectDirectory:e.projects?.new_project_directory??r.defaultNewProjectDirectory,defaultTeamId:e.defaults?.team_id??null,advancedWorkspaceControls:e.ui?.advanced_workspace_controls??r.advancedWorkspaceControls,steerActiveResponses:e.chat?.steer_active_responses??r.steerActiveResponses,contextCompaction:{autoEnabled:e.context_compaction?.auto_enabled??r.contextCompaction.autoEnabled,triggerPercent:e.context_compaction?.trigger_percent??r.contextCompaction.triggerPercent,summaryModel:e.context_compaction?.summary_model??r.contextCompaction.summaryModel},training:{defaultModelRef:e.training?.default_model?.mode==="custom"?_t(e.training.default_model.ref):null,creationMode:e.training?.creation_mode??r.training.creationMode,autoApproveEvidence:e.training?.auto_approve_evidence??r.training.autoApproveEvidence},editor:{languageServers:e.editor?.language_servers??r.editor.languageServers,diagnosticsWhileEditing:e.editor?.diagnostics_while_editing??r.editor.diagnosticsWhileEditing,checkOnSave:e.editor?.check_on_save??r.editor.checkOnSave,languages:Object.fromEntries(Object.entries(r.editor.languages).map(([a,s])=>{let l=e.editor?.languages?.[a];return[a,{mode:l?.mode??s.mode,customCommand:l?.custom_command??s.customCommand}]}))},subagents:{...r.subagents,enabled:o?.enabled??r.subagents.enabled,delegationMode:o?.delegation_mode??r.subagents.delegationMode,defaultModelRef:o?.default_model?.mode==="custom"?_t(o.default_model.ref):null,roles:[...i.values()],maxConcurrentRuns:o?.max_concurrent_runs??r.subagents.maxConcurrentRuns,maxConcurrentRunsPerProvider:o?.max_concurrent_runs_per_provider==="unlimited"?null:o?.max_concurrent_runs_per_provider??r.subagents.maxConcurrentRunsPerProvider,maxConcurrentRunsPerWorkspaceTarget:o?.max_concurrent_runs_per_workspace_target==="unlimited"?null:o?.max_concurrent_runs_per_workspace_target??r.subagents.maxConcurrentRunsPerWorkspaceTarget}})}c(ze,"configToPreferences");function yt(e){return{sidebarWidth:e.sidebarWidth,diffPanelWidth:e.diffPanelWidth,sidebarSectionsCollapsed:e.sidebarSectionsCollapsed}}c(yt,"layoutPreferences");import ti from"node:path";import{existsSync as Qt,promises as ri}from"node:fs";var ni="CREATE TABLE IF NOT EXISTS entries (namespace TEXT NOT NULL, cache_key TEXT NOT NULL, payload TEXT NOT NULL, updated_at TEXT NOT NULL, error TEXT, expires_at INTEGER NOT NULL, last_used INTEGER NOT NULL, PRIMARY KEY(namespace, cache_key));";async function wt(e,t){return L(ti.join(_(e).runtime,"cache"),async()=>{for(let r=0;;r++){let n;try{return n=D(_(e).cache),n.exec(ni),t(n)}catch(o){let i=o;if(!(o instanceof SyntaxError||i.errcode!==void 0&&[11,26].includes(i.errcode&255)||["SQLITE_CORRUPT","SQLITE_NOTADB"].includes(i.code??""))||r>0)throw o;n?.close(),n=void 0;for(let s of["-wal","-shm",""])await ri.rm(`${_(e).cache}${s}`,{force:!0})}finally{n?.close()}}})}c(wt,"withCache");async function ys(e,t,r,n={}){return Qt(_(e).cache)?wt(e,o=>{let i=o.prepare("SELECT payload, updated_at, error, expires_at FROM entries WHERE namespace = ? AND cache_key = ?").get(t,r);return!i||!n.allowStale&&i.expires_at<Date.now()?null:(o.prepare("UPDATE entries SET last_used = ? WHERE namespace = ? AND cache_key = ?").run(Date.now(),t,r),{payload:JSON.parse(i.payload),updatedAt:i.updated_at,error:i.error})}):null}c(ys,"readCache");async function Yt(e,t,r,n,o={}){let i=Date.now(),a=new Date(i).toISOString(),s=JSON.stringify(n);return await wt(e,l=>{l.prepare("INSERT INTO entries VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(namespace, cache_key) DO UPDATE SET payload=excluded.payload, updated_at=excluded.updated_at, error=excluded.error, expires_at=excluded.expires_at, last_used=excluded.last_used").run(t,r,s,a,o.error??null,i+(o.ttlMs??36e5),i);let f=Number(l.prepare("DELETE FROM entries WHERE expires_at < ?").run(i-7*864e5).changes)>0,p=Number(l.prepare("SELECT coalesce(sum(length(CAST(payload AS BLOB))),0) AS size FROM entries").get().size);if(p>512*1024*1024){for(let g of l.prepare("SELECT namespace, cache_key, length(CAST(payload AS BLOB)) AS size FROM entries ORDER BY last_used").all())if(l.prepare("DELETE FROM entries WHERE namespace = ? AND cache_key = ?").run(g.namespace,g.cache_key),f=!0,p-=g.size,p<=512*1024*1024)break}f&&l.exec("PRAGMA wal_checkpoint(TRUNCATE); VACUUM;")}),{payload:n,updatedAt:a,error:o.error??null}}c(Yt,"writeCache");async function ws(e,t){return Qt(_(e).cache)?wt(e,r=>Object.fromEntries(r.prepare("SELECT cache_key, payload, updated_at, error FROM entries WHERE namespace = ? AND expires_at >= ?").all(t,Date.now()).map(n=>[n.cache_key,{payload:JSON.parse(n.payload),updatedAt:n.updated_at,error:n.error}]))):{}}c(ws,"listCache");async function Ts(e,t){Qt(_(e).cache)&&await wt(e,r=>{t?r.prepare("DELETE FROM entries WHERE namespace = ?").run(t):r.exec("DELETE FROM entries"),r.exec("PRAGMA wal_checkpoint(TRUNCATE); VACUUM;")})}c(Ts,"clearCache");import{createCipheriv as oi,createDecipheriv as ii,randomBytes as on,randomUUID as ai,createHash as Zt}from"node:crypto";var si=u.strictObject({owner:u.string(),revision:u.number().int().positive(),algorithm:u.literal("aes-256-gcm"),keyId:u.string(),iv:u.string(),ciphertext:u.string(),tag:u.string()}),ci=u.strictObject({schemaVersion:u.literal("openpond.credentials.v1"),records:u.record(u.string(),si)});async function We(e){let t=_(e).credentials;try{return ci.parse(await M(t,()=>({schemaVersion:"openpond.credentials.v1",records:{}})))}catch(r){throw r instanceof y?r:er(e,"The credential store has an invalid format.",r)}}c(We,"readVault");async function Tt(e,t){let r=_(e),n=await A(r.key);if(n===null&&t&&await A(r.credentials)===null){let i=on(32);return await I(r.key,`${i.toString("base64")}
24
- `),i}let o=n?Buffer.from(n.trim(),"base64"):null;if(!o||o.length!==32)throw er(e,"The credential encryption key is missing or invalid.");return o}c(Tt,"readKey");function er(e,t,r){return new y({code:"CREDENTIAL_RECOVERY_REQUIRED",path:_(e).credentials,message:t,action:"Restore the matching credential store and key from a verified backup. Existing files have been preserved."},{cause:r})}c(er,"credentialError");function tr(e,t,r,n){try{if(r.owner!==t||r.keyId!==Zt("sha256").update(n).digest("hex"))throw new Error("Credential ownership mismatch");let o=ii("aes-256-gcm",n,Buffer.from(r.iv,"base64"));o.setAAD(Buffer.from(`${t}:${r.revision}`)),o.setAuthTag(Buffer.from(r.tag,"base64"));let i=JSON.parse(Buffer.concat([o.update(Buffer.from(r.ciphertext,"base64")),o.final()]).toString("utf8"));return{revision:r.revision,value:i}}catch(o){throw er(e,"A credential could not be verified or decrypted.",o)}}c(tr,"decrypt");async function Et(e,t){let r=await We(e),n=r.records[t];return n?tr(e,t,n,await Tt(e,!1)):null}c(Et,"readCredential");async function Os(e,t){let r=await We(e),n=Object.entries(r.records).filter(([i])=>i.startsWith(t));if(!n.length)return{};let o=await Tt(e,!1);return Object.fromEntries(n.map(([i,a])=>[i,tr(e,i,a,o)]))}c(Os,"readCredentials");async function At(e,t,r,n){return L(_(e).credentials,async()=>{let o=await We(e),i=o.records[t];if(n!==void 0&&n!==(i?.revision??null))throw new y({code:"CREDENTIAL_CONFLICT",path:t,message:"This credential changed or was revoked.",action:"Reload the connection before retrying."});let a=await Tt(e,!0),s=(i?.revision??0)+1,l=on(12),f=oi("aes-256-gcm",a,l);f.setAAD(Buffer.from(`${t}:${s}`));let p=Buffer.concat([f.update(JSON.stringify(r),"utf8"),f.final()]);return o.records[t]={owner:t,revision:s,algorithm:"aes-256-gcm",keyId:Zt("sha256").update(a).digest("hex"),iv:l.toString("base64"),ciphertext:p.toString("base64"),tag:f.getAuthTag().toString("base64")},await I(_(e).credentials,`${JSON.stringify(o,null,2)}
25
- `),s})}c(At,"writeCredential");async function an(e,t){await L(_(e).credentials,async()=>{let r=await We(e);t in r.records&&(delete r.records[t],await I(_(e).credentials,`${JSON.stringify(r,null,2)}
26
- `))})}c(an,"deleteCredential");function sn(e){return`${e}:${ai()}`}c(sn,"newCredentialId");async function cn(e,t){let r=await We(e),n=t.some(o=>r.records[o])?await Tt(e,!1):null;return Object.fromEntries([...new Set(t)].sort().map(o=>{let i=r.records[o];if(!i||!n)return[o,null];let a=tr(e,o,i,n).value,s=o.startsWith("provider:")&&a?.source==="chatgpt_subscription"?{id:o,keyId:i.keyId,source:a.source,endpoint:a.endpoint,createdAt:a.createdAt,accountId:a.oauth?.accountId}:i;return[o,Zt("sha256").update(JSON.stringify(s)).digest("hex")]}))}c(cn,"credentialVersions");import{createHash as ln}from"node:crypto";function dn(e){return ln("sha256").update(JSON.stringify([e.handle,e.base_url??null,e.api_base_url??null,e.chat_api_base_url??null])).digest("hex")}c(dn,"credentialContext");function Ne(e,t){return`account-${ln("sha256").update(JSON.stringify([e.trim().toLowerCase(),t?.trim().replace(/\/$/,"")??""])).digest("hex").slice(0,24)}`}c(Ne,"accountId");async function un(e){return L(`${_(e).runtime}/accounts`,()=>pn(e))}c(un,"readAccountConfiguration");async function pn(e,t){let{document:r}=t??await O(e),n=[];for(let[l,f]of Object.entries(r.accounts??{})){if(f.enabled===!1)continue;let p={};if(f.credential?.source==="secret"){let m=await Et(e,f.credential.id);if(!m)throw new y({code:"CREDENTIAL_MISSING",path:_(e).config,message:`The credential referenced by account ${l} is unavailable.`,action:"Reconnect this account or restore its credential backup."});p=m.value.context===dn(f)?m.value:{}}else f.credential?.source==="env"&&(p={apiKey:process.env[f.credential.name]});let g=H(e,"account_sessions",l)?.value;n.push({handle:f.handle,...f.base_url?{baseUrl:f.base_url}:{},...f.api_base_url?{apiBaseUrl:f.api_base_url}:{},...f.chat_api_base_url?{chatApiBaseUrl:f.chat_api_base_url}:{},...f.environment?{environment:f.environment}:{},...p.apiKey?{apiKey:p.apiKey}:{},...g||p.token?{session:{...g,...p.token?{token:p.token}:{}}}:{}})}let o=r.defaults?.account_id?r.accounts?.[r.defaults.account_id]:void 0;if(r.defaults?.account_id&&(!o||o.enabled===!1))throw new y({code:"INVALID_ACCOUNT_DEFAULT",path:_(e).config,message:"The configured default account is missing or disabled.",action:"Choose an enabled default account or remove defaults.account_id."});let i=o?{handle:o.handle,baseUrl:o.base_url}:H(e,"account_selection","last_used")?.value,a=H(e,"profile_installations","library")?.value,s=r.defaults?.profile_ref;if(s){let l=a,f=l?.profiles?.find(p=>p.source===s.source&&p.repositoryId===s.repository_id&&p.profile===s.profile_id);if(!f)throw new y({code:"INVALID_PROFILE_DEFAULT",path:_(e).config,message:"The configured default Profile is not installed.",action:"Install that Profile or remove defaults.profile_ref."});a={...l,repoPath:f.repoPath,profile:f.profile,mode:"local"}}return{accounts:n,...i?{activeProfile:i}:{},...a?{openpondProfile:a}:{},...r.editor?.language_servers?{lspEnabled:r.editor.language_servers!=="off"}:{},...r.runtime?.execution_mode?{executionMode:r.runtime.execution_mode}:{},...r.runtime?.mode?{mode:r.runtime.mode}:{}}}c(pn,"readUnlocked");async function fn(e,t){return L(`${_(e).runtime}/accounts`,async()=>{let r=await O(e),n=r.document,o=await pn(e,r),i=await t(structuredClone(o)),a=new Map,s=Object.fromEntries(Object.entries(n.accounts??{}).filter(([,p])=>p.enabled===!1)),l=new Set;for(let p of i.accounts??[]){let g=Ne(p.handle,p.baseUrl);if(l.has(g))throw new y({code:"DUPLICATE_ACCOUNT",path:_(e).config,message:"Two accounts have the same handle and service endpoint.",action:"Resolve the duplicate accounts before saving."});l.add(g);let m=Object.entries(n.accounts??{}).find(([,b])=>Ne(b.handle,b.base_url)===Ne(p.handle,p.baseUrl))?.[0]??Ne(p.handle,p.baseUrl),h=n.accounts?.[m],w={...p.apiKey?{apiKey:p.apiKey}:{},...p.session?.token?{token:p.session.token}:{}},T=h?.credential,N=o.accounts?.find(b=>Ne(b.handle,b.baseUrl)===Ne(p.handle,p.baseUrl));if((N?.apiKey!==p.apiKey||N?.session?.token!==p.session?.token||N?.apiBaseUrl!==p.apiBaseUrl||N?.chatApiBaseUrl!==p.chatApiBaseUrl||!T&&Object.keys(w).length)&&(T=void 0,Object.keys(w).length)){let b=sn(m);await At(e,b,{...w,context:dn({handle:p.handle,base_url:p.baseUrl,api_base_url:p.apiBaseUrl,chat_api_base_url:p.chatApiBaseUrl})},null),T={source:"secret",id:b}}s[m]={...h?.enabled===void 0?{}:{enabled:h.enabled},handle:p.handle,...p.baseUrl?{base_url:p.baseUrl}:{},...p.apiBaseUrl?{api_base_url:p.apiBaseUrl}:{},...p.chatApiBaseUrl?{chat_api_base_url:p.chatApiBaseUrl}:{},...p.environment?{environment:p.environment}:{},...T?{credential:T}:{}},p.session&&a.set(m,{appId:p.session.appId??null,conversationId:p.session.conversationId??null})}await W(e,p=>({...p,accounts:s,...p.defaults?.account_id&&!s[p.defaults.account_id]?{defaults:{...p.defaults,account_id:void 0}}:{},...i.lspEnabled===void 0?{}:{editor:{...p.editor,language_servers:i.lspEnabled?"auto":"off"}},...i.executionMode||i.mode?{runtime:{...p.runtime,...i.executionMode?{execution_mode:i.executionMode}:{},...i.mode?{mode:i.mode}:{}}}:{}}),r.rawRevision),fe(e,p=>{p.exec("BEGIN IMMEDIATE");try{for(let g of new Set([...Object.keys(n.accounts??{}),...Object.keys(s)])){let m=a.get(g);m?p.prepare("INSERT INTO account_sessions VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(g,JSON.stringify(m)):p.prepare("DELETE FROM account_sessions WHERE id = ?").run(g)}JSON.stringify(o.activeProfile)!==JSON.stringify(i.activeProfile)&&p.prepare("INSERT INTO account_selection VALUES ('last_used', ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(JSON.stringify(i.activeProfile??null)),JSON.stringify(o.openpondProfile)!==JSON.stringify(i.openpondProfile)&&p.prepare("INSERT INTO profile_installations VALUES ('library', ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(JSON.stringify(i.openpondProfile??null)),p.exec("COMMIT")}catch(g){throw p.exec("ROLLBACK"),g}});let f=new Set(Object.values(s).flatMap(p=>p.credential?.source==="secret"?[p.credential.id]:[]));for(let p of Object.values(n.accounts??{}))p.credential?.source==="secret"&&!f.has(p.credential.id)&&await an(e,p.credential.id);return i})}c(fn,"updateAccountConfiguration");import{existsSync as li,promises as di}from"node:fs";import Xe from"node:path";var rr=new Set(["sessions","projection_session_shells","sidebar_file_bookmarks","saved_local_projects","profile_installations","extension_installations","scaffold_registrations","refiner_bindings","harness_release_records","dataset_artifacts","dataset_import_jobs","taskset_drafts","taskset_draft_workspaces","training_artifacts","task_attempt_artifacts","local_agent_schedules"]);function bt(e,t){let r=Xe.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${Xe.sep}`)&&!Xe.isAbsolute(r)}c(bt,"isWithinHome");async function St(e){let t=new Set,r=(await O(e)).document;function n(a){Xe.isAbsolute(a)&&!bt(a,e)&&t.add(Xe.normalize(a))}c(n,"add"),r.storage?.datasets_dir&&n(Fe(r.storage.datasets_dir,e)),r.personalization?.user_instructions&&n(Fe(r.personalization.user_instructions,e));function o(a,s=""){if(typeof a=="string"&&/(?:path|directory|root|cwd)$/i.test(s))n(a);else if(Array.isArray(a))for(let l of a)o(l,s);else if(a&&typeof a=="object")for(let[l,f]of Object.entries(a))["messages","events","turns","metadata","input","output","result","credential"].includes(l)||o(f,l)}c(o,"visit");let i=_(e).database;if(li(i)){let a=D(i,!0);try{for(let{name:s}of a.prepare("SELECT name FROM sqlite_master WHERE type='table'").all())if(rr.has(s)){let l=a.prepare(`PRAGMA table_info(${s})`).all();if(l.some(f=>f.name==="payload"))for(let f of a.prepare(`SELECT payload FROM ${s}`).all())o(JSON.parse(f.payload));for(let{name:f}of l.filter(p=>/(?:_path|_directory|_root)$/.test(p.name)||p.name==="cwd"))for(let p of a.prepare(`SELECT "${f}" AS value FROM ${s}`).all())typeof p.value=="string"&&n(p.value)}}finally{a.close()}}return Promise.all([...t].sort().map(async a=>({path:a,available:!!await di.stat(a).catch(()=>null),included:!1})))}c(St,"externalStorageReferences");import{randomUUID as ui}from"node:crypto";import{promises as vt,existsSync as mn}from"node:fs";import pi from"node:os";import xe from"node:path";async function hn(e,t,r){let n=await vt.mkdtemp(xe.join(pi.tmpdir(),"openpond-migration-preview-")),o=`migration-preview-${ui()}`,i={schemaVersion:"openpond.migration.v1",id:o,status:"preparing",home:n,stage:xe.join(xe.dirname(n),`.${xe.basename(n)}-${o}`),backup:xe.join(n,"backups",o),files:[],installed:[],createdAt:new Date().toISOString(),sourceAppHome:t.sourceAppHome,sourceConfig:t.sourceConfig,sourceBrowserState:t.sourceBrowserState};try{try{await r(i)}catch(w){return{issues:[mr(w,e)],counts:{},destinations:[],conflicts:[],estimatedBytes:null,credentialRecords:null}}let a=await O(i.stage),s=mn(_(e).config)?await O(e):null,l=s?ae(s.document,a.document).map(w=>({path:w.path,choices:["imported","existing"]})):[],f=ae({schema_version:1},a.document).map(w=>({path:w.path,destination:"config.toml",operation:w.op})),p={},g=_(i.stage).database;if(mn(g)){let w=D(g,!0);try{for(let T of w.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all())p[T.name]=Number(w.prepare(`SELECT count(*) AS count FROM "${T.name.replaceAll('"','""')}"`).get().count)}finally{w.close()}}let m=0;for(let w of i.files)m+=(await vt.lstat(xe.join(i.stage,w.path))).size;let h=Object.values(a.document.accounts??{}).filter(w=>w.credential?.source==="secret").length+Object.values(a.document.providers??{}).filter(w=>w.credential?.source==="secret").length;return{issues:[],counts:p,destinations:f,conflicts:l,estimatedBytes:m,credentialRecords:h,externalRoots:await St(i.stage),layoutVersion:1,configSchemaVersion:a.document.schema_version}}finally{await vt.rm(i.stage,{recursive:!0,force:!0}),await vt.rm(n,{recursive:!0,force:!0})}}c(hn,"previewMigration");import{randomUUID as _n}from"node:crypto";import{promises as F}from"node:fs";import Ae from"node:path";import{createHash as fi}from"node:crypto";import{createReadStream as mi,promises as gn}from"node:fs";async function K(e){let t=await gn.lstat(e),r=fi("sha256");if(t.isSymbolicLink())return r.update(`symlink:${await gn.readlink(e)}`).digest("hex");if(!t.isFile())throw new Error(`Unsupported migration object: ${e}`);for await(let n of mi(e))r.update(n);return r.digest("hex")}c(K,"digestFile");var yn=u.string().regex(/^[a-f0-9]{64}$/),nr=u.strictObject({schemaVersion:u.literal("openpond.artifact.v1"),sha256:yn,sizeBytes:u.number().int().nonnegative().safe(),createdAt:u.string().datetime()}),hi=`CREATE TABLE IF NOT EXISTS managed_artifact_objects (sha256 TEXT PRIMARY KEY, payload TEXT NOT NULL, orphaned_at TEXT);
27
- CREATE TABLE IF NOT EXISTS managed_artifact_references (domain TEXT NOT NULL, owner_id TEXT NOT NULL, sha256 TEXT NOT NULL REFERENCES managed_artifact_objects(sha256), payload TEXT NOT NULL, PRIMARY KEY(domain,owner_id));
28
- CREATE TABLE IF NOT EXISTS managed_artifact_pins (id TEXT PRIMARY KEY, sha256 TEXT NOT NULL REFERENCES managed_artifact_objects(sha256), owner_pid INTEGER NOT NULL, created_at TEXT NOT NULL);`,It=c((e,t)=>Ae.join(e,"artifacts","objects",yn.parse(t).slice(0,2),t),"artifactPath"),Lt=c(e=>Ae.join(_(e).runtime,"artifacts"),"lockPath");function be(e,t){return fe(e,r=>(r.exec(hi),t(r)))}c(be,"database");function ue(e){return new y({code:"ARTIFACT_UNAVAILABLE",path:e,message:"A referenced artifact is missing or failed its checksum.",action:"Restore the object from a verified backup. Its reference has been preserved."})}c(ue,"invalid");async function wn(e){let t=D(_(e).database,!0),r;try{if(!t.prepare("SELECT 1 FROM sqlite_master WHERE name='managed_artifact_references'").get())return;r=t.prepare("SELECT DISTINCT o.sha256,o.payload FROM managed_artifact_objects o JOIN managed_artifact_references r ON r.sha256=o.sha256").all()}finally{t.close()}for(let n of r){let o=It(e,n.sha256);try{let i=nr.parse(JSON.parse(n.payload)),a=nr.parse(JSON.parse(await F.readFile(`${o}.json`,"utf8"))),s=await F.lstat(o);if(!s.isFile()||i.sha256!==n.sha256||JSON.stringify(i)!==JSON.stringify(a)||s.size!==i.sizeBytes||await K(o)!==n.sha256)throw ue(o)}catch{throw ue(o)}}}c(wn,"validateManagedArtifacts");async function Tn(e,t){if(!t.owner.id||t.owner.id.length>4096||/[\u0000-\u001f]/.test(t.displayName))throw new Error("Invalid artifact identity or display name.");return L(Lt(e),async()=>{let r=Ae.join(e,"artifacts",".staging");await U(r);let n=Ae.join(r,_n());try{if("bytes"in t)await I(n,t.bytes);else{if(!(await F.lstat(t.sourceFile)).isFile())throw ue(t.sourceFile);await F.copyFile(t.sourceFile,n,F.constants.COPYFILE_EXCL);let m=await F.open(n,"r+");try{await m.sync()}finally{await m.close()}}let o=await K(n),i=(await F.stat(n)).size,a=It(e,o),s=`${a}.json`,l=new Date().toISOString();await U(Ae.dirname(a));let f=await F.lstat(a).catch(m=>{if(P(m))return null;throw m});if(f){if(!f.isFile()||await K(a)!==o)throw ue(a)}else process.platform!=="win32"&&await F.chmod(n,256),await F.rename(n,a);let p;try{p=nr.parse(JSON.parse(await F.readFile(s,"utf8")))}catch(m){if(!P(m))throw ue(s);p={schemaVersion:"openpond.artifact.v1",sha256:o,sizeBytes:i,createdAt:l},await I(s,JSON.stringify(p))}if(p.sha256!==o||p.sizeBytes!==i)throw ue(s);let g={owner:t.owner,sha256:o,sizeBytes:i,displayName:t.displayName,mediaType:t.mediaType,createdAt:l};return be(e,m=>{m.exec("BEGIN IMMEDIATE");try{let h=m.prepare("SELECT sha256 FROM managed_artifact_references WHERE domain=? AND owner_id=?").get(t.owner.domain,t.owner.id);if(h&&h.sha256!==o)throw new y({code:"IMMUTABLE_ARTIFACT_CONFLICT",path:t.owner.id,message:"This artifact identity already refers to different bytes.",action:"Create a new artifact revision instead of replacing immutable content."});m.prepare("INSERT INTO managed_artifact_objects VALUES (?, ?, NULL) ON CONFLICT(sha256) DO UPDATE SET orphaned_at=NULL").run(o,JSON.stringify(p)),m.prepare("INSERT INTO managed_artifact_references VALUES (?, ?, ?, ?) ON CONFLICT(domain,owner_id) DO NOTHING").run(t.owner.domain,t.owner.id,o,JSON.stringify(g)),m.exec("COMMIT")}catch(h){throw m.exec("ROLLBACK"),h}}),{...g,path:a}}finally{await F.rm(n,{force:!0})}})}c(Tn,"publishManagedArtifact");function gi(e,t){return be(e,r=>{let n=r.prepare("SELECT payload FROM managed_artifact_references WHERE domain=? AND owner_id=?").get(t.domain,t.id);return n?JSON.parse(n.payload):null})}c(gi,"artifactReference");async function yc(e,t,r){let n=_n(),o=await L(Lt(e),async()=>{let i=gi(e,t);if(!i)throw ue(t.id);return be(e,a=>{a.prepare("INSERT INTO managed_artifact_pins VALUES (?, ?, ?, ?)").run(n,i.sha256,process.pid,new Date().toISOString())}),i});try{let i=It(e,o.sha256),a=await F.lstat(i).catch(()=>null);if(!a?.isFile()||a.size!==o.sizeBytes||await K(i)!==o.sha256)throw ue(i);return await r(i,o)}finally{be(e,i=>{i.prepare("DELETE FROM managed_artifact_pins WHERE id=?").run(n)})}}c(yc,"withManagedArtifact");async function wc(e,t){await L(Lt(e),async()=>{be(e,r=>{r.exec("BEGIN IMMEDIATE");try{r.prepare("DELETE FROM managed_artifact_references WHERE domain=? AND owner_id=?").run(t.domain,t.id),r.prepare("UPDATE managed_artifact_objects SET orphaned_at=coalesce(orphaned_at,?) WHERE sha256 NOT IN (SELECT sha256 FROM managed_artifact_references)").run(new Date().toISOString()),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}})})}c(wc,"releaseArtifactReference");async function Tc(e){return L(Lt(e),async()=>{let t=Date.now()-6048e5,r=be(e,i=>{let a=i.prepare("PRAGMA integrity_check").all();if(a.length!==1||Object.values(a[0])[0]!=="ok"||i.prepare("PRAGMA foreign_key_check").all().length)throw ue(_(e).database);return new Set(i.prepare("SELECT sha256 FROM managed_artifact_references UNION SELECT sha256 FROM managed_artifact_pins UNION SELECT sha256 FROM managed_artifact_objects WHERE orphaned_at IS NULL OR orphaned_at >= ?").all(new Date(t).toISOString()).map(s=>s.sha256))}),n=Ae.join(e,"artifacts","objects"),o=[];for(let i of await F.readdir(n,{withFileTypes:!0}).catch(a=>{if(P(a))return[];throw a}))if(!(!i.isDirectory()||!/^[a-f0-9]{2}$/.test(i.name)))for(let a of await F.readdir(Ae.join(n,i.name))){if(!/^[a-f0-9]{64}$/.test(a)||!a.startsWith(i.name)||r.has(a))continue;let s=It(e,a),l=await F.lstat(s);!l.isFile()||l.mtimeMs>=t||(await F.rm(s),await F.rm(`${s}.json`,{force:!0}),be(e,f=>{f.prepare("DELETE FROM managed_artifact_objects WHERE sha256=?").run(a)}),o.push(a))}return{removed:o}})}c(Tc,"collectArtifactOrphans");var Ot=u.array(u.strictObject({path:u.array(u.string().min(1)).min(1),choice:u.enum(["imported","existing"])})).max(1e4);async function En(e,t,r=[]){let n=await O(e),o=await O(t),i=ae(n.document,o.document),a=Ot.parse(r),s=new Map(a.map(p=>[JSON.stringify(p.path),p.choice])),l=i.filter(p=>!s.has(JSON.stringify(p.path)));if(l.length)throw new y({code:"MIGRATION_CONFLICT",path:n.path,message:`Existing configuration conflicts with ${l.length} imported fields: ${l.map(p=>JSON.stringify(p.path)).join(", ")}.`,action:"Preview the migration, choose imported or existing for each conflicting field, and supply the resolution map. Both source versions remain preserved."});let f=Je(await A(n.path)??`schema_version = 1
29
- `,i.filter(p=>s.get(JSON.stringify(p.path))==="imported"),n.path);oe(re(f,n.path).value),await I(o.path,f)}c(En,"resolveMigrationTarget");import{createHash as An}from"node:crypto";import _i from"node:path";var or=u.strictObject({conversations:u.record(u.string(),u.strictObject({activeTabId:u.string().nullable(),tabs:u.array(u.strictObject({id:u.string().min(1),url:u.string(),title:u.string().nullable(),faviconUrl:u.string().nullable(),lastUpdatedAt:u.number().finite()}))}))});async function bn(e,t){await L(_i.join(_(e).runtime,"browser-metadata-import"),async()=>{let r=await A(t);if(r===null)return;let n=or.safeParse(JSON.parse(r));if(!n.success)throw new y({code:"MIGRATION_CONFLICT",path:t,message:"Native browser tab metadata has an unsupported structure.",action:"Preserve this file and resolve the metadata format before retrying."});let o=`browser-import:${An("sha256").update(t).digest("hex")}`;fe(e,i=>{i.exec("BEGIN IMMEDIATE");try{if(!i.prepare("SELECT 1 FROM client_preferences WHERE id=?").get(o)){for(let[a,s]of Object.entries(n.data.conversations))i.prepare("INSERT INTO browser_tab_state VALUES (?, ?, 1) ON CONFLICT(id) DO NOTHING").run(a,JSON.stringify(s));i.prepare("INSERT INTO client_preferences VALUES (?, ?, 1)").run(o,JSON.stringify({schemaVersion:"openpond.browserMetadataImport.v1",source:t,hash:An("sha256").update(r).digest("hex"),importedAt:new Date().toISOString()}))}i.exec("COMMIT")}catch(a){throw i.exec("ROLLBACK"),a}})})}c(bn,"importBrowserMetadataOnce");import{randomUUID as ur}from"node:crypto";import{existsSync as le,promises as R}from"node:fs";import E from"node:path";import{backup as Ci}from"node:sqlite";import{createDecipheriv as Ei,createHash as ar}from"node:crypto";import{promises as cr}from"node:fs";import te from"node:path";function ir(e,t){throw new y({code:"MIGRATION_CONFLICT",path:e,message:t,action:"Resolve this source field and restart failed migration preparation. Its original backup is retained."})}c(ir,"conflict");function qe(e,t,r,n=[]){if(!(!e||typeof e!="object"||!t||typeof t!="object")){if(Array.isArray(e)&&Array.isArray(t)){e.forEach((o,i)=>qe(o,t[i],r,[...n,String(i)]));return}for(let[o,i]of Object.entries(e))Object.hasOwn(t,o)||ir(r,`Unmapped stored field: ${[...n,o].join(".")}`),qe(i,t[o],r,[...n,o])}}c(qe,"assertNoUnmappedFields");var yi=u.strictObject({token:u.string().optional(),appId:u.string().nullable().optional(),conversationId:u.string().nullable().optional()}),wi=u.strictObject({handle:u.string().min(1),baseUrl:u.string().optional(),apiBaseUrl:u.string().optional(),chatApiBaseUrl:u.string().optional(),environment:u.string().optional(),apiKey:u.string().optional(),session:yi.optional()});function Sn(e,t){if(e.accounts!==void 0){let r=u.array(wi).safeParse(e.accounts);r.success||ir(t,`Invalid stored accounts: ${r.error.issues.map(n=>n.path.join(".")).join(", ")}`)}e.activeProfile!==void 0&&!u.strictObject({handle:u.string().min(1),baseUrl:u.string().nullable().optional()}).safeParse(e.activeProfile).success&&ir(t,"Invalid stored active account selector.")}c(Sn,"validateImportedAccounts");function vn(e,t){let r=ee.parse(e);qe(e,r,t);let n=Ti(e),o=ee.parse(n),i=o.defaultChatProvider==="codex"&&["codex-default","gpt-5.5"].includes(o.defaultChatModel);return{...o,defaultTeamId:o.defaultTeamId?.trim()||null,defaultNewProjectDirectory:gr(o.defaultNewProjectDirectory.trim()),...i?{defaultChatModel:Sr}:{},...i&&o.codexReasoningEffort==="medium"?{codexReasoningEffort:vr}:{}}}c(vn,"normalizeImportedPreferences");function Ti(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e,r=t.subagents;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r,o=n.workspaceDefaultsVersion===1,i=n.toolDefaultsVersion===1;if(o&&i)return e;let a=Array.isArray(n.roles)?n.roles.map(s=>({...s,...!o&&s.isolationMode==="copy_on_write"?{isolationMode:"none"}:{},...i?{}:{toolPolicy:"full_tools"}})):n.roles;return{...t,subagents:{...n,workspaceDefaultsVersion:1,toolDefaultsVersion:1,maxConcurrentRunsPerWorkspaceTarget:!o&&n.maxConcurrentRunsPerWorkspaceTarget===2?1:n.maxConcurrentRunsPerWorkspaceTarget,...a===void 0?{}:{roles:a}}}}c(Ti,"migrateSubagentDefaults");var ge=u.string().nullable().optional(),In=u.strictObject({version:u.literal(1),providers:u.record(u.string().min(1),u.strictObject({source:u.enum(["local_secret","env","chatgpt_subscription"]),envVar:ge,ciphertext:ge,iv:ge,tag:ge,createdAt:ge,updatedAt:ge,lastValidatedAt:ge,lastError:ge}))}),Ln=u.strictObject({accessToken:u.string().nullable(),refreshToken:u.string().min(1),expiresAt:u.number().finite(),accountId:u.string().nullable()}),On=u.strictObject({version:u.literal(1),activeTemplateId:u.string(),updatedAt:u.string()}),Cn=u.strictObject({schemaVersion:u.literal("openpond.datasetStorageSettings.v1"),datasetStorePath:u.string().min(1),updatedAt:u.string()});function C(e,t){return new y({code:"MIGRATION_CONFLICT",path:e,message:t,action:"Open migration details, resolve this conflict, and retry. The source installation has been preserved."})}c(C,"migrationConflict");async function Nn(e,t){if(!t)return;let r=await M(t,()=>({})),n=new Set(["accounts","activeProfile","openpondProfile","baseUrl","apiBaseUrl","chatApiBaseUrl","apiKey","token","appId","conversationId","lspEnabled","executionMode","mode"]);for(let a of Object.keys(r))if(!n.has(a))throw C(t,`Unmapped account configuration field: ${a}`);Sn(r,t);let o=r.accounts;if(o!==void 0&&!Array.isArray(o))throw C(t,"The account list is invalid.");!o?.length&&(r.apiKey||r.token||r.baseUrl)&&(o=[{handle:r.activeProfile?.handle??"default",...r,session:{token:r.token,appId:r.appId,conversationId:r.conversationId}}]);let i={...r,accounts:o};await fn(e,()=>i)}c(Nn,"importAccountConfig");async function xn(e,t){let r=_(e).database;if(!await cr.stat(r).catch(()=>null))return;let o=D(r),i=[];try{o.exec(Cr),o.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cache_entries'").get()&&(i=o.prepare("SELECT type, cache_key, payload, updated_at, error FROM cache_entries").all())}finally{o.close()}for(let s of i){let l=JSON.parse(s.payload);if(s.type==="app_preferences"){let f=l;for(let m of Object.keys(f))if(!(m in ee.shape))throw C(r,`Unmapped preference field: ${m}`);let p=vn(l,r),g=(await O(e)).document;if(f.editor&&g.editor?.language_servers&&g.editor.language_servers!==p.editor.languageServers)throw C(r,"CLI language-server configuration conflicts with saved editor settings.");if(p.defaultChatModelRef&&(p.defaultChatModelRef.providerId!==p.defaultChatProvider||p.defaultChatModelRef.modelId!==p.defaultChatModel))throw C(r,"Saved model fields disagree; select which model should be retained.");await W(e,m=>gt(m,Ee(p))),B(e,"client_preferences","global",yt(p))}else if(s.type==="local.projects"){if(!Array.isArray(l))throw C(r,"Saved projects must be an array.");for(let f of l){if(!f||typeof f.id!="string")throw C(r,"A saved project has no identity.");B(e,"saved_local_projects",f.id,f)}}else if(s.type==="codex_history.sidebar_preferences")B(e,"codex_sidebar_state",s.cache_key,l);else if(s.type==="personalization")B(e,"account_selection","imported_personality",l);else if(s.type==="openpond.scaffoldApps")B(e,"scaffold_registrations",s.cache_key,l);else if(["openpond.account","openpond.apps","openpond.cloudProjects","training.hosted-model-project-catalog.v1"].includes(s.type))await Yt(e,s.type,s.cache_key,l,{error:s.error});else throw C(r,`Unmapped cache namespace: ${s.type}`)}let a=D(r);try{i.length&&a.exec("DELETE FROM cache_entries"),a.exec("PRAGMA wal_checkpoint(TRUNCATE)")}finally{a.close()}}c(xn,"importPreferenceRecords");async function kn(e,t){if(!t)return;let r=te.join(t,"providers.json"),n=await M(r,()=>({}));for(let m of Object.keys(n))if(!["version","providers","modelCaches","catalogCache","statuses","updatedAt"].includes(m))throw C(r,`Unmapped provider field: ${m}`);let o=yr.parse(n);qe(Object.fromEntries(Object.entries(n).filter(([m])=>m!=="catalogCache")),o,r);let i={};for(let[m,h]of Object.entries(o.providers))i[m]={enabled:h.enabled,...h.baseUrl?{base_url:h.baseUrl}:{},...h.defaultModel?{default_model:h.defaultModel}:{},model_overrides:h.modelOverrides};await W(e,m=>({...m,providers:i})),await Yt(e,"providers","catalog",{modelCaches:o.modelCaches,catalogCache:n.catalogCache??null});let a=te.join(t,"provider-secrets.json"),s=await M(a,()=>null);if(s===null)return;let l=In.safeParse(s);if(!l.success)throw C(a,"The provider vault has an unsupported version or field.");let f=l.data,p=await A(te.join(t,"provider-secrets.key")),g=p?Buffer.from(p.trim(),"base64"):null;for(let[m,h]of Object.entries(f.providers)){let w=null,T=null;if(h.source!=="env"){if(!g||g.length!==32||!h.ciphertext||!h.iv||!h.tag)throw C(a,"The old provider credential cannot be decrypted with its saved key.");try{let v=Ei("aes-256-gcm",g,Buffer.from(String(h.iv),"base64"));v.setAuthTag(Buffer.from(String(h.tag),"base64")),w=Buffer.concat([v.update(Buffer.from(String(h.ciphertext),"base64")),v.final()]).toString("utf8"),h.source==="chatgpt_subscription"&&(T=Ln.parse(JSON.parse(w)),w=null)}catch{throw C(a,"The saved provider credential failed integrity verification.")}}let N=`provider:${m}`,b={endpoint:i[m]?.base_url??null,source:h.source,value:w,oauth:T,envVar:h.envVar??null,createdAt:h.createdAt,updatedAt:h.updatedAt,lastValidatedAt:h.lastValidatedAt??null,lastError:h.lastError??null};await At(e,N,b,null),await W(e,v=>({...v,providers:{...v.providers,[m]:{...v.providers?.[m],credential:h.source==="env"?{source:"env",name:String(h.envVar)}:{source:"secret",id:N}}}}))}}c(kn,"importProviderConfig");async function Rn(e,t){if(!t)return;let r=new Map;for(let h of[t,te.join(t,"souls")]){let w=await cr.readdir(h,{withFileTypes:!0}).catch(()=>[]);for(let T of w){if(!T.isFile()||!(h===t?/^soul-.+\.md$/i:/\.md$/i).test(T.name))continue;let N=await cr.readFile(te.join(h,T.name),"utf8"),b=`imported-${ar("sha256").update(N).digest("hex").slice(0,16)}`;await sr(e,b,N),r.set(`file:${te.relative(t,te.join(h,T.name)).split(te.sep).join("/")}`,{id:b,content:N})}}let n=await A(te.join(t,"SOUL.md")),o=te.join(t,"personalization.json"),i=await M(o,()=>null),a=i===null?null:On.safeParse(i);if(a&&!a.success)throw C(o,"Personalization has an unsupported version or field.");let s=a?.success?a.data:{},{getLocalRecord:l}=await import("./database-X2CUV732.js"),f=l(e,"account_selection","imported_personality")?.value??s.activeTemplateId??"default",p=r.get(f),g=nt.find(h=>h.id===f),m=p?`custom:${p.id}`:g?`builtin:${g.id}`:"builtin:default";if(n?.trim()&&!p&&!g){let h=`imported-${ar("sha256").update(n).digest("hex").slice(0,16)}`;await sr(e,h,n),m=`custom:${h}`}else if(n?.trim()&&n.trim()!==(p?.content??g?.content)?.trim()){let h=`preserved-${ar("sha256").update(n).digest("hex").slice(0,16)}`;await sr(e,h,n)}await W(e,h=>({...h,personalization:{...h.personalization,active:m}}))}c(Rn,"importPersonalization");async function Pn(e,t){if(!t)return;let r=te.join(t,"datasets","settings.json"),n=await M(r,()=>null),o=n===null?null:Cn.safeParse(n);if(o&&!o.success)throw C(r,"Dataset settings have an unsupported version or field.");let i=o?.success?o.data:{};i.datasetStorePath&&await W(e,a=>({...a,storage:{...a.storage,datasets_dir:i.datasetStorePath}})),oe((await O(e)).document)}c(Pn,"importDatasetPreference");async function sr(e,t,r){await I(te.join(e,"instructions","imported-originals",`${t}.md`),r),await I(te.join(e,"instructions","personalities",`${t}.md`),r.trim().slice(0,8e3))}c(sr,"preserveImportedPersonality");import{execFile as Ai}from"node:child_process";import{promisify as bi}from"node:util";import{existsSync as Ct,promises as Qe}from"node:fs";import Mn from"node:os";import X from"node:path";var Dn=bi(Ai);async function Un(e,t){let r=e===X.join(Mn.homedir(),".openpond-nightly"),n=X.join(Mn.homedir(),".openpond"),o=["openpond-app-dev","openpond-app-nightly-dev"].some(g=>e===X.join(n,g)),i=r||o?n:e,a=(o?[e]:[e,X.join(i,r?"openpond-app-nightly":"openpond-app")]).filter(g=>Ct(X.join(g,"state.sqlite"))||Ct(X.join(g,"providers.json"))),s=[...new Set([X.join(i,"config.json"),X.join(e,"config","config.json")])].filter(Ct),l=[];!t.sourceAppHome&&a.length>1&&l.push({code:"AMBIGUOUS_APP_HOME",message:"Select the previous app home with --source-app-home.",paths:a}),!t.sourceConfig&&s.length>1&&l.push({code:"AMBIGUOUS_CONFIG",message:"Select the previous account configuration with --source-config.",paths:s});let f=t.sourceAppHome?X.resolve(t.sourceAppHome):a.length===1?a[0]:void 0,p=t.sourceConfig?X.resolve(t.sourceConfig):s.length===1?s[0]:void 0;for(let g of[f,p,t.sourceBrowserState])if(g&&!Ct(g))throw new y({code:"MIGRATION_SOURCE_MISSING",path:g,message:"The selected migration source is unavailable.",action:"Correct the source path before retrying."});return{...f?{sourceAppHome:f}:{},...p?{sourceConfig:p}:{},...t.sourceBrowserState?{sourceBrowserState:X.resolve(t.sourceBrowserState)}:{},issues:l,sourceCandidates:{appHomes:a,configs:s}}}c(Un,"discoverMigrationSources");async function Ye(e,t){let r=[e?X.join(e,"state.sqlite"):null,t].filter(o=>!!o);if(!r.length)return;let n=c(()=>new y({code:"MIGRATION_SOURCE_BUSY",path:e??t,message:"A previous OpenPond process is still using the source installation.",action:"Close that installation and retry. No migration source has been changed."}),"fail");if(process.platform==="linux"){for(let o of await Qe.readdir("/proc"))if(!(!/^\d+$/.test(o)||Number(o)===process.pid))try{let i=`/proc/${o}/fd`;for(let a of await Qe.readdir(i)){let s=await Qe.readlink(X.join(i,a)).catch(l=>{if(P(l))return"";throw l});if(r.some(l=>s===l||s===`${l}-wal`||s===`${l}-shm`))throw n()}}catch(i){if(i instanceof y)throw i;if(P(i))continue;if(["EACCES","EPERM"].includes(i.code??"")){let a=await Qe.stat(`/proc/${o}`).catch(s=>{if(P(s))return null;throw s});if(a&&a.uid===process.getuid?.()){let s=await Qe.readFile(`/proc/${o}/cmdline`,"utf8").catch(p=>{if(P(p))return"";throw p}),l=X.basename(s.split("\0")[0]??"");if(/^(?:node|electron|openpond(?:-code)?)(?:\.exe)?$/i.test(l)&&!s.includes("--type=")||r.some(p=>s.includes(p)))throw new y({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"A possible previous runtime could not be inspected for open migration sources.",action:"Close the previous OpenPond processes and retry with process inspection available."})}}else throw i}return}if(process.platform==="darwin"){try{if((await Dn("/usr/sbin/lsof",["-F","p","--",...r],{maxBuffer:1e6})).stdout.split(`
30
- `).some(i=>/^p\d+$/.test(i)&&Number(i.slice(1))!==process.pid))throw n()}catch(o){if(o instanceof y)throw o;if(o.code!==1)throw new y({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"OpenPond could not verify that the previous installation is stopped.",action:"Ensure lsof is available, close the previous app and retry."})}return}if(process.platform==="win32"){let o="Get-CimInstance Win32_Process | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress";try{let{stdout:i}=await Dn("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBuffer:4e6,env:_r()}),a=JSON.parse(i),s=Array.isArray(a)?a:[a];for(let l of s)if(!(!l.CommandLine||l.ProcessId===process.pid)&&/(?:openpond|apps[\\/]server).*(?:serve|server|desktop)/i.test(l.CommandLine)&&(r.some(f=>l.CommandLine.includes(f))||e&&l.CommandLine.includes(e)))throw n()}catch(i){throw i instanceof y?i:new y({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"OpenPond could not inspect previous runtime ownership.",action:"Close the previous app and enable local process inspection before retrying."})}return}throw new y({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"Automatic migration ownership checks are unavailable on this platform.",action:"Migrate this installation on a supported desktop platform."})}c(Ye,"assertMigrationSourcesStopped");import{randomUUID as Si}from"node:crypto";import{promises as q}from"node:fs";import Q from"node:path";var Fn=u.string().min(1).refine(e=>!Q.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).some(t=>!t||t==="."||t==="..")),vi=u.strictObject({path:Fn,sha256:u.string().regex(/^[a-f0-9]{64}$/),executable:u.boolean().optional()}),jn=u.strictObject({schemaVersion:u.literal("openpond.migration.v1"),id:u.string().regex(/^migration-[A-Za-z0-9-]+$/),status:u.enum(["preparing","prepared","installing","committed","verified","failed"]),home:u.string(),stage:u.string(),backup:u.string(),files:u.array(vi),installed:u.array(Fn),sourceAppHome:u.string().optional(),sourceConfig:u.string().optional(),sourceBrowserState:u.string().optional(),resolutions:Ot.optional(),snapshotComplete:u.boolean().optional(),error:u.string().optional(),createdAt:u.string()}),Nt={schemaVersion:"openpond.storage.v1",version:1};async function ke(e){let t=Q.join(_(e).runtime,"migration.json"),r=await M(t,()=>null);if(r===null)return null;let n=jn.safeParse(r);if(!n.success)throw lr(t);let o=n.data,i=Q.resolve(e);if(o.home!==i||o.stage!==Q.join(Q.dirname(i),`.${Q.basename(i)}-${o.id}`)||o.backup!==Q.join(i,"backups",o.id))throw lr(t);let a=new Set(o.files.map(s=>s.path));if(a.size!==o.files.length||o.installed.some(s=>!a.has(s))||o.files.some(s=>/^(runtime|backups)([\\/]|$)/.test(s.path)||s.path==="storage.json"))throw lr(t);return o}c(ke,"readMigrationJournal");function lr(e){return new y({code:"INVALID_MIGRATION_JOURNAL",path:e,message:"The migration journal could not be verified.",action:"Preserve the journal and backups. Restore a verified backup into a separate home."})}c(lr,"invalidJournal");async function ce(e){jn.parse(e),await I(Q.join(_(e.home).runtime,"migration.json"),`${JSON.stringify(e,null,2)}
31
- `)}c(ce,"saveMigrationJournal");async function Ze(e,t=e){let r=[];for(let n of await q.readdir(t,{withFileTypes:!0})){let o=Q.join(t,n.name);n.isDirectory()?r.push(...await Ze(e,o)):r.push({path:Q.relative(e,o),sha256:await K(o),executable:!!((await q.lstat(o)).mode&64)})}return r.sort((n,o)=>n.path.localeCompare(o.path))}c(Ze,"fileReceipts");async function Y(e,t){let r=await q.lstat(e),n=await q.lstat(t).catch(o=>{if(P(o))return null;throw o});if(r.isDirectory()){if(n&&!n.isDirectory())throw new Error(`Backup path is not a directory: ${t}`);await U(t);for(let o of await q.readdir(e))await Y(Q.join(e,o),Q.join(t,o));return}if(n){if(await K(e)!==await K(t))throw new y({code:"SOURCE_CHANGED_DURING_MIGRATION",path:e,message:"A source file changed after its migration backup was created.",action:"Stop the old installation and review the preserved backup before retrying."});return}if(await U(Q.dirname(t)),r.isSymbolicLink())await q.symlink(await q.readlink(e),t);else{let o=`${t}.${Si()}.snapshot`;try{await q.copyFile(e,o,q.constants.COPYFILE_EXCL),await q.chmod(o,r.mode&64?448:384);let i=await q.open(o,"r+");try{await i.sync()}finally{await i.close()}if(await q.link(o,t),process.platform!=="win32"){let a=await q.open(Q.dirname(t),"r");try{await a.sync()}finally{await a.close()}}}finally{await q.rm(o,{force:!0})}}}c(Y,"snapshotCopy");import{existsSync as Bn}from"node:fs";import Re from"node:path";var Ii="CREATE TABLE IF NOT EXISTS storage_path_relocations (source TEXT PRIMARY KEY, destination TEXT NOT NULL)";function xt(e,t){let r=_(e).database;if(!Bn(r))return;let n=[...t].sort((l,f)=>f.from.length-l.from.length);function o(l){if(!Re.isAbsolute(l))return l;let f=n.find(p=>bt(l,p.from));return f?Re.join(f.to,Re.relative(f.from,l)):l}c(o,"rebase");function i(l,f=""){return typeof l=="string"&&/(?:path|directory|root|cwd)$/i.test(f)?o(l):Array.isArray(l)?l.map(p=>i(p,f)):l&&typeof l=="object"?Object.fromEntries(Object.entries(l).map(([p,g])=>[p,["messages","events","turns","metadata","input","output","result","credential","manifest"].includes(p)?g:i(g,p)])):l}c(i,"visit");let a=c(l=>`"${l.replaceAll('"','""')}"`,"quote"),s=D(r);try{s.exec("BEGIN IMMEDIATE"),s.exec(Ii);for(let l of s.prepare("SELECT source, destination FROM storage_path_relocations").all())s.prepare("UPDATE storage_path_relocations SET destination=? WHERE source=?").run(o(l.destination),l.source);for(let l of n)l.from!==l.to&&s.prepare("INSERT INTO storage_path_relocations VALUES (?, ?) ON CONFLICT(source) DO UPDATE SET destination=excluded.destination").run(l.from,l.to);for(let{name:l}of s.prepare("SELECT name FROM sqlite_master WHERE type='table'").all())if(rr.has(l)){let f=s.prepare(`PRAGMA table_info(${a(l)})`).all(),p=f.filter(h=>h.pk).sort((h,w)=>h.pk-w.pk);if(!p.length)continue;let g=f.filter(h=>h.name==="payload"||/(?:_path|_directory|_root)$/.test(h.name)||h.name==="cwd"),m=p.map(h=>`${a(h.name)}=?`).join(" AND ");for(let h of s.prepare(`SELECT * FROM ${a(l)}`).all())for(let w of g){let T=h[w.name];if(typeof T!="string")continue;let N=w.name==="payload"?JSON.stringify(i(JSON.parse(T))):o(T);T!==N&&s.prepare(`UPDATE ${a(l)} SET ${a(w.name)}=? WHERE ${m}`).run(N,...p.map(b=>h[b.name]))}}s.exec("COMMIT; PRAGMA wal_checkpoint(TRUNCATE)")}finally{s.close()}}c(xt,"rebaseStoragePointers");function Li(e,t){let r=_(e).database;if(!Re.isAbsolute(t)||!Bn(r))return t;let n=D(r,!0);try{if(!n.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='storage_path_relocations'").get())return t;let i=n.prepare("SELECT source, destination FROM storage_path_relocations").all().sort((a,s)=>s.source.length-a.source.length).find(a=>bt(t,a.source));return i?Re.join(i.destination,Re.relative(i.source,t)):t}finally{n.close()}}c(Li,"resolveStoredPath");import{existsSync as Pe,promises as et}from"node:fs";import S from"node:path";async function Vn(e){let t=S.join(e.backup,"app"),r=S.join(t,"refiners");if(Pe(S.join(r,"binding.json"))){let s=await M(S.join(r,"binding.json"),()=>({}));if(s.schemaVersion!=="openpond.refinerBinding.v1")throw C(r,"Unsupported Refiner binding schema.");B(e.stage,"refiner_bindings","active",s);let l=S.join(r,"transitions");if(Pe(l))for(let f of await et.readdir(l)){if(!f.endsWith(".json"))continue;let p=await M(S.join(l,f),()=>({}));if(p.schemaVersion!=="openpond.refinerTransitionReceipt.v1"||typeof p.contentHash!="string")throw C(l,"Unsupported Refiner transition schema.");B(e.stage,"refiner_transitions",p.contentHash,p)}await et.rm(S.join(e.stage,"library","refiners","binding.json"),{force:!0}),await et.rm(S.join(e.stage,"library","refiners","transitions"),{recursive:!0,force:!0})}let n=S.join(e.backup,"global","extensions");if(Pe(n)&&(await Y(n,S.join(e.stage,"library","extensions")),Pe(S.join(n,"registry.json")))){let s=await M(S.join(n,"registry.json"),()=>({}));if(s.schemaVersion!==1||!Array.isArray(s.extensions))throw C(n,"Unsupported extension registry schema.");B(e.stage,"extension_installations","registry",s),await et.rm(S.join(e.stage,"library","extensions","registry.json"),{force:!0})}let o=S.join(e.backup,"global","profiles");if(Pe(o)){await Y(o,S.join(e.stage,"library","profiles"));let s=H(e.stage,"profile_installations","library"),l=e.sourceConfig?S.join(S.dirname(e.sourceConfig),"profiles"):null;if(s&&l){let f=c(g=>({...g,...typeof g.repoPath=="string"&&Oi(g.repoPath,l)?{repoPath:S.join(e.home,"library","profiles",S.relative(l,g.repoPath))}:{}}),"rebase"),p=f(s.value);Array.isArray(p.profiles)&&(p.profiles=p.profiles.map(g=>f(g))),B(e.stage,"profile_installations","library",p)}}if(e.sourceBrowserState){let s=S.join(e.backup,"browser-sidebar-state.json"),l=or.safeParse(await M(s,()=>null));if(!l.success)throw C(s,"Unsupported browser tab metadata.");let f=l.data;for(let[p,g]of Object.entries(f.conversations))B(e.stage,"browser_tab_state",p,g)}let i=[];if(e.sourceAppHome){for(let s of["harnesses","refiners"])i.push({from:S.join(e.sourceAppHome,s),to:S.join(e.home,"library",s)});i.push({from:e.sourceAppHome,to:e.home})}if(e.sourceConfig)for(let s of["profiles","extensions"])i.push({from:S.join(S.dirname(e.sourceConfig),s),to:S.join(e.home,"library",s)});xt(e.stage,i);let a=S.join(e.stage,"attachments");Pe(a)&&await $n(e.stage,a,[])}c(Vn,"importAdditionalDomains");function Oi(e,t){let r=S.relative(t,e);return r===""||!r.startsWith(`..${S.sep}`)&&r!==".."&&!S.isAbsolute(r)}c(Oi,"within");async function $n(e,t,r){for(let n of await et.readdir(t,{withFileTypes:!0})){let o=S.join(t,n.name),i=[...r,n.name];if(n.isDirectory())await $n(e,o,i);else if(n.isFile()&&i.length>=3){let a=i.slice(2).join("/");await Tn(e,{owner:{domain:"chat_attachment",id:JSON.stringify([i[0],i[1],a])},displayName:n.name,mediaType:"application/octet-stream",sourceFile:o})}else throw C(o,"Attachment storage contains an unsupported file or symbolic link.")}}c($n,"importAttachments");var Ni=new Set(["config.json","providers.json","provider-secrets.json","provider-secrets.key","personalization.json","SOUL.md","token","state.sqlite","state.sqlite-wal","state.sqlite-shm"]),xi=new Set(["cache","logs","diagnostics","backups","runtime"]);async function Kn(e,t={}){e=E.resolve(e),Le(e);let r=await M(_(e).marker,()=>null),n=await ke(e);if(r&&(Gn(r,e),!n||n.status==="verified"))return t.sourceBrowserState&&!t.dryRun&&await bn(e,t.sourceBrowserState),Me(e,"current",n);if(n&&!t.dryRun)return Pi(e);let o=await Un(e,t),{issues:i,sourceCandidates:a,...s}=o;if(t.dryRun)return{...Me(e,"planned",null),sourceAppHome:s.sourceAppHome??null,sourceConfig:s.sourceConfig??null,issues:i,sourceCandidates:a,...i.length?{}:{preview:await hn(e,s,Hn)}};if(i.length)throw C(e,i.map(l=>l.message).join(" "));return L(E.join(_(e).runtime,"migration-owner"),async()=>{let l=await M(_(e).marker,()=>null);if(l)return Gn(l,e),Me(e,"current",null);let f=await ke(e);if(f)return dr(f);if(!s.sourceAppHome&&!s.sourceConfig&&!s.sourceBrowserState)return await U(e),await O(e),await I(_(e).marker,`${JSON.stringify({...Nt,migrationId:null},null,2)}
32
- `),Me(e,"new",null);for(let m of[_(e).database,_(e).credentials])if(m&&le(m))throw C(m,"The destination already contains authoritative state. Import the previous installation into a fresh home; existing history and credentials have been preserved.");await Ye(s.sourceAppHome,s.sourceConfig);let p=`migration-${new Date().toISOString().replace(/[:.]/g,"-")}-${ur().slice(0,8)}`,g={schemaVersion:"openpond.migration.v1",id:p,status:"preparing",home:e,stage:E.join(E.dirname(e),`.${E.basename(e)}-${p}`),backup:E.join(e,"backups",p),files:[],installed:[],...s,resolutions:t.resolutions,createdAt:new Date().toISOString()};return await ce(g),dr(g)})}c(Kn,"initializeHome");function Gn(e,t){if(e.version!==1||e.schemaVersion!==Nt.schemaVersion)throw new y({code:"UNSUPPORTED_STORAGE_VERSION",path:_(t).marker,message:"This OpenPond home requires a different application version.",action:"Update OpenPond, or restore a compatible backup into a separate home."})}c(Gn,"assertLayout");async function ki(e){if(!e.snapshotComplete){if(await Ye(e.sourceAppHome,e.sourceConfig),await U(e.backup),e.sourceConfig){await Y(e.sourceConfig,E.join(e.backup,"config.json"));for(let t of["extensions","profiles"]){let r=E.join(E.dirname(e.sourceConfig),t);le(r)&&await Y(r,E.join(e.backup,"global",t))}}if(e.sourceBrowserState&&await Y(e.sourceBrowserState,E.join(e.backup,"browser-sidebar-state.json")),e.sourceAppHome){for(let n of await R.readdir(e.sourceAppHome,{withFileTypes:!0}))["openpond-app","openpond-app-nightly","storage.json","config.toml","state","browser"].includes(n.name)||xi.has(n.name)||n.name.startsWith("state.sqlite")||await Y(E.join(e.sourceAppHome,n.name),E.join(e.backup,"app",n.name));let t=E.join(e.sourceAppHome,"state.sqlite"),r=E.join(e.backup,"state.sqlite");if(le(t)&&!le(r)){let n=`${r}.${ur()}.tmp`,o=D(t,!0);try{await Ci(o,n);let i=await R.open(n,"r+");try{await i.sync()}finally{await i.close()}if(await R.rename(n,r),process.platform!=="win32"){let a=await R.open(E.dirname(r),"r");try{await a.sync()}finally{await a.close()}}}finally{o.close(),await R.rm(n,{force:!0})}}}await Ye(e.sourceAppHome,e.sourceConfig),e.snapshotComplete=!0,await ce(e)}}c(ki,"captureSources");async function Hn(e){await ki(e),await U(e.stage);let t=E.join(e.backup,"app");if(le(t))for(let n of await R.readdir(t)){if(Ni.has(n)||n==="souls"||/^soul-.+\.md$/i.test(n))continue;let o=["harnesses","refiners"].includes(n)?E.join("library",n):n;await Y(E.join(t,n),E.join(e.stage,o))}le(E.join(e.backup,"state.sqlite"))&&await Y(E.join(e.backup,"state.sqlite"),_(e.stage).database),await Nn(e.stage,e.sourceConfig?E.join(e.backup,"config.json"):void 0),await xn(e.stage,e.sourceAppHome),await kn(e.stage,e.sourceAppHome?t:void 0),await Rn(e.stage,e.sourceAppHome?t:void 0),await Pn(e.stage,e.sourceAppHome?t:void 0);let r=await A(E.join(t,"token"));r&&await I(_(e.stage).token,r),await Vn(e),le(_(e.home).config)&&await En(e.home,e.stage,e.resolutions),await Se(e.stage),await R.rm(E.join(e.stage,"runtime"),{recursive:!0,force:!0}),await R.rm(E.join(e.stage,"backups"),{recursive:!0,force:!0}),await R.rm(E.join(e.stage,"datasets","settings.json"),{force:!0}),e.files=(await Ze(e.stage)).filter(n=>!n.path.endsWith("-wal")&&!n.path.endsWith("-shm")),e.status="prepared",await ce(e)}c(Hn,"prepare");async function Se(e){let{document:t}=await O(e);await un(e);for(let r of Object.values(t.providers??{}))if(r.credential?.source==="secret"&&!await Et(e,r.credential.id))throw C(_(e).config,"An imported provider credential is missing.");if(le(_(e).database)){let r=D(_(e).database);try{let n=r.prepare("PRAGMA integrity_check").all();if(n.length!==1||Object.values(n[0])[0]!=="ok"||r.prepare("PRAGMA foreign_key_check").all().length)throw C(_(e).database,"The imported database failed integrity checks.");r.exec("PRAGMA wal_checkpoint(TRUNCATE)")}finally{r.close()}await wn(e)}}c(Se,"validateMigratedHome");async function Ri(e){e.status="installing",await ce(e);for(let t of e.files){let r=E.join(e.home,t.path),n=E.join(e.stage,t.path),o=le(r)?await K(r):null;if(e.installed.includes(t.path)&&o!==t.sha256)throw C(r,"An installed file changed before migration recovery completed.");if(o!==t.sha256){if(await K(n)!==t.sha256)throw C(n,"A staged file failed its checksum check.");if(o!==null&&await Y(r,E.join(e.backup,"destination",t.path)),await U(E.dirname(r)),(await R.lstat(n)).isSymbolicLink())le(r)&&await R.unlink(r),await R.symlink(await R.readlink(n),r);else{let a=`${r}.${ur()}.migration`;try{await R.copyFile(n,a),await R.chmod(a,t.executable?448:384);let s=await R.open(a,"r+");try{await s.sync()}finally{await s.close()}await R.rename(a,r)}finally{await R.rm(a,{force:!0})}}}if(process.platform!=="win32"){let i=await R.open(E.dirname(r),"r");try{await i.sync()}finally{await i.close()}}e.installed.includes(t.path)||e.installed.push(t.path),await ce(e)}await Se(e.home),await I(_(e.home).marker,`${JSON.stringify({...Nt,migrationId:e.id},null,2)}
33
- `),e.status="committed",await ce(e),e.status="verified",delete e.error,await ce(e),await R.rm(e.stage,{recursive:!0,force:!0})}c(Ri,"install");async function Pi(e){return L(E.join(_(e).runtime,"migration-owner"),async()=>{let t=await ke(e);if(!t)throw C(e,"No migration journal is available.");return dr(t)})}c(Pi,"recoverMigration");async function dr(e){if(e.status==="verified")return Me(e.home,"current",e);try{return(e.status==="preparing"||e.status==="failed")&&(await R.rm(e.stage,{recursive:!0,force:!0}),e.status="preparing",await Hn(e)),e.status!=="committed"?await Ri(e):(await Se(e.home),e.status="verified",await ce(e),await R.rm(e.stage,{recursive:!0,force:!0})),Me(e.home,"verified",e)}catch(t){throw e.error=t instanceof y?t.issue.code:"MIGRATION_FAILED",e.status==="preparing"&&(e.status="failed"),await ce(e),t instanceof y?t:new y({code:"MIGRATION_FAILED",path:E.join(_(e.home).runtime,"migration.json"),message:"OpenPond could not finish updating its storage.",action:"Open migration details or run openpond config recover. Original data and snapshots have been preserved."},{cause:t})}}c(dr,"recoverUnlocked");function Me(e,t,r){return{id:r?.id??null,status:t,home:e,sourceAppHome:r?.sourceAppHome??null,sourceConfig:r?.sourceConfig??null,backup:r?.backup??null}}c(Me,"report");async function hd(e){return L(E.join(_(e).runtime,"migration-owner"),async()=>{let t=await ke(e);if(!t)return{restarted:!1,backup:null};if(!["preparing","failed"].includes(t.status)||t.installed.length||t.files.length)throw C(e,"Installation has already begun. Resume recovery or restore into a fresh home; preparation cannot be restarted.");return await Ye(t.sourceAppHome,t.sourceConfig),await I(E.join(t.backup,"abandoned-preparation.json"),JSON.stringify(t,null,2)),await R.rm(t.stage,{recursive:!0,force:!0}),await R.rm(E.join(_(e).runtime,"migration.json")),{restarted:!0,backup:t.backup}})}c(hd,"restartMigration");async function Mi(e){let t=await O(e),r=H(e,"client_preferences","global");return{preferences:ze(t.document,r?.value),config:t}}c(Mi,"readPreferences");async function Id(e,t,r){return L(`${_(e).runtime}/preferences`,async()=>{let n=H(e,"client_preferences","global"),o=n?.value;return await W(e,i=>{let a=ze(i,n?.value),s=ee.parse({...a,...t,...t.defaultChatModelRef===void 0&&(t.defaultChatModel!==void 0||t.defaultChatProvider!==void 0)?{defaultChatModelRef:{providerId:t.defaultChatProvider??a.defaultChatProvider,modelId:t.defaultChatModel??a.defaultChatModel}}:{}});o=yt(s);let l=structuredClone(i);for(let f of ae(Ee(a),Ee(s))){let p=l;for(let m of f.path.slice(0,-1))p[m]??={},p=p[m];let g=f.path.at(-1);f.op==="set"?p[g]=f.value:delete p[g]}return l},r),o&&JSON.stringify(o)!==JSON.stringify(n?.value)&&B(e,"client_preferences","global",o,n?.revision??null),Mi(e)})}c(Id,"updatePreferences");import{createHash as Di}from"node:crypto";import{promises as ve}from"node:fs";import zn from"node:path";var pe=c(e=>Di("sha256").update(JSON.stringify(e)??"null").digest("hex"),"hash"),Wn=c((e,t="local")=>pe([e,t]),"trustKey");async function Vd(e,t,r,n){let o=await ve.realpath(t);B(e,"project_trust",Wn(o,r),{root:o,accountId:r,trusted:n,updatedAt:new Date().toISOString()})}c(Vd,"setProjectTrust");async function Xn(e,t={}){let r=Ee(ee.parse({})),n=[],o={},i=[];function a(h,w,T,N=pe(w)){let b={layer:h,path:T,revision:N};r=gt(r,w),n.push(b);function v(j,de){if(j&&typeof j=="object"&&!Array.isArray(j)&&!("mode"in j)&&!("source"in j)&&!("provider_id"in j))for(let[Ue,rt]of Object.entries(j))v(rt,[...de,Ue]);else o[JSON.stringify(de)]=b}c(v,"visit"),v(w,[])}c(a,"apply"),a("defaults",r,"shipped"),t.profile&&(Jn(t.profile.defaults,"profile"),a("profile",t.profile.defaults,t.profile.id,t.profile.revision));let s=await O(e);a("user",s.document,s.path,s.rawRevision);let l=structuredClone(r.permissions),f=null,p=null;if(t.projectRoot){f=await ve.realpath(t.projectRoot);let h=zn.join(f,".openpond","config.toml");if(await ve.lstat(h).catch(T=>{if(P(T))return null;throw T})){if(await ve.realpath(h)!==h)throw new y({code:"UNSAFE_PROJECT_CONFIG",path:h,message:"Project configuration must be a regular file inside its canonical project root.",action:"Replace symbolic links in the project configuration path with a regular local file."});let N=H(e,"project_trust",Wn(f,t.accountId));if(!N?.value.trusted)i.push({code:"PROJECT_CONFIG_UNTRUSTED",path:h,message:"Project settings are ignored until this project is trusted.",action:"Review the project configuration, then trust it in configuration settings."});else{p=N.revision;let b=await O(e,{path:h,scope:"project"});a("project",b.document,b.path,b.rawRevision),l?.command_access==="disabled"&&(r.permissions={...r.permissions,command_access:"disabled"}),l?.codex_mode==="default"&&(r.permissions={...r.permissions,codex_mode:"default"}),l=structuredClone(r.permissions)}}}for(let h of["task","turn"])t[h]&&(Jn(t[h],h),a(h,t[h],h));(l?.command_access==="disabled"||l?.command_access==="ask"&&r.permissions?.command_access==="full-access")&&(r.permissions={...r.permissions,command_access:l.command_access}),l?.codex_mode&&l.codex_mode!=="full-access"&&r.permissions?.codex_mode!=="default"&&(r.permissions={...r.permissions,codex_mode:l.codex_mode}),oe(r),await Ui(e,r);let g=[...Object.values(r.accounts??{}),...Object.values(r.providers??{})].flatMap(h=>h.credential?.source==="secret"?[h.credential.id]:[]),m=await cn(e,g);return{document:r,effectiveRevision:pe({document:r,sources:n,projectTrustRevision:p,versions:m}),sources:n,provenance:o,diagnostics:i,projectRoot:f,projectTrustRevision:p,credentialVersions:m}}c(Xn,"resolveEffectiveConfig");function Jn(e,t){oe(e);let r=t==="profile"?["schema_version","chat","codex","context_compaction","subagents","runtime"]:["schema_version","chat","codex","context_compaction","subagents","permissions"];for(let n of Object.keys(e))if(!r.includes(n))throw new y({code:"CONFIG_SCOPE_VIOLATION",path:`${t}.${n}`,message:`This setting is not allowed in ${t} configuration.`,action:"Move host settings to the user configuration file."})}c(Jn,"checkScope");async function Ui(e,t){let r=t.defaults;if(r?.account_id&&(!t.accounts?.[r.account_id]||t.accounts[r.account_id].enabled===!1))throw new y({code:"INVALID_ACCOUNT_DEFAULT",path:"defaults.account_id",message:"The default account is missing or disabled.",action:"Choose an enabled account or remove the explicit default."});let n=t.personalization?.active;if(n&&t.personalization?.mode!=="disabled"){let i=n.startsWith("custom:")?zn.join(e,"instructions","personalities",`${n.slice(7)}.md`):n,a=n.startsWith("custom:")?await A(i):nt.find(s=>s.id===n.slice(8))?.content;if(a==null||a.trim().length>8e3)throw new y({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The selected personality is missing or exceeds its supported size.",action:"Restore its Markdown file or select an available personality in Settings."})}let o=t.personalization?.user_instructions;if(o){let i=Fe(o,e);try{if(!(await ve.stat(i)).isFile())throw new Error("Not a file");await ve.access(i,ve.constants.R_OK)}catch(a){throw new y({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The configured user instruction file cannot be read.",action:"Restore the file or remove its configuration reference."},{cause:a})}}}c(Ui,"validateRequiredSources");async function $d(e,t,r={}){let n=await Xn(e,r);return B(e,"config_run_snapshots",t,{...n,capturedAt:new Date().toISOString()},null),n}c($d,"captureConfigRun");async function Gd(e,t,r={}){let n=await Xn(e,r);if(t.projectTrustRevision!==null&&n.projectTrustRevision!==t.projectTrustRevision)throw new y({code:"PROJECT_TRUST_CHANGED",path:t.projectRoot??e,message:"Project trust changed during this turn.",action:"Review project trust before starting a new turn."});let o=t.document.permissions,i=n.document.permissions;if(i?.command_access!==o?.command_access||i?.codex_mode!==o?.codex_mode||pe(n.credentialVersions)!==pe(t.credentialVersions)||pe(n.document.accounts)!==pe(t.document.accounts)||pe(n.document.providers)!==pe(t.document.providers))throw new y({code:"EXECUTION_POLICY_CHANGED",path:e,message:"Permissions or credential configuration changed during this turn.",action:"Start a new turn with the current settings."})}c(Gd,"assertConfigRunCurrent");function Kd(e){return ze(e.document)}c(Kd,"effectivePreferences");import{createHash as Fi}from"node:crypto";var kt=u.strictObject({chatMode:u.enum(["chat","work"]).optional(),sidebarPresentation:u.enum(["grouped","inbox"]).optional(),notificationMode:u.enum(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:u.boolean().optional(),sidebarVisibility:u.strictObject({showCodexChats:u.boolean(),onlyRunningTasks:u.boolean()}).optional(),scheduledWorkView:u.enum(["calendar","list"]).optional(),editorControlsVisible:u.boolean().optional(),voiceNoticeAcknowledged:u.boolean().optional(),lessonProgress:u.record(u.string().min(1).max(200),u.strictObject({completed:u.boolean(),currentTime:u.number().finite().nonnegative(),duration:u.number().finite().positive(),updatedAt:u.number().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Wd={"openpond:last-chat-task-mode":"chatMode","openpond.sidebar.presentation.v1":"sidebarPresentation","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"};import ji from"node:path";async function qn(e){let r=(await O(e)).document.defaults?.account_id??H(e,"account_selection","last_used")?.value??"local";return`choices:${Fi("sha256").update(JSON.stringify(r)).digest("hex")}`}c(qn,"scope");async function Bi(e){let t=await qn(e),r=H(e,"client_preferences",t),n=await O(e);return{owner:t,revision:r?.revision??null,value:kt.parse({...r?.value,notificationMode:n.document.notifications?.team_chat??"all"})}}c(Bi,"readClientChoices");async function ou(e,t,r,n=!1){return L(ji.join(_(e).runtime,"accounts"),async()=>{let o=kt.parse(r);if(await qn(e)!==t)throw new y({code:"CLIENT_OWNER_CHANGED",path:"client_preferences",message:"The active account changed before this preference was saved.",action:"Reload preferences for the current account."});let{notificationMode:i,...a}=o;return i!==void 0&&await W(e,s=>n&&s.notifications?.team_chat!==void 0?s:{...s,notifications:{...s.notifications,team_chat:i}}),fe(e,s=>{s.exec("BEGIN IMMEDIATE");try{let l=s.prepare("SELECT payload, revision FROM client_preferences WHERE id=?").get(t),f=l?JSON.parse(l.payload):{};delete f.notificationMode;let p=kt.parse(n?{...a,...f}:{...f,...a});s.prepare("INSERT INTO client_preferences VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(t,JSON.stringify(p)),s.exec("COMMIT")}catch(l){throw s.exec("ROLLBACK"),l}}),Bi(e)})}c(ou,"updateClientChoices");import{randomUUID as pr}from"node:crypto";import{promises as Z}from"node:fs";import k from"node:path";import{backup as qi}from"node:sqlite";import{createCipheriv as Vi,createDecipheriv as $i,randomBytes as Gi}from"node:crypto";import{createReadStream as Qn,createWriteStream as Ki,promises as De}from"node:fs";import ne from"node:path";import{Readable as Hi}from"node:stream";import{pipeline as Yn}from"node:stream/promises";import{createGzip as Ji,createGunzip as zi}from"node:zlib";var Ie=Buffer.from("OPBK1\0"),Wi=u.string().min(1).refine(e=>!ne.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).some(t=>!t||t==="."||t==="..")),Xi=u.strictObject({path:Wi,sizeBytes:u.number().safe().int().nonnegative(),sha256:u.string().regex(/^[a-f0-9]{64}$/),executable:u.boolean(),link:u.string().optional()}),Zn=u.strictObject({schemaVersion:u.literal("openpond.recoveryBackup.v1"),originalHome:u.string(),createdAt:u.string().datetime(),entries:u.array(Xi).max(5e5),externalRoots:u.array(u.strictObject({path:u.string(),available:u.boolean(),included:u.literal(!1)})),browserIncluded:u.boolean()});async function eo(e,t,r,n){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let o=Buffer.from(JSON.stringify(Zn.parse(n)));if(o.length>32*1024*1024)throw new Error("Backup manifest exceeds the supported size.");let i=Buffer.alloc(4);i.writeUInt32BE(o.length);let a=Gi(12),s=Vi("aes-256-gcm",r,a);s.setAAD(Ie);let l=await De.open(t,"wx",384);try{await l.write(Buffer.concat([Ie,a])),await l.sync()}finally{await l.close()}async function*f(){yield i,yield o;for(let g of n.entries)if(g.link===void 0)for await(let m of Qn(ne.join(e,g.path)))yield m}c(f,"archive"),await Yn(Hi.from(f()),Ji(),s,Ki(t,{flags:"a"}));let p=await De.open(t,"a");try{await p.write(s.getAuthTag()),await p.sync()}finally{await p.close()}}c(eo,"encryptBackup");async function to(e,t,r){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let n=(await De.stat(e)).size,o=Ie.length+12;if(n<o+16)throw new Error("Truncated recovery backup.");let i=await De.open(e,"r"),a=Buffer.alloc(o),s=Buffer.alloc(16);try{await i.read(a,0,a.length,0),await i.read(s,0,16,n-16)}finally{await i.close()}if(!a.subarray(0,Ie.length).equals(Ie))throw new Error("Unsupported recovery backup format.");let l=$i("aes-256-gcm",r,a.subarray(Ie.length));l.setAAD(Ie),l.setAuthTag(s);let f=Qn(e,{start:o,end:n-17}),p=zi(),g=Yn(f,l,p);g.catch(()=>{});let m=p[Symbol.asyncIterator](),h=Buffer.alloc(0),w=0;async function T(N){let b=Buffer.alloc(N),v=0;for(;v<N;){if(w>=h.length){let de=await m.next();if(de.done)throw new Error("Truncated recovery object.");h=Buffer.from(de.value),w=0}let j=Math.min(N-v,h.length-w);h.copy(b,v,w,w+j),w+=j,v+=j}return b}c(T,"take");try{let N=(await T(4)).readUInt32BE();if(N>32*1024*1024)throw new Error("Invalid recovery manifest size.");let b=Zn.parse(JSON.parse((await T(N)).toString("utf8")));if(new Set(b.entries.map(v=>v.path)).size!==b.entries.length)throw new Error("Duplicate recovery object paths.");for(let v of b.entries){let j=ne.join(t,v.path);if(/^(runtime|backups)([\\/]|$)/.test(v.path)||v.path.endsWith("-wal")||v.path.endsWith("-shm"))throw new Error("Recovery manifest contains an unsupported runtime object.");if(await U(ne.dirname(j)),v.link!==void 0){if(ne.isAbsolute(v.link)||!tt(ne.resolve(ne.dirname(j),v.link),t))throw new Error("Recovery symlink leaves the backup root.");await De.symlink(v.link,j)}else{let de=await De.open(j,"wx",v.executable?448:384);try{for(let Ue=v.sizeBytes;Ue>0;){let rt=await T(Math.min(1048576,Ue));await de.writeFile(rt),Ue-=rt.length}await de.sync()}finally{await de.close()}}if(await K(j)!==v.sha256)throw new Error("Recovery object failed its checksum.")}if(w<h.length||!(await m.next()).done)throw new Error("Unexpected trailing recovery data.");return await g,b}catch(N){throw f.destroy(),l.destroy(),p.destroy(),await g.catch(()=>{}),N}}c(to,"decryptBackup");function tt(e,t){let r=ne.relative(ne.resolve(t),ne.resolve(e));return r===""||r!==".."&&!r.startsWith(`..${ne.sep}`)&&!ne.isAbsolute(r)}c(tt,"within");var Qi=new Set(["backups","runtime","cache","logs","diagnostics","browser","tmp","openpond-app","openpond-app-nightly","config.json","state.sqlite","state.sqlite-wal","state.sqlite-shm","providers.json","provider-secrets.json","provider-secrets.key","personalization.json","SOUL.md","token"]);async function ku(e,t,r){if(e=k.resolve(e),t=k.resolve(t),tt(t,e))throw new Error("Export recovery backups outside the active home.");let n=[],o=k.join(k.dirname(e),`.${k.basename(e)}-backup-${pr()}`),i=`${t}.${pr()}.tmp`;try{n.push(await _e(k.join(_(e).runtime,"server-owner"),100)),await Kn(e);for(let f of["accounts","providers","preferences","personalization","artifacts"])n.push(await _e(k.join(_(e).runtime,f)));n.push(await _e(_(e).config)),n.push(await _e(_(e).credentials)),await U(o);for(let f of await Z.readdir(e))Qi.has(f)||f==="state"||await Y(k.join(e,f),k.join(o,f));let a=_(e).database;if(await Z.stat(a).catch(f=>{if(P(f))return null;throw f})){await U(k.dirname(_(o).database));let f=D(a,!0);try{await qi(f,_(o).database)}finally{f.close()}}await Se(o);let s=await St(e),l=[];for(let f of await Ze(o)){if(f.path.endsWith("-wal")||f.path.endsWith("-shm")||/^(config\.toml|secrets[\\/](?:credentials\.json|server-token))\.lock(?:\.|$)/.test(f.path))continue;let p=k.join(o,f.path),g=await Z.lstat(p),m=g.isSymbolicLink()?await Z.readlink(p):void 0;if(m!==void 0&&(k.isAbsolute(m)||!tt(k.resolve(k.dirname(p),m),o)))throw new Error(`Source symlink requires rebinding before export: ${f.path}`);l.push({path:f.path,sha256:f.sha256,sizeBytes:m===void 0?g.size:0,executable:f.executable??!1,...m===void 0?{}:{link:m}})}return await Z.mkdir(k.dirname(t),{recursive:!0,mode:448}),await eo(o,i,r,{schemaVersion:"openpond.recoveryBackup.v1",originalHome:e,createdAt:new Date().toISOString(),entries:l,externalRoots:s,browserIncluded:!1}),await Z.link(i,t),{path:t,files:l.length,externalRoots:s}}catch(a){throw a instanceof y?a:new y({code:"BACKUP_FAILED",path:t,message:"The recovery backup could not be completed.",action:"Keep the application stopped, check the destination and supplied encryption key, then retry. Existing backups are never overwritten."},{cause:a})}finally{await Z.rm(o,{recursive:!0,force:!0}),await Z.rm(i,{force:!0});for(let a of n.reverse())await a()}}c(ku,"exportRecoveryBackup");async function Ru(e,t,r){t=k.resolve(t);let n=await Z.lstat(t).catch(i=>{if(P(i))return null;throw i});if(n&&(!n.isDirectory()||(await Z.readdir(t)).length))throw new Error("Restore requires a fresh, empty home. Existing homes are never overwritten.");let o=k.join(k.dirname(t),`.${k.basename(t)}-restore-${pr()}`);await U(o);try{let i=await to(e,o,r);return await Se(o),await Yi(o,i.originalHome,t),await I(_(o).marker,JSON.stringify({schemaVersion:"openpond.storage.v1",version:1,migrationId:null,restoredAt:new Date().toISOString()})),await I(k.join(o,"restore-receipt.json"),JSON.stringify({schemaVersion:"openpond.restoreReceipt.v1",originalHome:i.originalHome,restoredAt:new Date().toISOString(),externalRoots:i.externalRoots})),await Se(o),n&&await Z.rmdir(t),await Z.rename(o,t),{home:t,files:i.entries.length,externalRoots:await Promise.all(i.externalRoots.map(async a=>({...a,available:!!await Z.stat(a.path).catch(()=>null)})))}}catch(i){throw new y({code:"RESTORE_FAILED",path:t,message:"The backup could not be authenticated and validated for restoration.",action:"Check the backup and its separately stored key. The existing home has not been replaced."},{cause:i})}finally{await Z.rm(o,{recursive:!0,force:!0})}}c(Ru,"restoreRecoveryBackup");async function Yi(e,t,r){let n=c(o=>tt(o,t)?k.join(r,k.relative(t,o)):o,"rebase");await W(e,o=>({...o,...o.storage?.datasets_dir&&k.isAbsolute(o.storage.datasets_dir)?{storage:{...o.storage,datasets_dir:n(o.storage.datasets_dir)}}:{},...o.personalization?.user_instructions&&k.isAbsolute(o.personalization.user_instructions)?{personalization:{...o.personalization,user_instructions:n(o.personalization.user_instructions)}}:{},...o.projects?.new_project_directory&&k.isAbsolute(o.projects.new_project_directory)?{projects:{...o.projects,new_project_directory:n(o.projects.new_project_directory)}}:{}})),xt(e,[{from:t,to:r}])}c(Yi,"rebaseRestoredPointers");async function Uu(e){let t=structuredClone((await O(e)).document),r=[];function n(o,i,a,s){o&&Object.hasOwn(o,i)&&(delete o[i],r.push({path:[...a,i],reason:s}))}c(n,"omit");for(let o of["accounts","providers"])for(let[i,a]of Object.entries(t[o]??{}))n(a,"credential",[o,i],"Reconnect or bind a credential on the destination device.");for(let o of["accounts","providers"])for(let[i,a]of Object.entries(t[o]??{}))for(let s of["base_url","api_base_url","chat_api_base_url"]){let l=a[s];if(typeof l=="string")try{let f=new URL(l);(f.username||f.password||[...f.searchParams.keys()].some(p=>/token|key|secret|password|credential|signature/i.test(p))||f.hash)&&n(a,s,[o,i],"Rebind this endpoint without embedded authentication data.")}catch{n(a,s,[o,i],"Validate and bind this endpoint on the destination device.")}}n(t.storage,"datasets_dir",["storage"],"Choose the dataset storage root on the destination device."),n(t.projects,"new_project_directory",["projects"],"Choose the local projects directory."),n(t.personalization,"user_instructions",["personalization"],"Transfer the instruction source and bind its destination path."),t.personalization?.active?.startsWith("custom:")&&n(t.personalization,"active",["personalization"],"Transfer the selected custom personality Markdown before selecting it."),n(t.defaults,"profile_ref",["defaults"],"Install and select the Profile on the destination device.");for(let[o,i]of Object.entries(t.editor?.languages??{}))i.custom_command&&(n(i,"custom_command",["editor","languages",o],"Configure the local language-server command."),i.mode==="custom"&&delete i.mode);return{schemaVersion:"openpond.settingsExport.v1",config:t,requiresRebinding:r}}c(Uu,"exportSettings");async function Zi(e){let t=_(e).marker,r=await M(t,()=>null);if(r&&(r.schemaVersion!=="openpond.storage.v1"||r.version!==1))throw new y({code:"UNSUPPORTED_STORAGE_VERSION",path:t,message:"This OpenPond home requires a different application version.",action:"Update OpenPond, or restore a compatible backup into a separate home."})}c(Zi,"assertHomeCompatible");export{no as a,$ as b,A as c,U as d,I as e,L as f,_e as g,io as h,M as i,aa as j,kr as k,Ft as l,oe as m,ae as n,Xo as o,Xt as p,mt as q,qo as r,Qo as s,Ja as t,za as u,O as v,is as w,W as x,gt as y,as as z,ds as A,Ee as B,ze as C,yt as D,ys as E,Yt as F,ws as G,Ts as H,Et as I,Os as J,At as K,an as L,sn as M,cn as N,Ne as O,un as P,fn as Q,wn as R,Tn as S,gi as T,yc as U,wc as V,Tc as W,Ot as X,ke as Y,Li as Z,Kn as _,Se as $,Pi as aa,hd as ba,Mi as ca,Id as da,Vd as ea,Xn as fa,$d as ga,Gd as ha,Kd as ia,kt as ja,Wd as ka,Bi as la,ou as ma,ku as na,Ru as oa,Uu as pa,Zi as qa};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{W as H,X as y,Y as C,_ as E,aa as S,ba as P,ca as j,ea as I}from"./chunk-IKWDL3RB.js";import{D as h,F as v,G as l,L as w,N as b}from"./chunk-QRWPEW3Z.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as f}from"./chunk-FTQLQJQV.js";var a=e.string().min(1).max(240),d=e.string().regex(/^[a-f0-9]{64}$/),g=e.string().regex(/^[a-f0-9]{40}$/),x=e.object({schemaVersion:e.literal("openpond.hostedProfileCandidateExport.v1"),actorId:a,teamId:a,candidateId:a,candidateRevision:e.number().int().positive(),projectId:a.nullable(),profileRef:e.object({source:e.literal("openpond_git"),repositoryId:a,profileId:a}).strict(),expectedCommit:g,component:y.shape.component,baseRelease:h,frozenHash:d,executableSourceHash:d,protectedClosureHash:d,compiler:e.object({workspaceId:a,name:e.string().max(500),repositoryId:a}).strict(),sourceManifest:e.object({base64:e.string().max(28e5),contentHash:d,sizeBytes:e.number().int().positive().max(2e6)}).strict(),policySource:w,qualification:e.object({kind:e.enum(["owner_attested_local","hosted_execution"]),ownerActorId:a,teamId:a,originalEvidence:h,baseline:h,candidate:h,comparisonHash:d,recipe:H}).strict(),createdAt:e.string().datetime(),contentHash:d}).strict();function J(n){let o=x.parse(n),{contentHash:t,...c}=o;if(l(c)!==t||o.qualification.ownerActorId!==o.actorId||o.qualification.teamId!==o.teamId||o.qualification.recipe.externalDatasetBinding.profileId!==o.profileRef.profileId||o.qualification.recipe.externalDatasetBinding.protectedProfileClosureHash!==o.protectedClosureHash)throw new Error("Hosted candidate owner attestation identity differs.");return b(o.policySource),o}f(J,"verifyHostedProfileCandidateExport");var O=e.object({schemaVersion:e.literal("openpond.hostedProfileCandidateAdoption.v1"),id:a,operationId:a,actorId:a,teamId:a,candidateId:a,exportHash:d,executionOrigin:e.enum(["owner_attested_local","hosted_execution"]),qualification:x.shape.qualification,testedCandidateRelease:h,activeRelease:h,expectedCommit:g,committedProfileGit:g,executableSourceHash:d,protectedClosureHash:d,createdAt:e.string().datetime(),contentHash:d}).strict();function R(n){let o=O.parse(n),{contentHash:t,...c}=o;if(l(c)!==t||o.executionOrigin!==o.qualification.kind||o.qualification.ownerActorId!==o.actorId||o.qualification.teamId!==o.teamId)throw new Error("Hosted candidate receipt integrity differs.");return o}f(R,"verifyHostedProfileCandidateReceipt");var T=e.discriminatedUnion("operation",[e.object({operation:e.literal("adopt"),operationId:a,export:x}).strict(),e.object({operation:e.enum(["read","rollback"]),operationId:a,adoptionOperationId:a,profileRepositoryId:a}).strict()]),K=class{static{f(this,"ExperimentImprovementClient")}constructor(n){this.options=n;let o=new URL(n.baseUrl);if(!["http:","https:"].includes(o.protocol)||o.username||o.password||o.hash||o.search||!n.apiKey.trim()||!n.teamId.trim()||!n.actorId.trim())throw new Error("Select the authenticated Improve owner and API origin.");this.origin=o.toString().replace(/\/+$/,"")}options;origin;async hostedCandidate(n,o){let t=T.parse(n);if(t.operation==="adopt"&&(t.export.actorId!==this.options.actorId||t.export.teamId!==this.options.teamId))throw new Error("The hosted candidate export belongs to a different owner.");let{response:c,value:p}=await I(this.options.fetch??fetch,`${this.origin}/v1/profile-candidate-adoptions`,{method:"POST",redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"Content-Type":"application/json","X-OpenPond-Team-Id":this.options.teamId},body:JSON.stringify({teamId:this.options.teamId,command:t}),signal:o},(m,u,r)=>Object.assign(new Error(r),{status:m,code:u}));if(!c.ok){let m=e.object({code:e.string(),message:e.string().optional(),error:e.string().optional()}).passthrough().safeParse(p);throw Object.assign(new Error(m.success?m.data.message??m.data.error??m.data.code:"Hosted candidate operation failed."),{status:c.status,code:m.success?m.data.code:void 0})}let i=R(p);if(i.actorId!==this.options.actorId||i.teamId!==this.options.teamId||i.operationId!==t.operationId||t.operation==="adopt"&&(i.exportHash!==t.export.contentHash||i.candidateId!==t.export.candidateId||i.testedCandidateRelease.contentHash!==t.export.policySource.harnessRelease.contentHash))throw new Error("Hosted candidate readback differs from the exact owner request.");return i}async command(n,o){let t=S.parse(n),{response:c,value:p}=await I(this.options.fetch??fetch,`${this.origin}/v1/experiment-improvements`,{method:"POST",redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"Content-Type":"application/json","X-OpenPond-Team-Id":this.options.teamId},body:JSON.stringify({teamId:this.options.teamId,request:t}),signal:o},(r,s,q)=>Object.assign(new Error(q),{status:r,code:s}));if(!c.ok){let r=e.object({error:e.string(),code:e.string().optional()}).passthrough().safeParse(p);throw Object.assign(new Error(r.success?r.data.error:"The Improve operation failed."),{status:c.status,code:r.success?r.data.code:void 0})}if(t.operation==="options"){let r=P.parse(p);if(r.teamId!==this.options.teamId||l(r.evidence)!==l(t.evidence))throw new Error("The Improve choices changed their exact originating evidence.");return r}if(t.operation==="humanComparisonOptions"){let r=j(p);if(r.candidateId!==t.id||r.actorId!==this.options.actorId||r.teamId!==this.options.teamId)throw new Error("Human discovery belongs to another owner or candidate.");return r}if(t.operation==="instructions"){let r=e.object({candidateId:e.string(),candidateRevision:e.number().int().positive(),path:e.string(),text:e.string().max(25e4),textHash:e.string().regex(/^[a-f0-9]{64}$/),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(p);if(r.candidateId!==t.id||v(r.text)!==r.textHash)throw new Error("The candidate instructions belong to a different revision.");return r}let i=t.operation==="list"?E.parse(p):null;if(t.operation==="list"&&i&&(i.states.length>t.limit||i.states.some((r,s)=>t.cursor&&r.id<=t.cursor||s>0&&r.id<=i.states[s-1].id)||i.nextCursor&&(t.cursor&&i.nextCursor<=t.cursor||i.states.some(r=>r.id>i.nextCursor))))throw new Error("The retained candidate page changed its scan boundary.");let u=(i?i.states:[p]).map(r=>{let s=C(r);if(s.actorId!==this.options.actorId||s.teamId!==this.options.teamId||"id"in t&&s.id!==t.id)throw new Error("The Improve response belongs to a different owner or candidate.");if(t.operation==="start"&&s.requestHash!==l(t.request))throw new Error("The Improve request identity changed.");return s});return i?{states:u,nextCursor:i.nextCursor}:u[0]}};export{J as a,K as b};
@@ -1,6 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as fe,b as me,d as he,e as q,f as L,g as ye,h as Ae,i as ge,j as Pe}from"./chunk-HA7EFTPF.js";import{e as pe}from"./chunk-2JO2KWT3.js";import{d as N,e as B}from"./chunk-Z3D4C7BG.js";import{D as oe,g as te}from"./chunk-TGIB24K4.js";import{q as de}from"./chunk-NNF6KCHD.js";import{a}from"./chunk-FTQLQJQV.js";import{randomUUID as qe}from"node:crypto";var Te=new URL(B).hostname,we=new URL(N).hostname,Ne=`${B}/opchat/v1`;function l(e){if(!e)return null;let n=e.trim();return n?n.replace(/\/+$/,""):null}a(l,"normalizeBaseUrl");function V(e){let n=l(e);if(!n)return null;try{let o=new URL(n).hostname.toLowerCase();if(o===Te)return B;if(o===we||o===`www.${we}`||o==="openpond.live"||o==="www.openpond.live")return B;if(o.startsWith("api."))return n}catch{return null}return null}a(V,"mapUiBaseToApiBase");function G(e,n){let t=l(process.env.OPENPOND_API_URL);if(t)return t;let o=l(e?.apiBaseUrl);if(o)return o;let r=l(n.apiBaseUrl);if(r)return r;let s=V(process.env.OPENPOND_BASE_URL);return s||(V(e?.baseUrl||n.baseUrl)??B)}a(G,"resolvePublicApiBaseUrl");function J(e,n,t){return Le(e,n,t)}a(J,"resolveHostedChatApiBaseUrl");function Le(e,n,t){let o=typeof process<"u"?process.env:{};return W(o.OPENPOND_OPCHAT_API_URL)??W(e?.chatApiBaseUrl??n.chatApiBaseUrl)??W(o.OPENPOND_CHAT_API_URL)??De(t)}a(Le,"resolveOpChatApiBaseUrl");function W(e){let n=l(e);if(!n)return null;try{let t=new URL(n),o=t.pathname.split("/").filter(Boolean),r=o.findIndex(i=>i.toLowerCase()==="opchat");return r>=0?(t.pathname=`/${[...o.slice(0,r+1),"v1"].join("/")}`,t.search="",t.hash="",l(t.toString())??null):o.findIndex(i=>i.toLowerCase()==="v1")>=0?(t.pathname="/opchat/v1",t.search="",t.hash="",l(t.toString())??null):(t.pathname=`${t.pathname.replace(/\/+$/,"")}/opchat/v1`.replace(/\/{2,}/g,"/"),t.search="",t.hash="",l(t.toString())??null)}catch{return null}}a(W,"normalizeOpChatApiBaseUrl");function De(e){return W(e)??Ne}a(De,"opChatBaseFromPublicApiBase");function D(e){return e?.trim()?e.trim():"production"}a(D,"deriveEnvironment");function Y(e,n=process.env){let t=[e?.apiKey,e?.session?.token,e?.token,n.OPENPOND_API_KEY];for(let o of t){let r=typeof o=="string"?o.trim():"";if(r)return r}return null}a(Y,"accountToken");function P(e,n){return!!(e&&n&&e.toLowerCase()===n.toLowerCase())}a(P,"handleEquals");function b(e,n){return l(e)===l(n)}a(b,"baseUrlEquals");function F(e,n){return`${e?.trim().toLowerCase()||""}|${l(n)??"default"}`}a(F,"profileKey");function Q(e){return l(e?.baseUrl)}a(Q,"selectorBaseUrl");function _(e){let n=l(e.baseUrl);return n?{handle:e.handle,baseUrl:n}:{handle:e.handle}}a(_,"selectorFromAccount");function A(e){let n=typeof e?.handle=="string"?e.handle.trim():"";if(!n)return null;let t=l(e?.baseUrl);return t?{handle:n,baseUrl:t}:{handle:n}}a(A,"normalizeActiveProfile");function U(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?b(e.baseUrl,t):!l(e.baseUrl)}a(U,"accountMatchesSelector");function re(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?b(e.baseUrl,t):!l(e.baseUrl)}a(re,"profileMatchesSelector");function Oe(e,n,t){let o=Array.isArray(e.accounts)?e.accounts:[],r=n||process.env.OPENPOND_ACCOUNT?A({handle:n||process.env.OPENPOND_ACCOUNT||"",baseUrl:t??process.env.OPENPOND_BASE_URL??null}):A(e.activeProfile);if(r){let s=o.find(c=>U(c,r));if(s)return s;let i=o.filter(c=>P(c.handle,r.handle));return i.length===1?i[0]??null:null}return o[0]?o[0]:null}a(Oe,"findActiveAccount");function xe(e){let n=Array.isArray(e.accounts)?e.accounts:[],t=A(e.activeProfile)??(n[0]?_(n[0]):null);return ae(n.map(o=>({handle:o.handle,baseUrl:l(o.baseUrl),apiBaseUrl:l(o.apiBaseUrl),chatApiBaseUrl:l(o.chatApiBaseUrl),environment:D(o.environment),isActive:t?U(o,t):!1,hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!(o.session?.token?.trim()||o.token?.trim()),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null})))}a(xe,"fallbackProfilesFromConfig");function ae(e){let n=new Map;for(let t of e){let o=l(t.baseUrl),r=`${t.handle.toLowerCase()}|${o??"default"}`,s={...t,baseUrl:o,apiBaseUrl:l(t.apiBaseUrl),chatApiBaseUrl:l(t.chatApiBaseUrl),environment:D(t.environment),isActive:t.isActive},i=n.get(r);(!i||s.isActive&&!i.isActive||s.hasApiKey&&!i.hasApiKey)&&n.set(r,s)}return Array.from(n.values())}a(ae,"normalizeProfiles");function be(e){return e.hasApiKey||e.hasSessionToken?"signed_in":"signed_out"}a(be,"profileAuthHealth");function $e(e,n){return e?{reachable:e.reachable,authenticated:e.authenticated,apiBase:e.apiBase||n,latencyMs:e.latencyMs,status:e.status,service:e.service,checkedAt:e.checkedAt,error:e.error??null}:null}a($e,"normalizeHealth");function Ue(e){let n=e?.account;return n?{id:n.id??null,email:n.email??null,name:n.name??null,handle:n.handle??null,image:n.image??null,timezone:n.timezone??null,isAdmin:n.isAdmin??null,isVerified:n.isVerified??null,dailyAgentAppId:n.dailyAgentAppId??null,dailyAgentDeploymentId:n.dailyAgentDeploymentId??null,credits:n.credits??null}:null}a(Ue,"normalizeProfile");function He(e){return(e??[]).map(n=>({...n,id:n.id||n.userProductId||n.openPondProductId||n.name,name:n.name,type:n.type,status:n.status,isActive:n.isActive??null,price:n.price??null,currency:n.currency??null,credits:n.credits??null}))}a(He,"normalizeProducts");function Me(e){return e.handle.trim().toLowerCase()==="default"&&!l(e.baseUrl)&&!e.hasApiKey&&!e.hasSessionToken}a(Me,"isEmptyDefaultProfile");function ze(e){let n=e?.trim();return n?n.length>=12?`\u2022\u2022\u2022\u2022\u2022\u2022${n.slice(-6)}`:"\u2022\u2022\u2022\u2022\u2022\u2022":null}a(ze,"apiKeyHint");function Fe(e){return e?.auth?.authType!=="openpond-api-key"||!e.auth.keyAccess?null:{ownerType:e.auth.keyAccess.ownerType,teamId:e.auth.keyAccess.teamId,scopes:e.auth.scopes}}a(Fe,"apiKeyAccess");function X(e){let{config:n,profiles:t,account:o,token:r,apiBaseUrl:s,accountResponse:i,accountProfiles:c,health:m,authFailed:g,error:f}=e,w=J(o,n,s),h=Ue(i??null),C=A(n.activeProfile),v=(o?_(o):null)??C,O=h?.handle||o?.handle||v?.handle||null,I=(v?t.find(d=>re(d,v)):null)??t.find(d=>d.isActive)??null,y=g?"auth_error":r?"signed_in":"signed_out",u=h?.name||h?.handle||h?.email||O||"Signed out",R=l(I?.baseUrl||o?.baseUrl||N),k=D(I?.environment||o?.environment),x=A(v)??(O?A({handle:O,baseUrl:I?.baseUrl??o?.baseUrl}):null),M=(t.length>0?t:O?[{handle:O,baseUrl:Q(x)??l(o?.baseUrl),apiBaseUrl:s,chatApiBaseUrl:w,environment:k,isActive:!0,hasApiKey:!!r,hasSessionToken:!1,sessionAppId:null,sessionConversationId:null}]:[]).filter(d=>!Me(d));return{state:y,activeProfile:x,label:u,email:h?.email??null,avatarUrl:h?.image??null,environment:k,baseUrl:R,apiBaseUrl:s,chatApiBaseUrl:w,creditsLabel:h?.credits??null,profile:h,products:He(i?.products),apiHealth:$e(m??null,s),accounts:M.map(d=>{let T=l(d.baseUrl),Re=n.accounts?.find(ue=>P(ue.handle,d.handle)&&b(ue.baseUrl,T)),ne=c?.[F(d.handle,T)]??null,z=Ue(ne?.response??null);return{handle:d.handle,baseUrl:T,apiBaseUrl:l(d.apiBaseUrl),chatApiBaseUrl:l(d.chatApiBaseUrl),environment:D(d.environment),isActive:x?re(d,x):!1,authHealth:ne?.authFailed?"auth_error":be(d),displayLabel:z?.name||z?.handle||z?.email||d.handle,email:z?.email??null,avatarUrl:z?.image??null,apiKeyHint:ze(Re?.apiKey),apiKeyAccess:Fe(ne?.response??null)}}),error:f??m?.error??null}}a(X,"toAccountState");async function je(e){try{return ae(await Ae())}catch{return xe(e)}}a(je,"loadProfiles");async function p(e,n){let t=await ye(),o=await je(t),r=Oe(t,e,n),s=Y(r),i=G(r,t),c=J(r,t,i);return{config:t,profiles:o,account:r,token:s,apiBaseUrl:i,chatApiBaseUrl:c,accountState:X({config:t,profiles:o,account:r,token:s,apiBaseUrl:i})}}a(p,"loadOpenPondAccountContext");async function Ke(e){let n=l(e.baseUrl);return await ge(e.handle,{baseUrl:n}),p(e.handle,n)}a(Ke,"switchOpenPondAccount");function $(e){return e instanceof Error?e.message:String(e)}a($,"errorMessage");var We=15e3;function Ve(e){return e===oe?"OpenPond Chat":e==="deepseek-v4-flash"?"DeepSeek V4 Flash":e.replace(/[-_/]+/g," ")}a(Ve,"displayNameForHostedModel");function Ge(e){let n=typeof e.id=="string"?e.id:null;return n?{id:n,displayName:Ve(n),ownedBy:typeof e.owned_by=="string"?e.owned_by:null,streaming:!0,raw:e}:null}a(Ge,"normalizeHostedModel");async function Je(){let e=await p();if(!e.token)return{models:[],error:"No OpenPond API key or session token is configured."};try{return{models:(await Xe({apiBaseUrl:e.chatApiBaseUrl,token:e.token})).data.map(o=>Ge(o)).filter(o=>!!o),error:null}}catch(n){return{models:[],error:$(n)}}}a(Je,"loadOpenPondHostedModels");async function Ye(){let e=await p();if(!e.token)return{catalog:null,error:"No OpenPond API key or session token is configured."};let n=new AbortController,t=setTimeout(()=>{n.abort(new Error("OpenPond provider catalog request timed out."))},We);try{return{catalog:await Ee({apiBaseUrl:e.chatApiBaseUrl,token:e.token,signal:n.signal}),error:null}}catch(o){return{catalog:null,error:$(o)}}finally{clearTimeout(t)}}a(Ye,"loadOpenPondProviderCatalog");async function*Qe(e){let n=await p();if(!n.token)throw new Error("OpenPond is signed out. Add an account in Settings before using OpenPond Chat.");yield*ve({apiBaseUrl:n.chatApiBaseUrl,token:n.token,model:e.model||oe,messages:e.messages,tools:e.tools,toolChoice:e.toolChoice,requestId:e.requestId,reasoningEffort:e.reasoningEffort,maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,signal:e.signal})}a(Qe,"streamOpenPondHostedChatTurn");async function Xe(e){let n=se(e.apiBaseUrl,"models"),t=await fetch(n,{method:"GET",headers:ie(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat model list failed: ${t.status} ${await le(t)}`);return await t.json()}a(Xe,"listOpChatModels");async function Ee(e){let n=se(e.apiBaseUrl,"provider-catalog"),t=await fetch(n,{method:"GET",headers:ie(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat provider catalog failed: ${t.status} ${await le(t)}`);let o=await t.json();return!o||typeof o!="object"||!Array.isArray(o.providers)?te.parse(o):te.parse({...o,providers:o.providers.filter(r=>r!==null&&typeof r=="object"&&de.safeParse(r.id).success)})}a(Ee,"listOpChatProviderCatalog");async function*ve(e){let n=se(e.apiBaseUrl,"chat/completions"),t=await fetch(n,{method:"POST",headers:ie(e.token,"text/event-stream",e.requestId),body:JSON.stringify(rn(e,!0)),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat request failed: ${t.status} ${await le(t)}`);if(!t.body)throw new Error("OpenPond OpChat request failed: streaming response body is missing.");let o=new Map,r=!1,s=null,i={},c="",m=null,g=Ze(t.headers),f=t.body.getReader(),w=new TextDecoder,h="",C=[],ee=a(()=>{if(C.length===0)return[];let y=C.join(`
3
- `);if(C=[],y==="[DONE]")return r=!0,[];let u;try{u=JSON.parse(y)}catch{throw new Error("OpenPond OpChat request failed: malformed streaming event.")}if(u&&typeof u=="object"&&"error"in u)throw new Error(`OpenPond OpChat request failed: ${_e(u)}`);i=u;let R=u&&typeof u=="object"?u:{},k=Array.isArray(R.choices)?R.choices:[],x=k[0]&&typeof k[0]=="object"?k[0]:{},K=x.delta&&typeof x.delta=="object"?x.delta:{},M=[],d=Be(K.reasoning_content);d&&(c+=d,M.push({type:"reasoning_delta",text:d,raw:u}));let T=Be(K.content);return T&&M.push({type:"text_delta",text:T,raw:u}),tn(o,K.tool_calls),s=H(x.finish_reason)??s,m=ln(u)??m,M},"consumeEvent"),v=a(y=>{let u=y.endsWith("\r")?y.slice(0,-1):y;return u?u.startsWith(":")?[]:(u.startsWith("data:")&&C.push(u.slice(5).trimStart()),[]):ee()},"consumeLine");try{for(;;){let y=await f.read();if(y.done)break;h+=w.decode(y.value,{stream:!0});let u=h.split(`
4
- `);h=u.pop()??"";for(let R of u)for(let k of v(R))yield k}if(h+=w.decode(),h)for(let y of v(h))yield y;for(let y of ee())yield y}finally{f.releaseLock()}if(!r)throw new Error("OpenPond OpChat request failed: stream ended before [DONE].");let O=on(o);O.length>0&&(yield{type:"tool_call_delta",toolCalls:O,raw:i}),O.length>0&&c&&(yield{type:"continuation",continuation:{kind:"chat_completions_reasoning",reasoningContent:c},raw:i});let I=en(m,g);I&&(yield{type:"usage",usage:I,raw:i}),yield{type:"finish",finishReason:s,raw:i}}a(ve,"streamOpChatChatCompletion");function Ze(e){let n=ke(e,["fireworks-prompt-tokens","prompt-tokens"]),t=ke(e,["fireworks-cached-prompt-tokens","cached-prompt-tokens"]);return t===null?null:{...n===null?{}:{prompt_tokens:n},cached_input_tokens:t,cache_telemetry_source:"provider_response_headers"}}a(Ze,"cacheUsageFromResponseHeaders");function ke(e,n){for(let t of n){let o=e.get(t);if(o===null||!/^\d+$/.test(o.trim()))continue;let r=Number(o);if(Number.isSafeInteger(r)&&r>=0)return r}return null}a(ke,"firstHeaderTokenCount");function en(e,n){if(!n||nn(e))return e;let t={...e??{},cached_input_tokens:n.cached_input_tokens,cache_telemetry_source:"provider_response_headers"};return E(e?.prompt_tokens)===null&&n.prompt_tokens!==void 0&&(t.prompt_tokens=n.prompt_tokens),t}a(en,"usageWithResponseHeaderCache");function nn(e){return e?E(e.cached_input_tokens)!==null||E(e.cache_read_input_tokens)!==null||E(e.cache_creation_input_tokens)!==null||E(e.prompt_cache_hit_tokens)!==null||E(e.prompt_cache_miss_tokens)!==null?!0:E(e.prompt_tokens_details?.cached_tokens)!==null||E(e.input_tokens_details?.cached_tokens)!==null:!1}a(nn,"usageHasCacheTelemetry");function E(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return e;if(typeof e!="string"||!/^\d+$/.test(e.trim()))return null;let n=Number(e);return Number.isSafeInteger(n)?n:null}a(E,"usageTokenCount");function tn(e,n){Array.isArray(n)&&n.forEach((t,o)=>{if(!t||typeof t!="object")return;let r=t,s=typeof r.index=="number"&&Number.isInteger(r.index)?r.index:o,i=e.get(s)??{arguments:""};typeof r.id=="string"&&(i.id=r.id);let c=r.function&&typeof r.function=="object"?r.function:{};typeof c.name=="string"&&(i.name=`${i.name??""}${c.name}`),typeof c.arguments=="string"&&(i.arguments+=c.arguments),e.set(s,i)})}a(tn,"mergeOpChatToolCallDeltas");function on(e){return[...e.entries()].sort(([n],[t])=>n-t).flatMap(([,n])=>n.id&&n.name?[{id:n.id,type:"function",function:{name:n.name,arguments:n.arguments}}]:[])}a(on,"completedOpChatToolCalls");function rn(e,n){let t={model:e.model,messages:e.messages.map(sn),stream:n};return e.tools&&(t.tools=e.tools),e.toolChoice!==void 0&&(t.tool_choice=e.toolChoice),typeof e.maxTokens=="number"&&(t.max_tokens=e.maxTokens),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.topP=="number"&&(t.top_p=e.topP),Object.assign(t,an(e.reasoningEffort)),t}a(rn,"buildOpChatBody");function an(e){return e?e==="off"?{thinking:{type:"disabled"}}:{thinking:{type:"enabled"},reasoning_effort:e}:{}}a(an,"opChatReasoningFields");function sn(e){let{continuation:n,images:t,...o}=e,r=t?.length?[...typeof e.content=="string"&&e.content.trim()?[{type:"text",text:e.content}]:[],...t.map(s=>({type:"image_url",image_url:{url:s.url,...s.detail?{detail:s.detail}:{}}}))]:e.content;return e.role==="assistant"&&n?.kind==="chat_completions_reasoning"?{...o,...r!==void 0?{content:r}:{},reasoning_content:n.reasoningContent}:{...o,...r!==void 0?{content:r}:{}}}a(sn,"opChatMessage");function se(e,n){let t=e.trim().replace(/\/+$/,"");if(!t)throw new Error("OpenPond OpChat API base URL is required.");return`${t}/${n}`}a(se,"opChatEndpointUrl");function ie(e,n,t){let o=e.trim();if(!o)throw new Error("OpenPond API key is required for OpChat.");let r=new Headers;r.set("Authorization",`Bearer ${o}`),r.set("Content-Type","application/json"),r.set("Accept",n),r.set("x-openpond-client","openpond-app");let s=t||qe();return r.set("x-openpond-request-id",s),r.set("x-request-id",s),r}a(ie,"opChatHeaders");async function le(e){let n=await e.text().catch(()=>"");if(!n)return e.statusText||`HTTP ${e.status}`;try{return _e(JSON.parse(n))}catch{return n}}a(le,"readOpChatError");function _e(e){if(!e||typeof e!="object")return String(e||"unknown_error");let n=e,t=n.error;if(t&&typeof t=="object"){let o=t;return[H(o.code),H(o.type),H(o.message)].filter(Boolean).join(": ")}return[H(n.error),H(n.message)].filter(Boolean).join(": ")||JSON.stringify(e)}a(_e,"errorMessageFromPayload");function ln(e){if(!e||typeof e!="object")return null;let n=e.usage;return!n||typeof n!="object"?null:n}a(ln,"parseUsage");function H(e){return typeof e=="string"&&e.trim()?e:null}a(H,"stringValue");function Be(e){return typeof e=="string"&&e.length>0?e:null}a(Be,"streamTextValue");import{readFileSync as cn}from"node:fs";var j;function un(){if(j!==void 0)return j??"openpond-code bundled";try{let e=new URL("../package.json",import.meta.resolve("openpond")),n=JSON.parse(cn(e,"utf8"));j=typeof n.version=="string"?`openpond-code@${n.version}`:null}catch{j=null}return j??"openpond-code bundled"}a(un,"getBundledRuntimeVersion");import{spawn as dn}from"node:child_process";function Se(e,n=process.platform){return n==="darwin"?{command:"open",args:[e]}:n==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}a(Se,"resolveSystemBrowserCommand");async function pn(e,n={}){let t=n.command??Se(e),o=n.handoffTimeoutMs??1500;return new Promise(r=>{let s=!1,i=null,c=a(g=>{s||(s=!0,i&&clearTimeout(i),r(g))},"finish"),m=dn(t.command,t.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});m.once("error",g=>{let f=g.code;c({opened:!1,error:f?`browser launcher ${t.command} failed (${f})`:`browser launcher ${t.command} failed`})}),m.once("close",(g,f)=>{if(g===0){c({opened:!0});return}let w=f?`signal ${f}`:`code ${g??"unknown"}`;c({opened:!1,error:`browser launcher ${t.command} exited with ${w}`})}),i=setTimeout(()=>{m.unref(),c({opened:!0})},o),i.unref()})}a(pn,"openUrlWithSystemBrowser");function fn(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t;if(!t||!o)return null;let r=n.latestDeployment&&typeof n.latestDeployment=="object"?n.latestDeployment:null,s=pe.safeParse(n.sandboxActionRegistry);return{id:t,name:o,description:typeof n.description=="string"?n.description:null,visibility:typeof n.visibility=="string"?n.visibility:null,gitOwner:typeof n.gitOwner=="string"?n.gitOwner:null,gitRepo:typeof n.gitRepo=="string"?n.gitRepo:null,gitHost:typeof n.gitHost=="string"?n.gitHost:null,defaultBranch:typeof n.defaultBranch=="string"?n.defaultBranch:null,sandbox:n.sandbox===!0,sandboxActionRegistry:s.success?s.data:null,sandboxManifestHash:typeof n.sandboxManifestHash=="string"?n.sandboxManifestHash:null,sandboxManifestPath:typeof n.sandboxManifestPath=="string"?n.sandboxManifestPath:null,sandboxManifestSyncedAt:typeof n.sandboxManifestSyncedAt=="string"?n.sandboxManifestSyncedAt:n.sandboxManifestSyncedAt instanceof Date?n.sandboxManifestSyncedAt.toISOString():null,sandboxManifestError:typeof n.sandboxManifestError=="string"?n.sandboxManifestError:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null,latestDeployment:r?{id:typeof r.id=="string"?r.id:void 0,status:typeof r.status=="string"?r.status:void 0,deploymentDomain:typeof r.deploymentDomain=="string"?r.deploymentDomain:null,createdAt:typeof r.createdAt=="string"?r.createdAt:void 0,isProduction:typeof r.isProduction=="boolean"?r.isProduction:null,gitBranch:typeof r.gitBranch=="string"?r.gitBranch:null}:null,scheduleSummary:hn(n.scheduleSummary)}}a(fn,"normalizeApp");function S(e){return typeof e=="string"?e:e instanceof Date?e.toISOString():null}a(S,"normalizeDateString");function mn(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t,r=typeof n.deploymentId=="string"?n.deploymentId:null;return!t||!o||!r?null:{id:t,name:o,description:typeof n.description=="string"?n.description:null,scheduleType:typeof n.scheduleType=="string"?n.scheduleType:"cron",scheduleExpression:typeof n.scheduleExpression=="string"?n.scheduleExpression:"",enabled:!!n.enabled,rawEnabled:typeof n.rawEnabled=="boolean"?n.rawEnabled:void 0,syncStatus:typeof n.syncStatus=="string"?n.syncStatus:null,syncError:typeof n.syncError=="string"?n.syncError:null,startAt:S(n.startAt),endAt:S(n.endAt),maxRuns:typeof n.maxRuns=="number"?n.maxRuns:null,executionCount:typeof n.executionCount=="number"?n.executionCount:null,lifecycleStatus:typeof n.lifecycleStatus=="string"?n.lifecycleStatus:null,lifecycleReason:typeof n.lifecycleReason=="string"?n.lifecycleReason:null,lastExecutionAt:S(n.lastExecutionAt),lastExecutionStatus:typeof n.lastExecutionStatus=="string"?n.lastExecutionStatus:null,lastRunNowAt:S(n.lastRunNowAt),lastRunNowStatus:typeof n.lastRunNowStatus=="string"?n.lastRunNowStatus:null,updatedAt:S(n.updatedAt)??new Date().toISOString(),deploymentId:r,isProduction:typeof n.isProduction=="boolean"?n.isProduction:void 0,payload:n.payload}}a(mn,"normalizeSchedule");function hn(e){if(!e||typeof e!="object")return null;let n=e,t=Array.isArray(n.schedules)?n.schedules.map(mn).filter(i=>!!i):[],o=typeof n.total=="number"?n.total:t.length,r=typeof n.active=="number"?n.active:t.filter(i=>i.enabled).length,s=typeof n.paused=="number"?n.paused:Math.max(0,o-r);return{total:o,active:r,paused:s,enabled:typeof n.enabled=="number"?n.enabled:r,disabled:typeof n.disabled=="number"?n.disabled:s,nextRunAt:S(n.nextRunAt),lastRunAt:S(n.lastRunAt),schedules:t,truncated:typeof n.truncated=="boolean"?n.truncated:void 0}}a(hn,"normalizeScheduleSummary");async function yn(e){let n=Array.isArray(e.config.accounts)?e.config.accounts:[],t=await Promise.all(n.map(async o=>{let r=F(o.handle,o.baseUrl),s=Y(o);if(!s)return[r,{response:null,authFailed:!1,error:null}];try{return[r,{response:await q(G(o,e.config),s),authFailed:!1,error:null}]}catch(i){return[r,{response:null,authFailed:!0,error:$(i)}]}}));return Object.fromEntries(t)}a(yn,"loadAccountProfileLookups");async function Ce(e){let n=await yn(e),t=e.account?n[F(e.account.handle,e.account.baseUrl)]??null:null,o=t?.response??null,r=e.token&&t?.authFailed?t.error||"OpenPond account authentication failed.":null;return{account:X({...e,accountResponse:o,accountProfiles:n,authFailed:!!r,error:r})}}a(Ce,"loadOpenPondAccountStateForContext");async function An(){return Ce(await p())}a(An,"loadOpenPondAccountState");async function Ie(e={}){let n=await p(),t=Ce(n);if(!n.token)return{...await t,apps:[],error:"No OpenPond API key or session token is configured."};let[o,r]=await Promise.allSettled([t,fe(n.apiBaseUrl,n.token,{handle:n.account?.handle,limit:e.limit??20,offset:e.offset??0,includeScheduled:e.includeScheduled??!0})]);if(o.status==="rejected")throw o.reason;return{account:o.value.account,apps:r.status==="fulfilled"?r.value.map(fn).filter(s=>!!s):[],error:r.status==="rejected"?$(r.reason):null}}a(Ie,"loadOpenPondApps");async function gn(e){let n=await p();if(!n.token)throw new Error("No OpenPond API key or session token is configured.");return{account:n,response:await me(n.apiBaseUrl,n.token,e)}}a(gn,"createOpenPondRepoApp");import{createHash as Pn}from"node:crypto";function wn(e){return`account-${Pn("sha256").update(e).digest("hex").slice(0,8)}`}a(wn,"fallbackHandleForApiKey");function Z(e){let n=e?.trim();return n?n.replace(/^@/,""):null}a(Z,"normalizeDerivedHandle");async function On(e,n){let t=Z(e.handle);if(t)return t;try{let r=(await q(n,e.apiKey)).account,s=Z(r.handle)??Z(r.email?.split("@")[0])??Z(r.id);if(s)return s}catch{}return wn(e.apiKey)}a(On,"deriveHandleForApiKey");async function xn(e){let n=e.baseUrl??N,t=l(e.apiBaseUrl)??V(n)??B,o=l(e.chatApiBaseUrl),r=await On(e,t);return await Pe({handle:r,apiKey:e.apiKey,baseUrl:n,apiBaseUrl:t,chatApiBaseUrl:o,environment:e.environment??"production",setActive:e.setActive}),p(r,n)}a(xn,"saveOpenPondAccount");function bn(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&b(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its base URL.`);return-1}a(bn,"findAccountIndex");async function Un(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");return await L(t=>{let o=(t.accounts??[]).map(m=>({...m})),r=bn(o,n,e.baseUrl);if(r===-1)throw new Error(`OpenPond account not found: ${n}`);let s=o[r],i=A(t.activeProfile),c=!!(i&&U(s,i));o.splice(r,1),t.accounts=o,(c||!i||!o.some(m=>U(m,i)))&&(o[0]?t.activeProfile=_(o[0]):delete t.activeProfile)}),p()}a(Un,"removeOpenPondAccount");async function kn(){let e;return await L(n=>{let t=A(n.activeProfile),o=(n.accounts??[]).map(s=>({...s})),r=t?o.findIndex(s=>U(s,t)):0;if(r<0||!o[r])throw new Error("No active OpenPond account to log out.");e={...o[r]},delete e.apiKey,delete e.session,o[r]=e,n.accounts=o}),p(e.handle,e.baseUrl)}a(kn,"signOutOpenPondAccount");function Bn(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&b(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its current base URL.`);return-1}a(Bn,"findAccountIndex");function ce(e,n,t){if(t===void 0)return;let o=l(t);if(o){e[n]=o;return}(t===null||t.trim()==="")&&delete e[n]}a(ce,"applyOptionalUrl");async function En(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");let t;return await L(o=>{let r=(o.accounts??[]).map(f=>({...f})),s=Bn(r,n,e.currentBaseUrl);if(s===-1)throw new Error(`OpenPond account not found: ${n}`);let i=r[s];if(t={...i},e.apiKey!==void 0){let f=e.apiKey.trim();if(!f)throw new Error("OpenPond API key cannot be empty.");t.apiKey=f,delete t.session,delete t.token}if(ce(t,"baseUrl",e.baseUrl),ce(t,"apiBaseUrl",e.apiBaseUrl),ce(t,"chatApiBaseUrl",e.chatApiBaseUrl),e.environment===null?delete t.environment:typeof e.environment=="string"&&e.environment.trim()&&(t.environment=e.environment.trim()),r.findIndex((f,w)=>w!==s&&P(f.handle,t.handle)&&b(f.baseUrl,t.baseUrl))!==-1)throw new Error("Another OpenPond account already uses that handle and base URL.");let m=A(o.activeProfile),g=!!(m&&U(i,m));r[s]=t,o.accounts=r,o.activeProfile=e.setActive||g?_(t):o.activeProfile}),p(t.handle,t.baseUrl)}a(En,"updateOpenPondAccountConfig");async function vn(e){let n=await p();if(!n.token)throw new Error("OpenPond is signed out. Add an account before reading app config.");return he(n.apiBaseUrl,n.token,e.appId)}a(vn,"getOpenPondAppEnvironment");function _n(e,n){let t="",o=a(r=>{r.startsWith(e)&&n(JSON.parse(r.slice(e.length)))},"processLine");return{push(r){for(t+=r;;){let s=Sn(t);if(s<0)return;let i=t.slice(0,s).replace(/\r$/,""),c=t[s]==="\r"&&t[s+1]===`
5
- `?2:1;t=t.slice(s+c),o(i)}},flush(){let r=t.trimEnd();t="",r&&o(r)}}}a(_n,"createReadyLineParser");function Sn(e){let n=e.indexOf(`
6
- `),t=e.indexOf("\r");return n<0?t:t<0?n:Math.min(n,t)}a(Sn,"nextLineEnd");export{p as a,Ke as b,An as c,Ie as d,gn as e,Je as f,Ye as g,Qe as h,ve as i,xn as j,Un as k,kn as l,En as m,vn as n,un as o,_n as p,pn as q};
@@ -1,5 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{h as S}from"./chunk-USKE34VR.js";import{F as h}from"./chunk-7ZG3IT7C.js";import{ha as A}from"./chunk-4TZHH5FC.js";import{Ga as O,Ha as k,j as I,m as P,p as b,r as H,s as w,w as f}from"./chunk-SDEDAHV6.js";import{m as g}from"./chunk-NNF6KCHD.js";import{b as c}from"./chunk-ES2ISFJC.js";import{a as u}from"./chunk-FTQLQJQV.js";import{randomUUID as T}from"node:crypto";import{readFile as v}from"node:fs/promises";import p from"node:path";import{randomUUID as $}from"node:crypto";var y=c.object({revision:c.number().int().nonnegative(),overlay:H}).strict(),z=y.extend({proposal:w}).strict(),m=class{constructor(e){this.client=e}client;static{u(this,"HostedHarnessOverlayStorage")}async getHarnessRunOverlay(e){let s=await this.client.request({contractVersion:h,requestId:$(),operation:"harness/overlay/get",params:{runId:e}});return s===null?null:y.parse(s).overlay}async putHarnessRunOverlay(e){let s=H.parse(e.overlay);if(!e.requestId.trim()||s.revision!==(e.expectedRevision===null?0:e.expectedRevision+1))throw new Error("Hosted Harness overlay mutation requires a stable request and next revision.");let r=y.parse(await this.client.request({contractVersion:h,requestId:e.requestId,operation:"harness/overlay/put",params:{runId:s.runId,expectedRevision:e.expectedRevision,overlay:s}}));if(r.revision!==s.revision||r.overlay.contentHash!==s.contentHash)throw new Error("Host Harness overlay response changed committed identity.");return r.overlay}async createHarnessRunOverlay(e){if(e.revision!==0||e.status!=="active")throw new Error("A new Harness run overlay must be active at revision 0.");return this.putHarnessRunOverlay({overlay:e,expectedRevision:null,requestId:`harness-overlay:${e.runId}:${e.contentHash}`})}async ensureHarnessRunOverlay(e){let s=await this.getHarnessRunOverlay(e.runId);if(s){if(s.workspace.workspaceId!==e.workspace.id||s.baseHarnessRelease.id!==e.harnessRelease.id||s.baseHarnessRelease.contentHash!==e.harnessRelease.contentHash)throw new Error("The durable Agent run is already bound to another Harness release.");return s}let r=f({schemaVersion:"openpond.harnessRunOverlay.v1",id:`overlay-${g({runId:e.runId,harnessRelease:e.harnessRelease}).slice(0,24)}`,runId:e.runId,baseHarnessRelease:e.harnessRelease,workspace:{workspaceId:e.workspace.id,revision:e.workspace.revision,sourceRevision:e.workspace.sourceRevision,channelRevision:e.workspace.currentChannel.revision},revision:0,status:"active",edits:[],createdAt:e.admittedAt,updatedAt:e.admittedAt,metadata:{}});return this.createHarnessRunOverlay(r)}async appendHarnessRunOverlayEditsAtomically(e){return this.transition(e,"append")}async freezeHarnessRunOverlayAtomically(e){return this.transition({...e,edits:[]},"freeze")}async abandonHarnessRunOverlayAtomically(e){return this.transition({...e,edits:[]},"abandon")}async freezeHarnessRunOverlayWithProposalAtomically(e){let s=await this.getHarnessRunOverlay(e.runId);if(!s||s.revision!==e.expectedRevision||s.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");let r=new Set(s.edits.map(i=>i.id));for(let i of e.edits){if(r.has(i.id))throw new Error(`Harness overlay edit id already exists: ${i.id}.`);r.add(i.id)}let{contentHash:l,...n}=s,t=f({...n,revision:s.revision+1,status:"frozen",edits:[...s.edits,...e.edits],updatedAt:e.updatedAt}),d=w.parse(e.buildProposal(t)),a=z.parse(await this.client.request({contractVersion:h,requestId:`harness-proposal:${t.runId}:${d.contentHash}`,operation:"harness/overlay/freezeProposal",params:{runId:t.runId,expectedRevision:s.revision,overlay:t,proposal:d}}));if(a.overlay.contentHash!==t.contentHash||a.proposal.contentHash!==d.contentHash)throw new Error("Host Harness proposal response changed committed identity.");return{overlay:a.overlay,proposal:a.proposal}}async transition(e,s){let r=await this.getHarnessRunOverlay(e.runId);if(!r||r.revision!==e.expectedRevision||r.status==="abandoned"||s!=="abandon"&&r.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");if(s==="append"&&e.edits.length===0)throw new Error("Harness overlay append requires edits.");let l=new Set(r.edits.map(a=>a.id));for(let a of e.edits){if(l.has(a.id))throw new Error(`Harness overlay edit id already exists: ${a.id}.`);l.add(a.id)}let{contentHash:n,...t}=r,d=f({...t,revision:r.revision+1,status:s==="append"?"active":s==="freeze"?"frozen":"abandoned",edits:[...r.edits,...e.edits],updatedAt:e.updatedAt});return this.putHarnessRunOverlay({overlay:d,expectedRevision:r.revision,requestId:`harness-overlay:${d.runId}:${d.contentHash}`})}};var N=c.object({workspace:b,release:c.object({id:c.string().min(1),contentHash:c.string().regex(/^[a-f0-9]{64}$/),sourceRevision:c.string().min(1),assetsPath:c.string().min(1)}).strict()}).strict();async function C(o,e=null){let s=await o.request({contractVersion:h,requestId:T(),operation:"harness/get",params:{reference:e}});if(s===null)return null;let r=N.parse(s);if(!p.isAbsolute(r.release.assetsPath))throw new Error("Hosted Harness assets path must be absolute.");let[l,n]=await Promise.all([v(p.join(r.release.assetsPath,"agent-snapshot.json"),"utf8"),v(p.join(r.release.assetsPath,"harness-release.json"),"utf8")]),t=A.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:r.workspace.id,sourceRevision:r.release.sourceRevision,agentSnapshot:I.parse(JSON.parse(l)),harnessRelease:P.parse(JSON.parse(n)),bundlePath:r.release.assetsPath,createdAt:new Date().toISOString()});if(t.harnessRelease.id!==r.release.id||t.harnessRelease.contentHash!==r.release.contentHash||(e!==null?e.id!==r.release.id||e.contentHash!==r.release.contentHash:r.workspace.currentChannel.release?.contentHash!==r.release.contentHash))throw new Error("Hosted Harness release differs from its bound workspace.");return S({workspace:r.workspace,release:t})}u(C,"loadHostedHarnessRuntime");async function se(o,e){let s=e.profileComponentBinding,r=e.profileWorkflowBinding;if(s){if(r||e.currentProfile?.profileId!==s.profileId)throw new Error("Profile component binding differs from the session Profile reference.");let n=await x(o,s.harnessRelease);if(E(n,s.profileId,s.sourceRevision,e.currentProfile?.repositoryId),s.target.kind==="profile")return n;if(s.target.kind==="skill"){let i=s.target.skillPath;if(!n.release.agentSnapshot.skills.some(j=>j.path===i))throw new Error("Bound Profile Skill is unavailable in its released source.");let R=await v(p.join(n.release.bundlePath,"source",i),"utf8");return{...n,instructionContext:[n.instructionContext,`Released Profile Skill (${i}):
3
- ${R}`].join(`
4
-
5
- `)}}let t=await q(n),d=s.target.actionId,a=t.actions.find(i=>i.id===d);if(!a)throw new Error("Bound Profile Agent action is unavailable in its released source.");return{...n,workflowAction:a}}if(r){if(e.currentProfile?.profileId!==r.profileId)throw new Error("Profile workflow binding differs from the session Profile reference.");let n=await x(o,r.harnessRelease);E(n,r.profileId,r.sourceRevision,e.currentProfile?.repositoryId);let t=await q(n),d=k({binding:r,harnessRelease:n.release.harnessRelease,catalog:t.catalog,catalogHash:t.catalogHash}),a=d.invocation.kind==="agent_action"?d.invocation.actionId:null,i=a?t.actions.find(R=>R.id===a):void 0;if(a&&!i)throw new Error(`Bound Profile action ${a} is missing from its release.`);return{...n,workflow:d,...i?{workflowAction:i}:{}}}let l=await new m(o).getHarnessRunOverlay(e.id);return C(o,l?.baseHarnessRelease??null)}u(se,"loadHostedHarnessRuntimeForSession");async function x(o,e){let s=await C(o,e);if(!s)throw new Error("The bound Profile Harness release is unavailable.");return s}u(x,"requireRelease");function E(o,e,s,r){let l=o.release.harnessRelease.metadata.profile;if(!l||typeof l!="object"||l.id!==e||l.sourceRevision!==s||l.repositoryId!==void 0&&l.repositoryId!==r)throw new Error("Bound Profile source differs from its released Harness source.")}u(E,"assertProfileProvenance");async function q(o){let e=p.join(o.release.bundlePath,"source"),[s,r]=await Promise.all([v(p.join(e,"workflows","catalog.json")),v(p.join(e,"workflows","actions.json"))]);return O({agentSnapshot:o.release.agentSnapshot,harnessRelease:o.release.harnessRelease,catalogBytes:s,actionBytes:r})}u(q,"loadHostedProfileCatalog");export{m as a,C as b,se as c};