@mycadet/app 0.14.0 → 0.14.1

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 (323) hide show
  1. package/dist/package/{account-ClsQnHGQ.js → account-BjSsTtRF.js} +34 -4
  2. package/dist/package/{account-ClsQnHGQ.js.map → account-BjSsTtRF.js.map} +1 -1
  3. package/dist/package/{account-BvjgJwlA.js → account-Cpv1eLtg.js} +34 -4
  4. package/dist/package/{account-BvjgJwlA.js.map → account-Cpv1eLtg.js.map} +1 -1
  5. package/dist/package/{account-D1YjLGV9.js → account-D3gupGpI.js} +34 -4
  6. package/dist/package/{account-D1YjLGV9.js.map → account-D3gupGpI.js.map} +1 -1
  7. package/dist/package/{account-8eKos9G7.js → account-DThRwtFx.js} +26 -3
  8. package/dist/package/{account-8eKos9G7.js.map → account-DThRwtFx.js.map} +1 -1
  9. package/dist/package/{common-oxewtz-Y.js → common-C_oPdXpV.js} +3 -2
  10. package/dist/package/{common-oxewtz-Y.js.map → common-C_oPdXpV.js.map} +1 -1
  11. package/dist/package/{common-dGbBloR6.js → common-D1kBgkpz.js} +3 -2
  12. package/dist/package/{common-dGbBloR6.js.map → common-D1kBgkpz.js.map} +1 -1
  13. package/dist/package/{common-BluQGYDb.js → common-DVJ5NUo5.js} +8 -3
  14. package/dist/package/{common-BluQGYDb.js.map → common-DVJ5NUo5.js.map} +1 -1
  15. package/dist/package/{common-DNZ_4X_m.js → common-sYQVH-gY.js} +3 -2
  16. package/dist/package/{common-DNZ_4X_m.js.map → common-sYQVH-gY.js.map} +1 -1
  17. package/dist/package/contracts.js +2 -2
  18. package/dist/package/index.js +217 -176
  19. package/dist/package/index.js.map +1 -1
  20. package/dist/package/package.json +1 -1
  21. package/dist/package/{resolution-contract-D6qbDWH9.js → resolution-contract-Cx6VTw9G.js} +7 -3
  22. package/dist/package/{resolution-contract-D6qbDWH9.js.map → resolution-contract-Cx6VTw9G.js.map} +1 -1
  23. package/dist/package/types/assistant/resolution-contract.d.ts +10 -0
  24. package/dist/package/types/i18n/i18n.d.ts +0 -33
  25. package/dist/package/types/i18n/locales/en/account.json +34 -1
  26. package/dist/package/types/i18n/locales/en/common.json +2 -1
  27. package/dist/package/types/i18n/locales/es/account.json +31 -1
  28. package/dist/package/types/i18n/locales/es/common.json +2 -1
  29. package/dist/package/types/i18n/locales/ru/account.json +31 -1
  30. package/dist/package/types/i18n/locales/ru/common.json +5 -0
  31. package/dist/package/types/i18n/locales/zh/account.json +31 -1
  32. package/dist/package/types/i18n/locales/zh/common.json +2 -1
  33. package/dist/package/types/i18n/locales/zh-TW/account.json +23 -0
  34. package/dist/package/types/i18n/locales/zh-TW/common.json +2 -1
  35. package/dist/package/types/utils/routes.d.ts +2 -0
  36. package/dist/standalone/assets/{about-page-bFAEorIh.js → about-page-DPL4LQJQ.js} +2 -2
  37. package/dist/standalone/assets/{about-page-bFAEorIh.js.map → about-page-DPL4LQJQ.js.map} +1 -1
  38. package/dist/standalone/assets/{account-6E86_HHi.js → account-DWvlCD26.js} +2 -2
  39. package/dist/standalone/assets/{account-6E86_HHi.js.map → account-DWvlCD26.js.map} +1 -1
  40. package/dist/standalone/assets/{account-BkOLkgsM.js → account-Dbxkj5gp.js} +2 -2
  41. package/dist/standalone/assets/{account-BkOLkgsM.js.map → account-Dbxkj5gp.js.map} +1 -1
  42. package/dist/standalone/assets/{account-TbSfcuuQ.js → account-Z_QP9-yF.js} +2 -2
  43. package/dist/standalone/assets/{account-TbSfcuuQ.js.map → account-Z_QP9-yF.js.map} +1 -1
  44. package/dist/standalone/assets/{account-BhR_HGNE.js → account-cww-kAPn.js} +2 -2
  45. package/dist/standalone/assets/{account-BhR_HGNE.js.map → account-cww-kAPn.js.map} +1 -1
  46. package/dist/standalone/assets/{account-form-XXd0H39n.js → account-form-C4XJbJg7.js} +2 -2
  47. package/dist/standalone/assets/{account-form-XXd0H39n.js.map → account-form-C4XJbJg7.js.map} +1 -1
  48. package/dist/standalone/assets/{account-page-C9RTiet9.js → account-page-DvOiHNmB.js} +2 -2
  49. package/dist/standalone/assets/{account-page-C9RTiet9.js.map → account-page-DvOiHNmB.js.map} +1 -1
  50. package/dist/standalone/assets/{account-shell-8wPEal0o.js → account-shell-0G7JjvNP.js} +1 -1
  51. package/dist/standalone/assets/{account-shell-8wPEal0o.js.map → account-shell-0G7JjvNP.js.map} +1 -1
  52. package/dist/standalone/assets/{api-Di6JRcb2.js → api-CQhZI0Rx.js} +2 -2
  53. package/dist/standalone/assets/{api-Di6JRcb2.js.map → api-CQhZI0Rx.js.map} +1 -1
  54. package/dist/standalone/assets/api-key-screen-Dpe_rQH5.js +2 -0
  55. package/dist/standalone/assets/api-key-screen-Dpe_rQH5.js.map +1 -0
  56. package/dist/standalone/assets/{assistant-selection-DZ-dloFF.js → assistant-selection-Ce-208FP.js} +2 -2
  57. package/dist/standalone/assets/{assistant-selection-DZ-dloFF.js.map → assistant-selection-Ce-208FP.js.map} +1 -1
  58. package/dist/standalone/assets/assistants-page-BJq5OAqN.js +2 -0
  59. package/dist/standalone/assets/assistants-page-BJq5OAqN.js.map +1 -0
  60. package/dist/standalone/assets/{auth-flow-DRKdI57z.js → auth-flow-1MlxN0jj.js} +2 -2
  61. package/dist/standalone/assets/auth-flow-1MlxN0jj.js.map +1 -0
  62. package/dist/standalone/assets/{auth-store-Da8bCODz.js → auth-store-DVFVhss9.js} +3 -3
  63. package/dist/standalone/assets/{auth-store-Da8bCODz.js.map → auth-store-DVFVhss9.js.map} +1 -1
  64. package/dist/standalone/assets/{auth-welcome-screen-BYvKnLEN.js → auth-welcome-screen-CQ7B7WaS.js} +2 -2
  65. package/dist/standalone/assets/{auth-welcome-screen-BYvKnLEN.js.map → auth-welcome-screen-CQ7B7WaS.js.map} +1 -1
  66. package/dist/standalone/assets/{avatar-bundled-components-Bt-85W__.js → avatar-bundled-components-Ci-Feb5F.js} +1 -1
  67. package/dist/standalone/assets/{avatar-bundled-components-Bt-85W__.js.map → avatar-bundled-components-Ci-Feb5F.js.map} +1 -1
  68. package/dist/standalone/assets/avatar-bundled-components-D3cWHbfX.js +1 -0
  69. package/dist/standalone/assets/{avatar-random-B7ItAA05.js → avatar-random-Djl5Rkg7.js} +2 -2
  70. package/dist/standalone/assets/{avatar-random-B7ItAA05.js.map → avatar-random-Djl5Rkg7.js.map} +1 -1
  71. package/dist/standalone/assets/{button-DXWFbocH.js → button-VN1Hg58T.js} +2 -2
  72. package/dist/standalone/assets/{button-DXWFbocH.js.map → button-VN1Hg58T.js.map} +1 -1
  73. package/dist/standalone/assets/{capture-error-N-BrfSzo.js → capture-error-DOE5Xzi8.js} +1 -1
  74. package/dist/standalone/assets/{capture-error-N-BrfSzo.js.map → capture-error-DOE5Xzi8.js.map} +1 -1
  75. package/dist/standalone/assets/{checkbox-DjYdyWsT.js → checkbox-BillvEmp.js} +2 -2
  76. package/dist/standalone/assets/{checkbox-DjYdyWsT.js.map → checkbox-BillvEmp.js.map} +1 -1
  77. package/dist/standalone/assets/circle-BDAthucW.js +2 -0
  78. package/dist/standalone/assets/circle-BDAthucW.js.map +1 -0
  79. package/dist/standalone/assets/circle-alert-BDlVZkal.js +2 -0
  80. package/dist/standalone/assets/circle-alert-BDlVZkal.js.map +1 -0
  81. package/dist/standalone/assets/circle-check-COWWfbA3.js +2 -0
  82. package/dist/standalone/assets/circle-check-COWWfbA3.js.map +1 -0
  83. package/dist/standalone/assets/{cloud-loopback-page-BMz0_4p-.js → cloud-loopback-page-DhSM3WBX.js} +2 -2
  84. package/dist/standalone/assets/{cloud-loopback-page-BMz0_4p-.js.map → cloud-loopback-page-DhSM3WBX.js.map} +1 -1
  85. package/dist/standalone/assets/cloud-off-B_OI861m.js +2 -0
  86. package/dist/standalone/assets/cloud-off-B_OI861m.js.map +1 -0
  87. package/dist/standalone/assets/{common-B65SaoD3.js → common-3OvOvQDN.js} +2 -2
  88. package/dist/standalone/assets/{common-B65SaoD3.js.map → common-3OvOvQDN.js.map} +1 -1
  89. package/dist/standalone/assets/common-Cjc3xE1r.js +2 -0
  90. package/dist/standalone/assets/{common-CXt-X9JZ.js.map → common-Cjc3xE1r.js.map} +1 -1
  91. package/dist/standalone/assets/common-WLzzUH2C.js +2 -0
  92. package/dist/standalone/assets/{common-DiqTxEoY.js.map → common-WLzzUH2C.js.map} +1 -1
  93. package/dist/standalone/assets/common-h2jurip9.js +2 -0
  94. package/dist/standalone/assets/{common-CF7RP46x.js.map → common-h2jurip9.js.map} +1 -1
  95. package/dist/standalone/assets/confirm-dialog-CIACfqv5.js +2 -0
  96. package/dist/standalone/assets/confirm-dialog-CIACfqv5.js.map +1 -0
  97. package/dist/standalone/assets/connect-screen-Brum91Sy.js +3 -0
  98. package/dist/standalone/assets/connect-screen-Brum91Sy.js.map +1 -0
  99. package/dist/standalone/assets/{consent-CtNgR_OY.js → consent-BcFQnaLH.js} +1 -1
  100. package/dist/standalone/assets/{consent-CtNgR_OY.js.map → consent-BcFQnaLH.js.map} +1 -1
  101. package/dist/standalone/assets/{consent-DO714CFR.js → consent-Bjn1fLPJ.js} +1 -1
  102. package/dist/standalone/assets/{consent-DO714CFR.js.map → consent-Bjn1fLPJ.js.map} +1 -1
  103. package/dist/standalone/assets/{consent-CsUnMqF9.js → consent-CxKSOZv9.js} +1 -1
  104. package/dist/standalone/assets/{consent-CsUnMqF9.js.map → consent-CxKSOZv9.js.map} +1 -1
  105. package/dist/standalone/assets/{consent-BQKxIOyu.js → consent-D9PjkqNI.js} +1 -1
  106. package/dist/standalone/assets/{consent-BQKxIOyu.js.map → consent-D9PjkqNI.js.map} +1 -1
  107. package/dist/standalone/assets/{consent-persistence-CrqlC1nt.js → consent-persistence-oB3otA8w.js} +2 -2
  108. package/dist/standalone/assets/{consent-persistence-CrqlC1nt.js.map → consent-persistence-oB3otA8w.js.map} +1 -1
  109. package/dist/standalone/assets/{copy-to-clipboard-B95wqsGH.js → copy-to-clipboard-CRm8TWVX.js} +2 -2
  110. package/dist/standalone/assets/{copy-to-clipboard-B95wqsGH.js.map → copy-to-clipboard-CRm8TWVX.js.map} +1 -1
  111. package/dist/standalone/assets/{create-selectors-CcrSgAwQ.js → create-selectors-lj3eOKUw.js} +2 -2
  112. package/dist/standalone/assets/{create-selectors-CcrSgAwQ.js.map → create-selectors-lj3eOKUw.js.map} +1 -1
  113. package/dist/standalone/assets/definitions-DKzaHSgf.js +2 -0
  114. package/dist/standalone/assets/definitions-DKzaHSgf.js.map +1 -0
  115. package/dist/standalone/assets/{describe-error-CGCx3ZS3.js → describe-error-B2U_mZYH.js} +1 -1
  116. package/dist/standalone/assets/{describe-error-CGCx3ZS3.js.map → describe-error-B2U_mZYH.js.map} +1 -1
  117. package/dist/standalone/assets/{dist-Bsp7oWdO.js → dist-B0U1otb8.js} +2 -2
  118. package/dist/standalone/assets/{dist-Bsp7oWdO.js.map → dist-B0U1otb8.js.map} +1 -1
  119. package/dist/standalone/assets/{dist-D_g3U3xX.js → dist-DAjFxRQx.js} +1 -1
  120. package/dist/standalone/assets/{dist-D_g3U3xX.js.map → dist-DAjFxRQx.js.map} +1 -1
  121. package/dist/standalone/assets/{doctor-CqLlYvNj.js → doctor-BNBU-nDr.js} +1 -1
  122. package/dist/standalone/assets/{doctor-CqLlYvNj.js.map → doctor-BNBU-nDr.js.map} +1 -1
  123. package/dist/standalone/assets/{doctor-YwCkq2Cy.js → doctor-DVa-D3ub.js} +1 -1
  124. package/dist/standalone/assets/{doctor-YwCkq2Cy.js.map → doctor-DVa-D3ub.js.map} +1 -1
  125. package/dist/standalone/assets/{doctor-D7pMtU6A.js → doctor-DYecNDg0.js} +1 -1
  126. package/dist/standalone/assets/{doctor-D7pMtU6A.js.map → doctor-DYecNDg0.js.map} +1 -1
  127. package/dist/standalone/assets/{doctor-BIfQyFc_.js → doctor-D_9bUTmK.js} +1 -1
  128. package/dist/standalone/assets/{doctor-BIfQyFc_.js.map → doctor-D_9bUTmK.js.map} +1 -1
  129. package/dist/standalone/assets/{doctor-page-DrbQzv7g.js → doctor-page-DvOQYT8k.js} +4 -4
  130. package/dist/standalone/assets/doctor-page-DvOQYT8k.js.map +1 -0
  131. package/dist/standalone/assets/{electron-bridge-B1sJkvH-.js → electron-bridge-DGEnu054.js} +1 -1
  132. package/dist/standalone/assets/{electron-bridge-B1sJkvH-.js.map → electron-bridge-DGEnu054.js.map} +1 -1
  133. package/dist/standalone/assets/{ellipsis-vertical-DRMhSLjp.js → ellipsis-vertical-OHRxK2jN.js} +1 -1
  134. package/dist/standalone/assets/{ellipsis-vertical-DRMhSLjp.js.map → ellipsis-vertical-OHRxK2jN.js.map} +1 -1
  135. package/dist/standalone/assets/esm-8JFfcDJc.js +3 -0
  136. package/dist/standalone/assets/{esm-qBiA1_4M.js.map → esm-8JFfcDJc.js.map} +1 -1
  137. package/dist/standalone/assets/esm-CvGfLIIV.js +3 -0
  138. package/dist/standalone/assets/esm-CvGfLIIV.js.map +1 -0
  139. package/dist/standalone/assets/{external-anchor-CMWL9CU_.js → external-anchor-ilPkJGfF.js} +3 -3
  140. package/dist/standalone/assets/{external-anchor-CMWL9CU_.js.map → external-anchor-ilPkJGfF.js.map} +1 -1
  141. package/dist/standalone/assets/{full-page-navigation-VfHlqUPi.js → full-page-navigation-Dose89il.js} +1 -1
  142. package/dist/standalone/assets/{full-page-navigation-VfHlqUPi.js.map → full-page-navigation-Dose89il.js.map} +1 -1
  143. package/dist/standalone/assets/{hard-navigate-BjhB5Ecy.js → hard-navigate-B4a9GrBh.js} +1 -1
  144. package/dist/standalone/assets/{hard-navigate-BjhB5Ecy.js.map → hard-navigate-B4a9GrBh.js.map} +1 -1
  145. package/dist/standalone/assets/hatching-screen-Dbgb8N_M.js +2 -0
  146. package/dist/standalone/assets/hatching-screen-Dbgb8N_M.js.map +1 -0
  147. package/dist/standalone/assets/hosting-screen--Il_gW2L.js +2 -0
  148. package/dist/standalone/assets/hosting-screen--Il_gW2L.js.map +1 -0
  149. package/dist/standalone/assets/{i18n-BaPIfk2c.js → i18n-DFnZ8-i_.js} +3 -3
  150. package/dist/standalone/assets/{i18n-BaPIfk2c.js.map → i18n-DFnZ8-i_.js.map} +1 -1
  151. package/dist/standalone/assets/index-C08pbEAK.js +25 -0
  152. package/dist/standalone/assets/index-C08pbEAK.js.map +1 -0
  153. package/dist/standalone/assets/index-CFXuh0ea.css +2 -0
  154. package/dist/standalone/assets/input-Bo9hZuBu.js +2 -0
  155. package/dist/standalone/assets/input-Bo9hZuBu.js.map +1 -0
  156. package/dist/standalone/assets/{is-electron-DLjujt3j.js → is-electron-BsUxh4Xi.js} +1 -1
  157. package/dist/standalone/assets/is-electron-BsUxh4Xi.js.map +1 -0
  158. package/dist/standalone/assets/login-page-LPHH9xQG.js +2 -0
  159. package/dist/standalone/assets/{login-page-BZGRX0EO.js.map → login-page-LPHH9xQG.js.map} +1 -1
  160. package/dist/standalone/assets/logout-page-cLfdsXbJ.js +2 -0
  161. package/dist/standalone/assets/{logout-page-B2MWIJOU.js.map → logout-page-cLfdsXbJ.js.map} +1 -1
  162. package/dist/standalone/assets/{native-deep-link-BBxdwlv4.js → native-deep-link-BeCO19L3.js} +1 -1
  163. package/dist/standalone/assets/{native-deep-link-BBxdwlv4.js.map → native-deep-link-BeCO19L3.js.map} +1 -1
  164. package/dist/standalone/assets/{native-platform-CAw_N48L.js → native-platform-CnRhTtiM.js} +2 -2
  165. package/dist/standalone/assets/{native-platform-CAw_N48L.js.map → native-platform-CnRhTtiM.js.map} +1 -1
  166. package/dist/standalone/assets/{oauth-complete-page-CEH8Zi-1.js → oauth-complete-page-2sMtnpI_.js} +2 -2
  167. package/dist/standalone/assets/{oauth-complete-page-CEH8Zi-1.js.map → oauth-complete-page-2sMtnpI_.js.map} +1 -1
  168. package/dist/standalone/assets/{oauth-popup-CdRon5Q4.js → oauth-popup-5kYG1nBo.js} +1 -1
  169. package/dist/standalone/assets/{oauth-popup-CdRon5Q4.js.map → oauth-popup-5kYG1nBo.js.map} +1 -1
  170. package/dist/standalone/assets/{oauth-popup-complete-page-CLQh8_Yg.js → oauth-popup-complete-page-B7qjuExF.js} +2 -2
  171. package/dist/standalone/assets/{oauth-popup-complete-page-CLQh8_Yg.js.map → oauth-popup-complete-page-B7qjuExF.js.map} +1 -1
  172. package/dist/standalone/assets/{onboarding-OFRPhT96.js → onboarding-Bi8rl7dz.js} +1 -1
  173. package/dist/standalone/assets/{onboarding-OFRPhT96.js.map → onboarding-Bi8rl7dz.js.map} +1 -1
  174. package/dist/standalone/assets/{onboarding-DGo1yvDA.js → onboarding-CYYEvrwq.js} +1 -1
  175. package/dist/standalone/assets/{onboarding-DGo1yvDA.js.map → onboarding-CYYEvrwq.js.map} +1 -1
  176. package/dist/standalone/assets/{onboarding-BEGUvKly.js → onboarding-CiccIb7u.js} +1 -1
  177. package/dist/standalone/assets/{onboarding-BEGUvKly.js.map → onboarding-CiccIb7u.js.map} +1 -1
  178. package/dist/standalone/assets/{onboarding-DOVL-dOM.js → onboarding-DukwZdnX.js} +1 -1
  179. package/dist/standalone/assets/{onboarding-DOVL-dOM.js.map → onboarding-DukwZdnX.js.map} +1 -1
  180. package/dist/standalone/assets/{onboarding-destination-B66p_VZu.js → onboarding-destination-q-EPuxb3.js} +2 -2
  181. package/dist/standalone/assets/{onboarding-destination-B66p_VZu.js.map → onboarding-destination-q-EPuxb3.js.map} +1 -1
  182. package/dist/standalone/assets/onboarding-navigation-Dw2QOi_5.js +2 -0
  183. package/dist/standalone/assets/{onboarding-navigation-DC8_8LuV.js.map → onboarding-navigation-Dw2QOi_5.js.map} +1 -1
  184. package/dist/standalone/assets/operations-BC6rKy26.js +2 -0
  185. package/dist/standalone/assets/operations-BC6rKy26.js.map +1 -0
  186. package/dist/standalone/assets/{organization-Br5qMM6Y.js → organization-NPa4IZtD.js} +2 -2
  187. package/dist/standalone/assets/{organization-Br5qMM6Y.js.map → organization-NPa4IZtD.js.map} +1 -1
  188. package/dist/standalone/assets/pairing-address-COHnw3DQ.js +2 -0
  189. package/dist/standalone/assets/pairing-address-COHnw3DQ.js.map +1 -0
  190. package/dist/standalone/assets/pairing-page-DQ-BNJpo.js +2 -0
  191. package/dist/standalone/assets/{pairing-page-o5yOUb6T.js.map → pairing-page-DQ-BNJpo.js.map} +1 -1
  192. package/dist/standalone/assets/{password-reset-page-B7JZRJhp.js → password-reset-page-khDtNPzn.js} +2 -2
  193. package/dist/standalone/assets/{password-reset-page-B7JZRJhp.js.map → password-reset-page-khDtNPzn.js.map} +1 -1
  194. package/dist/standalone/assets/{post-auth-destination-Cq5foKw9.js → post-auth-destination-BupBlIwQ.js} +2 -2
  195. package/dist/standalone/assets/{post-auth-destination-Cq5foKw9.js.map → post-auth-destination-BupBlIwQ.js.map} +1 -1
  196. package/dist/standalone/assets/{progress-bar-C_-cwBiK.js → progress-bar-CAYa80XA.js} +2 -2
  197. package/dist/standalone/assets/{progress-bar-C_-cwBiK.js.map → progress-bar-CAYa80XA.js.map} +1 -1
  198. package/dist/standalone/assets/provider-J4HrSK2Z.js +2 -0
  199. package/dist/standalone/assets/{provider-i52bX5VR.js.map → provider-J4HrSK2Z.js.map} +1 -1
  200. package/dist/standalone/assets/{provider-callback-D4ezuOSB.js → provider-callback-BOwTfecP.js} +2 -2
  201. package/dist/standalone/assets/{provider-callback-D4ezuOSB.js.map → provider-callback-BOwTfecP.js.map} +1 -1
  202. package/dist/standalone/assets/{provider-callback-page-BOUah2_i.js → provider-callback-page-DMG9x8dV.js} +2 -2
  203. package/dist/standalone/assets/{provider-callback-page-BOUah2_i.js.map → provider-callback-page-DMG9x8dV.js.map} +1 -1
  204. package/dist/standalone/assets/{provider-key-BFW2wBsh.js → provider-key-9STaxAFD.js} +1 -1
  205. package/dist/standalone/assets/{provider-key-BFW2wBsh.js.map → provider-key-9STaxAFD.js.map} +1 -1
  206. package/dist/standalone/assets/{provider-signup-page-DBqdgyHS.js → provider-signup-page-Cnde-syi.js} +2 -2
  207. package/dist/standalone/assets/{provider-signup-page-DBqdgyHS.js.map → provider-signup-page-Cnde-syi.js.map} +1 -1
  208. package/dist/standalone/assets/{proxy-m8LraLg9.js → proxy-TFSdn8tX.js} +1 -1
  209. package/dist/standalone/assets/{proxy-m8LraLg9.js.map → proxy-TFSdn8tX.js.map} +1 -1
  210. package/dist/standalone/assets/{radio-card-nav-C_Yh88ZX.js → radio-card-nav-Rys6Y38q.js} +1 -1
  211. package/dist/standalone/assets/{radio-card-nav-C_Yh88ZX.js.map → radio-card-nav-Rys6Y38q.js.map} +1 -1
  212. package/dist/standalone/assets/{rehype-katex-BcOWYTKW.js → rehype-katex-COhdT63m.js} +2 -2
  213. package/dist/standalone/assets/{rehype-katex-BcOWYTKW.js.map → rehype-katex-COhdT63m.js.map} +1 -1
  214. package/dist/standalone/assets/{remote-web-pairing-ya9f4HXm.js → remote-web-pairing-BGorUWrN.js} +2 -2
  215. package/dist/standalone/assets/{remote-web-pairing-ya9f4HXm.js.map → remote-web-pairing-BGorUWrN.js.map} +1 -1
  216. package/dist/standalone/assets/{request-BpOspF-T.js → request-B0qW_5SX.js} +2 -2
  217. package/dist/standalone/assets/{request-BpOspF-T.js.map → request-B0qW_5SX.js.map} +1 -1
  218. package/dist/standalone/assets/resolve-assistant-CFtChAyl.js +2 -0
  219. package/dist/standalone/assets/{resolve-assistant-D3wYg0xs.js.map → resolve-assistant-CFtChAyl.js.map} +1 -1
  220. package/dist/standalone/assets/retire-assistant-D4ZGhhiW.js +2 -0
  221. package/dist/standalone/assets/retire-assistant-D4ZGhhiW.js.map +1 -0
  222. package/dist/standalone/assets/{return-to-DazNKK_L.js → return-to-D0IPrnXo.js} +2 -2
  223. package/dist/standalone/assets/{return-to-DazNKK_L.js.map → return-to-D0IPrnXo.js.map} +1 -1
  224. package/dist/standalone/assets/{returning-user-CMNG1o-y.js → returning-user-DJy7811e.js} +2 -2
  225. package/dist/standalone/assets/{returning-user-CMNG1o-y.js.map → returning-user-DJy7811e.js.map} +1 -1
  226. package/dist/standalone/assets/{review-terms-screen-f75A8Lfc.js → review-terms-screen-wOBwEHSz.js} +2 -2
  227. package/dist/standalone/assets/{review-terms-screen-f75A8Lfc.js.map → review-terms-screen-wOBwEHSz.js.map} +1 -1
  228. package/dist/standalone/assets/{rotate-ccw-BzeQSlMY.js → rotate-ccw-BMei42NT.js} +1 -1
  229. package/dist/standalone/assets/{rotate-ccw-BzeQSlMY.js.map → rotate-ccw-BMei42NT.js.map} +1 -1
  230. package/dist/standalone/assets/routes-CfiHTSsp.js +2 -0
  231. package/dist/standalone/assets/routes-CfiHTSsp.js.map +1 -0
  232. package/dist/standalone/assets/{schemas-BZBjRX4t.js → schemas-BYL1R3CL.js} +1 -1
  233. package/dist/standalone/assets/{schemas-BZBjRX4t.js.map → schemas-BYL1R3CL.js.map} +1 -1
  234. package/dist/standalone/assets/select-BOe987hM.js +42 -0
  235. package/dist/standalone/assets/select-BOe987hM.js.map +1 -0
  236. package/dist/standalone/assets/select-assistant-screen-BLFkl2UB.js +2 -0
  237. package/dist/standalone/assets/select-assistant-screen-BLFkl2UB.js.map +1 -0
  238. package/dist/standalone/assets/selected-assistant-storage-B41ut3io.js +2 -0
  239. package/dist/standalone/assets/selected-assistant-storage-B41ut3io.js.map +1 -0
  240. package/dist/standalone/assets/{session-token-Ev2cmr9G.js → session-token-CeIMyut9.js} +2 -2
  241. package/dist/standalone/assets/{session-token-Ev2cmr9G.js.map → session-token-CeIMyut9.js.map} +1 -1
  242. package/dist/standalone/assets/{signup-page-KeolUD_u.js → signup-page-of6Iiudt.js} +2 -2
  243. package/dist/standalone/assets/{signup-page-KeolUD_u.js.map → signup-page-of6Iiudt.js.map} +1 -1
  244. package/dist/standalone/assets/{signup-shell-DohGIoF-.js → signup-shell-BDfHIQLT.js} +2 -2
  245. package/dist/standalone/assets/signup-shell-BDfHIQLT.js.map +1 -0
  246. package/dist/standalone/assets/{src-Cr-NnTju.js → src-DeIvGAbb.js} +12 -12
  247. package/dist/standalone/assets/src-DeIvGAbb.js.map +1 -0
  248. package/dist/standalone/assets/{start-screen-C5WcGw-O.js → start-screen-D-pwgW-n.js} +2 -2
  249. package/dist/standalone/assets/{start-screen-C5WcGw-O.js.map → start-screen-D-pwgW-n.js.map} +1 -1
  250. package/dist/standalone/assets/startup-page-Cq42ASjx.js +2 -0
  251. package/dist/standalone/assets/startup-page-Cq42ASjx.js.map +1 -0
  252. package/dist/standalone/assets/{text-link-DFDM7RLf.js → text-link-B8VO4Tjc.js} +2 -2
  253. package/dist/standalone/assets/{text-link-DFDM7RLf.js.map → text-link-B8VO4Tjc.js.map} +1 -1
  254. package/dist/standalone/assets/triangle-alert-BNKcT3qS.js +2 -0
  255. package/dist/standalone/assets/triangle-alert-BNKcT3qS.js.map +1 -0
  256. package/dist/standalone/assets/{typography-Bp7J7PNm.js → typography-D4_LOmJc.js} +2 -2
  257. package/dist/standalone/assets/{typography-Bp7J7PNm.js.map → typography-D4_LOmJc.js.map} +1 -1
  258. package/dist/standalone/assets/{use-assistant-choices-D7BXbNtP.js → use-assistant-choices-BwNy8OaV.js} +2 -2
  259. package/dist/standalone/assets/{use-assistant-choices-D7BXbNtP.js.map → use-assistant-choices-BwNy8OaV.js.map} +1 -1
  260. package/dist/standalone/assets/{use-assistant-request-BQZn0euZ.js → use-assistant-request-QoPz05UZ.js} +2 -2
  261. package/dist/standalone/assets/{use-assistant-request-BQZn0euZ.js.map → use-assistant-request-QoPz05UZ.js.map} +1 -1
  262. package/dist/standalone/assets/{use-return-to-short-circuit-Crw-Q49N.js → use-return-to-short-circuit-D2L7632b.js} +2 -2
  263. package/dist/standalone/assets/{use-return-to-short-circuit-Crw-Q49N.js.map → use-return-to-short-circuit-D2L7632b.js.map} +1 -1
  264. package/dist/standalone/assets/vellum-migration-screen-D-v7uA1B.js +2 -0
  265. package/dist/standalone/assets/vellum-migration-screen-D-v7uA1B.js.map +1 -0
  266. package/dist/standalone/assets/web-BCuBYUw6.js +2 -0
  267. package/dist/standalone/assets/web-BCuBYUw6.js.map +1 -0
  268. package/dist/standalone/assets/{web-D9n6hYj1.js → web-CmxaSjFh.js} +2 -2
  269. package/dist/standalone/assets/{web-D9n6hYj1.js.map → web-CmxaSjFh.js.map} +1 -1
  270. package/dist/standalone/assets/{web-vi5sY1tx.js → web-FBKaUSAr.js} +2 -2
  271. package/dist/standalone/assets/{web-vi5sY1tx.js.map → web-FBKaUSAr.js.map} +1 -1
  272. package/dist/standalone/assets/{web-namespaces-TlpveG6O.js → web-namespaces-DsiStifa.js} +1 -1
  273. package/dist/standalone/assets/{web-namespaces-TlpveG6O.js.map → web-namespaces-DsiStifa.js.map} +1 -1
  274. package/dist/standalone/assets/welcome-screen-CMBLj6ti.js +1 -0
  275. package/dist/standalone/assets/{welcome-screen-71VYtG_N.js → welcome-screen-D1DwJHr3.js} +2 -2
  276. package/dist/standalone/assets/{welcome-screen-71VYtG_N.js.map → welcome-screen-D1DwJHr3.js.map} +1 -1
  277. package/dist/standalone/index.html +38 -33
  278. package/package.json +1 -1
  279. package/dist/package/types/contracts.d.ts +0 -1
  280. package/dist/standalone/assets/api-key-screen-7Oeb4VZb.js +0 -2
  281. package/dist/standalone/assets/api-key-screen-7Oeb4VZb.js.map +0 -1
  282. package/dist/standalone/assets/assistants-page-DGzqC4QI.js +0 -2
  283. package/dist/standalone/assets/assistants-page-DGzqC4QI.js.map +0 -1
  284. package/dist/standalone/assets/auth-flow-DRKdI57z.js.map +0 -1
  285. package/dist/standalone/assets/avatar-bundled-components-Df4QxjdY.js +0 -1
  286. package/dist/standalone/assets/circle-check-CuQDC50A.js +0 -2
  287. package/dist/standalone/assets/circle-check-CuQDC50A.js.map +0 -1
  288. package/dist/standalone/assets/common-CF7RP46x.js +0 -2
  289. package/dist/standalone/assets/common-CXt-X9JZ.js +0 -2
  290. package/dist/standalone/assets/common-DiqTxEoY.js +0 -2
  291. package/dist/standalone/assets/confirm-dialog-ClRO5F9p.js +0 -2
  292. package/dist/standalone/assets/confirm-dialog-ClRO5F9p.js.map +0 -1
  293. package/dist/standalone/assets/doctor-page-DrbQzv7g.js.map +0 -1
  294. package/dist/standalone/assets/esm-qBiA1_4M.js +0 -3
  295. package/dist/standalone/assets/hatching-screen-DTkoz7iW.js +0 -2
  296. package/dist/standalone/assets/hatching-screen-DTkoz7iW.js.map +0 -1
  297. package/dist/standalone/assets/hosting-screen-DM7aTZ8U.js +0 -2
  298. package/dist/standalone/assets/hosting-screen-DM7aTZ8U.js.map +0 -1
  299. package/dist/standalone/assets/index-D72X30LM.js +0 -25
  300. package/dist/standalone/assets/index-D72X30LM.js.map +0 -1
  301. package/dist/standalone/assets/index-v5jIc7Ne.css +0 -2
  302. package/dist/standalone/assets/is-electron-DLjujt3j.js.map +0 -1
  303. package/dist/standalone/assets/login-page-BZGRX0EO.js +0 -2
  304. package/dist/standalone/assets/logout-page-B2MWIJOU.js +0 -2
  305. package/dist/standalone/assets/onboarding-navigation-DC8_8LuV.js +0 -2
  306. package/dist/standalone/assets/pairing-address-oW5PUuio.js +0 -2
  307. package/dist/standalone/assets/pairing-address-oW5PUuio.js.map +0 -1
  308. package/dist/standalone/assets/pairing-page-o5yOUb6T.js +0 -2
  309. package/dist/standalone/assets/provider-i52bX5VR.js +0 -2
  310. package/dist/standalone/assets/resolve-assistant-D3wYg0xs.js +0 -2
  311. package/dist/standalone/assets/retire-assistant-V-UCSVA2.js +0 -2
  312. package/dist/standalone/assets/retire-assistant-V-UCSVA2.js.map +0 -1
  313. package/dist/standalone/assets/routes-bHGywETD.js +0 -2
  314. package/dist/standalone/assets/routes-bHGywETD.js.map +0 -1
  315. package/dist/standalone/assets/select-DT_GqrSO.js +0 -42
  316. package/dist/standalone/assets/select-DT_GqrSO.js.map +0 -1
  317. package/dist/standalone/assets/select-assistant-screen-eJq9_eeQ.js +0 -2
  318. package/dist/standalone/assets/select-assistant-screen-eJq9_eeQ.js.map +0 -1
  319. package/dist/standalone/assets/signup-shell-DohGIoF-.js.map +0 -1
  320. package/dist/standalone/assets/src-Cr-NnTju.js.map +0 -1
  321. package/dist/standalone/assets/startup-page-8yUObKaM.js +0 -2
  322. package/dist/standalone/assets/startup-page-8yUObKaM.js.map +0 -1
  323. package/dist/standalone/assets/welcome-screen-DsOD5vcC.js +0 -1
@@ -1,2 +1,2 @@
1
- import{c as e,l as t,o as n,p as r}from"./schemas-BZBjRX4t.js";t({deviceCode:r(),userCode:r(),verificationUri:r(),publicBaseUrl:r(),expiresAt:r(),expiresInSeconds:e(),intervalSeconds:e()}),t({status:n(`approved`),verificationUri:r(),expiresAt:r()});function i(e){let t=new URL(e);t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=n.indexOf(`account`);return r>=0&&n.splice(r),t.pathname=n.length?`/${n.join(`/`)}`:`/`,t.toString().replace(/\/+$/,``)}function a(e){let t=new URL(e.verificationUri);return t.hash=new URLSearchParams({device_code:e.deviceCode}).toString(),t.toString()}var o=`https://pairing.invalid`;function s(e,...t){for(let n of t){let t=e.get(n)?.trim();if(t)return t}return null}function c(e){let t=new URLSearchParams(e.search),n=e.hash.startsWith(`#`)?e.hash.slice(1):e.hash;for(let[e,r]of new URLSearchParams(n))t.has(e)||t.set(e,r);return t}function l(e){let t=c(typeof e==`string`?new URL(e,o):e);return{deviceCode:s(t,`deviceCode`,`device_code`),userCode:s(t,`userCode`,`user_code`)}}var u={"invalid-address":!1,"unknown-session":!1,expired:!1,unreachable:!0,"gateway-retryable":!0,gateway:!1,import:!1,"import-precheck":!1};new Set(Object.keys(u).filter(e=>u[e]));export{i as n,l as r,a as t};
2
- //# sourceMappingURL=remote-web-pairing-ya9f4HXm.js.map
1
+ import{c as e,l as t,o as n,p as r}from"./schemas-BYL1R3CL.js";t({deviceCode:r(),userCode:r(),verificationUri:r(),publicBaseUrl:r(),expiresAt:r(),expiresInSeconds:e(),intervalSeconds:e()}),t({status:n(`approved`),verificationUri:r(),expiresAt:r()});function i(e){let t=new URL(e);t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=n.indexOf(`account`);return r>=0&&n.splice(r),t.pathname=n.length?`/${n.join(`/`)}`:`/`,t.toString().replace(/\/+$/,``)}function a(e){let t=new URL(e.verificationUri);return t.hash=new URLSearchParams({device_code:e.deviceCode}).toString(),t.toString()}var o=`https://pairing.invalid`;function s(e,...t){for(let n of t){let t=e.get(n)?.trim();if(t)return t}return null}function c(e){let t=new URLSearchParams(e.search),n=e.hash.startsWith(`#`)?e.hash.slice(1):e.hash;for(let[e,r]of new URLSearchParams(n))t.has(e)||t.set(e,r);return t}function l(e){let t=c(typeof e==`string`?new URL(e,o):e);return{deviceCode:s(t,`deviceCode`,`device_code`),userCode:s(t,`userCode`,`user_code`)}}var u={"invalid-address":!1,"unknown-session":!1,expired:!1,unreachable:!0,"gateway-retryable":!0,gateway:!1,import:!1,"import-precheck":!1},d=new Set(Object.keys(u).filter(e=>u[e]));function f(e){return e!=null&&d.has(e)}export{l as i,f as n,i as r,a as t};
2
+ //# sourceMappingURL=remote-web-pairing-BGorUWrN.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-web-pairing-ya9f4HXm.js","names":[],"sources":["../../../../../packages/service-contracts/src/remote-web-pairing.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Wire contracts for the remote-web pairing flow — the RFC 8628-style\n * device-code exchange that connects a browser (or the iOS app) to a\n * self-hosted assistant over its public ingress URL.\n *\n * The gateway routes are the authoritative serving side:\n * - `POST /v1/remote-web/pairing-challenge` mint a challenge\n * (`gateway/src/http/routes/remote-web-pairing-challenge.ts`,\n * `gateway/src/remote-web/pairing-challenge-store.ts`)\n * - `POST /v1/remote-web/pairing-verification` approve by user code\n * (`gateway/src/http/routes/remote-web-pairing-verification.ts`)\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-token` poll + exchange device code\n * (`gateway/src/http/routes/remote-web-pairing-token.ts`): a browser\n * receives its refresh token as an `HttpOnly` cookie; a request that\n * carries a `deviceId` receives a device-bound one in the body instead\n * - `GET /v1/remote-web/pairing-requests` list pending challenges\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-requests/approve` approve by request id\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-requests/deny` deny (delete) by request id\n * (loopback-only)\n *\n * These shapes mirror those handlers' request/response bodies exactly so the\n * gateway, the `cadet pair` CLI (`cli/src/commands/pair.ts`), the host-side\n * pairing sessions (`packages/local-mode/src/pair.ts`), and the web SPA\n * (`clients/web/src/lib/auth/remote-gateway-session.ts`) share one definition\n * and cannot silently drift.\n *\n * Timestamps are ISO-8601 strings — every gateway response serializes them via\n * `Date#toISOString()`.\n */\n\n/**\n * Pairing-challenge TTL in milliseconds (10 minutes): the gateway's challenge\n * store enforces it and the `cadet pair` CLI renders it in user-facing copy.\n */\nexport const REMOTE_WEB_PAIRING_CODE_TTL_MS = 10 * 60 * 1000;\n\n/** `POST /v1/remote-web/pairing-challenge` success response body (200). */\nexport interface RemoteWebPairingChallengeResponse {\n /** Opaque secret the paired device exchanges for a token. */\n deviceCode: string;\n /** Short human-readable code the host approves out of band. */\n userCode: string;\n /** URL the device opens to complete pairing. */\n verificationUri: string;\n /**\n * The base URL the challenge was minted for (echoed into verificationUri).\n * The gateway self-sources it — the request's own host through the trusted\n * edge, else its recorded ingress URL; callers cannot request a URL.\n */\n publicBaseUrl: string;\n /** ISO-8601 instant the challenge expires. */\n expiresAt: string;\n /** Seconds until the challenge expires. */\n expiresInSeconds: number;\n /** Recommended poll interval (seconds) for the token-exchange endpoint. */\n intervalSeconds: number;\n}\n\nexport const RemoteWebPairingChallengeResponseSchema = z.object({\n deviceCode: z.string(),\n userCode: z.string(),\n verificationUri: z.string(),\n publicBaseUrl: z.string(),\n expiresAt: z.string(),\n expiresInSeconds: z.number(),\n intervalSeconds: z.number(),\n}) satisfies z.ZodType<RemoteWebPairingChallengeResponse>;\n\n/** `POST /v1/remote-web/pairing-verification` request body. */\nexport interface RemoteWebPairingVerificationRequest {\n /** The `userCode` from the challenge, entered/scanned on the host. */\n userCode: string;\n}\n\n/**\n * `POST /v1/remote-web/pairing-verification` success response body (200).\n *\n * The gateway maps the `expired` / `invalid` outcomes to error responses, so\n * the only success shape on the wire is the approved variant.\n */\nexport const RemoteWebPairingVerificationResponseSchema = z.object({\n status: z.literal(\"approved\"),\n verificationUri: z.string(),\n /** ISO-8601 instant the approved challenge expires. */\n expiresAt: z.string(),\n}) satisfies z.ZodType<RemoteWebPairingVerificationResponse>;\n\nexport interface RemoteWebPairingVerificationResponse {\n status: \"approved\";\n verificationUri: string;\n /** ISO-8601 instant the approved challenge expires. */\n expiresAt: string;\n}\n\n/**\n * Platforms a device-bound pairing exchange may declare for itself. The value\n * is what the host's `Paired devices` list renders for the new pairing.\n */\nexport const REMOTE_WEB_PAIRING_PLATFORMS = [\n \"cli\",\n \"desktop\",\n \"ios\",\n \"android\",\n] as const;\n\nexport type RemoteWebPairingPlatform =\n (typeof REMOTE_WEB_PAIRING_PLATFORMS)[number];\n\n/** Platform recorded when an exchange names none the gateway recognizes. */\nexport const DEFAULT_REMOTE_WEB_PAIRING_PLATFORM: RemoteWebPairingPlatform =\n \"desktop\";\n\n/**\n * A requested platform coerced to a known value. The pairing-token route is\n * publicly reachable and the cloud renders verbatim in the host's\n * paired-devices list, so an unrecognized value never reaches the DB.\n */\nexport function resolveRemoteWebPairingPlatform(\n raw: unknown,\n): RemoteWebPairingPlatform {\n return (\n REMOTE_WEB_PAIRING_PLATFORMS.find((platform) => platform === raw) ??\n DEFAULT_REMOTE_WEB_PAIRING_PLATFORM\n );\n}\n\n/** `POST /v1/remote-web/pairing-token` request body. */\nexport interface RemoteWebPairingTokenRequest {\n /** The `deviceCode` from the challenge. */\n deviceCode: string;\n /**\n * Client-generated device id, sent only by a trusted host completing the\n * exchange for itself. It switches the gateway to a device-bound, per-device\n * revocable credential whose refresh token comes back in the response body.\n * Browsers omit it and keep the cookie delivery.\n */\n deviceId?: string;\n /** Platform to record for the device. Ignored without a `deviceId`. */\n platform?: RemoteWebPairingPlatform;\n /**\n * Optional self-reported device name, for example \"Cadet iOS app\". The gateway\n * stores it verbatim (capped) and never trusts it for authorization. Absent from\n * clients that predate this field.\n */\n clientReportedName?: string;\n}\n\n/**\n * `POST /v1/remote-web/pairing-token` still-pending response body (202) — the\n * challenge exists but has not been approved yet, so the client keeps polling.\n */\nexport interface RemoteWebPairingTokenPendingResponse {\n status: \"pending\";\n /** ISO-8601 instant the challenge expires. */\n expiresAt: string;\n /** Recommended poll interval (seconds) before the next exchange attempt. */\n intervalSeconds: number;\n}\n\n/**\n * `POST /v1/remote-web/pairing-token` approved response body (200) — carries\n * the minted session credentials. A browser exchange (no `deviceId`) receives\n * its refresh token out of band as an `HttpOnly` cookie and so omits the two\n * refresh fields below; a device-bound exchange receives it here instead.\n */\nexport interface RemoteWebPairingTokenApprovedResponse {\n status: \"approved\";\n accessToken: string;\n /** ISO-8601 instant the access token expires. */\n accessTokenExpiresAt: string;\n /** ISO-8601 instant after which the client should refresh the session. */\n refreshAfter: string;\n guardianId: string;\n assistantId: string;\n /** Device-bound refresh token, present only for a `deviceId` exchange. */\n refreshToken?: string;\n /** ISO-8601 instant the device-bound refresh token expires. */\n refreshTokenExpiresAt?: string;\n}\n\n/** Union of the two terminal `pairing-token` response bodies. */\nexport type RemoteWebPairingTokenResponse =\n | RemoteWebPairingTokenPendingResponse\n | RemoteWebPairingTokenApprovedResponse;\n\n// ── Shared pairing URL helpers ──────────────────────────────────────────────\n//\n// Every surface that mints a pairing (the `cadet pair` CLI, the web\n// settings \"Pair a device\" card) must accept the same public URLs and build\n// the same scannable links. The helpers are environment-neutral (WHATWG URL\n// only) so both Node and browser callers share one implementation.\n\n/** Why a public base URL can't be advertised in a pairing challenge. */\nexport type PublicBaseUrlRejection =\n | \"unparseable\"\n | \"loopback\"\n | \"private-address\"\n | \"non-https\"\n | \"service-website\";\n\nexport type PublicBaseUrlResult =\n | { ok: true; url: string }\n | { ok: false; reason: PublicBaseUrlRejection };\n\n/**\n * Hosts that are a tunnel/ingress vendor's own website, not a user's assistant\n * endpoint. These are the tunnel vendors our docs mention, and their sites are\n * exactly where a lost user grabs a URL from — e.g. a Tailscale admin invite\n * link (`login.tailscale.com/admin/invite/…`), which is https and non-loopback\n * and so clears every other check. Pairing refuses them with a targeted message\n * rather than minting a challenge the scanning device can never reach.\n */\nexport const TUNNEL_PROVIDER_WEBSITE_HOSTS = [\n \"login.tailscale.com\",\n \"tailscale.com\",\n \"www.tailscale.com\",\n \"ngrok.com\",\n \"dashboard.ngrok.com\",\n \"dash.cloudflare.com\",\n \"cloudflare.com\",\n \"www.cloudflare.com\",\n] as const;\n\n/**\n * A hostname with any trailing DNS root dot removed. `example.com.` and\n * `example.com` name the same host, and a resolver reads `localhost.` as the\n * loopback name, so every host comparison below runs on the stripped form.\n * Bracketed IPv6 literals never carry one.\n */\nfunction hostnameWithoutRootDot(hostname: string): string {\n return hostname.replace(/\\.+$/, \"\");\n}\n\n/**\n * A URL whose exact host is a tunnel/ingress vendor's own website (see\n * {@link TUNNEL_PROVIDER_WEBSITE_HOSTS}). Exact-host only: a user's real\n * Tailscale endpoint (`*.ts.net`) or Cloudflare-fronted domain is never a\n * listed host, so a legitimate address is never mistaken for a vendor site.\n */\nexport function isTunnelProviderWebsiteUrl(url: string): boolean {\n let hostname: string;\n try {\n // WHATWG URL lowercases the hostname during parsing.\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return false;\n }\n return (TUNNEL_PROVIDER_WEBSITE_HOSTS as readonly string[]).includes(\n hostname,\n );\n}\n\n/**\n * The display name of the tunnel/ingress vendor a service-website URL points\n * at (`\"Tailscale\"` / `\"ngrok\"` / `\"Cloudflare\"`), or null when the host is not\n * a known vendor site. Drives the \"This is <Name>'s website\" pairing guidance.\n */\nexport function tunnelProviderWebsiteName(url: string): string | null {\n let hostname: string;\n try {\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return null;\n }\n if (\n !(TUNNEL_PROVIDER_WEBSITE_HOSTS as readonly string[]).includes(hostname)\n ) {\n return null;\n }\n if (hostname.includes(\"tailscale\")) return \"Tailscale\";\n if (hostname.includes(\"ngrok\")) return \"ngrok\";\n if (hostname.includes(\"cloudflare\")) return \"Cloudflare\";\n return null;\n}\n\n/**\n * A URL's comparable host: root dot stripped and IPv6 brackets removed, or\n * null when the value is not a parseable URL.\n */\nfunction comparableHost(url: string): string | null {\n try {\n // WHATWG URL canonicalizes hostnames: IPv6 loopback is always \"[::1]\", a\n // bare \"0\" is \"0.0.0.0\", and encoded IPv4 literals become dotted quads.\n return hostnameWithoutRootDot(new URL(url).hostname).replace(\n /^\\[|\\]$/g,\n \"\",\n );\n } catch {\n return null;\n }\n}\n\n/**\n * Hosts that reach the dialing machine without a resolver having to agree:\n * `localhost`, `127.x.x.x`, `[::1]`, and the wildcard binds `0.0.0.0` / `[::]`,\n * in their dotted, hex, and IPv4-mapped spellings.\n */\nfunction isDnsIndependentLoopbackHost(host: string): boolean {\n return (\n host === \"localhost\" ||\n host === \"::1\" ||\n host === \"0:0:0:0:0:0:0:1\" ||\n /^127(?:\\.\\d{1,3}){3}$/.test(host) ||\n // A wildcard host reaches a local listener when dialed, so it counts as\n // local for the pairing and refresh-channel guards alike.\n host === \"0.0.0.0\" ||\n host === \"0\" ||\n host === \"::\" ||\n host === \"0:0:0:0:0:0:0:0\" ||\n // IPv4-mapped loopback and wildcard, in dotted and hex encodings.\n /^(?:0:0:0:0:0|:):ffff:127(?:\\.\\d{1,3}){3}$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:0\\.0\\.0\\.0$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:0:0$/.test(host)\n );\n}\n\n/**\n * A URL that reaches a listener on the machine dialing it, judged wide: the\n * literals {@link isDnsIndependentLoopbackHost} covers PLUS the whole reserved\n * `localhost` namespace (RFC 6761, so `foo.localhost` counts). A pairing link\n * that encodes one is unreachable from the scanning device, and a host that\n * POSTs to one is calling a service on its own machine.\n *\n * This is the one loopback predicate the whole pairing path reads (the pasted\n * address, and the gatewayUrl an import registers), so the same address class\n * can never be refused by one entry point and accepted by another. Every read\n * of it REFUSES the address it matches, which is why it is the wide one.\n * A guard that GRANTS something to loopback reads\n * {@link isDnsIndependentLoopbackUrl} instead.\n */\nexport function isLoopbackPublicUrl(url: string): boolean {\n const host = comparableHost(url);\n if (host === null) {\n return false;\n }\n return host.endsWith(\".localhost\") || isDnsIndependentLoopbackHost(host);\n}\n\n/**\n * A URL that reaches this machine whatever the resolver does, judged narrow:\n * exact `localhost` and the loopback/wildcard IP literals, and NOT the\n * reserved `.localhost` namespace. RFC 6761 says a resolver should map that\n * namespace to loopback, but glibc does not by default, so `evil.localhost`\n * is an ordinary DNS name that can answer with any address at all.\n *\n * Read this wherever loopback EARNS a privilege a public host does not get,\n * such as accepting a plaintext channel as confidential; read the wider\n * {@link isLoopbackPublicUrl} wherever loopback is refused. Both directions\n * then fail safe on a name that only might be local.\n */\nexport function isDnsIndependentLoopbackUrl(url: string): boolean {\n const host = comparableHost(url);\n return host !== null && isDnsIndependentLoopbackHost(host);\n}\n\n/** Canonical dotted-quad as its four octets, or null when it is not one. */\nfunction parseIpv4Literal(hostname: string): number[] | null {\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(hostname);\n if (!match) {\n return null;\n }\n const octets = match.slice(1).map(Number);\n return octets.every((octet) => octet <= 255) ? octets : null;\n}\n\n/** Bracketed IPv6 literal as its eight 16-bit pieces, or null. */\nfunction parseIpv6Literal(hostname: string): number[] | null {\n if (!hostname.startsWith(\"[\") || !hostname.endsWith(\"]\")) {\n return null;\n }\n const halves = hostname.slice(1, -1).split(\"::\");\n if (halves.length > 2) {\n return null;\n }\n const toPieces = (part: string): number[] | null => {\n if (!part) {\n return [];\n }\n const pieces: number[] = [];\n const labels = part.split(\":\");\n for (const [index, label] of labels.entries()) {\n // A trailing dotted-quad is legal IPv6 text. The WHATWG serializer never\n // emits one, but a hand-built literal can still reach this parser.\n if (index === labels.length - 1 && label.includes(\".\")) {\n const octets = parseIpv4Literal(label);\n if (!octets) {\n return null;\n }\n pieces.push(\n ((octets[0] ?? 0) << 8) | (octets[1] ?? 0),\n ((octets[2] ?? 0) << 8) | (octets[3] ?? 0),\n );\n continue;\n }\n if (!/^[0-9a-f]{1,4}$/i.test(label)) {\n return null;\n }\n pieces.push(Number.parseInt(label, 16));\n }\n return pieces;\n };\n const head = toPieces(halves[0] ?? \"\");\n const tail = halves.length === 2 ? toPieces(halves[1] ?? \"\") : [];\n if (!head || !tail) {\n return null;\n }\n if (halves.length === 1) {\n return head.length === 8 ? head : null;\n }\n const gap = 8 - head.length - tail.length;\n return gap >= 1 ? [...head, ...Array<number>(gap).fill(0), ...tail] : null;\n}\n\n/**\n * IPv4 ranges that are not publicly routable, judged from the four octets of a\n * canonical dotted-quad. Loopback (127/8) is included so the predicate is\n * complete on its own; `resolvePublicBaseUrl` still reports it as `loopback`\n * because it checks that first.\n *\n * 100.64.0.0/10 is DELIBERATELY ABSENT. Tailscale hands out CGNAT addresses\n * from that range and a Tailscale endpoint is a supported pairing target.\n */\nfunction isPrivateIpv4(octets: readonly number[]): boolean {\n const a = octets[0] ?? 0;\n const b = octets[1] ?? 0;\n const c = octets[2] ?? 0;\n return (\n a === 0 || // 0/8 \"this network\"\n a === 10 || // 10/8 private\n a === 127 || // 127/8 loopback\n (a === 169 && b === 254) || // 169.254/16 link-local, incl. cloud metadata\n (a === 172 && b >= 16 && b <= 31) || // 172.16/12 private\n (a === 192 && b === 0 && c === 0) || // 192.0.0/24 protocol assignments\n (a === 192 && b === 168) || // 192.168/16 private\n (a === 198 && (b === 18 || b === 19)) || // 198.18/15 benchmarking\n a >= 224 // 224/4 multicast, 240/4 reserved, 255.255.255.255 broadcast\n );\n}\n\n/**\n * A URL whose hostname is an IP literal outside publicly routable space:\n * private, loopback, link-local (which is where the cloud instance metadata\n * endpoint 169.254.169.254 lives), multicast, or reserved, in either address\n * family. Pairing POSTs to whatever address the user pasted, so a literal\n * aimed at the host's own network is refused before any request is made.\n *\n * Only literals written directly in the address are checked. Hostnames are\n * NEVER resolved and resolved addresses are NEVER filtered, deliberately:\n * Tailscale endpoints (`*.ts.net`) are a supported pairing target and resolve\n * into the 100.64.0.0/10 CGNAT range, so post-DNS filtering would refuse them\n * outright. It would also be TOCTOU-prone, since a name can resolve\n * differently between the check and the connection.\n */\nexport function isPrivateNetworkPublicUrl(url: string): boolean {\n let hostname: string;\n try {\n // WHATWG URL canonicalizes IP literals: decimal, octal, and hex IPv4 forms\n // collapse to a dotted-quad, and IPv6 to a bracketed lowercase literal.\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return false;\n }\n const ipv4 = parseIpv4Literal(hostname);\n if (ipv4) {\n return isPrivateIpv4(ipv4);\n }\n const ipv6 = parseIpv6Literal(hostname);\n if (!ipv6) {\n return false;\n }\n // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d) literals carry\n // an IPv4 destination, so they are unwrapped and judged as IPv4.\n const low = ipv6[5] ?? 0;\n if (\n ipv6.slice(0, 5).every((piece) => piece === 0) &&\n (low === 0xffff || low === 0)\n ) {\n const mapped = ipv6[6] ?? 0;\n const trailing = ipv6[7] ?? 0;\n return isPrivateIpv4([\n mapped >> 8,\n mapped & 0xff,\n trailing >> 8,\n trailing & 0xff,\n ]);\n }\n const top = ipv6[0] ?? 0;\n return (\n (top & 0xfe00) === 0xfc00 || // fc00::/7 unique-local\n (top & 0xffc0) === 0xfe80 || // fe80::/10 link-local\n (top & 0xff00) === 0xff00 // ff00::/8 multicast\n );\n}\n\n/**\n * Normalize an address to the public base a scanning device opens:\n * query/hash stripped, the pair page's `account` path segment (and everything\n * after it) removed so a pasted pair-page URL collapses to its base, and\n * trailing slashes trimmed. Throws if the value is not a parseable URL.\n */\nexport function normalizePairingBaseUrl(value: string): string {\n const url = new URL(value);\n url.search = \"\";\n url.hash = \"\";\n const parts = url.pathname.split(\"/\").filter(Boolean);\n const cutIndex = parts.indexOf(\"account\");\n if (cutIndex >= 0) {\n parts.splice(cutIndex);\n }\n url.pathname = parts.length ? `/${parts.join(\"/\")}` : \"/\";\n return url.toString().replace(/\\/+$/, \"\");\n}\n\n/**\n * Resolve an address to the public https base URL to advertise in a pairing\n * challenge, or report why it can't be used. Loopback, private-network IP\n * literals, and non-https links are refused with a specific reason callers\n * turn into their own guidance.\n *\n * Hosts POST to this address during pairing, so the refusals are the SSRF\n * containment for every pairing surface. See\n * {@link isPrivateNetworkPublicUrl} for why resolved addresses are left alone.\n */\nexport function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {\n let normalized: string;\n try {\n normalized = normalizePairingBaseUrl(raw);\n } catch {\n return { ok: false, reason: \"unparseable\" };\n }\n if (isLoopbackPublicUrl(normalized)) {\n return { ok: false, reason: \"loopback\" };\n }\n if (isPrivateNetworkPublicUrl(normalized)) {\n return { ok: false, reason: \"private-address\" };\n }\n if (isTunnelProviderWebsiteUrl(normalized)) {\n return { ok: false, reason: \"service-website\" };\n }\n if (new URL(normalized).protocol !== \"https:\") {\n return { ok: false, reason: \"non-https\" };\n }\n return { ok: true, url: normalized };\n}\n\n/**\n * The scannable pair URL: the challenge's verification URI with the device\n * code carried in the fragment (`#device_code=…`), matching what the pair\n * page reads on load. Fragments never reach the wire.\n */\nexport function buildRemoteWebPairingUrl(\n challenge: Pick<\n RemoteWebPairingChallengeResponse,\n \"verificationUri\" | \"deviceCode\"\n >,\n): string {\n const url = new URL(challenge.verificationUri);\n url.hash = new URLSearchParams({\n device_code: challenge.deviceCode,\n }).toString();\n return url.toString();\n}\n\n/**\n * Base that makes a relative pairing link parseable. Only the query and\n * fragment are read off the result, so it never reaches a caller.\n */\nconst RELATIVE_PAIRING_LINK_BASE = \"https://pairing.invalid\";\n\n/** The device/user codes a pairing link can carry. */\nexport interface RemoteWebPairingParams {\n deviceCode: string | null;\n userCode: string | null;\n}\n\nfunction firstParam(\n params: URLSearchParams,\n ...names: string[]\n): string | null {\n for (const name of names) {\n const value = params.get(name)?.trim();\n if (value) {\n return value;\n }\n }\n return null;\n}\n\n/**\n * Query parameters merged with fragment parameters, query winning on a clash.\n * Pairing links carry the device code in the fragment so it never reaches the\n * wire, but hand-assembled links put it in the query.\n */\nfunction pairingLinkParams(url: URL): URLSearchParams {\n const merged = new URLSearchParams(url.search);\n const hash = url.hash.startsWith(\"#\") ? url.hash.slice(1) : url.hash;\n for (const [key, value] of new URLSearchParams(hash)) {\n if (!merged.has(key)) {\n merged.set(key, value);\n }\n }\n return merged;\n}\n\n/**\n * Read the pairing codes off a link, accepting either casing (`device_code` /\n * `deviceCode`) from either the query string or the fragment. Relative values\n * are accepted so a router can pass `pathname + search + hash` straight in.\n */\nexport function parseRemoteWebPairingParams(\n value: string | URL,\n): RemoteWebPairingParams {\n const url =\n typeof value === \"string\"\n ? new URL(value, RELATIVE_PAIRING_LINK_BASE)\n : value;\n const params = pairingLinkParams(url);\n return {\n deviceCode: firstParam(params, \"deviceCode\", \"device_code\"),\n userCode: firstParam(params, \"userCode\", \"user_code\"),\n };\n}\n\n/** Outcome of {@link parsePairingAddress}. */\nexport type ParsePairingAddressResult =\n | { ok: true; publicBaseUrl: string; deviceCode: string | null }\n | { ok: false; reason: PublicBaseUrlRejection };\n\n/**\n * The inverse of {@link buildRemoteWebPairingUrl}: what a pasted pairing\n * address means. A full pairing link yields its base plus the device code it\n * carries; a bare `https://host` address yields a null device code, leaving\n * the caller to mint its own challenge. The base goes through\n * {@link resolvePublicBaseUrl}, so loopback, private-network literals,\n * non-https, and tunnel-vendor websites are refused with the same reasons\n * every other pairing surface reports.\n */\nexport function parsePairingAddress(raw: string): ParsePairingAddressResult {\n const resolved = resolvePublicBaseUrl(raw);\n if (!resolved.ok) {\n return resolved;\n }\n return {\n ok: true,\n publicBaseUrl: resolved.url,\n deviceCode: parseRemoteWebPairingParams(raw).deviceCode,\n };\n}\n\n/**\n * What a pairing attempt failed on, for callers picking recovery copy\n */\nexport type PairingFailureReason =\n /** The pasted address is not a usable assistant address. */\n | \"invalid-address\"\n /** No live session for this handle: it was cancelled or never existed. */\n | \"unknown-session\"\n /** The device code expired, was denied, or was already spent. */\n | \"expired\"\n /** The assistant could not be reached. */\n | \"unreachable\"\n /**\n * The assistant refused the request with a status that left the device code\n * exchangeable, so the same session is worth another attempt.\n */\n | \"gateway-retryable\"\n /**\n * The assistant answered, but with a reply this device cannot use. The code\n * behind it is spent or unknowable, so the attempt is settled.\n */\n | \"gateway\"\n /** The credentials arrived, but registering them locally was refused. */\n | \"import\"\n /**\n * The local destination was refused BEFORE the exchange, so the one-time\n * code is untouched and the session is still pollable. Only a caller that\n * changes what it asked for (a different `name`) can get past it, so it is\n * not worth another identical attempt.\n */\n | \"import-precheck\";\n\n/**\n * Every reason, mapped to whether another attempt against the same session can\n * still succeed. Two classes leave the device code exchangeable host-side:\n *\n * - `unreachable`, the transport class (a thrown fetch, a timeout, a refused\n * redirect, a body that errored mid-stream). Nothing reached the assistant,\n * so the session and the code are untouched.\n * - `gateway-retryable`, a non-200 the assistant answered with. The gateway\n * releases the challenge before a repairable failure (a transient error, or\n * the `GUARDIAN_REPAIR_REQUIRED` 503), so the same code stays exchangeable.\n *\n * Everything else ends the attempt. `invalid-address` and `unknown-session`\n * cannot resolve by waiting; `expired` and `import` mean the one-time code is\n * already spent; `gateway` means the assistant answered with something this\n * device cannot use (an over-cap body, credentials it cannot persist, a 200\n * that is not a pairing reply), past which the code is spent rather than\n * released; and `import-precheck` refused the local destination before the\n * exchange, so an identical attempt is refused identically.\n *\n * `import-precheck` is the one of those that leaves the SESSION alive, which\n * is a separate question from whether to retry: see\n * {@link pairingSessionSurvives}.\n *\n * The `satisfies` clause keeps the map exhaustive, so a new reason does not\n * compile until it is classified here.\n */\nconst PAIRING_REASON_RETRYABLE = {\n \"invalid-address\": false,\n \"unknown-session\": false,\n expired: false,\n unreachable: true,\n \"gateway-retryable\": true,\n gateway: false,\n import: false,\n \"import-precheck\": false,\n} satisfies Record<PairingFailureReason, boolean>;\n\n/** The reasons {@link isRetryablePairingReason} accepts. */\nexport const RETRYABLE_PAIRING_REASONS: ReadonlySet<PairingFailureReason> =\n new Set(\n (Object.keys(PAIRING_REASON_RETRYABLE) as PairingFailureReason[]).filter(\n (reason) => PAIRING_REASON_RETRYABLE[reason],\n ),\n );\n\n/**\n * Whether a refused pairing step is worth another attempt. An unlabelled\n * failure reads as settled, so a host too old to name a reason ends the\n * attempt rather than being spun against until the code expires.\n */\nexport function isRetryablePairingReason(\n reason: PairingFailureReason | null | undefined,\n): boolean {\n return reason != null && RETRYABLE_PAIRING_REASONS.has(reason);\n}\n\n/**\n * Every reason, mapped to whether the pairing session it came from is still\n * live host-side. A caller holding the handle reads this to decide whether to\n * release the session: releasing a live one throws away a device code that is\n * still good and costs the user a fresh pairing link.\n *\n * This is deliberately NOT the retryable map. `import-precheck` is the reason\n * the two disagree on: nothing was spent and the same handle still polls, but\n * only once the caller changes the name it asked for, so a blind retry is\n * futile while dropping the session is destructive.\n *\n * `invalid-address` never had a session to begin with, so it reads false the\n * same way a dead one does: there is nothing to hold onto either way.\n */\nconst PAIRING_REASON_SESSION_LIVE = {\n \"invalid-address\": false,\n \"unknown-session\": false,\n expired: false,\n unreachable: true,\n \"gateway-retryable\": true,\n gateway: false,\n import: false,\n \"import-precheck\": true,\n} satisfies Record<PairingFailureReason, boolean>;\n\n/**\n * Whether the session behind a refused pairing step is still pollable. An\n * unlabelled failure reads as settled, so a host too old to name a reason has\n * its session released rather than left to time out.\n */\nexport function pairingSessionSurvives(\n reason: PairingFailureReason | null | undefined,\n): boolean {\n return reason != null && PAIRING_REASON_SESSION_LIVE[reason] === true;\n}\n"],"mappings":"+DA+DuD,EAAS,CAC9D,WAAY,GAAU,CACtB,SAAU,GAAU,CACpB,gBAAiB,GAAU,CAC3B,cAAe,GAAU,CACzB,UAAW,GAAU,CACrB,iBAAkB,GAAU,CAC5B,gBAAiB,GAAU,CAC5B,CAAC,CAcwD,EAAS,CACjE,OAAQ,EAAU,WAAW,CAC7B,gBAAiB,GAAU,CAE3B,UAAW,GAAU,CACtB,CAAC,CAgaF,SAAgB,EAAwB,EAAuB,CAC7D,IAAM,EAAM,IAAI,IAAI,EAAM,CAC1B,EAAI,OAAS,GACb,EAAI,KAAO,GACX,IAAM,EAAQ,EAAI,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CAC/C,EAAW,EAAM,QAAQ,UAAU,CAKzC,OAJI,GAAY,GACd,EAAM,OAAO,EAAS,CAExB,EAAI,SAAW,EAAM,OAAS,IAAI,EAAM,KAAK,IAAI,GAAK,IAC/C,EAAI,UAAU,CAAC,QAAQ,OAAQ,GAAG,CAwC3C,SAAgB,EACd,EAIQ,CACR,IAAM,EAAM,IAAI,IAAI,EAAU,gBAAgB,CAI9C,MAHA,GAAI,KAAO,IAAI,gBAAgB,CAC7B,YAAa,EAAU,WACxB,CAAC,CAAC,UAAU,CACN,EAAI,UAAU,CAOvB,IAAM,EAA6B,0BAQnC,SAAS,EACP,EACA,GAAG,EACY,CACf,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAQ,EAAO,IAAI,EAAK,EAAE,MAAM,CACtC,GAAI,EACF,OAAO,EAGX,OAAO,KAQT,SAAS,EAAkB,EAA2B,CACpD,IAAM,EAAS,IAAI,gBAAgB,EAAI,OAAO,CACxC,EAAO,EAAI,KAAK,WAAW,IAAI,CAAG,EAAI,KAAK,MAAM,EAAE,CAAG,EAAI,KAChE,IAAK,GAAM,CAAC,EAAK,KAAU,IAAI,gBAAgB,EAAK,CAC7C,EAAO,IAAI,EAAI,EAClB,EAAO,IAAI,EAAK,EAAM,CAG1B,OAAO,EAQT,SAAgB,EACd,EACwB,CAKxB,IAAM,EAAS,EAHb,OAAO,GAAU,SACb,IAAI,IAAI,EAAO,EAA2B,CAC1C,EAC+B,CACrC,MAAO,CACL,WAAY,EAAW,EAAQ,aAAc,cAAc,CAC3D,SAAU,EAAW,EAAQ,WAAY,YAAY,CACtD,CAuFH,IAAM,EAA2B,CAC/B,kBAAmB,GACnB,kBAAmB,GACnB,QAAS,GACT,YAAa,GACb,oBAAqB,GACrB,QAAS,GACT,OAAQ,GACR,kBAAmB,GACpB,CAIC,IAAI,IACD,OAAO,KAAK,EAAyB,CAA4B,OAC/D,GAAW,EAAyB,GACtC,CACF"}
1
+ {"version":3,"file":"remote-web-pairing-BGorUWrN.js","names":[],"sources":["../../../../../packages/service-contracts/src/remote-web-pairing.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Wire contracts for the remote-web pairing flow — the RFC 8628-style\n * device-code exchange that connects a browser (or the iOS app) to a\n * self-hosted assistant over its public ingress URL.\n *\n * The gateway routes are the authoritative serving side:\n * - `POST /v1/remote-web/pairing-challenge` mint a challenge\n * (`gateway/src/http/routes/remote-web-pairing-challenge.ts`,\n * `gateway/src/remote-web/pairing-challenge-store.ts`)\n * - `POST /v1/remote-web/pairing-verification` approve by user code\n * (`gateway/src/http/routes/remote-web-pairing-verification.ts`)\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-token` poll + exchange device code\n * (`gateway/src/http/routes/remote-web-pairing-token.ts`): a browser\n * receives its refresh token as an `HttpOnly` cookie; a request that\n * carries a `deviceId` receives a device-bound one in the body instead\n * - `GET /v1/remote-web/pairing-requests` list pending challenges\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-requests/approve` approve by request id\n * (loopback-only)\n * - `POST /v1/remote-web/pairing-requests/deny` deny (delete) by request id\n * (loopback-only)\n *\n * These shapes mirror those handlers' request/response bodies exactly so the\n * gateway, the `cadet pair` CLI (`cli/src/commands/pair.ts`), the host-side\n * pairing sessions (`packages/local-mode/src/pair.ts`), and the web SPA\n * (`clients/web/src/lib/auth/remote-gateway-session.ts`) share one definition\n * and cannot silently drift.\n *\n * Timestamps are ISO-8601 strings — every gateway response serializes them via\n * `Date#toISOString()`.\n */\n\n/**\n * Pairing-challenge TTL in milliseconds (10 minutes): the gateway's challenge\n * store enforces it and the `cadet pair` CLI renders it in user-facing copy.\n */\nexport const REMOTE_WEB_PAIRING_CODE_TTL_MS = 10 * 60 * 1000;\n\n/** `POST /v1/remote-web/pairing-challenge` success response body (200). */\nexport interface RemoteWebPairingChallengeResponse {\n /** Opaque secret the paired device exchanges for a token. */\n deviceCode: string;\n /** Short human-readable code the host approves out of band. */\n userCode: string;\n /** URL the device opens to complete pairing. */\n verificationUri: string;\n /**\n * The base URL the challenge was minted for (echoed into verificationUri).\n * The gateway self-sources it — the request's own host through the trusted\n * edge, else its recorded ingress URL; callers cannot request a URL.\n */\n publicBaseUrl: string;\n /** ISO-8601 instant the challenge expires. */\n expiresAt: string;\n /** Seconds until the challenge expires. */\n expiresInSeconds: number;\n /** Recommended poll interval (seconds) for the token-exchange endpoint. */\n intervalSeconds: number;\n}\n\nexport const RemoteWebPairingChallengeResponseSchema = z.object({\n deviceCode: z.string(),\n userCode: z.string(),\n verificationUri: z.string(),\n publicBaseUrl: z.string(),\n expiresAt: z.string(),\n expiresInSeconds: z.number(),\n intervalSeconds: z.number(),\n}) satisfies z.ZodType<RemoteWebPairingChallengeResponse>;\n\n/** `POST /v1/remote-web/pairing-verification` request body. */\nexport interface RemoteWebPairingVerificationRequest {\n /** The `userCode` from the challenge, entered/scanned on the host. */\n userCode: string;\n}\n\n/**\n * `POST /v1/remote-web/pairing-verification` success response body (200).\n *\n * The gateway maps the `expired` / `invalid` outcomes to error responses, so\n * the only success shape on the wire is the approved variant.\n */\nexport const RemoteWebPairingVerificationResponseSchema = z.object({\n status: z.literal(\"approved\"),\n verificationUri: z.string(),\n /** ISO-8601 instant the approved challenge expires. */\n expiresAt: z.string(),\n}) satisfies z.ZodType<RemoteWebPairingVerificationResponse>;\n\nexport interface RemoteWebPairingVerificationResponse {\n status: \"approved\";\n verificationUri: string;\n /** ISO-8601 instant the approved challenge expires. */\n expiresAt: string;\n}\n\n/**\n * Platforms a device-bound pairing exchange may declare for itself. The value\n * is what the host's `Paired devices` list renders for the new pairing.\n */\nexport const REMOTE_WEB_PAIRING_PLATFORMS = [\n \"cli\",\n \"desktop\",\n \"ios\",\n \"android\",\n] as const;\n\nexport type RemoteWebPairingPlatform =\n (typeof REMOTE_WEB_PAIRING_PLATFORMS)[number];\n\n/** Platform recorded when an exchange names none the gateway recognizes. */\nexport const DEFAULT_REMOTE_WEB_PAIRING_PLATFORM: RemoteWebPairingPlatform =\n \"desktop\";\n\n/**\n * A requested platform coerced to a known value. The pairing-token route is\n * publicly reachable and the cloud renders verbatim in the host's\n * paired-devices list, so an unrecognized value never reaches the DB.\n */\nexport function resolveRemoteWebPairingPlatform(\n raw: unknown,\n): RemoteWebPairingPlatform {\n return (\n REMOTE_WEB_PAIRING_PLATFORMS.find((platform) => platform === raw) ??\n DEFAULT_REMOTE_WEB_PAIRING_PLATFORM\n );\n}\n\n/** `POST /v1/remote-web/pairing-token` request body. */\nexport interface RemoteWebPairingTokenRequest {\n /** The `deviceCode` from the challenge. */\n deviceCode: string;\n /**\n * Client-generated device id, sent only by a trusted host completing the\n * exchange for itself. It switches the gateway to a device-bound, per-device\n * revocable credential whose refresh token comes back in the response body.\n * Browsers omit it and keep the cookie delivery.\n */\n deviceId?: string;\n /** Platform to record for the device. Ignored without a `deviceId`. */\n platform?: RemoteWebPairingPlatform;\n /**\n * Optional self-reported device name, for example \"Cadet iOS app\". The gateway\n * stores it verbatim (capped) and never trusts it for authorization. Absent from\n * clients that predate this field.\n */\n clientReportedName?: string;\n}\n\n/**\n * `POST /v1/remote-web/pairing-token` still-pending response body (202) — the\n * challenge exists but has not been approved yet, so the client keeps polling.\n */\nexport interface RemoteWebPairingTokenPendingResponse {\n status: \"pending\";\n /** ISO-8601 instant the challenge expires. */\n expiresAt: string;\n /** Recommended poll interval (seconds) before the next exchange attempt. */\n intervalSeconds: number;\n}\n\n/**\n * `POST /v1/remote-web/pairing-token` approved response body (200) — carries\n * the minted session credentials. A browser exchange (no `deviceId`) receives\n * its refresh token out of band as an `HttpOnly` cookie and so omits the two\n * refresh fields below; a device-bound exchange receives it here instead.\n */\nexport interface RemoteWebPairingTokenApprovedResponse {\n status: \"approved\";\n accessToken: string;\n /** ISO-8601 instant the access token expires. */\n accessTokenExpiresAt: string;\n /** ISO-8601 instant after which the client should refresh the session. */\n refreshAfter: string;\n guardianId: string;\n assistantId: string;\n /** Device-bound refresh token, present only for a `deviceId` exchange. */\n refreshToken?: string;\n /** ISO-8601 instant the device-bound refresh token expires. */\n refreshTokenExpiresAt?: string;\n}\n\n/** Union of the two terminal `pairing-token` response bodies. */\nexport type RemoteWebPairingTokenResponse =\n | RemoteWebPairingTokenPendingResponse\n | RemoteWebPairingTokenApprovedResponse;\n\n// ── Shared pairing URL helpers ──────────────────────────────────────────────\n//\n// Every surface that mints a pairing (the `cadet pair` CLI, the web\n// settings \"Pair a device\" card) must accept the same public URLs and build\n// the same scannable links. The helpers are environment-neutral (WHATWG URL\n// only) so both Node and browser callers share one implementation.\n\n/** Why a public base URL can't be advertised in a pairing challenge. */\nexport type PublicBaseUrlRejection =\n | \"unparseable\"\n | \"loopback\"\n | \"private-address\"\n | \"non-https\"\n | \"service-website\";\n\nexport type PublicBaseUrlResult =\n | { ok: true; url: string }\n | { ok: false; reason: PublicBaseUrlRejection };\n\n/**\n * Hosts that are a tunnel/ingress vendor's own website, not a user's assistant\n * endpoint. These are the tunnel vendors our docs mention, and their sites are\n * exactly where a lost user grabs a URL from — e.g. a Tailscale admin invite\n * link (`login.tailscale.com/admin/invite/…`), which is https and non-loopback\n * and so clears every other check. Pairing refuses them with a targeted message\n * rather than minting a challenge the scanning device can never reach.\n */\nexport const TUNNEL_PROVIDER_WEBSITE_HOSTS = [\n \"login.tailscale.com\",\n \"tailscale.com\",\n \"www.tailscale.com\",\n \"ngrok.com\",\n \"dashboard.ngrok.com\",\n \"dash.cloudflare.com\",\n \"cloudflare.com\",\n \"www.cloudflare.com\",\n] as const;\n\n/**\n * A hostname with any trailing DNS root dot removed. `example.com.` and\n * `example.com` name the same host, and a resolver reads `localhost.` as the\n * loopback name, so every host comparison below runs on the stripped form.\n * Bracketed IPv6 literals never carry one.\n */\nfunction hostnameWithoutRootDot(hostname: string): string {\n return hostname.replace(/\\.+$/, \"\");\n}\n\n/**\n * A URL whose exact host is a tunnel/ingress vendor's own website (see\n * {@link TUNNEL_PROVIDER_WEBSITE_HOSTS}). Exact-host only: a user's real\n * Tailscale endpoint (`*.ts.net`) or Cloudflare-fronted domain is never a\n * listed host, so a legitimate address is never mistaken for a vendor site.\n */\nexport function isTunnelProviderWebsiteUrl(url: string): boolean {\n let hostname: string;\n try {\n // WHATWG URL lowercases the hostname during parsing.\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return false;\n }\n return (TUNNEL_PROVIDER_WEBSITE_HOSTS as readonly string[]).includes(\n hostname,\n );\n}\n\n/**\n * The display name of the tunnel/ingress vendor a service-website URL points\n * at (`\"Tailscale\"` / `\"ngrok\"` / `\"Cloudflare\"`), or null when the host is not\n * a known vendor site. Drives the \"This is <Name>'s website\" pairing guidance.\n */\nexport function tunnelProviderWebsiteName(url: string): string | null {\n let hostname: string;\n try {\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return null;\n }\n if (\n !(TUNNEL_PROVIDER_WEBSITE_HOSTS as readonly string[]).includes(hostname)\n ) {\n return null;\n }\n if (hostname.includes(\"tailscale\")) return \"Tailscale\";\n if (hostname.includes(\"ngrok\")) return \"ngrok\";\n if (hostname.includes(\"cloudflare\")) return \"Cloudflare\";\n return null;\n}\n\n/**\n * A URL's comparable host: root dot stripped and IPv6 brackets removed, or\n * null when the value is not a parseable URL.\n */\nfunction comparableHost(url: string): string | null {\n try {\n // WHATWG URL canonicalizes hostnames: IPv6 loopback is always \"[::1]\", a\n // bare \"0\" is \"0.0.0.0\", and encoded IPv4 literals become dotted quads.\n return hostnameWithoutRootDot(new URL(url).hostname).replace(\n /^\\[|\\]$/g,\n \"\",\n );\n } catch {\n return null;\n }\n}\n\n/**\n * Hosts that reach the dialing machine without a resolver having to agree:\n * `localhost`, `127.x.x.x`, `[::1]`, and the wildcard binds `0.0.0.0` / `[::]`,\n * in their dotted, hex, and IPv4-mapped spellings.\n */\nfunction isDnsIndependentLoopbackHost(host: string): boolean {\n return (\n host === \"localhost\" ||\n host === \"::1\" ||\n host === \"0:0:0:0:0:0:0:1\" ||\n /^127(?:\\.\\d{1,3}){3}$/.test(host) ||\n // A wildcard host reaches a local listener when dialed, so it counts as\n // local for the pairing and refresh-channel guards alike.\n host === \"0.0.0.0\" ||\n host === \"0\" ||\n host === \"::\" ||\n host === \"0:0:0:0:0:0:0:0\" ||\n // IPv4-mapped loopback and wildcard, in dotted and hex encodings.\n /^(?:0:0:0:0:0|:):ffff:127(?:\\.\\d{1,3}){3}$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:0\\.0\\.0\\.0$/.test(host) ||\n /^(?:0:0:0:0:0|:):ffff:0:0$/.test(host)\n );\n}\n\n/**\n * A URL that reaches a listener on the machine dialing it, judged wide: the\n * literals {@link isDnsIndependentLoopbackHost} covers PLUS the whole reserved\n * `localhost` namespace (RFC 6761, so `foo.localhost` counts). A pairing link\n * that encodes one is unreachable from the scanning device, and a host that\n * POSTs to one is calling a service on its own machine.\n *\n * This is the one loopback predicate the whole pairing path reads (the pasted\n * address, and the gatewayUrl an import registers), so the same address class\n * can never be refused by one entry point and accepted by another. Every read\n * of it REFUSES the address it matches, which is why it is the wide one.\n * A guard that GRANTS something to loopback reads\n * {@link isDnsIndependentLoopbackUrl} instead.\n */\nexport function isLoopbackPublicUrl(url: string): boolean {\n const host = comparableHost(url);\n if (host === null) {\n return false;\n }\n return host.endsWith(\".localhost\") || isDnsIndependentLoopbackHost(host);\n}\n\n/**\n * A URL that reaches this machine whatever the resolver does, judged narrow:\n * exact `localhost` and the loopback/wildcard IP literals, and NOT the\n * reserved `.localhost` namespace. RFC 6761 says a resolver should map that\n * namespace to loopback, but glibc does not by default, so `evil.localhost`\n * is an ordinary DNS name that can answer with any address at all.\n *\n * Read this wherever loopback EARNS a privilege a public host does not get,\n * such as accepting a plaintext channel as confidential; read the wider\n * {@link isLoopbackPublicUrl} wherever loopback is refused. Both directions\n * then fail safe on a name that only might be local.\n */\nexport function isDnsIndependentLoopbackUrl(url: string): boolean {\n const host = comparableHost(url);\n return host !== null && isDnsIndependentLoopbackHost(host);\n}\n\n/** Canonical dotted-quad as its four octets, or null when it is not one. */\nfunction parseIpv4Literal(hostname: string): number[] | null {\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(hostname);\n if (!match) {\n return null;\n }\n const octets = match.slice(1).map(Number);\n return octets.every((octet) => octet <= 255) ? octets : null;\n}\n\n/** Bracketed IPv6 literal as its eight 16-bit pieces, or null. */\nfunction parseIpv6Literal(hostname: string): number[] | null {\n if (!hostname.startsWith(\"[\") || !hostname.endsWith(\"]\")) {\n return null;\n }\n const halves = hostname.slice(1, -1).split(\"::\");\n if (halves.length > 2) {\n return null;\n }\n const toPieces = (part: string): number[] | null => {\n if (!part) {\n return [];\n }\n const pieces: number[] = [];\n const labels = part.split(\":\");\n for (const [index, label] of labels.entries()) {\n // A trailing dotted-quad is legal IPv6 text. The WHATWG serializer never\n // emits one, but a hand-built literal can still reach this parser.\n if (index === labels.length - 1 && label.includes(\".\")) {\n const octets = parseIpv4Literal(label);\n if (!octets) {\n return null;\n }\n pieces.push(\n ((octets[0] ?? 0) << 8) | (octets[1] ?? 0),\n ((octets[2] ?? 0) << 8) | (octets[3] ?? 0),\n );\n continue;\n }\n if (!/^[0-9a-f]{1,4}$/i.test(label)) {\n return null;\n }\n pieces.push(Number.parseInt(label, 16));\n }\n return pieces;\n };\n const head = toPieces(halves[0] ?? \"\");\n const tail = halves.length === 2 ? toPieces(halves[1] ?? \"\") : [];\n if (!head || !tail) {\n return null;\n }\n if (halves.length === 1) {\n return head.length === 8 ? head : null;\n }\n const gap = 8 - head.length - tail.length;\n return gap >= 1 ? [...head, ...Array<number>(gap).fill(0), ...tail] : null;\n}\n\n/**\n * IPv4 ranges that are not publicly routable, judged from the four octets of a\n * canonical dotted-quad. Loopback (127/8) is included so the predicate is\n * complete on its own; `resolvePublicBaseUrl` still reports it as `loopback`\n * because it checks that first.\n *\n * 100.64.0.0/10 is DELIBERATELY ABSENT. Tailscale hands out CGNAT addresses\n * from that range and a Tailscale endpoint is a supported pairing target.\n */\nfunction isPrivateIpv4(octets: readonly number[]): boolean {\n const a = octets[0] ?? 0;\n const b = octets[1] ?? 0;\n const c = octets[2] ?? 0;\n return (\n a === 0 || // 0/8 \"this network\"\n a === 10 || // 10/8 private\n a === 127 || // 127/8 loopback\n (a === 169 && b === 254) || // 169.254/16 link-local, incl. cloud metadata\n (a === 172 && b >= 16 && b <= 31) || // 172.16/12 private\n (a === 192 && b === 0 && c === 0) || // 192.0.0/24 protocol assignments\n (a === 192 && b === 168) || // 192.168/16 private\n (a === 198 && (b === 18 || b === 19)) || // 198.18/15 benchmarking\n a >= 224 // 224/4 multicast, 240/4 reserved, 255.255.255.255 broadcast\n );\n}\n\n/**\n * A URL whose hostname is an IP literal outside publicly routable space:\n * private, loopback, link-local (which is where the cloud instance metadata\n * endpoint 169.254.169.254 lives), multicast, or reserved, in either address\n * family. Pairing POSTs to whatever address the user pasted, so a literal\n * aimed at the host's own network is refused before any request is made.\n *\n * Only literals written directly in the address are checked. Hostnames are\n * NEVER resolved and resolved addresses are NEVER filtered, deliberately:\n * Tailscale endpoints (`*.ts.net`) are a supported pairing target and resolve\n * into the 100.64.0.0/10 CGNAT range, so post-DNS filtering would refuse them\n * outright. It would also be TOCTOU-prone, since a name can resolve\n * differently between the check and the connection.\n */\nexport function isPrivateNetworkPublicUrl(url: string): boolean {\n let hostname: string;\n try {\n // WHATWG URL canonicalizes IP literals: decimal, octal, and hex IPv4 forms\n // collapse to a dotted-quad, and IPv6 to a bracketed lowercase literal.\n hostname = hostnameWithoutRootDot(new URL(url).hostname);\n } catch {\n return false;\n }\n const ipv4 = parseIpv4Literal(hostname);\n if (ipv4) {\n return isPrivateIpv4(ipv4);\n }\n const ipv6 = parseIpv6Literal(hostname);\n if (!ipv6) {\n return false;\n }\n // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d) literals carry\n // an IPv4 destination, so they are unwrapped and judged as IPv4.\n const low = ipv6[5] ?? 0;\n if (\n ipv6.slice(0, 5).every((piece) => piece === 0) &&\n (low === 0xffff || low === 0)\n ) {\n const mapped = ipv6[6] ?? 0;\n const trailing = ipv6[7] ?? 0;\n return isPrivateIpv4([\n mapped >> 8,\n mapped & 0xff,\n trailing >> 8,\n trailing & 0xff,\n ]);\n }\n const top = ipv6[0] ?? 0;\n return (\n (top & 0xfe00) === 0xfc00 || // fc00::/7 unique-local\n (top & 0xffc0) === 0xfe80 || // fe80::/10 link-local\n (top & 0xff00) === 0xff00 // ff00::/8 multicast\n );\n}\n\n/**\n * Normalize an address to the public base a scanning device opens:\n * query/hash stripped, the pair page's `account` path segment (and everything\n * after it) removed so a pasted pair-page URL collapses to its base, and\n * trailing slashes trimmed. Throws if the value is not a parseable URL.\n */\nexport function normalizePairingBaseUrl(value: string): string {\n const url = new URL(value);\n url.search = \"\";\n url.hash = \"\";\n const parts = url.pathname.split(\"/\").filter(Boolean);\n const cutIndex = parts.indexOf(\"account\");\n if (cutIndex >= 0) {\n parts.splice(cutIndex);\n }\n url.pathname = parts.length ? `/${parts.join(\"/\")}` : \"/\";\n return url.toString().replace(/\\/+$/, \"\");\n}\n\n/**\n * Resolve an address to the public https base URL to advertise in a pairing\n * challenge, or report why it can't be used. Loopback, private-network IP\n * literals, and non-https links are refused with a specific reason callers\n * turn into their own guidance.\n *\n * Hosts POST to this address during pairing, so the refusals are the SSRF\n * containment for every pairing surface. See\n * {@link isPrivateNetworkPublicUrl} for why resolved addresses are left alone.\n */\nexport function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {\n let normalized: string;\n try {\n normalized = normalizePairingBaseUrl(raw);\n } catch {\n return { ok: false, reason: \"unparseable\" };\n }\n if (isLoopbackPublicUrl(normalized)) {\n return { ok: false, reason: \"loopback\" };\n }\n if (isPrivateNetworkPublicUrl(normalized)) {\n return { ok: false, reason: \"private-address\" };\n }\n if (isTunnelProviderWebsiteUrl(normalized)) {\n return { ok: false, reason: \"service-website\" };\n }\n if (new URL(normalized).protocol !== \"https:\") {\n return { ok: false, reason: \"non-https\" };\n }\n return { ok: true, url: normalized };\n}\n\n/**\n * The scannable pair URL: the challenge's verification URI with the device\n * code carried in the fragment (`#device_code=…`), matching what the pair\n * page reads on load. Fragments never reach the wire.\n */\nexport function buildRemoteWebPairingUrl(\n challenge: Pick<\n RemoteWebPairingChallengeResponse,\n \"verificationUri\" | \"deviceCode\"\n >,\n): string {\n const url = new URL(challenge.verificationUri);\n url.hash = new URLSearchParams({\n device_code: challenge.deviceCode,\n }).toString();\n return url.toString();\n}\n\n/**\n * Base that makes a relative pairing link parseable. Only the query and\n * fragment are read off the result, so it never reaches a caller.\n */\nconst RELATIVE_PAIRING_LINK_BASE = \"https://pairing.invalid\";\n\n/** The device/user codes a pairing link can carry. */\nexport interface RemoteWebPairingParams {\n deviceCode: string | null;\n userCode: string | null;\n}\n\nfunction firstParam(\n params: URLSearchParams,\n ...names: string[]\n): string | null {\n for (const name of names) {\n const value = params.get(name)?.trim();\n if (value) {\n return value;\n }\n }\n return null;\n}\n\n/**\n * Query parameters merged with fragment parameters, query winning on a clash.\n * Pairing links carry the device code in the fragment so it never reaches the\n * wire, but hand-assembled links put it in the query.\n */\nfunction pairingLinkParams(url: URL): URLSearchParams {\n const merged = new URLSearchParams(url.search);\n const hash = url.hash.startsWith(\"#\") ? url.hash.slice(1) : url.hash;\n for (const [key, value] of new URLSearchParams(hash)) {\n if (!merged.has(key)) {\n merged.set(key, value);\n }\n }\n return merged;\n}\n\n/**\n * Read the pairing codes off a link, accepting either casing (`device_code` /\n * `deviceCode`) from either the query string or the fragment. Relative values\n * are accepted so a router can pass `pathname + search + hash` straight in.\n */\nexport function parseRemoteWebPairingParams(\n value: string | URL,\n): RemoteWebPairingParams {\n const url =\n typeof value === \"string\"\n ? new URL(value, RELATIVE_PAIRING_LINK_BASE)\n : value;\n const params = pairingLinkParams(url);\n return {\n deviceCode: firstParam(params, \"deviceCode\", \"device_code\"),\n userCode: firstParam(params, \"userCode\", \"user_code\"),\n };\n}\n\n/** Outcome of {@link parsePairingAddress}. */\nexport type ParsePairingAddressResult =\n | { ok: true; publicBaseUrl: string; deviceCode: string | null }\n | { ok: false; reason: PublicBaseUrlRejection };\n\n/**\n * The inverse of {@link buildRemoteWebPairingUrl}: what a pasted pairing\n * address means. A full pairing link yields its base plus the device code it\n * carries; a bare `https://host` address yields a null device code, leaving\n * the caller to mint its own challenge. The base goes through\n * {@link resolvePublicBaseUrl}, so loopback, private-network literals,\n * non-https, and tunnel-vendor websites are refused with the same reasons\n * every other pairing surface reports.\n */\nexport function parsePairingAddress(raw: string): ParsePairingAddressResult {\n const resolved = resolvePublicBaseUrl(raw);\n if (!resolved.ok) {\n return resolved;\n }\n return {\n ok: true,\n publicBaseUrl: resolved.url,\n deviceCode: parseRemoteWebPairingParams(raw).deviceCode,\n };\n}\n\n/**\n * What a pairing attempt failed on, for callers picking recovery copy\n */\nexport type PairingFailureReason =\n /** The pasted address is not a usable assistant address. */\n | \"invalid-address\"\n /** No live session for this handle: it was cancelled or never existed. */\n | \"unknown-session\"\n /** The device code expired, was denied, or was already spent. */\n | \"expired\"\n /** The assistant could not be reached. */\n | \"unreachable\"\n /**\n * The assistant refused the request with a status that left the device code\n * exchangeable, so the same session is worth another attempt.\n */\n | \"gateway-retryable\"\n /**\n * The assistant answered, but with a reply this device cannot use. The code\n * behind it is spent or unknowable, so the attempt is settled.\n */\n | \"gateway\"\n /** The credentials arrived, but registering them locally was refused. */\n | \"import\"\n /**\n * The local destination was refused BEFORE the exchange, so the one-time\n * code is untouched and the session is still pollable. Only a caller that\n * changes what it asked for (a different `name`) can get past it, so it is\n * not worth another identical attempt.\n */\n | \"import-precheck\";\n\n/**\n * Every reason, mapped to whether another attempt against the same session can\n * still succeed. Two classes leave the device code exchangeable host-side:\n *\n * - `unreachable`, the transport class (a thrown fetch, a timeout, a refused\n * redirect, a body that errored mid-stream). Nothing reached the assistant,\n * so the session and the code are untouched.\n * - `gateway-retryable`, a non-200 the assistant answered with. The gateway\n * releases the challenge before a repairable failure (a transient error, or\n * the `GUARDIAN_REPAIR_REQUIRED` 503), so the same code stays exchangeable.\n *\n * Everything else ends the attempt. `invalid-address` and `unknown-session`\n * cannot resolve by waiting; `expired` and `import` mean the one-time code is\n * already spent; `gateway` means the assistant answered with something this\n * device cannot use (an over-cap body, credentials it cannot persist, a 200\n * that is not a pairing reply), past which the code is spent rather than\n * released; and `import-precheck` refused the local destination before the\n * exchange, so an identical attempt is refused identically.\n *\n * `import-precheck` is the one of those that leaves the SESSION alive, which\n * is a separate question from whether to retry: see\n * {@link pairingSessionSurvives}.\n *\n * The `satisfies` clause keeps the map exhaustive, so a new reason does not\n * compile until it is classified here.\n */\nconst PAIRING_REASON_RETRYABLE = {\n \"invalid-address\": false,\n \"unknown-session\": false,\n expired: false,\n unreachable: true,\n \"gateway-retryable\": true,\n gateway: false,\n import: false,\n \"import-precheck\": false,\n} satisfies Record<PairingFailureReason, boolean>;\n\n/** The reasons {@link isRetryablePairingReason} accepts. */\nexport const RETRYABLE_PAIRING_REASONS: ReadonlySet<PairingFailureReason> =\n new Set(\n (Object.keys(PAIRING_REASON_RETRYABLE) as PairingFailureReason[]).filter(\n (reason) => PAIRING_REASON_RETRYABLE[reason],\n ),\n );\n\n/**\n * Whether a refused pairing step is worth another attempt. An unlabelled\n * failure reads as settled, so a host too old to name a reason ends the\n * attempt rather than being spun against until the code expires.\n */\nexport function isRetryablePairingReason(\n reason: PairingFailureReason | null | undefined,\n): boolean {\n return reason != null && RETRYABLE_PAIRING_REASONS.has(reason);\n}\n\n/**\n * Every reason, mapped to whether the pairing session it came from is still\n * live host-side. A caller holding the handle reads this to decide whether to\n * release the session: releasing a live one throws away a device code that is\n * still good and costs the user a fresh pairing link.\n *\n * This is deliberately NOT the retryable map. `import-precheck` is the reason\n * the two disagree on: nothing was spent and the same handle still polls, but\n * only once the caller changes the name it asked for, so a blind retry is\n * futile while dropping the session is destructive.\n *\n * `invalid-address` never had a session to begin with, so it reads false the\n * same way a dead one does: there is nothing to hold onto either way.\n */\nconst PAIRING_REASON_SESSION_LIVE = {\n \"invalid-address\": false,\n \"unknown-session\": false,\n expired: false,\n unreachable: true,\n \"gateway-retryable\": true,\n gateway: false,\n import: false,\n \"import-precheck\": true,\n} satisfies Record<PairingFailureReason, boolean>;\n\n/**\n * Whether the session behind a refused pairing step is still pollable. An\n * unlabelled failure reads as settled, so a host too old to name a reason has\n * its session released rather than left to time out.\n */\nexport function pairingSessionSurvives(\n reason: PairingFailureReason | null | undefined,\n): boolean {\n return reason != null && PAIRING_REASON_SESSION_LIVE[reason] === true;\n}\n"],"mappings":"+DA+DuD,EAAS,CAC9D,WAAY,GAAU,CACtB,SAAU,GAAU,CACpB,gBAAiB,GAAU,CAC3B,cAAe,GAAU,CACzB,UAAW,GAAU,CACrB,iBAAkB,GAAU,CAC5B,gBAAiB,GAAU,CAC5B,CAAC,CAcwD,EAAS,CACjE,OAAQ,EAAU,WAAW,CAC7B,gBAAiB,GAAU,CAE3B,UAAW,GAAU,CACtB,CAAC,CAgaF,SAAgB,EAAwB,EAAuB,CAC7D,IAAM,EAAM,IAAI,IAAI,EAAM,CAC1B,EAAI,OAAS,GACb,EAAI,KAAO,GACX,IAAM,EAAQ,EAAI,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CAC/C,EAAW,EAAM,QAAQ,UAAU,CAKzC,OAJI,GAAY,GACd,EAAM,OAAO,EAAS,CAExB,EAAI,SAAW,EAAM,OAAS,IAAI,EAAM,KAAK,IAAI,GAAK,IAC/C,EAAI,UAAU,CAAC,QAAQ,OAAQ,GAAG,CAwC3C,SAAgB,EACd,EAIQ,CACR,IAAM,EAAM,IAAI,IAAI,EAAU,gBAAgB,CAI9C,MAHA,GAAI,KAAO,IAAI,gBAAgB,CAC7B,YAAa,EAAU,WACxB,CAAC,CAAC,UAAU,CACN,EAAI,UAAU,CAOvB,IAAM,EAA6B,0BAQnC,SAAS,EACP,EACA,GAAG,EACY,CACf,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAQ,EAAO,IAAI,EAAK,EAAE,MAAM,CACtC,GAAI,EACF,OAAO,EAGX,OAAO,KAQT,SAAS,EAAkB,EAA2B,CACpD,IAAM,EAAS,IAAI,gBAAgB,EAAI,OAAO,CACxC,EAAO,EAAI,KAAK,WAAW,IAAI,CAAG,EAAI,KAAK,MAAM,EAAE,CAAG,EAAI,KAChE,IAAK,GAAM,CAAC,EAAK,KAAU,IAAI,gBAAgB,EAAK,CAC7C,EAAO,IAAI,EAAI,EAClB,EAAO,IAAI,EAAK,EAAM,CAG1B,OAAO,EAQT,SAAgB,EACd,EACwB,CAKxB,IAAM,EAAS,EAHb,OAAO,GAAU,SACb,IAAI,IAAI,EAAO,EAA2B,CAC1C,EAC+B,CACrC,MAAO,CACL,WAAY,EAAW,EAAQ,aAAc,cAAc,CAC3D,SAAU,EAAW,EAAQ,WAAY,YAAY,CACtD,CAuFH,IAAM,EAA2B,CAC/B,kBAAmB,GACnB,kBAAmB,GACnB,QAAS,GACT,YAAa,GACb,oBAAqB,GACrB,QAAS,GACT,OAAQ,GACR,kBAAmB,GACpB,CAGY,EACX,IAAI,IACD,OAAO,KAAK,EAAyB,CAA4B,OAC/D,GAAW,EAAyB,GACtC,CACF,CAOH,SAAgB,EACd,EACS,CACT,OAAO,GAAU,MAAQ,EAA0B,IAAI,EAAO"}
@@ -1,2 +1,2 @@
1
- import{a as e}from"./i18n-BaPIfk2c.js";import{t}from"./electron-bridge-B1sJkvH-.js";import{n,r,t as i}from"./session-token-Ev2cmr9G.js";import{l as a,n as o,p as s}from"./schemas-BZBjRX4t.js";async function c(e){if(e.set(`Content-Type`,`application/json`),!t()){await n();let t=r();t&&e.set(`X-CSRFToken`,t)}}var l=a({detail:s()});async function u(e,t,n={}){return h(e,t,n)}async function d(e,t,n,r={}){return h(e,t,r,n)}async function f(e,t,n,r={}){return h(e,t,r,n,`PATCH`)}async function p(e,t={}){return h(e,o(),t,void 0,`DELETE`)}async function m(t,n,r={}){try{let a=new Headers({Accept:`application/json`,"Accept-Language":e()}),o=i();o&&a.set(`X-Session-Token`,o),await c(a),a.delete(`Content-Type`);let s=await fetch(t,{method:`POST`,body:n,headers:a,credentials:`same-origin`,signal:r.signal}),u=await s.json().catch(()=>null);if(!s.ok){let e=l.safeParse(u);return{ok:!1,status:s.status,error:{detail:e.success?e.data.detail:`Cloud request failed (HTTP ${s.status}).`}}}return{ok:!0,status:s.status,data:null}}catch{return{ok:!1,status:0,error:{detail:`Cloud request unavailable.`}}}}async function h(t,n,r,a,o){try{let s=new Headers({Accept:`application/json`,"Accept-Language":e()}),u=i();u&&s.set(`X-Session-Token`,u),r.organizationId&&s.set(`Cadet-Organization-Id`,r.organizationId),(a!==void 0||o===`DELETE`)&&await c(s);let d=await fetch(t,{method:o??(a===void 0?`GET`:`POST`),...a===void 0?{}:{body:JSON.stringify(a)},headers:s,credentials:`same-origin`,signal:r.signal}),f=await d.json().catch(()=>null);if(!d.ok){let e=l.safeParse(f);return{ok:!1,status:d.status,error:{detail:e.success?e.data.detail:`Cloud request failed (HTTP ${d.status}).`}}}let p=n.safeParse(f);return p.success?{ok:!0,status:d.status,data:p.data}:{ok:!1,status:d.status,error:{detail:`Invalid cloud response.`}}}catch{return{ok:!1,status:0,error:{detail:`Cloud request unavailable.`}}}}export{m as a,d as i,u as n,f as r,p as t};
2
- //# sourceMappingURL=request-BpOspF-T.js.map
1
+ import{a as e}from"./i18n-DFnZ8-i_.js";import{t}from"./electron-bridge-DGEnu054.js";import{n,r,t as i}from"./session-token-CeIMyut9.js";import{l as a,n as o,p as s}from"./schemas-BYL1R3CL.js";async function c(e){if(e.set(`Content-Type`,`application/json`),!t()){await n();let t=r();t&&e.set(`X-CSRFToken`,t)}}var l=a({detail:s()});async function u(e,t,n={}){return h(e,t,n)}async function d(e,t,n,r={}){return h(e,t,r,n)}async function f(e,t,n,r={}){return h(e,t,r,n,`PATCH`)}async function p(e,t={}){return h(e,o(),t,void 0,`DELETE`)}async function m(t,n,r={}){try{let a=new Headers({Accept:`application/json`,"Accept-Language":e()}),o=i();o&&a.set(`X-Session-Token`,o),await c(a),a.delete(`Content-Type`);let s=await fetch(t,{method:`POST`,body:n,headers:a,credentials:`same-origin`,signal:r.signal}),u=await s.json().catch(()=>null);if(!s.ok){let e=l.safeParse(u);return{ok:!1,status:s.status,error:{detail:e.success?e.data.detail:`Cloud request failed (HTTP ${s.status}).`}}}return{ok:!0,status:s.status,data:null}}catch{return{ok:!1,status:0,error:{detail:`Cloud request unavailable.`}}}}async function h(t,n,r,a,o){try{let s=new Headers({Accept:`application/json`,"Accept-Language":e()}),u=i();u&&s.set(`X-Session-Token`,u),r.organizationId&&s.set(`Cadet-Organization-Id`,r.organizationId),(a!==void 0||o===`DELETE`)&&await c(s);let d=await fetch(t,{method:o??(a===void 0?`GET`:`POST`),...a===void 0?{}:{body:JSON.stringify(a)},headers:s,credentials:`same-origin`,signal:r.signal}),f=await d.json().catch(()=>null);if(!d.ok){let e=l.safeParse(f);return{ok:!1,status:d.status,error:{detail:e.success?e.data.detail:`Cloud request failed (HTTP ${d.status}).`}}}let p=n.safeParse(f);return p.success?{ok:!0,status:d.status,data:p.data}:{ok:!1,status:d.status,error:{detail:`Invalid cloud response.`}}}catch{return{ok:!1,status:0,error:{detail:`Cloud request unavailable.`}}}}export{m as a,d as i,u as n,f as r,p as t};
2
+ //# sourceMappingURL=request-B0qW_5SX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-BpOspF-T.js","names":[],"sources":["../../../src/lib/cloud/mutation-headers.ts","../../../src/lib/cloud/request.ts"],"sourcesContent":["import { ensureCsrfCookie, getCsrfToken } from \"@app/lib/auth/csrf\";\nimport { getElectronBridge } from \"@app/runtime/electron-bridge\";\n\nexport async function addCloudMutationHeaders(headers: Headers): Promise<void> {\n headers.set(\"Content-Type\", \"application/json\");\n if (!getElectronBridge()) {\n await ensureCsrfCookie();\n const csrf = getCsrfToken();\n if (csrf) {\n headers.set(\"X-CSRFToken\", csrf);\n }\n }\n}\n","import { addCloudMutationHeaders } from \"@app/lib/cloud/mutation-headers\";\nimport { z } from \"zod\";\nimport { currentLocale } from \"@app/i18n\";\nimport { getElectronSessionToken } from \"@app/runtime/session-token\";\n\nexport type CloudResult<T> =\n | { ok: true; status: number; data: T }\n | { ok: false; status: number; error: { detail: string } };\nconst ErrorSchema = z.object({ detail: z.string() });\n\n/** GET through the browser/native host's cloud proxy, independently of web clients. */\nexport async function getCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options);\n}\n\n/** POST through the browser/native host's cloud proxy. */\nexport async function postCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n body: unknown,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, body);\n}\n\n/** PATCH through the browser/native host's cloud proxy. */\nexport async function patchCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n body: unknown,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, body, \"PATCH\");\n}\n\n/** Bodyless POST (e.g. the daemon's conversation archive route). A POST with\n * no body is still a distinct method from GET — the daemon 405s a GET archive. */\nexport async function postCloudEmpty<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, undefined, \"POST\");\n}\n\n/** DELETE through the browser/native host's cloud proxy. A 204 body parses\n * as null, so the success data is always null. */\nexport async function deleteCloud(\n path: string,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<null>> {\n return requestCloud(path, z.null(), options, undefined, \"DELETE\");\n}\n\n/**\n * Multipart POST through the browser/native host's cloud proxy — the\n * same header assembly as {@link postCloud} minus the JSON serialization\n * (the body IS the form). Used by the feedback submission, whose\n * attachments and log files only travel as multipart parts.\n */\nexport async function postCloudForm(\n path: string,\n form: FormData,\n options: { signal?: AbortSignal } = {},\n): Promise<CloudResult<null>> {\n try {\n const headers = new Headers({\n Accept: \"application/json\",\n \"Accept-Language\": currentLocale(),\n });\n const token = getElectronSessionToken();\n if (token) {\n headers.set(\"X-Session-Token\", token);\n }\n await addCloudMutationHeaders(headers);\n // Leave Content-Type unset so the browser sets the multipart boundary.\n headers.delete(\"Content-Type\");\n const response = await fetch(path, {\n method: \"POST\",\n body: form,\n headers,\n credentials: \"same-origin\",\n signal: options.signal,\n });\n const payload: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const error = ErrorSchema.safeParse(payload);\n return {\n ok: false,\n status: response.status,\n error: {\n detail: error.success\n ? error.data.detail\n : `Cloud request failed (HTTP ${response.status}).`,\n },\n };\n }\n return { ok: true, status: response.status, data: null };\n } catch {\n return {\n ok: false,\n status: 0,\n error: { detail: \"Cloud request unavailable.\" },\n };\n }\n}\n\nasync function requestCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal },\n body?: unknown,\n method?: \"DELETE\" | \"POST\" | \"PATCH\",\n): Promise<CloudResult<T>> {\n try {\n const headers = new Headers({\n Accept: \"application/json\",\n \"Accept-Language\": currentLocale(),\n });\n const token = getElectronSessionToken();\n if (token) {\n headers.set(\"X-Session-Token\", token);\n }\n if (options.organizationId) {\n headers.set(\"Cadet-Organization-Id\", options.organizationId);\n }\n // A bodyless DELETE is still a mutation: the cloud's CSRF gate covers\n // every unsafe method, not just the ones that carry JSON.\n if (body !== undefined || method === \"DELETE\") {\n await addCloudMutationHeaders(headers);\n }\n const response = await fetch(path, {\n method: method ?? (body === undefined ? \"GET\" : \"POST\"),\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n headers,\n credentials: \"same-origin\",\n signal: options.signal,\n });\n const payload: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const error = ErrorSchema.safeParse(payload);\n return {\n ok: false,\n status: response.status,\n error: {\n detail: error.success\n ? error.data.detail\n : `Cloud request failed (HTTP ${response.status}).`,\n },\n };\n }\n const parsed = schema.safeParse(payload);\n return parsed.success\n ? { ok: true, status: response.status, data: parsed.data }\n : {\n ok: false,\n status: response.status,\n error: { detail: \"Invalid cloud response.\" },\n };\n } catch {\n return {\n ok: false,\n status: 0,\n error: { detail: \"Cloud request unavailable.\" },\n };\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"request-B0qW_5SX.js","names":[],"sources":["../../../src/lib/cloud/mutation-headers.ts","../../../src/lib/cloud/request.ts"],"sourcesContent":["import { ensureCsrfCookie, getCsrfToken } from \"@app/lib/auth/csrf\";\nimport { getElectronBridge } from \"@app/runtime/electron-bridge\";\n\nexport async function addCloudMutationHeaders(headers: Headers): Promise<void> {\n headers.set(\"Content-Type\", \"application/json\");\n if (!getElectronBridge()) {\n await ensureCsrfCookie();\n const csrf = getCsrfToken();\n if (csrf) {\n headers.set(\"X-CSRFToken\", csrf);\n }\n }\n}\n","import { addCloudMutationHeaders } from \"@app/lib/cloud/mutation-headers\";\nimport { z } from \"zod\";\nimport { currentLocale } from \"@app/i18n\";\nimport { getElectronSessionToken } from \"@app/runtime/session-token\";\n\nexport type CloudResult<T> =\n | { ok: true; status: number; data: T }\n | { ok: false; status: number; error: { detail: string } };\nconst ErrorSchema = z.object({ detail: z.string() });\n\n/** GET through the browser/native host's cloud proxy, independently of web clients. */\nexport async function getCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options);\n}\n\n/** POST through the browser/native host's cloud proxy. */\nexport async function postCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n body: unknown,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, body);\n}\n\n/** PATCH through the browser/native host's cloud proxy. */\nexport async function patchCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n body: unknown,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, body, \"PATCH\");\n}\n\n/** Bodyless POST (e.g. the daemon's conversation archive route). A POST with\n * no body is still a distinct method from GET — the daemon 405s a GET archive. */\nexport async function postCloudEmpty<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<T>> {\n return requestCloud(path, schema, options, undefined, \"POST\");\n}\n\n/** DELETE through the browser/native host's cloud proxy. A 204 body parses\n * as null, so the success data is always null. */\nexport async function deleteCloud(\n path: string,\n options: { organizationId?: string; signal?: AbortSignal } = {},\n): Promise<CloudResult<null>> {\n return requestCloud(path, z.null(), options, undefined, \"DELETE\");\n}\n\n/**\n * Multipart POST through the browser/native host's cloud proxy — the\n * same header assembly as {@link postCloud} minus the JSON serialization\n * (the body IS the form). Used by the feedback submission, whose\n * attachments and log files only travel as multipart parts.\n */\nexport async function postCloudForm(\n path: string,\n form: FormData,\n options: { signal?: AbortSignal } = {},\n): Promise<CloudResult<null>> {\n try {\n const headers = new Headers({\n Accept: \"application/json\",\n \"Accept-Language\": currentLocale(),\n });\n const token = getElectronSessionToken();\n if (token) {\n headers.set(\"X-Session-Token\", token);\n }\n await addCloudMutationHeaders(headers);\n // Leave Content-Type unset so the browser sets the multipart boundary.\n headers.delete(\"Content-Type\");\n const response = await fetch(path, {\n method: \"POST\",\n body: form,\n headers,\n credentials: \"same-origin\",\n signal: options.signal,\n });\n const payload: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const error = ErrorSchema.safeParse(payload);\n return {\n ok: false,\n status: response.status,\n error: {\n detail: error.success\n ? error.data.detail\n : `Cloud request failed (HTTP ${response.status}).`,\n },\n };\n }\n return { ok: true, status: response.status, data: null };\n } catch {\n return {\n ok: false,\n status: 0,\n error: { detail: \"Cloud request unavailable.\" },\n };\n }\n}\n\nasync function requestCloud<T>(\n path: string,\n schema: z.ZodType<T>,\n options: { organizationId?: string; signal?: AbortSignal },\n body?: unknown,\n method?: \"DELETE\" | \"POST\" | \"PATCH\",\n): Promise<CloudResult<T>> {\n try {\n const headers = new Headers({\n Accept: \"application/json\",\n \"Accept-Language\": currentLocale(),\n });\n const token = getElectronSessionToken();\n if (token) {\n headers.set(\"X-Session-Token\", token);\n }\n if (options.organizationId) {\n headers.set(\"Cadet-Organization-Id\", options.organizationId);\n }\n // A bodyless DELETE is still a mutation: the cloud's CSRF gate covers\n // every unsafe method, not just the ones that carry JSON.\n if (body !== undefined || method === \"DELETE\") {\n await addCloudMutationHeaders(headers);\n }\n const response = await fetch(path, {\n method: method ?? (body === undefined ? \"GET\" : \"POST\"),\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n headers,\n credentials: \"same-origin\",\n signal: options.signal,\n });\n const payload: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const error = ErrorSchema.safeParse(payload);\n return {\n ok: false,\n status: response.status,\n error: {\n detail: error.success\n ? error.data.detail\n : `Cloud request failed (HTTP ${response.status}).`,\n },\n };\n }\n const parsed = schema.safeParse(payload);\n return parsed.success\n ? { ok: true, status: response.status, data: parsed.data }\n : {\n ok: false,\n status: response.status,\n error: { detail: \"Invalid cloud response.\" },\n };\n } catch {\n return {\n ok: false,\n status: 0,\n error: { detail: \"Cloud request unavailable.\" },\n };\n }\n}\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-BNv3lrIs.js";import{a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./schemas-BYL1R3CL.js";var _=7840;function v(e){return{daemon:e,gateway:e+100,qdrant:e+200,ces:e+300,outboundProxy:e+400,tcp:e+500}}v(17e3),v(19e3),v(18e3),`${_}`,v(2e4);var y=[`cadet`,`ngrok`,`cloudflare`,`tailscale`];e(((e,t)=>{t.exports={}}))();var b=h([`local`,`docker`,`apple-container`,`cloud`,`custom`,`baseten`]),x={}.GATEWAY_PORT?Number({}.GATEWAY_PORT):7830,S=c({assistantImage:f(),gatewayImage:f(),cesImage:f()}),C=i({memory:i({high:n().int().positive().optional(),max:n().int().positive().optional()}).superRefine((e,t)=>{e.high!==void 0&&e.max!==void 0&&e.high>e.max&&t.addIssue({code:`custom`,path:[`high`],message:`memory.high (${e.high}) must not exceed memory.max (${e.max})`})}).optional()}),w=c({assistantId:f(),cloudAssistantId:f().optional(),cloudOrganizationId:f().optional(),allowAdminAccess:s().optional(),name:f().optional(),hatchedAt:f().optional(),onboardedAt:f().optional(),watcherPid:n().optional(),machine:C.optional().catch(void 0)}),T={port:n(),daemonPort:n().optional(),cesPort:n().optional()},E=w.extend({...T,instanceDir:f().optional(),cloud:d(`local`)}),D=w.extend({...T,cloud:d(`docker`),containerInfo:S.optional()}),O=w.extend({...T,cloud:d(`apple-container`),mgmtSocket:f()}),k=w.extend({cloud:d(`cloud`)}),A=w.extend({cloud:d(`custom`),ipAddress:f(),port:n()}),j=w.extend({cloud:d(`baseten`),sandboxUrl:f(),port:n(),previewUrl:f().optional()});function M(e){if(typeof e!=`object`||!e)return e;let t=e,n=t.cloud;if(typeof n==`string`&&b.safeParse(n).success||(t={...t,cloud:`local`}),t.port===void 0){let e=t.resources,n=e&&typeof e==`object`?e.gatewayPort:void 0;t={...t,port:typeof n==`number`?n:x}}return t}var N=g(M,t(`cloud`,[E,D,O,k,A,j])),P=c({pid:n(),provider:h(y),startedAt:f(),publicUrl:f().optional()}),F=c({pid:n().optional(),startedAt:f().optional(),port:n()});m({assistants:p(N.nullable().catch(null)).catch([]).transform(e=>e.filter(e=>e!==null)),activeAssistant:l([f(),u()]).catch(null),tunnel:P.optional().catch(void 0),app:F.optional().catch(void 0)});function I(e){if(/[\\\u0000-\u0020]/.test(e)||e.startsWith(`//`)||!e.startsWith(`/`)&&!/^https?:\/\//i.test(e)&&e.includes(`:`)||/(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i.test(e))return!1;try{let t=new URL(e,`https://app.example`);return t.username||t.password||t.search||t.hash?!1:e.startsWith(`/`)||t.protocol===`https:`||t.protocol===`http:`&&[`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname)}catch{return!1}}var L=f().min(1).refine(I,`Expected a public host URL without credentials or query parameters.`),R=c({id:f().min(1),version:f().min(1)}),z=c({id:f().min(1),name:f().nullish().transform(e=>e?.trim()||`New Assistant`),avatar_url:f().nullish(),created:f().nullish(),remote:b.nullish().catch(()=>void 0),allow_admin_access:s().nullish().catch(()=>void 0)}),B=t(`status`,[c({status:d(`ready`),assistant:R}),c({status:d(`notReady`)}),c({status:d(`unavailable`)}),c({status:d(`selection`)}),c({status:d(`empty`)}),c({status:d(`unauthenticated`)})]),V=t(`status`,[c({status:d(`selection`),assistants:p(z)}),c({status:d(`empty`)}),c({status:d(`unauthenticated`)})]),H=c({source:d(`mycadet-web-nav`),nav:h([`push`,`replace`,`pop`]),path:f()}),U=c({source:d(`mycadet-web-host-nav`),path:f()}),W=c({source:d(`mycadet-web-share-feedback`)}),G=c({source:d(`mycadet-web-host-proxy-forward`),message:r(f(),o())});function K(e,t){let n=e.safeParse(t);if(!n.success)throw Error(`Invalid assistant API data.\n${a(n.error)}`);return n.data}var q=Symbol(`unauthenticated`),J=Symbol(`not ready`),Y=Symbol(`unavailable`);function X({apiBaseUrl:e=`/`,signal:t}){let n=window.location.origin,r=new URL(K(L,e),n);r.pathname=r.pathname.replace(/\/*$/,`/`);let i=new Headers({Accept:`application/json`});async function a(e){t.throwIfAborted();let n=new URL(e,r),a=await fetch(n,{headers:i,signal:t,credentials:`include`});if(t.throwIfAborted(),a.status===401)return q;if(a.status===409)return J;if(a.status===410)return Y;if(!a.ok)throw console.error(`Assistant request failed: ${a.status} ${a.headers.get(`content-type`)??``} from ${n.href}`),Error(`Assistant request failed: ${a.status} from ${n.href}`);let o=await a.json().catch(e=>{throw console.error(`Assistant response was not JSON from ${n.href}: ${e}`),e});return t.throwIfAborted(),o}return{base:r,get:a}}async function Z(e){let t=await X(e).get(`v1/assistants/`);return t===q?{status:`unauthenticated`}:K(V,t)}async function Q(e){let t=await X(e).get(e.assistantId?`v1/assistants/${encodeURIComponent(e.assistantId)}/`:`v1/assistant`);return t===q?{status:`unauthenticated`}:t===J?{status:`notReady`}:t===Y?{status:`unavailable`}:K(B,t)}export{U as a,b as c,B as i,Q as n,G as o,H as r,W as s,Z as t};
2
+ //# sourceMappingURL=resolve-assistant-CFtChAyl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-assistant-D3wYg0xs.js","names":[],"sources":["../../../../../packages/shared/github-repository.ts","../../../../../packages/shared/seeds.ts","../../../../../packages/service-contracts/src/ingress.ts","../../../__vite-browser-external","../../../../../packages/local-mode/src/paths.ts","../../../../../packages/local-mode/src/lockfile-contract.ts","../../../src/assistant/resolution-contract.ts","../../../src/assistant/resolve-assistant.ts"],"sourcesContent":["/** The GitHub repository Cadet's source and releases live in. */\nexport const CADET_GITHUB_REPOSITORY = \"vargasjr-dev/mycadet-temp\";\n\n/** URL of the public GitHub repository. */\nexport const CADET_GITHUB_REPOSITORY_URL = `https://github.com/${CADET_GITHUB_REPOSITORY}`;\n","// Loaded standalone by Capacitor's single-file TS config loader (via the\n// `./seeds` subpath) — keep imports type-only (this file has none) and keep\n// this file free of the import-meta meta-property: the loader transpiles this\n// file to CJS, where that syntax is illegal and makes Node misroute the\n// result as ESM. Browser bundles (chrome extension, web renderer) import it\n// for the same reason.\n\n/**\n * Per-service default port set. Phase 5 (per-environment port offsets) is\n * deferred from MVP, so today every environment uses the same port set. The\n * shape exists so the rest of the stack can call `getDefaultPorts(env)` and\n * gain per-env offsets later without changing any call sites.\n */\nexport interface PortMap {\n daemon: number;\n gateway: number;\n qdrant: number;\n ces: number;\n outboundProxy: number;\n tcp: number;\n}\n\n/**\n * The port the local app server binds by default — the single origin every\n * local surface (webview, assistant daemon, CLI) dials. The local seed's\n * base URL reuses it so no surface carries its own port constant.\n */\nexport const DEFAULT_APP_SERVER_PORT = 7840;\n\n/**\n * A resolved environment definition. Required fields are `name` and\n * `baseUrl`. All other fields are optional and declared upfront — new\n * fields are additive, never breaking. `name` is a `CadetEnvironment`: a\n * definition outside the known names has nowhere to key into.\n */\nexport interface EnvironmentDefinition {\n name: CadetEnvironment;\n\n /**\n * The single origin for API, auth, web, and the assistant mount — one\n * deployment serves all of it, so one URL describes it. The local seed\n * points at the app server's default port; the cloud seeds point at the\n * environment's host.\n */\n baseUrl: string;\n\n /** Human-readable label for UI surfaces. */\n displayName?: string;\n\n /** Hint for UI surfaces that want to tint or badge their display. */\n tintColor?: string;\n\n /** Per-service port overrides merged on top of defaults. */\n portsOverride?: Partial<PortMap>;\n\n /** Override for the XDG config directory. */\n configDirOverride?: string;\n\n /**\n * Override for the directory containing the lockfile. In-memory only —\n * tests inject curated env lists with it; path helpers never read env\n * vars to populate it.\n */\n lockfileDirOverride?: string;\n}\n\n/**\n * Non-prod port blocks. Each environment gets a 1000-port window in the\n * 17000–21000 band. Within a block, services are spaced 100 apart so up to\n * 100 assistants can coexist without the scan (`findAvailablePort`) running\n * one service's range into the next. Band chosen to sit below Linux's\n * default ephemeral start (32768) and macOS's (49152), and away from the\n * 3000/5000/8000/9000 dev-tool swamp. Production keeps its legacy,\n * non-contiguous port set (7821/7830/6333/8090/8080/8765): cross-env\n * collision is the only problem this change targets, prod is unaffected\n * because only one env's assistants compete on a given machine, and\n * churning it would leave existing hatches on 7821 while new ones\n * allocated elsewhere.\n */\nfunction portBlock(base: number): PortMap {\n return {\n daemon: base,\n gateway: base + 100,\n qdrant: base + 200,\n ces: base + 300,\n outboundProxy: base + 400,\n tcp: base + 500,\n };\n}\n\n/**\n * The set of environment names every surface shares — the seeds below are\n * exactly these five. Lockfiles, config directories, release channels, and\n * the mobile shells' scheme keys all key off this union, so a name outside\n * it is a bug the compiler can catch.\n */\nexport const CADET_ENVIRONMENT_NAMES = [\n \"local\",\n \"dev\",\n \"staging\",\n \"production\",\n \"test\",\n] as const;\n\nexport type CadetEnvironment = (typeof CADET_ENVIRONMENT_NAMES)[number];\n\nfunction isCadetEnvironment(\n name: string | undefined,\n): name is CadetEnvironment {\n return (\n typeof name === \"string\" &&\n (CADET_ENVIRONMENT_NAMES as readonly string[]).includes(name)\n );\n}\n\n/**\n * globalThis.process reads the same env under bun/node while staying\n * crash-free in browser bundles (no bare `process` reference) — and free\n * of import-meta syntax, which the Capacitor config loader can't transpile.\n */\nfunction processEnv(): Record<string, string | undefined> | undefined {\n return (\n globalThis as unknown as {\n process?: { env?: Record<string, string | undefined> };\n }\n ).process?.env;\n}\n\n/**\n * Whether a version string denotes a dev build from the dev-release\n * pipeline, e.g. `0.12.6-dev.202610081023.3a27b77`.\n */\nexport function isDevVersion(version: string): boolean {\n return /-dev\\./i.test(version);\n}\n\n/**\n * Whether a version string denotes a staging build, e.g. `0.6.0-staging.3`.\n */\nexport function isStagingVersion(version: string): boolean {\n return /-staging\\./i.test(version);\n}\n\n/**\n * Whether a version string denotes a local build, e.g. `0.12.6-local.42`.\n * Local builds are never published.\n */\nexport function isLocalVersion(version: string): boolean {\n return /-local\\./i.test(version);\n}\n\n/**\n * The environment a released channel version pins, or `undefined` when the\n * version carries no channel suffix. A plain version — a workspace\n * checkout's unstamped package version — reads as \"no version signal\",\n * leaving the remaining steps to decide. Mirrors the CLI resolver's mapping\n * (local, dev, staging).\n */\nexport function environmentFromVersion(\n version: string | undefined,\n): CadetEnvironment | undefined {\n if (isLocalVersion(version ?? \"\")) return \"local\";\n if (isDevVersion(version ?? \"\")) return \"dev\";\n if (isStagingVersion(version ?? \"\")) return \"staging\";\n return undefined;\n}\n\n/**\n * Read the persisted default environment — the file pre-version-tied CLIs\n * wrote so their successors honor the machine's chosen default. Node-only\n * and resolved at call time (`process.getBuiltinModule`), so this file\n * keeps zero static node imports: the Capacitor config loader transpiles it\n * standalone and a static node import would die there, while browser\n * bundles (chrome extension, web renderer) never reach the call.\n */\nfunction readPersistedDefault(): CadetEnvironment | undefined {\n const node = process as unknown as {\n getBuiltinModule?: (id: string) => unknown;\n platform: string;\n };\n const fs = node.getBuiltinModule?.(\"node:fs\") as\n | typeof import(\"node:fs\")\n | undefined;\n const os = node.getBuiltinModule?.(\"node:os\") as\n | typeof import(\"node:os\")\n | undefined;\n const path = node.getBuiltinModule?.(\"node:path\") as\n | typeof import(\"node:path\")\n | undefined;\n if (!fs || !os || !path) return undefined;\n\n // Mirrors local-mode's resolveConfigHome (the same XDG/AppData derivation).\n const isWindows = node.platform === \"win32\";\n const join = isWindows ? path.win32.join : path.posix.join;\n const configHome = isWindows\n ? process.env.APPDATA?.trim() || join(os.homedir(), \"AppData\", \"Roaming\")\n : process.env.XDG_CONFIG_HOME?.trim() || join(os.homedir(), \".config\");\n const filePath = join(configHome, \"cadet\", \"environment\");\n try {\n if (!fs.existsSync(filePath)) return undefined;\n const content = fs.readFileSync(filePath, \"utf-8\").trim();\n return isCadetEnvironment(content) ? content : undefined;\n } catch {\n // Unreadable file — no default.\n return undefined;\n }\n}\n\n/**\n * The environment name every surface shares: `CADET_ENVIRONMENT`, then\n * `VITE_ENVIRONMENT`, then the release channel the copy's version carries\n * (`__CADET_OWN_VERSION__`, defined at build time by hosts that bundle\n * local-mode), then the persisted default written by pre-version-tied CLIs,\n * then production.\n */\nexport function resolveEnvironmentName(): CadetEnvironment {\n const env = processEnv();\n const named = [\n env?.CADET_ENVIRONMENT?.trim(),\n env?.VITE_ENVIRONMENT?.trim(),\n ].find(isCadetEnvironment);\n if (named) return named;\n return (\n environmentFromVersion(\n (globalThis as { __CADET_OWN_VERSION__?: string }).__CADET_OWN_VERSION__,\n ) ??\n readPersistedDefault() ??\n \"production\"\n );\n}\n\n/**\n * The base URL of Cadet Cloud — the hosted deployment the local surfaces\n * pair with (API, auth, web, and the assistant mount all live on it). The\n * explicit `CADET_CLOUD_URL` override wins, else the seed of\n * `resolveEnvironmentName`. This says \"cloud\" because the URL always points\n * at a Cadet Cloud deployment, never at something that represents this\n * surface itself.\n */\nexport function getCloudBaseUrl(): string {\n const explicit = processEnv()?.CADET_CLOUD_URL?.trim();\n if (explicit) return explicit;\n return SEEDS[resolveEnvironmentName()].baseUrl;\n}\n\n/**\n * Built-in environment definitions and the source of truth for the\n * set of known environment names.\n *\n * Custom environments via a user config file are a future phase — see the\n * \"Coexisting environments\" design doc. Until then, a call site that needs a\n * new environment must add it here and rebuild.\n */\nexport const SEEDS: Record<CadetEnvironment, EnvironmentDefinition> = {\n production: {\n name: \"production\",\n baseUrl: \"https://mycadet.ai\",\n },\n staging: {\n name: \"staging\",\n baseUrl: \"https://staging.mycadet.ai\",\n portsOverride: portBlock(17000),\n },\n test: {\n name: \"test\",\n baseUrl: \"https://test.mycadet.ai\",\n portsOverride: portBlock(19000),\n },\n dev: {\n name: \"dev\",\n baseUrl: \"https://dev.mycadet.ai\",\n portsOverride: portBlock(18000),\n },\n local: {\n name: \"local\",\n baseUrl: `http://localhost:${DEFAULT_APP_SERVER_PORT}`,\n // assistantBaseUrl: \"http://host.docker.internal:7840\",\n // ^ uncomment once dockerized hatch path is live — the assistant runs\n // in a different network namespace than the host.\n portsOverride: portBlock(20000),\n },\n};\n","/**\n * Map a Cadet Cloud host onto its environment's tunnel host, following the\n * deployment naming convention (`cloud.mycadet.ai` → `tunnel.mycadet.ai`,\n * `{env}-cloud.mycadet.ai` → `{env}-tunnel.mycadet.ai`). Returns null for\n * hosts outside that convention (localhost, custom domains). Shared by the\n * gateway speech relay (which passes the request's own host) and the web\n * live-voice client (which defaults to the page's origin) so the two ends\n * of the cloud-speech transport can't drift.\n */\nexport function tunnelHostForCloudHost(\n host: string = (globalThis as { location?: { hostname?: string } }).location\n ?.hostname ?? \"\",\n): string | null {\n if (host === \"cloud.mycadet.ai\") {\n return \"tunnel.mycadet.ai\";\n }\n const match = /^([a-z0-9-]+)-cloud\\.mycadet\\.ai$/.exec(host);\n return match ? `${match[1]}-tunnel.mycadet.ai` : null;\n}\n\nexport function normalizePublicBaseUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim().replace(/\\/+$/, \"\");\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Application close code the gateway's tunnel bridge sends to proxied\n * WebSockets when the tunnel itself is lost (tunnel disconnect, gateway\n * shutdown). A dedicated code because the natural 1001 (going away) cannot\n * be sent through the JS `close()` API (the bridge would remap it to a\n * misleading 4001), and Bun's WebSocket client drops close reasons, so the\n * code is the only signal that survives the relay to the daemon.\n */\nexport const GATEWAY_TUNNEL_LOST_WS_CLOSE_CODE = 4801;\n\nexport function normalizeHttpPublicBaseUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n if (/[?#]/.test(trimmed)) return undefined;\n\n try {\n const url = new URL(trimmed);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return undefined;\n }\n if (!url.hostname) return undefined;\n url.pathname = url.pathname.replace(/\\/+$/, \"\") || \"/\";\n return url.toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The same validation as `normalizeHttpPublicBaseUrl`, minus the root path it\n * always emits (`https://x` becomes `https://x/`). Callers that append a path\n * or persist the result want this shape, so they neither join through a double\n * slash nor re-strip what the normalizer just added.\n */\nexport function normalizeHttpPublicBaseUrlWithoutTrailingSlash(\n value: unknown,\n): string | undefined {\n return normalizePublicBaseUrl(normalizeHttpPublicBaseUrl(value));\n}\n\n/**\n * A trimmed string, or undefined when the value is not a non-blank string.\n *\n * Exported because the identity check in the daemon's tunnel probe compares an\n * id recorded here against one an edge serves, and the two sides have to trim\n * alike: a padded served id must read as a match, not as a different\n * assistant.\n */\nexport function trimmedNonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n// Records `cadet tunnel` leaves in the workspace config's `ingress` section.\n// The CLI writes them and the daemon reads them, and the two are separate\n// build units that cannot import each other, so the key names, the provider\n// allowlist, and the validation all live here rather than in a copy on each\n// side.\n\n/** Key under `ingress` holding the tunnel that most recently ran. */\nexport const INGRESS_LAST_TUNNEL_KEY = \"lastTunnel\";\n\n/**\n * Key under `ingress` holding a tunnel published for device pairing alone.\n *\n * A tailnet-only tunnel started while webhook integrations are configured\n * cannot carry their callbacks, so it leaves `publicBaseUrl` (the callback\n * base) as it is and records itself here. Readers that answer the pairing card\n * prefer this address over `publicBaseUrl`; teardown drops the key.\n */\nexport const INGRESS_PAIRING_TUNNEL_KEY = \"pairingTunnel\";\n\n/** Key under `ingress` holding the assistant id that tunnel fronted. */\nexport const INGRESS_ASSISTANT_ID_KEY = \"assistantId\";\n\n/**\n * The tunnel providers the CLI offers, in the order they are presented —\n * the managed `cadet` tunnel first (listed, not yet implemented), then the\n * local ones. `cadet tunnel`'s accepted `--provider` values and the\n * persisted-record validation below both derive from it.\n */\nexport const TUNNEL_PROVIDERS = [\n \"cadet\",\n \"ngrok\",\n \"cloudflare\",\n \"tailscale\",\n] as const;\n\nexport type TunnelProviderName = (typeof TUNNEL_PROVIDERS)[number];\n\n/** A recorded tunnel, kept after teardown so UIs can name the command to restart. */\nexport interface TunnelRecord {\n provider: TunnelProviderName;\n publicBaseUrl: string;\n}\n\nfunction isTunnelProviderName(value: unknown): value is TunnelProviderName {\n return (\n typeof value === \"string\" &&\n (TUNNEL_PROVIDERS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Parse an `ingress.lastTunnel` or `ingress.pairingTunnel` value, or null when\n * it is absent or malformed.\n *\n * A hand-edited config must not hand callers an unusable address or a provider\n * name no command accepts: the provider is checked against the allowlist\n * because readers render it into a restart command, and the URL faces the same\n * absolute HTTP(S) constraint as every other public base URL. The URL comes\n * back in the shape the validator produced, so readers never re-normalize it.\n */\nexport function parseTunnelRecord(value: unknown): TunnelRecord | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const { provider, publicBaseUrl } = value as Record<string, unknown>;\n if (!isTunnelProviderName(provider)) {\n return null;\n }\n const normalized =\n normalizeHttpPublicBaseUrlWithoutTrailingSlash(publicBaseUrl);\n if (normalized === undefined) {\n return null;\n }\n return { provider, publicBaseUrl: normalized };\n}\n\n/**\n * The tunnel a reader should offer to restart, given an `ingress` section, or\n * null when it records none.\n *\n * A pairing-only record wins: it is written by a tunnel that deliberately left\n * `publicBaseUrl` (and the `lastTunnel` beside it) pointing at an older public\n * provider, so naming that older one would send the user to rebuild an ingress\n * they are not using instead of the tunnel actually in front of them.\n */\nexport function selectRestartTunnelRecord(\n ingress: unknown,\n): TunnelRecord | null {\n if (typeof ingress !== \"object\" || ingress === null) {\n return null;\n }\n const section = ingress as Record<string, unknown>;\n return (\n parseTunnelRecord(section[INGRESS_PAIRING_TUNNEL_KEY]) ??\n parseTunnelRecord(section[INGRESS_LAST_TUNNEL_KEY])\n );\n}\n\n/** Parse an `ingress.assistantId` value, or null when it is absent or blank. */\nexport function parseRecordedAssistantId(value: unknown): string | null {\n return trimmedNonEmptyString(value) ?? null;\n}\n","module.exports = {}","import { homedir } from \"node:os\";\nimport path from \"node:path\";\n\nconst PRODUCTION_ENVIRONMENT_NAME = \"production\";\n\nconst isWindows = () => process.platform === \"win32\";\nconst paths = () => (isWindows() ? path.win32 : path.posix);\n\nexport function resolveConfigHome(): string {\n if (isWindows()) {\n return (\n process.env.APPDATA?.trim() ||\n paths().join(homedir(), \"AppData\", \"Roaming\")\n );\n }\n return process.env.XDG_CONFIG_HOME?.trim() || paths().join(homedir(), \".config\");\n}\n\nexport function resolveDataHome(): string {\n if (isWindows()) {\n return (\n process.env.LOCALAPPDATA?.trim() ||\n paths().join(homedir(), \"AppData\", \"Local\")\n );\n }\n return process.env.XDG_DATA_HOME?.trim() || paths().join(homedir(), \".local\", \"share\");\n}\n\nexport const joinLocalPath = (...segments: string[]) => paths().join(...segments);\n\nexport function assertSafePathSegment(value: string, label: string): void {\n const unsafe =\n !value ||\n /[/\\\\\\0]/.test(value) ||\n /^\\.{1,2}$/.test(value) ||\n (isWindows() &&\n (/[<>:\"|?*\\u0000-\\u001f]/.test(value) ||\n /[. ]$/.test(value) ||\n /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(value)));\n if (unsafe) {\n throw new Error(`Invalid ${label}: ${value}`);\n }\n}\n\n/**\n * The directory name an environment's state lives under: `cadet` for\n * production (the legacy location other environments must not collide with),\n * `cadet-<env>` otherwise. Exported so hosts that enumerate a SPECIFIC\n * environment's directories — the CLI's cross-environment detection — can\n * compose them from {@link resolveConfigHomes} and {@link resolveDataHome}\n * without an options bag threading through the ambient resolvers.\n */\nexport function environmentDirectoryName(cadetEnv: string): string {\n assertSafePathSegment(cadetEnv, \"environment name\");\n return cadetEnv === PRODUCTION_ENVIRONMENT_NAME\n ? \"cadet\"\n : `cadet-${cadetEnv}`;\n}\n","/**\n * The lockfile wire contract — one Zod schema that is the single source of truth\n * for an assistant entry's shape, its validation, the `cloud` taxonomy, the\n * normalization, and the redaction policy.\n *\n * Kept in its own module, exported from the package as `./contract`, so\n * consumers import the contract without pulling in the host I/O graph\n * (`node:fs`, the CLI resolver). The CLI, the host I/O layer, the Electron and\n * dev-server bridges, and the renderer all depend on this one definition. It\n * references no node built-ins — the renderer bundles it directly — and `zod`\n * is its only third-party import.\n *\n * The lockfile is written by the Cadet CLI and read across the macOS↔CLI\n * boundary, which do not release in lockstep, so the parser is permissive at\n * the file level: it validates each entry whole through the schema (a\n * malformed field drops that entry, never the file), accepts — but drops from\n * the validated value — entry fields this build has never heard of, and\n * defaults `cloud` when it is absent or unknown. The schema is strict over\n * the fields it models: every field a reader needs is IN the schema, so a\n * CLI read-modify-write round-trip preserves it by construction. The\n * local-mode write path still merges raw JSON (unknown root fields survive\n * on disk; see `lockfile.ts`); the validated value carries only the modeled\n * shape.\n */\nimport { getCloudBaseUrl } from \"@mycadet/shared\";\nimport { TUNNEL_PROVIDERS } from \"@mycadet/service-contracts/ingress\";\nimport { z } from \"zod\";\n\nimport { readLockfile } from \"./lockfile\";\n\n/**\n * Known deployment topologies of a Cadet:\n * - `local` — on-machine bare-metal processes\n * - `docker` — docker-managed container\n * - `apple-container` — macOS-app-managed container\n * - `cloud` — managed by Cadet Cloud\n * - `custom` — remote VM accessible via SSH\n */\nexport const KNOWN_REMOTES = [\n \"local\",\n \"docker\",\n \"apple-container\",\n \"cloud\",\n \"custom\",\n \"baseten\",\n] as const;\n\n/**\n * The topology values as one zod enum, shared by the lockfile schema (which\n * wraps it in a `catch`) and the clients' injected-config schema, so the two\n * can never drift.\n */\nexport const RemoteSchema = z.enum(KNOWN_REMOTES);\nexport type Remote = z.infer<typeof RemoteSchema>;\n\n/**\n * Keys that must never cross the host→renderer boundary. Stripped from raw\n * lockfile JSON before it leaves a host (see `stripSensitiveFields`) and absent\n * from the renderer-facing schema below; the CLI's extended type is the only\n * place they are modeled.\n */\nexport const SENSITIVE_KEYS = [\n \"bearerToken\",\n \"guardianBootstrapSecret\",\n] as const;\n\n/**\n * Strip every `SENSITIVE_KEYS` field from a parsed lockfile, in place: from\n * each assistant entry and from that entry's `resources`. The one redaction\n * every host runs before lockfile data crosses to the renderer — pure, no\n * node built-ins, so it lives beside the keys it enforces and bundles into\n * the renderer through the `./contract` subpath.\n */\nexport function stripSensitiveFields(data: Record<string, unknown>): void {\n const assistants = data.assistants;\n if (!Array.isArray(assistants)) return;\n for (const assistant of assistants) {\n if (assistant && typeof assistant === \"object\") {\n const entry = assistant as Record<string, unknown>;\n for (const field of SENSITIVE_KEYS) {\n delete entry[field];\n }\n const resources = entry.resources;\n if (resources && typeof resources === \"object\") {\n for (const field of SENSITIVE_KEYS) {\n delete (resources as Record<string, unknown>)[field];\n }\n }\n }\n }\n}\n\n/**\n * Whether an entry's `runtimeUrl` is one a serving host can forward to: an\n * absolute http(s) URL. Shared by the renderer's paired-gateway URL derivation\n * and the host-side paired allowlist reader so the two can't drift.\n */\nexport function isUsableBaseUrl(url: unknown): url is string {\n if (typeof url !== \"string\" || url === \"\") {\n return false;\n }\n try {\n const parsed = new URL(url);\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n/**\n * The local build's control-plane base, read from the lockfile alone: the\n * auto-tunnel's recorded `publicUrl` when one is up, else the app server\n * edge's loopback port. A loopback base is reachable from the iOS simulator\n * only — a device's `127.0.0.1` is the phone itself — so a device build\n * wants a tunnel up before it stamps. `undefined` when neither record\n * carries a usable address.\n *\n * The assistants play no role in this resolution — the capacitor app shell\n * only deals with the app server — and the CLI's workspace config is never\n * touched: the lockfile is the single home for edge state.\n */\nexport function resolveLocalServerUrl(): string | undefined {\n const lockfile = readLockfile();\n const tunnelUrl = lockfile.tunnel?.publicUrl;\n if (isUsableBaseUrl(tunnelUrl)) {\n return tunnelUrl;\n }\n const port = lockfile.app?.port;\n if (typeof port === \"number\") {\n return `http://127.0.0.1:${port}`;\n }\n return undefined;\n}\n\n/**\n * Clouds whose gateway listens on a loopback port of this machine: the\n * on-machine daemon (\"local\") and local Docker instances (\"docker\").\n */\nexport const LOOPBACK_GATEWAY_CLOUDS: readonly Remote[] = [\"local\", \"docker\"];\n\nexport function isLoopbackGatewayCloud(cloud: Remote): boolean {\n return LOOPBACK_GATEWAY_CLOUDS.includes(cloud);\n}\n\n/**\n * The gateway port a freshly hatched assistant's gateway listens on, with\n * the `GATEWAY_PORT` env override the CLI tooling honors.\n */\nexport const GATEWAY_PORT = process.env.GATEWAY_PORT\n ? Number(process.env.GATEWAY_PORT)\n : 7830;\n\n/**\n * The URL to dial an entry's gateway on, derived from the entry's canonical\n * fields — the one seam every consumer addresses a gateway through, and the\n * one place a trailing slash is stripped: the returned URL is always\n * slash-free, so callers join paths directly:\n *\n * - `custom` remotes: their recorded host and port.\n * - cloud-managed: the environment's base url (`getCloudBaseUrl()`).\n * - loopback topologies (`local`, `docker`, `apple-container`): the\n * recorded loopback gateway port, else the default gateway port.\n */\nexport function getGatewayUrl(entry: LockfileAssistant): string {\n // Baseten: the private preview is the door when one was minted — the\n // preview edge opens the port dynamically and guards it with a preview\n // token, so `Authorization` stays free for the gateway's own bearer.\n // Without one, the sandbox API's `/port/<PORT>/` route (the sandbox\n // access token authenticates it).\n if (entry.cloud === \"baseten\") {\n if (entry.previewUrl) {\n return entry.previewUrl.replace(/\\/+$/, \"\");\n }\n return `${entry.sandboxUrl.replace(/\\/+$/, \"\")}/port/${entry.port}`;\n }\n if (entry.cloud === \"custom\") {\n // Custom remotes speak TLS. Default ports elided the way a URL prints\n // them. The schema requires the address and port.\n const elided = entry.port === 443;\n return `https://${entry.ipAddress}${elided ? \"\" : `:${entry.port}`}`;\n }\n if (isCloudEntry(entry)) {\n return getCloudBaseUrl().replace(/\\/+$/, \"\");\n }\n return `http://127.0.0.1:${entry.port}`;\n}\n\n/** Docker image metadata for the service group. Enables rollback to known-good refs. */\nexport const ContainerInfoSchema = z.object({\n assistantImage: z.string(),\n gatewayImage: z.string(),\n cesImage: z.string(),\n});\nexport type ContainerInfo = z.infer<typeof ContainerInfoSchema>;\n\n/**\n * Host-independent resource policy for one assistant's machine allocation —\n * what the allocation *should be*, as opposed to the record fields (ports,\n * instanceDir, containerInfo) that describe what *is*. The section rides\n * every topology's entry: the stored shape is the same everywhere, while\n * each remote's plan/apply ops own how it materializes there.\n *\n * The schema is strict — unknown keys are rejected — because the write path\n * (future `cadet machine set`, daemon PATCH, cloud API) is the loud validator:\n * a typo'd knob must fail at the boundary, never silently degrade to the\n * runtime default. Parse time is deliberately softer: the field is embedded\n * with `.catch(undefined)`, so a malformed or unrecognized section from a\n * hand-edit or a different build quarantines to the defaults while the\n * entry itself survives, and the drift is visible to readers instead of\n * costing the assistant its identity fields.\n */\nexport const MachineMemoryPolicySchema = z\n .strictObject({\n /**\n * Soft limit in bytes: where the runtime should start reclaiming early\n * and smoothly (cgroup v2 `memory.high` on docker remotes). Absent =\n * unconstrained.\n */\n high: z.number().int().positive().optional(),\n /** Hard limit in bytes: the backstop the runtime may not exceed\n * (cgroup v2 `memory.max` on docker remotes). Absent = unconstrained. */\n max: z.number().int().positive().optional(),\n })\n .superRefine((memory, context) => {\n if (\n memory.high !== undefined &&\n memory.max !== undefined &&\n memory.high > memory.max\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"high\"],\n message: `memory.high (${memory.high}) must not exceed memory.max (${memory.max})`,\n });\n }\n });\nexport type MachineMemoryPolicy = z.infer<typeof MachineMemoryPolicySchema>;\n\n/** The `machine` section: one key per resource knob, added as they migrate here. */\nexport const MachinePolicySchema = z.strictObject({\n memory: MachineMemoryPolicySchema.optional(),\n});\nexport type MachinePolicy = z.infer<typeof MachinePolicySchema>;\n\n/**\n * The dotted paths of the machine policy, walked from the schema itself so\n * a grown schema joins the `get`/`set`/`reset` surface without any command\n * or operation learning its field names. Sections are the object nodes\n * (`memory`); leaves are the scalar knobs (`memory.high`, `memory.max`) —\n * the settable units.\n */\nexport function machinePolicyPaths(): {\n sections: string[];\n leaves: string[];\n} {\n const sections: string[] = [];\n const leaves: string[] = [];\n /** A zod wrapper node, narrowed to the two reflective members the walk needs. */\n type ZodNode = z.ZodType & {\n unwrap?: () => z.ZodType;\n shape?: Record<string, z.ZodType>;\n };\n const walk = (node: z.ZodType, path: string | undefined): void => {\n const inner = node as ZodNode;\n const shape =\n typeof inner.unwrap === \"function\"\n ? (inner.unwrap() as ZodNode).shape\n : inner.shape;\n if (shape) {\n if (path !== undefined) sections.push(path);\n for (const [key, child] of Object.entries(shape)) {\n walk(child, path === undefined ? key : `${path}.${key}`);\n }\n } else if (path !== undefined) {\n leaves.push(path);\n }\n };\n walk(MachinePolicySchema, undefined);\n return { sections, leaves };\n}\n\n/**\n * The fields every topology actually uses: the identity every reader looks\n * entries up by, the display name, and the hatch/onboarding/conversation\n * bookkeeping that is topology-agnostic.\n */\nconst BaseAssistantSchema = z.object({\n assistantId: z.string(),\n /** Platform assistant UUID for this assistant's registration. */\n cloudAssistantId: z.string().optional(),\n /** Platform organization the entry belongs to. */\n cloudOrganizationId: z.string().optional(),\n name: z.string().optional(),\n hatchedAt: z.string().optional(),\n /**\n * When this assistant finished first-run onboarding. Absent for entries that\n * predate the record, which fall back to hatch age (see the web client's\n * `onboarded-assistant.ts`).\n */\n onboardedAt: z.string().optional(),\n /** PID of the file watcher process for instances hatched with --watch. */\n watcherPid: z.number().optional(),\n /**\n * Host-independent resource policy for this assistant's machine allocation\n * (see {@link MachinePolicySchema} for the strict-at-write,\n * fallback-at-parse contract; each remote's plan/apply ops own how it\n * materializes there). Absent = the runtime's own defaults apply.\n */\n machine: MachinePolicySchema.optional().catch(undefined),\n});\n\n/**\n * The fields the self-hosted, on-machine topologies (local, docker,\n * apple-container) share: host-recorded ports.\n */\nconst LocalRuntimeAssistantFields = {\n /** The gateway port a freshly hatched assistant's gateway listens on. */\n port: z.number(),\n /** The runtime daemon's port, recorded at hatch. */\n daemonPort: z.number().optional(),\n /** The content-editor server's port, recorded at hatch. */\n cesPort: z.number().optional(),\n};\n\n/** A plain on-machine assistant: host-managed ports and instance dir. */\nconst LocalAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n /** The instance's state root on this machine. Local instances keep their\n * data here. */\n instanceDir: z.string().optional(),\n cloud: z.literal(\"local\"),\n});\n\n/** A docker-hosted assistant: container metadata for rollback/upgrade. */\nconst DockerAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n cloud: z.literal(\"docker\"),\n /** Docker image metadata for rollback. Only present for docker topology entries. */\n containerInfo: ContainerInfoSchema.optional(),\n});\n\n/** An apple-container assistant, driven through its management socket. */\nconst AppleContainerAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n cloud: z.literal(\"apple-container\"),\n /** Management socket path for apple-container assistants; written by the macOS host. */\n mgmtSocket: z.string(),\n});\n\n/** A platform-hosted assistant, registered against the cloud API. */\nconst CloudAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"cloud\"),\n});\n\n/** A self-hosted remote assistant, reached at its own address. */\nconst CustomAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"custom\"),\n /** Host address of the custom remote's gateway. */\n ipAddress: z.string(),\n /** Gateway port on the custom remote. */\n port: z.number(),\n});\n\n/**\n * A Baseten sandbox entry: the sandbox server URL and the sandbox-internal\n * gateway port are pinned at creation. When the hatch also minted the\n * gateway's private preview, `previewUrl` is the gateway's canonical\n * address — the preview edge opens the port dynamically and guards it with\n * a preview token, leaving `Authorization` free for the gateway's own\n * bearer end to end. Entries without one (tokenless hatches, legacy) ride\n * the `{sandboxUrl}/port/{port}` route with the sandbox access token.\n */\nconst BasetenAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"baseten\"),\n /** The Baseten sandbox server URL; the port route rides on it. */\n sandboxUrl: z.string(),\n /** The sandbox-internal gateway port, piped in as `GATEWAY_PORT` at creation. */\n port: z.number(),\n /** The gateway's private preview URL, minted at hatch when a token resolves. */\n previewUrl: z.string().optional(),\n});\n\n/**\n * Route absent and unknown topology values to the local default before the\n * union discriminates, keeping the on-disk contract permissive about clouds\n * this build has never heard of.\n */\n/**\n * The one preprocess the entry union parses through. Routes absent and\n * unknown topology values to the local default before the union\n * discriminates, and backfills the legacy `resources.gatewayPort` onto\n * `port` — but only when the flat `port` field would fail the number\n * schema (absent or not a number): a valid port always wins. Zod has no\n * field-level sibling fallback, so the object-level preprocess is the\n * supported surface for this.\n */\nfunction normalizeEntry(entry: unknown): unknown {\n if (typeof entry !== \"object\" || entry === null) return entry;\n let rec = entry as Record<string, unknown>;\n const cloud = rec.cloud;\n if (!(typeof cloud === \"string\" && RemoteSchema.safeParse(cloud).success)) {\n rec = { ...rec, cloud: \"local\" };\n }\n if (rec.port === undefined) {\n // The flat port failed the required schema (absent on a legacy or bare\n // entry): fall back to the legacy resources.gatewayPort, else the\n // gateway default. A mistyped port never falls back — a bad modeled\n // field still drops the entry.\n const resources = rec.resources;\n const gatewayPort =\n resources && typeof resources === \"object\"\n ? (resources as Record<string, unknown>).gatewayPort\n : undefined;\n rec = {\n ...rec,\n port: typeof gatewayPort === \"number\" ? gatewayPort : GATEWAY_PORT,\n };\n }\n return rec;\n}\n\nexport const LockfileAssistantSchema = z.preprocess(\n normalizeEntry,\n z.discriminatedUnion(\"cloud\", [\n LocalAssistantSchema,\n DockerAssistantSchema,\n AppleContainerAssistantSchema,\n CloudAssistantSchema,\n CustomAssistantSchema,\n BasetenAssistantSchema,\n ]),\n);\n\n/**\n * A validated, normalized assistant entry — a discriminated union on\n * `cloud`, so each topology carries exactly the fields it uses: a baseten\n * entry's `sandboxUrl`/`port` are always defined, a docker entry's\n * `containerInfo` reads without touching unrelated topologies, and absent or\n * unknown on-disk clouds route to the local branch.\n */\nexport type LockfileAssistant = z.infer<typeof LockfileAssistantSchema>;\n\nexport type LocalAssistant = z.infer<typeof LocalAssistantSchema>;\nexport type DockerAssistant = z.infer<typeof DockerAssistantSchema>;\nexport type AppleContainerAssistant = z.infer<\n typeof AppleContainerAssistantSchema\n>;\nexport type CloudAssistant = z.infer<typeof CloudAssistantSchema>;\nexport type CustomAssistant = z.infer<typeof CustomAssistantSchema>;\nexport type BasetenAssistant = z.infer<typeof BasetenAssistantSchema>;\n\n/** Whether the entry is a platform-hosted assistant. */\nexport function isCloudEntry(\n entry: LockfileAssistant,\n): entry is CloudAssistant {\n return entry.cloud === \"cloud\";\n}\n\n/** Whether the entry is a docker-hosted assistant. */\nexport function isDockerEntry(\n entry: LockfileAssistant,\n): entry is DockerAssistant {\n return entry.cloud === \"docker\";\n}\n\n/** Whether the entry is an apple-container assistant. */\nexport function isAppleContainerEntry(\n entry: LockfileAssistant,\n): entry is AppleContainerAssistant {\n return entry.cloud === \"apple-container\";\n}\n\n/** Whether the entry is a plain on-machine assistant. */\nexport function isLocalEntry(\n entry: LockfileAssistant,\n): entry is LocalAssistant {\n return entry.cloud === \"local\";\n}\n\n/**\n * A CLI-managed OS process recorded at the lockfile root under `tunnel`:\n * the auto-tunnel agent fronting the edge. `cadet ps` renders it alongside\n * the per-assistant process trees, and the stop paths verify the pid before\n * signaling it.\n */\nexport const TunnelProcessRecordSchema = z.object({\n pid: z.number(),\n /** Which tunnel provider owns the process. */\n provider: z.enum(TUNNEL_PROVIDERS),\n startedAt: z.string(),\n /** The public URL the tunnel agent serves. */\n publicUrl: z.string().optional(),\n});\nexport type TunnelProcessRecord = z.infer<typeof TunnelProcessRecordSchema>;\n\n/**\n * A CLI-managed OS process recorded at the lockfile root under `app`: the\n * app server (web artifacts, `/v1` proxying, the outer shell). Shares\n * nothing with the tunnel record beyond the pid bookkeeping — a tunnel\n * serves a URL, the app server serves a port.\n */\nexport const AppProcessRecordSchema = z.object({\n /** The app server's bookkeeping, present while it runs. */\n pid: z.number().optional(),\n startedAt: z.string().optional(),\n /** Listening port for the app server. */\n port: z.number(),\n});\nexport type AppProcessRecord = z.infer<typeof AppProcessRecordSchema>;\n\n/**\n * Renderer-facing result of a lockfile write, returned across the host bridge.\n * Carries no HTTP-style status — hosts map that away because the renderer\n * surfaces failures by message alone.\n */\nexport type LockfileWriteResult =\n | { ok: true; lockfile: Lockfile }\n | { ok: false; error: string };\n\nexport const LockfileSchema = z.looseObject({\n assistants: z\n .array(LockfileAssistantSchema.nullable().catch(null))\n .catch([])\n .transform((entries) =>\n entries.filter((entry): entry is LockfileAssistant => entry !== null),\n ),\n activeAssistant: z.union([z.string(), z.null()]).catch(null),\n tunnel: TunnelProcessRecordSchema.optional().catch(undefined),\n app: AppProcessRecordSchema.optional().catch(undefined),\n});\n\n/**\n * A validated, normalized lockfile — this schema's own output. Loose at the\n * root so the CLI's read-modify-write round-trip preserves the root keys it\n * owns and anything a newer writer added; readers key on the\n * modeled fields.\n */\nexport type Lockfile = z.infer<typeof LockfileSchema>;\n\n/**\n * Coerce parsed JSON into a validated {@link Lockfile}. Total and non-throwing:\n * the whole file parses through {@link LockfileSchema} — an entry that fails\n * validation is dropped whole (one malformed entry can't discard the file), a\n * missing or non-array `assistants` becomes `[]`, a non-string\n * `activeAssistant` becomes null, and a non-object root becomes an empty\n * lockfile.\n */\nexport function parseLockfile(raw: unknown): Lockfile {\n const parsed = LockfileSchema.safeParse(raw);\n return parsed.success ? parsed.data : LockfileSchema.parse({});\n}\n","import { z } from \"zod\";\n\nimport { RemoteSchema } from \"@mycadet/local-mode/contract\";\n\nfunction publicUrl(value: string): boolean {\n if (/[\\\\\\u0000-\\u0020]/.test(value) || value.startsWith(\"//\")) {\n return false;\n }\n if (\n (!value.startsWith(\"/\") &&\n !/^https?:\\/\\//i.test(value) &&\n value.includes(\":\")) ||\n /(?:^|\\/)(?:\\.|%2e){1,2}(?:\\/|$)/i.test(value)\n ) {\n return false;\n }\n try {\n const url = new URL(value, \"https://app.example\");\n if (url.username || url.password || url.search || url.hash) {\n return false;\n }\n return (\n value.startsWith(\"/\") ||\n url.protocol === \"https:\" ||\n (url.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n );\n } catch {\n return false;\n }\n}\n\nexport const PublicUrlSchema = z\n .string()\n .min(1)\n .refine(\n publicUrl,\n \"Expected a public host URL without credentials or query parameters.\",\n );\nexport const ResolvedAssistantSchema = z.object({\n id: z.string().min(1),\n version: z.string().min(1),\n});\n\nexport const AssistantChoiceSchema = z.object({\n id: z.string().min(1),\n name: z\n .string()\n .nullish()\n .transform((name) => name?.trim() || \"New Assistant\"),\n /** The cloud's synced avatar thumbnail; null means the cloud holds none. */\n avatar_url: z.string().nullish(),\n /** When the cloud hatched the assistant (ISO 8601); null when unknown. */\n created: z.string().nullish(),\n /**\n * The assistant's own hosting kind, stamped per row by the serving control\n * plane — the cloud lists its assistants \"cloud\", a self-hosted edge\n * stamps its lockfile cloud. Unknown or absent values (servers predating\n * the stamp, a hostile row) fall back to undefined; the chooser then uses\n * the build's own remote.\n */\n remote: RemoteSchema.nullish().catch(() => undefined),\n /**\n * The cloud row's admin-access opt-in (the owner's toggle on the\n * management page reads it from the selection state). Only the cloud's\n * list union carries it — self-hosted rows and servers predating the\n * field decode to undefined, which the panel reads as not available.\n */\n allow_admin_access: z\n .boolean()\n .nullish()\n .catch(() => undefined),\n});\n\nexport const AssistantResolutionSchema = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"ready\"), assistant: ResolvedAssistantSchema }),\n z.object({ status: z.literal(\"notReady\") }),\n z.object({ status: z.literal(\"unavailable\") }),\n // Selection carries no rows by design — the rows are the list contract's;\n // this arm just sends the shell to the selection page.\n z.object({ status: z.literal(\"selection\") }),\n z.object({ status: z.literal(\"empty\") }),\n z.object({ status: z.literal(\"unauthenticated\") }),\n]);\n/**\n * What the list endpoint alone can answer: the choices on the machine\n * (nothing hatched is the empty arm), or no session to read them with. The chooser renders off this contract only —\n * the single-assistant resolution arms (ready/notReady/unavailable/empty)\n * belong to the shell's resolution flow, whose own selection arm carries no\n * rows — it routes here.\n */\nexport const AssistantListSchema = z.discriminatedUnion(\"status\", [\n z.object({\n status: z.literal(\"selection\"),\n assistants: z.array(AssistantChoiceSchema),\n }),\n z.object({ status: z.literal(\"empty\") }),\n z.object({ status: z.literal(\"unauthenticated\") }),\n]);\nexport type ResolvedAssistant = z.infer<typeof ResolvedAssistantSchema>;\nexport type AssistantResolution = z.infer<typeof AssistantResolutionSchema>;\nexport type AssistantList = z.infer<typeof AssistantListSchema>;\nexport const AssistantNavigationSchema = z.object({\n source: z.literal(\"mycadet-web-nav\"),\n nav: z.enum([\"push\", \"replace\", \"pop\"]),\n path: z.string(),\n});\n\n/**\n * The frame's HOST-navigation request: the assistant bundle opening a\n * surface outside its own url space (the account area — the Doctor page).\n * The frame listener allowlists `/account/*`; the schema only fixes the\n * message's shape.\n */\nexport const HostNavigationSchema = z.object({\n source: z.literal(\"mycadet-web-host-nav\"),\n path: z.string(),\n});\n\nexport const ShareFeedbackRequestSchema = z.object({\n source: z.literal(\"mycadet-web-share-feedback\"),\n});\n","import { z } from \"zod\";\n\nimport {\n AssistantListSchema,\n AssistantResolutionSchema,\n PublicUrlSchema,\n type AssistantList,\n type AssistantResolution,\n} from \"./resolution-contract\";\n\nfunction decode<T>(schema: z.ZodType<T>, payload: unknown): T {\n const result = schema.safeParse(payload);\n if (!result.success) {\n // The zod error object carries the path and the per-field failures —\n // surface them so a contract drift names the field that moved.\n throw new Error(\n `Invalid assistant API data.\\n${z.prettifyError(result.error)}`,\n );\n }\n return result.data;\n}\n\nexport interface AssistantRequest {\n apiBaseUrl?: string;\n assistantId?: string;\n signal: AbortSignal;\n}\n\nconst unauthenticated = Symbol(\"unauthenticated\");\nconst notReady = Symbol(\"not ready\");\nconst unavailable = Symbol(\"unavailable\");\n\nfunction createClient({ apiBaseUrl = \"/\", signal }: AssistantRequest) {\n // The shell is same-origin by construction — every host (the desktop\n // protocol, the web dev server, the cloud takeover) proxies the API at\n // the page's own origin. Read inside: SSR renders the shell without a\n // window, and the origin is a browser fact.\n const origin = window.location.origin;\n const base = new URL(decode(PublicUrlSchema, apiBaseUrl), origin);\n base.pathname = base.pathname.replace(/\\/*$/, \"/\");\n const headers = new Headers({ Accept: \"application/json\" });\n async function get(path: string) {\n signal.throwIfAborted();\n const requestUrl = new URL(path, base);\n const response = await fetch(requestUrl, {\n headers,\n signal,\n credentials: \"include\",\n });\n signal.throwIfAborted();\n if (response.status === 401) {\n return unauthenticated;\n }\n if (response.status === 409) {\n return notReady;\n }\n if (response.status === 410) {\n return unavailable;\n }\n if (!response.ok) {\n console.error(\n `Assistant request failed: ${response.status} ${response.headers.get(\"content-type\") ?? \"\"} from ${requestUrl.href}`,\n );\n throw new Error(\n `Assistant request failed: ${response.status} from ${requestUrl.href}`,\n );\n }\n const payload: unknown = await response.json().catch((error) => {\n console.error(\n `Assistant response was not JSON from ${requestUrl.href}: ${error}`,\n );\n throw error;\n });\n signal.throwIfAborted();\n return payload;\n }\n return { base, get };\n}\n\n/**\n * The chooser's list: ONE call to the same-origin list endpoint — the\n * unscoped `v1/assistants/` is the list CONTRACT (the machine's rows\n * without a credential field), and the client just decodes it. No session\n * (401) reads as the contract's own unauthenticated arm.\n */\nexport async function listAssistantChoices(\n options: AssistantRequest,\n): Promise<AssistantList> {\n const client = createClient(options);\n const payload = await client.get(\"v1/assistants/\");\n if (payload === unauthenticated) {\n return { status: \"unauthenticated\" };\n }\n return decode(AssistantListSchema, payload);\n}\n\n/**\n * The shell's resolution: ONE call to the same-origin assistant resolution\n * endpoint — the serving host's operation composes the whole union (the\n * lockfile's choice, the entry gateway's identity and the caller's own auth\n * verdict) and the client just decodes it. The status-code arms stay for\n * hosts whose operation forwards a platform detail's own codes, and for\n * older stacks whose baked metadata predates the union.\n */\nexport async function resolveAssistant(\n options: AssistantRequest,\n): Promise<AssistantResolution> {\n const client = createClient(options);\n const payload = await client.get(\n options.assistantId\n ? `v1/assistants/${encodeURIComponent(options.assistantId)}/`\n : \"v1/assistant\",\n );\n if (payload === unauthenticated) {\n return { status: \"unauthenticated\" };\n }\n if (payload === notReady) {\n return { status: \"notReady\" };\n }\n if (payload === unavailable) {\n return { status: \"unavailable\" };\n }\n return decode(AssistantResolutionSchema, payload);\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"resolve-assistant-CFtChAyl.js","names":[],"sources":["../../../../../packages/shared/github-repository.ts","../../../../../packages/shared/seeds.ts","../../../../../packages/service-contracts/src/ingress.ts","../../../__vite-browser-external","../../../../../packages/local-mode/src/paths.ts","../../../../../packages/local-mode/src/lockfile-contract.ts","../../../src/assistant/resolution-contract.ts","../../../src/assistant/resolve-assistant.ts"],"sourcesContent":["/** The GitHub repository Cadet's source and releases live in. */\nexport const CADET_GITHUB_REPOSITORY = \"vargasjr-dev/mycadet-temp\";\n\n/** URL of the public GitHub repository. */\nexport const CADET_GITHUB_REPOSITORY_URL = `https://github.com/${CADET_GITHUB_REPOSITORY}`;\n","// Loaded standalone by Capacitor's single-file TS config loader (via the\n// `./seeds` subpath) — keep imports type-only (this file has none) and keep\n// this file free of the import-meta meta-property: the loader transpiles this\n// file to CJS, where that syntax is illegal and makes Node misroute the\n// result as ESM. Browser bundles (chrome extension, web renderer) import it\n// for the same reason.\n\n/**\n * Per-service default port set. Phase 5 (per-environment port offsets) is\n * deferred from MVP, so today every environment uses the same port set. The\n * shape exists so the rest of the stack can call `getDefaultPorts(env)` and\n * gain per-env offsets later without changing any call sites.\n */\nexport interface PortMap {\n daemon: number;\n gateway: number;\n qdrant: number;\n ces: number;\n outboundProxy: number;\n tcp: number;\n}\n\n/**\n * The port the local app server binds by default — the single origin every\n * local surface (webview, assistant daemon, CLI) dials. The local seed's\n * base URL reuses it so no surface carries its own port constant.\n */\nexport const DEFAULT_APP_SERVER_PORT = 7840;\n\n/**\n * A resolved environment definition. Required fields are `name` and\n * `baseUrl`. All other fields are optional and declared upfront — new\n * fields are additive, never breaking. `name` is a `CadetEnvironment`: a\n * definition outside the known names has nowhere to key into.\n */\nexport interface EnvironmentDefinition {\n name: CadetEnvironment;\n\n /**\n * The single origin for API, auth, web, and the assistant mount — one\n * deployment serves all of it, so one URL describes it. The local seed\n * points at the app server's default port; the cloud seeds point at the\n * environment's host.\n */\n baseUrl: string;\n\n /** Human-readable label for UI surfaces. */\n displayName?: string;\n\n /** Hint for UI surfaces that want to tint or badge their display. */\n tintColor?: string;\n\n /** Per-service port overrides merged on top of defaults. */\n portsOverride?: Partial<PortMap>;\n\n /** Override for the XDG config directory. */\n configDirOverride?: string;\n\n /**\n * Override for the directory containing the lockfile. In-memory only —\n * tests inject curated env lists with it; path helpers never read env\n * vars to populate it.\n */\n lockfileDirOverride?: string;\n}\n\n/**\n * Non-prod port blocks. Each environment gets a 1000-port window in the\n * 17000–21000 band. Within a block, services are spaced 100 apart so up to\n * 100 assistants can coexist without the scan (`findAvailablePort`) running\n * one service's range into the next. Band chosen to sit below Linux's\n * default ephemeral start (32768) and macOS's (49152), and away from the\n * 3000/5000/8000/9000 dev-tool swamp. Production keeps its legacy,\n * non-contiguous port set (7821/7830/6333/8090/8080/8765): cross-env\n * collision is the only problem this change targets, prod is unaffected\n * because only one env's assistants compete on a given machine, and\n * churning it would leave existing hatches on 7821 while new ones\n * allocated elsewhere.\n */\nfunction portBlock(base: number): PortMap {\n return {\n daemon: base,\n gateway: base + 100,\n qdrant: base + 200,\n ces: base + 300,\n outboundProxy: base + 400,\n tcp: base + 500,\n };\n}\n\n/**\n * The set of environment names every surface shares — the seeds below are\n * exactly these five. Lockfiles, config directories, release channels, and\n * the mobile shells' scheme keys all key off this union, so a name outside\n * it is a bug the compiler can catch.\n */\nexport const CADET_ENVIRONMENT_NAMES = [\n \"local\",\n \"dev\",\n \"staging\",\n \"production\",\n \"test\",\n] as const;\n\nexport type CadetEnvironment = (typeof CADET_ENVIRONMENT_NAMES)[number];\n\nfunction isCadetEnvironment(\n name: string | undefined,\n): name is CadetEnvironment {\n return (\n typeof name === \"string\" &&\n (CADET_ENVIRONMENT_NAMES as readonly string[]).includes(name)\n );\n}\n\n/**\n * globalThis.process reads the same env under bun/node while staying\n * crash-free in browser bundles (no bare `process` reference) — and free\n * of import-meta syntax, which the Capacitor config loader can't transpile.\n */\nfunction processEnv(): Record<string, string | undefined> | undefined {\n return (\n globalThis as unknown as {\n process?: { env?: Record<string, string | undefined> };\n }\n ).process?.env;\n}\n\n/**\n * Whether a version string denotes a dev build from the dev-release\n * pipeline, e.g. `0.12.6-dev.202610081023.3a27b77`.\n */\nexport function isDevVersion(version: string): boolean {\n return /-dev\\./i.test(version);\n}\n\n/**\n * Whether a version string denotes a staging build, e.g. `0.6.0-staging.3`.\n */\nexport function isStagingVersion(version: string): boolean {\n return /-staging\\./i.test(version);\n}\n\n/**\n * Whether a version string denotes a local build, e.g. `0.12.6-local.42`.\n * Local builds are never published.\n */\nexport function isLocalVersion(version: string): boolean {\n return /-local\\./i.test(version);\n}\n\n/**\n * The environment a released channel version pins, or `undefined` when the\n * version carries no channel suffix. A plain version — a workspace\n * checkout's unstamped package version — reads as \"no version signal\",\n * leaving the remaining steps to decide. Mirrors the CLI resolver's mapping\n * (local, dev, staging).\n */\nexport function environmentFromVersion(\n version: string | undefined,\n): CadetEnvironment | undefined {\n if (isLocalVersion(version ?? \"\")) return \"local\";\n if (isDevVersion(version ?? \"\")) return \"dev\";\n if (isStagingVersion(version ?? \"\")) return \"staging\";\n return undefined;\n}\n\n/**\n * Read the persisted default environment — the file pre-version-tied CLIs\n * wrote so their successors honor the machine's chosen default. Node-only\n * and resolved at call time (`process.getBuiltinModule`), so this file\n * keeps zero static node imports: the Capacitor config loader transpiles it\n * standalone and a static node import would die there, while browser\n * bundles (chrome extension, web renderer) never reach the call.\n */\nfunction readPersistedDefault(): CadetEnvironment | undefined {\n const node = process as unknown as {\n getBuiltinModule?: (id: string) => unknown;\n platform: string;\n };\n const fs = node.getBuiltinModule?.(\"node:fs\") as\n | typeof import(\"node:fs\")\n | undefined;\n const os = node.getBuiltinModule?.(\"node:os\") as\n | typeof import(\"node:os\")\n | undefined;\n const path = node.getBuiltinModule?.(\"node:path\") as\n | typeof import(\"node:path\")\n | undefined;\n if (!fs || !os || !path) return undefined;\n\n // Mirrors local-mode's resolveConfigHome (the same XDG/AppData derivation).\n const isWindows = node.platform === \"win32\";\n const join = isWindows ? path.win32.join : path.posix.join;\n const configHome = isWindows\n ? process.env.APPDATA?.trim() || join(os.homedir(), \"AppData\", \"Roaming\")\n : process.env.XDG_CONFIG_HOME?.trim() || join(os.homedir(), \".config\");\n const filePath = join(configHome, \"cadet\", \"environment\");\n try {\n if (!fs.existsSync(filePath)) return undefined;\n const content = fs.readFileSync(filePath, \"utf-8\").trim();\n return isCadetEnvironment(content) ? content : undefined;\n } catch {\n // Unreadable file — no default.\n return undefined;\n }\n}\n\n/**\n * The environment name every surface shares: `CADET_ENVIRONMENT`, then\n * `VITE_ENVIRONMENT`, then the release channel the copy's version carries\n * (`__CADET_OWN_VERSION__`, defined at build time by hosts that bundle\n * local-mode), then the persisted default written by pre-version-tied CLIs,\n * then production.\n */\nexport function resolveEnvironmentName(): CadetEnvironment {\n const env = processEnv();\n const named = [\n env?.CADET_ENVIRONMENT?.trim(),\n env?.VITE_ENVIRONMENT?.trim(),\n ].find(isCadetEnvironment);\n if (named) return named;\n return (\n environmentFromVersion(\n (globalThis as { __CADET_OWN_VERSION__?: string }).__CADET_OWN_VERSION__,\n ) ??\n readPersistedDefault() ??\n \"production\"\n );\n}\n\n/**\n * The base URL of Cadet Cloud — the hosted deployment the local surfaces\n * pair with (API, auth, web, and the assistant mount all live on it). The\n * explicit `CADET_CLOUD_URL` override wins, else the seed of\n * `resolveEnvironmentName`. This says \"cloud\" because the URL always points\n * at a Cadet Cloud deployment, never at something that represents this\n * surface itself.\n */\nexport function getCloudBaseUrl(): string {\n const explicit = processEnv()?.CADET_CLOUD_URL?.trim();\n if (explicit) return explicit;\n return SEEDS[resolveEnvironmentName()].baseUrl;\n}\n\n/**\n * Built-in environment definitions and the source of truth for the\n * set of known environment names.\n *\n * Custom environments via a user config file are a future phase — see the\n * \"Coexisting environments\" design doc. Until then, a call site that needs a\n * new environment must add it here and rebuild.\n */\nexport const SEEDS: Record<CadetEnvironment, EnvironmentDefinition> = {\n production: {\n name: \"production\",\n baseUrl: \"https://mycadet.ai\",\n },\n staging: {\n name: \"staging\",\n baseUrl: \"https://staging.mycadet.ai\",\n portsOverride: portBlock(17000),\n },\n test: {\n name: \"test\",\n baseUrl: \"https://test.mycadet.ai\",\n portsOverride: portBlock(19000),\n },\n dev: {\n name: \"dev\",\n baseUrl: \"https://dev.mycadet.ai\",\n portsOverride: portBlock(18000),\n },\n local: {\n name: \"local\",\n baseUrl: `http://localhost:${DEFAULT_APP_SERVER_PORT}`,\n // assistantBaseUrl: \"http://host.docker.internal:7840\",\n // ^ uncomment once dockerized hatch path is live — the assistant runs\n // in a different network namespace than the host.\n portsOverride: portBlock(20000),\n },\n};\n","/**\n * Map a Cadet Cloud host onto its environment's tunnel host, following the\n * deployment naming convention (`cloud.mycadet.ai` → `tunnel.mycadet.ai`,\n * `{env}-cloud.mycadet.ai` → `{env}-tunnel.mycadet.ai`). Returns null for\n * hosts outside that convention (localhost, custom domains). Shared by the\n * gateway speech relay (which passes the request's own host) and the web\n * live-voice client (which defaults to the page's origin) so the two ends\n * of the cloud-speech transport can't drift.\n */\nexport function tunnelHostForCloudHost(\n host: string = (globalThis as { location?: { hostname?: string } }).location\n ?.hostname ?? \"\",\n): string | null {\n if (host === \"cloud.mycadet.ai\") {\n return \"tunnel.mycadet.ai\";\n }\n const match = /^([a-z0-9-]+)-cloud\\.mycadet\\.ai$/.exec(host);\n return match ? `${match[1]}-tunnel.mycadet.ai` : null;\n}\n\nexport function normalizePublicBaseUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim().replace(/\\/+$/, \"\");\n return normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Application close code the gateway's tunnel bridge sends to proxied\n * WebSockets when the tunnel itself is lost (tunnel disconnect, gateway\n * shutdown). A dedicated code because the natural 1001 (going away) cannot\n * be sent through the JS `close()` API (the bridge would remap it to a\n * misleading 4001), and Bun's WebSocket client drops close reasons, so the\n * code is the only signal that survives the relay to the daemon.\n */\nexport const GATEWAY_TUNNEL_LOST_WS_CLOSE_CODE = 4801;\n\nexport function normalizeHttpPublicBaseUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n if (/[?#]/.test(trimmed)) return undefined;\n\n try {\n const url = new URL(trimmed);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return undefined;\n }\n if (!url.hostname) return undefined;\n url.pathname = url.pathname.replace(/\\/+$/, \"\") || \"/\";\n return url.toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The same validation as `normalizeHttpPublicBaseUrl`, minus the root path it\n * always emits (`https://x` becomes `https://x/`). Callers that append a path\n * or persist the result want this shape, so they neither join through a double\n * slash nor re-strip what the normalizer just added.\n */\nexport function normalizeHttpPublicBaseUrlWithoutTrailingSlash(\n value: unknown,\n): string | undefined {\n return normalizePublicBaseUrl(normalizeHttpPublicBaseUrl(value));\n}\n\n/**\n * A trimmed string, or undefined when the value is not a non-blank string.\n *\n * Exported because the identity check in the daemon's tunnel probe compares an\n * id recorded here against one an edge serves, and the two sides have to trim\n * alike: a padded served id must read as a match, not as a different\n * assistant.\n */\nexport function trimmedNonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n// Records `cadet tunnel` leaves in the workspace config's `ingress` section.\n// The CLI writes them and the daemon reads them, and the two are separate\n// build units that cannot import each other, so the key names, the provider\n// allowlist, and the validation all live here rather than in a copy on each\n// side.\n\n/** Key under `ingress` holding the tunnel that most recently ran. */\nexport const INGRESS_LAST_TUNNEL_KEY = \"lastTunnel\";\n\n/**\n * Key under `ingress` holding a tunnel published for device pairing alone.\n *\n * A tailnet-only tunnel started while webhook integrations are configured\n * cannot carry their callbacks, so it leaves `publicBaseUrl` (the callback\n * base) as it is and records itself here. Readers that answer the pairing card\n * prefer this address over `publicBaseUrl`; teardown drops the key.\n */\nexport const INGRESS_PAIRING_TUNNEL_KEY = \"pairingTunnel\";\n\n/** Key under `ingress` holding the assistant id that tunnel fronted. */\nexport const INGRESS_ASSISTANT_ID_KEY = \"assistantId\";\n\n/**\n * The tunnel providers the CLI offers, in the order they are presented —\n * the managed `cadet` tunnel first (listed, not yet implemented), then the\n * local ones. `cadet tunnel`'s accepted `--provider` values and the\n * persisted-record validation below both derive from it.\n */\nexport const TUNNEL_PROVIDERS = [\n \"cadet\",\n \"ngrok\",\n \"cloudflare\",\n \"tailscale\",\n] as const;\n\nexport type TunnelProviderName = (typeof TUNNEL_PROVIDERS)[number];\n\n/** A recorded tunnel, kept after teardown so UIs can name the command to restart. */\nexport interface TunnelRecord {\n provider: TunnelProviderName;\n publicBaseUrl: string;\n}\n\nfunction isTunnelProviderName(value: unknown): value is TunnelProviderName {\n return (\n typeof value === \"string\" &&\n (TUNNEL_PROVIDERS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Parse an `ingress.lastTunnel` or `ingress.pairingTunnel` value, or null when\n * it is absent or malformed.\n *\n * A hand-edited config must not hand callers an unusable address or a provider\n * name no command accepts: the provider is checked against the allowlist\n * because readers render it into a restart command, and the URL faces the same\n * absolute HTTP(S) constraint as every other public base URL. The URL comes\n * back in the shape the validator produced, so readers never re-normalize it.\n */\nexport function parseTunnelRecord(value: unknown): TunnelRecord | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const { provider, publicBaseUrl } = value as Record<string, unknown>;\n if (!isTunnelProviderName(provider)) {\n return null;\n }\n const normalized =\n normalizeHttpPublicBaseUrlWithoutTrailingSlash(publicBaseUrl);\n if (normalized === undefined) {\n return null;\n }\n return { provider, publicBaseUrl: normalized };\n}\n\n/**\n * The tunnel a reader should offer to restart, given an `ingress` section, or\n * null when it records none.\n *\n * A pairing-only record wins: it is written by a tunnel that deliberately left\n * `publicBaseUrl` (and the `lastTunnel` beside it) pointing at an older public\n * provider, so naming that older one would send the user to rebuild an ingress\n * they are not using instead of the tunnel actually in front of them.\n */\nexport function selectRestartTunnelRecord(\n ingress: unknown,\n): TunnelRecord | null {\n if (typeof ingress !== \"object\" || ingress === null) {\n return null;\n }\n const section = ingress as Record<string, unknown>;\n return (\n parseTunnelRecord(section[INGRESS_PAIRING_TUNNEL_KEY]) ??\n parseTunnelRecord(section[INGRESS_LAST_TUNNEL_KEY])\n );\n}\n\n/** Parse an `ingress.assistantId` value, or null when it is absent or blank. */\nexport function parseRecordedAssistantId(value: unknown): string | null {\n return trimmedNonEmptyString(value) ?? null;\n}\n","module.exports = {}","import { homedir } from \"node:os\";\nimport path from \"node:path\";\n\nconst PRODUCTION_ENVIRONMENT_NAME = \"production\";\n\nconst isWindows = () => process.platform === \"win32\";\nconst paths = () => (isWindows() ? path.win32 : path.posix);\n\nexport function resolveConfigHome(): string {\n if (isWindows()) {\n return (\n process.env.APPDATA?.trim() ||\n paths().join(homedir(), \"AppData\", \"Roaming\")\n );\n }\n return process.env.XDG_CONFIG_HOME?.trim() || paths().join(homedir(), \".config\");\n}\n\nexport function resolveDataHome(): string {\n if (isWindows()) {\n return (\n process.env.LOCALAPPDATA?.trim() ||\n paths().join(homedir(), \"AppData\", \"Local\")\n );\n }\n return process.env.XDG_DATA_HOME?.trim() || paths().join(homedir(), \".local\", \"share\");\n}\n\nexport const joinLocalPath = (...segments: string[]) => paths().join(...segments);\n\nexport function assertSafePathSegment(value: string, label: string): void {\n const unsafe =\n !value ||\n /[/\\\\\\0]/.test(value) ||\n /^\\.{1,2}$/.test(value) ||\n (isWindows() &&\n (/[<>:\"|?*\\u0000-\\u001f]/.test(value) ||\n /[. ]$/.test(value) ||\n /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(value)));\n if (unsafe) {\n throw new Error(`Invalid ${label}: ${value}`);\n }\n}\n\n/**\n * The directory name an environment's state lives under: `cadet` for\n * production (the legacy location other environments must not collide with),\n * `cadet-<env>` otherwise. Exported so hosts that enumerate a SPECIFIC\n * environment's directories — the CLI's cross-environment detection — can\n * compose them from {@link resolveConfigHomes} and {@link resolveDataHome}\n * without an options bag threading through the ambient resolvers.\n */\nexport function environmentDirectoryName(cadetEnv: string): string {\n assertSafePathSegment(cadetEnv, \"environment name\");\n return cadetEnv === PRODUCTION_ENVIRONMENT_NAME\n ? \"cadet\"\n : `cadet-${cadetEnv}`;\n}\n","/**\n * The lockfile wire contract — one Zod schema that is the single source of truth\n * for an assistant entry's shape, its validation, the `cloud` taxonomy, the\n * normalization, and the redaction policy.\n *\n * Kept in its own module, exported from the package as `./contract`, so\n * consumers import the contract without pulling in the host I/O graph\n * (`node:fs`, the CLI resolver). The CLI, the host I/O layer, the Electron and\n * dev-server bridges, and the renderer all depend on this one definition. It\n * references no node built-ins — the renderer bundles it directly — and `zod`\n * is its only third-party import.\n *\n * The lockfile is written by the Cadet CLI and read across the macOS↔CLI\n * boundary, which do not release in lockstep, so the parser is permissive at\n * the file level: it validates each entry whole through the schema (a\n * malformed field drops that entry, never the file), accepts — but drops from\n * the validated value — entry fields this build has never heard of, and\n * defaults `cloud` when it is absent or unknown. The schema is strict over\n * the fields it models: every field a reader needs is IN the schema, so a\n * CLI read-modify-write round-trip preserves it by construction. The\n * local-mode write path still merges raw JSON (unknown root fields survive\n * on disk; see `lockfile.ts`); the validated value carries only the modeled\n * shape.\n */\nimport { getCloudBaseUrl } from \"@mycadet/shared\";\nimport { TUNNEL_PROVIDERS } from \"@mycadet/service-contracts/ingress\";\nimport { z } from \"zod\";\n\nimport { readLockfile } from \"./lockfile\";\n\n/**\n * Known deployment topologies of a Cadet:\n * - `local` — on-machine bare-metal processes\n * - `docker` — docker-managed container\n * - `apple-container` — macOS-app-managed container\n * - `cloud` — managed by Cadet Cloud\n * - `custom` — remote VM accessible via SSH\n */\nexport const KNOWN_REMOTES = [\n \"local\",\n \"docker\",\n \"apple-container\",\n \"cloud\",\n \"custom\",\n \"baseten\",\n] as const;\n\n/**\n * The topology values as one zod enum, shared by the lockfile schema (which\n * wraps it in a `catch`) and the clients' injected-config schema, so the two\n * can never drift.\n */\nexport const RemoteSchema = z.enum(KNOWN_REMOTES);\nexport type Remote = z.infer<typeof RemoteSchema>;\n\n/**\n * Keys that must never cross the host→renderer boundary. Stripped from raw\n * lockfile JSON before it leaves a host (see `stripSensitiveFields`) and absent\n * from the renderer-facing schema below; the CLI's extended type is the only\n * place they are modeled.\n */\nexport const SENSITIVE_KEYS = [\n \"bearerToken\",\n \"guardianBootstrapSecret\",\n] as const;\n\n/**\n * Strip every `SENSITIVE_KEYS` field from a parsed lockfile, in place: from\n * each assistant entry and from that entry's `resources`. The one redaction\n * every host runs before lockfile data crosses to the renderer — pure, no\n * node built-ins, so it lives beside the keys it enforces and bundles into\n * the renderer through the `./contract` subpath.\n */\nexport function stripSensitiveFields(data: Record<string, unknown>): void {\n const assistants = data.assistants;\n if (!Array.isArray(assistants)) return;\n for (const assistant of assistants) {\n if (assistant && typeof assistant === \"object\") {\n const entry = assistant as Record<string, unknown>;\n for (const field of SENSITIVE_KEYS) {\n delete entry[field];\n }\n const resources = entry.resources;\n if (resources && typeof resources === \"object\") {\n for (const field of SENSITIVE_KEYS) {\n delete (resources as Record<string, unknown>)[field];\n }\n }\n }\n }\n}\n\n/**\n * Whether an entry's `runtimeUrl` is one a serving host can forward to: an\n * absolute http(s) URL. Shared by the renderer's paired-gateway URL derivation\n * and the host-side paired allowlist reader so the two can't drift.\n */\nexport function isUsableBaseUrl(url: unknown): url is string {\n if (typeof url !== \"string\" || url === \"\") {\n return false;\n }\n try {\n const parsed = new URL(url);\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n\n/**\n * The local build's control-plane base, read from the lockfile alone: the\n * auto-tunnel's recorded `publicUrl` when one is up, else the app server\n * edge's loopback port. A loopback base is reachable from the iOS simulator\n * only — a device's `127.0.0.1` is the phone itself — so a device build\n * wants a tunnel up before it stamps. `undefined` when neither record\n * carries a usable address.\n *\n * The assistants play no role in this resolution — the capacitor app shell\n * only deals with the app server — and the CLI's workspace config is never\n * touched: the lockfile is the single home for edge state.\n */\nexport function resolveLocalServerUrl(): string | undefined {\n const lockfile = readLockfile();\n const tunnelUrl = lockfile.tunnel?.publicUrl;\n if (isUsableBaseUrl(tunnelUrl)) {\n return tunnelUrl;\n }\n const port = lockfile.app?.port;\n if (typeof port === \"number\") {\n return `http://127.0.0.1:${port}`;\n }\n return undefined;\n}\n\n/**\n * Clouds whose gateway listens on a loopback port of this machine: the\n * on-machine daemon (\"local\") and local Docker instances (\"docker\").\n */\nexport const LOOPBACK_GATEWAY_CLOUDS: readonly Remote[] = [\"local\", \"docker\"];\n\nexport function isLoopbackGatewayCloud(cloud: Remote): boolean {\n return LOOPBACK_GATEWAY_CLOUDS.includes(cloud);\n}\n\n/**\n * The gateway port a freshly hatched assistant's gateway listens on, with\n * the `GATEWAY_PORT` env override the CLI tooling honors.\n */\nexport const GATEWAY_PORT = process.env.GATEWAY_PORT\n ? Number(process.env.GATEWAY_PORT)\n : 7830;\n\n/**\n * The URL to dial an entry's gateway on, derived from the entry's canonical\n * fields — the one seam every consumer addresses a gateway through, and the\n * one place a trailing slash is stripped: the returned URL is always\n * slash-free, so callers join paths directly:\n *\n * - `custom` remotes: their recorded host and port.\n * - cloud-managed: the environment's base url (`getCloudBaseUrl()`).\n * - loopback topologies (`local`, `docker`, `apple-container`): the\n * recorded loopback gateway port, else the default gateway port.\n */\nexport function getGatewayUrl(entry: LockfileAssistant): string {\n // Baseten: the private preview is the door when one was minted — the\n // preview edge opens the port dynamically and guards it with a preview\n // token, so `Authorization` stays free for the gateway's own bearer.\n // Without one, the sandbox API's `/port/<PORT>/` route (the sandbox\n // access token authenticates it).\n if (entry.cloud === \"baseten\") {\n if (entry.previewUrl) {\n return entry.previewUrl.replace(/\\/+$/, \"\");\n }\n return `${entry.sandboxUrl.replace(/\\/+$/, \"\")}/port/${entry.port}`;\n }\n if (entry.cloud === \"custom\") {\n // Custom remotes speak TLS. Default ports elided the way a URL prints\n // them. The schema requires the address and port.\n const elided = entry.port === 443;\n return `https://${entry.ipAddress}${elided ? \"\" : `:${entry.port}`}`;\n }\n if (isCloudEntry(entry)) {\n return getCloudBaseUrl().replace(/\\/+$/, \"\");\n }\n return `http://127.0.0.1:${entry.port}`;\n}\n\n/** Docker image metadata for the service group. Enables rollback to known-good refs. */\nexport const ContainerInfoSchema = z.object({\n assistantImage: z.string(),\n gatewayImage: z.string(),\n cesImage: z.string(),\n});\nexport type ContainerInfo = z.infer<typeof ContainerInfoSchema>;\n\n/**\n * Host-independent resource policy for one assistant's machine allocation —\n * what the allocation *should be*, as opposed to the record fields (ports,\n * instanceDir, containerInfo) that describe what *is*. The section rides\n * every topology's entry: the stored shape is the same everywhere, while\n * each remote's plan/apply ops own how it materializes there.\n *\n * The schema is strict — unknown keys are rejected — because the write path\n * (future `cadet machine set`, daemon PATCH, cloud API) is the loud validator:\n * a typo'd knob must fail at the boundary, never silently degrade to the\n * runtime default. Parse time is deliberately softer: the field is embedded\n * with `.catch(undefined)`, so a malformed or unrecognized section from a\n * hand-edit or a different build quarantines to the defaults while the\n * entry itself survives, and the drift is visible to readers instead of\n * costing the assistant its identity fields.\n */\nexport const MachineMemoryPolicySchema = z\n .strictObject({\n /**\n * Soft limit in bytes: where the runtime should start reclaiming early\n * and smoothly (cgroup v2 `memory.high` on docker remotes). Absent =\n * unconstrained.\n */\n high: z.number().int().positive().optional(),\n /** Hard limit in bytes: the backstop the runtime may not exceed\n * (cgroup v2 `memory.max` on docker remotes). Absent = unconstrained. */\n max: z.number().int().positive().optional(),\n })\n .superRefine((memory, context) => {\n if (\n memory.high !== undefined &&\n memory.max !== undefined &&\n memory.high > memory.max\n ) {\n context.addIssue({\n code: \"custom\",\n path: [\"high\"],\n message: `memory.high (${memory.high}) must not exceed memory.max (${memory.max})`,\n });\n }\n });\nexport type MachineMemoryPolicy = z.infer<typeof MachineMemoryPolicySchema>;\n\n/** The `machine` section: one key per resource knob, added as they migrate here. */\nexport const MachinePolicySchema = z.strictObject({\n memory: MachineMemoryPolicySchema.optional(),\n});\nexport type MachinePolicy = z.infer<typeof MachinePolicySchema>;\n\n/**\n * The dotted paths of the machine policy, walked from the schema itself so\n * a grown schema joins the `get`/`set`/`reset` surface without any command\n * or operation learning its field names. Sections are the object nodes\n * (`memory`); leaves are the scalar knobs (`memory.high`, `memory.max`) —\n * the settable units.\n */\nexport function machinePolicyPaths(): {\n sections: string[];\n leaves: string[];\n} {\n const sections: string[] = [];\n const leaves: string[] = [];\n /** A zod wrapper node, narrowed to the two reflective members the walk needs. */\n type ZodNode = z.ZodType & {\n unwrap?: () => z.ZodType;\n shape?: Record<string, z.ZodType>;\n };\n const walk = (node: z.ZodType, path: string | undefined): void => {\n const inner = node as ZodNode;\n const shape =\n typeof inner.unwrap === \"function\"\n ? (inner.unwrap() as ZodNode).shape\n : inner.shape;\n if (shape) {\n if (path !== undefined) sections.push(path);\n for (const [key, child] of Object.entries(shape)) {\n walk(child, path === undefined ? key : `${path}.${key}`);\n }\n } else if (path !== undefined) {\n leaves.push(path);\n }\n };\n walk(MachinePolicySchema, undefined);\n return { sections, leaves };\n}\n\n/**\n * The fields every topology actually uses: the identity every reader looks\n * entries up by, the display name, and the hatch/onboarding/conversation\n * bookkeeping that is topology-agnostic.\n */\nconst BaseAssistantSchema = z.object({\n assistantId: z.string(),\n /** Platform assistant UUID for this assistant's registration. */\n cloudAssistantId: z.string().optional(),\n /** Platform organization the entry belongs to. */\n cloudOrganizationId: z.string().optional(),\n /** The admin-access opt-in: the management page's toggle writes it through the operator's PATCH row. */\n allowAdminAccess: z.boolean().optional(),\n name: z.string().optional(),\n hatchedAt: z.string().optional(),\n /**\n * When this assistant finished first-run onboarding. Absent for entries that\n * predate the record, which fall back to hatch age (see the web client's\n * `onboarded-assistant.ts`).\n */\n onboardedAt: z.string().optional(),\n /** PID of the file watcher process for instances hatched with --watch. */\n watcherPid: z.number().optional(),\n /**\n * Host-independent resource policy for this assistant's machine allocation\n * (see {@link MachinePolicySchema} for the strict-at-write,\n * fallback-at-parse contract; each remote's plan/apply ops own how it\n * materializes there). Absent = the runtime's own defaults apply.\n */\n machine: MachinePolicySchema.optional().catch(undefined),\n});\n\n/**\n * The fields the self-hosted, on-machine topologies (local, docker,\n * apple-container) share: host-recorded ports.\n */\nconst LocalRuntimeAssistantFields = {\n /** The gateway port a freshly hatched assistant's gateway listens on. */\n port: z.number(),\n /** The runtime daemon's port, recorded at hatch. */\n daemonPort: z.number().optional(),\n /** The content-editor server's port, recorded at hatch. */\n cesPort: z.number().optional(),\n};\n\n/** A plain on-machine assistant: host-managed ports and instance dir. */\nconst LocalAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n /** The instance's state root on this machine. Local instances keep their\n * data here. */\n instanceDir: z.string().optional(),\n cloud: z.literal(\"local\"),\n});\n\n/** A docker-hosted assistant: container metadata for rollback/upgrade. */\nconst DockerAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n cloud: z.literal(\"docker\"),\n /** Docker image metadata for rollback. Only present for docker topology entries. */\n containerInfo: ContainerInfoSchema.optional(),\n});\n\n/** An apple-container assistant, driven through its management socket. */\nconst AppleContainerAssistantSchema = BaseAssistantSchema.extend({\n ...LocalRuntimeAssistantFields,\n cloud: z.literal(\"apple-container\"),\n /** Management socket path for apple-container assistants; written by the macOS host. */\n mgmtSocket: z.string(),\n});\n\n/** A platform-hosted assistant, registered against the cloud API. */\nconst CloudAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"cloud\"),\n});\n\n/** A self-hosted remote assistant, reached at its own address. */\nconst CustomAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"custom\"),\n /** Host address of the custom remote's gateway. */\n ipAddress: z.string(),\n /** Gateway port on the custom remote. */\n port: z.number(),\n});\n\n/**\n * A Baseten sandbox entry: the sandbox server URL and the sandbox-internal\n * gateway port are pinned at creation. When the hatch also minted the\n * gateway's private preview, `previewUrl` is the gateway's canonical\n * address — the preview edge opens the port dynamically and guards it with\n * a preview token, leaving `Authorization` free for the gateway's own\n * bearer end to end. Entries without one (tokenless hatches, legacy) ride\n * the `{sandboxUrl}/port/{port}` route with the sandbox access token.\n */\nconst BasetenAssistantSchema = BaseAssistantSchema.extend({\n cloud: z.literal(\"baseten\"),\n /** The Baseten sandbox server URL; the port route rides on it. */\n sandboxUrl: z.string(),\n /** The sandbox-internal gateway port, piped in as `GATEWAY_PORT` at creation. */\n port: z.number(),\n /** The gateway's private preview URL, minted at hatch when a token resolves. */\n previewUrl: z.string().optional(),\n});\n\n/**\n * Route absent and unknown topology values to the local default before the\n * union discriminates, keeping the on-disk contract permissive about clouds\n * this build has never heard of.\n */\n/**\n * The one preprocess the entry union parses through. Routes absent and\n * unknown topology values to the local default before the union\n * discriminates, and backfills the legacy `resources.gatewayPort` onto\n * `port` — but only when the flat `port` field would fail the number\n * schema (absent or not a number): a valid port always wins. Zod has no\n * field-level sibling fallback, so the object-level preprocess is the\n * supported surface for this.\n */\nfunction normalizeEntry(entry: unknown): unknown {\n if (typeof entry !== \"object\" || entry === null) return entry;\n let rec = entry as Record<string, unknown>;\n const cloud = rec.cloud;\n if (!(typeof cloud === \"string\" && RemoteSchema.safeParse(cloud).success)) {\n rec = { ...rec, cloud: \"local\" };\n }\n if (rec.port === undefined) {\n // The flat port failed the required schema (absent on a legacy or bare\n // entry): fall back to the legacy resources.gatewayPort, else the\n // gateway default. A mistyped port never falls back — a bad modeled\n // field still drops the entry.\n const resources = rec.resources;\n const gatewayPort =\n resources && typeof resources === \"object\"\n ? (resources as Record<string, unknown>).gatewayPort\n : undefined;\n rec = {\n ...rec,\n port: typeof gatewayPort === \"number\" ? gatewayPort : GATEWAY_PORT,\n };\n }\n return rec;\n}\n\nexport const LockfileAssistantSchema = z.preprocess(\n normalizeEntry,\n z.discriminatedUnion(\"cloud\", [\n LocalAssistantSchema,\n DockerAssistantSchema,\n AppleContainerAssistantSchema,\n CloudAssistantSchema,\n CustomAssistantSchema,\n BasetenAssistantSchema,\n ]),\n);\n\n/**\n * A validated, normalized assistant entry — a discriminated union on\n * `cloud`, so each topology carries exactly the fields it uses: a baseten\n * entry's `sandboxUrl`/`port` are always defined, a docker entry's\n * `containerInfo` reads without touching unrelated topologies, and absent or\n * unknown on-disk clouds route to the local branch.\n */\nexport type LockfileAssistant = z.infer<typeof LockfileAssistantSchema>;\n\nexport type LocalAssistant = z.infer<typeof LocalAssistantSchema>;\nexport type DockerAssistant = z.infer<typeof DockerAssistantSchema>;\nexport type AppleContainerAssistant = z.infer<\n typeof AppleContainerAssistantSchema\n>;\nexport type CloudAssistant = z.infer<typeof CloudAssistantSchema>;\nexport type CustomAssistant = z.infer<typeof CustomAssistantSchema>;\nexport type BasetenAssistant = z.infer<typeof BasetenAssistantSchema>;\n\n/** Whether the entry is a platform-hosted assistant. */\nexport function isCloudEntry(\n entry: LockfileAssistant,\n): entry is CloudAssistant {\n return entry.cloud === \"cloud\";\n}\n\n/** Whether the entry is a docker-hosted assistant. */\nexport function isDockerEntry(\n entry: LockfileAssistant,\n): entry is DockerAssistant {\n return entry.cloud === \"docker\";\n}\n\n/** Whether the entry is an apple-container assistant. */\nexport function isAppleContainerEntry(\n entry: LockfileAssistant,\n): entry is AppleContainerAssistant {\n return entry.cloud === \"apple-container\";\n}\n\n/** Whether the entry is a plain on-machine assistant. */\nexport function isLocalEntry(\n entry: LockfileAssistant,\n): entry is LocalAssistant {\n return entry.cloud === \"local\";\n}\n\n/**\n * A CLI-managed OS process recorded at the lockfile root under `tunnel`:\n * the auto-tunnel agent fronting the edge. `cadet ps` renders it alongside\n * the per-assistant process trees, and the stop paths verify the pid before\n * signaling it.\n */\nexport const TunnelProcessRecordSchema = z.object({\n pid: z.number(),\n /** Which tunnel provider owns the process. */\n provider: z.enum(TUNNEL_PROVIDERS),\n startedAt: z.string(),\n /** The public URL the tunnel agent serves. */\n publicUrl: z.string().optional(),\n});\nexport type TunnelProcessRecord = z.infer<typeof TunnelProcessRecordSchema>;\n\n/**\n * A CLI-managed OS process recorded at the lockfile root under `app`: the\n * app server (web artifacts, `/v1` proxying, the outer shell). Shares\n * nothing with the tunnel record beyond the pid bookkeeping — a tunnel\n * serves a URL, the app server serves a port.\n */\nexport const AppProcessRecordSchema = z.object({\n /** The app server's bookkeeping, present while it runs. */\n pid: z.number().optional(),\n startedAt: z.string().optional(),\n /** Listening port for the app server. */\n port: z.number(),\n});\nexport type AppProcessRecord = z.infer<typeof AppProcessRecordSchema>;\n\n/**\n * Renderer-facing result of a lockfile write, returned across the host bridge.\n * Carries no HTTP-style status — hosts map that away because the renderer\n * surfaces failures by message alone.\n */\nexport type LockfileWriteResult =\n | { ok: true; lockfile: Lockfile }\n | { ok: false; error: string };\n\nexport const LockfileSchema = z.looseObject({\n assistants: z\n .array(LockfileAssistantSchema.nullable().catch(null))\n .catch([])\n .transform((entries) =>\n entries.filter((entry): entry is LockfileAssistant => entry !== null),\n ),\n activeAssistant: z.union([z.string(), z.null()]).catch(null),\n tunnel: TunnelProcessRecordSchema.optional().catch(undefined),\n app: AppProcessRecordSchema.optional().catch(undefined),\n});\n\n/**\n * A validated, normalized lockfile — this schema's own output. Loose at the\n * root so the CLI's read-modify-write round-trip preserves the root keys it\n * owns and anything a newer writer added; readers key on the\n * modeled fields.\n */\nexport type Lockfile = z.infer<typeof LockfileSchema>;\n\n/**\n * Coerce parsed JSON into a validated {@link Lockfile}. Total and non-throwing:\n * the whole file parses through {@link LockfileSchema} — an entry that fails\n * validation is dropped whole (one malformed entry can't discard the file), a\n * missing or non-array `assistants` becomes `[]`, a non-string\n * `activeAssistant` becomes null, and a non-object root becomes an empty\n * lockfile.\n */\nexport function parseLockfile(raw: unknown): Lockfile {\n const parsed = LockfileSchema.safeParse(raw);\n return parsed.success ? parsed.data : LockfileSchema.parse({});\n}\n","import { z } from \"zod\";\n\nimport { RemoteSchema } from \"@mycadet/local-mode/contract\";\n\nfunction publicUrl(value: string): boolean {\n if (/[\\\\\\u0000-\\u0020]/.test(value) || value.startsWith(\"//\")) {\n return false;\n }\n if (\n (!value.startsWith(\"/\") &&\n !/^https?:\\/\\//i.test(value) &&\n value.includes(\":\")) ||\n /(?:^|\\/)(?:\\.|%2e){1,2}(?:\\/|$)/i.test(value)\n ) {\n return false;\n }\n try {\n const url = new URL(value, \"https://app.example\");\n if (url.username || url.password || url.search || url.hash) {\n return false;\n }\n return (\n value.startsWith(\"/\") ||\n url.protocol === \"https:\" ||\n (url.protocol === \"http:\" &&\n [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n );\n } catch {\n return false;\n }\n}\n\nexport const PublicUrlSchema = z\n .string()\n .min(1)\n .refine(\n publicUrl,\n \"Expected a public host URL without credentials or query parameters.\",\n );\nexport const ResolvedAssistantSchema = z.object({\n id: z.string().min(1),\n version: z.string().min(1),\n});\n\nexport const AssistantChoiceSchema = z.object({\n id: z.string().min(1),\n name: z\n .string()\n .nullish()\n .transform((name) => name?.trim() || \"New Assistant\"),\n /** The cloud's synced avatar thumbnail; null means the cloud holds none. */\n avatar_url: z.string().nullish(),\n /** When the cloud hatched the assistant (ISO 8601); null when unknown. */\n created: z.string().nullish(),\n /**\n * The assistant's own hosting kind, stamped per row by the serving control\n * plane — the cloud lists its assistants \"cloud\", a self-hosted edge\n * stamps its lockfile cloud. Unknown or absent values (servers predating\n * the stamp, a hostile row) fall back to undefined; the chooser then uses\n * the build's own remote.\n */\n remote: RemoteSchema.nullish().catch(() => undefined),\n /**\n * The assistant's admin-access opt-in (the owner's toggle on the\n * management page writes it through the operator's PATCH row; the\n * operator's list stamps it from the lockfile entry, the cloud's list\n * union from the cloud row). Absent values — servers predating the\n * field — decode to undefined, which the panel reads as not available.\n */\n allow_admin_access: z\n .boolean()\n .nullish()\n .catch(() => undefined),\n});\n\nexport const AssistantResolutionSchema = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"ready\"), assistant: ResolvedAssistantSchema }),\n z.object({ status: z.literal(\"notReady\") }),\n z.object({ status: z.literal(\"unavailable\") }),\n // Selection carries no rows by design — the rows are the list contract's;\n // this arm just sends the shell to the selection page.\n z.object({ status: z.literal(\"selection\") }),\n z.object({ status: z.literal(\"empty\") }),\n z.object({ status: z.literal(\"unauthenticated\") }),\n]);\n/**\n * What the list endpoint alone can answer: the choices on the machine\n * (nothing hatched is the empty arm), or no session to read them with. The chooser renders off this contract only —\n * the single-assistant resolution arms (ready/notReady/unavailable/empty)\n * belong to the shell's resolution flow, whose own selection arm carries no\n * rows — it routes here.\n */\nexport const AssistantListSchema = z.discriminatedUnion(\"status\", [\n z.object({\n status: z.literal(\"selection\"),\n assistants: z.array(AssistantChoiceSchema),\n }),\n z.object({ status: z.literal(\"empty\") }),\n z.object({ status: z.literal(\"unauthenticated\") }),\n]);\nexport type ResolvedAssistant = z.infer<typeof ResolvedAssistantSchema>;\nexport type AssistantResolution = z.infer<typeof AssistantResolutionSchema>;\nexport type AssistantList = z.infer<typeof AssistantListSchema>;\nexport const AssistantNavigationSchema = z.object({\n source: z.literal(\"mycadet-web-nav\"),\n nav: z.enum([\"push\", \"replace\", \"pop\"]),\n path: z.string(),\n});\n\n/**\n * The frame's HOST-navigation request: the assistant bundle opening a\n * surface outside its own url space (the account area — the Doctor page).\n * The frame listener allowlists `/account/*`; the schema only fixes the\n * message's shape.\n */\nexport const HostNavigationSchema = z.object({\n source: z.literal(\"mycadet-web-host-nav\"),\n path: z.string(),\n});\n\nexport const ShareFeedbackRequestSchema = z.object({\n source: z.literal(\"mycadet-web-share-feedback\"),\n});\n\n/**\n * A host-proxy frame (`host_*_request` / `host_*_cancel`) the assistant\n * bundle received on its event stream and cannot serve itself — the\n * executors live in the desktop main process. The frame forwards the raw\n * message; the app shell posts it over the `cadet.hostProxy` bridge.\n */\nexport const HostProxyForwardSchema = z.object({\n source: z.literal(\"mycadet-web-host-proxy-forward\"),\n message: z.record(z.string(), z.unknown()),\n});\n","import { z } from \"zod\";\n\nimport {\n AssistantListSchema,\n AssistantResolutionSchema,\n PublicUrlSchema,\n type AssistantList,\n type AssistantResolution,\n} from \"./resolution-contract\";\n\nfunction decode<T>(schema: z.ZodType<T>, payload: unknown): T {\n const result = schema.safeParse(payload);\n if (!result.success) {\n // The zod error object carries the path and the per-field failures —\n // surface them so a contract drift names the field that moved.\n throw new Error(\n `Invalid assistant API data.\\n${z.prettifyError(result.error)}`,\n );\n }\n return result.data;\n}\n\nexport interface AssistantRequest {\n apiBaseUrl?: string;\n assistantId?: string;\n signal: AbortSignal;\n}\n\nconst unauthenticated = Symbol(\"unauthenticated\");\nconst notReady = Symbol(\"not ready\");\nconst unavailable = Symbol(\"unavailable\");\n\nfunction createClient({ apiBaseUrl = \"/\", signal }: AssistantRequest) {\n // The shell is same-origin by construction — every host (the desktop\n // protocol, the web dev server, the cloud takeover) proxies the API at\n // the page's own origin. Read inside: SSR renders the shell without a\n // window, and the origin is a browser fact.\n const origin = window.location.origin;\n const base = new URL(decode(PublicUrlSchema, apiBaseUrl), origin);\n base.pathname = base.pathname.replace(/\\/*$/, \"/\");\n const headers = new Headers({ Accept: \"application/json\" });\n async function get(path: string) {\n signal.throwIfAborted();\n const requestUrl = new URL(path, base);\n const response = await fetch(requestUrl, {\n headers,\n signal,\n credentials: \"include\",\n });\n signal.throwIfAborted();\n if (response.status === 401) {\n return unauthenticated;\n }\n if (response.status === 409) {\n return notReady;\n }\n if (response.status === 410) {\n return unavailable;\n }\n if (!response.ok) {\n console.error(\n `Assistant request failed: ${response.status} ${response.headers.get(\"content-type\") ?? \"\"} from ${requestUrl.href}`,\n );\n throw new Error(\n `Assistant request failed: ${response.status} from ${requestUrl.href}`,\n );\n }\n const payload: unknown = await response.json().catch((error) => {\n console.error(\n `Assistant response was not JSON from ${requestUrl.href}: ${error}`,\n );\n throw error;\n });\n signal.throwIfAborted();\n return payload;\n }\n return { base, get };\n}\n\n/**\n * The chooser's list: ONE call to the same-origin list endpoint — the\n * unscoped `v1/assistants/` is the list CONTRACT (the machine's rows\n * without a credential field), and the client just decodes it. No session\n * (401) reads as the contract's own unauthenticated arm.\n */\nexport async function listAssistantChoices(\n options: AssistantRequest,\n): Promise<AssistantList> {\n const client = createClient(options);\n const payload = await client.get(\"v1/assistants/\");\n if (payload === unauthenticated) {\n return { status: \"unauthenticated\" };\n }\n return decode(AssistantListSchema, payload);\n}\n\n/**\n * The shell's resolution: ONE call to the same-origin assistant resolution\n * endpoint — the serving host's operation composes the whole union (the\n * lockfile's choice, the entry gateway's identity and the caller's own auth\n * verdict) and the client just decodes it. The status-code arms stay for\n * hosts whose operation forwards a platform detail's own codes, and for\n * older stacks whose baked metadata predates the union.\n */\nexport async function resolveAssistant(\n options: AssistantRequest,\n): Promise<AssistantResolution> {\n const client = createClient(options);\n const payload = await client.get(\n options.assistantId\n ? `v1/assistants/${encodeURIComponent(options.assistantId)}/`\n : \"v1/assistant\",\n );\n if (payload === unauthenticated) {\n return { status: \"unauthenticated\" };\n }\n if (payload === notReady) {\n return { status: \"notReady\" };\n }\n if (payload === unavailable) {\n return { status: \"unavailable\" };\n }\n return decode(AssistantResolutionSchema, payload);\n}\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./jsx-runtime-pmtNMKr4.js";import{r as t}from"./i18n-DFnZ8-i_.js";import{t as n}from"./confirm-dialog-CIACfqv5.js";import{r}from"./api-CQhZI0Rx.js";import{n as i,t as a}from"./selected-assistant-storage-B41ut3io.js";var o=e();function s({open:e,error:r,isPending:i,onConfirm:a,onCancel:s}){let{t:c}=t();return(0,o.jsx)(n,{open:e,title:c(`retireConfirmDialog.title`),message:c(`retireConfirmDialog.message`),error:r,confirmLabel:c(`retireConfirmDialog.confirmLabel`),destructive:!0,isPending:i,onConfirm:a,onCancel:s})}async function c(e){let t=await r(e);return!t.ok&&t.status!==404?{ok:!1,error:t.error.detail}:(i()===e&&a(),{ok:!0})}export{s as n,c as t};
2
+ //# sourceMappingURL=retire-assistant-D4ZGhhiW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retire-assistant-D4ZGhhiW.js","names":[],"sources":["../../../src/components/retire-confirm-dialog.tsx","../../../src/assistant/retire-assistant.ts"],"sourcesContent":["import { ConfirmDialog } from \"@mycadet/design-library/components/confirm-dialog\";\nimport { useTranslation } from \"@app/i18n\";\n\n/**\n * Canonical destructive confirmation for retiring an assistant — port of\n * web's `RetireConfirmDialog`, so the irreversible-action warning reads the\n * same on every surface that retires through it.\n */\nexport function RetireConfirmDialog({\n open,\n error,\n isPending,\n onConfirm,\n onCancel,\n}: {\n open: boolean;\n /** Inline failure line; the dialog stays open so the user can retry. */\n error?: string | null;\n isPending: boolean;\n onConfirm: () => void;\n onCancel: () => void;\n}) {\n const { t } = useTranslation();\n return (\n <ConfirmDialog\n open={open}\n title={t(\"retireConfirmDialog.title\")}\n message={t(\"retireConfirmDialog.message\")}\n error={error}\n confirmLabel={t(\"retireConfirmDialog.confirmLabel\")}\n destructive\n isPending={isPending}\n onConfirm={onConfirm}\n onCancel={onCancel}\n />\n );\n}\n","import { retireAssistantById } from \"@app/assistant/api\";\nimport {\n clearSelectedAssistantId,\n readSelectedAssistantId,\n} from \"@app/assistant/selected-assistant-storage\";\n\nexport type RetireAssistantResult = { ok: true } | { ok: false; error: string };\n\n/**\n * Permanently retire an assistant through the scoped surface's one retire\n * endpoint, for every entry type: the request is same-origin, and the serving\n * host decides how to honor it (the desktop proxy and the dev server run the\n * host CLI for on-machine entries; the cloud retires platform rows). The\n * bundle never branches on entry type.\n *\n * A 404 means the assistant is already gone — the same success web's\n * retire-service granted, so a stale chooser row still clears instead of\n * wedging the dialog on an error nothing can fix. Retiring the stored\n * selection drops it, mirroring web's active-id cleanup: without that, the\n * shell could admit a retired assistant with nothing behind it.\n */\nexport async function retireAssistant(\n assistantId: string,\n): Promise<RetireAssistantResult> {\n const result = await retireAssistantById(assistantId);\n if (!result.ok && result.status !== 404) {\n return { ok: false, error: result.error.detail };\n }\n if (readSelectedAssistantId() === assistantId) {\n clearSelectedAssistantId();\n }\n return { ok: true };\n}\n"],"mappings":"qPAQA,SAAgB,EAAoB,CAClC,OACA,QACA,YACA,YACA,YAQC,CACD,GAAM,CAAE,KAAM,GAAgB,CAC9B,OACE,EAAA,EAAA,KAAC,EAAD,CACQ,OACN,MAAO,EAAE,4BAA4B,CACrC,QAAS,EAAE,8BAA8B,CAClC,QACP,aAAc,EAAE,mCAAmC,CACnD,YAAA,GACW,YACA,YACD,WACV,CAAA,CCbN,eAAsB,EACpB,EACgC,CAChC,IAAM,EAAS,MAAM,EAAoB,EAAY,CAOrD,MANI,CAAC,EAAO,IAAM,EAAO,SAAW,IAC3B,CAAE,GAAI,GAAO,MAAO,EAAO,MAAM,OAAQ,EAE9C,GAAyB,GAAK,GAChC,GAA0B,CAErB,CAAE,GAAI,GAAM"}
@@ -1,2 +1,2 @@
1
- import{i as e}from"./routes-bHGywETD.js";var t=/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;function n(n,r){if(!n)return r;if(t.test(n)){try{let t=new URL(n);if(t.protocol===`https:`&&e(t.hostname))return n}catch{}return r}return n.startsWith(`//`)||n.includes(`\\`)||!n.startsWith(`/`)?r:n}export{n as t};
2
- //# sourceMappingURL=return-to-DazNKK_L.js.map
1
+ import{i as e}from"./routes-CfiHTSsp.js";var t=/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;function n(n,r){if(!n)return r;if(t.test(n)){try{let t=new URL(n);if(t.protocol===`https:`&&e(t.hostname))return n}catch{}return r}return n.startsWith(`//`)||n.includes(`\\`)||!n.startsWith(`/`)?r:n}export{n as t};
2
+ //# sourceMappingURL=return-to-D0IPrnXo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"return-to-DazNKK_L.js","names":[],"sources":["../../../src/utils/return-to.ts"],"sourcesContent":["import { isCadetDomain } from \"@app/utils/domains\";\n\nconst ABSOLUTE_URL_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//;\n\n/**\n * Sanitize a `returnTo` URL parameter to prevent open-redirect attacks.\n *\n * Relative paths (strings starting with `/`) and absolute URLs whose\n * hostname belongs to the mycadet.ai domain family are allowed through.\n * All other absolute URLs (`https://…`, `//…`), non-path strings,\n * and nullish / empty values resolve to the provided `fallback`.\n */\nexport function sanitizeReturnTo(\n value: string | null | undefined,\n fallback: string,\n): string {\n if (!value) {\n return fallback;\n }\n\n // Allow absolute URLs from any *.mycadet.ai domain.\n // This is safe because we control all mycadet.ai subdomains, and works\n // in both server and client contexts (no env var dependency).\n //\n // Important: only treat values that START with a URL scheme as absolute.\n // Relative paths can legitimately contain `https://...` inside query params\n // (e.g. `/accounts/chrome-extension/start?redirect_uri=https://...`).\n if (ABSOLUTE_URL_SCHEME_RE.test(value)) {\n try {\n const url = new URL(value);\n if (url.protocol === \"https:\" && isCadetDomain(url.hostname)) {\n return value;\n }\n } catch {\n // Malformed URL — fall through to block\n }\n return fallback;\n }\n\n // Block protocol-relative URLs (e.g. \"//evil.com\")\n if (value.startsWith(\"//\")) {\n return fallback;\n }\n\n // Block backslash-based open redirects (e.g. \"/\\evil.com\").\n // Browsers normalise `\\` to `/` per the WHATWG URL spec, so `/\\` is\n // treated as `//` — a protocol-relative URL that navigates off-site.\n if (value.includes(\"\\\\\")) {\n return fallback;\n }\n\n // Only allow paths that start with \"/\"\n if (!value.startsWith(\"/\")) {\n return fallback;\n }\n\n return value;\n}\n"],"mappings":"yCAEA,IAAM,EAAyB,gCAU/B,SAAgB,EACd,EACA,EACQ,CACR,GAAI,CAAC,EACH,OAAO,EAUT,GAAI,EAAuB,KAAK,EAAM,CAAE,CACtC,GAAI,CACF,IAAM,EAAM,IAAI,IAAI,EAAM,CAC1B,GAAI,EAAI,WAAa,UAAY,EAAc,EAAI,SAAS,CAC1D,OAAO,OAEH,EAGR,OAAO,EAoBT,OAhBI,EAAM,WAAW,KAAK,EAOtB,EAAM,SAAS,KAAK,EAKpB,CAAC,EAAM,WAAW,IAAI,CACjB,EAGF"}
1
+ {"version":3,"file":"return-to-D0IPrnXo.js","names":[],"sources":["../../../src/utils/return-to.ts"],"sourcesContent":["import { isCadetDomain } from \"@app/utils/domains\";\n\nconst ABSOLUTE_URL_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//;\n\n/**\n * Sanitize a `returnTo` URL parameter to prevent open-redirect attacks.\n *\n * Relative paths (strings starting with `/`) and absolute URLs whose\n * hostname belongs to the mycadet.ai domain family are allowed through.\n * All other absolute URLs (`https://…`, `//…`), non-path strings,\n * and nullish / empty values resolve to the provided `fallback`.\n */\nexport function sanitizeReturnTo(\n value: string | null | undefined,\n fallback: string,\n): string {\n if (!value) {\n return fallback;\n }\n\n // Allow absolute URLs from any *.mycadet.ai domain.\n // This is safe because we control all mycadet.ai subdomains, and works\n // in both server and client contexts (no env var dependency).\n //\n // Important: only treat values that START with a URL scheme as absolute.\n // Relative paths can legitimately contain `https://...` inside query params\n // (e.g. `/accounts/chrome-extension/start?redirect_uri=https://...`).\n if (ABSOLUTE_URL_SCHEME_RE.test(value)) {\n try {\n const url = new URL(value);\n if (url.protocol === \"https:\" && isCadetDomain(url.hostname)) {\n return value;\n }\n } catch {\n // Malformed URL — fall through to block\n }\n return fallback;\n }\n\n // Block protocol-relative URLs (e.g. \"//evil.com\")\n if (value.startsWith(\"//\")) {\n return fallback;\n }\n\n // Block backslash-based open redirects (e.g. \"/\\evil.com\").\n // Browsers normalise `\\` to `/` per the WHATWG URL spec, so `/\\` is\n // treated as `//` — a protocol-relative URL that navigates off-site.\n if (value.includes(\"\\\\\")) {\n return fallback;\n }\n\n // Only allow paths that start with \"/\"\n if (!value.startsWith(\"/\")) {\n return fallback;\n }\n\n return value;\n}\n"],"mappings":"yCAEA,IAAM,EAAyB,gCAU/B,SAAgB,EACd,EACA,EACQ,CACR,GAAI,CAAC,EACH,OAAO,EAUT,GAAI,EAAuB,KAAK,EAAM,CAAE,CACtC,GAAI,CACF,IAAM,EAAM,IAAI,IAAI,EAAM,CAC1B,GAAI,EAAI,WAAa,UAAY,EAAc,EAAI,SAAS,CAC1D,OAAO,OAEH,EAGR,OAAO,EAoBT,OAhBI,EAAM,WAAW,KAAK,EAOtB,EAAM,SAAS,KAAK,EAKpB,CAAC,EAAM,WAAW,IAAI,CACjB,EAGF"}
@@ -1,2 +1,2 @@
1
- import{m as e}from"./i18n-BaPIfk2c.js";import{d as t,l as n,o as r,p as i,r as a}from"./schemas-BZBjRX4t.js";import{n as o}from"./api-Di6JRcb2.js";var s=`device:onboarded_assistants`,c=t(i(),i()),l=n({key:r(s),value:i().nullable()}),u;typeof window<`u`&&(window.addEventListener(`cadet:pref-changed`,e=>{if(!(e instanceof CustomEvent))return;let t=l.safeParse(e.detail);if(t.success)try{let e=c.safeParse(JSON.parse(t.data.value??`{}`));e.success&&(u=e.data)}catch{}}),window.addEventListener(`storage`,e=>{(e.key===null||e.key===s)&&(u=void 0)}));function d(e){return u?u[e]||void 0:f()[e]||void 0}function f(){try{let t=c.safeParse(JSON.parse(e(s,`{}`)));return t.success?t.data:{}}catch{return{}}}var p=n({assistants:a(n({assistantId:i().min(1),onboardedAt:i().optional(),hatchedAt:i().optional()}))}),m=10080*60*1e3;function h(e){if(e.onboardedAt||d(e.id))return!0;let t=Date.parse(e.created??``);return Number.isFinite(t)&&Date.now()-t>=m}async function g(e={}){let t=e.signal??AbortSignal.timeout(5e3);if(t.aborted)return!1;let n,r=new Promise(e=>{n=()=>e(!1),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([_(t),r])}catch{return!1}finally{t.removeEventListener(`abort`,n)}}async function _(e){try{let t=await fetch(`/v1/assistants/`,{signal:e}),n=t.ok?await t.json():null,r=p.safeParse(n);if(r.success&&r.data.assistants.some(e=>h({id:e.assistantId,created:e.hatchedAt,onboardedAt:e.onboardedAt})))return!0}catch{}if(e.aborted)return!1;let t=await o({signal:e});return t.ok&&t.data.some(h)}export{g as t};
2
- //# sourceMappingURL=returning-user-CMNG1o-y.js.map
1
+ import{m as e}from"./i18n-DFnZ8-i_.js";import{d as t,l as n,o as r,p as i,r as a}from"./schemas-BYL1R3CL.js";import{n as o}from"./api-CQhZI0Rx.js";var s=`device:onboarded_assistants`,c=t(i(),i()),l=n({key:r(s),value:i().nullable()}),u;typeof window<`u`&&(window.addEventListener(`cadet:pref-changed`,e=>{if(!(e instanceof CustomEvent))return;let t=l.safeParse(e.detail);if(t.success)try{let e=c.safeParse(JSON.parse(t.data.value??`{}`));e.success&&(u=e.data)}catch{}}),window.addEventListener(`storage`,e=>{(e.key===null||e.key===s)&&(u=void 0)}));function d(e){return u?u[e]||void 0:f()[e]||void 0}function f(){try{let t=c.safeParse(JSON.parse(e(s,`{}`)));return t.success?t.data:{}}catch{return{}}}var p=n({assistants:a(n({assistantId:i().min(1),onboardedAt:i().optional(),hatchedAt:i().optional()}))}),m=10080*60*1e3;function h(e){if(e.onboardedAt||d(e.id))return!0;let t=Date.parse(e.created??``);return Number.isFinite(t)&&Date.now()-t>=m}async function g(e={}){let t=e.signal??AbortSignal.timeout(5e3);if(t.aborted)return!1;let n,r=new Promise(e=>{n=()=>e(!1),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([_(t),r])}catch{return!1}finally{t.removeEventListener(`abort`,n)}}async function _(e){try{let t=await fetch(`/v1/assistants/`,{signal:e}),n=t.ok?await t.json():null,r=p.safeParse(n);if(r.success&&r.data.assistants.some(e=>h({id:e.assistantId,created:e.hatchedAt,onboardedAt:e.onboardedAt})))return!0}catch{}if(e.aborted)return!1;let t=await o({signal:e});return t.ok&&t.data.some(h)}export{g as t};
2
+ //# sourceMappingURL=returning-user-DJy7811e.js.map