@trainheroic-unofficial/core 0.6.2 → 0.6.3

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 +41 -19
  2. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { blockSpecSchema, 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, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, isRecord, logAthleteSet, presentAthleteWorkouts, presentExerciseHistory, publishSession, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment } from "@trainheroic-unofficial/js";
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";
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;
@@ -221,7 +221,8 @@ function historyInRange(presented, since, until) {
221
221
  }
222
222
  //#endregion
223
223
  //#region src/tools/reads.ts
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 summary, so query each lift you care about (squat, bench, deadlift, …) and an empty result just means the athlete has not logged that lift. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
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 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.";
225
226
  function enc(value) {
226
227
  return encodeURIComponent(String(value));
227
228
  }
@@ -268,7 +269,7 @@ function registerRosterReads(server, ctx) {
268
269
  }, () => apiCall(ctx, "GET", t.path));
269
270
  server.registerTool("list_athletes", {
270
271
  title: "List athletes",
271
- description: "Every athlete on this coach's org roster, across all teams (not scoped to one team, and demo/placeholder athletes are included). `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. There is no per-athlete team field here, so to attribute athletes to a team use the team's roster. Optional q (case-insensitive substring filter over each athlete record) and limit, applied client-side, to keep large rosters small.",
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.",
272
273
  inputSchema: {
273
274
  q: z.string().optional(),
274
275
  limit: z.number().int().positive().max(500).optional()
@@ -283,8 +284,11 @@ function registerRosterReads(server, ctx) {
283
284
  if (!Array.isArray(res.data)) return jsonResult(res.data);
284
285
  let rows = res.data;
285
286
  if (q !== void 0) {
286
- const needle = q.toLowerCase();
287
- rows = rows.filter((row) => JSON.stringify(row).toLowerCase().includes(needle));
287
+ const needles = q.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
288
+ rows = rows.filter((row) => {
289
+ const hay = JSON.stringify(row).toLowerCase();
290
+ return needles.every((n) => hay.includes(n));
291
+ });
288
292
  }
289
293
  const total = rows.length;
290
294
  if (limit !== void 0 && rows.length > limit) return jsonResult({
@@ -343,6 +347,18 @@ function registerEntityReads(server, ctx) {
343
347
  if (raw === true) return jsonResult(detail);
344
348
  return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
345
349
  }));
350
+ server.registerTool("athlete_training", {
351
+ title: "Athlete training month (roster)",
352
+ description: ATHLETE_TRAINING_DESC,
353
+ inputSchema: {
354
+ athleteId: idParam,
355
+ year: z.number().int(),
356
+ month: z.number().int().min(1).max(12)
357
+ },
358
+ annotations: READ
359
+ }, ({ athleteId, year, month }) => attempt(async () => {
360
+ return jsonResult(presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month), toId(athleteId), year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
361
+ }));
346
362
  server.registerTool("get_program", {
347
363
  title: "Get program detail",
348
364
  description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
@@ -408,9 +424,21 @@ function registerProfileTools(server, ctx, whoami, userId) {
408
424
  return jsonResult(await fetchLeaderboard(ctx.client, toId(workoutId), opts));
409
425
  }));
410
426
  }
411
- const ATHLETE_WORKOUTS_DESC = "Workouts in an inclusive YYYY-MM-DD window, flattened to blocks/exercises. Each exercise carries both its `prescribed` sets (what the program called for) and `performed` sets (what the athlete actually logged); each workout has a top-level `logged` flag. Use `performed`/`logged` to tell what was recorded or done. That is the reliable signal: a session can hold logged sets while the API's own completion flags stay 0, and an empty `performed` means nothing was logged for that exercise. For 'did I record anything / what did I do', set loggedOnly:true to return only sessions with logged sets (it keeps whole sessions that have any logged set, so individual exercises inside can still show empty `performed`; it also shrinks a large result); limit returns the most recent N workouts (newest first). For 'what's my next workout', query a forward window from today; if it comes back empty, the most recent session is likely yesterday's still-unlogged one, so widen the window backward a day or two. Both filters apply to the presented view, not raw. raw:true returns the untouched API objects. This is a date-windowed fetch, NOT an aggregate: for lifetime totals (all-time session count, total volume, first/last logged date) call athlete_profile instead of summing windows — a multi-year range here can time out. Narrow the window if the result is truncated.";
412
- const ATHLETE_EXERCISE_HISTORY_DESC = "Per-exercise PRs and the dated session time-series (sets performed, estimated 1RM). The returned `sessions` run all-time, newest first; pass since/until (YYYY-MM-DD, inclusive) to keep only sessions in that window — use it for 'last 3 months' / 'this year' questions so the result stays small. `liftPRs` are always all-time and ignore since/until. Set raw:true for the untouched API object. Get the exercise id from athlete_exercises.";
413
- const ATHLETE_EXERCISES_DESC = "The exercises the athlete has logged (id + title + positional units). Pass q to free-text search by name; use the returned id with athlete_exercise_history, athlete_personal_records, or athlete_exercise_stats (all of which require an exercise id).";
427
+ const ATHLETE_WORKOUTS_DESC = "Workouts in an inclusive YYYY-MM-DD window, flattened to blocks/exercises. Each exercise carries both its `prescribed` sets (what the program called for) and `performed` sets (what the athlete actually logged); each workout has a top-level `logged` flag. Use `performed`/`logged` to tell what was recorded or done. That is the reliable signal: a session can hold logged sets while the API's own completion flags stay 0, and an empty `performed` means nothing was logged for that exercise. For 'did I record anything / what did I do', set loggedOnly:true to return only sessions with logged sets (it keeps whole sessions that have any logged set, so individual exercises inside can still show empty `performed`; it also shrinks a large result); limit returns the most recent N workouts (newest first). For a high-level overview ('what's on my schedule this week', 'what have I been training lately') set summary:true to get one compact row per session (date, program, title, logged flag, and exerciseCount/performedCount — read performedCount against exerciseCount, e.g. 1 of 12 logged) instead of every set — a multi-program week of full detail is large, so prefer summary first, then re-query a single day without it to drill into that day's sets. For 'what's my next workout', query a forward window from today; if it comes back empty, the most recent session is likely yesterday's still-unlogged one, so widen the window backward a day or two. Both filters apply to the presented view, not raw. raw:true returns the untouched API objects. This is a date-windowed fetch, NOT an aggregate: for lifetime totals (all-time session count, total volume, first/last logged date) call athlete_profile instead of summing windows — a multi-year range here can time out. Narrow the window if the result is truncated.";
428
+ const ATHLETE_EXERCISE_HISTORY_DESC = "Per-exercise PRs and the dated session time-series (sets performed, estimated 1RM). The returned `sessions` run all-time, newest first; pass since/until (YYYY-MM-DD, inclusive) to keep only sessions in that window — use it for 'last 3 months' / 'this year' questions so the result stays small. estimated1RM is a formula off the session's best set and reads high when a session mixes a heavy single with high-rep backdown work, so treat it as approximate, not a logged single. `liftPRs` are always all-time and ignore since/until, but each carries the date it was set, so filter those dates yourself to answer 'PRs set this year'. Set raw:true for the untouched API object. Get the exercise id from athlete_exercises.";
429
+ const ATHLETE_EXERCISES_DESC = "The exercises the athlete has logged (id + title + positional units). Pass q to free-text search by name; use the returned id with athlete_exercise_history, athlete_personal_records, or athlete_exercise_stats (all of which require an exercise id). A common name returns several variants (e.g. plain 'Bench Press' id 1162 vs 'BARBELL BENCH PRESS'); each variant keeps its own separate history and PR board, so prefer the plain canonical entry, and if a PR or trend looks incomplete, the work may be split across variants — check the others.";
430
+ function runAthleteWorkouts(ctx, args) {
431
+ return attempt(async () => {
432
+ const workouts = await fetchAthleteWorkouts(ctx.client, args.startDate, args.endDate);
433
+ if (args.raw === true) return jsonResult(workouts, { hint: "Narrow startDate/endDate to shrink this result." });
434
+ const opts = {};
435
+ if (args.loggedOnly !== void 0) opts.loggedOnly = args.loggedOnly;
436
+ if (args.limit !== void 0) opts.limit = args.limit;
437
+ const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
438
+ if (args.summary === true) return jsonResult(summarizeAthleteWorkouts(selected), { hint: "Compact per-session overview. Re-query a narrow startDate/endDate without summary for a day's full prescribed/performed sets." });
439
+ return jsonResult(selected, { hint: "Large? Set summary:true for one row per session, loggedOnly:true, pass limit, or narrow the dates." });
440
+ });
441
+ }
414
442
  /** Workouts, exercise catalog, per-exercise history/PRs/stats. */
415
443
  function registerExerciseTools$1(server, ctx, userId) {
416
444
  server.registerTool("athlete_workouts", {
@@ -421,17 +449,11 @@ function registerExerciseTools$1(server, ctx, userId) {
421
449
  endDate: dateString,
422
450
  raw: z.boolean().optional(),
423
451
  loggedOnly: z.boolean().optional(),
424
- limit: z.number().int().positive().max(200).optional()
452
+ limit: z.number().int().positive().max(200).optional(),
453
+ summary: z.boolean().optional()
425
454
  },
426
455
  annotations: READ
427
- }, ({ startDate, endDate, raw, loggedOnly, limit }) => attempt(async () => {
428
- const workouts = await fetchAthleteWorkouts(ctx.client, startDate, endDate);
429
- if (raw === true) return jsonResult(workouts, { hint: "Narrow startDate/endDate to shrink this result." });
430
- const opts = {};
431
- if (loggedOnly !== void 0) opts.loggedOnly = loggedOnly;
432
- if (limit !== void 0) opts.limit = limit;
433
- return jsonResult(selectWorkouts(presentAthleteWorkouts(workouts), opts), { hint: "Large? Set loggedOnly:true, pass limit, or narrow startDate/endDate." });
434
- }));
456
+ }, (args) => runAthleteWorkouts(ctx, args));
435
457
  server.registerTool("athlete_exercises", {
436
458
  title: "Search logged exercises",
437
459
  description: ATHLETE_EXERCISES_DESC,
@@ -466,7 +488,7 @@ function registerExerciseTools$1(server, ctx, userId) {
466
488
  }));
467
489
  server.registerTool("athlete_personal_records", {
468
490
  title: "Exercise personal records",
469
- description: "The all-time PR board for an exercise (reps/weight per rep-max, strength-standard filters). Get the exercise id from athlete_exercises. For a point-in-time snapshot use athlete_exercise_stats; for the dated session trend use athlete_exercise_history.",
491
+ description: "The all-time PR board for an exercise (reps/weight per rep-max, strength-standard filters). Get the exercise id from athlete_exercises. A lift is often logged under several name variants, each with its own board, so if a PR looks missing check the other variants. For a point-in-time snapshot use athlete_exercise_stats; for the dated session trend use athlete_exercise_history.",
470
492
  inputSchema: { exerciseId: idParam },
471
493
  annotations: READ
472
494
  }, ({ exerciseId }) => attempt(async () => jsonResult(await fetchPersonalRecords(ctx.client, toId(exerciseId)))));
@@ -798,7 +820,7 @@ const BODY_KEY = {
798
820
  function registerAnalyticsTools(server, ctx) {
799
821
  server.registerTool("analytics_query", {
800
822
  title: "Pull an analytics report",
801
- 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). 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.",
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.",
802
824
  inputSchema: {
803
825
  metric: z.enum(METRIC_KEYS),
804
826
  teamId: idParam.optional(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/core",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
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.2",
29
- "@trainheroic-unofficial/js": "0.6.2"
28
+ "@trainheroic-unofficial/dto": "0.6.3",
29
+ "@trainheroic-unofficial/js": "0.6.3"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.0.0",