@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,102 @@
1
+ // Tool definitions are sent to the model on every turn, so their size is paid
2
+ // for constantly. zod's JSON Schema output and the SDK's listing carry noise a
3
+ // model never needs:
4
+ // - a validation regex on every ISO date / date-time / uuid field (the
5
+ // `format` keyword already says what it is);
6
+ // - JavaScript's safe-integer bounds on every integer;
7
+ // - a `$schema` URL on every tool;
8
+ // - `default: false` / `default: []` (what an omitted flag or list means anyway);
9
+ // - `minLength: 1` / `minItems: 1` / `exclusiveMinimum: 0` (nobody sends "",
10
+ // [] or a weight of zero on purpose);
11
+ // - `propertyNames: {type: "string"}` (JSON keys are always strings);
12
+ // - literal unions spelled as `anyOf: [{const}, …]` (an `enum` says the same);
13
+ // - `execution: {taskSupport: "forbidden"}` on every tool (the MCP default
14
+ // when the field is absent).
15
+ // This strips those from the tools/list response. Validation is unchanged: the
16
+ // server still parses every call with the full zod schema, so anything dropped
17
+ // here is still enforced, with an error that says what was wrong.
18
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
+ import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
20
+
21
+ /** Formats that fully describe the string; zod's regex for them adds nothing a model uses. */
22
+ const SELF_DESCRIBING_FORMATS = new Set(["date", "date-time", "time", "duration", "uuid"]);
23
+
24
+ const isObject = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v);
25
+ const isEmptyArray = (v: unknown): boolean => Array.isArray(v) && v.length === 0;
26
+
27
+ /** `anyOf: [{type, const}, …]` with one shared type → `{type, enum}`; otherwise null. */
28
+ function literalUnion(anyOf: unknown): { type: unknown; enum: unknown[] } | null {
29
+ if (!Array.isArray(anyOf) || anyOf.length < 2) return null;
30
+ const members = anyOf.filter(isObject);
31
+ if (members.length !== anyOf.length) return null;
32
+ const type = members[0]!.type;
33
+ if (typeof type !== "string") return null;
34
+ for (const m of members) {
35
+ const keys = Object.keys(m);
36
+ if (keys.length !== 2 || !("const" in m) || m.type !== type) return null;
37
+ }
38
+ return { type, enum: members.map((m) => m.const) };
39
+ }
40
+
41
+ export function slimSchema<T>(schema: T): T {
42
+ if (Array.isArray(schema)) return schema.map((item) => slimSchema(item)) as unknown as T;
43
+ if (!isObject(schema)) return schema;
44
+ const node = schema;
45
+ const out: Record<string, unknown> = {};
46
+ const formatted = typeof node.format === "string" && SELF_DESCRIBING_FORMATS.has(node.format);
47
+ for (const [key, value] of Object.entries(node)) {
48
+ if (key === "$schema") continue;
49
+ if (key === "pattern" && formatted) continue;
50
+ if (key === "minimum" && value === Number.MIN_SAFE_INTEGER) continue;
51
+ if (key === "maximum" && value === Number.MAX_SAFE_INTEGER) continue;
52
+ if (key === "default" && (value === false || isEmptyArray(value))) continue;
53
+ if ((key === "minLength" || key === "minItems") && value === 1) continue;
54
+ if (key === "exclusiveMinimum" && value === 0) continue;
55
+ if (key === "propertyNames" && isObject(value) && Object.keys(value).length === 1 && value.type === "string") continue;
56
+ if (key === "anyOf") {
57
+ const literals = literalUnion(value);
58
+ if (literals) {
59
+ Object.assign(out, literals);
60
+ continue;
61
+ }
62
+ }
63
+ // Under `properties` the keys are field names, not schema keywords: slim each
64
+ // field's schema, but never drop a field because of what it's called.
65
+ out[key] = key === "properties" && isObject(value)
66
+ ? Object.fromEntries(Object.entries(value).map(([name, field]) => [name, slimSchema(field)]))
67
+ : slimSchema(value);
68
+ }
69
+ return out as T;
70
+ }
71
+
72
+ type ListedTool = { inputSchema: unknown; execution?: unknown } & Record<string, unknown>;
73
+
74
+ /** One listed tool, slimmed: its input schema, and `execution` when it only states the default. */
75
+ export function slimTool<T extends ListedTool>(tool: T): T {
76
+ const { execution, ...rest } = tool;
77
+ const defaultExecution = isObject(execution) && Object.keys(execution).length === 1 && execution.taskSupport === "forbidden";
78
+ return {
79
+ ...rest,
80
+ ...(execution === undefined || defaultExecution ? {} : { execution }),
81
+ inputSchema: slimSchema(tool.inputSchema),
82
+ } as unknown as T;
83
+ }
84
+
85
+ type ListHandler = (request: unknown, extra: unknown) => Promise<{ tools: ListedTool[] } & Record<string, unknown>>;
86
+
87
+ /**
88
+ * Wrap the SDK's tools/list handler so every listed tool is slimmed. Call it
89
+ * after all tools are registered. If the SDK's internals move (the handler map
90
+ * is not public API), this does nothing and the full schemas are served; the
91
+ * registry test fails in that case, so it can't regress unnoticed.
92
+ */
93
+ export function installSlimToolList(server: McpServer): boolean {
94
+ const handlers = (server.server as unknown as { _requestHandlers?: Map<string, ListHandler> })._requestHandlers;
95
+ const original = handlers?.get("tools/list");
96
+ if (!original) return false;
97
+ server.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
98
+ const result = await original(request, extra);
99
+ return { ...result, tools: result.tools.map(slimTool) } as never;
100
+ });
101
+ return true;
102
+ }
@@ -1,33 +1,71 @@
1
+ // whoop_activity_delete: replaces v1 whoop_activity_delete.
2
+ //
3
+ // Routes by the pre-read's kind (SPEC.md §4.3, §4.4): DELETE cd/v1/cardio-details
4
+ // for CARDIO/RECOVERY, DELETE cd/v2/sleep-details/{id} for sleeps and naps.
5
+ // WHOOP answers 204 even for ids that don't exist, so success is a fresh read
6
+ // that 404s, never the status code.
1
7
  import { z } from "zod";
2
8
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
9
  import type { WhoopClient } from "../../whoop/client.js";
4
- import { ActivityDeleteOut } from "../../schemas/workouts.js";
10
+ import { defineTool, respond } from "../define.js";
11
+ import { WRITE_DESTRUCTIVE, idempotent } from "../annotations.js";
5
12
  import { preview } from "../../whoop/write_safety.js";
6
- import { jsonOut } from "../../whoop/json_out.js";
13
+ import { WhoopApiError } from "../../whoop/errors.js";
14
+ import { ActivityDeleteOut } from "../../schemas/activities.js";
15
+ import { CARDIO_DETAILS_V1, isGone, readActivity, sleepDetailsPath } from "../../lib/activity_records.js";
16
+ import { DELETE_MAIN_SLEEP_WARNING, errorResult, writeRejection } from "../../lib/activity_results.js";
17
+ import { typeForInternalName } from "../../lib/activity_types.js";
7
18
 
8
19
  export function registerActivityDelete(server: McpServer, client: WhoopClient): void {
9
- server.tool(
10
- "whoop_activity_delete",
11
- "WRITE / DESTRUCTIVE: delete a workout/activity. Preview unless confirm:true.",
12
- {
13
- activity_id: z.string(),
20
+ defineTool(server, {
21
+ name: "whoop_activity_delete",
22
+ description:
23
+ "Delete one activity, nap or sleep by activity_id (from whoop_workouts or whoop_sleep) and confirm it's gone. Deleting a main " +
24
+ "sleep doesn't restore the day's cycles. Previews unless confirm:true.",
25
+ input: {
26
+ activity_id: z.string().min(1),
14
27
  confirm: z.boolean().default(false),
15
28
  },
16
- async ({ activity_id, confirm }) => {
17
- const path = "/core-details-bff/v1/cardio-details";
18
- if (!confirm) {
19
- return {
20
- content: [
21
- {
22
- type: "text",
23
- text: jsonOut(preview("DELETE", `${path}?activityId=${activity_id}`, { activity_id })),
24
- },
25
- ],
26
- };
29
+ annotations: idempotent(WRITE_DESTRUCTIVE),
30
+ }, async ({ activity_id, confirm }) => {
31
+ const rec = await readActivity(client, activity_id);
32
+ if (!rec) return errorResult({ error: `No activity ${activity_id}: WHOOP says it doesn't exist (already deleted?).` });
33
+ const scoreType = rec.score_type ?? typeForInternalName(rec.type)?.score_type ?? "CARDIO";
34
+ const isSleep = scoreType === "SLEEP";
35
+ const method = "DELETE";
36
+ const path = isSleep ? sleepDetailsPath(activity_id) : CARDIO_DETAILS_V1;
37
+ const query = isSleep ? {} : { activityId: activity_id };
38
+ const warnings: string[] = [];
39
+ if (rec.type === "sleep") warnings.push(DELETE_MAIN_SLEEP_WARNING);
40
+
41
+ if (!confirm) {
42
+ return respond("whoop_activity_delete", ActivityDeleteOut, preview(method, isSleep ? path : `${path}?activityId=${activity_id}`, {
43
+ activity: { type: rec.type, score_type: scoreType, start: rec.start, end: rec.end },
44
+ warnings,
45
+ }));
46
+ }
47
+
48
+ try {
49
+ await client.delete(path, query);
50
+ } catch (e) {
51
+ // A 404 means it's already gone; the read below confirms either way.
52
+ if (!(e instanceof WhoopApiError && e.status === 404)) {
53
+ const rejected = writeRejection(e, path);
54
+ if (rejected) return rejected;
55
+ throw e;
27
56
  }
28
- await client.delete(path, { activityId: activity_id });
29
- const out = ActivityDeleteOut.parse({ deleted: true as const, activity_id });
30
- return { content: [{ type: "text", text: jsonOut(out) }] };
31
- },
32
- );
57
+ }
58
+ const gone = await isGone(client, activity_id, scoreType);
59
+ if (gone === null) warnings.push("Couldn't confirm the deletion (the read-back failed); check whoop_workouts.");
60
+ else if (!gone) warnings.push("WHOOP still returns the activity after the delete.");
61
+ return respond("whoop_activity_delete", ActivityDeleteOut, {
62
+ deleted: gone === true,
63
+ type: rec.type,
64
+ score_type: scoreType,
65
+ start: rec.start,
66
+ end: rec.end,
67
+ verified: gone === true,
68
+ warnings,
69
+ });
70
+ });
33
71
  }
@@ -0,0 +1,378 @@
1
+ // whoop_activity_edit: replaces v1 whoop_sleep_edit and adds cardio/recovery edits.
2
+ //
3
+ // Routes (SPEC.md §4.3, §4.4, D5, §7 S15–S18):
4
+ // - CARDIO/RECOVERY (window and/or type, CARDIO↔RECOVERY allowed):
5
+ // PUT cd/v2/cardio-details?activityId= {start_time, end_time, activity_internal_name[, garment_id]}
6
+ // - nap → main sleep: the same cardio-details PUT with activity_internal_name "sleep".
7
+ // - sleep/nap window: PUT cd/v2/sleep-details/{id} {start_time, end_time[, resolve_overlaps]}.
8
+ // resolve_overlaps DELETES the overlapped activities (it doesn't trim them), so
9
+ // totem only sends it when the caller lists exactly the ids that will go.
10
+ // - sleep → nap is refused by WHOOP silently; totem refuses it up front.
11
+ // - merge (the app's Edit Activities drawer; route from @Acetone1's Android list):
12
+ // PATCH cd/v1/activities/merge?startTime=&endTime= [ids]
13
+ // Live (2026-11-22): WHOOP keeps the EARLIEST activity (its id and type) over
14
+ // the query bounds and deletes the others, whatever order the ids come in.
15
+ // The app's undo, DELETE …/merge?id=, answers 405, so there is no undo. It
16
+ // answers 422 while any activity inside the bounds is still pending scoring.
17
+ // After every write: fresh read-back of the type and window. A main sleep that
18
+ // comes back as a nap is repaired once via the cardio-details PUT.
19
+ import { z } from "zod";
20
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
21
+ import type { WhoopClient } from "../../whoop/client.js";
22
+ import { defineTool, respond, type ToolResult } from "../define.js";
23
+ import { WRITE_DESTRUCTIVE } from "../annotations.js";
24
+ import { preview } from "../../whoop/write_safety.js";
25
+ import { WhoopApiError, WhoopConflictError } from "../../whoop/errors.js";
26
+ import { get, str } from "../../whoop/bff.js";
27
+ import { ActivityEditOut } from "../../schemas/activities.js";
28
+ import { assertNotFuture, canonicalUtc } from "../../lib/dates.js";
29
+ import { describeType, resolveActivityTypeLive, resolveGarment, typeForInternalName } from "../../lib/activity_types.js";
30
+ import {
31
+ CARDIO_DETAILS_V2, isGone, readActivity, readActivityAs, recordFromActivity, sameInstant, sleepDetailsPath,
32
+ toUtc, type ActivityRecord,
33
+ } from "../../lib/activity_records.js";
34
+ import { overlappingTiles, type ActivityTile } from "../../lib/activity_list.js";
35
+ import { DELETE_MAIN_SLEEP_WARNING, NAP_TO_SLEEP_WARNING, errorResult, writeRejection } from "../../lib/activity_results.js";
36
+ import type { ScoreType } from "../../data/sports.js";
37
+ import { instantInput, toInstantOpt } from "../../lib/instant.js";
38
+
39
+ const LAST_NIGHT_PATH = "/home-service/v1/deep-dive/sleep/last-night";
40
+ export const MERGE_PATH = "/core-details-bff/v1/activities/merge";
41
+ const MIN_DURATION_MS = 60_000;
42
+
43
+ function describeTile(t: ActivityTile): string {
44
+ return `${t.activity_id} ${t.internal_name ?? t.title ?? "activity"} ${t.start ?? "?"} – ${t.end ?? "?"}`;
45
+ }
46
+
47
+ const sameSet = (a: string[], b: string[]): boolean => {
48
+ const sa = new Set(a);
49
+ const sb = new Set(b);
50
+ return sa.size === sb.size && [...sa].every((x) => sb.has(x));
51
+ };
52
+
53
+ export function registerActivityEdit(server: McpServer, client: WhoopClient): void {
54
+ defineTool(server, {
55
+ name: "whoop_activity_edit",
56
+ description:
57
+ "Change an activity's start/end or type (CARDIO↔RECOVERY, nap→main sleep), or a sleep/nap window, by activity_id or sleep_date " +
58
+ "(that day's main sleep). Omitted bounds keep their value. An overlapping sleep window needs delete_overlapping = exactly the " +
59
+ "ids the preview lists (WHOOP DELETES them). merge keeps the earliest over the joint window and DELETES the rest. Previews " +
60
+ "unless confirm:true.",
61
+ input: {
62
+ activity_id: z.string().min(1).optional(),
63
+ sleep_date: z.iso.date().optional(),
64
+ start: instantInput().optional(),
65
+ end: instantInput().optional(),
66
+ type: z.string().optional().describe("internal_name, display name or sport_id"),
67
+ garment_id: z.number().int().optional().describe("Activities only"),
68
+ delete_overlapping: z.array(z.string().min(1)).optional()
69
+ .describe("Overlapping ids from the preview; WHOOP deletes them"),
70
+ merge: z.array(z.string().min(1)).optional().describe("Ids to combine with activity_id"),
71
+ confirm: z.boolean().default(false),
72
+ },
73
+ annotations: WRITE_DESTRUCTIVE,
74
+ }, async ({ activity_id, sleep_date, start: startIn, end: endIn, type, garment_id, delete_overlapping, merge, confirm }) => {
75
+ const start = toInstantOpt(startIn, "start");
76
+ const end = toInstantOpt(endIn, "end");
77
+ if ((activity_id === undefined) === (sleep_date === undefined)) {
78
+ return errorResult({ error: "Pass exactly one of activity_id or sleep_date." });
79
+ }
80
+ if (merge?.length) {
81
+ if (!activity_id) return errorResult({ error: "merge needs activity_id (sleeps and naps can't be merged)." });
82
+ if (start || end || type !== undefined || garment_id !== undefined || delete_overlapping?.length) {
83
+ return errorResult({ error: "merge can't be combined with other changes; merge first, then edit the result." });
84
+ }
85
+ return mergeActivities(client, activity_id, merge, confirm);
86
+ }
87
+ if (!start && !end && type === undefined && garment_id === undefined && !delete_overlapping?.length) {
88
+ return errorResult({ error: "Nothing to change: pass start, end, type, garment_id or merge." });
89
+ }
90
+ try {
91
+ if (start) assertNotFuture(start, "start");
92
+ if (end) assertNotFuture(end, "end");
93
+ } catch (e) {
94
+ return errorResult({ error: (e as Error).message });
95
+ }
96
+ if (garment_id !== undefined) {
97
+ const g = resolveGarment(garment_id);
98
+ if (!g.ok) return errorResult({ error: g.error });
99
+ }
100
+ let newType: { internal_name: string; score_type: ScoreType; name: string } | null = null;
101
+ if (type !== undefined) {
102
+ const r = await resolveActivityTypeLive(client, type);
103
+ if (!r.ok) return errorResult({ error: r.error, suggestions: r.suggestions });
104
+ newType = r.type;
105
+ }
106
+
107
+ // ── Pre-read (fresh) ──
108
+ let id = activity_id;
109
+ if (sleep_date) {
110
+ const lastNight = await client.get(LAST_NIGHT_PATH, { date: sleep_date }, { fresh: true });
111
+ id = str(get(lastNight, "header_section", "destination", "parameters", "activity_id")) ?? undefined;
112
+ if (!id) return errorResult({ error: `No main sleep found for ${sleep_date}.`, hint: "Naps aren't listed by day here: pass their activity_id (whoop_sleep or whoop_workouts with types [SLEEP])." });
113
+ }
114
+ const activityId = id!;
115
+ const before = await readActivity(client, activityId);
116
+ if (!before) return errorResult({ error: `No activity ${activityId}: WHOOP says it doesn't exist.` });
117
+ const beforeScore: ScoreType | null = before.score_type ?? typeForInternalName(before.type)?.score_type ?? null;
118
+ if (!before.type) return errorResult({ error: `Couldn't read ${activityId}'s current type from WHOOP; not editing blind.` });
119
+ if ((!start && !before.start) || (!end && !before.end)) {
120
+ return errorResult({ error: "Couldn't read the current window; pass both start and end." });
121
+ }
122
+ const newStart = canonicalUtc(start ?? before.start!);
123
+ const newEnd = canonicalUtc(end ?? before.end!);
124
+ const windowSame = sameInstant(newStart, before.start) && sameInstant(newEnd, before.end);
125
+ if (Date.parse(newEnd) <= Date.parse(newStart)) return errorResult({ error: `end (${newEnd}) must be after start (${newStart}).` });
126
+ if (!windowSame && Date.parse(newEnd) - Date.parse(newStart) < MIN_DURATION_MS) {
127
+ return errorResult({ error: "The new window must be at least one minute long." });
128
+ }
129
+
130
+ // ── Route ──
131
+ const targetType = newType?.internal_name ?? before.type;
132
+ const targetScore: ScoreType = newType?.score_type ?? beforeScore ?? "CARDIO";
133
+ const typeChanged = targetType !== before.type;
134
+ const warnings: string[] = [];
135
+ let route: "cardio-details" | "sleep-details";
136
+ if (beforeScore === "SLEEP") {
137
+ if (typeChanged) {
138
+ if (before.type === "nap" && targetType === "sleep") {
139
+ route = "cardio-details";
140
+ warnings.push(NAP_TO_SLEEP_WARNING);
141
+ } else if (before.type === "sleep" && targetType === "nap") {
142
+ return errorResult({ error: "WHOOP doesn't turn a main sleep into a nap: it answers 200 and keeps it a sleep. Delete it and log a nap instead." });
143
+ } else {
144
+ return errorResult({ error: `Changing a ${before.type} into ${targetType} isn't supported. Delete it (whoop_activity_delete) and log the new one (whoop_activity_log).` });
145
+ }
146
+ if (delete_overlapping?.length) return errorResult({ error: "delete_overlapping only applies to sleep/nap window edits without a type change." });
147
+ } else {
148
+ route = "sleep-details";
149
+ if (garment_id !== undefined) warnings.push("garment_id is ignored for sleep and nap windows.");
150
+ }
151
+ } else {
152
+ if (targetScore === "SLEEP") {
153
+ return errorResult({ error: `Turning a ${before.type} into a ${targetType} isn't supported. Delete it and log the ${targetType} with whoop_activity_log.` });
154
+ }
155
+ if (delete_overlapping?.length) {
156
+ return errorResult({ error: "delete_overlapping only applies to sleep/nap window edits; WHOOP refuses overlapping workout edits (409) and deletes nothing." });
157
+ }
158
+ route = "cardio-details";
159
+ }
160
+
161
+ const beforeOut = { type: before.type, score_type: beforeScore, start: before.start, end: before.end };
162
+ const garmentChange = garment_id !== undefined && route === "cardio-details";
163
+ if (windowSame && !typeChanged && !garmentChange && !delete_overlapping?.length) {
164
+ return respond("whoop_activity_edit", ActivityEditOut, {
165
+ edited: false, no_change: true, activity_id: activityId, before: beforeOut,
166
+ after: { ...beforeOut, version: before.version }, deleted_overlapping: [], verified: true, warnings,
167
+ });
168
+ }
169
+
170
+ // ── Overlaps (sleep windows: resolve_overlaps deletes, so it is gated on an exact id list) ──
171
+ let overlapping: ActivityTile[] = [];
172
+ let resolve = false;
173
+ if (route === "sleep-details") {
174
+ const found = await overlappingTiles(client, newStart, newEnd, activityId);
175
+ overlapping = found.tiles;
176
+ if (delete_overlapping?.length) {
177
+ if (!found.complete) return errorResult({ error: "Couldn't read every day around the new window, so the overlap list can't be confirmed. Nothing was changed; try again." });
178
+ if (!overlapping.length) return errorResult({ error: "Nothing overlaps the new window now; drop delete_overlapping." });
179
+ if (!sameSet(delete_overlapping, overlapping.map((t) => t.activity_id))) {
180
+ return errorResult({
181
+ error: "delete_overlapping must list exactly the activities WHOOP would delete. Nothing was changed.",
182
+ would_delete: overlapping.map(describeTile),
183
+ });
184
+ }
185
+ resolve = true;
186
+ } else if (overlapping.length) {
187
+ warnings.push(`The new window overlaps ${overlapping.length} activit${overlapping.length === 1 ? "y" : "ies"} (listed). WHOOP will refuse (409) unless delete_overlapping lists exactly these ids, and then it DELETES them; it never trims.`);
188
+ }
189
+ if (overlapping.some((t) => t.internal_name === "sleep")) warnings.push(DELETE_MAIN_SLEEP_WARNING);
190
+ }
191
+
192
+ const path = route === "sleep-details" ? sleepDetailsPath(activityId) : CARDIO_DETAILS_V2;
193
+ const query: Record<string, string> = route === "sleep-details" ? {} : { activityId };
194
+ const body: Record<string, unknown> = { start_time: newStart, end_time: newEnd };
195
+ if (route === "cardio-details") {
196
+ body.activity_internal_name = targetType;
197
+ if (garment_id !== undefined) body.garment_id = garment_id;
198
+ } else if (resolve) {
199
+ body.resolve_overlaps = true;
200
+ }
201
+
202
+ if (!confirm) {
203
+ return respond("whoop_activity_edit", ActivityEditOut, preview("PUT", route === "sleep-details" ? path : `${path}?activityId=${activityId}`, {
204
+ body,
205
+ before: beforeOut,
206
+ after: { type: targetType, score_type: targetScore, start: newStart, end: newEnd },
207
+ new_type: newType ? describeType(newType) : null,
208
+ overlapping: overlapping.map(describeTile),
209
+ will_delete: resolve ? overlapping.map(describeTile) : [],
210
+ warnings,
211
+ }));
212
+ }
213
+
214
+ // ── Send ──
215
+ let response: unknown;
216
+ try {
217
+ response = await client.put(path, body, query);
218
+ } catch (e) {
219
+ let fallback: string[] = overlapping.map(describeTile);
220
+ if (e instanceof WhoopConflictError && !fallback.length && route === "cardio-details") {
221
+ fallback = await overlappingTiles(client, newStart, newEnd, activityId).then((r) => r.tiles.map(describeTile)).catch(() => []);
222
+ }
223
+ const rejected = writeRejection(e, path, fallback);
224
+ if (rejected) return rejected;
225
+ throw e;
226
+ }
227
+ let after: ActivityRecord | null = recordFromActivity(response);
228
+
229
+ // ── Read back (fresh), repairing a demoted main sleep once ──
230
+ const readBack = async (): Promise<ActivityRecord | null> => {
231
+ try {
232
+ return await readActivityAs(client, activityId, targetScore);
233
+ } catch (e) {
234
+ warnings.push(`Read-back failed: ${(e as Error).message}`);
235
+ return null;
236
+ }
237
+ };
238
+ let back = await readBack();
239
+ let repaired = false;
240
+ if (route === "sleep-details" && targetType === "sleep" && (after?.type === "nap" || back?.type === "nap")) {
241
+ try {
242
+ const fixed = await client.put(CARDIO_DETAILS_V2, { activity_internal_name: "sleep", start_time: newStart, end_time: newEnd }, { activityId });
243
+ after = recordFromActivity(fixed) ?? after;
244
+ repaired = true;
245
+ warnings.push("WHOOP demoted the main sleep to a nap after the edit; totem converted it back to a sleep.");
246
+ } catch (e) {
247
+ warnings.push(`WHOOP demoted the main sleep to a nap and the repair failed (${(e as Error).message}). Retry with type "sleep".`);
248
+ }
249
+ back = await readBack();
250
+ }
251
+
252
+ const deleted: string[] = [];
253
+ if (resolve) {
254
+ for (const t of overlapping) {
255
+ const kind: ScoreType = t.score_type === "SLEEP" || t.score_type === "RECOVERY" ? t.score_type : "CARDIO";
256
+ if (await isGone(client, t.activity_id, kind)) deleted.push(t.activity_id);
257
+ else warnings.push(`${t.activity_id} still exists after resolve_overlaps.`);
258
+ }
259
+ }
260
+
261
+ const afterType = back?.type ?? after?.type ?? null;
262
+ const afterStart = back?.start ?? after?.start ?? null;
263
+ const afterEnd = back?.end ?? after?.end ?? null;
264
+ if (back && back.type !== targetType) warnings.push(`WHOOP shows the type as ${back.type ?? "unknown"}, not ${targetType}.`);
265
+ if (back && !(sameInstant(afterStart, newStart) && sameInstant(afterEnd, newEnd))) warnings.push(`WHOOP shows the window as ${afterStart} – ${afterEnd}.`);
266
+ const verified = Boolean(back) && afterType === targetType && sameInstant(afterStart, newStart) && sameInstant(afterEnd, newEnd) &&
267
+ deleted.length === (resolve ? overlapping.length : 0);
268
+ return respond("whoop_activity_edit", ActivityEditOut, {
269
+ edited: true,
270
+ activity_id: activityId,
271
+ before: beforeOut,
272
+ after: {
273
+ type: afterType,
274
+ score_type: back?.score_type ?? after?.score_type ?? targetScore,
275
+ start: toUtc(afterStart),
276
+ end: toUtc(afterEnd),
277
+ version: after?.version ?? null,
278
+ },
279
+ ...(repaired ? { repaired: true as const } : {}),
280
+ deleted_overlapping: deleted,
281
+ verified,
282
+ warnings,
283
+ });
284
+ });
285
+ }
286
+
287
+ /** Combine activities into one (see the header for what WHOOP does). */
288
+ async function mergeActivities(client: WhoopClient, activityId: string, others: string[], confirm: boolean): Promise<ToolResult> {
289
+ const ids = [...new Set([activityId, ...others])];
290
+ if (ids.length < 2) return errorResult({ error: "merge needs at least one activity id other than activity_id." });
291
+
292
+ const recs = await Promise.all(ids.map((i) => readActivity(client, i)));
293
+ const missing = ids.filter((_, i) => !recs[i]);
294
+ if (missing.length) return errorResult({ error: `No activity ${missing.join(", ")}: WHOOP says it doesn't exist.` });
295
+ const rows = ids.map((id, i) => {
296
+ const rec = recs[i]!;
297
+ return { id, rec, score: rec.score_type ?? typeForInternalName(rec.type)?.score_type ?? null };
298
+ });
299
+ for (const r of rows) {
300
+ if (r.score === "SLEEP") return errorResult({ error: `${r.id} is a ${r.rec.type}; WHOOP only merges workouts and recovery activities.` });
301
+ if (!r.rec.start || !r.rec.end) return errorResult({ error: `Couldn't read ${r.id}'s window from WHOOP; not merging blind.` });
302
+ }
303
+ // WHOOP keeps the earliest; sending it first keeps the body readable.
304
+ rows.sort((a, b) => Date.parse(a.rec.start!) - Date.parse(b.rec.start!));
305
+ const keep = rows[0]!;
306
+ const gone = rows.slice(1);
307
+ const start = canonicalUtc(keep.rec.start!);
308
+ const end = canonicalUtc(rows.reduce((m, r) => (Date.parse(r.rec.end!) > Date.parse(m) ? r.rec.end! : m), keep.rec.end!));
309
+
310
+ // Anything else inside the joint window would block the merge or be swept into it.
311
+ const warnings: string[] = [`WHOOP keeps ${keep.id} (${keep.rec.type}, the earliest) over the joint window and DELETES the others. There is no undo.`];
312
+ const found = await overlappingTiles(client, start, end);
313
+ const strangers = found.tiles.filter((t) => !ids.includes(t.activity_id));
314
+ if (strangers.length) {
315
+ return errorResult({ error: "Other activities fall inside the merged window. Add them to merge, or merge a smaller set. Nothing was changed.", inside: strangers.map(describeTile) });
316
+ }
317
+ if (!found.complete) warnings.push("Couldn't read every day around the window, so other activities inside it may not be listed.");
318
+
319
+ const query = { startTime: start, endTime: end };
320
+ const body = rows.map((r) => r.id);
321
+ const window = (r: (typeof rows)[number]) => ({ type: r.rec.type, score_type: r.score, start: r.rec.start, end: r.rec.end });
322
+ if (!confirm) {
323
+ return respond("whoop_activity_edit", ActivityEditOut, preview("PATCH", `${MERGE_PATH}?startTime=${start}&endTime=${end}`, {
324
+ body,
325
+ keep: { activity_id: keep.id, ...window(keep) },
326
+ after: { type: keep.rec.type, score_type: keep.score, start, end },
327
+ will_delete: gone.map((r) => `${r.id} ${r.rec.type ?? "activity"} ${r.rec.start} – ${r.rec.end}`),
328
+ warnings,
329
+ }));
330
+ }
331
+
332
+ let response: unknown;
333
+ try {
334
+ response = await client.patch(MERGE_PATH, body, query);
335
+ } catch (e) {
336
+ if (e instanceof WhoopApiError && e.status === 422 && /pending/i.test(e.body)) {
337
+ return errorResult({ error: "WHOOP is still scoring one of these activities. Nothing was merged; try again in a minute.", status: 422, endpoint: MERGE_PATH });
338
+ }
339
+ const rejected = writeRejection(e, MERGE_PATH);
340
+ if (rejected) return rejected;
341
+ throw e;
342
+ }
343
+ const after = recordFromActivity(response);
344
+ const survivor = after?.id ?? keep.id;
345
+ if (survivor !== keep.id) warnings.push(`WHOOP kept ${survivor}, not the earliest (${keep.id}).`);
346
+ let back: ActivityRecord | null = null;
347
+ try {
348
+ back = await readActivityAs(client, survivor, keep.score ?? "CARDIO");
349
+ } catch (e) {
350
+ warnings.push(`Read-back failed: ${(e as Error).message}`);
351
+ }
352
+ const merged: string[] = [];
353
+ for (const r of gone) {
354
+ if (r.id === survivor) continue;
355
+ if (await isGone(client, r.id, r.score === "RECOVERY" ? "RECOVERY" : "CARDIO")) merged.push(r.id);
356
+ else warnings.push(`${r.id} still exists after the merge.`);
357
+ }
358
+ const afterStart = back?.start ?? after?.start ?? null;
359
+ const afterEnd = back?.end ?? after?.end ?? null;
360
+ if (back && !(sameInstant(afterStart, start) && sameInstant(afterEnd, end))) warnings.push(`WHOOP shows the window as ${afterStart} – ${afterEnd}.`);
361
+ const verified = Boolean(back) && sameInstant(afterStart, start) && sameInstant(afterEnd, end) && merged.length === gone.length;
362
+ return respond("whoop_activity_edit", ActivityEditOut, {
363
+ edited: true,
364
+ activity_id: survivor,
365
+ before: window(keep),
366
+ after: {
367
+ type: back?.type ?? after?.type ?? keep.rec.type,
368
+ score_type: back?.score_type ?? after?.score_type ?? keep.score,
369
+ start: toUtc(afterStart),
370
+ end: toUtc(afterEnd),
371
+ version: after?.version ?? null,
372
+ },
373
+ merged,
374
+ deleted_overlapping: [],
375
+ verified,
376
+ warnings,
377
+ });
378
+ }