@trainheroic-unofficial/core 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +87 -149
  2. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { blockSpecSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSetArgsSchema, parseWorkoutDate } from "@trainheroic-unofficial/dto";
1
+ import { blockSpecSchema, coachLogSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSetArgsSchema, parseWorkoutDate } from "@trainheroic-unofficial/dto";
2
2
  import { z } from "zod";
3
- import { addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, isRecord, logAthleteSet, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, publishSession, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment, summarizeAthleteWorkouts } from "@trainheroic-unofficial/js";
3
+ import { ANALYTICS_METRIC_KEYS, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, inviteAthletes, isRecord, logAthleteSet, logForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, publishSession, queryAnalytics, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment, summarizeAthleteWorkouts } from "@trainheroic-unofficial/js";
4
4
  //#region src/context.ts
5
5
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
6
6
  const idParam = idArgSchema;
@@ -222,6 +222,7 @@ function historyInRange(presented, since, until) {
222
222
  //#endregion
223
223
  //#region src/tools/reads.ts
224
224
  const ATHLETE_LIFT_HISTORY_DESC = "A roster athlete's lift history for ONE exercise: the all-time PR board (liftPRs — each entry carries its rep-max label, weight, and the date it was set) plus the dated session series (sets, estimated 1RM). This is the coach-side way to answer 'show me <athlete>'s PRs / how is <athlete>'s squat trending' — pass athleteId from list_athletes and exerciseId from exercise_resolve. There is no cross-exercise PR rollup, so you query one lift at a time, but do NOT guess lift names blindly: first call athlete_training for the month(s) of interest — it lists every exercise the athlete actually performed (with the exact exercise the program used, e.g. 'Clean & Jerk' not 'Clean') — then bring those exerciseIds here. An empty result means that lift was not logged. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
225
+ const ROSTER_ACTIVITY_DESC = "A coach's roster ranked by actual training recency: for each athleteId you pass (from list_athletes), the all-time sessionsCount, firstLoggedDate, lastLoggedDate, totalReps and totalVolume, sorted most-recently-active first. Use lastLoggedDate — the real training signal — NOT list_athletes' daysSinceLastLogin (app-login, not training) to answer 'who is my most recently active athlete' (the top row) or 'who is falling behind' (a stale or null lastLoggedDate, or low volume). A null lastLoggedDate means the athlete has never logged a session. This fans out one lookup per athlete, so for a large org pass only the athletes you care about. Then drill into a name with athlete_training (their month) or athlete_lift_history.";
225
226
  const ATHLETE_TRAINING_DESC = "A roster athlete's training for one calendar month (coach-side): one row per session with its title, the `logged` flag (the reliable did-they-train signal — true means they logged it), rpe, duration (minutes), notes, and the exercises they performed, each with a set summary like '5 x 2 @ 205 lb'. Use this to answer 'how has <athlete> been training lately' in ONE call, and as the discovery handle a coach otherwise lacks: read the exercise titles here to learn what the athlete actually did, then pass the lifts you care about to athlete_lift_history for their dated PR board. Pass athleteId from list_athletes and a year + month (1-12); query the current month, and the previous month for more history. Sessions are in calendar order within the month (the API carries no per-session date). An empty list means no sessions that month.";
226
227
  function enc(value) {
227
228
  return encodeURIComponent(String(value));
@@ -269,7 +270,7 @@ function registerRosterReads(server, ctx) {
269
270
  }, () => apiCall(ctx, "GET", t.path));
270
271
  server.registerTool("list_athletes", {
271
272
  title: "List athletes",
272
- description: "Every athlete on this coach's org roster, across all teams (not scoped to one team; the account owner themselves and demo/placeholder athletes are included, so the roster count includes you). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. For per-team attribution use each athlete's own `groups`/`groupTitles` (the teams they are enrolled in) and `teamCount`; there is no per-team roster endpoint or other per-athlete team field. Optional q (case-insensitive; each whitespace-separated word must appear in the record, so 'Kyle Jones' matches a 'Jones, [Demo] Kyle' entry) and limit, applied client-side, keep large rosters small.",
273
+ description: "Every athlete on this coach's org roster, across all teams (not scoped to one team; the account owner themselves and demo/placeholder athletes are included, so the roster count includes you). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. For per-team attribution use each athlete's own `groups`/`groupTitles` (the teams they are enrolled in) and `teamCount`; there is no per-team roster endpoint or other per-athlete team field. To rank athletes by real training recency (most recently active, or who is falling behind), pass their ids to roster_activity instead of reading daysSinceLastLogin. Optional q (case-insensitive; each whitespace-separated word must appear in the record, so 'Kyle Jones' matches a 'Jones, [Demo] Kyle' entry) and limit, applied client-side, keep large rosters small.",
273
274
  inputSchema: {
274
275
  q: z.string().optional(),
275
276
  limit: z.number().int().positive().max(500).optional()
@@ -347,6 +348,15 @@ function registerEntityReads(server, ctx) {
347
348
  if (raw === true) return jsonResult(detail);
348
349
  return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
349
350
  }));
351
+ server.registerTool("roster_activity", {
352
+ title: "Roster training activity (recency)",
353
+ description: ROSTER_ACTIVITY_DESC,
354
+ inputSchema: {
355
+ athleteIds: z.array(idParam).min(1),
356
+ useMetric: z.boolean().optional()
357
+ },
358
+ annotations: READ
359
+ }, ({ athleteIds, useMetric }) => attempt(async () => jsonResult(await fetchRosterActivity(ctx.client, athleteIds.map(toId), useMetric ?? false), { hint: "Sorted most-recently-active first; lastLoggedDate null = never logged. The top row is the most recently active athlete." })));
350
360
  server.registerTool("athlete_training", {
351
361
  title: "Athlete training month (roster)",
352
362
  description: ATHLETE_TRAINING_DESC,
@@ -592,7 +602,6 @@ function registerAthleteTrainingTools(server, ctx) {
592
602
  }
593
603
  //#endregion
594
604
  //#region src/tools/athletes.ts
595
- const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
596
605
  /** Normalize one-or-many emails into a deduped, trimmed list. */
597
606
  function asEmailList(emails) {
598
607
  return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -620,28 +629,14 @@ function registerAthleteTools(server, ctx) {
620
629
  if (list.length === 0) return errorResult("Provide at least one email address to invite.");
621
630
  const id = toId(teamId);
622
631
  if (!await confirmGate(server, extra.requestId, `Invite ${list.join(", ")} to team ${id}? This emails them a real TrainHeroic invitation.`, confirm)) return errorResult(NOT_CONFIRMED);
623
- const validation = await ctx.client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
624
- if (!validation.ok) {
625
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
626
- return errorResult(`Email validation failed (HTTP ${validation.status}): ${detail}`);
627
- }
628
- const valid = Array.isArray(validation.data) ? validation.data : list;
629
- if (valid.length === 0) return errorResult(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
630
- const invite = await ctx.client.request("POST", "/v5/athletes/inviteToTeam", { body: {
631
- teamType: 0,
632
- teamId: id,
633
- orgId: null,
634
- emails: valid,
635
- message: message ?? DEFAULT_INVITE_MESSAGE
636
- } });
637
- if (!invite.ok) {
638
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
639
- return errorResult(`Invite failed (HTTP ${invite.status}): ${detail}`);
640
- }
641
632
  return jsonResult({
642
633
  invited: true,
643
634
  teamId: id,
644
- result: invite.data
635
+ result: (await inviteAthletes(ctx.client, definedProps({
636
+ teamId: id,
637
+ emails: list,
638
+ message
639
+ }))).result
645
640
  });
646
641
  }));
647
642
  server.registerTool("athlete_archive", {
@@ -668,6 +663,57 @@ function registerAthleteTools(server, ctx) {
668
663
  openWorldHint: true
669
664
  }
670
665
  }, ({ athleteIds }) => apiCall(ctx, "PUT", "/v5/athletes/restore", { body: { athleteIds: athleteIds.map(toId) } }));
666
+ registerAthleteLogTools(server, ctx);
667
+ }
668
+ /**
669
+ * Coach "Log for Athlete": read a roster athlete's saved workouts (to get the log ids), then
670
+ * record set results on their behalf. The write is the API equivalent of the app's mobile
671
+ * "Log for Athlete" flow. Kept in its own function so registerAthleteTools stays under the
672
+ * oxlint max-lines-per-function cap.
673
+ */
674
+ function registerAthleteLogTools(server, ctx) {
675
+ server.registerTool("athlete_saved_workouts", {
676
+ title: "Roster athlete's saved workouts (with log ids)",
677
+ description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window — the coach-side view that carries the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set needs. Get athleteId from list_athletes. Defaults to a presented view; set raw:true for the untouched API objects that expose those ids (each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId). athlete_training gives a whole-month overview but not these ids.",
678
+ inputSchema: {
679
+ athleteId: idParam,
680
+ startDate: dateString,
681
+ endDate: dateString,
682
+ raw: z.boolean().optional()
683
+ },
684
+ annotations: READ
685
+ }, ({ athleteId, startDate, endDate, raw }) => attempt(async () => {
686
+ const workouts = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate);
687
+ if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. Pass both to log_athlete_set. Narrow the dates to shrink this." });
688
+ return jsonResult(presentAthleteWorkouts(workouts), { hint: "Set raw:true to get savedWorkoutSetId + savedWorkoutSetExerciseId for log_athlete_set." });
689
+ }));
690
+ server.registerTool("log_athlete_set", {
691
+ title: "Log set results for a roster athlete",
692
+ description: "Coach-facing write: record entered results (reps/weight per set) for one of a roster athlete's saved workout sets on a given day, marking the set completed — the API equivalent of the app's \"Log for Athlete\". Writes to that athlete's training log and shows in their history. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
693
+ inputSchema: {
694
+ ...coachLogSetArgsSchema.shape,
695
+ confirm: z.boolean().optional()
696
+ },
697
+ annotations: DESTRUCTIVE
698
+ }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
699
+ const aId = toId(athleteId);
700
+ if (!await confirmGate(server, extra.requestId, `Log results to athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
701
+ const mapped = results.map((r) => ({
702
+ savedWorkoutSetExerciseId: toId(r.savedWorkoutSetExerciseId),
703
+ sets: r.sets.map((s) => {
704
+ const slot = {};
705
+ if (s.param1 !== void 0) slot.param1 = s.param1;
706
+ if (s.param2 !== void 0) slot.param2 = s.param2;
707
+ return slot;
708
+ })
709
+ }));
710
+ return jsonResult(await logForAthlete(ctx.client, {
711
+ athleteId: aId,
712
+ date,
713
+ savedWorkoutSetId: toId(savedWorkoutSetId),
714
+ results: mapped
715
+ }));
716
+ }));
671
717
  }
672
718
  //#endregion
673
719
  //#region src/tools/teams.ts
@@ -734,95 +780,14 @@ function registerTeamTools(server, ctx) {
734
780
  }
735
781
  //#endregion
736
782
  //#region src/tools/analytics.ts
737
- const METRIC_KEYS = [
738
- "readiness-team",
739
- "readiness-athlete",
740
- "lift-1rm-history",
741
- "training-summary-athlete",
742
- "compliance-team",
743
- "lift-progress-team",
744
- "working-max-history"
745
- ];
746
- const METRICS = {
747
- "readiness-team": {
748
- path: "/v5/analytics/readiness/teams",
749
- scope: "team",
750
- inputs: ["date"],
751
- requires: ["date"]
752
- },
753
- "readiness-athlete": {
754
- path: "/v5/analytics/readiness/users",
755
- scope: "user",
756
- inputs: ["dateStart", "dateEnd"],
757
- requires: ["dateStart", "dateEnd"]
758
- },
759
- "lift-1rm-history": {
760
- path: "/v5/analytics/lift-one-rep-max-history/users",
761
- scope: "user",
762
- inputs: [
763
- "dateStart",
764
- "dateEnd",
765
- "exerciseId",
766
- "useMetric"
767
- ],
768
- requires: [
769
- "dateStart",
770
- "dateEnd",
771
- "exerciseId"
772
- ]
773
- },
774
- "training-summary-athlete": {
775
- path: "/v5/analytics/training-summary/users",
776
- scope: "user",
777
- inputs: ["dateStart", "dateEnd"],
778
- requires: ["dateStart", "dateEnd"]
779
- },
780
- "compliance-team": {
781
- path: "/v5/analytics/compliance",
782
- scope: "team",
783
- inputs: ["dateStart", "dateEnd"],
784
- requires: ["dateStart", "dateEnd"]
785
- },
786
- "lift-progress-team": {
787
- path: "/v5/analytics/lift-progress/teams",
788
- scope: "team",
789
- inputs: [
790
- "exerciseId",
791
- "dateStart",
792
- "dateEnd"
793
- ],
794
- requires: [
795
- "exerciseId",
796
- "dateStart",
797
- "dateEnd"
798
- ]
799
- },
800
- "working-max-history": {
801
- path: "/v5/analytics/working-max-history/users",
802
- scope: "user",
803
- inputs: [
804
- "exerciseId",
805
- "dateStart",
806
- "dateEnd",
807
- "useMetric"
808
- ],
809
- requires: ["exerciseId"]
810
- }
811
- };
812
- const BODY_KEY = {
813
- date: "date",
814
- dateStart: "date_start",
815
- dateEnd: "date_end",
816
- exerciseId: "exercise_id",
817
- useMetric: "use_metric"
818
- };
783
+ const ANALYTICS_QUERY_DESC = "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). Use that for triage: training-summary-athlete with a single athleteId is the fastest 'has this athlete trained at all, and when' check — no rows means no logged training in range, so don't then fan out blind per-lift athlete_lift_history calls. Despite 'athlete' in the name this metric accepts 1–N userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.";
819
784
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
820
785
  function registerAnalyticsTools(server, ctx) {
821
786
  server.registerTool("analytics_query", {
822
787
  title: "Pull an analytics report",
823
- description: "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). Use that for triage: training-summary-athlete with a single athleteId is the fastest 'has this athlete trained at all, and when' check — no rows means no logged training in range, so don't then fan out blind per-lift athlete_lift_history calls. Despite 'athlete' in the name this metric accepts 1–N userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.",
788
+ description: ANALYTICS_QUERY_DESC,
824
789
  inputSchema: {
825
- metric: z.enum(METRIC_KEYS),
790
+ metric: z.enum(ANALYTICS_METRIC_KEYS),
826
791
  teamId: idParam.optional(),
827
792
  userIds: z.array(idParam).optional(),
828
793
  exerciseId: idParam.optional(),
@@ -832,32 +797,16 @@ function registerAnalyticsTools(server, ctx) {
832
797
  useMetric: z.boolean().optional()
833
798
  },
834
799
  annotations: READ
835
- }, async ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => {
836
- const spec = METRICS[metric];
837
- const inputs = {
838
- date,
839
- dateStart,
840
- dateEnd,
841
- exerciseId,
842
- useMetric
843
- };
844
- const body = {};
845
- if (spec.scope === "team") {
846
- if (teamId === void 0) return errorResult(`${metric} needs teamId.`);
847
- body.teamId = toId(teamId);
848
- } else {
849
- if (userIds === void 0 || userIds.length === 0) return errorResult(`${metric} needs userIds (one or more athlete ids).`);
850
- body.user_ids = userIds.map((u) => String(toId(u)));
851
- }
852
- const missing = spec.requires.filter((k) => inputs[k] === void 0);
853
- if (missing.length > 0) return errorResult(`${metric} also needs: ${missing.join(", ")}.`);
854
- for (const k of spec.inputs) {
855
- const v = inputs[k];
856
- if (v === void 0) continue;
857
- body[BODY_KEY[k]] = k === "exerciseId" ? String(toId(v)) : v;
858
- }
859
- return apiCall(ctx, "POST", spec.path, { body }, "Narrow with a tighter date range or fewer athletes.");
860
- });
800
+ }, ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => attempt(async () => jsonResult(await queryAnalytics(ctx.client, definedProps({
801
+ metric,
802
+ teamId: teamId !== void 0 ? toId(teamId) : void 0,
803
+ userIds: userIds?.map(toId),
804
+ exerciseId: exerciseId !== void 0 ? toId(exerciseId) : void 0,
805
+ date,
806
+ dateStart,
807
+ dateEnd,
808
+ useMetric
809
+ })), { hint: "Narrow with a tighter date range or fewer athletes." })));
861
810
  }
862
811
  //#endregion
863
812
  //#region src/tools/exercises.ts
@@ -1058,22 +1007,11 @@ function registerLifecycle(server, ctx) {
1058
1007
  destructiveHint: false,
1059
1008
  openWorldHint: true
1060
1009
  }
1061
- }, ({ toProgramId, pwId, toDate }) => attempt(async () => {
1062
- const [year, month, day] = parseWorkoutDate(toDate);
1063
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1064
- return apiCall(ctx, "POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1065
- toProgramId,
1066
- pwId,
1067
- toDate: {
1068
- date: `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`,
1069
- day,
1070
- month,
1071
- year,
1072
- dayOfWeek,
1073
- isToday: false
1074
- }
1075
- } });
1076
- }));
1010
+ }, ({ toProgramId, pwId, toDate }) => attempt(async () => jsonResult(await copySession(ctx.client, {
1011
+ toProgramId,
1012
+ pwId,
1013
+ toDate
1014
+ }))));
1077
1015
  server.registerTool("session_save_as_template", {
1078
1016
  title: "Save a session to the library",
1079
1017
  description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/core",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  "@cfworker/json-schema": "^4.1.1",
26
26
  "@modelcontextprotocol/sdk": "^1.29.0",
27
27
  "zod": "^4.4.3",
28
- "@trainheroic-unofficial/dto": "0.6.3",
29
- "@trainheroic-unofficial/js": "0.6.3"
28
+ "@trainheroic-unofficial/dto": "0.6.5",
29
+ "@trainheroic-unofficial/js": "0.6.5"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.0.0",