@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,255 @@
1
+ // whoop_lift_sessions (R): replaces whoop_lift_history + whoop_lift_overview.
2
+ // Lists come from the app's own day screens (SPEC.md D1), never /developer/v2,
3
+ // which hides unscored activities.
4
+ import { z } from "zod";
5
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import type { WhoopClient } from "../../whoop/client.js";
7
+ import { defineTool, respond } from "../define.js";
8
+ import { READ_ONLY } from "../annotations.js";
9
+ import { LiftSessionsOut, type LiftSessionOutT } from "../../schemas/strength_v2.js";
10
+ import {
11
+ activityFromDetail,
12
+ buildSession,
13
+ exerciseCols,
14
+ hasLiftData,
15
+ hoistUnit,
16
+ homeActivities,
17
+ parseCardioDetails,
18
+ parseHistoryCards,
19
+ type HomeActivity,
20
+ } from "../../projections/lift_sessions.js";
21
+ import type { LiftCard } from "../../projections/lift_cards.js";
22
+ import { walkHistory } from "../../lib/lift_history.js";
23
+ import { badActivityIdError, readActivityAs } from "../../lib/activity_records.js";
24
+ import { WhoopApiError } from "../../whoop/errors.js";
25
+ import { get } from "../../whoop/bff.js";
26
+ import { runPaced } from "../../lib/concurrency.js";
27
+ import { isoDay, todayIso } from "../../lib/dates.js";
28
+
29
+ const TOOL = "whoop_lift_sessions";
30
+ const MAX_SPAN_DAYS = 60;
31
+ const DEFAULT_SPAN_DAYS = 14;
32
+ const DAY_CHUNK = 3;
33
+ // The unscored sweep (opt-in): WHOOP has no read for one workout's sets, only
34
+ // per-exercise history, so it costs up to PR_PAGES requests plus one or more per
35
+ // exercise the account has a PR tile for (live: 30–45 requests for 25 exercises).
36
+ const PR_PAGES = 6; // exercises probed for unscored sessions: 10 per page
37
+ const HISTORY_PAGES = 4; // 5 workouts per page
38
+ const PACE = { concurrency: 3, jitterMaxMs: 120 };
39
+ const STRENGTH_TRAINER = "weightlifting_msk";
40
+
41
+ type Session = LiftSessionOutT & { _unit: "kg" | "lb" | null };
42
+ /** cardio-details answered 400 (pending): treat as unscored. */
43
+ const PENDING_400 = Symbol("pending");
44
+ type CardIndex = Map<string, Array<{ exercise_id: string; name: string | null; card: LiftCard }>>;
45
+
46
+ function addDays(date: string, n: number): string {
47
+ return new Date(Date.parse(`${date}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
48
+ }
49
+ function daysBetween(a: string, b: string): number {
50
+ return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);
51
+ }
52
+
53
+ /** Days in [start, end] that calendar/overview marks has_data (newest first), or every day if it can't be read. */
54
+ async function daysWithData(client: WhoopClient, start: string, end: string, warnings: string[]): Promise<string[]> {
55
+ const all: string[] = [];
56
+ for (let d = end; d >= start; d = addDays(d, -1)) all.push(d);
57
+ try {
58
+ const marked = new Set<string>();
59
+ for (const month of [...new Set(all.map((d) => d.slice(0, 7)))]) {
60
+ const raw = await client.get("/home-service/v1/calendar/overview", { date: `${month}-01` });
61
+ for (const day of (get(raw, "days_of_month") ?? []) as unknown[]) {
62
+ const n = Number(get(day, "date_value_display"));
63
+ if (get(day, "has_data") === true && Number.isInteger(n)) marked.add(`${month}-${String(n).padStart(2, "0")}`);
64
+ }
65
+ }
66
+ return all.filter((d) => marked.has(d));
67
+ } catch {
68
+ warnings.push("Calendar unreadable; checked every day.");
69
+ return all;
70
+ }
71
+ }
72
+
73
+ /** An activity whose lift sets (if any) only exercise_history can show. */
74
+ function unscored(activity: HomeActivity, detail: unknown): boolean {
75
+ if (hasLiftData(detail)) return false;
76
+ const strain = get(detail, "horizontal_stat", "stat_main_value_display");
77
+ return activity.internal_name === STRENGTH_TRAINER || activity.status === "INCOMPLETE" || strain === "---" || strain === "--";
78
+ }
79
+
80
+ /**
81
+ * Sets for unscored sessions: exercise_history is per exercise, so walk the
82
+ * exercises the account has records for (v3/prs, deduped, deleted dropped) and
83
+ * keep the cards whose GO TO ACTIVITY button points at a wanted activity.
84
+ * `fresh` skips the cache (a just-logged workout can lag ~30 s behind).
85
+ */
86
+ async function historyIndex(client: WhoopClient, wanted: Set<string>, notBefore: string | undefined, fresh: boolean, warnings: string[]): Promise<CardIndex> {
87
+ const exercises = new Map<string, string | null>();
88
+ let offset = 0;
89
+ let more = true;
90
+ for (let page = 0; page < PR_PAGES && more; page++) {
91
+ const raw = await client.get("/weightlifting-service/v3/prs", offset ? { offset } : {}, fresh ? { fresh: true } : {});
92
+ for (const t of (get(raw, "tiles") ?? []) as unknown[]) {
93
+ const id = get(t, "exercise_id");
94
+ if (typeof id === "string" && get(t, "deleted") !== true && !exercises.has(id)) exercises.set(id, (get(t, "name") as string | undefined) ?? null);
95
+ }
96
+ more = get(raw, "show_more") === true;
97
+ const next = Number(get(raw, "next_exercise_offset"));
98
+ offset = Number.isFinite(next) && next > offset ? next : offset + 10;
99
+ }
100
+ if (more) warnings.push(`Unscored sessions were matched against the first ${exercises.size} exercises of your PR list only; an exercise beyond them is missing.`);
101
+
102
+ const index: CardIndex = new Map();
103
+ await runPaced([...exercises].map(([exerciseId, name]) => () =>
104
+ walkHistory(client, exerciseId, { notBefore, maxPages: HISTORY_PAGES, fresh }, (cards) => {
105
+ for (const card of cards) {
106
+ if (!card.activity_id || !wanted.has(card.activity_id)) continue;
107
+ const list = index.get(card.activity_id) ?? [];
108
+ list.push({ exercise_id: exerciseId, name, card });
109
+ index.set(card.activity_id, list);
110
+ }
111
+ })), PACE);
112
+ return index;
113
+ }
114
+
115
+ /**
116
+ * How far back the sweep pages each exercise's history: a day before the oldest
117
+ * wanted activity, not the whole requested range. `fallbackDay` when a start is unknown.
118
+ */
119
+ function sweepFloor(activities: HomeActivity[], fallbackDay: string): string {
120
+ const starts = activities.map((a) => a.start);
121
+ if (starts.length === 0 || starts.some((s) => !s)) return `${fallbackDay}T00:00:00.000Z`;
122
+ const oldest = Math.min(...starts.map((s) => Date.parse(s!)));
123
+ return new Date(oldest - 86_400_000).toISOString();
124
+ }
125
+
126
+ /** True when any activity started within the last 2 h (its history may still be catching up). */
127
+ function recent(activities: HomeActivity[], now = Date.now()): boolean {
128
+ return activities.some((a) => !a.start || now - Date.parse(a.start) < 2 * 3_600_000);
129
+ }
130
+
131
+ function fromIndex(activity: HomeActivity, detail: unknown, index: CardIndex, withRows: boolean): Session | null {
132
+ const cards = index.get(activity.activity_id);
133
+ if (cards?.length) return buildSession(activity, detail, parseHistoryCards(cards), "history", withRows);
134
+ if (activity.internal_name === STRENGTH_TRAINER) return buildSession(activity, detail, { exercises: [], volume: null, unit: null }, "none", withRows);
135
+ return null;
136
+ }
137
+
138
+ export function registerLiftSessions(server: McpServer, client: WhoopClient): void {
139
+ defineTool(server, {
140
+ name: TOOL,
141
+ description:
142
+ "Strength sessions, newest first (default last 14 days, max 60): any activity with Strength Trainer sets. Exercises are rows in " +
143
+ "exercise_cols order: id, set scheme, top set [weight, reps], volume, medal. Unscored sessions list without exercises: include " +
144
+ "unscored (or activity_id) reads their sets from exercise history, which is slow. Weights are in unit.",
145
+ input: {
146
+ start_date: z.iso.date().optional(),
147
+ end_date: z.iso.date().optional(),
148
+ activity_id: z.string().optional(),
149
+ limit: z.number().int().min(1).max(20).default(3),
150
+ include: z.array(z.enum(["sets", "unscored"])).optional(),
151
+ },
152
+ annotations: READ_ONLY,
153
+ }, async ({ start_date, end_date, activity_id, limit, include }) => {
154
+ const warnings: string[] = [];
155
+ const withRows = include?.includes("sets") ?? false;
156
+ const sweep = include?.includes("unscored") ?? false;
157
+ const today = todayIso();
158
+
159
+ if (activity_id) {
160
+ let detail: unknown = null;
161
+ try {
162
+ detail = await client.get("/core-details-bff/v1/cardio-details", { activityId: activity_id });
163
+ } catch (e) {
164
+ // WHOOP sometimes answers 400 "Cannot view activity details for a pending activity" for a few seconds after a log.
165
+ if (!(e instanceof WhoopApiError && e.status === 400)) throw badActivityIdError(e, activity_id) ?? e;
166
+ warnings.push("Activity details unavailable while pending; sets come from exercise history.");
167
+ }
168
+ let activity = activityFromDetail(activity_id, detail, today);
169
+ if (!activity.start) {
170
+ // The raw record answers in every state: its window bounds the history paging below.
171
+ const record = await readActivityAs(client, activity_id, "CARDIO").catch(() => null);
172
+ if (record?.start) activity = { ...activity, internal_name: activity.internal_name ?? record.type, start: record.start, end: record.end };
173
+ }
174
+ if (activity.start) activity.date = isoDay(new Date(activity.start));
175
+ let session: Session | null;
176
+ if (hasLiftData(detail)) session = buildSession(activity, detail, parseCardioDetails(detail), "details", withRows);
177
+ // A scored activity of another sport with no lift block has no sets: the list applies the
178
+ // same rule. Sweeping every exercise's history to say so cost 28 requests for a boxing id.
179
+ else if (detail !== null && !unscored(activity, detail)) session = null;
180
+ else {
181
+ session = fromIndex(activity, detail, await historyIndex(client, new Set([activity_id]), sweepFloor([activity], addDays(today, -MAX_SPAN_DAYS)), recent([activity]), warnings), withRows);
182
+ }
183
+ if (!session) warnings.push("This activity has no Strength Trainer sets.");
184
+ const hoisted = hoistUnit(session ? [session] : []);
185
+ return respond(TOOL, LiftSessionsOut, {
186
+ from: activity.date, to: activity.date, ...hoisted, exercise_cols: exerciseCols(hoisted.sessions, withRows), more: false, warnings,
187
+ });
188
+ }
189
+
190
+ const end = !end_date || end_date > today ? today : end_date;
191
+ const start = start_date ?? addDays(end, -(DEFAULT_SPAN_DAYS - 1));
192
+ if (start > end) throw new Error(`start_date ${start} is after end_date ${end}.`);
193
+ const span = daysBetween(start, end) + 1;
194
+ if (span > MAX_SPAN_DAYS) throw new Error(`The range is ${span} days; the maximum is ${MAX_SPAN_DAYS}.`);
195
+
196
+ const days = await daysWithData(client, start, end, warnings);
197
+ const sessions: Session[] = [];
198
+ const candidates = new Map<string, { activity: HomeActivity; detail: unknown }>();
199
+ const seen = new Set<string>();
200
+ const found = () => sessions.length + [...candidates.values()].filter((c) => c.activity.internal_name === STRENGTH_TRAINER).length;
201
+ let scanned = 0;
202
+ let detailFailures = 0;
203
+ for (let i = 0; i < days.length && found() < limit; i += DAY_CHUNK) {
204
+ const chunk = days.slice(i, i + DAY_CHUNK);
205
+ const homes = await runPaced(chunk.map((d) => () => client.get("/home-service/v1/home", { date: d }).catch(() => null)), PACE);
206
+ scanned += chunk.length;
207
+ const activities = homes
208
+ .flatMap((h, k) => (h ? homeActivities(h, chunk[k]!) : []))
209
+ .filter((a) => a.type === "CARDIO" && !seen.has(a.activity_id) && (seen.add(a.activity_id), true));
210
+ const details = await runPaced(
211
+ activities.map((a) => () => client.get("/core-details-bff/v1/cardio-details", { activityId: a.activity_id })
212
+ .catch((e) => (e instanceof WhoopApiError && e.status === 400 ? PENDING_400 : undefined))),
213
+ PACE,
214
+ );
215
+ activities.forEach((a, k) => {
216
+ const detail = details[k];
217
+ if (detail === PENDING_400) candidates.set(a.activity_id, { activity: a, detail: null });
218
+ else if (detail === undefined) detailFailures++;
219
+ else if (hasLiftData(detail)) sessions.push(buildSession(a, detail, parseCardioDetails(detail), "details", withRows));
220
+ else if (unscored(a, detail)) candidates.set(a.activity_id, { activity: a, detail });
221
+ });
222
+ }
223
+ if (detailFailures) warnings.push(`${detailFailures} activity detail read(s) failed.`);
224
+
225
+ if (candidates.size > 0 && sweep) {
226
+ const list = [...candidates.values()].map((c) => c.activity);
227
+ const index = await historyIndex(client, new Set(candidates.keys()), sweepFloor(list, addDays(start, -1)), recent(list), warnings);
228
+ for (const { activity, detail } of candidates.values()) {
229
+ const s = fromIndex(activity, detail, index, withRows);
230
+ if (s) sessions.push(s);
231
+ }
232
+ } else if (candidates.size > 0) {
233
+ // Default: no sweep. Strength Trainer workouts are listed without their sets;
234
+ // other unscored sports are left out (only the sweep can tell whether sets were attached).
235
+ let listed = 0;
236
+ for (const { activity, detail } of candidates.values()) {
237
+ if (activity.internal_name !== STRENGTH_TRAINER) continue;
238
+ sessions.push(buildSession(activity, detail, { exercises: [], volume: null, unit: null }, "unscored", withRows));
239
+ listed++;
240
+ }
241
+ if (listed) warnings.push(`${listed} unscored session(s) listed without exercises; include ["unscored"] (or activity_id) reads their sets from exercise history.`);
242
+ }
243
+
244
+ sessions.sort((a, b) => (b.start ?? "").localeCompare(a.start ?? ""));
245
+ const hoisted = hoistUnit(sessions.slice(0, limit));
246
+ return respond(TOOL, LiftSessionsOut, {
247
+ from: start,
248
+ to: end,
249
+ ...hoisted,
250
+ exercise_cols: exerciseCols(hoisted.sessions, withRows),
251
+ more: sessions.length > limit || scanned < days.length,
252
+ warnings,
253
+ });
254
+ });
255
+ }
@@ -0,0 +1,229 @@
1
+ // whoop_lift_template (W!): replaces whoop_lift_template_save; closes issue #5
2
+ // (update + delete). SPEC.md D4: POST v3 with an existing key edits in place, but
3
+ // an unknown or deleted key silently creates a new template, so edits are
4
+ // existence-checked first; copy = GET + POST without a key.
5
+ import { z } from "zod";
6
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import type { WhoopClient } from "../../whoop/client.js";
8
+ import { defineTool, respond } from "../define.js";
9
+ import { WRITE_DESTRUCTIVE } from "../annotations.js";
10
+ import { LiftTemplateOut } from "../../schemas/strength_v2.js";
11
+ import { preview } from "../../whoop/write_safety.js";
12
+ import { accountWeightUnit } from "../../whoop/units.js";
13
+ import { WhoopApiError } from "../../whoop/errors.js";
14
+ import { get } from "../../whoop/bff.js";
15
+ import { ExerciseResolver } from "../../lib/lift_catalog.js";
16
+ import { buildTemplateGroups, sentWeight, setShapeProblems, type ExerciseSets } from "../../lib/lift_sets.js";
17
+ import { errorMessage, liftError } from "../../lib/lift_tool.js";
18
+ import { groupExercises } from "../../projections/lift_library_v2.js";
19
+
20
+ const TOOL = "whoop_lift_template";
21
+ export const TEMPLATE_POST = "/weightlifting-service/v3/workout-template";
22
+ export const templatePath = (key: number | string) => `/weightlifting-service/v2/workout-template/${encodeURIComponent(String(key))}`;
23
+ const prebuiltPath = (id: string) => `/weightlifting-service/v2/prebuilt-workout-template/${encodeURIComponent(id)}`;
24
+
25
+ const SetIn = z.object({
26
+ reps: z.number().int().min(0).max(1000).optional(),
27
+ weight: z.number().min(0).max(2000).optional(),
28
+ time_seconds: z.number().int().min(1).max(86_400).optional(),
29
+ });
30
+ const ExerciseIn = z.object({
31
+ exercise_id: z.string().optional(),
32
+ name: z.string().optional().describe("Or the exact name"),
33
+ sets: z.array(SetIn).min(1).max(50),
34
+ });
35
+
36
+ const is404 = (e: unknown) => e instanceof WhoopApiError && e.status === 404;
37
+
38
+ /** Re-send groups as read: the verbatim exercise rows with sets cut to the three fields WHOOP keeps. */
39
+ function cleanGroups(groups: unknown): unknown[] {
40
+ const list = Array.isArray(groups) ? groups : [];
41
+ return list.map((g) => ({
42
+ workout_exercises: ((get(g, "workout_exercises") ?? []) as unknown[]).map((we) => ({
43
+ exercise_details: get(we, "exercise_details"),
44
+ sets: ((get(we, "sets") ?? []) as unknown[]).map((s) => {
45
+ const set: Record<string, unknown> = { number_of_reps: get(s, "number_of_reps") ?? 0 };
46
+ if (typeof get(s, "weight") === "number") set.weight = get(s, "weight");
47
+ if (typeof get(s, "time_in_seconds") === "number") set.time_in_seconds = get(s, "time_in_seconds");
48
+ return set;
49
+ }),
50
+ })),
51
+ }));
52
+ }
53
+
54
+ function shape(groups: unknown): { ids: string[]; sets: number } {
55
+ const ex = groupExercises(groups);
56
+ return { ids: ex.map((e) => e.id), sets: ex.reduce((n, e) => n + e.sets.length, 0) };
57
+ }
58
+
59
+ type Exercises = ReturnType<typeof groupExercises>;
60
+
61
+ /** Same exercises in the same order, and every set's reps, weight and time as sent. */
62
+ function sameSets(sent: Exercises, back: Exercises): boolean {
63
+ return sent.length === back.length && sent.every((e, i) => {
64
+ const b = back[i]!;
65
+ return e.id === b.id && e.sets.length === b.sets.length && e.sets.every((s, k) => {
66
+ const t = b.sets[k]!;
67
+ return (s.reps ?? 0) === (t.reps ?? 0) && Math.abs((s.weight ?? 0) - (t.weight ?? 0)) <= 0.05 && (s.time ?? 0) === (t.time ?? 0);
68
+ });
69
+ });
70
+ }
71
+
72
+ export function registerLiftTemplate(server: McpServer, client: WhoopClient): void {
73
+ defineTool(server, {
74
+ name: TOOL,
75
+ description:
76
+ "Manage your Strength Trainer templates. create: name and exercises. edit: template_key with a new name and/or exercises (the " +
77
+ "whole list is replaced). copy: copy_from (your template_key or a WHOOP prebuilt_id) into a new template. delete: template_key. " +
78
+ "Weights need unit. Keys: whoop_lift_library. Previews unless confirm:true.",
79
+ input: {
80
+ action: z.enum(["create", "edit", "copy", "delete"]),
81
+ template_key: z.number().int().optional(),
82
+ copy_from: z.union([z.number().int(), z.string()]).optional(),
83
+ name: z.string().min(1).max(100).optional(),
84
+ exercises: z.array(ExerciseIn).min(1).max(30).optional(),
85
+ unit: z.enum(["kg", "lb"]).optional(),
86
+ confirm: z.boolean().default(false),
87
+ },
88
+ annotations: WRITE_DESTRUCTIVE,
89
+ }, async ({ action, template_key, copy_from, name, exercises, unit, confirm }) => {
90
+ const warnings: string[] = [];
91
+
92
+ // 1. Validate.
93
+ if ((action === "edit" || action === "delete") && template_key === undefined) return liftError({ error: `${action} needs template_key.` });
94
+ if (action === "create" && (!name || !exercises)) return liftError({ error: "create needs name and exercises." });
95
+ if (action === "copy" && copy_from === undefined) return liftError({ error: "copy needs copy_from." });
96
+ if (action === "edit" && !name && !exercises) return liftError({ error: "edit needs a new name and/or exercises." });
97
+ if (action === "delete" && (name || exercises)) return liftError({ error: "delete takes only template_key." });
98
+ // No default unit: a bare 225 read as kg on a lb account would be saved as 496 lb.
99
+ if (!unit && exercises?.some((e) => e.sets.some((s) => (s.weight ?? 0) > 0))) {
100
+ return liftError({ error: "Say which unit the weights are in: unit \"kg\" or \"lb\". Nothing is assumed." });
101
+ }
102
+
103
+ // 2. Fresh pre-reads.
104
+ let current: unknown = null;
105
+ let copiedFrom: string | null = null;
106
+ if (action === "edit" || action === "delete") {
107
+ try {
108
+ current = await client.get(templatePath(template_key!), {}, { fresh: true });
109
+ } catch (e) {
110
+ if (is404(e)) return liftError({ error: `No template ${template_key}. List yours with whoop_lift_library.` });
111
+ throw e;
112
+ }
113
+ }
114
+ if (action === "copy") {
115
+ const key = String(copy_from);
116
+ try {
117
+ current = await client.get(templatePath(key), {}, { fresh: true });
118
+ copiedFrom = `template ${key}`;
119
+ } catch (e) {
120
+ if (!is404(e)) throw e;
121
+ try {
122
+ current = get(await client.get(prebuiltPath(key), {}, { fresh: true }), "workout_template");
123
+ copiedFrom = `WHOOP workout ${key}`;
124
+ } catch (e2) {
125
+ if (is404(e2)) return liftError({ error: `copy_from ${key} is neither your template nor a WHOOP workout.` });
126
+ throw e2;
127
+ }
128
+ }
129
+ }
130
+
131
+ let items: ExerciseSets[] | null = null;
132
+ if (exercises) {
133
+ const resolution = await new ExerciseResolver(client).resolveAll(exercises);
134
+ if (!resolution.ok) return liftError({ error: "Unknown exercise(s).", misses: resolution.misses });
135
+ items = resolution.exercises.map((exercise, i) => ({ exercise, sets: exercises[i]!.sets }));
136
+ const problems = setShapeProblems(items);
137
+ if (problems.length > 0) return liftError({ error: "Some sets don't fit their exercise.", problems });
138
+ }
139
+
140
+ if (action === "delete") {
141
+ const currentName = String(get(current, "name") ?? "");
142
+ if (!confirm) {
143
+ return respond(TOOL, LiftTemplateOut, preview("DELETE", templatePath(template_key!), { template_key, name: currentName, ...shape(get(current, "workout_groups")) }));
144
+ }
145
+ await client.delete(templatePath(template_key!));
146
+ let gone = false;
147
+ try {
148
+ await client.get(templatePath(template_key!), {}, { fresh: true });
149
+ warnings.push("The template still reads back after the delete.");
150
+ } catch (e) {
151
+ gone = is404(e);
152
+ if (!gone) warnings.push(`Read-back failed: ${errorMessage(e)}`);
153
+ }
154
+ const s = shape(get(current, "workout_groups"));
155
+ return respond(TOOL, LiftTemplateOut, {
156
+ action: "deleted", template_key: template_key!, name: currentName, exercises: s.ids.length, sets: s.sets,
157
+ unit: null, sent_unit: null, verified: gone, warnings,
158
+ });
159
+ }
160
+
161
+ // The display unit is the last read before the write (D2). Without new sets the
162
+ // weights are re-sent exactly as read, so no unit is involved.
163
+ const account = items ? await accountWeightUnit(client) : null;
164
+ const input = unit ?? account;
165
+ const converted = account !== null && input !== account;
166
+ const groups = items ? buildTemplateGroups(items, { input: input!, account: account! }) : cleanGroups(get(current, "workout_groups"));
167
+ const finalName = name ?? (action === "copy" ? `${String(get(current, "name") ?? "Workout")} (copy)` : String(get(current, "name") ?? ""));
168
+ const body: Record<string, unknown> = { name: finalName, workout_groups: groups };
169
+ if (action === "edit") {
170
+ body.workout_template_key = template_key;
171
+ const source = get(current, "source");
172
+ if (source === "USER" || source === "AI") body.source = source;
173
+ }
174
+ const sent = shape(groups);
175
+
176
+ if (!confirm) {
177
+ const was = shape(get(current, "workout_groups"));
178
+ return respond(TOOL, LiftTemplateOut, preview("POST", TEMPLATE_POST, {
179
+ action,
180
+ ...(action === "edit" ? { template_key, was: String(get(current, "name") ?? "") } : {}),
181
+ ...(copiedFrom ? { copy_of: copiedFrom } : {}),
182
+ name: finalName,
183
+ // New sets: weights as the caller gave them, plus `sent` (the account's unit) when converted.
184
+ // Unchanged sets (rename, copy): counts only; whoop_lift_library shows them with their unit.
185
+ ...(items
186
+ ? {
187
+ exercises: items.map(({ exercise, sets }) => ({
188
+ id: exercise.exercise_id,
189
+ sets: sets.map((s) => [s.weight ?? 0, exercise.volume_input_format === "TIME" ? (s.time_seconds ?? null) : (s.reps ?? null)]),
190
+ ...(converted ? { sent: sets.map((s) => sentWeight(s.weight, input!, account!)) } : {}),
191
+ })),
192
+ unit: input,
193
+ ...(converted ? { sent_unit: account } : {}),
194
+ ...(action === "edit" ? { replaces: { exercises: was.ids.length, sets: was.sets } } : {}),
195
+ }
196
+ : { exercises: sent.ids.length, sets: sent.sets, ...(action === "edit" ? { note: "Exercises unchanged." } : {}) }),
197
+ }));
198
+ }
199
+
200
+ const receipt = await client.post(TEMPLATE_POST, body);
201
+ const key = get(receipt, "workout_template_key");
202
+ if (typeof key !== "number") throw new Error("WHOOP saved the template but returned no workout_template_key; check whoop_lift_library.");
203
+ // An edit must come back under the same key. A different one means WHOOP created a
204
+ // new template (the key vanished after the existence check), so nothing was edited.
205
+ const strayed = action === "edit" && key !== template_key;
206
+ if (strayed) warnings.push(`WHOOP created template ${key} instead of editing ${template_key} (it no longer exists). Delete ${key} if it isn't wanted.`);
207
+
208
+ let verified = false;
209
+ try {
210
+ const back = await client.get(templatePath(key), {}, { fresh: true });
211
+ const same = get(back, "name") === finalName && sameSets(groupExercises(groups), groupExercises(get(back, "workout_groups")));
212
+ if (!same) warnings.push("The template read back differently from what was sent.");
213
+ verified = same && !strayed;
214
+ } catch (e) {
215
+ warnings.push(`Read-back failed: ${errorMessage(e)}`);
216
+ }
217
+ return respond(TOOL, LiftTemplateOut, {
218
+ action: action === "create" || strayed ? "created" : action === "edit" ? "edited" : "copied",
219
+ template_key: key,
220
+ name: finalName,
221
+ exercises: sent.ids.length,
222
+ sets: sent.sets,
223
+ unit: items ? input : null,
224
+ sent_unit: converted ? account : null,
225
+ verified,
226
+ warnings,
227
+ });
228
+ });
229
+ }
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { defineTool, respond } from "../define.js";
5
+ import { READ_ONLY } from "../annotations.js";
6
+ import { MemoryOut } from "../../schemas/memory.js";
7
+ import { findCardContent, projectMemoryDetail, projectMemoryItems } from "../../projections/memory.js";
8
+ import { WhoopServerError } from "../../whoop/errors.js";
9
+
10
+ const TOOL = "whoop_memory";
11
+ export const CONTEXT_HUB = "/context-hub-bff/v1/context-hub";
12
+
13
+ export const memoryInput = {
14
+ category: z.string().regex(/^[a-z][a-z_]{0,39}$/, "lower_snake_case category").default("timeline")
15
+ .describe("timeline = all, or a key from categories"),
16
+ limit: z.number().int().min(1).max(100).default(10),
17
+ memory_id: z.uuid().optional(),
18
+ };
19
+
20
+ /** Fresh read of one category's raw items (the context hub is never cached). */
21
+ export function readMemoryRaw(client: WhoopClient, category: string): Promise<unknown> {
22
+ return client.get(`${CONTEXT_HUB}/items`, { category }, { fresh: true });
23
+ }
24
+
25
+ export async function readMemoryItems(client: WhoopClient, category: string, limit?: number) {
26
+ return projectMemoryItems(await readMemoryRaw(client, category), category, limit);
27
+ }
28
+
29
+ export function registerMemory(server: McpServer, client: WhoopClient): void {
30
+ defineTool(
31
+ server,
32
+ {
33
+ name: TOOL,
34
+ description:
35
+ "What WHOOP Coach remembers about you: memories with id, title, summary and ACTIVE/INACTIVE status, plus the categories that have " +
36
+ "items. memory_id opens one memory's detail and marks it seen in the app, so only open it when asked. Memories can't be created " +
37
+ "here; the coach saves them from chats.",
38
+ input: memoryInput,
39
+ annotations: READ_ONLY,
40
+ },
41
+ async ({ category, limit, memory_id }) => {
42
+ if (!memory_id) return respond(TOOL, MemoryOut, await readMemoryItems(client, category, limit));
43
+ const [detail, timeline] = await Promise.all([
44
+ client.get(`${CONTEXT_HUB}/context-detail/${memory_id}`, {}, { fresh: true }).catch((e: unknown) => {
45
+ // A deleted id answers 500 HTML, not 404 (ai §2.11).
46
+ if (e instanceof WhoopServerError) throw new Error(`No memory ${memory_id} (WHOOP answers 500 for deleted or unknown ids).`);
47
+ throw e;
48
+ }),
49
+ readMemoryRaw(client, "timeline").catch(() => null),
50
+ ]);
51
+ return respond(TOOL, MemoryOut, projectMemoryDetail(detail, memory_id, findCardContent(timeline, memory_id)));
52
+ },
53
+ );
54
+ }
@@ -0,0 +1,110 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { defineTool, respond } from "../define.js";
5
+ import { WRITE_DESTRUCTIVE } from "../annotations.js";
6
+ import { preview } from "../../whoop/write_safety.js";
7
+ import { MemorySetOut, type MemoryRowT, type MemorySetReceiptT } from "../../schemas/memory.js";
8
+ import { memoryEnabled } from "../../projections/memory.js";
9
+ import { CONTEXT_HUB, readMemoryItems } from "./memory.js";
10
+
11
+ const TOOL = "whoop_memory_set";
12
+ export const AI_SETTINGS = "/ai-conversation-service/v1/settings";
13
+ const MEMORY_OFF_WARNING =
14
+ 'With memory off the coach may still say it saved something ("Added your … goal"), but nothing is stored.';
15
+
16
+ export const memorySetInput = {
17
+ action: z.enum(["activate", "deactivate", "delete", "enable_memory", "disable_memory"]),
18
+ memory_id: z.uuid().optional().describe("From whoop_memory"),
19
+ confirm: z.boolean().default(false),
20
+ };
21
+
22
+ /** Find a card without opening its detail (a read receipt): timeline first, then each category. */
23
+ export async function findMemory(client: WhoopClient, id: string): Promise<MemoryRowT | null> {
24
+ const timeline = await readMemoryItems(client, "timeline");
25
+ const hit = timeline.items.find((i) => i.id === id);
26
+ if (hit) return hit;
27
+ for (const key of timeline.categories.filter((k) => k !== "timeline")) {
28
+ const found = (await readMemoryItems(client, key)).items.find((i) => i.id === id);
29
+ if (found) return found;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function receipt(action: MemorySetReceiptT["action"]): MemorySetReceiptT {
35
+ return { action, changed: false, memory: null, memory_enabled: null, verified: false, warnings: [] };
36
+ }
37
+
38
+ async function setMemorySwitch(client: WhoopClient, action: "enable_memory" | "disable_memory", confirm: boolean) {
39
+ const active = action === "enable_memory";
40
+ const before = memoryEnabled(await client.get(AI_SETTINGS, {}, { fresh: true }));
41
+ const body = { setting_key: "WHOOP_COACH_MEMORY", active };
42
+ if (!confirm) {
43
+ return preview("PUT", AI_SETTINGS, { ...body, currently: before, note: active ? null : MEMORY_OFF_WARNING });
44
+ }
45
+ const out = receipt(action);
46
+ if (before !== active) {
47
+ await client.put(AI_SETTINGS, body);
48
+ out.changed = true;
49
+ } else {
50
+ out.warnings.push(`Memory was already ${active ? "on" : "off"}; nothing was sent.`);
51
+ }
52
+ // Read back with a GET, not the PUT's echo (S14).
53
+ out.memory_enabled = memoryEnabled(await client.get(AI_SETTINGS, {}, { fresh: true }));
54
+ out.verified = out.memory_enabled === active;
55
+ if (!out.verified) out.warnings.push(`WHOOP still reports memory ${out.memory_enabled ? "on" : "off"}.`);
56
+ if (!active) out.warnings.push(MEMORY_OFF_WARNING);
57
+ return out;
58
+ }
59
+
60
+ async function setMemoryItem(client: WhoopClient, action: "activate" | "deactivate" | "delete", id: string, confirm: boolean) {
61
+ const card = await findMemory(client, id);
62
+ if (!card) throw new Error(`No memory ${id} in your context hub. List them with whoop_memory.`);
63
+ const path = `${CONTEXT_HUB}/context-detail/${id}`;
64
+ const target = action === "activate" ? "ACTIVE" : "INACTIVE";
65
+ if (!confirm) {
66
+ if (action === "delete") return preview("DELETE", path, { memory: card, note: "Permanent: WHOOP can't restore it." });
67
+ return preview("PUT", `${path}/status`, { target_state: target, memory: card });
68
+ }
69
+ const out = receipt(action);
70
+ if (action === "delete") {
71
+ await client.delete(path);
72
+ out.changed = true;
73
+ } else if (card.status !== target) {
74
+ await client.put(`${path}/status`, { target_state: target });
75
+ out.changed = true;
76
+ } else {
77
+ out.warnings.push(`It was already ${target}; nothing was sent.`);
78
+ }
79
+ // Read back from the cards (never the detail: that's a read receipt). A 204 proves nothing (S14).
80
+ const after = await findMemory(client, id);
81
+ out.memory = action === "delete" ? card : after;
82
+ out.verified = action === "delete" ? after === null : after?.status === target;
83
+ if (!out.verified) {
84
+ out.warnings.push(action === "delete" ? "The memory is still listed after the delete." : `It reads back as ${after?.status ?? "missing"}.`);
85
+ }
86
+ return out;
87
+ }
88
+
89
+ export function registerMemorySet(server: McpServer, client: WhoopClient): void {
90
+ defineTool(
91
+ server,
92
+ {
93
+ name: TOOL,
94
+ description:
95
+ "Change what WHOOP Coach remembers: activate or deactivate a memory (inactive ones stop shaping coaching), delete one " +
96
+ "permanently, or enable_memory / disable_memory for the whole account. With memory off nothing is stored, whatever the coach " +
97
+ "says. Previews unless confirm:true.",
98
+ input: memorySetInput,
99
+ annotations: WRITE_DESTRUCTIVE,
100
+ },
101
+ async ({ action, memory_id, confirm }) => {
102
+ if (action === "enable_memory" || action === "disable_memory") {
103
+ if (memory_id) throw new Error(`${action} applies to the whole account; drop memory_id.`);
104
+ return respond(TOOL, MemorySetOut, await setMemorySwitch(client, action, confirm));
105
+ }
106
+ if (!memory_id) throw new Error(`${action} needs memory_id (from whoop_memory).`);
107
+ return respond(TOOL, MemorySetOut, await setMemoryItem(client, action, memory_id, confirm));
108
+ },
109
+ );
110
+ }