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