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