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