@thebriangao/totem 1.4.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (763) hide show
  1. package/.dev.vars.example +5 -0
  2. package/.dockerignore +5 -0
  3. package/.env.example +29 -20
  4. package/CHANGELOG.md +99 -1
  5. package/CONTRIBUTING.md +48 -116
  6. package/Dockerfile +46 -12
  7. package/README.md +172 -498
  8. package/SECURITY.md +36 -59
  9. package/TOOLS.md +448 -311
  10. package/WHOOP.md +497 -2659
  11. package/assets/brand/SOURCES.md +38 -0
  12. package/assets/brand/totem.png +0 -0
  13. package/assets/brand/totem.svg +13 -0
  14. package/assets/fonts/Manrope-OFL.txt +93 -0
  15. package/assets/fonts/manrope-latin.woff2 +0 -0
  16. package/dist/build_info.js +5 -0
  17. package/dist/build_info.js.map +1 -0
  18. package/dist/cli/app.js +675 -0
  19. package/dist/cli/app.js.map +1 -0
  20. package/dist/cli/auth.js +297 -0
  21. package/dist/cli/auth.js.map +1 -0
  22. package/dist/cli/auth_flow.js +268 -0
  23. package/dist/cli/auth_flow.js.map +1 -0
  24. package/dist/cli/browser_login.js +368 -0
  25. package/dist/cli/browser_login.js.map +1 -0
  26. package/dist/cli/clients.js +403 -0
  27. package/dist/cli/clients.js.map +1 -0
  28. package/dist/cli/deploy_record.js +96 -0
  29. package/dist/cli/deploy_record.js.map +1 -0
  30. package/dist/cli/index.js +39 -575
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/links.js +28 -0
  33. package/dist/cli/links.js.map +1 -0
  34. package/dist/cli/logo.js +63 -0
  35. package/dist/cli/logo.js.map +1 -0
  36. package/dist/cli/setup.js +1157 -1017
  37. package/dist/cli/setup.js.map +1 -1
  38. package/dist/cli/spawn.js +80 -0
  39. package/dist/cli/spawn.js.map +1 -0
  40. package/dist/cli/sys.js +219 -0
  41. package/dist/cli/sys.js.map +1 -0
  42. package/dist/cli/ui.js +712 -463
  43. package/dist/cli/ui.js.map +1 -1
  44. package/dist/cli/update.js +425 -282
  45. package/dist/cli/update.js.map +1 -1
  46. package/dist/cloudflare/token_store.js +48 -0
  47. package/dist/cloudflare/token_store.js.map +1 -0
  48. package/dist/cloudflare/worker.js +155 -0
  49. package/dist/cloudflare/worker.js.map +1 -0
  50. package/dist/data/behaviors.js +2733 -617
  51. package/dist/data/behaviors.js.map +1 -1
  52. package/dist/data/endpoint_catalog.js +2681 -0
  53. package/dist/data/endpoint_catalog.js.map +1 -0
  54. package/dist/data/exercises.js +373 -4859
  55. package/dist/data/exercises.js.map +1 -1
  56. package/dist/data/garments.js +19 -0
  57. package/dist/data/garments.js.map +1 -0
  58. package/dist/data/sports.js +219 -208
  59. package/dist/data/sports.js.map +1 -1
  60. package/dist/lib/activity_list.js +123 -0
  61. package/dist/lib/activity_list.js.map +1 -0
  62. package/dist/lib/activity_records.js +195 -0
  63. package/dist/lib/activity_records.js.map +1 -0
  64. package/dist/lib/activity_results.js +44 -0
  65. package/dist/lib/activity_results.js.map +1 -0
  66. package/dist/lib/activity_types.js +164 -0
  67. package/dist/lib/activity_types.js.map +1 -0
  68. package/dist/lib/brand.js +63 -0
  69. package/dist/lib/brand.js.map +1 -0
  70. package/dist/lib/clock.js +24 -0
  71. package/dist/lib/clock.js.map +1 -0
  72. package/dist/lib/coach_session.js +345 -0
  73. package/dist/lib/coach_session.js.map +1 -0
  74. package/dist/lib/concurrency.js.map +1 -1
  75. package/dist/lib/dates.js +19 -0
  76. package/dist/lib/dates.js.map +1 -1
  77. package/dist/lib/env_file.js +195 -0
  78. package/dist/lib/env_file.js.map +1 -0
  79. package/dist/lib/health_plans_write.js +44 -0
  80. package/dist/lib/health_plans_write.js.map +1 -0
  81. package/dist/lib/heart_rate.js +34 -0
  82. package/dist/lib/heart_rate.js.map +1 -0
  83. package/dist/lib/highlight.js +81 -0
  84. package/dist/lib/highlight.js.map +1 -0
  85. package/dist/lib/install_links.js +47 -0
  86. package/dist/lib/install_links.js.map +1 -0
  87. package/dist/lib/instant.js +50 -0
  88. package/dist/lib/instant.js.map +1 -0
  89. package/dist/lib/journal_behaviors.js +382 -0
  90. package/dist/lib/journal_behaviors.js.map +1 -0
  91. package/dist/lib/lift_catalog.js +218 -0
  92. package/dist/lib/lift_catalog.js.map +1 -0
  93. package/dist/lib/lift_history.js +66 -0
  94. package/dist/lib/lift_history.js.map +1 -0
  95. package/dist/lib/lift_sets.js +146 -0
  96. package/dist/lib/lift_sets.js.map +1 -0
  97. package/dist/lib/lift_tool.js +20 -0
  98. package/dist/lib/lift_tool.js.map +1 -0
  99. package/dist/lib/profile_settings.js +101 -0
  100. package/dist/lib/profile_settings.js.map +1 -0
  101. package/dist/lib/screen_content.js +44 -0
  102. package/dist/lib/screen_content.js.map +1 -0
  103. package/dist/lib/timezone.js +48 -6
  104. package/dist/lib/timezone.js.map +1 -1
  105. package/dist/lib/walk.js +6 -1
  106. package/dist/lib/walk.js.map +1 -1
  107. package/dist/lib/weight_readings.js +61 -0
  108. package/dist/lib/weight_readings.js.map +1 -0
  109. package/dist/projections/activities.js +193 -0
  110. package/dist/projections/activities.js.map +1 -0
  111. package/dist/projections/alarm_schedule.js +102 -0
  112. package/dist/projections/alarm_schedule.js.map +1 -0
  113. package/dist/projections/coach.js +203 -0
  114. package/dist/projections/coach.js.map +1 -0
  115. package/dist/projections/community.js +165 -0
  116. package/dist/projections/community.js.map +1 -0
  117. package/dist/projections/health_features.js +167 -0
  118. package/dist/projections/health_features.js.map +1 -0
  119. package/dist/projections/hormonal_insights.js +239 -0
  120. package/dist/projections/hormonal_insights.js.map +1 -0
  121. package/dist/projections/journal_v2.js +157 -0
  122. package/dist/projections/journal_v2.js.map +1 -0
  123. package/dist/projections/lift_cards.js +115 -0
  124. package/dist/projections/lift_cards.js.map +1 -0
  125. package/dist/projections/lift_exercise_v2.js +131 -0
  126. package/dist/projections/lift_exercise_v2.js.map +1 -0
  127. package/dist/projections/lift_library_v2.js +67 -0
  128. package/dist/projections/lift_library_v2.js.map +1 -0
  129. package/dist/projections/lift_sessions.js +211 -0
  130. package/dist/projections/lift_sessions.js.map +1 -0
  131. package/dist/projections/memory.js +95 -0
  132. package/dist/projections/memory.js.map +1 -0
  133. package/dist/projections/milestones.js +119 -0
  134. package/dist/projections/milestones.js.map +1 -0
  135. package/dist/projections/profile_v2.js +150 -0
  136. package/dist/projections/profile_v2.js.map +1 -0
  137. package/dist/projections/settings_v2.js +153 -0
  138. package/dist/projections/settings_v2.js.map +1 -0
  139. package/dist/projections/sleep.js +4 -21
  140. package/dist/projections/sleep.js.map +1 -1
  141. package/dist/projections/v2/calendar.js +43 -0
  142. package/dist/projections/v2/calendar.js.map +1 -0
  143. package/dist/projections/v2/core_common.js +86 -0
  144. package/dist/projections/v2/core_common.js.map +1 -0
  145. package/dist/projections/v2/core_home.js +136 -0
  146. package/dist/projections/v2/core_home.js.map +1 -0
  147. package/dist/projections/v2/core_sleep_need.js +23 -0
  148. package/dist/projections/v2/core_sleep_need.js.map +1 -0
  149. package/dist/projections/v2/day.js +92 -0
  150. package/dist/projections/v2/day.js.map +1 -0
  151. package/dist/projections/v2/heart_rate.js +54 -0
  152. package/dist/projections/v2/heart_rate.js.map +1 -0
  153. package/dist/projections/v2/history.js +140 -0
  154. package/dist/projections/v2/history.js.map +1 -0
  155. package/dist/projections/v2/now.js +39 -0
  156. package/dist/projections/v2/now.js.map +1 -0
  157. package/dist/projections/v2/recovery.js +77 -0
  158. package/dist/projections/v2/recovery.js.map +1 -0
  159. package/dist/projections/v2/sleep.js +218 -0
  160. package/dist/projections/v2/sleep.js.map +1 -0
  161. package/dist/projections/v2/strain.js +39 -0
  162. package/dist/projections/v2/strain.js.map +1 -0
  163. package/dist/projections/v2/stress.js +92 -0
  164. package/dist/projections/v2/stress.js.map +1 -0
  165. package/dist/projections/v2/trend.js +205 -0
  166. package/dist/projections/v2/trend.js.map +1 -0
  167. package/dist/projections/weekly_plan.js +66 -0
  168. package/dist/projections/weekly_plan.js.map +1 -0
  169. package/dist/projections/weight_readings.js +57 -0
  170. package/dist/projections/weight_readings.js.map +1 -0
  171. package/dist/projections/workout.js +37 -15
  172. package/dist/projections/workout.js.map +1 -1
  173. package/dist/schemas/activities.js +123 -0
  174. package/dist/schemas/activities.js.map +1 -0
  175. package/dist/schemas/alarm_schedule.js +62 -0
  176. package/dist/schemas/alarm_schedule.js.map +1 -0
  177. package/dist/schemas/coach.js +76 -8
  178. package/dist/schemas/coach.js.map +1 -1
  179. package/dist/schemas/community.js +70 -0
  180. package/dist/schemas/community.js.map +1 -0
  181. package/dist/schemas/health.js +36 -0
  182. package/dist/schemas/health.js.map +1 -0
  183. package/dist/schemas/hormonal_insights.js +90 -0
  184. package/dist/schemas/hormonal_insights.js.map +1 -0
  185. package/dist/schemas/journal.js +4 -0
  186. package/dist/schemas/journal.js.map +1 -1
  187. package/dist/schemas/journal_v2.js +106 -0
  188. package/dist/schemas/journal_v2.js.map +1 -0
  189. package/dist/schemas/memory.js +42 -0
  190. package/dist/schemas/memory.js.map +1 -0
  191. package/dist/schemas/milestones.js +39 -0
  192. package/dist/schemas/milestones.js.map +1 -0
  193. package/dist/schemas/profile_v2.js +60 -0
  194. package/dist/schemas/profile_v2.js.map +1 -0
  195. package/dist/schemas/settings_v2.js +56 -0
  196. package/dist/schemas/settings_v2.js.map +1 -0
  197. package/dist/schemas/sleep.js +8 -1
  198. package/dist/schemas/sleep.js.map +1 -1
  199. package/dist/schemas/strength.js +10 -1
  200. package/dist/schemas/strength.js.map +1 -1
  201. package/dist/schemas/strength_v2.js +190 -0
  202. package/dist/schemas/strength_v2.js.map +1 -0
  203. package/dist/schemas/v2/calendar.js +8 -0
  204. package/dist/schemas/v2/calendar.js.map +1 -0
  205. package/dist/schemas/v2/core_common.js +42 -0
  206. package/dist/schemas/v2/core_common.js.map +1 -0
  207. package/dist/schemas/v2/day.js +73 -0
  208. package/dist/schemas/v2/day.js.map +1 -0
  209. package/dist/schemas/v2/now.js +25 -0
  210. package/dist/schemas/v2/now.js.map +1 -0
  211. package/dist/schemas/v2/recovery.js +35 -0
  212. package/dist/schemas/v2/recovery.js.map +1 -0
  213. package/dist/schemas/v2/sleep.js +44 -0
  214. package/dist/schemas/v2/sleep.js.map +1 -0
  215. package/dist/schemas/v2/strain.js +16 -0
  216. package/dist/schemas/v2/strain.js.map +1 -0
  217. package/dist/schemas/v2/stress.js +20 -0
  218. package/dist/schemas/v2/stress.js.map +1 -0
  219. package/dist/schemas/v2/trend.js +42 -0
  220. package/dist/schemas/v2/trend.js.map +1 -0
  221. package/dist/schemas/weekly_plan.js +31 -0
  222. package/dist/schemas/weekly_plan.js.map +1 -0
  223. package/dist/schemas/weight.js +28 -0
  224. package/dist/schemas/weight.js.map +1 -0
  225. package/dist/scripts/build_behaviors.js +114 -0
  226. package/dist/scripts/build_behaviors.js.map +1 -0
  227. package/dist/scripts/cognito_bootstrap.js +9 -277
  228. package/dist/scripts/cognito_bootstrap.js.map +1 -1
  229. package/dist/scripts/gen_activity_catalogs.js +104 -0
  230. package/dist/scripts/gen_activity_catalogs.js.map +1 -0
  231. package/dist/server-admin.js +156 -0
  232. package/dist/server-admin.js.map +1 -0
  233. package/dist/server-http.js +270 -48
  234. package/dist/server-http.js.map +1 -1
  235. package/dist/server.js +136 -23
  236. package/dist/server.js.map +1 -1
  237. package/dist/tools/annotations.js +15 -0
  238. package/dist/tools/annotations.js.map +1 -0
  239. package/dist/tools/define.js +31 -0
  240. package/dist/tools/define.js.map +1 -0
  241. package/dist/tools/register.js +59 -94
  242. package/dist/tools/register.js.map +1 -1
  243. package/dist/tools/resources.js +70 -0
  244. package/dist/tools/resources.js.map +1 -0
  245. package/dist/tools/slim_schema.js +90 -0
  246. package/dist/tools/slim_schema.js.map +1 -0
  247. package/dist/tools/v2/activity_delete.js +63 -17
  248. package/dist/tools/v2/activity_delete.js.map +1 -1
  249. package/dist/tools/v2/activity_edit.js +396 -0
  250. package/dist/tools/v2/activity_edit.js.map +1 -0
  251. package/dist/tools/v2/activity_log.js +152 -0
  252. package/dist/tools/v2/activity_log.js.map +1 -0
  253. package/dist/tools/v2/calendar.js +19 -21
  254. package/dist/tools/v2/calendar.js.map +1 -1
  255. package/dist/tools/v2/coach_ask.js +74 -110
  256. package/dist/tools/v2/coach_ask.js.map +1 -1
  257. package/dist/tools/v2/coach_history.js +120 -0
  258. package/dist/tools/v2/coach_history.js.map +1 -0
  259. package/dist/tools/v2/community.js +124 -0
  260. package/dist/tools/v2/community.js.map +1 -0
  261. package/dist/tools/v2/cycle.js +63 -15
  262. package/dist/tools/v2/cycle.js.map +1 -1
  263. package/dist/tools/v2/cycle_log.js +289 -32
  264. package/dist/tools/v2/cycle_log.js.map +1 -1
  265. package/dist/tools/v2/day.js +126 -24
  266. package/dist/tools/v2/day.js.map +1 -1
  267. package/dist/tools/v2/health.js +116 -0
  268. package/dist/tools/v2/health.js.map +1 -0
  269. package/dist/tools/v2/hr_zones_set.js +134 -34
  270. package/dist/tools/v2/hr_zones_set.js.map +1 -1
  271. package/dist/tools/v2/journal.js +75 -17
  272. package/dist/tools/v2/journal.js.map +1 -1
  273. package/dist/tools/v2/journal_log.js +306 -65
  274. package/dist/tools/v2/journal_log.js.map +1 -1
  275. package/dist/tools/v2/lift_exercise.js +125 -22
  276. package/dist/tools/v2/lift_exercise.js.map +1 -1
  277. package/dist/tools/v2/lift_exercise_set.js +291 -0
  278. package/dist/tools/v2/lift_exercise_set.js.map +1 -0
  279. package/dist/tools/v2/lift_library.js +51 -12
  280. package/dist/tools/v2/lift_library.js.map +1 -1
  281. package/dist/tools/v2/lift_log.js +309 -72
  282. package/dist/tools/v2/lift_log.js.map +1 -1
  283. package/dist/tools/v2/lift_sessions.js +248 -0
  284. package/dist/tools/v2/lift_sessions.js.map +1 -0
  285. package/dist/tools/v2/lift_template.js +232 -0
  286. package/dist/tools/v2/lift_template.js.map +1 -0
  287. package/dist/tools/v2/memory.js +45 -0
  288. package/dist/tools/v2/memory.js.map +1 -0
  289. package/dist/tools/v2/memory_set.js +107 -0
  290. package/dist/tools/v2/memory_set.js.map +1 -0
  291. package/dist/tools/v2/milestones.js +50 -0
  292. package/dist/tools/v2/milestones.js.map +1 -0
  293. package/dist/tools/v2/now.js +49 -0
  294. package/dist/tools/v2/now.js.map +1 -0
  295. package/dist/tools/v2/preferences.js +51 -0
  296. package/dist/tools/v2/preferences.js.map +1 -0
  297. package/dist/tools/v2/preferences_set.js +388 -0
  298. package/dist/tools/v2/preferences_set.js.map +1 -0
  299. package/dist/tools/v2/profile.js +54 -22
  300. package/dist/tools/v2/profile.js.map +1 -1
  301. package/dist/tools/v2/profile_update.js +167 -55
  302. package/dist/tools/v2/profile_update.js.map +1 -1
  303. package/dist/tools/v2/raw.js +91 -34
  304. package/dist/tools/v2/raw.js.map +1 -1
  305. package/dist/tools/v2/recovery.js +37 -23
  306. package/dist/tools/v2/recovery.js.map +1 -1
  307. package/dist/tools/v2/sleep.js +52 -16
  308. package/dist/tools/v2/sleep.js.map +1 -1
  309. package/dist/tools/v2/smart_alarm.js +54 -20
  310. package/dist/tools/v2/smart_alarm.js.map +1 -1
  311. package/dist/tools/v2/smart_alarm_set.js +264 -86
  312. package/dist/tools/v2/smart_alarm_set.js.map +1 -1
  313. package/dist/tools/v2/strain.js +15 -15
  314. package/dist/tools/v2/strain.js.map +1 -1
  315. package/dist/tools/v2/stress.js +17 -15
  316. package/dist/tools/v2/stress.js.map +1 -1
  317. package/dist/tools/v2/trend.js +56 -20
  318. package/dist/tools/v2/trend.js.map +1 -1
  319. package/dist/tools/v2/weekly_plan.js +30 -0
  320. package/dist/tools/v2/weekly_plan.js.map +1 -0
  321. package/dist/tools/v2/weekly_plan_set.js +134 -0
  322. package/dist/tools/v2/weekly_plan_set.js.map +1 -0
  323. package/dist/tools/v2/weight.js +56 -0
  324. package/dist/tools/v2/weight.js.map +1 -0
  325. package/dist/tools/v2/weight_log.js +188 -0
  326. package/dist/tools/v2/weight_log.js.map +1 -0
  327. package/dist/tools/v2/workouts.js +159 -25
  328. package/dist/tools/v2/workouts.js.map +1 -1
  329. package/dist/version.js +6 -0
  330. package/dist/version.js.map +1 -0
  331. package/dist/whoop/bff.js +94 -0
  332. package/dist/whoop/bff.js.map +1 -0
  333. package/dist/whoop/client.js +392 -18
  334. package/dist/whoop/client.js.map +1 -1
  335. package/dist/whoop/cognito.js +106 -79
  336. package/dist/whoop/cognito.js.map +1 -1
  337. package/dist/whoop/connect_page.js +165 -0
  338. package/dist/whoop/connect_page.js.map +1 -0
  339. package/dist/whoop/consent_font.js +287 -0
  340. package/dist/whoop/consent_font.js.map +1 -0
  341. package/dist/whoop/consent_logos.js +22 -0
  342. package/dist/whoop/consent_logos.js.map +1 -0
  343. package/dist/whoop/consent_page.js +291 -0
  344. package/dist/whoop/consent_page.js.map +1 -0
  345. package/dist/whoop/constants.js +5 -1
  346. package/dist/whoop/constants.js.map +1 -1
  347. package/dist/whoop/device.js +4 -4
  348. package/dist/whoop/device.js.map +1 -1
  349. package/dist/whoop/errors.js +85 -4
  350. package/dist/whoop/errors.js.map +1 -1
  351. package/dist/whoop/init_timezone.js +57 -17
  352. package/dist/whoop/init_timezone.js.map +1 -1
  353. package/dist/whoop/installation.js +15 -10
  354. package/dist/whoop/installation.js.map +1 -1
  355. package/dist/whoop/json_out.js +52 -6
  356. package/dist/whoop/json_out.js.map +1 -1
  357. package/dist/whoop/oauth_provider.js +81 -78
  358. package/dist/whoop/oauth_provider.js.map +1 -1
  359. package/dist/whoop/token_lock.js +331 -0
  360. package/dist/whoop/token_lock.js.map +1 -0
  361. package/dist/whoop/token_manager.js +536 -42
  362. package/dist/whoop/token_manager.js.map +1 -1
  363. package/dist/whoop/token_store.js +303 -36
  364. package/dist/whoop/token_store.js.map +1 -1
  365. package/dist/whoop/units.js +28 -0
  366. package/dist/whoop/units.js.map +1 -0
  367. package/package.json +29 -13
  368. package/scripts/build-mcpb.mjs +72 -0
  369. package/scripts/embed-consent-font.mjs +34 -0
  370. package/scripts/readme-media.ts +195 -0
  371. package/scripts/tools-md.ts +89 -0
  372. package/scripts/whoop-md.ts +119 -0
  373. package/src/build_info.ts +4 -0
  374. package/src/cli/app.ts +696 -0
  375. package/src/cli/auth.ts +350 -0
  376. package/src/cli/auth_flow.ts +356 -0
  377. package/src/cli/browser_login.ts +402 -0
  378. package/src/cli/clients.ts +467 -0
  379. package/src/cli/deploy_record.ts +100 -0
  380. package/src/cli/index.ts +41 -583
  381. package/src/cli/links.ts +43 -0
  382. package/src/cli/logo.ts +64 -0
  383. package/src/cli/setup.ts +1147 -979
  384. package/src/cli/spawn.ts +88 -0
  385. package/src/cli/sys.ts +267 -0
  386. package/src/cli/ui.ts +778 -436
  387. package/src/cli/update.ts +436 -274
  388. package/src/cloudflare/runtime.d.ts +27 -0
  389. package/src/cloudflare/token_store.ts +57 -0
  390. package/src/cloudflare/worker.ts +174 -0
  391. package/src/data/behaviors.ts +2760 -622
  392. package/src/data/endpoint_catalog.ts +2695 -0
  393. package/src/data/exercises.ts +379 -4861
  394. package/src/data/garments.ts +28 -0
  395. package/src/data/sports.ts +239 -211
  396. package/src/lib/activity_list.ts +150 -0
  397. package/src/lib/activity_records.ts +213 -0
  398. package/src/lib/activity_results.ts +51 -0
  399. package/src/lib/activity_types.ts +176 -0
  400. package/src/lib/brand.ts +71 -0
  401. package/src/lib/clock.ts +16 -0
  402. package/src/lib/coach_session.ts +434 -0
  403. package/src/lib/dates.ts +18 -0
  404. package/src/lib/env_file.ts +191 -0
  405. package/src/lib/health_plans_write.ts +53 -0
  406. package/src/lib/heart_rate.ts +42 -0
  407. package/src/lib/highlight.ts +71 -0
  408. package/src/lib/install_links.ts +61 -0
  409. package/src/lib/instant.ts +54 -0
  410. package/src/lib/journal_behaviors.ts +453 -0
  411. package/src/lib/lift_catalog.ts +258 -0
  412. package/src/lib/lift_history.ts +75 -0
  413. package/src/lib/lift_sets.ts +164 -0
  414. package/src/lib/lift_tool.ts +25 -0
  415. package/src/lib/profile_settings.ts +102 -0
  416. package/src/lib/screen_content.ts +40 -0
  417. package/src/lib/timezone.ts +44 -8
  418. package/src/lib/walk.ts +4 -1
  419. package/src/lib/weight_readings.ts +82 -0
  420. package/src/projections/activities.ts +199 -0
  421. package/src/projections/alarm_schedule.ts +98 -0
  422. package/src/projections/coach.ts +218 -0
  423. package/src/projections/community.ts +187 -0
  424. package/src/projections/health_features.ts +191 -0
  425. package/src/projections/hormonal_insights.ts +277 -0
  426. package/src/projections/journal_v2.ts +173 -0
  427. package/src/projections/lift_cards.ts +131 -0
  428. package/src/projections/lift_exercise_v2.ts +147 -0
  429. package/src/projections/lift_library_v2.ts +77 -0
  430. package/src/projections/lift_sessions.ts +250 -0
  431. package/src/projections/memory.ts +100 -0
  432. package/src/projections/milestones.ts +133 -0
  433. package/src/projections/profile_v2.ts +166 -0
  434. package/src/projections/settings_v2.ts +179 -0
  435. package/src/projections/sleep.ts +7 -21
  436. package/src/projections/v2/calendar.ts +48 -0
  437. package/src/projections/v2/core_common.ts +95 -0
  438. package/src/projections/v2/core_home.ts +177 -0
  439. package/src/projections/v2/core_sleep_need.ts +37 -0
  440. package/src/projections/v2/day.ts +162 -0
  441. package/src/projections/v2/heart_rate.ts +73 -0
  442. package/src/projections/v2/history.ts +153 -0
  443. package/src/projections/v2/now.ts +59 -0
  444. package/src/projections/v2/recovery.ts +120 -0
  445. package/src/projections/v2/sleep.ts +281 -0
  446. package/src/projections/v2/strain.ts +63 -0
  447. package/src/projections/v2/stress.ts +111 -0
  448. package/src/projections/v2/trend.ts +242 -0
  449. package/src/projections/weekly_plan.ts +79 -0
  450. package/src/projections/weight_readings.ts +57 -0
  451. package/src/projections/workout.ts +36 -17
  452. package/src/schemas/activities.ts +136 -0
  453. package/src/schemas/alarm_schedule.ts +70 -0
  454. package/src/schemas/coach.ts +98 -8
  455. package/src/schemas/community.ts +77 -0
  456. package/src/schemas/health.ts +36 -0
  457. package/src/schemas/hormonal_insights.ts +108 -0
  458. package/src/schemas/journal.ts +4 -0
  459. package/src/schemas/journal_v2.ts +112 -0
  460. package/src/schemas/memory.ts +48 -0
  461. package/src/schemas/milestones.ts +48 -0
  462. package/src/schemas/profile_v2.ts +63 -0
  463. package/src/schemas/settings_v2.ts +63 -0
  464. package/src/schemas/sleep.ts +9 -1
  465. package/src/schemas/strength.ts +10 -1
  466. package/src/schemas/strength_v2.ts +210 -0
  467. package/src/schemas/v2/calendar.ts +8 -0
  468. package/src/schemas/v2/core_common.ts +50 -0
  469. package/src/schemas/v2/day.ts +79 -0
  470. package/src/schemas/v2/now.ts +25 -0
  471. package/src/schemas/v2/recovery.ts +38 -0
  472. package/src/schemas/v2/sleep.ts +46 -0
  473. package/src/schemas/v2/strain.ts +16 -0
  474. package/src/schemas/v2/stress.ts +20 -0
  475. package/src/schemas/v2/trend.ts +45 -0
  476. package/src/schemas/weekly_plan.ts +36 -0
  477. package/src/schemas/weight.ts +53 -0
  478. package/src/scripts/build_behaviors.ts +116 -0
  479. package/src/scripts/cognito_bootstrap.ts +10 -249
  480. package/src/scripts/gen_activity_catalogs.ts +121 -0
  481. package/src/server-admin.ts +171 -0
  482. package/src/server-http.ts +290 -53
  483. package/src/server.ts +130 -26
  484. package/src/tools/annotations.ts +25 -0
  485. package/src/tools/define.ts +53 -0
  486. package/src/tools/register.ts +64 -94
  487. package/src/tools/resources.ts +92 -0
  488. package/src/tools/slim_schema.ts +102 -0
  489. package/src/tools/v2/activity_delete.ts +61 -23
  490. package/src/tools/v2/activity_edit.ts +378 -0
  491. package/src/tools/v2/activity_log.ts +154 -0
  492. package/src/tools/v2/calendar.ts +22 -21
  493. package/src/tools/v2/coach_ask.ts +83 -119
  494. package/src/tools/v2/coach_history.ts +140 -0
  495. package/src/tools/v2/community.ts +137 -0
  496. package/src/tools/v2/cycle.ts +78 -20
  497. package/src/tools/v2/cycle_log.ts +291 -40
  498. package/src/tools/v2/day.ts +126 -25
  499. package/src/tools/v2/health.ts +114 -0
  500. package/src/tools/v2/hr_zones_set.ts +132 -45
  501. package/src/tools/v2/journal.ts +78 -23
  502. package/src/tools/v2/journal_log.ts +321 -69
  503. package/src/tools/v2/lift_exercise.ts +135 -27
  504. package/src/tools/v2/lift_exercise_set.ts +272 -0
  505. package/src/tools/v2/lift_library.ts +57 -21
  506. package/src/tools/v2/lift_log.ts +325 -83
  507. package/src/tools/v2/lift_sessions.ts +255 -0
  508. package/src/tools/v2/lift_template.ts +229 -0
  509. package/src/tools/v2/memory.ts +54 -0
  510. package/src/tools/v2/memory_set.ts +110 -0
  511. package/src/tools/v2/milestones.ts +59 -0
  512. package/src/tools/v2/now.ts +61 -0
  513. package/src/tools/v2/preferences.ts +61 -0
  514. package/src/tools/v2/preferences_set.ts +403 -0
  515. package/src/tools/v2/profile.ts +56 -26
  516. package/src/tools/v2/profile_update.ts +151 -60
  517. package/src/tools/v2/raw.ts +89 -36
  518. package/src/tools/v2/recovery.ts +44 -25
  519. package/src/tools/v2/sleep.ts +57 -18
  520. package/src/tools/v2/smart_alarm.ts +62 -24
  521. package/src/tools/v2/smart_alarm_set.ts +240 -90
  522. package/src/tools/v2/strain.ts +19 -16
  523. package/src/tools/v2/stress.ts +22 -17
  524. package/src/tools/v2/trend.ts +58 -20
  525. package/src/tools/v2/weekly_plan.ts +38 -0
  526. package/src/tools/v2/weekly_plan_set.ts +132 -0
  527. package/src/tools/v2/weight.ts +61 -0
  528. package/src/tools/v2/weight_log.ts +193 -0
  529. package/src/tools/v2/workouts.ts +156 -26
  530. package/src/version.ts +5 -0
  531. package/src/whoop/bff.ts +84 -0
  532. package/src/whoop/client.ts +448 -18
  533. package/src/whoop/cognito.ts +110 -99
  534. package/src/whoop/connect_page.ts +183 -0
  535. package/src/whoop/consent_font.ts +289 -0
  536. package/src/whoop/consent_logos.ts +24 -0
  537. package/src/whoop/consent_page.ts +326 -0
  538. package/src/whoop/constants.ts +5 -1
  539. package/src/whoop/device.ts +4 -4
  540. package/src/whoop/errors.ts +89 -4
  541. package/src/whoop/init_timezone.ts +57 -16
  542. package/src/whoop/installation.ts +16 -7
  543. package/src/whoop/json_out.ts +51 -6
  544. package/src/whoop/oauth_provider.ts +84 -91
  545. package/src/whoop/token_lock.ts +345 -0
  546. package/src/whoop/token_manager.ts +580 -53
  547. package/src/whoop/token_store.ts +341 -32
  548. package/src/whoop/units.ts +35 -0
  549. package/wrangler.jsonc +17 -0
  550. package/assets/banner.svg +0 -38
  551. package/dist/data/endpoints.js +0 -320
  552. package/dist/data/endpoints.js.map +0 -1
  553. package/dist/lib/format.js +0 -22
  554. package/dist/lib/format.js.map +0 -1
  555. package/dist/lib/stats.js +0 -32
  556. package/dist/lib/stats.js.map +0 -1
  557. package/dist/projections/calendar.js +0 -33
  558. package/dist/projections/calendar.js.map +0 -1
  559. package/dist/projections/communities.js +0 -105
  560. package/dist/projections/communities.js.map +0 -1
  561. package/dist/projections/cycle.js +0 -81
  562. package/dist/projections/cycle.js.map +0 -1
  563. package/dist/projections/hr_zones.js +0 -35
  564. package/dist/projections/hr_zones.js.map +0 -1
  565. package/dist/projections/journal.js +0 -56
  566. package/dist/projections/journal.js.map +0 -1
  567. package/dist/projections/leaderboard.js +0 -37
  568. package/dist/projections/leaderboard.js.map +0 -1
  569. package/dist/projections/lift_exercise.js +0 -22
  570. package/dist/projections/lift_exercise.js.map +0 -1
  571. package/dist/projections/lift_history.js +0 -133
  572. package/dist/projections/lift_history.js.map +0 -1
  573. package/dist/projections/lift_library.js +0 -71
  574. package/dist/projections/lift_library.js.map +0 -1
  575. package/dist/projections/lift_progression.js +0 -138
  576. package/dist/projections/lift_progression.js.map +0 -1
  577. package/dist/projections/lift_prs.js +0 -20
  578. package/dist/projections/lift_prs.js.map +0 -1
  579. package/dist/projections/live_hr.js +0 -19
  580. package/dist/projections/live_hr.js.map +0 -1
  581. package/dist/projections/live_state.js +0 -23
  582. package/dist/projections/live_state.js.map +0 -1
  583. package/dist/projections/live_stress.js +0 -11
  584. package/dist/projections/live_stress.js.map +0 -1
  585. package/dist/projections/performance_assessment.js +0 -15
  586. package/dist/projections/performance_assessment.js.map +0 -1
  587. package/dist/projections/profile.js +0 -59
  588. package/dist/projections/profile.js.map +0 -1
  589. package/dist/projections/recovery.js +0 -131
  590. package/dist/projections/recovery.js.map +0 -1
  591. package/dist/projections/sleep_need.js +0 -32
  592. package/dist/projections/sleep_need.js.map +0 -1
  593. package/dist/projections/smart_alarm.js +0 -45
  594. package/dist/projections/smart_alarm.js.map +0 -1
  595. package/dist/projections/strain.js +0 -128
  596. package/dist/projections/strain.js.map +0 -1
  597. package/dist/projections/stress.js +0 -86
  598. package/dist/projections/stress.js.map +0 -1
  599. package/dist/projections/today.js +0 -129
  600. package/dist/projections/today.js.map +0 -1
  601. package/dist/projections/trend.js +0 -149
  602. package/dist/projections/trend.js.map +0 -1
  603. package/dist/projections/workouts.js +0 -37
  604. package/dist/projections/workouts.js.map +0 -1
  605. package/dist/schemas/calendar.js +0 -12
  606. package/dist/schemas/calendar.js.map +0 -1
  607. package/dist/schemas/communities.js +0 -51
  608. package/dist/schemas/communities.js.map +0 -1
  609. package/dist/schemas/compare.js +0 -15
  610. package/dist/schemas/compare.js.map +0 -1
  611. package/dist/schemas/leaderboard.js +0 -25
  612. package/dist/schemas/leaderboard.js.map +0 -1
  613. package/dist/schemas/live.js +0 -26
  614. package/dist/schemas/live.js.map +0 -1
  615. package/dist/schemas/performance.js +0 -12
  616. package/dist/schemas/performance.js.map +0 -1
  617. package/dist/schemas/profile.js +0 -39
  618. package/dist/schemas/profile.js.map +0 -1
  619. package/dist/schemas/recovery.js +0 -27
  620. package/dist/schemas/recovery.js.map +0 -1
  621. package/dist/schemas/settings.js +0 -26
  622. package/dist/schemas/settings.js.map +0 -1
  623. package/dist/schemas/sleep_need.js +0 -15
  624. package/dist/schemas/sleep_need.js.map +0 -1
  625. package/dist/schemas/smart_alarm.js +0 -36
  626. package/dist/schemas/smart_alarm.js.map +0 -1
  627. package/dist/schemas/strain.js +0 -24
  628. package/dist/schemas/strain.js.map +0 -1
  629. package/dist/schemas/stress.js +0 -16
  630. package/dist/schemas/stress.js.map +0 -1
  631. package/dist/schemas/today.js +0 -38
  632. package/dist/schemas/today.js.map +0 -1
  633. package/dist/schemas/trend.js +0 -50
  634. package/dist/schemas/trend.js.map +0 -1
  635. package/dist/schemas/womens_health.js +0 -23
  636. package/dist/schemas/womens_health.js.map +0 -1
  637. package/dist/tools/v2/activity_create.js +0 -64
  638. package/dist/tools/v2/activity_create.js.map +0 -1
  639. package/dist/tools/v2/behavior_impact.js +0 -36
  640. package/dist/tools/v2/behavior_impact.js.map +0 -1
  641. package/dist/tools/v2/communities.js +0 -60
  642. package/dist/tools/v2/communities.js.map +0 -1
  643. package/dist/tools/v2/compare.js +0 -67
  644. package/dist/tools/v2/compare.js.map +0 -1
  645. package/dist/tools/v2/endpoints.js +0 -28
  646. package/dist/tools/v2/endpoints.js.map +0 -1
  647. package/dist/tools/v2/hidden_metric.js +0 -28
  648. package/dist/tools/v2/hidden_metric.js.map +0 -1
  649. package/dist/tools/v2/hr_zones.js +0 -24
  650. package/dist/tools/v2/hr_zones.js.map +0 -1
  651. package/dist/tools/v2/journal_autopop.js +0 -19
  652. package/dist/tools/v2/journal_autopop.js.map +0 -1
  653. package/dist/tools/v2/journal_catalog.js +0 -44
  654. package/dist/tools/v2/journal_catalog.js.map +0 -1
  655. package/dist/tools/v2/leaderboard.js +0 -79
  656. package/dist/tools/v2/leaderboard.js.map +0 -1
  657. package/dist/tools/v2/lift_catalog.js +0 -47
  658. package/dist/tools/v2/lift_catalog.js.map +0 -1
  659. package/dist/tools/v2/lift_custom_exercise.js +0 -108
  660. package/dist/tools/v2/lift_custom_exercise.js.map +0 -1
  661. package/dist/tools/v2/lift_history.js +0 -39
  662. package/dist/tools/v2/lift_history.js.map +0 -1
  663. package/dist/tools/v2/lift_progression.js +0 -30
  664. package/dist/tools/v2/lift_progression.js.map +0 -1
  665. package/dist/tools/v2/lift_prs.js +0 -21
  666. package/dist/tools/v2/lift_prs.js.map +0 -1
  667. package/dist/tools/v2/lift_template_save.js +0 -83
  668. package/dist/tools/v2/lift_template_save.js.map +0 -1
  669. package/dist/tools/v2/live_hr.js +0 -21
  670. package/dist/tools/v2/live_hr.js.map +0 -1
  671. package/dist/tools/v2/live_state.js +0 -21
  672. package/dist/tools/v2/live_state.js.map +0 -1
  673. package/dist/tools/v2/live_stress.js +0 -22
  674. package/dist/tools/v2/live_stress.js.map +0 -1
  675. package/dist/tools/v2/performance_assessment.js +0 -38
  676. package/dist/tools/v2/performance_assessment.js.map +0 -1
  677. package/dist/tools/v2/sleep_need.js +0 -21
  678. package/dist/tools/v2/sleep_need.js.map +0 -1
  679. package/dist/tools/v2/sports_catalog.js +0 -26
  680. package/dist/tools/v2/sports_catalog.js.map +0 -1
  681. package/dist/tools/v2/symptom_log.js +0 -72
  682. package/dist/tools/v2/symptom_log.js.map +0 -1
  683. package/dist/tools/v2/today.js +0 -30
  684. package/dist/tools/v2/today.js.map +0 -1
  685. package/dist/tools/v2/workout.js +0 -23
  686. package/dist/tools/v2/workout.js.map +0 -1
  687. package/dist/whoop/build_lift_body.js +0 -67
  688. package/dist/whoop/build_lift_body.js.map +0 -1
  689. package/dist/whoop/session_state.js +0 -34
  690. package/dist/whoop/session_state.js.map +0 -1
  691. package/dist/whoop/types.js +0 -82
  692. package/dist/whoop/types.js.map +0 -1
  693. package/src/data/endpoints.ts +0 -319
  694. package/src/lib/format.ts +0 -27
  695. package/src/lib/stats.ts +0 -35
  696. package/src/projections/calendar.ts +0 -46
  697. package/src/projections/communities.ts +0 -135
  698. package/src/projections/cycle.ts +0 -85
  699. package/src/projections/hr_zones.ts +0 -43
  700. package/src/projections/journal.ts +0 -55
  701. package/src/projections/leaderboard.ts +0 -49
  702. package/src/projections/lift_exercise.ts +0 -29
  703. package/src/projections/lift_history.ts +0 -140
  704. package/src/projections/lift_library.ts +0 -70
  705. package/src/projections/lift_progression.ts +0 -138
  706. package/src/projections/lift_prs.ts +0 -23
  707. package/src/projections/live_hr.ts +0 -21
  708. package/src/projections/live_state.ts +0 -28
  709. package/src/projections/live_stress.ts +0 -13
  710. package/src/projections/performance_assessment.ts +0 -19
  711. package/src/projections/profile.ts +0 -71
  712. package/src/projections/recovery.ts +0 -133
  713. package/src/projections/sleep_need.ts +0 -36
  714. package/src/projections/smart_alarm.ts +0 -70
  715. package/src/projections/strain.ts +0 -131
  716. package/src/projections/stress.ts +0 -95
  717. package/src/projections/today.ts +0 -166
  718. package/src/projections/trend.ts +0 -149
  719. package/src/projections/workouts.ts +0 -36
  720. package/src/schemas/calendar.ts +0 -13
  721. package/src/schemas/communities.ts +0 -56
  722. package/src/schemas/compare.ts +0 -17
  723. package/src/schemas/leaderboard.ts +0 -26
  724. package/src/schemas/live.ts +0 -31
  725. package/src/schemas/performance.ts +0 -13
  726. package/src/schemas/profile.ts +0 -40
  727. package/src/schemas/recovery.ts +0 -28
  728. package/src/schemas/settings.ts +0 -30
  729. package/src/schemas/sleep_need.ts +0 -16
  730. package/src/schemas/smart_alarm.ts +0 -40
  731. package/src/schemas/strain.ts +0 -25
  732. package/src/schemas/stress.ts +0 -17
  733. package/src/schemas/today.ts +0 -39
  734. package/src/schemas/trend.ts +0 -53
  735. package/src/schemas/womens_health.ts +0 -26
  736. package/src/tools/v2/activity_create.ts +0 -74
  737. package/src/tools/v2/behavior_impact.ts +0 -39
  738. package/src/tools/v2/communities.ts +0 -65
  739. package/src/tools/v2/compare.ts +0 -83
  740. package/src/tools/v2/endpoints.ts +0 -32
  741. package/src/tools/v2/hidden_metric.ts +0 -33
  742. package/src/tools/v2/hr_zones.ts +0 -29
  743. package/src/tools/v2/journal_autopop.ts +0 -26
  744. package/src/tools/v2/journal_catalog.ts +0 -48
  745. package/src/tools/v2/leaderboard.ts +0 -92
  746. package/src/tools/v2/lift_catalog.ts +0 -48
  747. package/src/tools/v2/lift_custom_exercise.ts +0 -117
  748. package/src/tools/v2/lift_history.ts +0 -52
  749. package/src/tools/v2/lift_progression.ts +0 -34
  750. package/src/tools/v2/lift_prs.ts +0 -26
  751. package/src/tools/v2/lift_template_save.ts +0 -89
  752. package/src/tools/v2/live_hr.ts +0 -26
  753. package/src/tools/v2/live_state.ts +0 -26
  754. package/src/tools/v2/live_stress.ts +0 -27
  755. package/src/tools/v2/performance_assessment.ts +0 -44
  756. package/src/tools/v2/sleep_need.ts +0 -26
  757. package/src/tools/v2/sports_catalog.ts +0 -32
  758. package/src/tools/v2/symptom_log.ts +0 -78
  759. package/src/tools/v2/today.ts +0 -35
  760. package/src/tools/v2/workout.ts +0 -28
  761. package/src/whoop/build_lift_body.ts +0 -84
  762. package/src/whoop/session_state.ts +0 -41
  763. package/src/whoop/types.ts +0 -89
package/src/cli/ui.ts CHANGED
@@ -1,505 +1,847 @@
1
- // Shared CLI primitives: colors, subprocess runner, HTTP ping, interactive
2
- // prompts, and small helpers used by both the command dispatcher (index.ts)
3
- // and the guided setup flows (setup.ts).
4
- import { spawn, spawnSync, type SpawnOptions } from "node:child_process";
1
+ // The CLI's visual language: one small set of primitives every screen is built
2
+ // from, so `totem local`, `totem cloud`, `totem auth`, `totem update` and the
3
+ // rest read as one tool. It is plain on purpose, like the CLIs people already
4
+ // use (gh, fly, vercel): text first, colour as a seasoning, no boxes or rails.
5
+ // The one picture is the logo, at the top of the big flows.
6
+ //
7
+ // banner the logo (rasterized from the SVG) beside a title: home, cloud, local
8
+ // header "totem <command>" and a one-line purpose, at the top of a command
9
+ // step "[2/6] Secrets": where you are in a flow
10
+ // section a bold title inside a screen
11
+ // ok/warn/fail/info one-line results, each led by a mark: "✓ Deployed [1m 42s]"
12
+ // para/hint wrapped prose: what is happening, what to do now
13
+ // rows aligned "Key: value" facts
14
+ // code something to paste, alone on its line
15
+ // next "Next" and what to do now
16
+ // problem what went wrong + the exact commands that fix it
17
+ // task a spinner with elapsed time for anything slow
18
+ // select/confirm/text/hidden the four prompts
19
+ //
20
+ // Rendering is separate from effects. `kit(style)` returns pure functions that
21
+ // turn data into lines; `Ui` writes those lines somewhere and asks questions.
22
+ // A screen can therefore be rendered in a test with a fixed Style and no
23
+ // terminal. Nothing here spawns a process or touches the network (see sys.ts).
24
+ //
25
+ // Rules the primitives enforce:
26
+ // - 80 columns at most, less on a narrow terminal; prose wraps, pasteable
27
+ // lines never get a border or a prefix.
28
+ // - Colour is decoration only: every state is also a glyph and a word. It
29
+ // is off for NO_COLOR, TERM=dumb and anything that isn't a terminal. The
30
+ // logo is only drawn where there is colour.
31
+ // - One icy palette (see "colour"), bold and dim, nothing else. Exact where
32
+ // the terminal draws 24-bit colour, the nearest of 256 otherwise, the basic
33
+ // colours nearest in meaning on a basic terminal, and darker when the
34
+ // terminal says its background is light.
35
+ // - ASCII glyphs where Unicode can't be trusted (legacy Windows consoles,
36
+ // TERM=dumb/linux, a non-UTF-8 locale).
5
37
  import { createInterface } from "node:readline/promises";
6
- import { randomBytes } from "node:crypto";
7
- import { request as httpsRequest } from "node:https";
8
- import { existsSync } from "node:fs";
9
- import { resolve } from "node:path";
10
-
11
- export const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
12
- // Modern truecolor palette (Tailwind-400-ish) — vivid but easy on a dark terminal.
13
- const ANSI = {
14
- reset: "\x1b[0m",
15
- bold: "\x1b[1m",
16
- dim: "\x1b[2m",
17
- brand: "\x1b[38;2;235;235;235m",
18
- brandDim: "\x1b[38;2;150;150;150m",
19
- gray: "\x1b[38;2;128;128;128m",
20
- white: "\x1b[38;2;245;245;245m",
21
- green: "\x1b[38;2;52;211;153m", // emerald
22
- red: "\x1b[38;2;248;113;113m", // red
23
- yellow: "\x1b[38;2;251;191;36m", // amber
24
- cyan: "\x1b[38;2;34;211;238m", // cyan
25
- violet: "\x1b[38;2;167;139;250m", // violet
26
- pink: "\x1b[38;2;244;114;182m", // pink
38
+ import { Writable } from "node:stream";
39
+ import { stripVTControlCharacters } from "node:util";
40
+ import { logoPixels, type Pixel } from "./logo.js";
41
+
42
+ // ── style ───────────────────────────────────────────────────────────────────
43
+
44
+ export interface Style {
45
+ color: boolean;
46
+ unicode: boolean;
47
+ /** Columns to lay out for: the terminal's width, kept between 40 and 80. */
48
+ width: number;
49
+ /** Colours the terminal can draw; the palette and the logo use more than the basic ones where they can. Default "basic". */
50
+ palette?: "basic" | "256" | "truecolor";
51
+ /** The terminal reports a light background (COLORFGBG), so every colour goes darker. */
52
+ light?: boolean;
53
+ /** Draw the logo in a banner. Default: wherever there is colour and Unicode. */
54
+ logo?: boolean;
55
+ }
56
+
57
+ type Env = Record<string, string | undefined>;
58
+ interface StreamLike { isTTY?: boolean | undefined; columns?: number | undefined }
59
+
60
+ const set = (v: string | undefined): boolean => v !== undefined && v !== "";
61
+
62
+ export function detectStyle(stream: StreamLike = process.stdout, env: Env = process.env, platform: NodeJS.Platform = process.platform): Style {
63
+ const color = set(env.NO_COLOR) ? false
64
+ : set(env.FORCE_COLOR) && env.FORCE_COLOR !== "0" ? true
65
+ : env.TERM === "dumb" ? false
66
+ : Boolean(stream.isTTY);
67
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
68
+ const unicode = env.TOTEM_ASCII === "1" ? false
69
+ : env.TERM === "dumb" || env.TERM === "linux" ? false
70
+ // Windows: only terminals known to render UTF-8 (Windows Terminal, VS Code,
71
+ // ConEmu, anything that sets TERM). The legacy console gets ASCII.
72
+ : platform === "win32" ? Boolean(env.WT_SESSION || env.TERM_PROGRAM || env.ConEmuTask || env.TERM)
73
+ : locale === "" || /utf-?8/i.test(locale);
74
+ const columns = stream.isTTY && stream.columns ? stream.columns : 80;
75
+ const palette = /^(truecolor|24bit)$/i.test(env.COLORTERM ?? "") || TRUECOLOR_APPS.has(env.TERM_PROGRAM ?? "") || set(env.WT_SESSION) ? "truecolor"
76
+ : /256/.test(env.TERM ?? "") ? "256"
77
+ : "basic";
78
+ // COLORFGBG is "fg;bg" (sometimes "fg;default;bg"); 7 and 15 are the light greys and white.
79
+ const bg = (env.COLORFGBG ?? "").split(";").pop();
80
+ return { color, unicode, width: Math.max(40, Math.min(80, columns)), palette, light: bg === "7" || bg === "15" };
81
+ }
82
+
83
+ /** Terminals that draw 24-bit colour without saying so in COLORTERM. */
84
+ const TRUECOLOR_APPS = new Set(["iTerm.app", "WezTerm", "ghostty", "vscode", "Hyper"]);
85
+
86
+ export const PLAIN: Style = { color: false, unicode: true, width: 80 };
87
+
88
+ // ── glyphs ──────────────────────────────────────────────────────────────────
89
+
90
+ export interface Glyphs {
91
+ ok: string; fail: string; warn: string; info: string;
92
+ /** Menu path separator: Settings → Connectors. */
93
+ arrow: string;
94
+ pointer: string; ask: string; dot: string; ellipsis: string; dash: string;
95
+ spinner: string[];
96
+ }
97
+ const UNICODE: Glyphs = {
98
+ ok: "✓", fail: "✗", warn: "!", info: "•", arrow: "→", pointer: "›", ask: "?", dot: "·", ellipsis: "…", dash: "–",
99
+ spinner: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
100
+ };
101
+ const ASCII: Glyphs = {
102
+ ok: "+", fail: "x", warn: "!", info: "-", arrow: ">", pointer: ">", ask: "?", dot: "-", ellipsis: "...", dash: "-",
103
+ spinner: ["-", "\\", "|", "/"],
27
104
  };
28
- function wrap(code: string, s: string): string {
29
- return useColor ? `${code}${s}${ANSI.reset}` : s;
105
+ export const glyphs = (style: Style): Glyphs => (style.unicode ? UNICODE : ASCII);
106
+
107
+ // ── colour ──────────────────────────────────────────────────────────────────
108
+
109
+ // The brand's ice draws the logo and the brand word; the palette marks what
110
+ // needs you:
111
+ // lead the step you are on, the spinner, a question, the choice and the answer
112
+ // command something to run or paste
113
+ // link an address
114
+ // secret the one-time connector password
115
+ // ok / warn / fail done, a warning, a failure
116
+ // dim: everything secondary
117
+ export interface Paint {
118
+ bold(s: string): string; dim(s: string): string;
119
+ /** The palette's ok, warn and fail colours. */
120
+ red(s: string): string; green(s: string): string; yellow(s: string): string;
121
+ /** Ice: the logo and the brand word. */
122
+ brand(s: string): string;
123
+ /** A command to run or paste. */
124
+ accent(s: string): string;
125
+ /** Lead: the current step, the spinner, a question, the highlighted choice and the answer given. */
126
+ ask(s: string): string;
127
+ /** An address: the server and connector URLs. */
128
+ link(s: string): string;
129
+ /** The one-time connector password. */
130
+ secret(s: string): string;
30
131
  }
31
- export const c = {
32
- brand: (s: string) => wrap(ANSI.brand, s),
33
- brandDim: (s: string) => wrap(ANSI.brandDim, s),
34
- gray: (s: string) => wrap(ANSI.gray, s),
35
- white: (s: string) => wrap(ANSI.white, s),
36
- green: (s: string) => wrap(ANSI.green, s),
37
- red: (s: string) => wrap(ANSI.red, s),
38
- yellow: (s: string) => wrap(ANSI.yellow, s),
39
- cyan: (s: string) => wrap(ANSI.cyan, s),
40
- violet: (s: string) => wrap(ANSI.violet, s),
41
- pink: (s: string) => wrap(ANSI.pink, s),
42
- bold: (s: string) => wrap(ANSI.bold, s),
43
- dim: (s: string) => wrap(ANSI.dim, s),
132
+
133
+ type Shade = "ice" | "fold";
134
+ // [r, g, b] and the nearest xterm-256 colour, on a dark and on a light background.
135
+ const SHADES: Record<"dark" | "light", Record<Shade, [rgb: string, x256: number, basic: number]>> = {
136
+ dark: { ice: ["183;211;242", 153, 94], fold: ["122;156;198", 110, 34] },
137
+ light: { ice: ["122;156;198", 110, 34], fold: ["79;111;153", 67, 34] },
44
138
  };
45
139
 
46
- // Spawn a command, inheriting stdio. Resolves with the exit code.
47
- export function run(cmd: string, args: string[], opts: SpawnOptions = {}): Promise<number> {
48
- return new Promise((res) => {
49
- const child = spawn(cmd, args, { stdio: "inherit", ...opts });
50
- child.on("exit", (code, signal) => {
51
- if (signal) {
52
- console.error(c.red(`\nKilled by signal ${signal}`));
53
- res(128);
54
- return;
55
- }
56
- res(code ?? 1);
57
- });
58
- child.on("error", (err) => {
59
- console.error(c.red("Failed to spawn:"), (err as Error).message);
60
- res(1);
61
- });
62
- });
140
+ /** The SGR code for a brand shade: ice #B7D3F2 (default) or fold #7A9CC6, a step darker on a light background. `bg` paints the cell behind. */
141
+ export function brandSgr(style: Style, shade: Shade = "ice", bg = false): string {
142
+ const [rgb, x256, basic] = SHADES[style.light ? "light" : "dark"][shade];
143
+ if (style.palette === "truecolor") return `${bg ? 48 : 38};2;${rgb}`;
144
+ if (style.palette === "256") return `${bg ? 48 : 38};5;${x256}`;
145
+ return String(bg ? basic + 10 : basic);
63
146
  }
64
147
 
65
- // Run a command and capture stdout (for parsing CLI output like a deploy URL).
66
- export function capture(cmd: string, args: string[], opts: SpawnOptions = {}): { code: number; stdout: string; stderr: string } {
67
- const r = spawnSync(cmd, args, { encoding: "utf8", ...opts });
68
- return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
148
+ export type Role = "lead" | "command" | "link" | "secret" | "ok" | "warn" | "fail";
149
+
150
+ /**
151
+ * The palette: glacier colours beside the brand's ice, chosen in OKLCH so
152
+ * their lightness is even and no one colour shouts over the others. Warnings
153
+ * and failures stay warm, so a problem still reads as one. The terminal gets
154
+ * these hues at a lightness it can read: lighter on a dark background
155
+ * (onDark), darker on a light one (onLight).
156
+ */
157
+ export const PALETTE: Record<Role, string> = {
158
+ lead: "#71C9FA", // glacier blue
159
+ command: "#72DEE4", // arctic cyan
160
+ link: "#B2B8F7", // frost lavender
161
+ secret: "#E5F4FE", // snow
162
+ ok: "#88E1D0", // glacial mint
163
+ warn: "#F0D49B", // winter sun
164
+ fail: "#EB8A99", // frostbite rose
165
+ };
166
+ /** A basic terminal has eight colours and its own idea of them: the nearest by meaning. */
167
+ const BASIC_ROLE: Record<Role, number> = { lead: 36, command: 37, link: 36, secret: 37, ok: 32, warn: 33, fail: 31 };
168
+
169
+ type Rgb = [number, number, number];
170
+ const hexRgb = (hex: string): Rgb => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as Rgb;
171
+
172
+ /** Relative luminance (WCAG): 0 for black, 1 for white. */
173
+ const luminance = (rgb: Rgb): number => {
174
+ const [r, g, b] = rgb.map((v) => { const c = v / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; });
175
+ return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;
176
+ };
177
+
178
+ /** WCAG contrast between two luminances: 1 (none) to 21 (black on white). */
179
+ const contrast = (a: number, b: number): number => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
180
+ /** The dark background colours are judged against: #1E1E1E, a typical dark terminal theme. */
181
+ const DARK_BG = luminance([30, 30, 30]);
182
+
183
+ /**
184
+ * The same hue at the first lightness, walking from its own in steps of
185
+ * `step`, that has 4.5:1 contrast with a background of luminance `bg`
186
+ * (WCAG's bar for text).
187
+ */
188
+ function readableOn([r, g, b]: Rgb, bg: number, step: number): Rgb {
189
+ const [R, G, B] = [r / 255, g / 255, b / 255];
190
+ const max = Math.max(R, G, B), min = Math.min(R, G, B), l = (max + min) / 2, d = max - min;
191
+ const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
192
+ // The hue as a sixth of the circle, 0 to 6 (a remainder in JS keeps its sign, so wrap it).
193
+ const h = d === 0 ? 0 : max === R ? (((G - B) / d) % 6 + 6) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
194
+ const fromHsl = (L: number): Rgb => {
195
+ const C = (1 - Math.abs(2 * L - 1)) * s, X = C * (1 - Math.abs((h % 2) - 1)), m = L - C / 2;
196
+ const [r1, g1, b1] = h < 1 ? [C, X, 0] : h < 2 ? [X, C, 0] : h < 3 ? [0, C, X] : h < 4 ? [0, X, C] : h < 5 ? [X, 0, C] : [C, 0, X];
197
+ return [r1, g1, b1].map((v) => Math.round((v + m) * 255)) as Rgb;
198
+ };
199
+ for (let L = l; L >= 0 && L <= 1; L += step) {
200
+ const out = fromHsl(L);
201
+ if (contrast(luminance(out), bg) >= 4.5) return out;
202
+ }
203
+ return step < 0 ? [0, 0, 0] : [255, 255, 255];
69
204
  }
70
205
 
71
- // Async sibling of capture(). `capture` uses spawnSync, which BLOCKS the event
72
- // loop for the whole subprocess — so a spinner (setInterval) can't animate over
73
- // it. For slow, network-bound lookups (gcloud/railway/fly API calls) run them
74
- // through this instead and wrap with withSpinner() so the UI stays alive.
75
- export function captureAsync(
76
- cmd: string,
77
- args: string[],
78
- opts: SpawnOptions & { input?: string } = {},
79
- ): Promise<{ code: number; stdout: string; stderr: string }> {
80
- const { input, ...spawnOpts } = opts;
81
- return new Promise((res) => {
82
- // input set → pipe stdin so secrets can be fed over a pipe (off the argv,
83
- // which is visible in `ps`/`/proc`); otherwise ignore stdin as before.
84
- const child = spawn(cmd, args, { stdio: [input !== undefined ? "pipe" : "ignore", "pipe", "pipe"], ...spawnOpts });
85
- let stdout = "";
86
- let stderr = "";
87
- child.stdout?.on("data", (d: Buffer) => (stdout += d.toString()));
88
- child.stderr?.on("data", (d: Buffer) => (stderr += d.toString()));
89
- child.on("error", () => res({ code: 1, stdout, stderr }));
90
- child.on("close", (code) => res({ code: code ?? 1, stdout, stderr }));
91
- if (input !== undefined) { child.stdin?.write(input); child.stdin?.end(); }
92
- });
206
+ /** Dark enough to read on white. Yellow and lime come down much further than violet. */
207
+ export const onLight = (rgb: Rgb): Rgb => readableOn(rgb, 1, -0.01);
208
+ /** Light enough to read on a dark terminal. Electric indigo comes up to a lavender. */
209
+ export const onDark = (rgb: Rgb): Rgb => readableOn(rgb, DARK_BG, 0.01);
210
+
211
+ /** The nearest of xterm's 256 colours: the 6×6×6 cube or the grey ramp. */
212
+ export function xterm256([r, g, b]: Rgb): number {
213
+ const levels = [0, 95, 135, 175, 215, 255];
214
+ const near = (v: number): number => levels.reduce((best, l, i) => (Math.abs(l - v) < Math.abs(levels[best]! - v) ? i : best), 0);
215
+ const [ri, gi, bi] = [near(r), near(g), near(b)];
216
+ const grey = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)));
217
+ const dist = (x: Rgb): number => (x[0] - r) ** 2 + (x[1] - g) ** 2 + (x[2] - b) ** 2;
218
+ const cube: Rgb = [levels[ri]!, levels[gi]!, levels[bi]!];
219
+ const g8 = 8 + 10 * grey;
220
+ return dist(cube) <= dist([g8, g8, g8]) ? 16 + 36 * ri + 6 * gi + bi : 232 + grey;
93
221
  }
94
222
 
95
- // ── spinner ──────────────────────────────────────────────────────────────
96
- // A braille spinner for the "thinking" gaps where we do work with no visible
97
- // output (our own network lookups, HTTP polling, backoff waits). Subprocesses
98
- // run with inherited stdio print their own progress, so they don't need this.
99
- // IMPORTANT: a spinner only animates while the event loop is free — pair it
100
- // with async work (await captureAsync / httpGet / setTimeout), never spawnSync.
101
- const SPIN_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
102
- export interface Spinner {
103
- stop: (final?: string) => void;
223
+ /** The SGR code for one of the palette's colours. */
224
+ export function roleSgr(style: Style, role: Role): string {
225
+ if (style.palette !== "truecolor" && style.palette !== "256") return String(BASIC_ROLE[role]);
226
+ const base = hexRgb(PALETTE[role]);
227
+ const rgb = style.light ? onLight(base) : onDark(base);
228
+ return style.palette === "truecolor" ? `38;2;${rgb.join(";")}` : `38;5;${xterm256(rgb)}`;
104
229
  }
105
230
 
106
- export function spin(message: string | (() => string)): Spinner {
107
- // Message can be a live function (e.g. an elapsed-time counter), re-evaluated
108
- // on every frame.
109
- const msg = (): string => (typeof message === "function" ? message() : message);
110
- // No TTY (piped/CI): no cursor tricks — print the message once, plainly.
111
- if (!process.stdout.isTTY) {
112
- console.log(c.gray(` ${msg()}…`));
113
- return { stop: (final) => { if (final) console.log(final); } };
114
- }
115
- let i = 0;
116
- process.stdout.write("\x1b[?25l"); // hide cursor
117
- const draw = (): void => {
118
- process.stdout.write(`\r\x1b[2K${c.cyan(SPIN_FRAMES[i % SPIN_FRAMES.length]!)} ${c.gray(msg())}`);
119
- i++;
120
- };
121
- draw();
122
- const timer = setInterval(draw, 80);
231
+ export function paint(style: Style): Paint {
232
+ const sgr = (open: number | string, close: number | string) => (s: string): string => (style.color && s ? `\x1b[${open}m${s}\x1b[${close}m` : s);
233
+ const role = (r: Role) => sgr(roleSgr(style, r), 39);
123
234
  return {
124
- stop: (final?: string): void => {
125
- clearInterval(timer);
126
- process.stdout.write("\r\x1b[2K\x1b[?25h"); // clear line + restore cursor
127
- if (final) console.log(final);
128
- },
235
+ bold: sgr(1, 22), dim: sgr(2, 22), red: role("fail"), green: role("ok"), yellow: role("warn"),
236
+ brand: sgr(brandSgr(style), 39),
237
+ accent: role("command"), ask: role("lead"), link: role("link"), secret: sgr(`1;${roleSgr(style, "secret")}`, "39;22"),
129
238
  };
130
239
  }
131
240
 
132
- // Run async work under a spinner; always stops the spinner, even on throw.
133
- export async function withSpinner<T>(message: string, fn: () => Promise<T>): Promise<T> {
134
- const s = spin(message);
135
- try {
136
- return await fn();
137
- } finally {
138
- s.stop();
241
+ // ── text ────────────────────────────────────────────────────────────────────
242
+
243
+ /** Columns a string takes on screen (escape sequences don't count). */
244
+ export const visibleWidth = (s: string): number => [...stripVTControlCharacters(s)].length;
245
+
246
+ export const padEnd = (s: string, width: number): string => s + " ".repeat(Math.max(0, width - visibleWidth(s)));
247
+
248
+ /**
249
+ * Word-wrap to `width` columns. A word longer than the line (a URL, a path, a
250
+ * command) stays whole on its own line: it is never cut, because a cut value
251
+ * can't be pasted.
252
+ */
253
+ export function wrap(text: string, width: number): string[] {
254
+ const out: string[] = [];
255
+ for (const paragraph of text.split("\n")) {
256
+ let line = "";
257
+ for (const word of paragraph.split(/\s+/).filter(Boolean)) {
258
+ if (line === "") line = word;
259
+ else if (visibleWidth(line) + 1 + visibleWidth(word) <= width) line += " " + word;
260
+ else { out.push(line); line = word; }
261
+ }
262
+ out.push(line);
139
263
  }
264
+ return out;
140
265
  }
141
266
 
142
- // A visible backoff: spin for `ms` so a silent wait doesn't look like a hang.
143
- export async function pause(ms: number, message: string): Promise<void> {
144
- const s = spin(message);
145
- await new Promise((r) => setTimeout(r, ms));
146
- s.stop();
267
+ /**
268
+ * wrap(), keeping a list marker hanging: the lines after "1. " or "- " start
269
+ * under the text, not under the marker.
270
+ */
271
+ export function wrapHanging(text: string, width: number): string[] {
272
+ const marker = text.match(/^(\d+\.|[-*])\s+/)?.[0];
273
+ if (!marker) return wrap(text, width);
274
+ const pad = " ".repeat(marker.length);
275
+ return wrap(text.slice(marker.length), width - marker.length).map((l, i) => (i === 0 ? marker + l : pad + l));
147
276
  }
148
277
 
149
- // Is a CLI tool on PATH? Uses which/where (real executables) rather than the
150
- // `command -v` shell builtin, so we avoid `shell: true` — which both triggers
151
- // Node 25's DEP0190 warning and is an injection risk.
152
- export function commandExists(cmd: string): boolean {
153
- const probe = process.platform === "win32" ? "where" : "which";
154
- const r = spawnSync(probe, [cmd], { encoding: "utf8" });
155
- return (r.status ?? 1) === 0 && (r.stdout ?? "").trim().length > 0;
278
+ /** Cut to `width` columns with an ellipsis: for output that must stay one line per line. */
279
+ export function truncate(text: string, width: number, ellipsis = "…"): string {
280
+ return visibleWidth(text) <= width ? text : [...text].slice(0, Math.max(0, width - ellipsis.length)).join("") + ellipsis;
156
281
  }
157
282
 
158
- // 256-bit random hex token (for MCP_AUTH_TOKEN / signing secret).
159
- export function genToken(): string {
160
- return randomBytes(32).toString("hex");
283
+ /** "a", "a and b", "a, b and c". */
284
+ export function listOf(items: string[]): string {
285
+ return items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
161
286
  }
162
287
 
163
- // Cryptographically-random password. Rejection sampling over an unambiguous
164
- // alphabet (no 0/O/1/l/I) plus symbols for entropy — safe to read/retype.
165
- export function genPassword(len = 18): string {
166
- const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*-_=+";
167
- const max = Math.floor(256 / alphabet.length) * alphabet.length; // reject modulo bias
168
- let out = "";
169
- while (out.length < len) {
170
- const b = randomBytes(1)[0]!;
171
- if (b < max) out += alphabet[b % alphabet.length];
172
- }
173
- return out;
288
+ /** "42s", "1m 42s"; empty under a second. */
289
+ export function duration(ms: number): string {
290
+ const s = Math.round(ms / 1000);
291
+ if (s < 1) return "";
292
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
174
293
  }
175
294
 
176
- // Best-effort copy to the OS clipboard. Returns true on success, false if no
177
- // clipboard tool is available (never throws).
178
- export function copyToClipboard(text: string): boolean {
179
- const [cmd, args]: [string, string[]] =
180
- process.platform === "darwin" ? ["pbcopy", []]
181
- : process.platform === "win32" ? ["clip", []]
182
- : ["xclip", ["-selection", "clipboard"]];
183
- try {
184
- const r = spawnSync(cmd, args, { input: text });
185
- return (r.status ?? 1) === 0;
186
- } catch {
187
- return false;
188
- }
295
+ /** An ISO timestamp as "2026-11-21 23:10 UTC" (the same on every machine). */
296
+ export function when(iso: string | null | undefined): string {
297
+ if (!iso) return "unknown";
298
+ const t = new Date(iso);
299
+ return Number.isNaN(t.getTime()) ? iso : `${t.toISOString().slice(0, 16).replace("T", " ")} UTC`;
189
300
  }
190
301
 
191
- // Run a bundled script resiliently. A published install (`npm install -g`)
192
- // ships the compiled `dist/*.js` and only runtime deps — no `tsx`/`typescript`.
193
- // A dev checkout has `tsx` + the TypeScript source. Prefer whichever fits:
194
- // dist+node by default (works everywhere), source+tsx when `preferSource` is set
195
- // (live dev, picks up edits without a rebuild). `relNoExt` is relative to src/
196
- // or dist/ without extension, e.g. "scripts/cognito_bootstrap" or "server".
197
- export function runScript(
198
- root: string,
199
- relNoExt: string,
200
- args: string[] = [],
201
- opts: { preferSource?: boolean } & SpawnOptions = {},
202
- ): Promise<number> {
203
- const { preferSource = false, ...spawnOpts } = opts;
204
- const distJs = resolve(root, "dist", `${relNoExt}.js`);
205
- const srcTs = resolve(root, "src", `${relNoExt}.ts`);
206
- const tsx = resolve(root, "node_modules", ".bin", "tsx");
207
- const viaDist: [string, string] = [process.execPath, distJs];
208
- const viaTsx: [string, string] = [tsx, srcTs];
209
- const order = preferSource ? [viaTsx, viaDist] : [viaDist, viaTsx];
210
- for (const [bin, script] of order) {
211
- const binOk = bin === process.execPath || existsSync(bin);
212
- if (binOk && existsSync(script)) return run(bin, [script, ...args], { cwd: root, ...spawnOpts });
302
+ /** A path as one shell word: quoted when it has a space or a quote in it. */
303
+ export const shellPath = (p: string): string => (/[\s'"]/.test(p) ? `"${p.replace(/"/g, '\\"')}"` : p);
304
+
305
+ /**
306
+ * One shell command as lines of at most `width` columns, split between
307
+ * arguments with a trailing backslash so the block still pastes as one
308
+ * command. Windows shells have no shared continuation character, so there the
309
+ * command stays on one line.
310
+ */
311
+ export function shellLines(words: string[], width: number, platform: NodeJS.Platform = process.platform): string[] {
312
+ const one = words.join(" ");
313
+ if (platform === "win32" || visibleWidth(one) <= width) return [one];
314
+ const lines: string[] = [];
315
+ let line = "";
316
+ for (const word of words) {
317
+ const candidate = line === "" ? word : `${line} ${word}`;
318
+ // Leave room for the " \" that marks a continued line.
319
+ if (line !== "" && visibleWidth(candidate) + 2 > width) { lines.push(line); line = " " + word; } else line = candidate;
213
320
  }
214
- console.error(c.red(`Can't run ${relNoExt}: need either a built dist/ or the tsx dev dependency.`));
215
- console.error(c.gray("Run ") + c.bold("npm install && totem build") + c.gray(" in a source checkout, or reinstall the published package."));
216
- return Promise.resolve(1);
321
+ lines.push(line);
322
+ return lines.map((l, i) => (i < lines.length - 1 ? `${l} \\` : l));
217
323
  }
218
324
 
219
- // Ensure a CLI tool is on PATH; if not, offer to install it (with permission).
220
- // Tries brew → npm → install script, in that order, based on what's available.
221
- // Note: a freshly installed tool often isn't on this process's PATH yet, so we
222
- // re-check and, if still missing, tell the user to re-run in a new shell.
223
- export async function ensureCli(
224
- name: string,
225
- opts: { brewPkg?: string; npmPkg?: string; scriptUrl?: string; manualHint: string },
226
- ): Promise<boolean> {
227
- if (commandExists(name)) return true;
228
- console.log(c.yellow(` ${name} isn't installed.`));
229
- // Collect the install methods that are actually available and try them in
230
- // order (brew → npm → script), falling THROUGH if one fails (e.g. a brew
231
- // formula doesn't exist) instead of giving up after the first.
232
- const methods: Array<[string, string[]]> = [];
233
- if (opts.brewPkg && commandExists("brew")) methods.push(["brew", ["install", opts.brewPkg]]);
234
- if (opts.npmPkg && commandExists("npm")) methods.push(["npm", ["install", "-g", opts.npmPkg]]);
235
- if (opts.scriptUrl) methods.push(["sh", ["-c", `curl -fsSL ${opts.scriptUrl} | sh`]]);
236
- if (methods.length === 0) {
237
- console.log(c.gray(` Install it manually: ${opts.manualHint}`));
238
- return false;
239
- }
240
- for (const [cmd, args] of methods) {
241
- console.log(c.gray(` $ ${cmd} ${args.join(" ")}`));
242
- if (!(await promptYesNo(`Install ${name} via \`${cmd}\`?`, true))) continue;
243
- if ((await run(cmd, args)) === 0 && commandExists(name)) return true;
244
- console.log(c.yellow(` ${cmd} didn't get ${name} working${methods.length > 1 ? " — trying the next method" : ""}.`));
245
- }
246
- if (!commandExists(name)) {
247
- console.log(c.yellow(` ${name} still isn't on this shell's PATH.`));
248
- console.log(c.gray(` ${opts.manualHint} — or open a new terminal and re-run.`));
249
- return false;
250
- }
251
- return true;
325
+ // ── primitives (pure) ───────────────────────────────────────────────────────
326
+
327
+ export type Mark = "ok" | "fail" | "warn" | "info";
328
+ /** A way out of a problem: what it does, and the exact command. */
329
+ export type Fix = [label: string, command: string];
330
+
331
+ /** Columns the logo takes, and the gap after it. */
332
+ const LOGO_COLS = 12;
333
+ const LOGO_ROWS = 5;
334
+ const LOGO_GAP = 3;
335
+
336
+ export interface Kit {
337
+ style: Style;
338
+ g: Glyphs;
339
+ c: Paint;
340
+ /** Whether banner() draws the logo here. */
341
+ logo: boolean;
342
+ /** The logo with a title and purpose beside it; without a logo, header(). */
343
+ banner(title: string, subtitle?: string, meta?: string): string[];
344
+ /** "totem <command>" and its purpose under it. */
345
+ header(title: string, subtitle?: string): string[];
346
+ /** "[2/6] Secrets". */
347
+ step(n: number, total: number, title: string): string[];
348
+ section(title: string): string[];
349
+ mark(kind: Mark, text: string, detail?: string): string[];
350
+ para(text: string, indent?: number): string[];
351
+ hint(text: string, indent?: number): string[];
352
+ rows(pairs: Array<[key: string, value: string]>, indent?: number): string[];
353
+ code(lines: string[], indent?: number): string[];
354
+ /** "Next" and what to do now. */
355
+ next(lines: string[], title?: string): string[];
356
+ /** A question as it is asked: "? Question (suffix)". */
357
+ question(question: string, suffix?: string): string;
358
+ /** A question once it is answered: "? Question answer", what stays on screen after a choice. */
359
+ answered(question: string, answer: string): string;
360
+ problem(what: string, opts?: { detail?: string | string[] | undefined; fix?: Fix[] | undefined }, indent?: number): string[];
252
361
  }
253
362
 
254
- // Open a URL in the default browser, cross-platform. Best-effort, never throws.
255
- export function openUrl(url: string): void {
256
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
257
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
258
- try { spawnSync(cmd, args, { stdio: "ignore" }); } catch { /* best-effort */ }
259
- }
363
+ /** An http(s) address inside prose, without trailing punctuation. Capturing, so split() keeps it. */
364
+ const URL_IN_TEXT = /(https?:\/\/[^\s)]*[^\s).,;:'"])/;
365
+ /** A time a step took ("4s", "1m 42s"): shown in brackets, the rest of a detail in parentheses. */
366
+ const TIME = /^\d+(m \d{2})?s$/;
367
+
368
+ export function kit(style: Style): Kit {
369
+ const g = glyphs(style);
370
+ const c = paint(style);
371
+ const W = style.width;
372
+ const symbol: Record<Mark, string> = { ok: c.green(g.ok), fail: c.red(g.fail), warn: c.yellow(g.warn), info: c.dim(g.info) };
373
+ const logo = (style.logo ?? (style.color && style.unicode)) && style.unicode && W >= 56;
374
+ // Addresses in the link colour wherever they turn up, the rest in `rest`.
375
+ // Text that already carries colour is left as it is.
376
+ const urls = (text: string, rest: (s: string) => string = (s) => s): string =>
377
+ text.includes("\x1b[") ? text : text.split(URL_IN_TEXT).map((part, i) => (i % 2 ? c.link(part) : part ? rest(part) : "")).join("");
378
+ // Commands inside prose in the command colour: "…: totem status", "run: codex mcp login whoop".
379
+ const commands = (text: string): string =>
380
+ text.replace(/(: |run: )(totem [a-z][\w -]*|[a-z]+ mcp [\w -]+)(?=\)|\.?$)/, (_m, lead: string, cmd: string) => `${lead}${c.accent(cmd.trimEnd())}`);
381
+
382
+ const mark = (kind: Mark, text: string, detail?: string): string[] => {
383
+ const lines = wrap(text, W - 2).map((line, i) => `${i === 0 ? symbol[kind] : " "} ${line}`);
384
+ if (!detail) return lines;
385
+ // "✓ Deployed [1m 42s]", "✓ Signed in to Fly (you@example.com)"; on its own line when it doesn't fit.
386
+ const tail = TIME.test(detail) ? `[${detail}]` : `(${detail})`;
387
+ const last = lines[lines.length - 1]!;
388
+ if (visibleWidth(last) + 1 + visibleWidth(tail) <= W) lines[lines.length - 1] = `${last} ${urls(tail, c.dim)}`;
389
+ else for (const d of wrap(detail, W - 2)) lines.push(` ${urls(d, c.dim)}`);
390
+ return lines;
391
+ };
260
392
 
261
- // GET a URL, resolve with {status, body}. Used for health + OAuth metadata checks.
262
- export function httpGet(url: string, timeoutMs = 12_000): Promise<{ status: number; body: string }> {
263
- return new Promise((res) => {
264
- const u = new URL(url);
265
- const req = httpsRequest(
266
- { method: "GET", hostname: u.hostname, port: u.port || 443, path: u.pathname + u.search, headers: { "user-agent": "totem-setup" } },
267
- (response) => {
268
- let body = "";
269
- response.setEncoding("utf8");
270
- response.on("data", (ch: string) => (body += ch));
271
- response.on("end", () => res({ status: response.statusCode ?? 0, body }));
272
- },
273
- );
274
- req.setTimeout(timeoutMs, () => { req.destroy(); res({ status: 0, body: "" }); });
275
- req.on("error", () => res({ status: 0, body: "" }));
276
- req.end();
277
- });
278
- }
393
+ const rows = (pairs: Array<[string, string]>, indent = 2): string[] => {
394
+ const keyWidth = Math.max(...pairs.map(([k]) => visibleWidth(k))) + 3;
395
+ const pad = " ".repeat(indent);
396
+ return pairs.flatMap(([key, value]) => {
397
+ const lines = wrap(value, Math.max(16, W - indent - keyWidth));
398
+ return lines.map((line, i) => `${pad}${i === 0 ? c.dim(padEnd(`${key}:`, keyWidth)) : " ".repeat(keyWidth)}${urls(line)}`);
399
+ });
400
+ };
279
401
 
280
- export function ping(url: string, timeoutMs = 10_000): Promise<number> {
281
- return httpGet(url, timeoutMs).then((r) => {
282
- const ok = r.status >= 200 && r.status < 300;
283
- const label = ok ? c.green(`✓ ${r.status}`) : c.red(`✗ ${r.status || "timeout"}`);
284
- const preview = r.body.length > 100 ? r.body.slice(0, 97) + "..." : r.body;
285
- console.log(`${label} ${url} ${c.gray(preview.replace(/\s+/g, " ").trim())}`);
286
- return ok ? 0 : 1;
287
- });
402
+ // "totem cloud": the brand word in ice, the whole title bold.
403
+ const name = (title: string): string => {
404
+ const [brandWord, ...rest] = title.split(" ");
405
+ return c.bold(`${c.brand(brandWord!)}${rest.length ? ` ${rest.join(" ")}` : ""}`);
406
+ };
407
+ const header = (title: string, subtitle?: string): string[] => [name(title), ...(subtitle ? wrap(subtitle, W).map((l) => c.dim(l)) : [])];
408
+
409
+ // Two pixels a cell: the upper in the foreground of a half block, the lower behind it.
410
+ const logoRows = (): string[] => {
411
+ const px = logoPixels(LOGO_COLS, LOGO_ROWS * 2);
412
+ const fg = (p: Exclude<Pixel, null>, ch: string): string => (style.color ? `\x1b[${brandSgr(style, p)}m${ch}\x1b[39m` : ch);
413
+ const cell = (top: Pixel, bottom: Pixel): string => {
414
+ if (!top && !bottom) return " ";
415
+ if (!top) return fg(bottom!, "▄");
416
+ if (!bottom) return fg(top, "▀");
417
+ if (top === bottom) return fg(top, "█");
418
+ return style.color ? `\x1b[${brandSgr(style, top)};${brandSgr(style, bottom, true)}m▀\x1b[39;49m` : "▀";
419
+ };
420
+ return Array.from({ length: LOGO_ROWS }, (_, r) => px[2 * r]!.map((top, x) => cell(top, px[2 * r + 1]![x]!)).join(""));
421
+ };
422
+
423
+ return {
424
+ style, g, c, logo,
425
+ banner: (title, subtitle, meta) => {
426
+ if (!logo) return header(title, subtitle);
427
+ const textWidth = W - 1 - LOGO_COLS - LOGO_GAP;
428
+ // The title on the logo's second row, the purpose and meta under it.
429
+ const text = ["", name(title), ...(subtitle ? wrap(subtitle, textWidth).map((l) => c.dim(l)) : []), ...(meta ? [c.dim(meta)] : [])];
430
+ const art = logoRows();
431
+ return Array.from({ length: Math.max(art.length, text.length) }, (_, i) => {
432
+ const left = ` ${art[i] ?? " ".repeat(LOGO_COLS)}`;
433
+ return text[i] ? `${left}${" ".repeat(LOGO_GAP)}${text[i]}` : art[i] ? left : "";
434
+ });
435
+ },
436
+ header,
437
+ step: (n, total, title) => [`${c.dim(`[${n}/${total}]`)} ${c.bold(title)}`],
438
+ section: (title) => [title.includes("\x1b[") ? c.bold(title) : urls(title, c.bold)],
439
+ question: (question, suffix = "") => `${c.ask(g.ask)} ${c.bold(question)}${suffix ? " " + c.dim(suffix) : ""}`,
440
+ answered: (question, answer) => `${c.ask(g.ask)} ${c.bold(question)} ${c.ask(answer)}`,
441
+ mark,
442
+ para: (text, indent = 0) => wrapHanging(text, W - indent).map((l) => " ".repeat(indent) + l),
443
+ hint: (text, indent = 2) => wrap(text, W - indent).map((l) => " ".repeat(indent) + c.dim(l)),
444
+ rows,
445
+ code: (lines, indent = 2) => lines.map((l) => " ".repeat(indent) + c.accent(l)),
446
+ next: (lines, title = "Next") => {
447
+ // Numbered steps keep their number in the lead colour, commands in theirs.
448
+ const body = lines.flatMap((l) => (l === "" ? [""] : wrapHanging(commands(urls(l)), W - 2).map((w) => w.replace(/^(\d+\.)(?= )/, (m) => c.ask(m)))));
449
+ return [c.bold(title), ...body.map((l) => (l === "" ? "" : ` ${l}`))];
450
+ },
451
+ problem: (what, opts = {}, indent = 0) => {
452
+ const pad = " ".repeat(indent);
453
+ const head = wrap(what, W - indent - 2).map((l, i) => `${pad}${i === 0 ? c.red(g.fail) : " "} ${c.bold(l)}`);
454
+ // A string is prose and wraps. An array is a command's own output, line by
455
+ // line: a long line continues indented, so where each one starts stays
456
+ // visible and nothing (the exit code at the end, say) is cut off.
457
+ const details = (Array.isArray(opts.detail)
458
+ ? opts.detail.flatMap((d) => wrap(d, W - indent - 4).map((l, i) => (i === 0 ? l : ` ${l}`)))
459
+ : opts.detail ? wrap(opts.detail, W - indent - 2) : [])
460
+ .map((l) => `${pad} ${c.dim(l)}`);
461
+ const fix = opts.fix ?? [];
462
+ const labelWidth = fix.length ? Math.max(...fix.map(([label]) => visibleWidth(label))) + 3 : 0;
463
+ const fixes = fix.map(([label, command]) => `${pad} ${padEnd(label, labelWidth)}${c.accent(command)}`);
464
+ return [...head, ...details, ...fixes];
465
+ },
466
+ };
288
467
  }
289
468
 
290
- // ── interactive prompts ─────────────────────────────────────────────────────
291
- // A fresh readline per question. Long-lived readlines break when a subprocess
292
- // in between (e.g. the build step) inherits stdin, so we open/close per ask.
293
- // On EOF (piped input) the question resolves empty instead of throwing.
294
- async function ask(query: string): Promise<string> {
295
- const rl = createInterface({ input: process.stdin, output: process.stdout });
296
- // Ctrl-C during a text prompt: readline swallows SIGINT (emits it on the
297
- // interface). Handle it here — restore the cursor, drop a line, exit.
298
- rl.on("SIGINT", () => { process.stderr.write("\x1b[?25h"); process.stdout.write("\n"); process.exit(130); });
299
- try {
300
- // Resolve "" if the stream closes (EOF) so the caller falls back to its
301
- // default instead of hanging.
302
- return await new Promise<string>((resolve) => {
303
- rl.once("close", () => resolve(""));
304
- rl.question(query).then((a) => resolve(a.trim())).catch(() => resolve(""));
305
- });
306
- } finally {
307
- rl.close();
469
+ // ── prompts ─────────────────────────────────────────────────────────────────
470
+
471
+ /**
472
+ * A question was asked and the input ended before an answer came (stdin closed
473
+ * or redirected from /dev/null, Ctrl-D at the prompt).
474
+ *
475
+ * No answer is not an answer: it must never be read as "take the default"
476
+ * (`totem cloud < /dev/null` once said yes to every deploy gate). Every prompt
477
+ * throws this instead, and the command stops.
478
+ */
479
+ export class InputClosedError extends Error {
480
+ constructor(public readonly question: string) {
481
+ super("Input ended before the question was answered.");
482
+ this.name = "InputClosedError";
308
483
  }
309
484
  }
310
485
 
311
- // Kept for API compatibility; no-op now that prompts are per-call.
312
- export function closePrompts(): void {}
313
-
314
- export async function prompt(question: string, fallback = ""): Promise<string> {
315
- const suffix = fallback ? c.gray(` [${fallback}]`) : "";
316
- const answer = await ask(`${c.violet("?")} ${c.white(question)}${suffix}${c.gray(" ›")} `);
317
- return answer || fallback;
486
+ export interface Choice {
487
+ label: string;
488
+ hint?: string | undefined;
318
489
  }
319
490
 
320
- // Like `ask`, but typed characters are NOT echoed — standard password-prompt
321
- // behavior, so a secret never appears on screen (or on camera). The override
322
- // lets the prompt itself and the commit newline through and swallows every
323
- // per-character echo; readline still captures the full value in its buffer.
324
- async function askHidden(query: string): Promise<string> {
325
- // Explicit raw-mode read: readline's _writeToOutput trick doesn't reliably
326
- // disable the TERMINAL's own echo, so the secret can still render. Here we set
327
- // raw mode ourselves (terminal echo off), read char-by-char, and echo nothing
328
- // — the password never appears on screen. Falls back to a normal line read
329
- // when there's no TTY to put in raw mode (piped/CI).
491
+ // Piped input: ONE line reader per input stream for the life of the process.
492
+ // A readline opened per question reads ahead, so with several answers piped in
493
+ // at once the first question's reader swallowed the lines meant for the next.
494
+ interface PipedLines { lines: string[]; waiters: Array<(line: string | null) => void>; ended: boolean }
495
+ const pipedReaders = new WeakMap<object, PipedLines>();
496
+ function pipedLine(signal?: AbortSignal): Promise<string | null> {
330
497
  const stdin = process.stdin;
331
- if (!(stdin.isTTY && typeof stdin.setRawMode === "function")) return ask(query);
332
-
333
- process.stdout.write(query);
334
- return new Promise<string>((resolve) => {
335
- let buf = "";
336
- const cleanup = (): void => {
337
- stdin.removeListener("data", onData);
338
- try { stdin.setRawMode(false); } catch { /* */ }
339
- stdin.pause();
340
- };
341
- const onData = (chunk: string): void => {
342
- for (const ch of chunk) {
343
- if (ch === "\r" || ch === "\n" || ch === "\u0004") { cleanup(); process.stdout.write("\n"); resolve(buf.trim()); return; }
344
- if (ch === "\u0003") { cleanup(); process.stdout.write("\n"); process.exit(130); } // Ctrl-C
345
- if (ch === "\u007f" || ch === "\b") { buf = buf.slice(0, -1); continue; } // backspace
346
- if (ch >= " ") buf += ch; // printable: captured, not echoed
347
- }
348
- };
349
- stdin.setRawMode(true);
350
- stdin.resume();
351
- stdin.setEncoding("utf8");
352
- stdin.on("data", onData);
498
+ let state = pipedReaders.get(stdin);
499
+ if (!state) {
500
+ const fresh: PipedLines = { lines: [], waiters: [], ended: false };
501
+ const rl = createInterface({ input: stdin, terminal: false });
502
+ rl.on("line", (line) => { const w = fresh.waiters.shift(); if (w) w(line); else fresh.lines.push(line); });
503
+ rl.on("close", () => { fresh.ended = true; for (const w of fresh.waiters.splice(0)) w(null); });
504
+ pipedReaders.set(stdin, fresh);
505
+ state = fresh;
506
+ }
507
+ if (signal?.aborted) return Promise.resolve(null);
508
+ if (state.lines.length) return Promise.resolve(state.lines.shift()!);
509
+ if (state.ended) return Promise.resolve(null);
510
+ const waiting = state;
511
+ return new Promise((resolve) => {
512
+ // A withdrawn question gives up its place, so its line goes to the next one.
513
+ const take = (line: string | null): void => { signal?.removeEventListener("abort", drop); resolve(line); };
514
+ const drop = (): void => { const i = waiting.waiters.indexOf(take); if (i >= 0) waiting.waiters.splice(i, 1); resolve(null); };
515
+ waiting.waiters.push(take);
516
+ signal?.addEventListener("abort", drop, { once: true });
353
517
  });
354
518
  }
355
519
 
356
- // A masked prompt for secrets (the Whoop account password). Same look as
357
- // `prompt`, but nothing you type is shown.
358
- export async function promptHidden(question: string): Promise<string> {
359
- return askHidden(`${c.violet("?")} ${c.white(question)}${c.gray(" ›")} `);
520
+ /** A question taken back before anyone answered it (see Ui.confirmUntil). */
521
+ class Withdrawn extends Error {}
522
+
523
+ const SHOW_CURSOR = "\x1b[?25h";
524
+ const HIDE_CURSOR = "\x1b[?25l";
525
+ const CLEAR_LINE = "\r\x1b[2K";
526
+
527
+ // ── Ui: writes the primitives and asks the questions ─────────────────────────
528
+
529
+ export interface UiOptions {
530
+ style?: Style;
531
+ /** Where screens go. Default: stdout. */
532
+ write?: (text: string) => void;
533
+ /** Where top-level problems go. Default: stderr. */
534
+ writeErr?: (text: string) => void;
535
+ /** Animate spinners and menus (a real terminal on both ends). */
536
+ live?: boolean;
537
+ /** Someone can answer a question (stdin is a terminal). */
538
+ canAsk?: boolean;
539
+ now?: () => number;
360
540
  }
361
541
 
362
- // Enter — and ANY answer that isn't an explicit "no" — proceeds when `defaultYes`
363
- // is set. To decline you must actually type n / no / N / NO. (When `defaultYes`
364
- // is false it's the mirror: only an explicit y / yes proceeds.)
365
- export async function promptYesNo(question: string, defaultYes = true): Promise<boolean> {
366
- const hint = defaultYes ? `${c.green(c.bold("Y"))}${c.gray("/n")}` : `${c.gray("y/")}${c.red(c.bold("N"))}`;
367
- const answer = (await ask(`${c.violet("?")} ${c.white(question)} ${c.gray("(")}${hint}${c.gray(")")}${c.gray(" ›")} `)).trim().toLowerCase();
368
- if (defaultYes) return !/^(n|no)$/.test(answer);
369
- return /^(y|yes)$/.test(answer);
370
- }
542
+ export class Ui {
543
+ readonly style: Style;
544
+ readonly live: boolean;
545
+ readonly canAsk: boolean;
546
+ protected readonly write: (text: string) => void;
547
+ protected readonly writeErr: (text: string) => void;
548
+ protected readonly now: () => number;
549
+ readonly kit: Kit;
550
+
551
+ constructor(opts: UiOptions = {}) {
552
+ this.style = opts.style ?? detectStyle();
553
+ this.kit = kit(this.style);
554
+ this.write = opts.write ?? ((text) => { process.stdout.write(text); });
555
+ this.writeErr = opts.writeErr ?? ((text) => { process.stderr.write(text); });
556
+ this.live = opts.live ?? (Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY) && process.env.TERM !== "dumb");
557
+ this.canAsk = opts.canAsk ?? Boolean(process.stdin.isTTY);
558
+ this.now = opts.now ?? Date.now;
559
+ }
371
560
 
372
- // Numbered menu. Returns the 0-based index of the choice. Used as the non-TTY
373
- // fallback for select() (piped stdin can't do raw-mode arrow keys).
374
- export async function promptChoice(question: string, choices: string[]): Promise<number> {
375
- console.log(`${c.violet("?")} ${c.bold(c.white(question))}`);
376
- choices.forEach((ch, i) => console.log(` ${c.cyan(c.bold(String(i + 1)))}${c.gray(".")} ${ch}`));
377
- for (let attempts = 0; attempts < 100; attempts++) {
378
- const raw = await ask(` ${c.gray("enter a number")}: `);
379
- const n = parseInt(raw, 10);
380
- if (Number.isInteger(n) && n >= 1 && n <= choices.length) return n - 1;
381
- if (raw === "") return 0; // EOF / piped input → first choice (safe default)
382
- console.log(c.red(` Please enter 1-${choices.length}.`));
561
+ // output ────────────────────────────────────────────────────────────────
562
+ private blank = false;
563
+ /** One line. Two blank lines in a row become one, so primitives can each ask for air. */
564
+ line(text = ""): void {
565
+ if (text === "" && this.blank) return;
566
+ this.blank = text === "";
567
+ this.write(text + "\n");
568
+ }
569
+ lines(lines: string[]): void { for (const l of lines) this.line(l); }
570
+ /** The logo and a title, at the top of a big flow. */
571
+ banner(title: string, subtitle?: string, meta?: string): void { this.lines(["", ...this.kit.banner(title, subtitle, meta), ""]); }
572
+ header(title: string, subtitle?: string): void { this.lines(["", ...this.kit.header(title, subtitle), ""]); }
573
+ step(n: number, total: number, title: string): void { this.lines(["", ...this.kit.step(n, total, title)]); }
574
+ section(title: string): void { this.lines(["", ...this.kit.section(title)]); }
575
+ ok(text: string, detail?: string): void { this.lines(this.kit.mark("ok", text, detail)); }
576
+ warn(text: string, detail?: string): void { this.lines(this.kit.mark("warn", text, detail)); }
577
+ fail(text: string, detail?: string): void { this.lines(this.kit.mark("fail", text, detail)); }
578
+ info(text: string, detail?: string): void { this.lines(this.kit.mark("info", text, detail)); }
579
+ para(text: string, indent?: number): void { this.lines(this.kit.para(text, indent)); }
580
+ hint(text: string, indent?: number): void { this.lines(this.kit.hint(text, indent)); }
581
+ rows(pairs: Array<[string, string]>, indent?: number): void { this.lines(this.kit.rows(pairs, indent)); }
582
+ code(lines: string[], indent?: number): void { this.lines(this.kit.code(lines, indent)); }
583
+ /** "Next" and what to do now. */
584
+ next(lines: string[], title?: string): void { this.lines(["", ...this.kit.next(lines, title)]); }
585
+ /** What went wrong and how to fix it, inside a flow. */
586
+ problem(what: string, opts?: { detail?: string | string[] | undefined; fix?: Fix[] | undefined }): void {
587
+ this.lines(this.kit.problem(what, opts));
588
+ }
589
+ /** A problem that ends the command: goes to stderr. */
590
+ error(what: string, opts?: { detail?: string | string[] | undefined; fix?: Fix[] | undefined }): void {
591
+ for (const l of this.kit.problem(what, opts)) this.writeErr(l + "\n");
383
592
  }
384
- return 0;
385
- }
386
593
 
387
- // ── arrow-key selector ──────────────────────────────────────────────────────
388
- // Up/down (or j/k, or 1-9) to move, Enter to pick, Ctrl-C to cancel. Each choice
389
- // is a label with an optional dim hint. Returns the 0-based index. Falls back to
390
- // the numbered prompt when stdin/stdout isn't an interactive TTY (pipes, CI).
391
- export interface SelectChoice {
392
- label: string;
393
- hint?: string | undefined;
394
- }
594
+ // progress ──────────────────────────────────────────────────────────────
595
+ /**
596
+ * Run slow work under a spinner that counts the seconds, so a wait never
597
+ * looks like a hang. `set(detail)` shows the latest thing happening (the
598
+ * last line a subprocess printed). The spinner line disappears when the work
599
+ * ends; the caller then prints the result with ok()/fail().
600
+ *
601
+ * Without a terminal there is nothing to animate: `slow` work gets one
602
+ * plain "started" line so a log shows what it is waiting on.
603
+ */
604
+ async task<T>(label: string, work: (set: (detail: string) => void) => Promise<T>, opts: { slow?: boolean } = {}): Promise<T> {
605
+ const { g, c } = this.kit;
606
+ if (!this.live) {
607
+ if (opts.slow) this.lines(this.kit.mark("info", c.dim(label + g.ellipsis)));
608
+ return work(() => {});
609
+ }
610
+ const started = this.now();
611
+ let detail = "";
612
+ let frame = 0;
613
+ const draw = (): void => {
614
+ const ms = this.now() - started;
615
+ const clock = ms >= 3000 ? ` ${c.dim(`[${duration(ms)}]`)}` : "";
616
+ const head = `${c.ask(g.spinner[frame++ % g.spinner.length]!)} ${label}`;
617
+ const room = this.style.width - visibleWidth(head) - visibleWidth(clock) - 3;
618
+ const tail = detail && room > 8 ? ` ${c.dim(detail.length > room ? detail.slice(0, room - 1) + g.ellipsis : detail)}` : "";
619
+ this.write(`${CLEAR_LINE}${head}${tail}${clock}`);
620
+ };
621
+ this.write(HIDE_CURSOR);
622
+ draw();
623
+ const timer = setInterval(draw, 90);
624
+ try {
625
+ return await work((d) => { detail = stripVTControlCharacters(d).replace(/\s+/g, " ").trim(); });
626
+ } finally {
627
+ clearInterval(timer);
628
+ this.write(`${CLEAR_LINE}${SHOW_CURSOR}`);
629
+ }
630
+ }
395
631
 
396
- export async function select(
397
- question: string,
398
- choices: Array<string | SelectChoice>,
399
- opts: { defaultIndex?: number } = {},
400
- ): Promise<number> {
401
- const items = choices.map((ch) => (typeof ch === "string" ? { label: ch } : ch));
402
- const stdin = process.stdin;
403
- const interactive = Boolean(stdin.isTTY) && Boolean(process.stdout.isTTY) && typeof stdin.setRawMode === "function";
404
- if (!interactive) {
405
- return promptChoice(question, items.map((it) => (it.hint ? `${it.label} ${c.gray(it.hint)}` : it.label)));
632
+ // prompts ───────────────────────────────────────────────────────────────
633
+ /** One line of input, or InputClosedError when the input ended instead. */
634
+ protected async answer(query: string, question: string, signal?: AbortSignal): Promise<string> {
635
+ let line: string | null;
636
+ if (!process.stdin.isTTY) {
637
+ this.write(query);
638
+ line = await pipedLine(signal);
639
+ this.write("\n");
640
+ if (signal?.aborted) throw new Withdrawn();
641
+ } else {
642
+ // A fresh readline per question: a long-lived one breaks when a
643
+ // subprocess in between (a login, a build) inherits stdin.
644
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
645
+ // readline swallows Ctrl-C; turn it back into a clean exit.
646
+ rl.on("SIGINT", () => { process.stdout.write(`${SHOW_CURSOR}\n`); process.exit(130); });
647
+ try {
648
+ line = await new Promise<string | null>((resolve) => {
649
+ rl.once("close", () => resolve(null));
650
+ rl.question(query, signal ? { signal } : {}).then(resolve).catch(() => resolve(null));
651
+ });
652
+ } finally {
653
+ rl.close();
654
+ }
655
+ // Taken back: the question leaves the screen, as if never asked.
656
+ if (signal?.aborted) { this.write(CLEAR_LINE); throw new Withdrawn(); }
657
+ }
658
+ this.blank = false;
659
+ if (line === null) throw new InputClosedError(question);
660
+ return line.trim();
406
661
  }
407
662
 
408
- let idx = Math.min(Math.max(opts.defaultIndex ?? 0, 0), items.length - 1);
409
-
410
- const render = (first: boolean): void => {
411
- if (!first) process.stdout.write(`\x1b[${items.length + 1}A`); // back up to the question line
412
- process.stdout.write(`\r\x1b[2K${c.violet("?")} ${c.bold(c.white(question))} ${c.dim("↑/↓ · enter")}\n`);
413
- items.forEach((it, i) => {
414
- const selected = i === idx;
415
- const pointer = selected ? c.cyan("❯") : " ";
416
- const label = selected ? c.bold(c.cyan(it.label)) : c.white(it.label);
417
- const hint = it.hint ? " " + c.dim(it.hint) : "";
418
- process.stdout.write(`\r\x1b[2K ${pointer} ${label}${hint}\n`);
419
- });
420
- };
663
+ protected q(question: string, suffix = ""): string {
664
+ return this.kit.question(question, suffix);
665
+ }
666
+
667
+ /**
668
+ * Yes or no. Enter takes the default; y/yes and n/no are the only other
669
+ * answers. Anything else is asked again, then counts as no: a stray key is
670
+ * not consent.
671
+ */
672
+ async confirm(question: string, defaultYes = true): Promise<boolean> {
673
+ return this.yesNo(question, defaultYes);
674
+ }
675
+
676
+ /**
677
+ * confirm(), unless `until` aborts first: something else settled it while
678
+ * totem was still asking (a sign-in finished from a link pasted elsewhere).
679
+ * Then the question leaves the screen and the answer is null.
680
+ */
681
+ async confirmUntil(question: string, until: AbortSignal, defaultYes = true): Promise<boolean | null> {
682
+ try {
683
+ return await this.yesNo(question, defaultYes, until);
684
+ } catch (error) {
685
+ if (error instanceof Withdrawn) return null;
686
+ throw error;
687
+ }
688
+ }
421
689
 
422
- render(true);
423
- process.stdout.write("\x1b[?25l"); // hide the blinking cursor while the menu is active
424
- stdin.setRawMode(true);
425
- stdin.resume();
426
- stdin.setEncoding("utf8");
690
+ private async yesNo(question: string, defaultYes: boolean, signal?: AbortSignal): Promise<boolean> {
691
+ for (let attempt = 0; attempt < 3; attempt++) {
692
+ const a = (await this.answer(`${this.q(question, defaultYes ? "(Y/n)" : "(y/N)")} `, question, signal)).toLowerCase();
693
+ if (a === "") return defaultYes;
694
+ if (a === "y" || a === "yes") return true;
695
+ if (a === "n" || a === "no") return false;
696
+ this.hint("Answer y or n.");
697
+ }
698
+ return false;
699
+ }
700
+
701
+ /** Free text; Enter takes `fallback`. */
702
+ async text(question: string, fallback = ""): Promise<string> {
703
+ const a = await this.answer(`${this.q(question, fallback ? `(${fallback})` : "")}${this.kit.c.dim(":")} `, question);
704
+ return a || fallback;
705
+ }
427
706
 
428
- const n = items.length;
429
- return new Promise<number>((resolveSel) => {
430
- const cleanup = (): void => {
431
- stdin.setRawMode(false);
707
+ /**
708
+ * A secret: nothing typed is shown, and nothing is trimmed. Readline does the
709
+ * editing (paste markers, backspace, Ctrl-U) on a muted stream, so not even
710
+ * its redraws reach the screen. Answers "" when the input ends.
711
+ */
712
+ async hidden(question: string): Promise<string> {
713
+ const query = `${this.q(question, "(hidden)")}${this.kit.c.dim(":")} `;
714
+ const stdin = process.stdin;
715
+ this.blank = false;
716
+ if (!stdin.isTTY) {
717
+ this.write(query);
718
+ const line = await pipedLine();
719
+ this.write("\n");
720
+ return line ?? "";
721
+ }
722
+ const wasRaw = stdin.isRaw;
723
+ const muted = new Writable({ write(_chunk, _encoding, done) { done(); } });
724
+ const rl = createInterface({ input: stdin, output: muted, terminal: true });
725
+ rl.on("SIGINT", () => { rl.close(); process.stdout.write("\n"); process.exit(130); });
726
+ this.write(query);
727
+ try {
728
+ return await new Promise<string>((resolve) => {
729
+ rl.once("close", () => resolve(""));
730
+ rl.question("").then(resolve).catch(() => resolve(""));
731
+ });
732
+ } finally {
733
+ rl.close();
734
+ if (typeof stdin.setRawMode === "function") stdin.setRawMode(Boolean(wasRaw));
432
735
  stdin.pause();
433
- stdin.removeListener("data", onData);
434
- process.stdout.write("\x1b[?25h"); // restore the cursor once a choice is made
435
- };
436
- // Scan the chunk left-to-right rather than exact-matching the whole thing:
437
- // a single read can batch several bytes (a paste, a fast double-press, or a
438
- // terminal/PTY that delivers the arrow sequence and the Enter together like
439
- // "\x1b[B\r"). Incomplete escape sequences at a chunk boundary are stashed in
440
- // `pending` and prepended to the next read so a split "\x1b" + "[B" still works.
441
- let pending = "";
442
- const onData = (raw: string): void => {
443
- const chunk = pending + raw;
444
- pending = "";
445
- if (chunk.includes("\x03")) { cleanup(); process.stdout.write("\n"); process.exit(130); }
446
- let moved = false;
447
- let i = 0;
448
- while (i < chunk.length) {
449
- const rest = chunk.slice(i);
450
- const ch = rest[0]!;
451
- if (ch === "\r" || ch === "\n") { cleanup(); if (moved) render(false); resolveSel(idx); return; }
452
- if (ch === "\x1b") {
453
- if (rest === "\x1b" || rest === "\x1b[") { pending = rest; break; } // incomplete — wait for more
454
- if (rest.startsWith("\x1b[A")) { idx = (idx - 1 + n) % n; moved = true; i += 3; continue; }
455
- if (rest.startsWith("\x1b[B")) { idx = (idx + 1) % n; moved = true; i += 3; continue; }
456
- i += rest.length >= 3 ? 3 : rest.length; continue; // unknown escape — skip it
457
- }
458
- if (ch === "k") { idx = (idx - 1 + n) % n; moved = true; }
459
- else if (ch === "j") { idx = (idx + 1) % n; moved = true; }
460
- else if (/[1-9]/.test(ch)) { const x = parseInt(ch, 10) - 1; if (x < n) { idx = x; moved = true; } }
461
- i += 1;
462
- }
463
- if (moved) render(false);
464
- };
465
- stdin.on("data", onData);
466
- });
467
- }
736
+ muted.end();
737
+ this.write("\n");
738
+ }
739
+ }
468
740
 
469
- // ── confirmation for sensitive actions ──────────────────────────────────────
470
- // A loud, explicit y/n gate for anything that mutates cloud state, spends money,
471
- // or changes permissions. Shows exactly what will run + why, so the user is
472
- // giving informed consent rather than watching it happen.
473
- export interface ConfirmOpts {
474
- detail?: string; // one-line consequence ("grants build access to …")
475
- cmd?: string; // the exact command we're about to run
476
- defaultYes?: boolean; // Enter = proceed (true) vs Enter = decline (false)
477
- }
741
+ /** The menu as it looks with `selected` chosen: what stays on screen after a choice. */
742
+ menu(question: string, choices: Choice[], selected: number, active = false): string[] {
743
+ const { c, g } = this.kit;
744
+ const labelWidth = Math.max(...choices.map((ch) => visibleWidth(ch.label))) + 3;
745
+ const room = this.style.width - 4 - labelWidth;
746
+ return [
747
+ this.q(question, active ? `(${this.style.unicode ? "↑↓" : "up/down"}, Enter)` : ""),
748
+ ...choices.map((ch, i) => {
749
+ const on = i === selected;
750
+ const hint = ch.hint && room >= 12 ? c.dim(ch.hint.length > room ? ch.hint.slice(0, room - 1) + g.ellipsis : ch.hint) : "";
751
+ const label = hint ? padEnd(ch.label, labelWidth) : ch.label;
752
+ return ` ${on ? c.ask(g.pointer) : " "} ${on ? c.ask(label) : label}${hint}`;
753
+ }),
754
+ ];
755
+ }
756
+
757
+ /**
758
+ * Pick one. On a terminal: arrows (or j/k, or a digit) move, Enter chooses.
759
+ * Piped: a numbered list, answered with a number (Enter = the default).
760
+ * Returns the index.
761
+ */
762
+ async select(question: string, choices: Choice[], defaultIndex = 0): Promise<number> {
763
+ const n = choices.length;
764
+ let idx = Math.min(Math.max(defaultIndex, 0), n - 1);
765
+ const stdin = process.stdin;
766
+ if (!this.live || typeof stdin.setRawMode !== "function") {
767
+ const { c } = this.kit;
768
+ const labelWidth = Math.max(...choices.map((ch) => visibleWidth(ch.label))) + 3;
769
+ this.line(this.q(question));
770
+ choices.forEach((ch, i) => this.line(` ${c.ask(String(i + 1))}. ${ch.hint ? padEnd(ch.label, labelWidth) + c.dim(ch.hint) : ch.label}`));
771
+ for (let attempt = 0; attempt < 3; attempt++) {
772
+ const raw = await this.answer(` ${c.dim(`Number (${idx + 1}):`)} `, question);
773
+ if (raw === "") return idx;
774
+ const picked = Number(raw);
775
+ if (Number.isInteger(picked) && picked >= 1 && picked <= n) return picked - 1;
776
+ this.hint(`Enter a number from 1 to ${n}.`);
777
+ }
778
+ throw new InputClosedError(question);
779
+ }
478
780
 
479
- export async function confirmStep(summary: string, opts: ConfirmOpts = {}): Promise<boolean> {
480
- console.log(` ${c.yellow("⚠")} ${c.bold(c.white(summary))}`);
481
- if (opts.detail) console.log(` ${c.gray(opts.detail)}`);
482
- if (opts.cmd) console.log(` ${c.dim("$")} ${c.cyan(opts.cmd)}`);
483
- return promptYesNo(" Proceed?", opts.defaultYes ?? true);
781
+ const render = (first: boolean, active: boolean): void => {
782
+ if (!first) this.write(`\x1b[${n + 1}A`);
783
+ for (const l of this.menu(question, choices, idx, active)) this.write(`${CLEAR_LINE}${l}\n`);
784
+ };
785
+ render(true, true);
786
+ this.blank = false;
787
+ this.write(HIDE_CURSOR);
788
+ stdin.setRawMode(true);
789
+ stdin.resume();
790
+ stdin.setEncoding("utf8");
791
+ return new Promise<number>((resolve) => {
792
+ const cleanup = (): void => {
793
+ stdin.setRawMode(false);
794
+ stdin.pause();
795
+ stdin.removeListener("data", onData);
796
+ this.write(SHOW_CURSOR);
797
+ };
798
+ // Scan each chunk left to right: one read can carry several keys (a fast
799
+ // double press, or an arrow and Enter together), and an escape sequence
800
+ // can be split across two reads.
801
+ let pending = "";
802
+ const onData = (raw: string): void => {
803
+ const chunk = pending + raw;
804
+ pending = "";
805
+ if (chunk.includes("\x03")) { cleanup(); this.write("\n"); process.exit(130); }
806
+ if (chunk.includes("\x04")) { cleanup(); this.write("\n"); process.exit(130); }
807
+ let i = 0;
808
+ while (i < chunk.length) {
809
+ const rest = chunk.slice(i);
810
+ const ch = rest[0]!;
811
+ if (ch === "\r" || ch === "\n") {
812
+ // The menu folds into one line: the question and what was chosen.
813
+ cleanup();
814
+ this.write(`\x1b[${n + 1}A`);
815
+ for (let k = 0; k <= n; k++) this.write(`${CLEAR_LINE}\n`);
816
+ this.write(`\x1b[${n + 1}A${CLEAR_LINE}${this.kit.answered(question, choices[idx]!.label)}\n`);
817
+ resolve(idx);
818
+ return;
819
+ }
820
+ if (ch === "\x1b") {
821
+ if (rest === "\x1b" || rest === "\x1b[") { pending = rest; break; }
822
+ if (rest.startsWith("\x1b[A")) { idx = (idx - 1 + n) % n; i += 3; continue; }
823
+ if (rest.startsWith("\x1b[B")) { idx = (idx + 1) % n; i += 3; continue; }
824
+ i += Math.min(rest.length, 3);
825
+ continue;
826
+ }
827
+ if (ch === "k") idx = (idx - 1 + n) % n;
828
+ else if (ch === "j") idx = (idx + 1) % n;
829
+ else if (/[1-9]/.test(ch) && Number(ch) <= n) idx = Number(ch) - 1;
830
+ i += 1;
831
+ }
832
+ render(false, true);
833
+ };
834
+ stdin.on("data", onData);
835
+ });
836
+ }
484
837
  }
485
838
 
486
- // Redact secret values when echoing a command so tokens/passwords never hit the
487
- // screen or scrollback. Masks the value of any KEY=value whose key looks
488
- // sensitive (or whose value is long enough to be a token).
489
- export function maskArgs(args: string[]): string {
839
+ /** Mask the value of any KEY=value whose key names a secret, for showing a command. */
840
+ export function maskSecrets(args: string[]): string {
490
841
  return args
491
842
  .map((a) => {
492
843
  const eq = a.indexOf("=");
493
- if (eq <= 0) return a;
494
- const key = a.slice(0, eq);
495
- if (/(_?TOKEN|PASSWORD|_SECRET|BEARER|REFRESH|EMAIL)/i.test(key)) return `${key}=${c.dim("•••")}`;
496
- return a;
844
+ return eq > 0 && /(TOKEN|PASSWORD|SECRET|BEARER|REFRESH)/i.test(a.slice(0, eq)) ? `${a.slice(0, eq)}=***` : a;
497
845
  })
498
846
  .join(" ");
499
847
  }
500
-
501
- // Section header for the guided flows — a violet rule + step counter + title.
502
- export function step(n: number, total: number, title: string): void {
503
- console.log("");
504
- console.log(`${c.violet("▌")} ${c.violet(c.bold(`${n}/${total}`))} ${c.bold(c.white(title))}`);
505
- }