@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
@@ -0,0 +1,16 @@
1
+ /** Normalize common human/Whoop clock forms to the wire format HH:MM:SS. */
2
+ export function normalizeClockTime(value: string): string | null {
3
+ const match = value.trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(AM|PM)?$/i);
4
+ if (!match) return null;
5
+ let hour = Number(match[1]);
6
+ const minute = Number(match[2]);
7
+ const second = Number(match[3] ?? "0");
8
+ const meridiem = match[4]?.toUpperCase();
9
+ if (minute > 59 || second > 59) return null;
10
+ if (meridiem) {
11
+ if (hour < 1 || hour > 12) return null;
12
+ if (hour === 12) hour = 0;
13
+ if (meridiem === "PM") hour += 12;
14
+ } else if (hour > 23) return null;
15
+ return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}:${String(second).padStart(2, "0")}`;
16
+ }
@@ -0,0 +1,434 @@
1
+ // I/O for the AI coach: open/reopen a conversation by fingerprint, post a turn,
2
+ // poll it to COMPLETE, look fingerprints up in the history list, resolve the
3
+ // cycle for Daily Outlook / Day in Review, and attach an image. specs/ai.md.
4
+ //
5
+ // Rules (SPEC.md §7 S23): address turns by fingerprint only; never send /seen,
6
+ // /end-seen or /last-viewed-turn; reopen only listed fingerprints (reopening an
7
+ // unlisted one creates it, and for outlooks generates the report); never cache
8
+ // or accept a cycle id.
9
+ import { randomInt, randomUUID } from "node:crypto";
10
+ import type { WhoopClient } from "../whoop/client.js";
11
+ import { WhoopApiError, WhoopServerError } from "../whoop/errors.js";
12
+ import { get, str } from "../whoop/bff.js";
13
+ import {
14
+ AGENT_SOURCES,
15
+ REPORT_PREFIX,
16
+ assistantText,
17
+ homeCycleId,
18
+ projectConversationList,
19
+ projectRecommendations,
20
+ recommendationPath,
21
+ turnActions,
22
+ turnCards,
23
+ turnStatus,
24
+ } from "../projections/coach.js";
25
+ import type { CoachAgent, CoachAskReceiptT, CoachConversationT, CoachRecommendationT } from "../schemas/coach.js";
26
+
27
+ export const AI = "/ai-conversation-bff/v1";
28
+
29
+ const conversationPath = (fp: string) => `${AI}/conversation/${encodeURIComponent(fp)}`;
30
+
31
+ export interface CoachTiming {
32
+ now: () => number;
33
+ sleep: (ms: number) => Promise<void>;
34
+ /** Delay before each poll. The spec's cadence is every 3–4 s. */
35
+ pollDelayMs: () => number;
36
+ /** How long to wait for the reply to reach COMPLETE (spec: ≥45 s; replies take 3–20 s). */
37
+ replyTimeoutMs: number;
38
+ /** How long to wait for an agent's turn-0 greeting or a previous turn to finish before posting. */
39
+ settleTimeoutMs: number;
40
+ /**
41
+ * Ceiling on all the waiting in one ask (settle + reply together). MCP clients
42
+ * built on the SDK give a tool call 60 s by default; past that the client
43
+ * reports a timeout while the coach carries on, and the reply is lost to the
44
+ * caller. Default 50 s: the ask returns in time with the thread to read later.
45
+ */
46
+ totalBudgetMs?: number;
47
+ }
48
+
49
+ const DEFAULT_TOTAL_BUDGET_MS = 50_000;
50
+
51
+ /** The same timing with both waits capped by what is left of the overall budget. */
52
+ function withinBudget(timing: CoachTiming): CoachTiming {
53
+ const end = timing.now() + (timing.totalBudgetMs ?? DEFAULT_TOTAL_BUDGET_MS);
54
+ const left = (): number => Math.max(0, end - timing.now());
55
+ return {
56
+ ...timing,
57
+ get replyTimeoutMs() { return Math.min(timing.replyTimeoutMs, left()); },
58
+ get settleTimeoutMs() { return Math.min(timing.settleTimeoutMs, left()); },
59
+ };
60
+ }
61
+
62
+ export const DEFAULT_TIMING: CoachTiming = {
63
+ now: Date.now,
64
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
65
+ pollDelayMs: () => randomInt(3_000, 4_001),
66
+ replyTimeoutMs: 60_000,
67
+ settleTimeoutMs: 30_000,
68
+ };
69
+
70
+ type Turn = Record<string, unknown>;
71
+
72
+ /**
73
+ * WHOOP's terminal failure: the turn comes back `turn_status:"FAILED"` with no
74
+ * messages and never changes again (seen live 2026-11-21 on an activity-agent
75
+ * greeting and on the user turn posted after it).
76
+ */
77
+ export const FAILED = "FAILED";
78
+
79
+ /** A 5xx, a network failure or a request timeout: worth another poll. */
80
+ function isTransient(e: unknown): boolean {
81
+ if (e instanceof WhoopServerError) return true;
82
+ if (!(e instanceof Error)) return false;
83
+ return e.name === "AbortError" || e.name === "TimeoutError" || (e instanceof TypeError && /fetch failed|network/i.test(e.message));
84
+ }
85
+
86
+ /** Poll GET …/conversation/{fingerprint}/turn/{id} until COMPLETE, FAILED or the deadline. */
87
+ export async function waitForTurn(
88
+ client: WhoopClient,
89
+ fingerprint: string,
90
+ turnId: string,
91
+ timeoutMs: number,
92
+ timing: CoachTiming,
93
+ ): Promise<{ turn: Turn | null; status: string; timedOut: boolean; polls: number }> {
94
+ const deadline = timing.now() + timeoutMs;
95
+ let turn: Turn | null = null;
96
+ let status = "ACTIVE";
97
+ let polls = 0;
98
+ // No "text stable for N polls" shortcut: text can sit unchanged for several
99
+ // polls while tools run (ai §2.3). COMPLETE is the only done signal; FAILED
100
+ // is the only other state that ends the wait.
101
+ while (timing.now() < deadline) {
102
+ await timing.sleep(Math.min(timing.pollDelayMs(), Math.max(0, deadline - timing.now())));
103
+ polls++;
104
+ try {
105
+ turn = await client.get<Turn>(`${conversationPath(fingerprint)}/turn/${encodeURIComponent(turnId)}`, {}, { fresh: true });
106
+ } catch (e) {
107
+ // One failed poll says nothing about the turn, which keeps running on WHOOP's side.
108
+ if (!isTransient(e)) throw e;
109
+ continue;
110
+ }
111
+ status = turnStatus(turn) ?? status;
112
+ if (status === "COMPLETE" || status === FAILED) return { turn, status, timedOut: false, polls };
113
+ }
114
+ return { turn, status, timedOut: true, polls };
115
+ }
116
+
117
+ export type OpenBody = {
118
+ fingerprint: string;
119
+ source_type: "CHAT_WITH_AGENT" | "UNKNOWN";
120
+ source_id?: string;
121
+ args?: Record<string, unknown>;
122
+ chat_entrypoint_experience?: "STANDARD";
123
+ };
124
+
125
+ /** POST …/conversation: creates the fingerprint, or reopens it (no side effects when it exists). */
126
+ export async function openConversation(client: WhoopClient, body: OpenBody): Promise<Turn> {
127
+ const res = await client.post<Turn>(`${AI}/conversation`, body);
128
+ return res && typeof res === "object" ? res : {};
129
+ }
130
+
131
+ function lastTurn(conversation: Turn): Turn | null {
132
+ const turns = Array.isArray(conversation.turns) ? conversation.turns : [];
133
+ const last = turns[turns.length - 1];
134
+ return last && typeof last === "object" ? (last as Turn) : null;
135
+ }
136
+
137
+ /**
138
+ * Wait for the conversation's last turn when it is still ACTIVE: an agent's
139
+ * turn-0 greeting (posting before it completes gets the greeting back as the
140
+ * "reply", ai §2.2) or a previous user turn (a new post would 409). coach-chat's
141
+ * empty turn 0 counts too: posting while it is ACTIVE got a 409 live
142
+ * (coach-build smoke test, 2026-11-21).
143
+ */
144
+ async function settle(client: WhoopClient, fingerprint: string, conversation: Turn, timing: CoachTiming): Promise<void> {
145
+ const last = lastTurn(conversation);
146
+ if (!last || turnStatus(last) !== "ACTIVE" || typeof last.id !== "string") return;
147
+ await waitForTurn(client, fingerprint, last.id, timing.settleTimeoutMs, timing);
148
+ }
149
+
150
+ const isBusy = (e: unknown) => e instanceof WhoopApiError && e.status === 409;
151
+
152
+ /**
153
+ * POST a user turn. On 409 "Another message is currently being processed",
154
+ * reopen (no side effects), wait for the active turn to COMPLETE, and retry.
155
+ */
156
+ export async function postTurn(
157
+ client: WhoopClient,
158
+ fingerprint: string,
159
+ body: { role: "user"; content: string; is_suggestion: false; file_ids?: string[] },
160
+ reopen: OpenBody,
161
+ timing: CoachTiming,
162
+ maxAttempts = 3,
163
+ ): Promise<{ id: string; retries: number }> {
164
+ for (let attempt = 1; ; attempt++) {
165
+ try {
166
+ const turn = await client.post<Turn>(`${conversationPath(fingerprint)}/turn`, body);
167
+ const id = str(get(turn, "id"));
168
+ if (!id) throw new Error("WHOOP accepted the message but returned no turn id; read the thread with whoop_coach_history.");
169
+ return { id, retries: attempt - 1 };
170
+ } catch (e) {
171
+ if (!isBusy(e) || attempt >= maxAttempts) {
172
+ if (isBusy(e)) {
173
+ throw new Error(`Another message is still being processed in thread ${fingerprint}; try again in a minute.`);
174
+ }
175
+ throw e;
176
+ }
177
+ const conversation = await openConversation(client, reopen);
178
+ const last = lastTurn(conversation);
179
+ if (last && turnStatus(last) === "ACTIVE" && typeof last.id === "string") {
180
+ await waitForTurn(client, fingerprint, last.id, timing.settleTimeoutMs, timing);
181
+ } else {
182
+ await timing.sleep(timing.pollDelayMs());
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ /** One page of the history list. */
189
+ export async function listConversations(
190
+ client: WhoopClient,
191
+ limit: number,
192
+ cursor?: string,
193
+ ): Promise<{ conversations: CoachConversationT[]; next_cursor: string | null }> {
194
+ const raw = await client.get(`${AI}/conversations`, { limit, next_token: cursor }, { fresh: true });
195
+ return projectConversationList(raw);
196
+ }
197
+
198
+ /** Look a fingerprint up in a fresh history list (newest first, a few pages). */
199
+ export async function findListed(
200
+ client: WhoopClient,
201
+ match: (c: CoachConversationT) => boolean,
202
+ maxPages = 5,
203
+ pageSize = 50,
204
+ ): Promise<CoachConversationT | null> {
205
+ let cursor: string | undefined;
206
+ for (let page = 0; page < maxPages; page++) {
207
+ const { conversations, next_cursor } = await listConversations(client, pageSize, cursor);
208
+ const hit = conversations.find(match);
209
+ if (hit) return hit;
210
+ if (!next_cursor) return null;
211
+ cursor = next_cursor;
212
+ }
213
+ return null;
214
+ }
215
+
216
+ /** The cycle id from home, read right before use (never cached: it changes under edits). */
217
+ export async function resolveCycleId(client: WhoopClient, date?: string): Promise<number> {
218
+ const home = await client.get("/home-service/v1/home", date ? { date } : {}, { fresh: true });
219
+ const id = homeCycleId(home);
220
+ if (id === null) throw new Error(`WHOOP's home screen${date ? ` for ${date}` : ""} has no cycle yet, so there is no report to open.`);
221
+ return id;
222
+ }
223
+
224
+ export async function fetchRecommendations(client: WhoopClient, path: string | null): Promise<CoachRecommendationT[] | null> {
225
+ if (!path) return null;
226
+ try {
227
+ const url = new URL(path.startsWith("/") ? path : `/${path}`, "https://x");
228
+ if (!url.pathname.startsWith(`${AI}/recommendation-widget`)) return null;
229
+ const query = Object.fromEntries(url.searchParams.entries());
230
+ const raw = await client.get(url.pathname, query, { fresh: true });
231
+ return projectRecommendations(raw);
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+
237
+ export async function fetchSuggestions(client: WhoopClient, fingerprint: string): Promise<string[]> {
238
+ try {
239
+ const raw = await client.get(`${conversationPath(fingerprint)}/suggestions`, {}, { fresh: true });
240
+ const list = get(raw, "suggestions");
241
+ return Array.isArray(list) ? list.filter((s): s is string => typeof s === "string") : [];
242
+ } catch {
243
+ return [];
244
+ }
245
+ }
246
+
247
+ // ─── Images ───────────────────────────────────────────────────────────────
248
+
249
+ export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
250
+
251
+ /** Decode and sniff a base64 image (optionally a data: URL). PNG and JPEG only. */
252
+ export function parseImage(input: string): { base64: string; contentType: "image/png" | "image/jpeg"; bytes: number } {
253
+ const base64 = input.replace(/^data:image\/[a-z+]+;base64,/i, "").replace(/\s+/g, "");
254
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) throw new Error("image_base64 isn't valid base64.");
255
+ const buf = Buffer.from(base64, "base64");
256
+ if (buf.length === 0) throw new Error("image_base64 decodes to nothing.");
257
+ if (buf.length > MAX_IMAGE_BYTES) throw new Error(`The image is ${buf.length} bytes; the limit is ${MAX_IMAGE_BYTES}.`);
258
+ const png = buf.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
259
+ const jpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
260
+ if (!png && !jpeg) throw new Error("Only PNG or JPEG images can be attached.");
261
+ return { base64, contentType: png ? "image/png" : "image/jpeg", bytes: buf.length };
262
+ }
263
+
264
+ // ─── Fingerprints ─────────────────────────────────────────────────────────
265
+
266
+ /** D7: one totem thread per agent per member-local day, e.g. `totem-HOME-2026-11-21`. */
267
+ export function dailyFingerprint(agent: CoachAgent, localDate: string, activityId?: string): string {
268
+ const tag = AGENT_SOURCES[agent]?.tag ?? agent.toUpperCase();
269
+ return activityId ? `totem-${tag}-${localDate}-${activityId}` : `totem-${tag}-${localDate}`;
270
+ }
271
+
272
+ export function freshFingerprint(agent: CoachAgent, localDate: string): string {
273
+ return `${dailyFingerprint(agent, localDate)}-${randomUUID().slice(0, 8)}`;
274
+ }
275
+
276
+ export function reportFingerprint(kind: "daily_outlook" | "day_in_review", cycleId: number): string {
277
+ return `${REPORT_PREFIX[kind]}${cycleId}`;
278
+ }
279
+
280
+
281
+ // ─── Ask ──────────────────────────────────────────────────────────────────
282
+
283
+ export interface AskPlan {
284
+ agent: CoachAgent;
285
+ message?: string;
286
+ activityId?: string;
287
+ thread?: string;
288
+ newThread: boolean;
289
+ image?: ReturnType<typeof parseImage>;
290
+ localDate: string;
291
+ }
292
+
293
+ function emptyReceipt(thread: string): CoachAskReceiptT {
294
+ return {
295
+ thread, text: null, actions: [], cards: [], suggestions: [], report: null, image_deleted: null,
296
+ verified: false, warnings: [],
297
+ };
298
+ }
299
+
300
+ function describeTurn(receipt: CoachAskReceiptT, turn: Turn | null): void {
301
+ receipt.text = turn ? assistantText(turn) : null;
302
+ receipt.actions = turn ? turnActions(turn) : [];
303
+ receipt.cards = turn ? turnCards(turn) : [];
304
+ if (receipt.actions.length) {
305
+ receipt.warnings.push("The coach changed your data (see actions). It returns no ids; check whoop_day or whoop_workouts.");
306
+ }
307
+ for (const card of receipt.cards) {
308
+ if (card.type === "workout_draft") {
309
+ receipt.warnings.push(
310
+ `The coach created a hidden draft template${card.draft_template_key ? ` (${card.draft_template_key})` : ""}; it's not in your library until saved (whoop_lift_template).`,
311
+ );
312
+ }
313
+ }
314
+ }
315
+
316
+ /** Local marker (never a WHOOP status): the turn was posted but could not be polled. */
317
+ const UNREAD = "UNREAD";
318
+
319
+ const notDone = (s: number, what: string, view: string) =>
320
+ `The ${what} wasn't COMPLETE after ${s} s; read it later with whoop_coach_history ${view}.`;
321
+
322
+ /** Generate or open the current cycle's Daily Outlook / Day in Review. */
323
+ async function openReport(
324
+ client: WhoopClient,
325
+ kind: "daily_outlook" | "day_in_review",
326
+ outerTiming: CoachTiming,
327
+ ): Promise<CoachAskReceiptT> {
328
+ const started = outerTiming.now();
329
+ const timing = withinBudget(outerTiming);
330
+ const cycleId = await resolveCycleId(client);
331
+ const fingerprint = reportFingerprint(kind, cycleId);
332
+ const existed = (await findListed(client, (c) => c.fingerprint === fingerprint, 1)) !== null;
333
+ const receipt = emptyReceipt(fingerprint);
334
+ const conversation = await openConversation(client, { fingerprint, source_id: AGENT_SOURCES[kind]!.source_id, source_type: "UNKNOWN" });
335
+ // The report is turn 0. Later turns are the member's follow-up chat about it.
336
+ const turns = Array.isArray(conversation.turns) ? conversation.turns : [];
337
+ let turn: Turn | null = turns[0] && typeof turns[0] === "object" ? (turns[0] as Turn) : null;
338
+ if (turn && turnStatus(turn) !== "COMPLETE" && turnStatus(turn) !== FAILED && typeof turn.id === "string") {
339
+ turn = (await waitForTurn(client, fingerprint, turn.id, timing.replyTimeoutMs, timing)).turn ?? turn;
340
+ }
341
+ describeTurn(receipt, turn);
342
+ receipt.verified = turnStatus(turn) === "COMPLETE";
343
+ const recommendations = receipt.verified ? await fetchRecommendations(client, recommendationPath(turn)) : null;
344
+ receipt.report = { kind, generated: !existed, recommendations };
345
+ if (turnStatus(turn) === FAILED) receipt.warnings.push("WHOOP failed to generate the report (turn FAILED); nothing more will arrive.");
346
+ else if (!receipt.verified) receipt.warnings.push(notDone(Math.round((outerTiming.now() - started) / 1000), "report", '{view:"outlook"}'));
347
+ return receipt;
348
+ }
349
+
350
+ /** The whole ask: open the thread, settle, (upload), post, poll, (delete the upload), suggestions. */
351
+ export async function askCoach(client: WhoopClient, plan: AskPlan, outerTiming: CoachTiming = DEFAULT_TIMING): Promise<CoachAskReceiptT> {
352
+ if (plan.agent === "daily_outlook" || plan.agent === "day_in_review") return openReport(client, plan.agent, outerTiming);
353
+ const started = outerTiming.now();
354
+ const timing = withinBudget(outerTiming);
355
+ if (!plan.message) throw new Error("message is required for this agent.");
356
+
357
+ let fingerprint: string;
358
+ let open: OpenBody;
359
+ if (plan.thread) {
360
+ const listed = await findListed(client, (c) => c.fingerprint === plan.thread);
361
+ if (!listed) {
362
+ throw new Error(
363
+ `Thread "${plan.thread}" isn't in your coach history. Only listed threads can be continued (reopening an unlisted fingerprint would create it); omit thread to use today's thread.`,
364
+ );
365
+ }
366
+ fingerprint = listed.fingerprint;
367
+ open = { fingerprint, source_type: "UNKNOWN", ...(listed.source_id ? { source_id: listed.source_id } : {}) };
368
+ } else {
369
+ const def = AGENT_SOURCES[plan.agent]!;
370
+ fingerprint = plan.newThread ? freshFingerprint(plan.agent, plan.localDate) : dailyFingerprint(plan.agent, plan.localDate, plan.activityId);
371
+ const args: Record<string, unknown> = def.context ? { context: def.context } : {};
372
+ if (plan.agent === "activity" && plan.activityId) args.activity_id = plan.activityId;
373
+ open = { fingerprint, source_type: "CHAT_WITH_AGENT", source_id: def.source_id, args, chat_entrypoint_experience: "STANDARD" };
374
+ }
375
+
376
+ const receipt = emptyReceipt(fingerprint);
377
+ const conversation = await openConversation(client, open);
378
+ await settle(client, fingerprint, conversation, timing);
379
+
380
+ let fileId: string | null = null;
381
+ let status = "ACTIVE";
382
+ try {
383
+ if (plan.image) {
384
+ const uploaded = await client.post<Record<string, unknown>>(`${AI}/files`, {
385
+ origin: "camera_roll",
386
+ content_type: plan.image.contentType,
387
+ filename: `totem-${timing.now()}.${plan.image.contentType === "image/png" ? "png" : "jpg"}`,
388
+ base64_content: plan.image.base64,
389
+ });
390
+ fileId = str(get(uploaded, "file_id"));
391
+ if (!fileId) throw new Error("WHOOP accepted the image but returned no file id; nothing was sent to the coach.");
392
+ }
393
+ const turnBody = {
394
+ role: "user" as const,
395
+ content: plan.message,
396
+ is_suggestion: false as const,
397
+ ...(fileId ? { file_ids: [fileId] } : {}),
398
+ };
399
+ const posted = await postTurn(client, fingerprint, turnBody, open, timing);
400
+ if (posted.retries) receipt.warnings.push("The thread was busy with another message; totem waited for it and resent.");
401
+ try {
402
+ const polled = await waitForTurn(client, fingerprint, posted.id, timing.replyTimeoutMs, timing);
403
+ status = polled.status;
404
+ describeTurn(receipt, polled.turn);
405
+ } catch (e) {
406
+ // The message is already with the coach (and it may be acting on it): an
407
+ // error here must not read as "nothing was sent", or the caller resends.
408
+ status = UNREAD;
409
+ receipt.warnings.push(
410
+ `Your message was sent, but its reply couldn't be read (${e instanceof Error ? e.message : String(e)}). Don't resend it: read the thread with whoop_coach_history {view:"transcript", fingerprint:"${fingerprint}"}.`,
411
+ );
412
+ }
413
+ // The client dropped its cache when the turn was POSTed, but the coach wrote
414
+ // the data afterwards: anything read (by another call) in between is stale.
415
+ if (receipt.actions.length || status === UNREAD) client.invalidateAll();
416
+ } finally {
417
+ if (fileId) {
418
+ receipt.image_deleted = await client.delete(`${AI}/files/${encodeURIComponent(fileId)}`).then(() => true, () => false);
419
+ if (!receipt.image_deleted) receipt.warnings.push(`Couldn't delete the uploaded image ${fileId} from WHOOP.`);
420
+ }
421
+ }
422
+
423
+ if (status === "COMPLETE") {
424
+ receipt.suggestions = await fetchSuggestions(client, fingerprint);
425
+ receipt.verified = true;
426
+ } else if (status === FAILED) {
427
+ receipt.warnings.push(
428
+ "WHOOP reports this turn FAILED: the coach produced no reply and none will arrive. Ask again, or use new_thread:true if this thread keeps failing.",
429
+ );
430
+ } else if (status !== UNREAD) {
431
+ receipt.warnings.push(notDone(Math.round((outerTiming.now() - started) / 1000), "reply", `{view:"transcript", fingerprint:"${fingerprint}"}`));
432
+ }
433
+ return receipt;
434
+ }
package/src/lib/dates.ts CHANGED
@@ -33,3 +33,21 @@ export function rangeFromDays(days: number, now: Date = new Date()): { start: st
33
33
  const start = new Date(end.getTime() - days * 24 * 60 * 60 * 1000);
34
34
  return { start: start.toISOString(), end: end.toISOString() };
35
35
  }
36
+
37
+ /** Canonical timestamp form required by several undocumented Whoop write APIs. */
38
+ export function canonicalUtc(iso: string | number | Date): string {
39
+ const date = new Date(iso);
40
+ if (Number.isNaN(date.getTime())) throw new Error("Invalid timestamp; expected an ISO-8601 datetime with an offset.");
41
+ return date.toISOString();
42
+ }
43
+
44
+ /**
45
+ * Refuse times in the future. WHOOP accepts future activities and sleeps, then
46
+ * leaves an empty cycle on that date that no API can delete (SPEC.md §7).
47
+ * A small allowance covers clock skew between this host and WHOOP.
48
+ */
49
+ export function assertNotFuture(iso: string, what = "time", now: number = Date.now(), skewMs = 2 * 60_000): void {
50
+ const t = Date.parse(iso);
51
+ if (Number.isNaN(t)) throw new Error(`Invalid ${what}: ${iso}`);
52
+ if (t > now + skewMs) throw new Error(`The ${what} ${iso} is in the future. WHOOP accepts future entries but then leaves an undeletable empty day behind, so totem refuses them.`);
53
+ }
@@ -0,0 +1,191 @@
1
+ // Shared .env reader/writer.
2
+ //
3
+ // Why this exists: values were previously written unquoted, but dotenv treats an
4
+ // unquoted `#` as the start of an inline comment and trims surrounding
5
+ // whitespace. A Whoop password of `#hunter2` therefore parsed back as `""`, and
6
+ // `abc#def` as `abc` — an auth failure that looks like a wrong password
7
+ // (issue #27). Every reader and writer now goes through this module so the value
8
+ // that comes out is byte-for-byte the value that went in.
9
+ //
10
+ // Quoting rules, verified against dotenv's actual parser:
11
+ // bare value ends at a `#` and is trimmed → only safe for "plain" values;
12
+ // backslashes are left alone, so a plain value may contain them
13
+ // '...' literal, but a `'` inside cannot be escaped
14
+ // "..." expands \n and \r, and does not unescape \" → no `"` or backslash
15
+ // `...` literal, but a backtick inside cannot be escaped
16
+ // any quote a backslash right before the closing quote reads as an escaped
17
+ // quote, so the value runs on to the next quote in the FILE and
18
+ // swallows the lines between (see assertReadsBack)
19
+ // CR dotenv turns every CR / CRLF in the file into LF before parsing,
20
+ // so only "..." (as the escape \r) can hold one
21
+ import {
22
+ readFileSync, writeFileSync, existsSync, chmodSync,
23
+ openSync, writeSync, fsyncSync, closeSync, renameSync, rmSync, realpathSync,
24
+ } from "node:fs";
25
+ import { randomBytes } from "node:crypto";
26
+ import { parse } from "dotenv";
27
+
28
+ /** Characters that make an unquoted value parse back as something else. */
29
+ const BARE_UNSAFE = /[#'"`\r\n]/;
30
+ /** A `KEY=` assignment line (leading whitespace and `export ` tolerated). */
31
+ const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
32
+
33
+ /**
34
+ * Quote `value` so `dotenv.parse` returns it unchanged. Prefers the least
35
+ * noisy form that round-trips.
36
+ */
37
+ export function serializeEnvValue(value: string): string {
38
+ if (value !== "" && !BARE_UNSAFE.test(value) && value.trim() === value) return value;
39
+ const literal = !value.includes("\r");
40
+ if (literal && !value.includes("'")) return `'${value}'`;
41
+ if (!value.includes('"') && !value.includes("\\")) return `"${value.replace(/\r/g, "\\r")}"`;
42
+ if (literal && !value.includes("`")) return `\`${value}\``;
43
+ throw new Error(
44
+ "Cannot represent this value in a .env file (it mixes ' \" and `, or a carriage return with a backslash or double quote). Change the value or set it directly in the environment.",
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Refuse a rewrite that dotenv would not read back as intended: every key in
50
+ * `updates` must parse to its new value, every key in `removed` must be gone,
51
+ * and every other key must parse to what it did before.
52
+ *
53
+ * Quoting one value correctly is not enough. A quoted value ending in a
54
+ * backslash (`K='#pw\'`) parses fine alone, but dotenv takes `\'` for an
55
+ * escaped quote when a later line offers another quote to close on: the value
56
+ * then swallows the following lines, and the keys on them vanish. Only the
57
+ * whole file shows that, so check the whole file before it replaces the old one.
58
+ */
59
+ function assertReadsBack(
60
+ before: string,
61
+ after: string,
62
+ updates: Record<string, string>,
63
+ removed: readonly string[] = [],
64
+ ): void {
65
+ const was = parse(before);
66
+ const now = parse(after);
67
+ const own = (record: object, key: string): boolean => Object.prototype.hasOwnProperty.call(record, key);
68
+ const broken = new Set<string>();
69
+ for (const [key, value] of Object.entries(updates)) if (now[key] !== value) broken.add(key);
70
+ for (const key of removed) if (own(now, key)) broken.add(key);
71
+ for (const [key, value] of Object.entries(was)) {
72
+ if (!own(updates, key) && !removed.includes(key) && now[key] !== value) broken.add(key);
73
+ }
74
+ // Keys that newly APPEAR are fine: rewriting a value that used to swallow its
75
+ // neighbours (files written before this check) is how those lines come back.
76
+ if (broken.size > 0) {
77
+ throw new Error(
78
+ `Refusing to rewrite the .env file: ${[...broken].join(", ")} would not read back intact ` +
79
+ "(a value ending in a backslash, or spanning lines, next to another quoted value). " +
80
+ "The file was left unchanged. Change the value, or set it directly in the environment.",
81
+ );
82
+ }
83
+ }
84
+
85
+ export function serializeEnvLine(key: string, value: string): string {
86
+ return `${key}=${serializeEnvValue(value)}`;
87
+ }
88
+
89
+ /** Parse with dotenv itself, so reads match what the server sees at boot. */
90
+ export function parseEnvText(text: string): Record<string, string> {
91
+ return parse(text);
92
+ }
93
+
94
+ export function readEnvFile(path: string): Record<string, string> {
95
+ if (!existsSync(path)) return {};
96
+ try {
97
+ return parse(readFileSync(path, "utf8"));
98
+ } catch {
99
+ return {};
100
+ }
101
+ }
102
+
103
+ /** Errors that mean "can't swap a new file in here", not "the disk is failing". */
104
+ const NO_SWAP = new Set(["EACCES", "EPERM", "EROFS", "EBUSY", "EXDEV", "ENOTSUP"]);
105
+
106
+ /**
107
+ * Replace the file's contents in one step, 0600. The text goes to a sibling
108
+ * temp file that is then renamed over the target, so the file is always either
109
+ * the old version or the new one.
110
+ *
111
+ * Writing in place truncates first. Several totem processes share this file
112
+ * (one per MCP client, plus `totem auth`) and refresh tokens at the same moment,
113
+ * since they hold the same access token. A process reading during another's
114
+ * rewrite saw an empty file about one read in six when measured, which at boot
115
+ * is "Missing WHOOP_EMAIL"; and a crash or a full disk mid-write left every
116
+ * credential gone.
117
+ *
118
+ * Where a sibling can't be created or renamed in (a read-only directory, a
119
+ * single file bind-mounted into a container) it falls back to the in-place
120
+ * write. Any other failure is rethrown with the original file untouched.
121
+ */
122
+ function replaceFile(path: string, text: string): void {
123
+ // Follow a symlinked .env so the link stays a link and its target is replaced.
124
+ let target = path;
125
+ try { target = realpathSync(path); } catch { /* doesn't exist yet */ }
126
+ const temp = `${target}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
127
+ try {
128
+ const fd = openSync(temp, "wx", 0o600);
129
+ try {
130
+ writeSync(fd, text);
131
+ fsyncSync(fd);
132
+ } finally {
133
+ closeSync(fd);
134
+ }
135
+ renameSync(temp, target);
136
+ } catch (error) {
137
+ try { rmSync(temp, { force: true }); } catch { /* nothing to clean up */ }
138
+ if (!NO_SWAP.has((error as NodeJS.ErrnoException).code ?? "")) throw error;
139
+ writeFileSync(target, text, { mode: 0o600 });
140
+ }
141
+ // The in-place path keeps an existing file's mode, so repair files written by older versions.
142
+ try { chmodSync(target, 0o600); } catch { /* best-effort on exotic filesystems */ }
143
+ }
144
+
145
+ /**
146
+ * Update keys in place, preserving comments, blank lines and unrelated
147
+ * entries. Duplicate assignments of an updated key collapse to one; keys not
148
+ * already present are appended. Written 0600 — this file holds tokens.
149
+ */
150
+ export function upsertEnvFile(path: string, updates: Record<string, string>): void {
151
+ const raw = existsSync(path) ? readFileSync(path, "utf8") : "";
152
+ const lines = raw.length > 0 ? raw.split("\n") : [];
153
+ // A trailing newline yields a final empty element; drop it and re-add on write
154
+ // so appended keys don't land after a blank line.
155
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
156
+
157
+ const pending = new Map(Object.entries(updates));
158
+ const out: string[] = [];
159
+ for (const line of lines) {
160
+ const key = ASSIGNMENT.exec(line)?.[1];
161
+ if (key !== undefined && Object.prototype.hasOwnProperty.call(updates, key)) {
162
+ // First occurrence becomes the new value; later duplicates are dropped.
163
+ if (pending.has(key)) {
164
+ out.push(serializeEnvLine(key, pending.get(key)!));
165
+ pending.delete(key);
166
+ }
167
+ continue;
168
+ }
169
+ out.push(line);
170
+ }
171
+ for (const [key, value] of pending) out.push(serializeEnvLine(key, value));
172
+
173
+ const text = out.join("\n") + "\n";
174
+ assertReadsBack(raw, text, updates);
175
+ replaceFile(path, text);
176
+ }
177
+
178
+ /** Remove keys entirely (used to wipe the one-time password after bootstrap). */
179
+ export function deleteEnvKeys(path: string, keys: readonly string[]): void {
180
+ if (!existsSync(path)) return;
181
+ const raw = readFileSync(path, "utf8");
182
+ const lines = raw.split("\n");
183
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
184
+ const kept = lines.filter((line) => {
185
+ const key = ASSIGNMENT.exec(line)?.[1];
186
+ return key === undefined || !keys.includes(key);
187
+ });
188
+ const text = kept.join("\n") + "\n";
189
+ assertReadsBack(raw, text, {}, keys);
190
+ replaceFile(path, text);
191
+ }