@thebriangao/totem 1.4.4 → 2.0.0

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 (763) hide show
  1. package/.dev.vars.example +5 -0
  2. package/.dockerignore +5 -0
  3. package/.env.example +29 -20
  4. package/CHANGELOG.md +99 -1
  5. package/CONTRIBUTING.md +48 -116
  6. package/Dockerfile +46 -12
  7. package/README.md +172 -498
  8. package/SECURITY.md +36 -59
  9. package/TOOLS.md +448 -311
  10. package/WHOOP.md +497 -2659
  11. package/assets/brand/SOURCES.md +38 -0
  12. package/assets/brand/totem.png +0 -0
  13. package/assets/brand/totem.svg +13 -0
  14. package/assets/fonts/Manrope-OFL.txt +93 -0
  15. package/assets/fonts/manrope-latin.woff2 +0 -0
  16. package/dist/build_info.js +5 -0
  17. package/dist/build_info.js.map +1 -0
  18. package/dist/cli/app.js +675 -0
  19. package/dist/cli/app.js.map +1 -0
  20. package/dist/cli/auth.js +297 -0
  21. package/dist/cli/auth.js.map +1 -0
  22. package/dist/cli/auth_flow.js +268 -0
  23. package/dist/cli/auth_flow.js.map +1 -0
  24. package/dist/cli/browser_login.js +368 -0
  25. package/dist/cli/browser_login.js.map +1 -0
  26. package/dist/cli/clients.js +403 -0
  27. package/dist/cli/clients.js.map +1 -0
  28. package/dist/cli/deploy_record.js +96 -0
  29. package/dist/cli/deploy_record.js.map +1 -0
  30. package/dist/cli/index.js +39 -575
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/links.js +28 -0
  33. package/dist/cli/links.js.map +1 -0
  34. package/dist/cli/logo.js +63 -0
  35. package/dist/cli/logo.js.map +1 -0
  36. package/dist/cli/setup.js +1157 -1017
  37. package/dist/cli/setup.js.map +1 -1
  38. package/dist/cli/spawn.js +80 -0
  39. package/dist/cli/spawn.js.map +1 -0
  40. package/dist/cli/sys.js +219 -0
  41. package/dist/cli/sys.js.map +1 -0
  42. package/dist/cli/ui.js +712 -463
  43. package/dist/cli/ui.js.map +1 -1
  44. package/dist/cli/update.js +425 -282
  45. package/dist/cli/update.js.map +1 -1
  46. package/dist/cloudflare/token_store.js +48 -0
  47. package/dist/cloudflare/token_store.js.map +1 -0
  48. package/dist/cloudflare/worker.js +155 -0
  49. package/dist/cloudflare/worker.js.map +1 -0
  50. package/dist/data/behaviors.js +2733 -617
  51. package/dist/data/behaviors.js.map +1 -1
  52. package/dist/data/endpoint_catalog.js +2681 -0
  53. package/dist/data/endpoint_catalog.js.map +1 -0
  54. package/dist/data/exercises.js +373 -4859
  55. package/dist/data/exercises.js.map +1 -1
  56. package/dist/data/garments.js +19 -0
  57. package/dist/data/garments.js.map +1 -0
  58. package/dist/data/sports.js +219 -208
  59. package/dist/data/sports.js.map +1 -1
  60. package/dist/lib/activity_list.js +123 -0
  61. package/dist/lib/activity_list.js.map +1 -0
  62. package/dist/lib/activity_records.js +195 -0
  63. package/dist/lib/activity_records.js.map +1 -0
  64. package/dist/lib/activity_results.js +44 -0
  65. package/dist/lib/activity_results.js.map +1 -0
  66. package/dist/lib/activity_types.js +164 -0
  67. package/dist/lib/activity_types.js.map +1 -0
  68. package/dist/lib/brand.js +63 -0
  69. package/dist/lib/brand.js.map +1 -0
  70. package/dist/lib/clock.js +24 -0
  71. package/dist/lib/clock.js.map +1 -0
  72. package/dist/lib/coach_session.js +345 -0
  73. package/dist/lib/coach_session.js.map +1 -0
  74. package/dist/lib/concurrency.js.map +1 -1
  75. package/dist/lib/dates.js +19 -0
  76. package/dist/lib/dates.js.map +1 -1
  77. package/dist/lib/env_file.js +195 -0
  78. package/dist/lib/env_file.js.map +1 -0
  79. package/dist/lib/health_plans_write.js +44 -0
  80. package/dist/lib/health_plans_write.js.map +1 -0
  81. package/dist/lib/heart_rate.js +34 -0
  82. package/dist/lib/heart_rate.js.map +1 -0
  83. package/dist/lib/highlight.js +81 -0
  84. package/dist/lib/highlight.js.map +1 -0
  85. package/dist/lib/install_links.js +47 -0
  86. package/dist/lib/install_links.js.map +1 -0
  87. package/dist/lib/instant.js +50 -0
  88. package/dist/lib/instant.js.map +1 -0
  89. package/dist/lib/journal_behaviors.js +382 -0
  90. package/dist/lib/journal_behaviors.js.map +1 -0
  91. package/dist/lib/lift_catalog.js +218 -0
  92. package/dist/lib/lift_catalog.js.map +1 -0
  93. package/dist/lib/lift_history.js +66 -0
  94. package/dist/lib/lift_history.js.map +1 -0
  95. package/dist/lib/lift_sets.js +146 -0
  96. package/dist/lib/lift_sets.js.map +1 -0
  97. package/dist/lib/lift_tool.js +20 -0
  98. package/dist/lib/lift_tool.js.map +1 -0
  99. package/dist/lib/profile_settings.js +101 -0
  100. package/dist/lib/profile_settings.js.map +1 -0
  101. package/dist/lib/screen_content.js +44 -0
  102. package/dist/lib/screen_content.js.map +1 -0
  103. package/dist/lib/timezone.js +48 -6
  104. package/dist/lib/timezone.js.map +1 -1
  105. package/dist/lib/walk.js +6 -1
  106. package/dist/lib/walk.js.map +1 -1
  107. package/dist/lib/weight_readings.js +61 -0
  108. package/dist/lib/weight_readings.js.map +1 -0
  109. package/dist/projections/activities.js +193 -0
  110. package/dist/projections/activities.js.map +1 -0
  111. package/dist/projections/alarm_schedule.js +102 -0
  112. package/dist/projections/alarm_schedule.js.map +1 -0
  113. package/dist/projections/coach.js +203 -0
  114. package/dist/projections/coach.js.map +1 -0
  115. package/dist/projections/community.js +165 -0
  116. package/dist/projections/community.js.map +1 -0
  117. package/dist/projections/health_features.js +167 -0
  118. package/dist/projections/health_features.js.map +1 -0
  119. package/dist/projections/hormonal_insights.js +239 -0
  120. package/dist/projections/hormonal_insights.js.map +1 -0
  121. package/dist/projections/journal_v2.js +157 -0
  122. package/dist/projections/journal_v2.js.map +1 -0
  123. package/dist/projections/lift_cards.js +115 -0
  124. package/dist/projections/lift_cards.js.map +1 -0
  125. package/dist/projections/lift_exercise_v2.js +131 -0
  126. package/dist/projections/lift_exercise_v2.js.map +1 -0
  127. package/dist/projections/lift_library_v2.js +67 -0
  128. package/dist/projections/lift_library_v2.js.map +1 -0
  129. package/dist/projections/lift_sessions.js +211 -0
  130. package/dist/projections/lift_sessions.js.map +1 -0
  131. package/dist/projections/memory.js +95 -0
  132. package/dist/projections/memory.js.map +1 -0
  133. package/dist/projections/milestones.js +119 -0
  134. package/dist/projections/milestones.js.map +1 -0
  135. package/dist/projections/profile_v2.js +150 -0
  136. package/dist/projections/profile_v2.js.map +1 -0
  137. package/dist/projections/settings_v2.js +153 -0
  138. package/dist/projections/settings_v2.js.map +1 -0
  139. package/dist/projections/sleep.js +4 -21
  140. package/dist/projections/sleep.js.map +1 -1
  141. package/dist/projections/v2/calendar.js +43 -0
  142. package/dist/projections/v2/calendar.js.map +1 -0
  143. package/dist/projections/v2/core_common.js +86 -0
  144. package/dist/projections/v2/core_common.js.map +1 -0
  145. package/dist/projections/v2/core_home.js +136 -0
  146. package/dist/projections/v2/core_home.js.map +1 -0
  147. package/dist/projections/v2/core_sleep_need.js +23 -0
  148. package/dist/projections/v2/core_sleep_need.js.map +1 -0
  149. package/dist/projections/v2/day.js +92 -0
  150. package/dist/projections/v2/day.js.map +1 -0
  151. package/dist/projections/v2/heart_rate.js +54 -0
  152. package/dist/projections/v2/heart_rate.js.map +1 -0
  153. package/dist/projections/v2/history.js +140 -0
  154. package/dist/projections/v2/history.js.map +1 -0
  155. package/dist/projections/v2/now.js +39 -0
  156. package/dist/projections/v2/now.js.map +1 -0
  157. package/dist/projections/v2/recovery.js +77 -0
  158. package/dist/projections/v2/recovery.js.map +1 -0
  159. package/dist/projections/v2/sleep.js +218 -0
  160. package/dist/projections/v2/sleep.js.map +1 -0
  161. package/dist/projections/v2/strain.js +39 -0
  162. package/dist/projections/v2/strain.js.map +1 -0
  163. package/dist/projections/v2/stress.js +92 -0
  164. package/dist/projections/v2/stress.js.map +1 -0
  165. package/dist/projections/v2/trend.js +205 -0
  166. package/dist/projections/v2/trend.js.map +1 -0
  167. package/dist/projections/weekly_plan.js +66 -0
  168. package/dist/projections/weekly_plan.js.map +1 -0
  169. package/dist/projections/weight_readings.js +57 -0
  170. package/dist/projections/weight_readings.js.map +1 -0
  171. package/dist/projections/workout.js +37 -15
  172. package/dist/projections/workout.js.map +1 -1
  173. package/dist/schemas/activities.js +123 -0
  174. package/dist/schemas/activities.js.map +1 -0
  175. package/dist/schemas/alarm_schedule.js +62 -0
  176. package/dist/schemas/alarm_schedule.js.map +1 -0
  177. package/dist/schemas/coach.js +76 -8
  178. package/dist/schemas/coach.js.map +1 -1
  179. package/dist/schemas/community.js +70 -0
  180. package/dist/schemas/community.js.map +1 -0
  181. package/dist/schemas/health.js +36 -0
  182. package/dist/schemas/health.js.map +1 -0
  183. package/dist/schemas/hormonal_insights.js +90 -0
  184. package/dist/schemas/hormonal_insights.js.map +1 -0
  185. package/dist/schemas/journal.js +4 -0
  186. package/dist/schemas/journal.js.map +1 -1
  187. package/dist/schemas/journal_v2.js +106 -0
  188. package/dist/schemas/journal_v2.js.map +1 -0
  189. package/dist/schemas/memory.js +42 -0
  190. package/dist/schemas/memory.js.map +1 -0
  191. package/dist/schemas/milestones.js +39 -0
  192. package/dist/schemas/milestones.js.map +1 -0
  193. package/dist/schemas/profile_v2.js +60 -0
  194. package/dist/schemas/profile_v2.js.map +1 -0
  195. package/dist/schemas/settings_v2.js +56 -0
  196. package/dist/schemas/settings_v2.js.map +1 -0
  197. package/dist/schemas/sleep.js +8 -1
  198. package/dist/schemas/sleep.js.map +1 -1
  199. package/dist/schemas/strength.js +10 -1
  200. package/dist/schemas/strength.js.map +1 -1
  201. package/dist/schemas/strength_v2.js +190 -0
  202. package/dist/schemas/strength_v2.js.map +1 -0
  203. package/dist/schemas/v2/calendar.js +8 -0
  204. package/dist/schemas/v2/calendar.js.map +1 -0
  205. package/dist/schemas/v2/core_common.js +42 -0
  206. package/dist/schemas/v2/core_common.js.map +1 -0
  207. package/dist/schemas/v2/day.js +73 -0
  208. package/dist/schemas/v2/day.js.map +1 -0
  209. package/dist/schemas/v2/now.js +25 -0
  210. package/dist/schemas/v2/now.js.map +1 -0
  211. package/dist/schemas/v2/recovery.js +35 -0
  212. package/dist/schemas/v2/recovery.js.map +1 -0
  213. package/dist/schemas/v2/sleep.js +44 -0
  214. package/dist/schemas/v2/sleep.js.map +1 -0
  215. package/dist/schemas/v2/strain.js +16 -0
  216. package/dist/schemas/v2/strain.js.map +1 -0
  217. package/dist/schemas/v2/stress.js +20 -0
  218. package/dist/schemas/v2/stress.js.map +1 -0
  219. package/dist/schemas/v2/trend.js +42 -0
  220. package/dist/schemas/v2/trend.js.map +1 -0
  221. package/dist/schemas/weekly_plan.js +31 -0
  222. package/dist/schemas/weekly_plan.js.map +1 -0
  223. package/dist/schemas/weight.js +28 -0
  224. package/dist/schemas/weight.js.map +1 -0
  225. package/dist/scripts/build_behaviors.js +114 -0
  226. package/dist/scripts/build_behaviors.js.map +1 -0
  227. package/dist/scripts/cognito_bootstrap.js +9 -277
  228. package/dist/scripts/cognito_bootstrap.js.map +1 -1
  229. package/dist/scripts/gen_activity_catalogs.js +104 -0
  230. package/dist/scripts/gen_activity_catalogs.js.map +1 -0
  231. package/dist/server-admin.js +156 -0
  232. package/dist/server-admin.js.map +1 -0
  233. package/dist/server-http.js +270 -48
  234. package/dist/server-http.js.map +1 -1
  235. package/dist/server.js +136 -23
  236. package/dist/server.js.map +1 -1
  237. package/dist/tools/annotations.js +15 -0
  238. package/dist/tools/annotations.js.map +1 -0
  239. package/dist/tools/define.js +31 -0
  240. package/dist/tools/define.js.map +1 -0
  241. package/dist/tools/register.js +59 -94
  242. package/dist/tools/register.js.map +1 -1
  243. package/dist/tools/resources.js +70 -0
  244. package/dist/tools/resources.js.map +1 -0
  245. package/dist/tools/slim_schema.js +90 -0
  246. package/dist/tools/slim_schema.js.map +1 -0
  247. package/dist/tools/v2/activity_delete.js +63 -17
  248. package/dist/tools/v2/activity_delete.js.map +1 -1
  249. package/dist/tools/v2/activity_edit.js +396 -0
  250. package/dist/tools/v2/activity_edit.js.map +1 -0
  251. package/dist/tools/v2/activity_log.js +152 -0
  252. package/dist/tools/v2/activity_log.js.map +1 -0
  253. package/dist/tools/v2/calendar.js +19 -21
  254. package/dist/tools/v2/calendar.js.map +1 -1
  255. package/dist/tools/v2/coach_ask.js +74 -110
  256. package/dist/tools/v2/coach_ask.js.map +1 -1
  257. package/dist/tools/v2/coach_history.js +120 -0
  258. package/dist/tools/v2/coach_history.js.map +1 -0
  259. package/dist/tools/v2/community.js +124 -0
  260. package/dist/tools/v2/community.js.map +1 -0
  261. package/dist/tools/v2/cycle.js +63 -15
  262. package/dist/tools/v2/cycle.js.map +1 -1
  263. package/dist/tools/v2/cycle_log.js +289 -32
  264. package/dist/tools/v2/cycle_log.js.map +1 -1
  265. package/dist/tools/v2/day.js +126 -24
  266. package/dist/tools/v2/day.js.map +1 -1
  267. package/dist/tools/v2/health.js +116 -0
  268. package/dist/tools/v2/health.js.map +1 -0
  269. package/dist/tools/v2/hr_zones_set.js +134 -34
  270. package/dist/tools/v2/hr_zones_set.js.map +1 -1
  271. package/dist/tools/v2/journal.js +75 -17
  272. package/dist/tools/v2/journal.js.map +1 -1
  273. package/dist/tools/v2/journal_log.js +306 -65
  274. package/dist/tools/v2/journal_log.js.map +1 -1
  275. package/dist/tools/v2/lift_exercise.js +125 -22
  276. package/dist/tools/v2/lift_exercise.js.map +1 -1
  277. package/dist/tools/v2/lift_exercise_set.js +291 -0
  278. package/dist/tools/v2/lift_exercise_set.js.map +1 -0
  279. package/dist/tools/v2/lift_library.js +51 -12
  280. package/dist/tools/v2/lift_library.js.map +1 -1
  281. package/dist/tools/v2/lift_log.js +309 -72
  282. package/dist/tools/v2/lift_log.js.map +1 -1
  283. package/dist/tools/v2/lift_sessions.js +248 -0
  284. package/dist/tools/v2/lift_sessions.js.map +1 -0
  285. package/dist/tools/v2/lift_template.js +232 -0
  286. package/dist/tools/v2/lift_template.js.map +1 -0
  287. package/dist/tools/v2/memory.js +45 -0
  288. package/dist/tools/v2/memory.js.map +1 -0
  289. package/dist/tools/v2/memory_set.js +107 -0
  290. package/dist/tools/v2/memory_set.js.map +1 -0
  291. package/dist/tools/v2/milestones.js +50 -0
  292. package/dist/tools/v2/milestones.js.map +1 -0
  293. package/dist/tools/v2/now.js +49 -0
  294. package/dist/tools/v2/now.js.map +1 -0
  295. package/dist/tools/v2/preferences.js +51 -0
  296. package/dist/tools/v2/preferences.js.map +1 -0
  297. package/dist/tools/v2/preferences_set.js +388 -0
  298. package/dist/tools/v2/preferences_set.js.map +1 -0
  299. package/dist/tools/v2/profile.js +54 -22
  300. package/dist/tools/v2/profile.js.map +1 -1
  301. package/dist/tools/v2/profile_update.js +167 -55
  302. package/dist/tools/v2/profile_update.js.map +1 -1
  303. package/dist/tools/v2/raw.js +91 -34
  304. package/dist/tools/v2/raw.js.map +1 -1
  305. package/dist/tools/v2/recovery.js +37 -23
  306. package/dist/tools/v2/recovery.js.map +1 -1
  307. package/dist/tools/v2/sleep.js +52 -16
  308. package/dist/tools/v2/sleep.js.map +1 -1
  309. package/dist/tools/v2/smart_alarm.js +54 -20
  310. package/dist/tools/v2/smart_alarm.js.map +1 -1
  311. package/dist/tools/v2/smart_alarm_set.js +264 -86
  312. package/dist/tools/v2/smart_alarm_set.js.map +1 -1
  313. package/dist/tools/v2/strain.js +15 -15
  314. package/dist/tools/v2/strain.js.map +1 -1
  315. package/dist/tools/v2/stress.js +17 -15
  316. package/dist/tools/v2/stress.js.map +1 -1
  317. package/dist/tools/v2/trend.js +56 -20
  318. package/dist/tools/v2/trend.js.map +1 -1
  319. package/dist/tools/v2/weekly_plan.js +30 -0
  320. package/dist/tools/v2/weekly_plan.js.map +1 -0
  321. package/dist/tools/v2/weekly_plan_set.js +134 -0
  322. package/dist/tools/v2/weekly_plan_set.js.map +1 -0
  323. package/dist/tools/v2/weight.js +56 -0
  324. package/dist/tools/v2/weight.js.map +1 -0
  325. package/dist/tools/v2/weight_log.js +188 -0
  326. package/dist/tools/v2/weight_log.js.map +1 -0
  327. package/dist/tools/v2/workouts.js +159 -25
  328. package/dist/tools/v2/workouts.js.map +1 -1
  329. package/dist/version.js +6 -0
  330. package/dist/version.js.map +1 -0
  331. package/dist/whoop/bff.js +94 -0
  332. package/dist/whoop/bff.js.map +1 -0
  333. package/dist/whoop/client.js +392 -18
  334. package/dist/whoop/client.js.map +1 -1
  335. package/dist/whoop/cognito.js +106 -79
  336. package/dist/whoop/cognito.js.map +1 -1
  337. package/dist/whoop/connect_page.js +165 -0
  338. package/dist/whoop/connect_page.js.map +1 -0
  339. package/dist/whoop/consent_font.js +287 -0
  340. package/dist/whoop/consent_font.js.map +1 -0
  341. package/dist/whoop/consent_logos.js +22 -0
  342. package/dist/whoop/consent_logos.js.map +1 -0
  343. package/dist/whoop/consent_page.js +291 -0
  344. package/dist/whoop/consent_page.js.map +1 -0
  345. package/dist/whoop/constants.js +5 -1
  346. package/dist/whoop/constants.js.map +1 -1
  347. package/dist/whoop/device.js +4 -4
  348. package/dist/whoop/device.js.map +1 -1
  349. package/dist/whoop/errors.js +85 -4
  350. package/dist/whoop/errors.js.map +1 -1
  351. package/dist/whoop/init_timezone.js +57 -17
  352. package/dist/whoop/init_timezone.js.map +1 -1
  353. package/dist/whoop/installation.js +15 -10
  354. package/dist/whoop/installation.js.map +1 -1
  355. package/dist/whoop/json_out.js +52 -6
  356. package/dist/whoop/json_out.js.map +1 -1
  357. package/dist/whoop/oauth_provider.js +81 -78
  358. package/dist/whoop/oauth_provider.js.map +1 -1
  359. package/dist/whoop/token_lock.js +331 -0
  360. package/dist/whoop/token_lock.js.map +1 -0
  361. package/dist/whoop/token_manager.js +536 -42
  362. package/dist/whoop/token_manager.js.map +1 -1
  363. package/dist/whoop/token_store.js +303 -36
  364. package/dist/whoop/token_store.js.map +1 -1
  365. package/dist/whoop/units.js +28 -0
  366. package/dist/whoop/units.js.map +1 -0
  367. package/package.json +29 -13
  368. package/scripts/build-mcpb.mjs +72 -0
  369. package/scripts/embed-consent-font.mjs +34 -0
  370. package/scripts/readme-media.ts +195 -0
  371. package/scripts/tools-md.ts +89 -0
  372. package/scripts/whoop-md.ts +119 -0
  373. package/src/build_info.ts +4 -0
  374. package/src/cli/app.ts +696 -0
  375. package/src/cli/auth.ts +350 -0
  376. package/src/cli/auth_flow.ts +356 -0
  377. package/src/cli/browser_login.ts +402 -0
  378. package/src/cli/clients.ts +467 -0
  379. package/src/cli/deploy_record.ts +100 -0
  380. package/src/cli/index.ts +41 -583
  381. package/src/cli/links.ts +43 -0
  382. package/src/cli/logo.ts +64 -0
  383. package/src/cli/setup.ts +1147 -979
  384. package/src/cli/spawn.ts +88 -0
  385. package/src/cli/sys.ts +267 -0
  386. package/src/cli/ui.ts +778 -436
  387. package/src/cli/update.ts +436 -274
  388. package/src/cloudflare/runtime.d.ts +27 -0
  389. package/src/cloudflare/token_store.ts +57 -0
  390. package/src/cloudflare/worker.ts +174 -0
  391. package/src/data/behaviors.ts +2760 -622
  392. package/src/data/endpoint_catalog.ts +2695 -0
  393. package/src/data/exercises.ts +379 -4861
  394. package/src/data/garments.ts +28 -0
  395. package/src/data/sports.ts +239 -211
  396. package/src/lib/activity_list.ts +150 -0
  397. package/src/lib/activity_records.ts +213 -0
  398. package/src/lib/activity_results.ts +51 -0
  399. package/src/lib/activity_types.ts +176 -0
  400. package/src/lib/brand.ts +71 -0
  401. package/src/lib/clock.ts +16 -0
  402. package/src/lib/coach_session.ts +434 -0
  403. package/src/lib/dates.ts +18 -0
  404. package/src/lib/env_file.ts +191 -0
  405. package/src/lib/health_plans_write.ts +53 -0
  406. package/src/lib/heart_rate.ts +42 -0
  407. package/src/lib/highlight.ts +71 -0
  408. package/src/lib/install_links.ts +61 -0
  409. package/src/lib/instant.ts +54 -0
  410. package/src/lib/journal_behaviors.ts +453 -0
  411. package/src/lib/lift_catalog.ts +258 -0
  412. package/src/lib/lift_history.ts +75 -0
  413. package/src/lib/lift_sets.ts +164 -0
  414. package/src/lib/lift_tool.ts +25 -0
  415. package/src/lib/profile_settings.ts +102 -0
  416. package/src/lib/screen_content.ts +40 -0
  417. package/src/lib/timezone.ts +44 -8
  418. package/src/lib/walk.ts +4 -1
  419. package/src/lib/weight_readings.ts +82 -0
  420. package/src/projections/activities.ts +199 -0
  421. package/src/projections/alarm_schedule.ts +98 -0
  422. package/src/projections/coach.ts +218 -0
  423. package/src/projections/community.ts +187 -0
  424. package/src/projections/health_features.ts +191 -0
  425. package/src/projections/hormonal_insights.ts +277 -0
  426. package/src/projections/journal_v2.ts +173 -0
  427. package/src/projections/lift_cards.ts +131 -0
  428. package/src/projections/lift_exercise_v2.ts +147 -0
  429. package/src/projections/lift_library_v2.ts +77 -0
  430. package/src/projections/lift_sessions.ts +250 -0
  431. package/src/projections/memory.ts +100 -0
  432. package/src/projections/milestones.ts +133 -0
  433. package/src/projections/profile_v2.ts +166 -0
  434. package/src/projections/settings_v2.ts +179 -0
  435. package/src/projections/sleep.ts +7 -21
  436. package/src/projections/v2/calendar.ts +48 -0
  437. package/src/projections/v2/core_common.ts +95 -0
  438. package/src/projections/v2/core_home.ts +177 -0
  439. package/src/projections/v2/core_sleep_need.ts +37 -0
  440. package/src/projections/v2/day.ts +162 -0
  441. package/src/projections/v2/heart_rate.ts +73 -0
  442. package/src/projections/v2/history.ts +153 -0
  443. package/src/projections/v2/now.ts +59 -0
  444. package/src/projections/v2/recovery.ts +120 -0
  445. package/src/projections/v2/sleep.ts +281 -0
  446. package/src/projections/v2/strain.ts +63 -0
  447. package/src/projections/v2/stress.ts +111 -0
  448. package/src/projections/v2/trend.ts +242 -0
  449. package/src/projections/weekly_plan.ts +79 -0
  450. package/src/projections/weight_readings.ts +57 -0
  451. package/src/projections/workout.ts +36 -17
  452. package/src/schemas/activities.ts +136 -0
  453. package/src/schemas/alarm_schedule.ts +70 -0
  454. package/src/schemas/coach.ts +98 -8
  455. package/src/schemas/community.ts +77 -0
  456. package/src/schemas/health.ts +36 -0
  457. package/src/schemas/hormonal_insights.ts +108 -0
  458. package/src/schemas/journal.ts +4 -0
  459. package/src/schemas/journal_v2.ts +112 -0
  460. package/src/schemas/memory.ts +48 -0
  461. package/src/schemas/milestones.ts +48 -0
  462. package/src/schemas/profile_v2.ts +63 -0
  463. package/src/schemas/settings_v2.ts +63 -0
  464. package/src/schemas/sleep.ts +9 -1
  465. package/src/schemas/strength.ts +10 -1
  466. package/src/schemas/strength_v2.ts +210 -0
  467. package/src/schemas/v2/calendar.ts +8 -0
  468. package/src/schemas/v2/core_common.ts +50 -0
  469. package/src/schemas/v2/day.ts +79 -0
  470. package/src/schemas/v2/now.ts +25 -0
  471. package/src/schemas/v2/recovery.ts +38 -0
  472. package/src/schemas/v2/sleep.ts +46 -0
  473. package/src/schemas/v2/strain.ts +16 -0
  474. package/src/schemas/v2/stress.ts +20 -0
  475. package/src/schemas/v2/trend.ts +45 -0
  476. package/src/schemas/weekly_plan.ts +36 -0
  477. package/src/schemas/weight.ts +53 -0
  478. package/src/scripts/build_behaviors.ts +116 -0
  479. package/src/scripts/cognito_bootstrap.ts +10 -249
  480. package/src/scripts/gen_activity_catalogs.ts +121 -0
  481. package/src/server-admin.ts +171 -0
  482. package/src/server-http.ts +290 -53
  483. package/src/server.ts +130 -26
  484. package/src/tools/annotations.ts +25 -0
  485. package/src/tools/define.ts +53 -0
  486. package/src/tools/register.ts +64 -94
  487. package/src/tools/resources.ts +92 -0
  488. package/src/tools/slim_schema.ts +102 -0
  489. package/src/tools/v2/activity_delete.ts +61 -23
  490. package/src/tools/v2/activity_edit.ts +378 -0
  491. package/src/tools/v2/activity_log.ts +154 -0
  492. package/src/tools/v2/calendar.ts +22 -21
  493. package/src/tools/v2/coach_ask.ts +83 -119
  494. package/src/tools/v2/coach_history.ts +140 -0
  495. package/src/tools/v2/community.ts +137 -0
  496. package/src/tools/v2/cycle.ts +78 -20
  497. package/src/tools/v2/cycle_log.ts +291 -40
  498. package/src/tools/v2/day.ts +126 -25
  499. package/src/tools/v2/health.ts +114 -0
  500. package/src/tools/v2/hr_zones_set.ts +132 -45
  501. package/src/tools/v2/journal.ts +78 -23
  502. package/src/tools/v2/journal_log.ts +321 -69
  503. package/src/tools/v2/lift_exercise.ts +135 -27
  504. package/src/tools/v2/lift_exercise_set.ts +272 -0
  505. package/src/tools/v2/lift_library.ts +57 -21
  506. package/src/tools/v2/lift_log.ts +325 -83
  507. package/src/tools/v2/lift_sessions.ts +255 -0
  508. package/src/tools/v2/lift_template.ts +229 -0
  509. package/src/tools/v2/memory.ts +54 -0
  510. package/src/tools/v2/memory_set.ts +110 -0
  511. package/src/tools/v2/milestones.ts +59 -0
  512. package/src/tools/v2/now.ts +61 -0
  513. package/src/tools/v2/preferences.ts +61 -0
  514. package/src/tools/v2/preferences_set.ts +403 -0
  515. package/src/tools/v2/profile.ts +56 -26
  516. package/src/tools/v2/profile_update.ts +151 -60
  517. package/src/tools/v2/raw.ts +89 -36
  518. package/src/tools/v2/recovery.ts +44 -25
  519. package/src/tools/v2/sleep.ts +57 -18
  520. package/src/tools/v2/smart_alarm.ts +62 -24
  521. package/src/tools/v2/smart_alarm_set.ts +240 -90
  522. package/src/tools/v2/strain.ts +19 -16
  523. package/src/tools/v2/stress.ts +22 -17
  524. package/src/tools/v2/trend.ts +58 -20
  525. package/src/tools/v2/weekly_plan.ts +38 -0
  526. package/src/tools/v2/weekly_plan_set.ts +132 -0
  527. package/src/tools/v2/weight.ts +61 -0
  528. package/src/tools/v2/weight_log.ts +193 -0
  529. package/src/tools/v2/workouts.ts +156 -26
  530. package/src/version.ts +5 -0
  531. package/src/whoop/bff.ts +84 -0
  532. package/src/whoop/client.ts +448 -18
  533. package/src/whoop/cognito.ts +110 -99
  534. package/src/whoop/connect_page.ts +183 -0
  535. package/src/whoop/consent_font.ts +289 -0
  536. package/src/whoop/consent_logos.ts +24 -0
  537. package/src/whoop/consent_page.ts +326 -0
  538. package/src/whoop/constants.ts +5 -1
  539. package/src/whoop/device.ts +4 -4
  540. package/src/whoop/errors.ts +89 -4
  541. package/src/whoop/init_timezone.ts +57 -16
  542. package/src/whoop/installation.ts +16 -7
  543. package/src/whoop/json_out.ts +51 -6
  544. package/src/whoop/oauth_provider.ts +84 -91
  545. package/src/whoop/token_lock.ts +345 -0
  546. package/src/whoop/token_manager.ts +580 -53
  547. package/src/whoop/token_store.ts +341 -32
  548. package/src/whoop/units.ts +35 -0
  549. package/wrangler.jsonc +17 -0
  550. package/assets/banner.svg +0 -38
  551. package/dist/data/endpoints.js +0 -320
  552. package/dist/data/endpoints.js.map +0 -1
  553. package/dist/lib/format.js +0 -22
  554. package/dist/lib/format.js.map +0 -1
  555. package/dist/lib/stats.js +0 -32
  556. package/dist/lib/stats.js.map +0 -1
  557. package/dist/projections/calendar.js +0 -33
  558. package/dist/projections/calendar.js.map +0 -1
  559. package/dist/projections/communities.js +0 -105
  560. package/dist/projections/communities.js.map +0 -1
  561. package/dist/projections/cycle.js +0 -81
  562. package/dist/projections/cycle.js.map +0 -1
  563. package/dist/projections/hr_zones.js +0 -35
  564. package/dist/projections/hr_zones.js.map +0 -1
  565. package/dist/projections/journal.js +0 -56
  566. package/dist/projections/journal.js.map +0 -1
  567. package/dist/projections/leaderboard.js +0 -37
  568. package/dist/projections/leaderboard.js.map +0 -1
  569. package/dist/projections/lift_exercise.js +0 -22
  570. package/dist/projections/lift_exercise.js.map +0 -1
  571. package/dist/projections/lift_history.js +0 -133
  572. package/dist/projections/lift_history.js.map +0 -1
  573. package/dist/projections/lift_library.js +0 -71
  574. package/dist/projections/lift_library.js.map +0 -1
  575. package/dist/projections/lift_progression.js +0 -138
  576. package/dist/projections/lift_progression.js.map +0 -1
  577. package/dist/projections/lift_prs.js +0 -20
  578. package/dist/projections/lift_prs.js.map +0 -1
  579. package/dist/projections/live_hr.js +0 -19
  580. package/dist/projections/live_hr.js.map +0 -1
  581. package/dist/projections/live_state.js +0 -23
  582. package/dist/projections/live_state.js.map +0 -1
  583. package/dist/projections/live_stress.js +0 -11
  584. package/dist/projections/live_stress.js.map +0 -1
  585. package/dist/projections/performance_assessment.js +0 -15
  586. package/dist/projections/performance_assessment.js.map +0 -1
  587. package/dist/projections/profile.js +0 -59
  588. package/dist/projections/profile.js.map +0 -1
  589. package/dist/projections/recovery.js +0 -131
  590. package/dist/projections/recovery.js.map +0 -1
  591. package/dist/projections/sleep_need.js +0 -32
  592. package/dist/projections/sleep_need.js.map +0 -1
  593. package/dist/projections/smart_alarm.js +0 -45
  594. package/dist/projections/smart_alarm.js.map +0 -1
  595. package/dist/projections/strain.js +0 -128
  596. package/dist/projections/strain.js.map +0 -1
  597. package/dist/projections/stress.js +0 -86
  598. package/dist/projections/stress.js.map +0 -1
  599. package/dist/projections/today.js +0 -129
  600. package/dist/projections/today.js.map +0 -1
  601. package/dist/projections/trend.js +0 -149
  602. package/dist/projections/trend.js.map +0 -1
  603. package/dist/projections/workouts.js +0 -37
  604. package/dist/projections/workouts.js.map +0 -1
  605. package/dist/schemas/calendar.js +0 -12
  606. package/dist/schemas/calendar.js.map +0 -1
  607. package/dist/schemas/communities.js +0 -51
  608. package/dist/schemas/communities.js.map +0 -1
  609. package/dist/schemas/compare.js +0 -15
  610. package/dist/schemas/compare.js.map +0 -1
  611. package/dist/schemas/leaderboard.js +0 -25
  612. package/dist/schemas/leaderboard.js.map +0 -1
  613. package/dist/schemas/live.js +0 -26
  614. package/dist/schemas/live.js.map +0 -1
  615. package/dist/schemas/performance.js +0 -12
  616. package/dist/schemas/performance.js.map +0 -1
  617. package/dist/schemas/profile.js +0 -39
  618. package/dist/schemas/profile.js.map +0 -1
  619. package/dist/schemas/recovery.js +0 -27
  620. package/dist/schemas/recovery.js.map +0 -1
  621. package/dist/schemas/settings.js +0 -26
  622. package/dist/schemas/settings.js.map +0 -1
  623. package/dist/schemas/sleep_need.js +0 -15
  624. package/dist/schemas/sleep_need.js.map +0 -1
  625. package/dist/schemas/smart_alarm.js +0 -36
  626. package/dist/schemas/smart_alarm.js.map +0 -1
  627. package/dist/schemas/strain.js +0 -24
  628. package/dist/schemas/strain.js.map +0 -1
  629. package/dist/schemas/stress.js +0 -16
  630. package/dist/schemas/stress.js.map +0 -1
  631. package/dist/schemas/today.js +0 -38
  632. package/dist/schemas/today.js.map +0 -1
  633. package/dist/schemas/trend.js +0 -50
  634. package/dist/schemas/trend.js.map +0 -1
  635. package/dist/schemas/womens_health.js +0 -23
  636. package/dist/schemas/womens_health.js.map +0 -1
  637. package/dist/tools/v2/activity_create.js +0 -64
  638. package/dist/tools/v2/activity_create.js.map +0 -1
  639. package/dist/tools/v2/behavior_impact.js +0 -36
  640. package/dist/tools/v2/behavior_impact.js.map +0 -1
  641. package/dist/tools/v2/communities.js +0 -60
  642. package/dist/tools/v2/communities.js.map +0 -1
  643. package/dist/tools/v2/compare.js +0 -67
  644. package/dist/tools/v2/compare.js.map +0 -1
  645. package/dist/tools/v2/endpoints.js +0 -28
  646. package/dist/tools/v2/endpoints.js.map +0 -1
  647. package/dist/tools/v2/hidden_metric.js +0 -28
  648. package/dist/tools/v2/hidden_metric.js.map +0 -1
  649. package/dist/tools/v2/hr_zones.js +0 -24
  650. package/dist/tools/v2/hr_zones.js.map +0 -1
  651. package/dist/tools/v2/journal_autopop.js +0 -19
  652. package/dist/tools/v2/journal_autopop.js.map +0 -1
  653. package/dist/tools/v2/journal_catalog.js +0 -44
  654. package/dist/tools/v2/journal_catalog.js.map +0 -1
  655. package/dist/tools/v2/leaderboard.js +0 -79
  656. package/dist/tools/v2/leaderboard.js.map +0 -1
  657. package/dist/tools/v2/lift_catalog.js +0 -47
  658. package/dist/tools/v2/lift_catalog.js.map +0 -1
  659. package/dist/tools/v2/lift_custom_exercise.js +0 -108
  660. package/dist/tools/v2/lift_custom_exercise.js.map +0 -1
  661. package/dist/tools/v2/lift_history.js +0 -39
  662. package/dist/tools/v2/lift_history.js.map +0 -1
  663. package/dist/tools/v2/lift_progression.js +0 -30
  664. package/dist/tools/v2/lift_progression.js.map +0 -1
  665. package/dist/tools/v2/lift_prs.js +0 -21
  666. package/dist/tools/v2/lift_prs.js.map +0 -1
  667. package/dist/tools/v2/lift_template_save.js +0 -83
  668. package/dist/tools/v2/lift_template_save.js.map +0 -1
  669. package/dist/tools/v2/live_hr.js +0 -21
  670. package/dist/tools/v2/live_hr.js.map +0 -1
  671. package/dist/tools/v2/live_state.js +0 -21
  672. package/dist/tools/v2/live_state.js.map +0 -1
  673. package/dist/tools/v2/live_stress.js +0 -22
  674. package/dist/tools/v2/live_stress.js.map +0 -1
  675. package/dist/tools/v2/performance_assessment.js +0 -38
  676. package/dist/tools/v2/performance_assessment.js.map +0 -1
  677. package/dist/tools/v2/sleep_need.js +0 -21
  678. package/dist/tools/v2/sleep_need.js.map +0 -1
  679. package/dist/tools/v2/sports_catalog.js +0 -26
  680. package/dist/tools/v2/sports_catalog.js.map +0 -1
  681. package/dist/tools/v2/symptom_log.js +0 -72
  682. package/dist/tools/v2/symptom_log.js.map +0 -1
  683. package/dist/tools/v2/today.js +0 -30
  684. package/dist/tools/v2/today.js.map +0 -1
  685. package/dist/tools/v2/workout.js +0 -23
  686. package/dist/tools/v2/workout.js.map +0 -1
  687. package/dist/whoop/build_lift_body.js +0 -67
  688. package/dist/whoop/build_lift_body.js.map +0 -1
  689. package/dist/whoop/session_state.js +0 -34
  690. package/dist/whoop/session_state.js.map +0 -1
  691. package/dist/whoop/types.js +0 -82
  692. package/dist/whoop/types.js.map +0 -1
  693. package/src/data/endpoints.ts +0 -319
  694. package/src/lib/format.ts +0 -27
  695. package/src/lib/stats.ts +0 -35
  696. package/src/projections/calendar.ts +0 -46
  697. package/src/projections/communities.ts +0 -135
  698. package/src/projections/cycle.ts +0 -85
  699. package/src/projections/hr_zones.ts +0 -43
  700. package/src/projections/journal.ts +0 -55
  701. package/src/projections/leaderboard.ts +0 -49
  702. package/src/projections/lift_exercise.ts +0 -29
  703. package/src/projections/lift_history.ts +0 -140
  704. package/src/projections/lift_library.ts +0 -70
  705. package/src/projections/lift_progression.ts +0 -138
  706. package/src/projections/lift_prs.ts +0 -23
  707. package/src/projections/live_hr.ts +0 -21
  708. package/src/projections/live_state.ts +0 -28
  709. package/src/projections/live_stress.ts +0 -13
  710. package/src/projections/performance_assessment.ts +0 -19
  711. package/src/projections/profile.ts +0 -71
  712. package/src/projections/recovery.ts +0 -133
  713. package/src/projections/sleep_need.ts +0 -36
  714. package/src/projections/smart_alarm.ts +0 -70
  715. package/src/projections/strain.ts +0 -131
  716. package/src/projections/stress.ts +0 -95
  717. package/src/projections/today.ts +0 -166
  718. package/src/projections/trend.ts +0 -149
  719. package/src/projections/workouts.ts +0 -36
  720. package/src/schemas/calendar.ts +0 -13
  721. package/src/schemas/communities.ts +0 -56
  722. package/src/schemas/compare.ts +0 -17
  723. package/src/schemas/leaderboard.ts +0 -26
  724. package/src/schemas/live.ts +0 -31
  725. package/src/schemas/performance.ts +0 -13
  726. package/src/schemas/profile.ts +0 -40
  727. package/src/schemas/recovery.ts +0 -28
  728. package/src/schemas/settings.ts +0 -30
  729. package/src/schemas/sleep_need.ts +0 -16
  730. package/src/schemas/smart_alarm.ts +0 -40
  731. package/src/schemas/strain.ts +0 -25
  732. package/src/schemas/stress.ts +0 -17
  733. package/src/schemas/today.ts +0 -39
  734. package/src/schemas/trend.ts +0 -53
  735. package/src/schemas/womens_health.ts +0 -26
  736. package/src/tools/v2/activity_create.ts +0 -74
  737. package/src/tools/v2/behavior_impact.ts +0 -39
  738. package/src/tools/v2/communities.ts +0 -65
  739. package/src/tools/v2/compare.ts +0 -83
  740. package/src/tools/v2/endpoints.ts +0 -32
  741. package/src/tools/v2/hidden_metric.ts +0 -33
  742. package/src/tools/v2/hr_zones.ts +0 -29
  743. package/src/tools/v2/journal_autopop.ts +0 -26
  744. package/src/tools/v2/journal_catalog.ts +0 -48
  745. package/src/tools/v2/leaderboard.ts +0 -92
  746. package/src/tools/v2/lift_catalog.ts +0 -48
  747. package/src/tools/v2/lift_custom_exercise.ts +0 -117
  748. package/src/tools/v2/lift_history.ts +0 -52
  749. package/src/tools/v2/lift_progression.ts +0 -34
  750. package/src/tools/v2/lift_prs.ts +0 -26
  751. package/src/tools/v2/lift_template_save.ts +0 -89
  752. package/src/tools/v2/live_hr.ts +0 -26
  753. package/src/tools/v2/live_state.ts +0 -26
  754. package/src/tools/v2/live_stress.ts +0 -27
  755. package/src/tools/v2/performance_assessment.ts +0 -44
  756. package/src/tools/v2/sleep_need.ts +0 -26
  757. package/src/tools/v2/sports_catalog.ts +0 -32
  758. package/src/tools/v2/symptom_log.ts +0 -78
  759. package/src/tools/v2/today.ts +0 -35
  760. package/src/tools/v2/workout.ts +0 -28
  761. package/src/whoop/build_lift_body.ts +0 -84
  762. package/src/whoop/session_state.ts +0 -41
  763. package/src/whoop/types.ts +0 -89
package/dist/cli/setup.js CHANGED
@@ -1,799 +1,458 @@
1
- // Guided setup flows: `totem cloud` (server-hosted, OAuth, recommended) and
2
- // `totem local` (stdio on this machine). These are the headline commands.
1
+ // The guided flows: `totem local` (run on this computer), `totem cloud`
2
+ // (deploy a server) and `totem connect` (connect another client).
3
3
  //
4
- // Fly, Railway, and Cloud Run are all fully CLI-automated and tested end-to-end:
5
- // the flow installs the host CLI if missing, logs you in, deploys, auto-detects
6
- // the resulting URL, sets PUBLIC_URL, and verifies /health + OAuth are live — no
7
- // copy-paste. Custom is a printed Docker guide for any other host or your own
8
- // server. Either way it's one command to a working, Claude-connected deployment.
9
- import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, chmodSync } from "node:fs";
10
- import { tmpdir } from "node:os";
4
+ // Each screen says what is happening, what the person must do now, and what
5
+ // comes next. Prompts are kept to the decisions only a person can make: which
6
+ // client, which host, and one confirmation of the whole deploy plan before
7
+ // anything is created or billed. Everything else takes a stated default.
8
+ //
9
+ // What a flow does (which commands run, in which order) is unchanged from the
10
+ // original; only how it is shown and asked is new. All effects go through
11
+ // io.sys, all output and questions through io.ui, so a test can drive a whole
12
+ // flow with a fake host and render the screen.
13
+ import { existsSync, rmSync, writeFileSync } from "node:fs";
11
14
  import { randomUUID } from "node:crypto";
12
- import { resolve, dirname } from "node:path";
13
- import { c, run, capture, captureAsync, commandExists, genToken, genPassword, copyToClipboard, httpGet, prompt, promptHidden, promptYesNo, select, confirmStep, step, closePrompts, withSpinner, spin, pause, maskArgs, runScript, ensureCli, openUrl, } from "./ui.js";
14
- // ── .env helpers ────────────────────────────────────────────────────────────
15
- function envPath(root) {
16
- return resolve(root, ".env");
17
- }
18
- function readEnv(root) {
19
- const p = envPath(root);
20
- if (!existsSync(p))
21
- return {};
22
- const out = {};
23
- for (const line of readFileSync(p, "utf8").split("\n")) {
24
- const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
25
- if (m && m[1])
26
- out[m[1]] = m[2] ?? "";
27
- }
28
- return out;
29
- }
30
- function upsertEnv(root, updates) {
31
- const p = envPath(root);
32
- const lines = existsSync(p) ? readFileSync(p, "utf8").split("\n") : [];
33
- for (const [k, v] of Object.entries(updates)) {
34
- const idx = lines.findIndex((l) => l.startsWith(`${k}=`));
35
- if (idx >= 0)
36
- lines[idx] = `${k}=${v}`;
37
- else
38
- lines.push(`${k}=${v}`);
39
- }
40
- // 0600 — this file holds the refresh token (and, transiently, the password).
41
- writeFileSync(p, lines.join("\n"), { mode: 0o600 });
42
- try {
43
- chmodSync(p, 0o600);
44
- }
45
- catch { /* best-effort */ }
15
+ import { tmpdir } from "node:os";
16
+ import { resolve } from "node:path";
17
+ import { pkgBin } from "./spawn.js";
18
+ import { realAuthDeps, runAuth } from "./auth.js";
19
+ import { checkPushUrl } from "./auth_flow.js";
20
+ import { configFile, deployRecordPath, dockerBuildArgs, readDeployRecord, writeDeployRecord } from "./deploy_record.js";
21
+ import { migrateFromEnv, resolveTokenFilePath, writeFileAtomic } from "../whoop/token_store.js";
22
+ import { CLIENTS, FIRST_QUESTION, SERVER_NAME, applyRecipe, connectCard, findClient, lastLine, recipeLines, tildify, } from "./clients.js";
23
+ import { offerLink } from "./links.js";
24
+ import { realIo } from "./sys.js";
25
+ import { duration, listOf, maskSecrets, shellLines, shellPath, when } from "./ui.js";
26
+ const NODE_MIN = 24;
27
+ export const FLY_VOLUME = "totem_data";
28
+ /** Fly's cheapest region (Ashburn, Virginia), and the smallest machine totem is comfortable in. */
29
+ export const FLY_REGION = "iad";
30
+ export const FLY_VM = { size: "shared-cpu-1x", memory: "512mb" };
31
+ /** Wrangler through npx: nothing to install, and the major version totem was tested with. */
32
+ export const WRANGLER = ["--yes", "wrangler@4"];
33
+ const wrangler = (args) => [...WRANGLER, ...args];
34
+ /** The last few lines a command printed: enough to see why it failed. */
35
+ function tail(r, lines = 6) {
36
+ const all = `${r.stdout}\n${r.stderr}`.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
37
+ return all.slice(-lines);
46
38
  }
47
- // A user-chosen connector password gates public web/mobile access to the
48
- // account. Require length + ≥2 character classes and reject obvious choices.
49
- // (Pressing Enter for the auto-generated 18-char option is always strong.)
50
- function weakPassword(pw) {
39
+ // A connector password the user chooses gates public access to their health
40
+ // data. Require length and two character classes, and refuse the obvious.
41
+ export function weakPassword(pw) {
51
42
  if (pw.length < 16)
52
- return "Use at least 16 characters (or press Enter to auto-generate).";
43
+ return "Use at least 16 characters.";
53
44
  const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(pw)).length;
54
45
  if (classes < 2)
55
- return "Mix at least two of: lower, upper, digits, symbols (or press Enter to auto-generate).";
46
+ return "Mix at least two of: lower case, upper case, digits, symbols.";
56
47
  if (/^(.)\1+$/.test(pw))
57
- return "That's a single repeated character — pick something stronger.";
48
+ return "That is one character repeated.";
58
49
  if (/^(password|whoop|123456|qwerty|letmein)/i.test(pw))
59
- return "That's too guessable — pick something stronger.";
50
+ return "That is too easy to guess.";
60
51
  return null;
61
52
  }
62
- function writeDeployRecord(root, rec) {
63
- writeFileSync(resolve(root, ".totem-deploy.json"), JSON.stringify(rec, null, 2));
64
- }
65
- // ── shared: ensure dependencies are installed (offer to run npm install) ─────
66
- // A published `npm install -g` already has node_modules; a fresh git checkout
67
- // that never ran `npm install` does not — without it the build + auth steps
68
- // would just error out. This keeps the flow zero-setup.
69
- async function ensureDeps(root) {
70
- if (existsSync(resolve(root, "node_modules")))
71
- return true;
72
- console.log(c.yellow(" Dependencies aren't installed yet."));
73
- if (!(await promptYesNo("Run `npm install` now?", true))) {
74
- console.log(c.red(" Can't continue without dependencies."));
53
+ // ── prerequisites ───────────────────────────────────────────────────────────
54
+ /** Node, dependencies and (for a local install) the build. Fixes what it can. */
55
+ async function prerequisites(root, io, build) {
56
+ const { ui, sys } = io;
57
+ if (Number(sys.nodeVersion.split(".")[0] ?? "0") < NODE_MIN) {
58
+ ui.problem(`totem needs Node.js ${NODE_MIN} or newer. This is ${sys.nodeVersion}.`, {
59
+ detail: "Install a newer one from https://nodejs.org, then run this command again.",
60
+ });
75
61
  return false;
76
62
  }
77
- return (await run("npm", ["install"], { cwd: root })) === 0;
78
- }
79
- // ── shared: ensure we have Whoop tokens (run auth if not) ────────────────────
80
- async function ensureAuth(root) {
81
- const env = readEnv(root);
82
- if (env.WHOOP_IOS_BEARER_TOKEN && env.WHOOP_COGNITO_REFRESH_TOKEN) {
83
- const reuse = await promptYesNo("Found existing Whoop tokens in .env. Reuse them?", true);
84
- if (reuse)
85
- return true;
63
+ ui.ok(`Node.js ${sys.nodeVersion}`);
64
+ if (existsSync(resolve(root, "node_modules"))) {
65
+ ui.ok("Dependencies installed");
86
66
  }
87
- // Need email + password in .env for the auth (cognito_bootstrap) script.
88
- if (!env.WHOOP_EMAIL) {
89
- const email = await promptRequired("Your Whoop account email", {
90
- validate: (v) => (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? null : "That doesn't look like an email address — try again."),
91
- });
92
- upsertEnv(root, { WHOOP_EMAIL: email });
67
+ else {
68
+ const started = sys.now();
69
+ const r = await ui.task("Installing dependencies", (set) => sys.exec("npm", ["install"], { cwd: root, onLine: set }), { slow: true });
70
+ if (r.code !== 0) {
71
+ ui.problem("Installing dependencies failed.", { detail: tail(r), fix: [["Run it yourself", "npm install"]] });
72
+ return false;
73
+ }
74
+ ui.ok("Dependencies installed", duration(sys.now() - started));
93
75
  }
94
- if (!readEnv(root).WHOOP_PASSWORD) {
95
- const pw = await promptRequired("Your Whoop account password (stored only in local .env, used once)", { hidden: true });
96
- upsertEnv(root, { WHOOP_PASSWORD: pw });
76
+ if (!build)
77
+ return true;
78
+ if (existsSync(resolve(root, "dist", "server.js"))) {
79
+ ui.ok("Server built");
80
+ return true;
97
81
  }
98
- console.log(c.gray("Authenticating with Whoop (you'll get an SMS code if your account has MFA)…"));
99
- // closePrompts so the auth script owns stdin for its own SMS prompt.
100
- closePrompts();
101
- // runScript prefers the compiled dist/ (works in a published install with no
102
- // tsx), falling back to tsx on source for a dev checkout. TOKENS_ONLY: the
103
- // guided flow handles the deploy itself, so the auth script must NOT push.
104
- const code = await runScript(root, "scripts/cognito_bootstrap", [], {
105
- env: { ...process.env, WHOOP_AUTH_TOKENS_ONLY: "1" },
106
- });
107
- if (code !== 0) {
108
- console.log(c.red("Auth failed."));
82
+ const tsc = pkgBin(root, "typescript", "tsc");
83
+ if (!tsc) {
84
+ ui.problem("The server isn't built, and the TypeScript compiler isn't installed.", { fix: [["Install it", "npm install"], ["Then", "totem local"]] });
109
85
  return false;
110
86
  }
87
+ const started = sys.now();
88
+ const r = await ui.task("Building the server", (set) => sys.exec(sys.node, [tsc], { cwd: root, onLine: set }), { slow: true });
89
+ if (r.code !== 0) {
90
+ ui.problem("Building the server failed.", { detail: tail(r), fix: [["See the full output", "totem build"]] });
91
+ return false;
92
+ }
93
+ ui.ok("Server built", duration(sys.now() - started));
111
94
  return true;
112
95
  }
113
- async function preflight(prereqs) {
114
- for (const p of prereqs) {
115
- if (await p.check()) {
116
- console.log(c.green(` ✓ ${p.label}`));
96
+ /** Make sure a host's CLI is installed, offering each way this machine has. */
97
+ async function ensureCli(io, names, title, install) {
98
+ const { ui, sys } = io;
99
+ const found = () => names.find((n) => sys.has(n)) ?? null;
100
+ const already = found();
101
+ if (already) {
102
+ ui.ok(`${title} installed`);
103
+ return already;
104
+ }
105
+ ui.warn(`The ${title} isn't installed.`);
106
+ const ways = [];
107
+ if (install.brew && sys.has("brew"))
108
+ ways.push({ via: "Homebrew", cmd: "brew", args: ["install", ...install.brew.split(" ")] });
109
+ if (install.npm && sys.has("npm"))
110
+ ways.push({ via: "npm", cmd: "npm", args: ["install", "-g", install.npm] });
111
+ if (install.script && sys.platform !== "win32")
112
+ ways.push({ via: "its install script", cmd: "sh", args: ["-c", install.script] });
113
+ for (const way of ways) {
114
+ const shown = way.cmd === "sh" ? way.args[1] : `${way.cmd} ${way.args.join(" ")}`;
115
+ ui.code([shown]);
116
+ if (!(await ui.confirm(`Install it with ${way.via}?`, true)))
117
117
  continue;
118
+ await sys.run(way.cmd, way.args);
119
+ const now = found();
120
+ if (now) {
121
+ ui.ok(`${title} installed`);
122
+ return now;
118
123
  }
119
- console.log(c.yellow(` • ${p.label} — setting it up`));
120
- if (!(await p.ensure())) {
121
- console.log(c.red(` ✗ ${p.label} — couldn't complete; fix the above + re-run.`));
122
- return false;
123
- }
124
- console.log(c.green(` ✓ ${p.label}`));
124
+ ui.warn(`That didn't put ${names[0]} on this shell's PATH.`);
125
125
  }
126
- return true;
127
- }
128
- // shared prerequisites ────────────────────────────────────────────────────────
129
- const nodePrereq = {
130
- label: `Node.js ≥ 24 (have ${process.version})`,
131
- check: () => Number(process.versions.node.split(".")[0] || "0") >= 24,
132
- ensure: async () => {
133
- console.log(c.gray(" Needs Node 24+. Upgrade (https://nodejs.org or `brew upgrade node`) and re-run."));
134
- return false;
135
- },
136
- };
137
- function depsPrereq(root) {
138
- return { label: "npm dependencies", check: () => existsSync(resolve(root, "node_modules")), ensure: () => ensureDeps(root) };
126
+ ui.problem(`totem can't go on without the ${title}.`, { fix: [["Install it", sys.platform === "win32" && install.windows ? install.windows : install.manual], ["Then, in a new terminal", "totem cloud"]] });
127
+ return null;
139
128
  }
140
- function buildPrereq(root) {
141
- return {
142
- label: "server built (dist/)",
143
- check: () => existsSync(resolve(root, "dist", "server.js")),
144
- ensure: async () => {
145
- const tsc = resolve(root, "node_modules", ".bin", "tsc");
146
- if (!existsSync(tsc)) {
147
- console.log(c.gray(" No TypeScript compiler — run `npm install`, then re-run."));
148
- return false;
149
- }
150
- return (await run(process.execPath, [tsc], { cwd: root })) === 0;
151
- },
152
- };
129
+ // ── connecting a client ─────────────────────────────────────────────────────
130
+ function localTarget(root, io) {
131
+ return { kind: "local", node: io.sys.node, serverJs: resolve(root, "dist", "server.js") };
153
132
  }
154
- // host-CLI prerequisite (install on demand via ensureCli) ──────────────────────
155
- function cliPrereq(label, name, install) {
156
- return { label, check: () => commandExists(name), ensure: () => ensureCli(name, install) };
133
+ /** Where this install runs, from the deploy record: a server with a URL, or this computer. */
134
+ export function installTarget(root, io) {
135
+ const record = readDeployRecord(root, io.sys);
136
+ if (record && record.platform !== "local" && record.url)
137
+ return { kind: "remote", mcpUrl: `${record.url.replace(/\/+$/, "")}/mcp` };
138
+ return localTarget(root, io);
157
139
  }
158
- const flyPrereqs = [
159
- {
160
- label: "Fly CLI (flyctl)",
161
- check: () => commandExists("fly") || commandExists("flyctl"),
162
- ensure: () => ensureCli("flyctl", { brewPkg: "flyctl", scriptUrl: "https://fly.io/install.sh", manualHint: "brew install flyctl (or: curl -L https://fly.io/install.sh | sh)" }),
163
- },
164
- {
165
- label: "logged into Fly",
166
- check: () => capture(commandExists("fly") ? "fly" : "flyctl", ["auth", "whoami"]).code === 0,
167
- ensure: async () => (await run(commandExists("fly") ? "fly" : "flyctl", ["auth", "login"])) === 0,
168
- },
169
- ];
170
- const railwayPrereqs = [
171
- cliPrereq("Railway CLI", "railway", { npmPkg: "@railway/cli", brewPkg: "railway", manualHint: "npm i -g @railway/cli (or: brew install railway)" }),
172
- {
173
- label: "logged into Railway",
174
- check: () => capture("railway", ["whoami"]).code === 0,
175
- ensure: async () => (await run("railway", ["login"])) === 0,
176
- },
177
- ];
178
- // gcloud needs more than a CLI: install → auth → account → project → billing.
179
- // The CLI install + "at least one account" are pure prerequisites (below). The
180
- // *which account / which project* decisions are choices the user must own, so
181
- // they live in chooseGcloudTarget() and are offered on every run — never silently
182
- // inheriting whatever happens to be active.
183
- const gcloudPrereqs = [
184
- {
185
- label: "gcloud SDK installed",
186
- check: () => commandExists("gcloud"),
187
- ensure: async () => {
188
- if (commandExists("brew") && await confirmStep("Install the gcloud SDK via Homebrew?", { cmd: "brew install --cask google-cloud-sdk", detail: "downloads + installs Google's CLI (~hundreds of MB)", defaultYes: true })) {
189
- await run("brew", ["install", "--cask", "google-cloud-sdk"]);
190
- }
191
- if (!commandExists("gcloud")) {
192
- if (await confirmStep("Install gcloud with Google's official script instead?", { cmd: "curl https://sdk.cloud.google.com | bash", detail: "runs a remote install script (follow its prompts)", defaultYes: true })) {
193
- await run("sh", ["-c", "curl https://sdk.cloud.google.com | bash"]);
194
- }
195
- }
196
- if (!commandExists("gcloud")) {
197
- console.log(c.yellow(" gcloud still isn't on PATH — open a new terminal and re-run `totem cloud`."));
198
- return false;
199
- }
200
- return true;
201
- },
202
- },
203
- {
204
- label: "authenticated with Google",
205
- check: () => capture("gcloud", ["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"]).stdout.trim().length > 0,
206
- ensure: async () => {
207
- if (!(await confirmStep("Sign into Google in your browser?", { cmd: "gcloud auth login", defaultYes: true })))
208
- return false;
209
- return (await run("gcloud", ["auth", "login"])) === 0;
210
- },
211
- },
212
- ];
213
- // Pick the Google account to deploy under (every run). gcloud can hold several
214
- // authenticated accounts at once, so switching between EXISTING ones needs no
215
- // logout — just `gcloud config set account`. Adding a new one runs `gcloud auth
216
- // login` (the browser opens right here in the flow). Loops so a decline returns
217
- // to the menu; verifies the active account before returning.
218
- async function chooseGcloudAccount() {
219
- for (;;) {
220
- const all = (await withSpinner("listing Google accounts", () => captureAsync("gcloud", ["auth", "list", "--format=value(account)"]))).stdout.trim().split("\n").filter(Boolean);
221
- const active = (await captureAsync("gcloud", ["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"])).stdout.trim();
222
- const choices = all.map((a) => ({ label: a, hint: a === active ? "active" : undefined }));
223
- choices.push({ label: "Sign into a different Google account…", hint: undefined });
224
- const idx = await select("Which Google account should own this deployment?", choices, { defaultIndex: Math.max(0, all.indexOf(active)) });
225
- if (idx === all.length) {
226
- // Add an account — the browser sign-in happens right here, in-process.
227
- if (!(await confirmStep("Open a browser to sign into another Google account?", { cmd: "gcloud auth login", detail: "the browser sign-in happens right here in this flow", defaultYes: true })))
228
- continue;
229
- if ((await run("gcloud", ["auth", "login"])) !== 0) {
230
- console.log(c.red(" ✗ Google sign-in didn't complete."));
231
- if (!(await promptYesNo(" Try again?", true)))
232
- return false;
233
- }
234
- continue; // re-list — the new account is now active; confirm it on the next pass
235
- }
236
- const picked = all[idx];
237
- if (picked !== active) {
238
- const set = await withSpinner(`switching to ${picked}`, () => captureAsync("gcloud", ["config", "set", "account", picked]));
239
- if (set.code !== 0) {
240
- console.log(c.red(` ✗ couldn't switch to ${picked}: ${lastLine(set)}`));
241
- continue;
242
- }
243
- }
244
- console.log(c.green(` ✓ deploying as ${picked}`));
245
- return true;
140
+ /** The universal stdio block, for a client totem doesn't know. */
141
+ function printOtherClient(io, target) {
142
+ const { ui, sys } = io;
143
+ if (target.kind === "remote") {
144
+ ui.para("Give the client this URL. It signs in through a totem page in your browser, with the connector password:");
145
+ ui.code([target.mcpUrl]);
146
+ ui.para("If it can't sign in through a browser, send the server's token as a bearer header instead:");
147
+ ui.code(["Authorization: Bearer $(totem token)"]);
148
+ return;
246
149
  }
150
+ ui.para(`Most clients take this in their MCP config (the key is usually "mcpServers"):`);
151
+ ui.code(JSON.stringify({ mcpServers: { [SERVER_NAME]: { command: target.node, args: [target.serverJs] } } }, null, 2).split("\n"));
152
+ ui.para("Or, as a command the client runs:");
153
+ ui.code(shellLines([target.node, target.serverJs], ui.style.width - 4, sys.platform));
247
154
  }
248
- // Pick (or create) the GCP project. Marks the current one; creating a brand-new
249
- // project is gated behind an explicit confirm (it's a real, billable resource).
250
- async function chooseGcloudProject() {
251
- const current = (await captureAsync("gcloud", ["config", "get-value", "project"])).stdout.trim().replace(/^\(unset\)$/, "");
252
- const projects = (await withSpinner("listing GCP projects", () => captureAsync("gcloud", ["projects", "list", "--format=value(projectId)"]))).stdout.trim().split("\n").filter(Boolean);
253
- const choices = projects.map((p) => ({ label: p, hint: p === current ? "current" : undefined }));
254
- choices.push({ label: "Create a new project…", hint: undefined });
255
- const idx = await select("Which GCP project should host the deployment?", choices, { defaultIndex: Math.max(0, projects.indexOf(current)) });
256
- let project;
257
- if (idx === projects.length) {
258
- let fresh = `totem-${genToken().slice(0, 6)}`;
259
- project = (await prompt("New project ID (lowercase, 6-30 chars, globally unique)", fresh)).trim() || fresh;
260
- // Retry with a new ID if creation fails (taken/invalid ID), surfacing the error.
261
- for (;;) {
262
- if (!(await confirmStep(`Create a new Google Cloud project '${project}'?`, { cmd: `gcloud projects create ${project}`, detail: "creates a real GCP project on your account", defaultYes: true })))
263
- return false;
264
- if ((await run("gcloud", ["projects", "create", project])) === 0)
265
- break;
266
- console.log(c.red(" ✗ project creation failed — the error is shown above (usually the ID is taken or malformed)."));
267
- if (!(await promptYesNo(" Try a different project ID?", true)))
268
- return false;
269
- fresh = `totem-${genToken().slice(0, 6)}`;
270
- project = (await prompt("New project ID (lowercase, 6-30 chars, globally unique)", fresh)).trim() || fresh;
271
- }
272
- }
273
- else {
274
- project = projects[idx];
155
+ /** Ask which client, then set it up. Returns what the person still does. */
156
+ async function chooseAndConnect(io, target) {
157
+ const { ui, sys } = io;
158
+ const offered = CLIENTS.filter((cl) => cl.recipe(target, sys).kind !== "unavailable");
159
+ const found = offered.map((cl) => cl.detect(sys));
160
+ const choices = [
161
+ ...offered.map((cl, i) => ({ label: cl.name, hint: found[i] ? "installed" : undefined })),
162
+ { label: "Another client", hint: "show what to paste" },
163
+ ];
164
+ const idx = await ui.select("Which client?", choices, Math.max(0, found.indexOf(true)));
165
+ const client = offered[idx] ?? null;
166
+ if (!client) {
167
+ printOtherClient(io, target);
168
+ return { client: null, done: false, steps: ["Add the config above to your client."] };
275
169
  }
276
- return (await withSpinner(`selecting ${project}`, () => captureAsync("gcloud", ["config", "set", "project", project]))).code === 0;
170
+ const applied = await applyRecipe(io, client, client.recipe(target, sys));
171
+ return { client, ...applied };
277
172
  }
278
- // Cloud Run requires billing on the chosen project. If you already have a billing
279
- // account, we LINK it from the CLI right here, in-process. Only *creating* a
280
- // billing account (adding a payment method) needs the web console — gcloud has no
281
- // CLI for that anywhere — so that single step is handed off, with the page auto-opened.
282
- async function ensureGcloudBilling() {
283
- const p = (await captureAsync("gcloud", ["config", "get-value", "project"])).stdout.trim();
284
- const b = await withSpinner("checking billing", () => captureAsync("gcloud", ["billing", "projects", "describe", p, "--format=value(billingEnabled)"]));
285
- if (b.code === 0 && /true/i.test(b.stdout)) {
286
- console.log(c.green(" ✓ billing enabled"));
287
- return true;
173
+ /**
174
+ * Set totem up in every app found on this computer, after one question. Each
175
+ * app gets its own best way in: its config file, its own command, or a link
176
+ * that opens it filled in. Apps that share one connection (claude.ai and
177
+ * Claude Desktop, for a server) are set up once. With nothing found, or a no,
178
+ * the person picks one app instead.
179
+ */
180
+ export async function connectInstalled(io, target) {
181
+ const { ui, sys } = io;
182
+ const found = CLIENTS.filter((cl) => cl.detect(sys) && cl.recipe(target, sys).kind !== "unavailable");
183
+ if (found.length === 0 || !ui.canAsk) {
184
+ if (found.length === 0)
185
+ ui.hint("No AI app found on this computer that totem knows how to set up.");
186
+ const picked = await chooseAndConnect(io, target);
187
+ return { done: picked.done && picked.client ? [picked.client.name] : [], steps: picked.steps };
288
188
  }
289
- // Link an existing OPEN billing account directly via the CLI (in-process).
290
- const accts = (await withSpinner("listing your billing accounts", () => captureAsync("gcloud", ["billing", "accounts", "list", "--filter=open=true", "--format=value(name)"]))).stdout.trim().split("\n").filter(Boolean);
291
- if (accts.length > 0) {
292
- const choices = accts.map((a) => ({ label: a }));
293
- choices.push({ label: "None of these — set one up in the console" });
294
- const idx = await select("Link which billing account to this project?", choices);
295
- if (idx < accts.length) {
296
- const acct = accts[idx];
297
- if (await confirmStep(`Link billing account ${acct} to ${p}?`, { cmd: `gcloud billing projects link ${p} --billing-account=${acct}`, detail: "enables billing on the project — done right here, no console", defaultYes: true })) {
298
- const link = await withSpinner("linking billing", () => captureAsync("gcloud", ["billing", "projects", "link", p, "--billing-account", acct]));
299
- if (link.code === 0) {
300
- console.log(c.green(" ✓ billing linked"));
301
- return true;
302
- }
303
- console.log(c.red(` ✗ couldn't link billing: ${lastLine(link)}`));
304
- }
305
- }
189
+ ui.line();
190
+ ui.para(`Found on this computer: ${listOf(found.map((cl) => cl.name))}.`);
191
+ const all = await ui.confirm(found.length === 1 ? `Add totem to ${found[0].name}?` : `Add totem to all ${found.length}?`, true);
192
+ if (!all) {
193
+ const picked = await chooseAndConnect(io, target);
194
+ return { done: picked.done && picked.client ? [picked.client.name] : [], steps: picked.steps };
306
195
  }
307
- // No usable billing account → the console is the only place to add a payment method.
308
- const url = `https://console.cloud.google.com/billing/linkedaccount?project=${p}`;
309
- console.log(c.yellow(" Add a payment method in the console (creating a billing account has no CLI)."));
310
- console.log(c.gray(` Opening: ${url}`));
311
- openUrl(url);
312
- await promptYesNo(" Press Enter once billing is enabled", true);
313
- return true;
314
- }
315
- // The full Cloud Run target picker: account → project → billing. Always offered.
316
- async function chooseGcloudTarget() {
317
- console.log(c.gray(" Choose the account + project to deploy into:"));
318
- if (!(await chooseGcloudAccount()))
319
- return false;
320
- if (!(await chooseGcloudProject()))
321
- return false;
322
- return ensureGcloudBilling();
323
- }
324
- // Fly target picker: confirm the logged-in account or switch to another. The
325
- // switch (logout + login) runs entirely in-process — `fly auth login` opens the
326
- // browser right here. Loops on decline; verifies + shows the account afterward.
327
- async function chooseFlyAccount() {
328
- const fly = commandExists("fly") ? "fly" : "flyctl";
329
- for (;;) {
330
- const who = (await withSpinner("checking Fly account", () => captureAsync(fly, ["auth", "whoami"]))).stdout.trim();
331
- const idx = await select("Deploy under which Fly account?", [
332
- { label: who || "(current account)", hint: "current" },
333
- { label: "Switch to a different account…" },
334
- ]);
335
- if (idx === 0) {
336
- console.log(c.green(` ✓ deploying as ${who || "(current account)"}`));
337
- return true;
338
- }
339
- if (!(await confirmStep("Log out of Fly and sign in as a different account?", { cmd: `${fly} auth logout && ${fly} auth login`, detail: "the browser login happens right here in this flow", defaultYes: true })))
196
+ const done = [];
197
+ const steps = [];
198
+ const opened = new Set();
199
+ for (const client of found) {
200
+ const recipe = client.recipe(target, sys);
201
+ if (recipe.kind === "link" && opened.has(recipe.url)) {
202
+ done.push(client.name);
340
203
  continue;
341
- await run(fly, ["auth", "logout"]);
342
- if ((await run(fly, ["auth", "login"])) !== 0) {
343
- console.log(c.red(" ✗ Fly login didn't complete."));
344
- if (!(await promptYesNo(" Try again?", true)))
345
- return false;
346
- continue;
347
- }
348
- const now = (await withSpinner("confirming Fly account", () => captureAsync(fly, ["auth", "whoami"]))).stdout.trim();
349
- console.log(c.green(` ✓ now signed in to Fly as ${now || "(unknown)"}`));
350
- return true;
351
- }
352
- }
353
- // Railway target picker: confirm the logged-in account or switch to another.
354
- // `railway login` runs in-process (browser / pairing happens right here). Loops
355
- // on decline; verifies + shows the account afterward.
356
- async function chooseRailwayAccount() {
357
- for (;;) {
358
- const who = (await withSpinner("checking Railway account", () => captureAsync("railway", ["whoami"]))).stdout.trim().replace(/\s+/g, " ");
359
- const idx = await select("Deploy under which Railway account?", [
360
- { label: who || "(current account)", hint: "current" },
361
- { label: "Switch to a different account…" },
362
- ]);
363
- if (idx === 0) {
364
- console.log(c.green(` ✓ deploying as ${who || "(current account)"}`));
365
- return true;
366
204
  }
367
- if (!(await confirmStep("Log out of Railway and log in as a different account?", { cmd: "railway logout && railway login", detail: "the login happens right here in this flow", defaultYes: true })))
368
- continue;
369
- await run("railway", ["logout"]);
370
- if ((await run("railway", ["login"])) !== 0) {
371
- console.log(c.red(" ✗ Railway login didn't complete."));
372
- if (!(await promptYesNo(" Try again?", true)))
373
- return false;
374
- continue;
375
- }
376
- const now = (await withSpinner("confirming Railway account", () => captureAsync("railway", ["whoami"]))).stdout.trim().replace(/\s+/g, " ");
377
- console.log(c.green(` ✓ now signed in to Railway as ${now || "(unknown)"}`));
378
- return true;
379
- }
380
- }
381
- // Merge { [key]: { [name]: entry } } into a JSON config without clobbering the
382
- // user's other servers/settings. Idempotent.
383
- function mergeJsonConfig(cfgPath, key, name, entry) {
384
- let merged = {};
385
- if (existsSync(cfgPath)) {
205
+ if (recipe.kind === "link")
206
+ opened.add(recipe.url);
207
+ // One app failing in a way totem didn't foresee (a permission error, say)
208
+ // doesn't stop the others.
386
209
  try {
387
- merged = JSON.parse(readFileSync(cfgPath, "utf8"));
210
+ const applied = await applyRecipe(io, client, recipe);
211
+ if (applied.done)
212
+ done.push(client.name);
213
+ for (const step of applied.steps)
214
+ if (!steps.includes(step))
215
+ steps.push(step);
388
216
  }
389
- catch {
390
- merged = {};
217
+ catch (error) {
218
+ ui.problem(`Couldn't set up ${client.name}.`, { detail: error instanceof Error ? error.message : String(error), fix: [["Try it alone", `totem connect ${client.id}`]] });
391
219
  }
392
220
  }
393
- const bucket = merged[key] ?? {};
394
- merged[key] = { ...bucket, [name]: entry };
395
- mkdirSync(dirname(cfgPath), { recursive: true });
396
- writeFileSync(cfgPath, JSON.stringify(merged, null, 2));
221
+ return { done, steps };
397
222
  }
398
- // A client wired by merging a JSON config file (most of them). `key` is the
399
- // top-level object: "mcpServers" for Claude Desktop/Cursor/Gemini/Windsurf,
400
- // "servers" (with a "type":"stdio" field) for VS Code.
401
- function jsonClient(label, hint, relPath, key, restart) {
402
- return {
403
- label, hint,
404
- wire: async (node, serverJs) => {
405
- const home = process.env.HOME ?? "~";
406
- const cfgPath = resolve(home, relPath);
407
- const entry = key === "servers"
408
- ? { type: "stdio", command: node, args: [serverJs] }
409
- : { command: node, args: [serverJs] };
410
- if (!(await promptYesNo(`Write the 'whoop' server into ${cfgPath}?`, true))) {
411
- console.log(c.gray(" Skipped — paste this into that file yourself:"));
412
- console.log(JSON.stringify({ [key]: { whoop: entry } }, null, 2));
413
- return false;
414
- }
415
- mergeJsonConfig(cfgPath, key, "whoop", entry);
416
- console.log(c.green(` ✓ ${label} updated`) + c.gray(` ${cfgPath}`));
417
- console.log(c.yellow(` → ${restart}`));
418
- return true;
419
- },
420
- };
223
+ function nextAfterConnect(io, steps) {
224
+ const all = [...steps, `Ask it: ${FIRST_QUESTION}`];
225
+ io.ui.next([...all.map((s, i) => `${i + 1}. ${s}`), "", "Connect another app: totem connect"]);
421
226
  }
422
- // Claude Code: wired by its own CLI.
423
- const claudeCodeClient = {
424
- label: "Claude Code", hint: "run the one-line `claude mcp add`",
425
- wire: async (node, serverJs) => {
426
- const manual = `claude mcp add whoop ${node} ${serverJs}`;
427
- if (commandExists("claude")) {
428
- if (await promptYesNo("Run `claude mcp add whoop …` now?", true)) {
429
- if ((await run("claude", ["mcp", "add", "whoop", node, serverJs])) === 0) {
430
- console.log(c.green(" ✓ added to Claude Code"));
431
- return true;
432
- }
433
- console.log(c.yellow(" That didn't work — run it yourself:"));
434
- console.log(` ${manual}`);
435
- return false;
436
- }
437
- console.log(c.gray(" Run it when ready:"));
438
- console.log(` ${manual}`);
439
- return false;
440
- }
441
- console.log(c.gray(" The `claude` CLI isn't on PATH. Install Claude Code, then run:"));
442
- console.log(` ${manual}`);
443
- return false;
444
- },
445
- };
446
- // Codex uses TOML — print the exact block (no fragile TOML merge/parse).
447
- const codexClient = {
448
- label: "Codex CLI", hint: "show the config.toml block to add",
449
- wire: async (node, serverJs) => {
450
- const home = process.env.HOME ?? "~";
451
- console.log("");
452
- console.log(c.gray(` Add this to ${resolve(home, ".codex/config.toml")} and restart Codex:`));
453
- console.log("");
454
- console.log(` [mcp_servers.whoop]`);
455
- console.log(` command = ${JSON.stringify(node)}`);
456
- console.log(` args = ${JSON.stringify([serverJs])}`);
457
- console.log("");
458
- return false;
459
- },
460
- };
461
- // Catch-all: print the universal stdio block for any other MCP client.
462
- const showConfigClient = {
463
- label: "Other / show the config", hint: "any MCP client — print the block",
464
- wire: async (node, serverJs) => {
465
- console.log("");
466
- console.log(c.gray(' Most MCP clients accept this (key is usually "mcpServers"; VS Code uses "servers" + "type":"stdio"):'));
467
- console.log(JSON.stringify({ mcpServers: { whoop: { command: node, args: [serverJs] } } }, null, 2));
468
- return false;
469
- },
470
- };
471
- const LOCAL_CLIENTS = [
472
- jsonClient("Claude Desktop", "write the config automatically", "Library/Application Support/Claude/claude_desktop_config.json", "mcpServers", "Quit and reopen Claude Desktop."),
473
- claudeCodeClient,
474
- jsonClient("Cursor", "write ~/.cursor/mcp.json", ".cursor/mcp.json", "mcpServers", "Reload Cursor (Settings → Tools & MCP)."),
475
- jsonClient("VS Code (Copilot)", "write the user mcp.json", "Library/Application Support/Code/User/mcp.json", "servers", "Reload VS Code; start the server in the MCP view."),
476
- jsonClient("Gemini CLI", "write ~/.gemini/settings.json", ".gemini/settings.json", "mcpServers", "Restart the gemini CLI."),
477
- codexClient,
478
- jsonClient("Windsurf", "write ~/.codeium/windsurf/mcp_config.json", ".codeium/windsurf/mcp_config.json", "mcpServers", "Reload Windsurf (Cascade → refresh MCP)."),
479
- showConfigClient,
480
- ];
481
- export async function runLocalSetup(root) {
482
- console.log(c.bold("\ntotem · local setup") + c.gray(" — run the MCP on this machine over stdio\n"));
483
- const TOTAL = 3;
484
- const serverJs = resolve(root, "dist", "server.js");
485
- step(1, TOTAL, "Prerequisites");
486
- if (!(await preflight([nodePrereq, depsPrereq(root), buildPrereq(root)])))
487
- return 1;
488
- step(2, TOTAL, "Whoop authentication");
489
- if (!(await ensureAuth(root)))
490
- return 1;
491
- console.log(c.green(" ✓ tokens in .env"));
492
- // Record this as a local install (overriding any stale cloud record) so
493
- // `auth` knows the tokens just go to .env — no remote to push to.
494
- writeDeployRecord(root, { platform: "local" });
495
- step(3, TOTAL, "Wire into your AI client");
496
- const idx = await select("Which client?", LOCAL_CLIENTS.map((cl) => ({ label: cl.label, hint: cl.hint })));
497
- const wired = await LOCAL_CLIENTS[idx].wire(process.execPath, serverJs);
498
- if (wired) {
499
- console.log(c.green("\n✓ Local setup complete.") + c.gray(" Restart the client, then ask: \"how am I doing today on whoop?\"\n"));
500
- }
501
- else {
502
- console.log(c.yellow("\n→ Almost done.") + c.gray(" Finish the step above + restart your client, then ask: \"how am I doing today on whoop?\"\n"));
503
- }
504
- closePrompts();
505
- return 0;
227
+ /** The server's Connect page (a button or a step for every app), offered to open in the browser. */
228
+ async function showConnectPage(io, mcpUrl) {
229
+ const page = `${mcpUrl.replace(/\/mcp$/, "")}/connect`;
230
+ await offerLink(io, "Your server's Connect page", page);
231
+ io.ui.hint("It has a button for claude.ai, Cursor and VS Code, and the steps for every other app.", 2);
232
+ return page;
506
233
  }
507
- export async function runCloudSetup(root) {
508
- console.log(c.bold("\ntotem · cloud setup") + c.gray(" — deploy a server + connect it to Claude (web, desktop, mobile)\n"));
509
- const TOTAL = 6;
510
- if (!(await preflight([nodePrereq, depsPrereq(root)])))
511
- return 1;
512
- step(1, TOTAL, "Whoop authentication");
513
- if (!(await ensureAuth(root)))
514
- return 1;
515
- const env = readEnv(root);
516
- console.log(c.green(" ✓ tokens ready"));
517
- step(2, TOTAL, "Choose a host");
518
- const platformIdx = await select("Where should the server run?", [
519
- { label: "Fly.io", hint: "fast-booting micro-VMs on a global edge network" },
520
- { label: "Railway", hint: "polished PaaS, instant deploys + a clean dashboard" },
521
- { label: "Google Cloud Run", hint: "Google Cloud's serverless containers, one instance kept warm" },
522
- { label: "Custom / own server", hint: "bring your own Docker host — a VPS, Render, a home server" },
523
- ]);
524
- const platforms = ["fly", "railway", "cloudrun", "custom"];
525
- const platform = platforms[platformIdx];
526
- // Per-host prerequisites (install the CLI, log in) — guided, auto-skipping
527
- // whatever you already have, BEFORE we generate secrets or deploy.
528
- const hostPrereqs = platform === "fly" ? flyPrereqs
529
- : platform === "railway" ? railwayPrereqs
530
- : platform === "cloudrun" ? gcloudPrereqs
531
- : [];
532
- if (hostPrereqs.length && !(await preflight(hostPrereqs)))
533
- return 1;
534
- // Account / project selection — always offered, never silently inheriting
535
- // whatever account or GCP project happens to be active. (Custom self-host has
536
- // no account concept.)
537
- const targetOk = platform === "fly" ? await chooseFlyAccount()
538
- : platform === "railway" ? await chooseRailwayAccount()
539
- : platform === "cloudrun" ? await chooseGcloudTarget()
540
- : true;
541
- if (!targetOk) {
542
- console.log(c.red(" Couldn't set the deploy target."));
543
- closePrompts();
234
+ /**
235
+ * `totem connect [client] [--print]`: connect a client to the install that is
236
+ * already set up, or show what to paste where for every client.
237
+ */
238
+ export async function runConnect(root, args, io = realIo()) {
239
+ const { ui, sys } = io;
240
+ const print = args.includes("--print");
241
+ const wanted = args.find((a) => !a.startsWith("-"));
242
+ const target = installTarget(root, io);
243
+ if (target.kind === "local" && !existsSync(target.serverJs)) {
244
+ ui.error("totem isn't set up on this computer yet.", { fix: [["Run on this computer", "totem local"], ["Or deploy a server", "totem cloud"]] });
544
245
  return 1;
545
246
  }
546
- step(3, TOTAL, "Generate secrets");
547
- const mcpToken = genToken();
548
- console.log(` MCP_AUTH_TOKEN: ${c.gray(mcpToken.slice(0, 12) + "… (generated)")}`);
549
- console.log(c.gray(" Connector password — you'll paste this into Claude once when adding the server."));
550
- console.log(c.gray(" Press Enter to auto-generate a secure 18-char one, or type your own (min 16)."));
551
- const useGenerated = (pw) => {
552
- const copied = copyToClipboard(pw);
553
- console.log(` ${c.green("✓")} generated: ${c.bold(pw)}${copied ? c.green(" ✓ copied to clipboard") : c.gray(" (copy it now)")}`);
554
- if (copied)
555
- console.log(c.gray(" (clear your clipboard after pasting — clipboard-history apps retain it)"));
556
- return pw;
557
- };
558
- let password = await prompt("Password (Enter = auto-generate)");
559
- if (password === "") {
560
- password = useGenerated(genPassword(18));
247
+ const where = target.kind === "remote" ? `your server at ${target.mcpUrl.replace(/\/mcp$/, "")}` : "the totem on this computer";
248
+ // "stdio" and "http" are what `totem config` took before it became connect.
249
+ if (wanted === "other" || wanted === "stdio" || wanted === "http") {
250
+ ui.header("totem connect", `Connect an app to ${where}.`);
251
+ printOtherClient(io, target);
252
+ return 0;
561
253
  }
562
- else {
563
- let why = weakPassword(password);
564
- while (why) {
565
- console.log(c.red(` ${why}`));
566
- password = await prompt("Password (Enter = auto-generate)");
567
- if (password === "") {
568
- password = useGenerated(genPassword(18));
569
- break;
570
- }
571
- why = weakPassword(password);
254
+ if (wanted) {
255
+ const client = findClient(wanted);
256
+ if (!client) {
257
+ ui.error(`totem doesn't know a client called "${wanted}".`, {
258
+ detail: `It knows: ${CLIENTS.map((cl) => cl.id).join(", ")}, other.`,
259
+ fix: [["See them all", "totem connect"]],
260
+ });
261
+ return 1;
572
262
  }
263
+ ui.header("totem connect", `Connect ${client.name} to ${where}.`);
264
+ const recipe = client.recipe(target, sys);
265
+ // A remote install is finished by signing in from the client, on the server's
266
+ // own page, so the address and which password it wants come first.
267
+ if (target.kind === "remote" && recipe.kind !== "unavailable") {
268
+ ui.rows([["URL", ui.kit.c.link(target.mcpUrl)], ["Password", "the connector password from totem cloud"]]);
269
+ ui.line();
270
+ }
271
+ // totem sets the client up itself when that is a file or the client's own
272
+ // command (for a server, both hold only its address). Steps in a client's
273
+ // settings, and --print, are shown instead.
274
+ if (print || recipe.kind === "steps" || recipe.kind === "unavailable") {
275
+ ui.line(ui.kit.c.bold(client.name));
276
+ ui.lines(recipeLines(recipe, ui.kit, sys));
277
+ return recipe.kind === "unavailable" ? 1 : 0;
278
+ }
279
+ const applied = await applyRecipe(io, client, recipe);
280
+ nextAfterConnect(io, applied.steps);
281
+ return 0;
573
282
  }
574
- const baseEnv = {
575
- WHOOP_EMAIL: env.WHOOP_EMAIL ?? "",
576
- WHOOP_IOS_BEARER_TOKEN: env.WHOOP_IOS_BEARER_TOKEN ?? "",
577
- WHOOP_COGNITO_REFRESH_TOKEN: env.WHOOP_COGNITO_REFRESH_TOKEN ?? "",
578
- MCP_TRANSPORT: "http",
579
- MCP_AUTH_TOKEN: mcpToken,
580
- AUTH_PASSWORD: password,
581
- WHOOP_TOKEN_STORE: "memory",
582
- };
583
- if (env.WHOOP_USER_ID)
584
- baseEnv.WHOOP_USER_ID = env.WHOOP_USER_ID;
585
- step(4, TOTAL, `Deploy to ${platform}`);
586
- const defaultName = `totem-${genToken().slice(0, 6)}`;
587
- let appName = "totem";
588
- if (platform !== "custom") {
589
- console.log(c.gray(" App name is optional — press Enter to use the suggested one in [brackets],"));
590
- console.log(c.gray(" or type your own (must be globally unique on the host)."));
591
- appName = await prompt("App name (Enter = use suggested)", defaultName);
592
- }
593
- const ctx = { root, env: baseEnv, appName, password };
594
- let url = null;
595
- if (platform === "fly")
596
- url = await deployFly(ctx);
597
- else if (platform === "railway")
598
- url = await deployRailway(ctx);
599
- else if (platform === "cloudrun")
600
- url = await deployCloudRun(ctx);
601
- else
602
- url = await deployCustom(ctx);
603
- if (!url) {
604
- console.log(c.yellow("\nDeploy didn't complete automatically. Follow the steps above, then re-run `totem cloud` or set PUBLIC_URL + redeploy manually."));
605
- closePrompts();
606
- return 1;
283
+ ui.header("totem connect", `Connect your apps to ${where}.`);
284
+ if (ui.canAsk && !print) {
285
+ if (target.kind === "remote")
286
+ await showConnectPage(io, target.mcpUrl);
287
+ const { steps } = await connectInstalled(io, target);
288
+ nextAfterConnect(io, steps);
289
+ return 0;
607
290
  }
608
- step(5, TOTAL, "Verify the server + OAuth are live");
609
- const ok = await verifyDeployment(url);
610
- if (!ok) {
611
- console.log(c.yellow(" Couldn't confirm the OAuth endpoints yet (the host may still be starting). Give it a minute, then run `totem ping`."));
291
+ ui.lines(connectCard(ui.kit, sys, { target, password: null }));
292
+ return 0;
293
+ }
294
+ // ── LOCAL ───────────────────────────────────────────────────────────────────
295
+ /** A WHOOP login on this computer: the saved one, v1's from .env, or a new browser login. */
296
+ async function ensureLocalLogin(root, io) {
297
+ const { ui } = io;
298
+ const auth = io.auth ?? realAuthDeps;
299
+ const env = auth.cliEnv(resolve(root, ".env"));
300
+ const local = auth.readLocalStatus(resolveTokenFilePath(env));
301
+ if (local.state === "tokens") {
302
+ ui.ok("Already logged in to WHOOP", `saved ${when(local.savedAt)}`);
303
+ ui.hint("To log in again: totem auth --local");
304
+ return true;
612
305
  }
613
- // Use ctx.appName, not the local appName: a Fly name conflict may have changed
614
- // it during deploy, and `auth` must push to the app that was actually used.
615
- const extra = {};
616
- if (platform === "cloudrun") {
617
- extra.region = "us-west1";
618
- const proj = capture("gcloud", ["config", "get-value", "project"]).stdout.trim();
619
- if (proj)
620
- extra.project = proj;
306
+ if (local.state !== "handed-off" && migrateFromEnv(env)) {
307
+ ui.ok("Using the WHOOP login from totem 1.x", "the server moves it out of .env on first start");
308
+ return true;
621
309
  }
622
- writeDeployRecord(root, { platform, app: ctx.appName, url, ...extra });
623
- step(6, TOTAL, "Connect your AI");
624
- printConnectInstructions(url, password, mcpToken);
625
- closePrompts();
626
- return 0;
310
+ return (await runAuth(root, ["--local"], { embedded: true }, io)) === 0;
627
311
  }
628
- // ── verification ─────────────────────────────────────────────────────────────
629
- async function verifyDeployment(baseUrl) {
630
- const root = baseUrl.replace(/\/(mcp)?$/, "");
631
- // Poll fast: a short per-attempt timeout means a not-yet-propagated DNS / cold
632
- // start fails in ~3s instead of hanging the full 12s default, and a tight 1.5s
633
- // interval detects readiness within ~1.5s of the host coming up. (Previously a
634
- // 12s timeout × 3s sleep × 10 made this feel like ~3 minutes.)
635
- const start = Date.now();
636
- const deadline = start + 90_000;
637
- let healthy = false;
638
- // Live elapsed counter so a slow DNS-propagation / cold-start wait visibly ticks.
639
- const s = spin(() => `waiting for ${root} (DNS + first boot) — ${Math.floor((Date.now() - start) / 1000)}s`);
640
- while (Date.now() < deadline) {
641
- const health = await httpGet(`${root}/health`, 3000);
642
- if (health.status === 200) {
643
- healthy = true;
644
- break;
312
+ export async function runLocalSetup(root, io = realIo()) {
313
+ const { ui } = io;
314
+ const TOTAL = 3;
315
+ ui.banner("totem local", "Run totem on this computer and connect your AI apps to it.");
316
+ // `totem local` records this install as local. If it is recorded as deployed,
317
+ // that record (and the server's token in it) is what `totem auth`, `status`
318
+ // and `logs` use: don't drop it without asking.
319
+ const record = readDeployRecord(root, io.sys);
320
+ if (record && record.platform !== "local" && record.url) {
321
+ ui.warn(`This install is set up for the server at ${record.url}.`);
322
+ ui.hint("Setting it up locally makes this computer forget that server (the server itself keeps running). A local server and a deployment must not share one WHOOP login.");
323
+ if (!(await ui.confirm("Switch this install to local?", false))) {
324
+ ui.hint("Nothing changed. To connect a client to the server: totem connect");
325
+ return 1;
645
326
  }
646
- await new Promise((r) => setTimeout(r, 1500));
647
327
  }
648
- s.stop();
649
- console.log(` /health: ${healthy ? c.green("200 ✓") : c.red("timeout")}`);
650
- const prm = await withSpinner("checking OAuth metadata", () => httpGet(`${root}/.well-known/oauth-protected-resource/mcp`, 5000));
651
- const prmOk = prm.status === 200 && prm.body.includes("/mcp");
652
- console.log(` OAuth metadata: ${prmOk ? c.green("✓") : c.red("not found")}`);
653
- // Prove the auth gate is live: an unauthenticated /mcp must be REJECTED (401),
654
- // not served. Catches a regression that left the endpoint open to the public.
655
- const gate = await withSpinner("checking /mcp is auth-gated", () => httpGet(`${root}/mcp`, 5000));
656
- const gated = gate.status === 401;
657
- console.log(` /mcp auth gate: ${gated ? c.green("401 ✓ (rejects unauthenticated)") : c.red(`${gate.status || "no response"} — expected 401`)}`);
658
- return healthy && prmOk && gated;
659
- }
660
- function printConnectInstructions(url, password, mcpToken) {
661
- const mcpUrl = url.replace(/\/$/, "") + "/mcp";
662
- // Header-auth clients (CLIs / editors) hit the server directly with the static
663
- // bearer token; OAuth clients (claude.ai, ChatGPT) use the password gate.
664
- const headerBlock = JSON.stringify({ mcpServers: { whoop: { url: mcpUrl, headers: { Authorization: `Bearer ${mcpToken}` } } } }, null, 2).split("\n").map((l) => " " + l).join("\n");
665
- console.log("");
666
- console.log(c.bold(" ── Connect your AI ──────────────────────────────────────────"));
667
- console.log("");
668
- console.log(c.bold(" claude.ai") + c.gray(" (web · desktop · mobile — syncs across your devices)"));
669
- console.log(` Settings → Connectors → ${c.bold("Add custom connector")}`);
670
- console.log(` URL: ${c.brand(mcpUrl)} Password: ${c.brand(password)}`);
671
- console.log("");
672
- console.log(c.bold(" ChatGPT") + c.gray(" (desktop)"));
673
- console.log(` Settings → Connectors → ${c.bold("Add")} · URL: ${c.brand(mcpUrl)} Password: ${c.brand(password)}`);
674
- console.log("");
675
- console.log(c.bold(" Claude Code") + c.gray(" (remote)"));
676
- console.log(` ${c.gray("$")} claude mcp add --transport http whoop ${mcpUrl} --header "Authorization: Bearer ${mcpToken}"`);
677
- console.log("");
678
- console.log(c.bold(" Cursor · Windsurf · any HTTP MCP client") + c.gray(" — config block:"));
679
- console.log(headerBlock);
680
- console.log("");
681
- // Best-effort: open the connectors page in the browser (cross-platform).
682
- openUrl("https://claude.ai/settings/connectors");
683
- console.log(c.gray(" (opened the claude.ai connectors page in your browser)"));
684
- console.log(c.green("\n✓ Cloud setup complete.\n"));
685
- }
686
- // ── platform adapters ────────────────────────────────────────────────────────
687
- function setSummary(env) {
688
- console.log(c.gray(" env to set: " + Object.keys(env).join(", ")));
328
+ ui.step(1, TOTAL, "Prerequisites");
329
+ if (!(await prerequisites(root, io, true)))
330
+ return 1;
331
+ ui.step(2, TOTAL, "WHOOP login");
332
+ if (!(await ensureLocalLogin(root, io)))
333
+ return 1;
334
+ writeDeployRecord(root, { platform: "local" }, io.sys);
335
+ ui.step(3, TOTAL, "Connect your apps");
336
+ const { steps } = await connectInstalled(io, localTarget(root, io));
337
+ nextAfterConnect(io, steps);
338
+ return 0;
689
339
  }
690
- // ── shared failure handling ──────────────────────────────────────────────────
691
- // The last meaningful line of a captured (spinner-wrapped) command's output —
692
- // so when a step that DIDN'T stream live fails, we can still show WHY.
693
- function lastLine(r) {
694
- const lines = (r.stderr + "\n" + r.stdout).split("\n").map((l) => l.trim()).filter(Boolean);
695
- return lines.length ? lines[lines.length - 1] : "unknown error";
340
+ const HOSTS = [
341
+ { id: "cloudflare", name: "Cloudflare", hint: "Workers free plan; no card, no machine (recommended)" },
342
+ { id: "fly", name: "Fly.io", hint: "one always-on machine, about $4 a month" },
343
+ { id: "railway", name: "Railway", hint: "managed, with a dashboard; needs Railway's paid plan" },
344
+ { id: "custom", name: "My own server", hint: "any Docker host; totem prints the commands" },
345
+ ];
346
+ const worked = (r) => (typeof r === "boolean" ? r : r.code === 0);
347
+ /**
348
+ * A host CLI's output with this deploy's secrets blanked. totem shows the
349
+ * latest line a command printed and, when it fails, the end of its output; a
350
+ * CLI that echoes what it was given must not put the token or the password on
351
+ * screen that way.
352
+ */
353
+ function redact(d, text) {
354
+ let out = text;
355
+ for (const secret of [d.env.MCP_AUTH_TOKEN, d.env.AUTH_PASSWORD]) {
356
+ if (!secret)
357
+ continue;
358
+ for (const form of secretForms(secret))
359
+ out = out.split(form).join("***");
360
+ }
361
+ return out;
696
362
  }
697
- // Run an inherited-stdio action (its error is already printed on screen by the
698
- // tool) and, on failure, let the user retry it or give up. Loops until success
699
- // or the user declines. Returns true once it succeeds.
700
- async function runWithRetry(desc, action) {
701
- for (;;) {
702
- console.log(c.gray(` ${desc}…`));
703
- if ((await action()) === 0)
704
- return true;
705
- console.log(c.red(" ✗ that failed — the error is shown above."));
706
- if (!(await promptYesNo(" Retry it?", true)))
707
- return false;
363
+ /**
364
+ * A secret as given, and the ways a CLI writes it back: inside JSON, in a URL
365
+ * or a form body. The generated token and password read the same in all of
366
+ * them; a password the person chose (spaces, quotes, &, \) does not, and the
367
+ * plain text alone would let the escaped one through.
368
+ */
369
+ export function secretForms(secret) {
370
+ const forms = [secret, JSON.stringify(secret).slice(1, -1)];
371
+ try {
372
+ const percent = encodeURIComponent(secret);
373
+ forms.push(percent, percent.replace(/%20/g, "+"));
708
374
  }
375
+ catch { /* a lone surrogate has no percent form */ }
376
+ return [...new Set(forms)].filter(Boolean);
709
377
  }
710
- // Ask for a public URL, re-asking (with a clear reason) on empty or malformed
711
- // input instead of bailing the whole flow. Accepts a bare domain (prepends
712
- // https://) and strips trailing slashes. Ctrl-C is the only way out.
713
- async function promptUrl(message) {
714
- const tty = Boolean(process.stdin.isTTY);
715
- for (;;) {
716
- let url = (await prompt(message)).trim();
717
- if (url) {
718
- if (!/^https?:\/\//i.test(url))
719
- url = "https://" + url; // accept a bare domain
720
- if (/^https?:\/\/[^/.\s]+\.[^/\s]+/.test(url))
721
- return url.replace(/\/+$/, "");
722
- console.log(c.red(` '${url}' isn't a valid URL (e.g. https://whoop.example.com) — try again.`));
723
- }
724
- else {
725
- console.log(c.red(" A URL is required — paste it, or press Ctrl-C to cancel."));
378
+ /** A host command: captured under a spinner showing its latest line, or attached with --verbose. */
379
+ function hostCommand(d, cmd, args, input) {
380
+ const { ui, sys } = d.io;
381
+ return async (set) => {
382
+ if (d.verbose && input === undefined) {
383
+ ui.hint(`$ ${cmd} ${maskSecrets(args)}`);
384
+ return (await sys.run(cmd, args, { cwd: d.root })) === 0;
726
385
  }
727
- // No interactive terminal (piped/EOF) → "" forever; don't spin, just stop.
728
- if (!tty) {
729
- console.log(c.red(" (no terminal to re-ask on — stopping.)"));
730
- process.exit(1);
731
- }
732
- }
386
+ return sys.exec(cmd, args, input === undefined ? { cwd: d.root, onLine: set } : { cwd: d.root, input, onLine: set });
387
+ };
733
388
  }
734
- // Ask for a required free-text value, re-asking (with a reason) on empty or
735
- // invalid input instead of bailing the flow. Optional validator returns an error
736
- // string to show + re-ask, or null when the value is good. Ctrl-C is the way out.
737
- async function promptRequired(message, opts = {}) {
738
- const tty = Boolean(process.stdin.isTTY);
389
+ /** Run one step. On failure show why and let the person retry, skip (if it can be) or stop. */
390
+ async function runStep(d, step) {
391
+ const { ui, sys } = d.io;
739
392
  for (;;) {
740
- const v = (await (opts.hidden ? promptHidden(message) : prompt(message))).trim();
741
- if (v) {
742
- const err = opts.validate ? opts.validate(v) : null;
743
- if (!err)
744
- return v;
745
- console.log(c.red(` ${err}`));
393
+ const started = sys.now();
394
+ let result = false;
395
+ // An attached command prints for itself: say what it is first.
396
+ if (step.attached || d.verbose)
397
+ ui.info(`${step.label}${ui.kit.g.ellipsis}`);
398
+ for (let attempt = 0; attempt <= (step.retries ?? 0); attempt++) {
399
+ if (attempt > 0)
400
+ await ui.task(`The host didn't answer; trying again (${attempt}/${step.retries})`, () => sys.sleep(2500));
401
+ result = step.attached || d.verbose
402
+ ? await step.run(() => { })
403
+ : await ui.task(step.label, (set) => step.run((line) => set(redact(d, line))), { slow: Boolean(step.slow) });
404
+ if (worked(result))
405
+ break;
746
406
  }
747
- else {
748
- console.log(c.red(" Required — enter a value, or press Ctrl-C to cancel."));
407
+ if (worked(result)) {
408
+ ui.ok(step.done, duration(sys.now() - started));
409
+ return "ok";
749
410
  }
750
- if (!tty) {
751
- console.log(c.red(" (no terminal to re-ask on — stopping.)"));
752
- process.exit(1);
411
+ ui.problem(`${step.label} failed.`, { detail: typeof result === "boolean" ? undefined : tail(result).map((line) => redact(d, line)) });
412
+ const choices = [
413
+ { label: "Try again" },
414
+ ...(step.optional ? [{ label: "Skip this step", hint: step.optional }] : []),
415
+ { label: "Stop here" },
416
+ ];
417
+ const pick = await ui.select("What now?", choices);
418
+ if (pick === 0)
419
+ continue;
420
+ if (step.optional && pick === 1) {
421
+ ui.warn(`Skipped. ${step.optional}`);
422
+ return "skipped";
753
423
  }
424
+ return "cancelled";
754
425
  }
755
426
  }
756
- // FLY — deploys as fast-booting micro-VMs via flyctl.
757
- // Create the Fly app, retrying with a new name when the chosen one is taken by
758
- // ANOTHER account (Fly app names are globally unique). If you already own an app
759
- // by that name, reuse it. Mutates ctx.appName to whatever name actually worked.
760
- async function createFlyApp(fly, ctx) {
761
- if (!(await confirmStep(`Create Fly app '${ctx.appName}'?`, { cmd: `fly apps create ${ctx.appName}`, detail: "reserves the name + URL on your Fly account", defaultYes: true })))
762
- return false;
763
- for (let attempt = 0; attempt < 10; attempt++) {
764
- const create = await withSpinner(`creating ${ctx.appName}`, () => captureAsync(fly, ["apps", "create", ctx.appName, "--json"]));
765
- if (create.code === 0) {
766
- console.log(c.green(` ✓ created ${ctx.appName}`));
767
- return true;
768
- }
769
- // Already on YOUR account? (re-running cloud, or a half-finished prior attempt) → reuse it.
770
- const mine = await withSpinner("checking your Fly apps", () => captureAsync(fly, ["apps", "list"]));
771
- if (new RegExp(`(^|\\s)${ctx.appName}(\\s|$)`, "m").test(mine.stdout)) {
772
- console.log(c.gray(` '${ctx.appName}' already exists on your account — reusing it.`));
773
- return true;
774
- }
775
- // Taken by someone else (or another error): SHOW it, then retry with a new name.
776
- console.log(c.red(` ✗ couldn't create '${ctx.appName}': ${lastLine(create)}`));
777
- console.log(c.yellow(" Fly app names are globally unique, so that one's unavailable — pick another."));
778
- const fresh = `totem-${genToken().slice(0, 6)}`;
779
- ctx.appName = (await prompt("New app name (Enter = unique suggestion)", fresh)).trim() || fresh;
780
- }
781
- console.log(c.red(" Too many name attempts — aborting the Fly deploy."));
782
- return false;
783
- }
784
- async function deployFly(ctx) {
785
- const fly = commandExists("fly") ? "fly" : "flyctl";
786
- if (!(await createFlyApp(fly, ctx)))
787
- return null;
788
- const url = `https://${ctx.appName}.fly.dev`;
789
- const env = { ...ctx.env, PUBLIC_URL: url };
790
- // Minimal fly.toml so `fly deploy` is non-interactive (builds the Dockerfile).
791
- writeFileSync(resolve(ctx.root, "fly.toml"), [
792
- `app = "${ctx.appName}"`,
793
- `primary_region = "sjc"`,
427
+ // FLY ─────────────────────────────────────────────────────────────────────────
428
+ /**
429
+ * The fly.toml `totem cloud` writes. With a volume, [mounts] puts it at /data,
430
+ * where the image keeps the WHOOP token file (TOTEM_TOKEN_FILE=/data/tokens.json),
431
+ * so the login survives restarts and deploys.
432
+ */
433
+ export function flyToml(appName, withVolume) {
434
+ return [
435
+ `app = "${appName}"`,
436
+ `primary_region = "${FLY_REGION}"`,
794
437
  ``,
795
438
  `[build]`,
796
439
  ``,
440
+ ...(withVolume
441
+ ? [
442
+ `# The WHOOP login lives here (/data/tokens.json). WHOOP rotates the refresh`,
443
+ `# token on every refresh, so it must survive restarts.`,
444
+ `[mounts]`,
445
+ ` source = "${FLY_VOLUME}"`,
446
+ ` destination = "/data"`,
447
+ ``,
448
+ ]
449
+ : []),
450
+ `# One small machine: 512 MB is enough, and with the volume it stays under`,
451
+ `# Fly's $5 a month at current prices.`,
452
+ `[[vm]]`,
453
+ ` size = "${FLY_VM.size}"`,
454
+ ` memory = "${FLY_VM.memory}"`,
455
+ ``,
797
456
  `[http_service]`,
798
457
  ` internal_port = 3000`,
799
458
  ` force_https = true`,
@@ -803,325 +462,806 @@ async function deployFly(ctx) {
803
462
  ` auto_start_machines = true`,
804
463
  ` min_machines_running = 1`,
805
464
  ``,
806
- ].join("\n"));
807
- // Set secrets (staged; applied on deploy) — surface the error if it fails.
808
- // `secrets import` reads KEY=val from stdin, keeping the token + password
809
- // values off the argv (which any local user could read via `ps`/`/proc`).
810
- const secretLines = Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
811
- const stage = await withSpinner("staging secrets", () => captureAsync(fly, ["secrets", "import", "--stage", "--app", ctx.appName], { cwd: ctx.root, input: secretLines }));
812
- if (stage.code !== 0) {
813
- console.log(c.yellow(` staging secrets failed (${lastLine(stage)}) — applying directly`));
814
- const direct = await withSpinner("setting secrets", () => captureAsync(fly, ["secrets", "import", "--app", ctx.appName], { cwd: ctx.root, input: secretLines }));
815
- if (direct.code !== 0)
816
- console.log(c.red(` ✗ couldn't set secrets: ${lastLine(direct)}`));
817
- }
818
- // Build + deploy — error visible (inherited stdio) + retry-on-failure.
819
- if (!(await confirmStep("Build + deploy to Fly now?", { cmd: `fly deploy --app ${ctx.appName}`, detail: "builds the Dockerfile and starts a billable machine (~1-2 min)", defaultYes: true })))
820
- return null;
821
- if (!(await runWithRetry(`deploying ${ctx.appName} (builds the Dockerfile, ~1-2 min)`, () => run(fly, ["deploy", "--app", ctx.appName, "--ha=false"], { cwd: ctx.root }))))
822
- return null;
823
- return url;
465
+ ].join("\n");
824
466
  }
825
- // Shared "assisted" deploy used by Railway + Cloud Run: install/login the host
826
- // CLI, run its deploy commands (each retryable), auto-detect the deployed URL
827
- // (falling back to a paste only if detection fails), then set PUBLIC_URL for OAuth.
828
- async function assistedDeploy(opts) {
829
- if (!commandExists(opts.cliName)) {
830
- if (!(await ensureCli(opts.cliName, opts.install)))
831
- return null;
832
- }
833
- if (!opts.loginCheck()) {
834
- console.log(c.gray(` Logging into ${opts.cliName}…`));
835
- if (await opts.loginCmd() !== 0)
836
- return null;
837
- }
838
- setSummary(opts.ctx.env);
839
- for (const s of opts.steps) {
840
- if (s.confirm) {
841
- const proceed = await confirmStep(s.confirm.summary, s.confirm);
842
- if (!proceed) {
843
- if (s.confirm.skippable) {
844
- console.log(c.gray(` ↷ skipped: ${s.desc}`));
845
- continue;
846
- }
847
- console.log(c.yellow(" Cancelled — this step is required, stopping here."));
848
- return null;
849
- }
467
+ async function deployFly(d) {
468
+ const { ui, sys } = d.io;
469
+ const fly = d.cli;
470
+ // The app. Names are unique across all of Fly: one you already own is reused
471
+ // (a re-run, or a half-finished earlier attempt); one someone else has needs
472
+ // another name.
473
+ for (let attempt = 0;; attempt++) {
474
+ const name = d.appName;
475
+ const create = await ui.task(`Creating the app ${name}`, () => sys.exec(fly, ["apps", "create", name, "--json"], { cwd: d.root }));
476
+ if (create.code === 0) {
477
+ ui.ok("App created", name);
478
+ break;
850
479
  }
851
- console.log(c.gray(` → ${s.desc}`));
852
- const tries = (s.retries ?? 0) + 1;
853
- let ok = false;
854
- for (let i = 0; i < tries && !ok; i++) {
855
- if (i > 0) {
856
- console.log(c.yellow(` API hiccup — retry ${i}/${s.retries}`));
857
- await pause(2500, "backing off before retry");
858
- }
859
- if (s.run)
860
- ok = await s.run();
861
- else {
862
- console.log(c.gray(` $ ${s.cmd[0]} ${maskArgs(s.cmd[1])}`));
863
- ok = (await run(s.cmd[0], s.cmd[1], { cwd: opts.ctx.root })) === 0;
864
- }
480
+ const mine = await ui.task("Checking your Fly apps", () => sys.exec(fly, ["apps", "list"], { cwd: d.root }));
481
+ if (new RegExp(`(^|\\s)${name}(\\s|$)`, "m").test(mine.stdout)) {
482
+ ui.ok("App already exists on your account; using it", name);
483
+ break;
865
484
  }
866
- // Auto-retries (above) exhausted and still failing: surface it + let the user
867
- // retry as many times as they like, skip it, or abort. The error is already
868
- // on screen (inherited stdio).
869
- while (!ok) {
870
- console.log(c.red(` ✗ step failed: ${s.desc} — the error is shown above.`));
871
- const choice = await select("How do you want to handle it?", [
872
- { label: "Retry this step" },
873
- { label: "Skip it and continue", hint: "you'll fix it manually" },
874
- { label: "Abort the deploy" },
875
- ]);
876
- if (choice === 0) {
877
- if (s.run)
878
- ok = await s.run();
879
- else {
880
- console.log(c.gray(` $ ${s.cmd[0]} ${maskArgs(s.cmd[1])}`));
881
- ok = (await run(s.cmd[0], s.cmd[1], { cwd: opts.ctx.root })) === 0;
882
- }
883
- }
884
- else if (choice === 1) {
885
- console.log(c.gray(` ↷ skipped: ${s.desc}`));
886
- break;
887
- }
888
- else {
889
- return null;
890
- }
485
+ if (attempt >= 9) {
486
+ ui.problem("Couldn't create a Fly app after ten names.", { detail: lastLine(create) });
487
+ return null;
891
488
  }
489
+ ui.warn(`Fly wouldn't create "${name}": ${lastLine(create)}`);
490
+ ui.hint("App names are unique across all of Fly, so someone else may have this one.");
491
+ const fresh = `totem-${sys.token().slice(0, 6)}`;
492
+ d.appName = (await ui.text("Another app name", fresh)).trim() || fresh;
892
493
  }
893
- // Auto-detect the deployed URL (the deploy just printed it); only fall back to
894
- // asking the user to paste if detection failed.
895
- const detected = opts.getUrl ? await opts.getUrl() : null;
896
- let url;
897
- if (detected) {
898
- url = detected.replace(/\/+$/, "");
899
- console.log(c.green(` ✓ detected URL: ${url}`));
494
+ d.cleanup = ["Remove the unfinished app", `${fly} apps destroy ${d.appName}`];
495
+ const url = `https://${d.appName}.fly.dev`;
496
+ const env = { ...d.env, PUBLIC_URL: url };
497
+ // The volume the WHOOP login lives on.
498
+ const list = await ui.task("Looking for the login volume", () => sys.exec(fly, ["volumes", "list", "--app", d.appName, "--json"], { cwd: d.root }));
499
+ let volume = list.code === 0 && new RegExp(`"name"\\s*:\\s*"${FLY_VOLUME}"`).test(list.stdout);
500
+ if (volume) {
501
+ ui.ok("Volume already exists", FLY_VOLUME);
900
502
  }
901
503
  else {
902
- url = await promptUrl("Paste your deployment's public URL (e.g. https://your-app.up.railway.app)");
903
- }
904
- // OAuth's issuer must equal the real URL, which we only know now — so set
905
- // PUBLIC_URL and redeploy automatically (run() inherits stdio → the user sees
906
- // progress) rather than asking them to run a command in a second terminal.
907
- if (!(await confirmStep("Set PUBLIC_URL and redeploy so OAuth works?", { detail: `points the server's OAuth issuer at ${url} (required for web/mobile connectors)`, defaultYes: true }))) {
908
- console.log(c.yellow(` Skipped. OAuth won't work until you set PUBLIC_URL=${url} and redeploy yourself.`));
909
- return url;
910
- }
911
- console.log(c.gray(" Setting PUBLIC_URL + redeploying so OAuth works…"));
912
- for (const [cmd, args] of opts.setPublicUrlCmds(url)) {
913
- console.log(c.gray(` $ ${cmd} ${args.join(" ")}`));
914
- let ok = false;
915
- for (let i = 0; i < 4 && !ok; i++) {
916
- if (i > 0) {
917
- console.log(c.yellow(` API hiccup — retry ${i}/3`));
918
- await pause(2500, "backing off before retry");
919
- }
920
- ok = (await run(cmd, args, { cwd: opts.ctx.root })) === 0;
921
- }
922
- while (!ok) {
923
- console.log(c.red(" ✗ that command failed — the error is shown above."));
924
- const choice = await select("How do you want to handle it?", [
925
- { label: "Retry it" },
926
- { label: "Skip and continue", hint: "OAuth won't work until you set PUBLIC_URL yourself" },
927
- { label: "Abort" },
928
- ]);
929
- if (choice === 0)
930
- ok = (await run(cmd, args, { cwd: opts.ctx.root })) === 0;
931
- else if (choice === 1)
932
- break;
933
- else
934
- return null;
935
- }
504
+ const made = await runStep(d, {
505
+ label: "Creating the volume", done: `Volume created`,
506
+ run: hostCommand(d, fly, ["volumes", "create", FLY_VOLUME, "--app", d.appName, "--region", FLY_REGION, "--size", "1", "--yes"]),
507
+ optional: "Without a volume the server loses its WHOOP login on every restart.",
508
+ });
509
+ if (made === "cancelled")
510
+ return null;
511
+ volume = made === "ok";
936
512
  }
937
- return url;
513
+ // Minimal fly.toml so `fly deploy` asks nothing (it builds the Dockerfile in
514
+ // the install). It lives in totem's config folder, not the install, which an
515
+ // npm update replaces: without it the next deploy would drop the volume.
516
+ const flyConfig = configFile(sys, "fly.toml");
517
+ writeFileAtomic(flyConfig, flyToml(d.appName, volume), 0o644);
518
+ // Secrets: `secrets import` reads KEY=value lines from stdin, so the token and
519
+ // password never appear on a command line. Staged, they apply on deploy.
520
+ const secretLines = Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
521
+ const secrets = await runStep(d, {
522
+ label: "Setting the secrets", done: "Secrets set",
523
+ run: async (set) => {
524
+ const staged = await sys.exec(fly, ["secrets", "import", "--stage", "--app", d.appName], { cwd: d.root, input: secretLines, onLine: set });
525
+ if (staged.code === 0)
526
+ return staged;
527
+ return sys.exec(fly, ["secrets", "import", "--app", d.appName], { cwd: d.root, input: secretLines, onLine: set });
528
+ },
529
+ });
530
+ if (secrets !== "ok")
531
+ return null;
532
+ const deployed = await runStep(d, {
533
+ label: "Building and deploying on Fly", done: "Deployed", slow: true,
534
+ run: hostCommand(d, fly, ["deploy", "--config", flyConfig, "--app", d.appName, "--ha=false"]),
535
+ });
536
+ return deployed === "ok" ? url : null;
537
+ }
538
+ // RAILWAY ─────────────────────────────────────────────────────────────────────
539
+ const SECRET_KEY = /(TOKEN|PASSWORD|SECRET)/i;
540
+ /**
541
+ * The one service totem creates in its Railway project. Every Railway command
542
+ * names it: \`railway up\` makes a service without linking it, so a later
543
+ * command that relies on the link fails with "No service found".
544
+ */
545
+ export const RAILWAY_SERVICE = "totem";
546
+ /**
547
+ * The `railway` invocations that set `env` on the linked service, with every
548
+ * secret value on stdin (`railway variable set KEY --stdin`) instead of the
549
+ * command line, where any local user could read it from `ps` while the command
550
+ * runs. Secrets go first with --skip-deploys; the plain values go last in one
551
+ * call, which triggers the single redeploy. Empty values are skipped (Railway
552
+ * rejects them).
553
+ */
554
+ export function railwayVariableCommands(env, opts = {}) {
555
+ const entries = Object.entries(env).filter(([, v]) => v !== "");
556
+ const secrets = entries.filter(([k]) => SECRET_KEY.test(k));
557
+ const plain = entries.filter(([k]) => !SECRET_KEY.test(k));
558
+ const service = opts.service ? ["--service", opts.service] : [];
559
+ // With deploy: false every call skips deploying (the caller deploys once, later).
560
+ const skip = (last) => (opts.deploy === false || !last ? ["--skip-deploys"] : []);
561
+ const commands = secrets.map(([k, v], i) => ({
562
+ args: ["variable", "set", k, "--stdin", ...service, ...skip(!plain.length && i === secrets.length - 1)],
563
+ input: v,
564
+ }));
565
+ if (plain.length)
566
+ commands.push({ args: ["variable", "set", ...plain.map(([k, v]) => `${k}=${v}`), ...service, ...skip(true)] });
567
+ return commands;
938
568
  }
939
- // Railway's GraphQL API (backboard.railway.com) intermittently times out, and a
940
- // timed-out `init` can still create the project server-side. So: try init, and if
941
- // it fails, check whether the project got created and LINK to it instead of
942
- // re-running init (which would pile up duplicate projects). Retries the flaky API.
943
- async function railwayHasProject(appName) {
944
- for (let i = 0; i < 3; i++) {
945
- const r = await withSpinner("checking Railway for the project", () => captureAsync("railway", ["list"]));
946
- if (r.code === 0)
947
- return r.stdout.includes(appName);
569
+ /**
570
+ * Set `env` on the linked Railway service. A Railway CLI too old to know
571
+ * `variable set --stdin` gets the values the old way (`variables --set`), and
572
+ * `onOldCli` is told: that is the only case a secret reaches a command line.
573
+ */
574
+ export async function setRailwayVariables(env, root, exec, onOldCli = () => { }, opts = {}) {
575
+ let last = { code: 0, stdout: "", stderr: "" };
576
+ for (const { args, input } of railwayVariableCommands(env, opts)) {
577
+ last = await exec("railway", args, input === undefined ? { cwd: root } : { cwd: root, input });
578
+ if (last.code === 0)
579
+ continue;
580
+ if (/unexpected argument|unrecognized subcommand|wasn't expected|found argument/i.test(last.stderr + last.stdout)) {
581
+ onOldCli();
582
+ const legacy = [
583
+ "variables", ...Object.entries(env).filter(([, v]) => v !== "").flatMap(([k, v]) => ["--set", `${k}=${v}`]),
584
+ ...(opts.service ? ["--service", opts.service] : []), ...(opts.deploy === false ? ["--skip-deploys"] : []),
585
+ ];
586
+ return exec("railway", legacy, { cwd: root });
587
+ }
588
+ return last;
948
589
  }
949
- return false;
590
+ return last;
950
591
  }
951
- async function railwayInitOrLink(appName, root) {
592
+ // Railway's API (backboard.railway.com) intermittently times out, and a
593
+ // timed-out `init` can still have created the project. So: try init, and if it
594
+ // fails, look for the project and LINK to it instead of running init again
595
+ // (which would pile up duplicate projects).
596
+ async function railwayInitOrLink(d) {
597
+ const { ui, sys } = d.io;
952
598
  for (let attempt = 1; attempt <= 4; attempt++) {
953
- if (attempt > 1) {
954
- console.log(c.yellow(` Railway API hiccup — retry ${attempt - 1}/3`));
955
- await pause(2500, "backing off (Railway's API is flaky)");
956
- }
957
- console.log(c.gray(` $ railway init --name ${appName}`));
958
- if ((await run("railway", ["init", "--name", appName], { cwd: root })) === 0)
599
+ if (attempt > 1)
600
+ await ui.task(`Railway didn't answer; trying again (${attempt - 1}/3)`, () => sys.sleep(2500));
601
+ if ((await sys.run("railway", ["init", "--name", d.appName], { cwd: d.root })) === 0)
959
602
  return true;
960
- // init's response may have timed out AFTER creating the project — link to it.
961
- if (await railwayHasProject(appName)) {
962
- console.log(c.gray(" (init's response timed out, but the project exists — linking to it)"));
963
- console.log(c.gray(` $ railway link --project ${appName}`));
964
- if ((await run("railway", ["link", "--project", appName], { cwd: root })) === 0)
603
+ let exists = false;
604
+ for (let i = 0; i < 3 && !exists; i++) {
605
+ const r = await ui.task("Checking whether Railway made the project", () => sys.exec("railway", ["list"], { cwd: d.root }));
606
+ if (r.code === 0) {
607
+ exists = r.stdout.includes(d.appName);
608
+ break;
609
+ }
610
+ }
611
+ if (exists) {
612
+ ui.hint("Railway timed out but did create the project; linking to it.");
613
+ if ((await sys.run("railway", ["link", "--project", d.appName], { cwd: d.root })) === 0)
965
614
  return true;
966
615
  }
967
616
  }
968
- console.log(c.red(" Railway's API (backboard.railway.com) kept timing out. Give it a minute and re-run."));
969
617
  return false;
970
618
  }
971
- // RAILWAY — CLI-automatable; resilient to Railway's flaky GraphQL API.
972
- async function deployRailway(ctx) {
973
- // Railway rejects `--set KEY=` (empty value), and PUBLIC_URL isn't known until
974
- // `domain` runs — so set the non-empty vars now, PUBLIC_URL in the 2nd pass.
975
- const varArgs = ["variables"];
976
- for (const [k, v] of Object.entries(ctx.env)) {
977
- if (v === "")
978
- continue;
979
- varArgs.push("--set", `${k}=${v}`);
980
- }
981
- return assistedDeploy({
982
- cliName: "railway",
983
- install: { npmPkg: "@railway/cli", brewPkg: "railway", manualHint: "npm i -g @railway/cli (or: brew install railway)" },
984
- loginCheck: () => capture("railway", ["whoami"]).code === 0,
985
- loginCmd: () => run("railway", ["login"]),
986
- steps: [
987
- // init creates a PROJECT (not a service); `up` creates the service, so it
988
- // runs first (deploys env-less + crashes once, then variables redeploys it
989
- // healthy). init is special — a timeout may have still created it, so we
990
- // link rather than re-init; the rest retry the flaky API.
991
- {
992
- desc: "create the project",
993
- run: () => railwayInitOrLink(ctx.appName, ctx.root),
994
- confirm: { summary: `Create a new Railway project '${ctx.appName}'?`, detail: "a new project on your Railway account", defaultYes: true },
995
- },
996
- {
997
- desc: "deploy (creates the service + builds the Dockerfile)",
998
- cmd: ["railway", ["up", "--detach"]],
999
- retries: 3,
1000
- confirm: { summary: "Deploy to Railway now?", detail: "creates a service + starts a build on your Railway account", defaultYes: true },
619
+ async function deployRailway(d) {
620
+ const { ui, sys } = d.io;
621
+ const svc = ["--service", RAILWAY_SERVICE];
622
+ d.cleanup = ["Remove the unfinished project", `railway delete --project ${d.appName}`];
623
+ // The secrets and the address are in place before the first build, so it
624
+ // starts ready to sign in. The volume comes after it: Railway's CLI can only
625
+ // add one to a service that has been deployed (4.x crashes otherwise).
626
+ const steps = [
627
+ { label: "Creating the Railway project", done: "Project created", attached: true, run: () => railwayInitOrLink(d) },
628
+ {
629
+ label: "Creating the service", done: `Service ${RAILWAY_SERVICE} created`, retries: 3,
630
+ run: async (set) => {
631
+ const made = await sys.exec("railway", ["add", "--service", RAILWAY_SERVICE], { cwd: d.root, onLine: set });
632
+ // A re-run finds it already there; either way, link it for later commands.
633
+ if (made.code !== 0 && !/already exists/i.test(`${made.stdout}${made.stderr}`))
634
+ return made;
635
+ return sys.exec("railway", ["service", RAILWAY_SERVICE], { cwd: d.root, onLine: set });
1001
636
  },
1002
- { desc: "set environment variables (redeploys with them)", cmd: ["railway", varArgs], retries: 3 },
1003
- ],
1004
- getUrl: async () => {
1005
- // `railway domain` prints "🚀 https://…up.railway.app" — capture + parse it
1006
- // instead of asking the user to paste what we just printed.
1007
- for (let i = 0; i < 4; i++) {
1008
- if (i > 0) {
1009
- console.log(c.yellow(` API hiccup — retry ${i}/3`));
1010
- await pause(2500, "backing off before retry");
1011
- }
1012
- const r = await withSpinner("fetching the public domain (railway domain)", () => captureAsync("railway", ["domain"], { cwd: ctx.root }));
1013
- const m = `${r.stdout}\n${r.stderr}`.match(/https?:\/\/[a-z0-9.-]+\.up\.railway\.app/i);
1014
- if (m)
1015
- return m[0];
1016
- }
637
+ },
638
+ {
639
+ label: "Setting the secrets", done: "Secrets set", retries: 3,
640
+ run: () => setRailwayVariables(d.env, d.root, (cmd, args, opts) => sys.exec(cmd, args, opts), () => {
641
+ ui.warn("This Railway CLI can't read a value from stdin, so the secrets are passed on its command line.");
642
+ ui.hint("Update it to keep them off it: npm i -g @railway/cli");
643
+ }, { service: RAILWAY_SERVICE, deploy: false }),
644
+ },
645
+ ];
646
+ for (const step of steps)
647
+ if ((await runStep(d, step)) === "cancelled")
1017
648
  return null;
649
+ // `railway domain` gives the service a public address and prints it.
650
+ let url = null;
651
+ for (let i = 0; i < 4 && !url; i++) {
652
+ if (i > 0)
653
+ await ui.task(`Railway didn't answer; trying again (${i}/3)`, () => sys.sleep(2500));
654
+ const r = await ui.task("Getting a public address", () => sys.exec("railway", ["domain", ...svc], { cwd: d.root }));
655
+ url = `${r.stdout}\n${r.stderr}`.match(/https?:\/\/[a-z0-9.-]+\.up\.railway\.app/i)?.[0] ?? null;
656
+ }
657
+ if (url)
658
+ ui.ok("Public address", url);
659
+ else
660
+ url = await askUrl(d.io, "Railway didn't report the address. Public URL of the service");
661
+ const build = (label, done) => ({ label, done, slow: true, retries: 2, run: (set) => railwayBuild(d, set) });
662
+ const rest = [
663
+ {
664
+ label: "Telling the server its address", done: "PUBLIC_URL set", retries: 3,
665
+ run: hostCommand(d, "railway", ["variable", "set", `PUBLIC_URL=${url}`, ...svc, "--skip-deploys"]),
666
+ optional: `Sign-in from claude.ai and other clients won't work until PUBLIC_URL=${url} is set on the server.`,
1018
667
  },
1019
- setPublicUrlCmds: (url) => [
1020
- ["railway", ["variables", "--set", `PUBLIC_URL=${url}`]],
1021
- ["railway", ["up", "--detach"]],
1022
- ],
1023
- ctx,
668
+ build("Building and deploying on Railway", "Deployed"),
669
+ ];
670
+ for (const step of rest) {
671
+ const r = await runStep(d, step);
672
+ if (r === "cancelled")
673
+ return null;
674
+ }
675
+ // Railway volumes mount root-owned; the image's entrypoint hands /data to the
676
+ // unprivileged user before starting the server.
677
+ const volume = await runStep(d, {
678
+ label: "Adding the volume for the login", done: "Volume added at /data", retries: 1,
679
+ run: () => addRailwayVolume(d),
680
+ optional: "Without a volume every restart or redeploy needs totem auth again.",
1024
681
  });
682
+ if (volume === "cancelled")
683
+ return null;
684
+ // Adding a volume restarts the service on Railway's own schedule. Deploy
685
+ // once more and wait for it, so the login goes to the server that has it.
686
+ if (volume === "ok" && (await runStep(d, build("Restarting with the volume", "Running with the volume"))) === "cancelled")
687
+ return null;
688
+ return url;
1025
689
  }
1026
- // GOOGLE CLOUD RUN — gcloud, builds from source. Best-effort.
1027
- async function deployCloudRun(ctx) {
1028
- // Env vars go in a temp YAML file (--env-vars-file), NOT --set-env-vars: values
1029
- // include an email (with `@`) and a random password, so any inline delimiter can
1030
- // collide (the `^@^` form broke on the email's `@`). The file lives in the OS
1031
- // temp dir — never the `--source` upload dir — and is deleted after. PUBLIC_URL
1032
- // is set in the 2nd pass once the deployed URL is known.
1033
- const envYaml = Object.entries(ctx.env)
1034
- .filter(([, v]) => v !== "")
1035
- .map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
1036
- .join("\n") + "\n";
1037
- const envFile = resolve(tmpdir(), `totem-env-${randomUUID()}.yaml`);
1038
- writeFileSync(envFile, envYaml, { mode: 0o600 });
690
+ /** The deployment id in the build-logs link \`railway up --detach\` prints. */
691
+ export function railwayDeploymentId(output) {
692
+ return output.match(/[?&]id=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i)?.[1] ?? null;
693
+ }
694
+ const RAILWAY_DONE = new Set(["SUCCESS", "FAILED", "CRASHED", "REMOVED", "SKIPPED"]);
695
+ /**
696
+ * Upload and build, then wait for Railway to report how the deployment ended.
697
+ * \`railway up --ci\` can keep streaming long after Railway calls the
698
+ * deployment a success (seen for 10 minutes on CLI 4.65), so the build starts
699
+ * detached and its status is read from \`railway deployment list\`.
700
+ */
701
+ async function railwayBuild(d, set) {
702
+ const { sys } = d.io;
703
+ const svc = ["--service", RAILWAY_SERVICE];
704
+ const up = await sys.exec("railway", ["up", "--detach", ...svc], { cwd: d.root, onLine: set });
705
+ if (up.code !== 0)
706
+ return up;
707
+ const id = railwayDeploymentId(`${up.stdout}\n${up.stderr}`);
708
+ const started = sys.now();
709
+ let status = "QUEUED";
710
+ while (sys.now() - started < 15 * 60_000) {
711
+ await sys.sleep(5000);
712
+ const list = await sys.exec("railway", ["deployment", "list", ...svc, "--json"], { cwd: d.root });
713
+ try {
714
+ const parsed = JSON.parse(list.stdout);
715
+ const all = (Array.isArray(parsed) ? parsed : parsed.deployments ?? []);
716
+ // This deployment only: until it shows up, the newest one listed may be
717
+ // the previous deploy, already a success.
718
+ const mine = id ? all.find((x) => x.id === id) : all[0];
719
+ if (mine)
720
+ status = mine.status;
721
+ }
722
+ catch {
723
+ continue;
724
+ }
725
+ set(`Railway: ${status.toLowerCase().replace(/_/g, " ")}`);
726
+ if (RAILWAY_DONE.has(status))
727
+ break;
728
+ }
729
+ const ok = status === "SUCCESS";
730
+ return { code: ok ? 0 : 1, stdout: up.stdout, stderr: ok ? up.stderr : `${up.stderr}\nThe deployment ended as ${status}. Its build log: railway logs --build ${id ?? ""}`.trim() };
731
+ }
732
+ /** The project, environment and service ids `railway status --json` reports for the linked project. */
733
+ export function railwayIds(statusJson, service) {
1039
734
  try {
1040
- return await assistedDeploy({
1041
- cliName: "gcloud",
1042
- install: { manualHint: "install the gcloud SDK: https://cloud.google.com/sdk/docs/install" },
1043
- loginCheck: () => capture("gcloud", ["config", "get-value", "project"]).stdout.trim().length > 0,
1044
- loginCmd: async () => {
1045
- const a = await run("gcloud", ["auth", "login"]);
1046
- if (a !== 0)
1047
- return a;
1048
- console.log(c.gray(" Set your project: gcloud config set project <PROJECT_ID>"));
1049
- await promptYesNo("Project set?", true);
1050
- return 0;
1051
- },
1052
- steps: [
1053
- {
1054
- desc: "enable required APIs (run, cloudbuild, artifactregistry)",
1055
- cmd: ["gcloud", ["services", "enable", "run.googleapis.com", "cloudbuild.googleapis.com", "artifactregistry.googleapis.com"]],
1056
- confirm: { summary: "Enable the Cloud Run / Cloud Build / Artifact Registry APIs?", detail: "turns these APIs on for the selected project (one-time, idempotent)", cmd: "gcloud services enable run / cloudbuild / artifactregistry", defaultYes: true, skippable: true },
1057
- },
1058
- {
1059
- // gcloud run deploy --source builds via the project's COMPUTE default
1060
- // service account, which on new projects lacks build permissions
1061
- // (PERMISSION_DENIED resolving the source). Grant the builder role.
1062
- desc: "grant Cloud Build access to the default service account",
1063
- cmd: ["sh", ["-c", 'P="$(gcloud config get-value project 2>/dev/null)"; N="$(gcloud projects describe "$P" --format=\'value(projectNumber)\' 2>/dev/null)"; gcloud projects add-iam-policy-binding "$P" --member="serviceAccount:${N}-compute@developer.gserviceaccount.com" --role=roles/cloudbuild.builds.builder --condition=None']],
1064
- confirm: { summary: "Grant the Cloud Build builder role to the compute service account?", detail: "modifies project IAM — needed for `--source` builds. Skip if you've already granted it.", cmd: "gcloud projects add-iam-policy-binding … --role=roles/cloudbuild.builds.builder", defaultYes: true, skippable: true },
1065
- },
1066
- {
1067
- desc: "deploy from source (Cloud Build builds the Dockerfile)",
1068
- cmd: ["gcloud", [
1069
- "run", "deploy", ctx.appName,
1070
- "--source", ".",
1071
- "--region", "us-west1",
1072
- "--allow-unauthenticated",
1073
- "--port", "3000",
1074
- "--min-instances", "1",
1075
- "--env-vars-file", envFile,
1076
- "--quiet",
1077
- ]],
1078
- confirm: { summary: `Build + deploy '${ctx.appName}' to Cloud Run (us-west1)?`, detail: "uploads source, runs Cloud Build, and creates a public service (may incur charges)", cmd: `gcloud run deploy ${ctx.appName} --source . --region us-west1`, defaultYes: true },
1079
- },
1080
- ],
1081
- getUrl: async () => {
1082
- // gcloud knows the service URL — fetch it instead of asking the user.
1083
- const r = await withSpinner("fetching the Cloud Run service URL", () => captureAsync("gcloud", ["run", "services", "describe", ctx.appName, "--region", "us-west1", "--format=value(status.url)"]));
1084
- const url = r.stdout.trim();
1085
- return /^https?:\/\//.test(url) ? url : null;
735
+ const d = JSON.parse(statusJson);
736
+ for (const { node: env } of d.environments?.edges ?? []) {
737
+ const inst = (env.serviceInstances?.edges ?? []).find((e) => e.node.serviceName === service);
738
+ if (d.id && inst)
739
+ return { projectId: d.id, environmentId: env.id, serviceId: inst.node.serviceId };
740
+ }
741
+ }
742
+ catch { /* not JSON */ }
743
+ return null;
744
+ }
745
+ /**
746
+ * A volume at /data on the totem service. \`railway volume add\` crashes on a
747
+ * fresh service in Railway CLI 4.x and 5.x alike (it reads the service's region,
748
+ * which Railway doesn't report yet), so on failure the same thing goes through
749
+ * Railway's API: \`railway api\` from CLI 5, through npx when the installed one
750
+ * is older.
751
+ */
752
+ async function addRailwayVolume(d) {
753
+ const { sys } = d.io;
754
+ const direct = await sys.exec("railway", ["volume", "--service", RAILWAY_SERVICE, "add", "--mount-path", "/data"], { cwd: d.root });
755
+ if (direct.code === 0 && !/panicked/.test(`${direct.stdout}${direct.stderr}`))
756
+ return direct;
757
+ const status = await sys.exec("railway", ["status", "--json"], { cwd: d.root });
758
+ const ids = railwayIds(status.stdout, RAILWAY_SERVICE);
759
+ if (!ids)
760
+ return direct;
761
+ const mutation = "mutation($input: VolumeCreateInput!) { volumeCreate(input: $input) { id } }";
762
+ const variables = JSON.stringify({ input: { ...ids, mountPath: "/data" } });
763
+ const viaApi = await sys.exec("npx", ["--yes", "@railway/cli@5", "api", mutation, "--variables", variables], { cwd: d.root });
764
+ return { ...viaApi, code: viaApi.code === 0 && /"volumeCreate"\s*:\s*\{\s*"id"/.test(viaApi.stdout) ? 0 : viaApi.code || 1 };
765
+ }
766
+ /**
767
+ * Sign-in (OAuth) only works when the server knows its own public address,
768
+ * which exists only after the first deploy: set PUBLIC_URL and redeploy.
769
+ */
770
+ async function setPublicUrl(d, url, steps) {
771
+ for (const step of steps) {
772
+ const r = await runStep(d, { ...step, optional: `Sign-in from claude.ai and other clients won't work until PUBLIC_URL=${url} is set on the server.` });
773
+ if (r === "cancelled")
774
+ return null;
775
+ if (r === "skipped")
776
+ break;
777
+ }
778
+ return url;
779
+ }
780
+ // CLOUDFLARE ──────────────────────────────────────────────────────────────────
781
+ /** The address Wrangler prints after a deploy: https://<name>.<account subdomain>.workers.dev */
782
+ export function workersDevUrl(output, name) {
783
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
784
+ return output.match(new RegExp(`https://${escaped}\\.[a-z0-9-]+\\.workers\\.dev`, "i"))?.[0] ?? null;
785
+ }
786
+ // One Wrangler deploy: it bundles src/cloudflare/worker.ts with wrangler.jsonc,
787
+ // creates the Durable Object that keeps the login, and uploads the two secrets
788
+ // from a temporary file (never a command line). The server works out its own
789
+ // address from the requests it gets, so there is no second pass for PUBLIC_URL.
790
+ async function deployCloudflare(d) {
791
+ const { ui, sys } = d.io;
792
+ d.cleanup = ["Remove the unfinished Worker", `npx wrangler delete --name ${d.appName}`];
793
+ const secretsFile = resolve(tmpdir(), `totem-secrets-${randomUUID()}.json`);
794
+ writeFileSync(secretsFile, JSON.stringify({ MCP_AUTH_TOKEN: d.env.MCP_AUTH_TOKEN, AUTH_PASSWORD: d.env.AUTH_PASSWORD }), { mode: 0o600 });
795
+ let url = null;
796
+ try {
797
+ const deployed = await runStep(d, {
798
+ label: "Building and deploying on Cloudflare", done: "Deployed", slow: true,
799
+ run: async (set) => {
800
+ const r = await sys.exec("npx", wrangler(["deploy", "--name", d.appName, "--secrets-file", secretsFile]), {
801
+ cwd: d.root,
802
+ onLine: (line) => (d.verbose ? ui.hint(redact(d, line), 2) : set(line)),
803
+ });
804
+ url = workersDevUrl(`${r.stdout}\n${r.stderr}`, d.appName) ?? url;
805
+ return r;
1086
806
  },
1087
- setPublicUrlCmds: (url) => [
1088
- ["gcloud", ["run", "services", "update", ctx.appName, "--region", "us-west1", "--update-env-vars", `PUBLIC_URL=${url}`, "--quiet"]],
1089
- ],
1090
- ctx,
1091
807
  });
808
+ if (deployed !== "ok")
809
+ return null;
1092
810
  }
1093
811
  finally {
1094
812
  try {
1095
- rmSync(envFile);
813
+ rmSync(secretsFile);
1096
814
  }
1097
815
  catch { /* best-effort */ }
1098
816
  }
817
+ if (url)
818
+ ui.ok("Public address", url);
819
+ else
820
+ url = await askUrl(d.io, "Wrangler didn't print the address. The Worker's https address (in the Cloudflare dashboard)");
821
+ return url;
1099
822
  }
1100
- // CUSTOM — run the container yourself on any Docker host. Writes a complete,
1101
- // ready-to-run env file (so the real secret values are usable, not truncated on
1102
- // screen) + prints the exact docker commands.
1103
- async function deployCustom(ctx) {
1104
- // All settings — including the full tokens + generated password — go into an
1105
- // env file (chmod 600) instead of being printed (truncated + leaked) on screen.
1106
- const envFile = resolve(ctx.root, ".env.deploy");
1107
- const body = Object.entries(ctx.env).map(([k, v]) => `${k}=${v}`).join("\n") +
1108
- "\nPUBLIC_URL=https://CHANGE-ME-to-your-public-https-address\n";
1109
- writeFileSync(envFile, body, { mode: 0o600 });
1110
- console.log("");
1111
- console.log(` ${c.bold(c.white("Self-host it on any Docker host"))} ${c.gray("— a VPS, Render, your own box, whatever.")}`);
1112
- console.log("");
1113
- console.log(` ${c.violet("1")} ${c.white("Build the image")} ${c.gray("— the repo already has a Dockerfile:")}`);
1114
- console.log(` ${c.cyan("docker build -t totem .")}`);
1115
- console.log("");
1116
- console.log(` ${c.violet("2")} ${c.white("Your full config")} ${c.gray("(tokens + the generated password) was written to:")}`);
1117
- console.log(` ${c.brand(envFile)} ${c.gray("(chmod 600 — keep it private)")}`);
1118
- console.log(` ${c.gray("Open it and set")} ${c.bold(c.white("PUBLIC_URL"))} ${c.gray("to the")} ${c.white("https:// address your server will live at")}`);
1119
- console.log(` ${c.gray("— you need a public domain/hostname with HTTPS. That same URL is what you paste below.")}`);
1120
- console.log("");
1121
- console.log(` ${c.violet("3")} ${c.white("Run it")} ${c.gray("(serves on port 3000):")}`);
1122
- console.log(` ${c.cyan(`docker run -d --restart unless-stopped -p 3000:3000 --env-file ${envFile} totem`)}`);
1123
- console.log(` ${c.gray("then put it behind HTTPS at that domain (a reverse proxy, Cloudflare Tunnel, your host's TLS, …).")}`);
1124
- console.log("");
1125
- return promptUrl("Once it's reachable, paste that public URL (the PUBLIC_URL you set)");
823
+ // CUSTOM ──────────────────────────────────────────────────────────────────────
824
+ /**
825
+ * A server address as typed, made into one: a bare host gets https://, and a
826
+ * trailing /mcp or / is dropped (the server adds /mcp itself). Any http(s)
827
+ * address with a host counts, including localhost and a name on your own
828
+ * network; null when it isn't one.
829
+ */
830
+ export function serverAddress(input) {
831
+ let url = input.trim();
832
+ if (!url || /\s/.test(url))
833
+ return null;
834
+ // No scheme: https, except this computer itself, where a container answers
835
+ // plain http (localhost:3000 would otherwise never pass the running check).
836
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(url))
837
+ url = (/^(localhost|127(\.\d{1,3}){3}|\[::1\])(:\d+)?(\/|$)/i.test(url) ? "http://" : "https://") + url;
838
+ url = url.replace(/\/+$/, "").replace(/\/mcp$/i, "").replace(/\/+$/, "");
839
+ if (!URL.canParse(url))
840
+ return null;
841
+ const u = new URL(url);
842
+ if ((u.protocol !== "https:" && u.protocol !== "http:") || !u.hostname || u.username || u.password || u.search || u.hash)
843
+ return null;
844
+ return url;
845
+ }
846
+ /** Ask for a server address until it is one. */
847
+ async function askUrl(io, question) {
848
+ const { ui } = io;
849
+ for (;;) {
850
+ const typed = await ui.text(question);
851
+ if (!typed.trim()) {
852
+ ui.hint("An address is needed to go on. Ctrl-C stops.", 2);
853
+ continue;
854
+ }
855
+ const url = serverAddress(typed);
856
+ if (url)
857
+ return url;
858
+ ui.hint(`"${typed.trim()}" isn't a web address like https://totem.example.com.`, 2);
859
+ }
860
+ }
861
+ // Run the container yourself on any Docker host. The settings (with the real
862
+ // secrets) go into an env file rather than onto the screen.
863
+ async function deployCustom(d) {
864
+ const { ui, sys } = d.io;
865
+ // In totem's config folder, beside the deploy record: the install may be an
866
+ // npm folder that the next update replaces.
867
+ const envFile = configFile(sys, "deploy.env");
868
+ // Replaced, not written in place: a mode given to writeFileSync only applies
869
+ // to a file it creates, so a file that was already there (from an earlier
870
+ // run, or copied in) kept whatever permissions it had while the next line
871
+ // called it "readable only by you".
872
+ // The address first: it goes into the file with the secrets, so there is
873
+ // nothing to edit by hand.
874
+ const url = await askUrl(d.io, "The server's address (its public https URL)");
875
+ if (!checkPushUrl(url).ok) {
876
+ ui.warn("That's plain http. Apps on the web (claude.ai, chatgpt.com, the phone apps) need an https address, and totem sends " +
877
+ `the WHOOP login over http only to this computer. On a private network you trust: totem auth --url ${url} --allow-http`);
878
+ }
879
+ writeFileAtomic(envFile, Object.entries({ ...d.env, PUBLIC_URL: url }).map(([k, v]) => `${k}=${v}`).join("\n") + "\n");
880
+ const width = ui.style.width - 7;
881
+ const shown = tildify(envFile, sys.home);
882
+ ui.ok("Settings written", `${shown}, readable only by you`);
883
+ ui.para("That file holds the server's settings and secrets. totem doesn't run Docker for you; these are the steps:");
884
+ ui.line();
885
+ ui.para("1. Build the image from totem's folder (for another machine, copy the folder and that file there first):");
886
+ ui.code(shellLines([...dockerBuildArgs(d.root), shellPath(d.root)], width, sys.platform), 5);
887
+ ui.para("2. Start it. The totem-data volume keeps the WHOOP login across restarts:");
888
+ ui.code(shellLines(["docker", "run", "-d", "--restart", "unless-stopped", "-p", "3000:3000", "-v", "totem-data:/data", "--env-file", shellPath(envFile), "totem"], width, sys.platform), 5);
889
+ ui.para(url.startsWith("https:")
890
+ ? `3. Put it behind HTTPS at ${url} (a reverse proxy, a tunnel, or your host's TLS).`
891
+ : `3. Make it answer at ${url}.`);
892
+ ui.line();
893
+ while (!(await ui.confirm(`Is it running at ${url}?`, true))) {
894
+ ui.hint("Start it with the steps above, then answer yes. Ctrl-C stops; the settings file stays.", 2);
895
+ }
896
+ return url;
897
+ }
898
+ // ── verification ─────────────────────────────────────────────────────────────
899
+ /** Is the server up, does it advertise sign-in, and does /mcp refuse strangers? */
900
+ async function verifyDeployment(io, baseUrl) {
901
+ const { ui, sys } = io;
902
+ const root = baseUrl.replace(/\/(mcp)?$/, "");
903
+ // Poll with a short per-request timeout: an address that hasn't propagated
904
+ // yet fails fast and is asked again, instead of hanging on one request.
905
+ const started = sys.now();
906
+ let healthy = false;
907
+ let lastError = "";
908
+ await ui.task(`Waiting for ${root} to answer`, async (set) => {
909
+ while (sys.now() - started < 90_000) {
910
+ const health = await sys.httpGet(`${root}/health`, 3000);
911
+ if (health.status === 200) {
912
+ healthy = true;
913
+ return;
914
+ }
915
+ lastError = health.status ? `HTTP ${health.status}` : health.error ?? "no answer";
916
+ set(lastError);
917
+ await sys.sleep(1500);
918
+ }
919
+ }, { slow: true });
920
+ if (!healthy) {
921
+ ui.fail("The server didn't answer", `${lastError || "no answer"} after ${duration(sys.now() - started)}`);
922
+ return { healthy, locked: false };
923
+ }
924
+ ui.ok("The server is up", `/health answered in ${duration(sys.now() - started) || "under a second"}`);
925
+ const prm = await ui.task("Checking sign-in", () => sys.httpGet(`${root}/.well-known/oauth-protected-resource/mcp`, 5000));
926
+ const prmOk = prm.status === 200 && prm.body.includes("/mcp");
927
+ if (prmOk)
928
+ ui.ok("Sign-in is advertised", "clients can find where to log in");
929
+ else
930
+ ui.warn("The server doesn't advertise sign-in yet", prm.status ? `HTTP ${prm.status}` : prm.error ?? "no answer");
931
+ // An unauthenticated /mcp must be refused, not served.
932
+ const gate = await ui.task("Checking the lock on /mcp", () => sys.httpGet(`${root}/mcp`, 5000));
933
+ const gated = gate.status === 401;
934
+ if (gated)
935
+ ui.ok("/mcp is locked", "401 without a token");
936
+ else
937
+ ui.fail(gate.status ? "/mcp answered without a token" : "/mcp didn't answer", gate.status ? `HTTP ${gate.status}, expected 401` : gate.error ?? "no answer");
938
+ return { healthy, locked: gated };
939
+ }
940
+ // ── the flow ─────────────────────────────────────────────────────────────────
941
+ /** Where each host's sign-in link points, as its CLI prints it. */
942
+ const CLOUDFLARE_SIGN_IN = /https:\/\/dash\.cloudflare\.com\/oauth2\/auth\?\S+/;
943
+ const FLY_SIGN_IN = /https:\/\/fly\.io\/app\/auth\/cli\/[\w-]+/;
944
+ /**
945
+ * A host's browser sign-in, without its CLI opening the browser by itself (it
946
+ * would land in whichever browser profile was used last, maybe one without the
947
+ * account). Run away from the terminal, Wrangler (with --browser=false) and
948
+ * flyctl print their link and wait for the approval instead: totem offers the
949
+ * link (offerLink), then waits too. If the sign-in finishes from a link pasted
950
+ * elsewhere before an answer, the question is taken back. Railway asks before
951
+ * opening anything, so it runs in the terminal as itself.
952
+ */
953
+ async function browserSignIn(io, host, cmd, args, link) {
954
+ const { ui, sys } = io;
955
+ let seen = () => { };
956
+ const shown = new Promise((resolve) => { seen = resolve; });
957
+ const finished = new AbortController();
958
+ const result = sys.exec(cmd, args, { onLine: (line) => { const m = line.match(link); if (m)
959
+ seen(m[0]); } })
960
+ .finally(() => finished.abort());
961
+ const url = await ui.task(`Starting the ${host} sign-in`, () => Promise.race([shown, result.then(() => null)]), { slow: true });
962
+ if (url !== null) {
963
+ const offered = await offerLink(io, `${host} sign-in`, url, finished.signal);
964
+ if (offered !== "withdrawn" && !finished.signal.aborted)
965
+ await ui.task("Waiting for you to finish signing in", () => result);
966
+ }
967
+ return result;
968
+ }
969
+ /** The last thing a CLI said, for a problem's detail: its last error line, else its last line. */
970
+ const lastWords = (r) => {
971
+ const last = (text) => text.split("\n").map((l) => l.trim()).filter(Boolean).pop();
972
+ return last(r.stderr) ?? last(r.stdout);
973
+ };
974
+ /** The host's CLI and a signed-in account. Returns the binary and who is signed in. */
975
+ async function hostAccount(io, platform, already) {
976
+ const { ui, sys } = io;
977
+ const who = async (cli, args) => {
978
+ const r = await ui.task("Checking who is signed in", () => sys.exec(cli, args));
979
+ return r.code === 0 ? r.stdout.trim().replace(/\s+/g, " ").replace(/^Logged in as\s+/i, "").replace(/\s*👋$/u, "") || "your account" : null;
980
+ };
981
+ if (platform === "fly") {
982
+ const cli = await ensureCli(io, ["fly", "flyctl"], "Fly CLI", { brew: "flyctl", script: "curl -fsSL https://fly.io/install.sh | sh", manual: "brew install flyctl", windows: 'pwsh -Command "iwr https://fly.io/install.ps1 -useb | iex"' });
983
+ if (!cli)
984
+ return null;
985
+ let account = await who(cli, ["auth", "whoami"]);
986
+ if (!account) {
987
+ const r = await browserSignIn(io, "Fly", cli, ["auth", "login"], FLY_SIGN_IN);
988
+ if (r.code !== 0) {
989
+ ui.problem("The Fly sign-in didn't finish.", { detail: lastWords(r), fix: [["Sign in", `${cli} auth login`], ["Then", "totem cloud"]] });
990
+ return null;
991
+ }
992
+ account = (await who(cli, ["auth", "whoami"])) ?? "your account";
993
+ }
994
+ ui.ok("Signed in to Fly", account);
995
+ return { cli, account };
996
+ }
997
+ if (platform === "railway") {
998
+ const cli = await ensureCli(io, ["railway"], "Railway CLI", { npm: "@railway/cli", brew: "railway", manual: "npm i -g @railway/cli" });
999
+ if (!cli)
1000
+ return null;
1001
+ let account = await who(cli, ["whoami"]);
1002
+ if (!account) {
1003
+ ui.info("Signing in to Railway. It asks before opening your browser.");
1004
+ if ((await sys.run(cli, ["login"])) !== 0) {
1005
+ ui.problem("The Railway sign-in didn't finish.", { fix: [["Sign in", "railway login"], ["Then", "totem cloud"]] });
1006
+ return null;
1007
+ }
1008
+ account = (await who(cli, ["whoami"])) ?? "your account";
1009
+ }
1010
+ ui.ok("Signed in to Railway", account);
1011
+ return { cli, account };
1012
+ }
1013
+ if (platform === "cloudflare") {
1014
+ // npx comes with Node, which totem needs anyway; Wrangler downloads on first use.
1015
+ const whoami = async () => {
1016
+ const r = await ui.task("Checking who is signed in to Cloudflare", () => sys.exec("npx", wrangler(["whoami"])), { slow: true });
1017
+ return cloudflareAccount(`${r.stdout}\n${r.stderr}`, r.code);
1018
+ };
1019
+ let account = await whoami();
1020
+ if (!account) {
1021
+ const r = await browserSignIn(io, "Cloudflare", "npx", wrangler(["login", "--browser=false"]), CLOUDFLARE_SIGN_IN);
1022
+ if (r.code !== 0) {
1023
+ ui.problem("The Cloudflare sign-in didn't finish.", { detail: lastWords(r), fix: [["Sign in", "npx wrangler login"], ["Then", "totem cloud"]] });
1024
+ return null;
1025
+ }
1026
+ account = (await whoami()) ?? "your account";
1027
+ }
1028
+ ui.ok("Signed in to Cloudflare", account);
1029
+ return { cli: "npx", account };
1030
+ }
1031
+ return { cli: "docker", account: "" };
1032
+ }
1033
+ /**
1034
+ * Who `wrangler whoami` says is signed in: the email for a browser sign-in, the
1035
+ * account name for an API token, or null when nobody is.
1036
+ */
1037
+ export function cloudflareAccount(output, code) {
1038
+ if (code !== 0 || /not authenticated|not logged in|wrangler login/i.test(output))
1039
+ return null;
1040
+ const email = output.match(/associated with the email\s+(\S+?@\S+?)\.?\s*$/im)?.[1];
1041
+ if (email)
1042
+ return email;
1043
+ const row = output.match(/│\s*([^│\n]+?)\s*│\s*[0-9a-f]{32}\s*│/);
1044
+ return row?.[1]?.trim() || "your account";
1045
+ }
1046
+ /** Sign in to the host as someone else. Returns the new account, or null if it didn't finish. */
1047
+ async function switchAccount(io, platform, cli, _already) {
1048
+ const { ui, sys } = io;
1049
+ if (platform === "cloudflare") {
1050
+ await sys.run("npx", wrangler(["logout"]));
1051
+ const login = await browserSignIn(io, "Cloudflare", "npx", wrangler(["login", "--browser=false"]), CLOUDFLARE_SIGN_IN);
1052
+ if (login.code !== 0) {
1053
+ ui.fail("The sign-in didn't finish.", lastWords(login));
1054
+ return null;
1055
+ }
1056
+ const r = await sys.exec("npx", wrangler(["whoami"]));
1057
+ return cloudflareAccount(`${r.stdout}\n${r.stderr}`, r.code) ?? "your account";
1058
+ }
1059
+ const [out, login, whoami] = platform === "fly" ? [["auth", "logout"], ["auth", "login"], ["auth", "whoami"]] : [["logout"], ["login"], ["whoami"]];
1060
+ await sys.run(cli, out);
1061
+ const signedIn = platform === "fly"
1062
+ ? (await browserSignIn(io, "Fly", cli, login, FLY_SIGN_IN)).code === 0
1063
+ : (await sys.run(cli, login)) === 0;
1064
+ if (!signedIn) {
1065
+ ui.fail("The sign-in didn't finish.");
1066
+ return null;
1067
+ }
1068
+ const r = await sys.exec(cli, whoami);
1069
+ return r.stdout.trim().replace(/\s+/g, " ").replace(/^Logged in as\s+/i, "") || "your account";
1070
+ }
1071
+ /** What will be created and who pays, shown once before anything happens. */
1072
+ function planRows(d) {
1073
+ const host = HOSTS.find((h) => h.id === d.platform).name;
1074
+ if (d.platform === "fly") {
1075
+ return [
1076
+ ["Host", `${host}, as ${d.account}`],
1077
+ ["App", d.appName],
1078
+ ["Address", `https://${d.appName}.fly.dev`],
1079
+ ["Machine", `${FLY_VM.size}, 512 MB, in ${FLY_REGION} (Virginia), always on`],
1080
+ ["Volume", `${FLY_VOLUME}, 1 GB: keeps the WHOOP login across restarts`],
1081
+ ["Cost", "about $4 a month at Fly's prices, billed to your Fly account"],
1082
+ ];
1083
+ }
1084
+ if (d.platform === "cloudflare") {
1085
+ return [
1086
+ ["Host", `${host}, as ${d.account}`],
1087
+ ["Worker", d.appName],
1088
+ ["Address", `https://${d.appName}.<your subdomain>.workers.dev`],
1089
+ ["Storage", "a Durable Object keeps the WHOOP login across restarts"],
1090
+ ["Cost", "free plan: up to 100,000 requests a day"],
1091
+ ];
1092
+ }
1093
+ if (d.platform === "railway") {
1094
+ return [
1095
+ ["Host", `${host}, as ${d.account}`],
1096
+ ["Project", d.appName],
1097
+ ["Address", "assigned by Railway, under up.railway.app"],
1098
+ ["Volume", "mounted at /data: keeps the WHOOP login across restarts"],
1099
+ ["Cost", "Railway bills your account for the service and the volume"],
1100
+ ];
1101
+ }
1102
+ return [["Host", host]];
1103
+ }
1104
+ export async function runCloudSetup(root, io = realIo(), opts = {}) {
1105
+ const { ui, sys } = io;
1106
+ const TOTAL = 6;
1107
+ ui.banner("totem cloud", "Deploy your own totem server and connect your AI apps to it.");
1108
+ // This flow ends by writing the new server into the deploy record, over what
1109
+ // is there. For a server that is already deployed, that record is the only
1110
+ // copy of its MCP_AUTH_TOKEN on this computer (what `totem auth`, `status`
1111
+ // and `token` reach it with), and the server itself keeps running and
1112
+ // billing: don't replace it without asking.
1113
+ const existing = readDeployRecord(root, io.sys);
1114
+ if (existing && existing.platform !== "local" && existing.url) {
1115
+ ui.warn(`This install already has a server at ${existing.url}.`);
1116
+ ui.hint(`Deploying another makes this computer forget that one: its token leaves ${tildify(deployRecordPath(io.sys), io.sys.home)}, and the server keeps running until you remove it on its host. To deploy this install's code to it again: totem deploy`);
1117
+ if (!(await ui.confirm("Deploy a new server anyway?", false))) {
1118
+ ui.hint("Nothing changed. To connect a client to the server: totem connect");
1119
+ return 1;
1120
+ }
1121
+ }
1122
+ ui.step(1, TOTAL, "Host");
1123
+ const platform = HOSTS[await ui.select("Where should the server run?", HOSTS.map((h) => ({ label: h.name, hint: h.hint })))].id;
1124
+ if (!(await prerequisites(root, io, false)))
1125
+ return 1;
1126
+ // What choosing the host's account has created before the plan is confirmed,
1127
+ // in words for the person. No host creates anything at that point today.
1128
+ const already = [];
1129
+ const host = await hostAccount(io, platform, already);
1130
+ if (!host)
1131
+ return 1;
1132
+ ui.step(2, TOTAL, "Secrets");
1133
+ const mcpToken = sys.token();
1134
+ let password = sys.password();
1135
+ let ownPassword = false;
1136
+ ui.ok("MCP_AUTH_TOKEN generated", "64 random characters; the server's own key");
1137
+ ui.ok("Connector password generated", "you get it at the end, once");
1138
+ ui.hint(`Both are set on the server. The token is also kept in ${tildify(deployRecordPath(io.sys), io.sys.home)} (readable only by you), so totem auth can reach the server.`);
1139
+ // No WHOOP tokens in the host's environment: the server starts without a
1140
+ // login, and step 5 sends one to its token file over POST /admin/tokens.
1141
+ const d = {
1142
+ root, io, platform, verbose: Boolean(opts.verbose), cli: host.cli, account: host.account,
1143
+ env: { MCP_TRANSPORT: "http", MCP_AUTH_TOKEN: mcpToken, AUTH_PASSWORD: password },
1144
+ appName: platform === "custom" ? "totem" : `totem-${sys.token().slice(0, 6)}`,
1145
+ };
1146
+ ui.step(3, TOTAL, "Deploy");
1147
+ if (platform !== "custom") {
1148
+ for (;;) {
1149
+ ui.rows(planRows(d));
1150
+ const pick = await ui.select("Deploy this?", [
1151
+ { label: "Deploy" },
1152
+ { label: "Change something", hint: "the name, the password, or the account" },
1153
+ { label: "Cancel", hint: already.length ? "no server is created" : "nothing has been created" },
1154
+ ]);
1155
+ if (pick === 0)
1156
+ break;
1157
+ if (pick === 2) {
1158
+ ui.hint(already.length ? `Cancelled. No server was created. Already done above, and left as it is: ${listOf(already)}.` : "Cancelled. Nothing was created.", 2);
1159
+ return 1;
1160
+ }
1161
+ d.appName = (await ui.text("Name", d.appName)).trim() || d.appName;
1162
+ for (;;) {
1163
+ const typed = await ui.hidden(`Connector password (Enter keeps ${ownPassword ? "yours" : "the generated one"})`);
1164
+ if (typed === "")
1165
+ break;
1166
+ const why = weakPassword(typed);
1167
+ if (why) {
1168
+ ui.hint(why, 2);
1169
+ continue;
1170
+ }
1171
+ // It is typed blind and totem never shows it afterwards: a slip of the
1172
+ // finger would set a password on the server that nobody knows.
1173
+ if ((await ui.hidden("The same password again")) !== typed) {
1174
+ ui.hint("Those two are not the same. Nothing changed.", 2);
1175
+ continue;
1176
+ }
1177
+ password = typed;
1178
+ ownPassword = true;
1179
+ d.env.AUTH_PASSWORD = typed;
1180
+ break;
1181
+ }
1182
+ if (await ui.confirm(`Sign in to ${HOSTS.find((h) => h.id === platform).name} as someone else?`, false)) {
1183
+ const account = await switchAccount(io, platform, d.cli, already);
1184
+ if (account)
1185
+ d.account = account;
1186
+ }
1187
+ }
1188
+ }
1189
+ const url = platform === "fly" ? await deployFly(d)
1190
+ : platform === "railway" ? await deployRailway(d)
1191
+ : platform === "cloudflare" ? await deployCloudflare(d)
1192
+ : await deployCustom(d);
1193
+ if (!url) {
1194
+ ui.problem("The server was not deployed.", { fix: [["Start over", "totem cloud"], ...(d.cleanup ? [d.cleanup] : [])] });
1195
+ return 1;
1196
+ }
1197
+ ui.step(4, TOTAL, "Check");
1198
+ const check = await verifyDeployment(io, url);
1199
+ // Record the deployment before anything else can stop the flow, so auth,
1200
+ // status and logs know where it is. d.appName, not the first suggestion: a
1201
+ // name conflict may have changed it.
1202
+ writeDeployRecord(root, {
1203
+ platform, app: d.appName, url,
1204
+ ...(platform === "fly" ? { region: FLY_REGION } : platform === "railway" ? { service: RAILWAY_SERVICE } : {}),
1205
+ mcp_auth_token: mcpToken,
1206
+ }, io.sys);
1207
+ const mcpUrl = `${url.replace(/\/+$/, "")}/mcp`;
1208
+ // The server has had the connector password since the deploy finished, and
1209
+ // this run is the only time totem can show it. A flow that stops before the
1210
+ // connect card must still hand it over: otherwise the person owns a server
1211
+ // that no client can sign in to.
1212
+ const handOverPassword = () => {
1213
+ if (ownPassword)
1214
+ return;
1215
+ const handedOver = sys.copy(password);
1216
+ ui.line();
1217
+ ui.rows([
1218
+ ["URL", ui.kit.c.link(mcpUrl)],
1219
+ ["Password", `${ui.kit.c.secret(password)}${handedOver ? ui.kit.c.dim(" (copied to the clipboard)") : ""}`],
1220
+ ]);
1221
+ ui.hint("The connector password is already set on the server, and totem shows it this once. Save it in your password manager.", 2);
1222
+ };
1223
+ if (!check.healthy) {
1224
+ ui.problem("The deploy finished, but the server isn't answering.", {
1225
+ detail: "It may still be starting. Its logs say what it is doing.",
1226
+ fix: [["Read its logs", "totem logs"], ["Check it again", "totem ping"], ["Then log in", "totem auth"]],
1227
+ });
1228
+ handOverPassword();
1229
+ return 1;
1230
+ }
1231
+ // A totem server refuses /mcp without its token. Whatever answered some other
1232
+ // way is not one with its lock on (a mistyped address, a proxy's or a host's
1233
+ // own page that says 200 to everything): the WHOOP login, and the server's
1234
+ // token that goes with it, are not sent there.
1235
+ if (!check.locked) {
1236
+ ui.problem("totem didn't send a WHOOP login: this address isn't refusing /mcp without a token.", {
1237
+ detail: `A totem server answers 401 there. Check that ${url} is this server and nothing else, then log in.`,
1238
+ fix: [["Check the server", "totem status"], ["Then log in", "totem auth"]],
1239
+ });
1240
+ handOverPassword();
1241
+ return 1;
1242
+ }
1243
+ ui.step(5, TOTAL, "WHOOP login");
1244
+ const loggedIn = (await runAuth(root, [], { target: { kind: "remote", url, adminToken: mcpToken, platform }, embedded: true }, io)) === 0;
1245
+ if (!loggedIn)
1246
+ ui.warn("The server is up but has no WHOOP login yet.");
1247
+ ui.step(6, TOTAL, "Connect your apps");
1248
+ const copied = !ownPassword && sys.copy(password);
1249
+ ui.rows([
1250
+ ["URL", ui.kit.c.link(mcpUrl)],
1251
+ ["Password", ownPassword ? "the one you chose" : `${ui.kit.c.secret(password)}${copied ? ui.kit.c.dim(" (copied to the clipboard)") : ""}`],
1252
+ ]);
1253
+ if (!ownPassword)
1254
+ ui.hint("totem shows the password this once. Save it in your password manager.", 2);
1255
+ ui.line();
1256
+ const page = await showConnectPage(io, mcpUrl);
1257
+ const { steps } = await connectInstalled(io, { kind: "remote", mcpUrl });
1258
+ ui.next([
1259
+ ...(loggedIn ? [] : ["First, finish the WHOOP login: totem auth", ""]),
1260
+ ...[...steps, `Ask it: ${FIRST_QUESTION}`].map((s, i) => `${i + 1}. ${s}`),
1261
+ "",
1262
+ `Every app: ${page}`,
1263
+ "Check the server: totem status",
1264
+ ]);
1265
+ return loggedIn ? 0 : 1;
1126
1266
  }
1127
1267
  //# sourceMappingURL=setup.js.map