@trainheroic-unofficial/coach-mcp 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +284 -90
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -163,32 +163,45 @@ const loggedSetSchema = z.object({
163
163
  param2: z.union([z.number(), z.string()]).optional()
164
164
  });
165
165
  /**
166
- * Args for the set-logging write. `date` (the workout's day) locates the saved
167
- * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
168
- * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
166
+ * A logged set that can name the prescribed position it fills. `slot` is the 1-based set
167
+ * index in the prescription (10 max) the result should land in; omit it to fill the next
168
+ * sequential position (the first entry is set 1, the second set 2, and so on). Targeting a
169
+ * slot lets a partial log land in the right positions of a multi-set prescription — e.g.
170
+ * three top singles into the 4th/5th/6th positions of an `8,5,3,1,1,1` ramp. Used by the
171
+ * by-set logging write (not the by-exercise session log, where each exercise's sets are
172
+ * always sequential).
169
173
  */
170
- const logSetArgsSchema = z.object({
174
+ const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().min(1).max(10).optional() });
175
+ /**
176
+ * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
177
+ * roster `athleteId` whose set is being logged on their behalf.
178
+ */
179
+ const coachLogSetArgsSchema = z.object({
171
180
  date: dateString,
172
181
  savedWorkoutSetId: idArgSchema,
173
182
  results: z.array(z.object({
174
183
  savedWorkoutSetExerciseId: idArgSchema,
175
- sets: z.array(loggedSetSchema).min(1)
184
+ sets: z.array(loggedSetWithSlotSchema).min(1)
176
185
  })).min(1)
177
- });
178
- /**
179
- * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
180
- * roster `athleteId` whose set is being logged on their behalf.
181
- */
182
- const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
186
+ }).extend({ athleteId: idArgSchema });
183
187
  /**
184
- * Args for the coach prescription-override write. Structurally the same as
185
- * {@link coachLogSetArgsSchema} (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but
186
- * the values are prescribed targets (param1 = reps, param2 = weight) written to the athlete's
187
- * plan without marking the set performed. It is a separate schema (not an alias) so a future
188
- * prescribe-only constraint can be added here without changing the log args, and the write
189
- * replaces the slot's prescribed values for this athlete only.
188
+ * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
189
+ * (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but the values are prescribed
190
+ * targets (param1 = reps, param2 = weight) written to the athlete's plan without marking the set
191
+ * performed. The write replaces this athlete's whole prescription for the set, so its sets are
192
+ * positional and sequential by definition: it deliberately omits the log path's `slot` field (a
193
+ * sparse, slot-targeted prescription has no meaning here) by building its results off
194
+ * {@link loggedSetSchema} rather than {@link loggedSetWithSlotSchema}.
190
195
  */
191
- const coachPrescribeSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
196
+ const coachPrescribeSetArgsSchema = z.object({
197
+ date: dateString,
198
+ savedWorkoutSetId: idArgSchema,
199
+ athleteId: idArgSchema,
200
+ results: z.array(z.object({
201
+ savedWorkoutSetExerciseId: idArgSchema,
202
+ sets: z.array(loggedSetSchema).min(1)
203
+ })).min(1)
204
+ });
192
205
  /**
193
206
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
194
207
  * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
@@ -512,7 +525,20 @@ async function confirmGate(server, requestId, message, confirmArg) {
512
525
  const SERVER_INSTRUCTIONS = "Speak to the user in plain, everyday language about their training. Describe what you are doing in the TrainHeroic app's own terms (for example, say you are creating a workout rather than naming a tool). Do not surface internal tool names (the snake_case identifiers such as athlete_session_create), raw parameter names, or numeric ids in your replies unless the user explicitly asks for them; they are implementation details. The tool descriptions cross-reference each other by name only so you can chain them correctly. Keep that wiring to yourself.";
513
526
  //#endregion
514
527
  //#region ../js/src/auth.ts
515
- const AUTH_URL = "https://apis.trainheroic.com/auth";
528
+ const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
529
+ /**
530
+ * The login endpoint, allowing an env override so a test harness can authenticate against a local
531
+ * fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
532
+ * the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
533
+ * (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
534
+ */
535
+ function authUrl() {
536
+ const env = globalThis.process?.env;
537
+ if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
538
+ const apis = env?.TH_APIS_BASE;
539
+ if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
540
+ return DEFAULT_AUTH_URL;
541
+ }
516
542
  /**
517
543
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
518
544
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
@@ -520,7 +546,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
520
546
  * is sent as the `session-token` header and works against both API hosts.
521
547
  */
522
548
  async function loginTrainHeroic(email, password) {
523
- const res = await fetch(AUTH_URL, {
549
+ const res = await fetch(authUrl(), {
524
550
  method: "POST",
525
551
  headers: {
526
552
  "content-type": "application/x-www-form-urlencoded",
@@ -543,8 +569,19 @@ async function loginTrainHeroic(email, password) {
543
569
  }
544
570
  //#endregion
545
571
  //#region ../js/src/client.ts
546
- const COACH_BASE = "https://api.trainheroic.com";
547
- const APIS_BASE = "https://apis.trainheroic.com";
572
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
573
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
574
+ /**
575
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
576
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
577
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
578
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
579
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
580
+ */
581
+ function envBase(key, fallback) {
582
+ const v = (globalThis.process?.env)?.[key];
583
+ return v && v.length > 0 ? v : fallback;
584
+ }
548
585
  var TrainHeroicAuthError = class extends Error {
549
586
  name = "TrainHeroicAuthError";
550
587
  };
@@ -583,7 +620,7 @@ var TrainHeroicClient = class {
583
620
  return this.#sessionId;
584
621
  }
585
622
  async request(method, path, options = {}) {
586
- const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
623
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
587
624
  let session = await this.#ensureSession();
588
625
  let res = await this.#send(method, url, session, options.body);
589
626
  if (res.status === 401 || res.status === 403) {
@@ -752,6 +789,10 @@ function asExerciseList(body) {
752
789
  function isRecord(x) {
753
790
  return typeof x === "object" && x !== null && !Array.isArray(x);
754
791
  }
792
+ /** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
793
+ function str$1(v) {
794
+ return typeof v === "string" && v !== "" ? v : null;
795
+ }
755
796
  /**
756
797
  * Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
757
798
  * exact title, then prefix, then count of matched tokens, with shorter titles and
@@ -889,7 +930,6 @@ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
889
930
  function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
890
931
  return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
891
932
  }
892
- const SLOTS = 10;
893
933
  function nonEmpty(value) {
894
934
  return value !== void 0 && value !== null && String(value).trim() !== "";
895
935
  }
@@ -900,7 +940,7 @@ function nonEmpty(value) {
900
940
  */
901
941
  function prescribedSets(ex) {
902
942
  const out = [];
903
- for (let i = 1; i <= SLOTS; i += 1) {
943
+ for (let i = 1; i <= 10; i += 1) {
904
944
  const p1 = ex[`param_1_data_${i}`];
905
945
  const p2 = ex[`param_2_data_${i}`];
906
946
  const has1 = nonEmpty(p1);
@@ -921,7 +961,7 @@ function prescribedSets(ex) {
921
961
  */
922
962
  function performedSets(ex) {
923
963
  const out = [];
924
- for (let i = 1; i <= SLOTS; i += 1) {
964
+ for (let i = 1; i <= 10; i += 1) {
925
965
  if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
926
966
  const p1 = ex[`param_1_data_${i}`];
927
967
  const p2 = ex[`param_2_data_${i}`];
@@ -955,9 +995,6 @@ function presentBlock(set, performedById) {
955
995
  exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
956
996
  };
957
997
  }
958
- function str$1(v) {
959
- return typeof v === "string" && v !== "" ? v : null;
960
- }
961
998
  /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
962
999
  function savedSets(saved) {
963
1000
  const out = [];
@@ -1055,6 +1092,81 @@ function presentAthleteWorkouts(list) {
1055
1092
  return list.map(presentAthleteWorkout);
1056
1093
  }
1057
1094
  /**
1095
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
1096
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
1097
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
1098
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
1099
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
1100
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
1101
+ */
1102
+ function selectWorkoutsByProgram(list, filter) {
1103
+ const { programId, teamId, programTitle } = filter;
1104
+ const needle = programTitle?.trim().toLowerCase();
1105
+ if (programId === void 0 && teamId === void 0 && !needle) return [...list];
1106
+ return list.filter((pw) => {
1107
+ const rec = pw;
1108
+ if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
1109
+ if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
1110
+ if (needle) {
1111
+ if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
1112
+ }
1113
+ return false;
1114
+ });
1115
+ }
1116
+ /**
1117
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
1118
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
1119
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
1120
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
1121
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
1122
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
1123
+ * dropping any set with no resolvable id.
1124
+ */
1125
+ function presentLogTargets(list) {
1126
+ const targets = [];
1127
+ for (const pw of list) {
1128
+ const rec = pw;
1129
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1130
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1131
+ if (!saved) continue;
1132
+ const date = str$1(rec.date) ?? "";
1133
+ const workoutTitle = str$1(rec.workout_title) ?? "";
1134
+ const program = str$1(rec.program_title);
1135
+ const programId = coerceInt(rec.program_id);
1136
+ const team = str$1(rec.team_title);
1137
+ const teamId = coerceInt(rec.team_id);
1138
+ const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
1139
+ for (const s of sets) {
1140
+ if (!isRecord(s)) continue;
1141
+ const savedWorkoutSetId = coerceInt(s.id);
1142
+ if (savedWorkoutSetId === null) continue;
1143
+ const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1144
+ const id = coerceInt(ex.id);
1145
+ if (id === null) return null;
1146
+ return {
1147
+ savedWorkoutSetExerciseId: id,
1148
+ title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
1149
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1150
+ prescribed: prescribedSets(ex),
1151
+ performed: performedSets(ex)
1152
+ };
1153
+ }).filter((e) => e !== null);
1154
+ targets.push({
1155
+ date,
1156
+ workoutTitle,
1157
+ program,
1158
+ programId,
1159
+ team,
1160
+ teamId,
1161
+ savedWorkoutSetId,
1162
+ setTitle: str$1(s.title),
1163
+ exercises
1164
+ });
1165
+ }
1166
+ }
1167
+ return targets;
1168
+ }
1169
+ /**
1058
1170
  * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
1059
1171
  * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
1060
1172
  * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
@@ -1102,7 +1214,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1102
1214
  sessions
1103
1215
  };
1104
1216
  }
1105
- const MAX_PARAM_SLOTS = 10;
1217
+ /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1218
+ function presentExerciseHistory(detail) {
1219
+ return {
1220
+ liftPRs: (detail.liftPRs ?? []).map((p) => ({
1221
+ description: p.description ?? null,
1222
+ reps: p.reps ?? null,
1223
+ weight: p.weight ?? null,
1224
+ units: p.units ?? null,
1225
+ date: p.dateCompleted ?? null
1226
+ })),
1227
+ sessions: (detail.history ?? []).map((h) => ({
1228
+ date: h.dateCompleted,
1229
+ abr: h.abr ?? null,
1230
+ estimated1RM: h.bestEstimated1RM ?? null,
1231
+ sets: (h.sets ?? []).map((s) => ({
1232
+ setNumber: s.setNumber,
1233
+ value: s.formattedValue ?? null
1234
+ }))
1235
+ }))
1236
+ };
1237
+ }
1238
+ //#endregion
1239
+ //#region ../js/src/athlete-set-write.ts
1106
1240
  /**
1107
1241
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1108
1242
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1117,10 +1251,11 @@ function toSetResults(results) {
1117
1251
  return {
1118
1252
  savedWorkoutSetExerciseId: id,
1119
1253
  sets: r.sets.map((s) => {
1120
- const slot = {};
1121
- if (s.param1 !== void 0) slot.param1 = s.param1;
1122
- if (s.param2 !== void 0) slot.param2 = s.param2;
1123
- return slot;
1254
+ const set = {};
1255
+ if (s.param1 !== void 0) set.param1 = s.param1;
1256
+ if (s.param2 !== void 0) set.param2 = s.param2;
1257
+ if (s.slot !== void 0) set.slot = s.slot;
1258
+ return set;
1124
1259
  })
1125
1260
  };
1126
1261
  });
@@ -1132,36 +1267,96 @@ function toSetResults(results) {
1132
1267
  *
1133
1268
  * `mode` selects which write this is — the same endpoint serves both:
1134
1269
  * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1135
- * and the exercise `completed` flag is 1 when any set has data.
1270
+ * and the exercise `completed` flag is 1 when any set has logged data.
1136
1271
  * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1137
1272
  * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1138
1273
  * coach edits an athlete's prescribed reps/weight.
1139
1274
  *
1275
+ * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1276
+ * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1277
+ * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1278
+ * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1279
+ * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1280
+ * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1281
+ * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1282
+ * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1283
+ *
1140
1284
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1141
- * required from the live exercise record; everything else is derived from `results`.
1285
+ * required from the live exercise record; everything else is derived from `results` and the
1286
+ * preserved slots of `existing`.
1142
1287
  *
1143
1288
  * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1144
1289
  */
1145
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1146
- if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1290
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1291
+ if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1292
+ const bySlot = /* @__PURE__ */ new Map();
1293
+ results.forEach((set, i) => {
1294
+ const slot = set.slot ?? i + 1;
1295
+ if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1296
+ if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1297
+ bySlot.set(slot, set);
1298
+ });
1147
1299
  const performed = mode === "log";
1148
- const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1300
+ const carryOver = performed && existing !== void 0;
1149
1301
  const body = {
1150
1302
  id: savedWorkoutSetExerciseId,
1151
1303
  saved_workout_set_id: savedWorkoutSetId,
1152
- workout_set_exercise_id: workoutSetExerciseId,
1153
- completed: performed && hasData ? 1 : 0
1304
+ workout_set_exercise_id: workoutSetExerciseId
1154
1305
  };
1155
- for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1156
- const slot = results[i - 1];
1157
- const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1158
- const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1159
- body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1306
+ let anyMade = false;
1307
+ for (let i = 1; i <= 10; i += 1) {
1308
+ const target = bySlot.get(i);
1309
+ let p1;
1310
+ let p2;
1311
+ let made;
1312
+ if (target) {
1313
+ p1 = target.param1 !== void 0 ? String(target.param1) : "";
1314
+ p2 = target.param2 !== void 0 ? String(target.param2) : "";
1315
+ made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1316
+ } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1317
+ p1 = existingSlotData(existing, `param_1_data_${i}`);
1318
+ p2 = existingSlotData(existing, `param_2_data_${i}`);
1319
+ made = 1;
1320
+ } else {
1321
+ p1 = "";
1322
+ p2 = "";
1323
+ made = 0;
1324
+ }
1325
+ if (made === 1) anyMade = true;
1326
+ body[`param_${i}_made`] = made;
1160
1327
  body[`param_1_data_${i}`] = p1;
1161
1328
  body[`param_2_data_${i}`] = p2;
1162
1329
  }
1330
+ body.completed = performed && anyMade ? 1 : 0;
1163
1331
  return body;
1164
1332
  }
1333
+ /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1334
+ function existingSlotData(existing, key) {
1335
+ const v = existing?.[key];
1336
+ return v === void 0 || v === null ? "" : String(v);
1337
+ }
1338
+ /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1339
+ function exerciseHasLoggedData(ex) {
1340
+ for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1341
+ return false;
1342
+ }
1343
+ /** True when a result carries at least one non-empty param value (so it produces a performed slot). */
1344
+ function resultHasData(result) {
1345
+ return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
1346
+ }
1347
+ /**
1348
+ * Whether every exercise in a saved workout set now has logged data — either written with data in
1349
+ * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1350
+ * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1351
+ * does not flip its still-empty siblings to "done". An exercise written with only empty values does
1352
+ * not count (it would not be marked performed), so an all-empty log never completes the set.
1353
+ */
1354
+ function isSetFullyLogged(exercises, loggedIds) {
1355
+ return exercises.every((ex) => {
1356
+ const id = coerceInt(ex.id);
1357
+ return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1358
+ });
1359
+ }
1165
1360
  /**
1166
1361
  * Locate the target saved workout set across all program workouts on the given day.
1167
1362
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1260,7 +1455,8 @@ async function logAthleteSet(client, args) {
1260
1455
  const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1261
1456
  return {
1262
1457
  savedWorkoutSetId: r.savedWorkoutSetId,
1263
- exercisesLogged: r.exercisesWritten
1458
+ exercisesLogged: r.exercisesWritten,
1459
+ setCompleted: r.setCompleted
1264
1460
  };
1265
1461
  }
1266
1462
  /**
@@ -1281,7 +1477,8 @@ async function logForAthlete(client, args) {
1281
1477
  }, workouts, args.savedWorkoutSetId, args.results, "log");
1282
1478
  return {
1283
1479
  savedWorkoutSetId: r.savedWorkoutSetId,
1284
- exercisesLogged: r.exercisesWritten
1480
+ exercisesLogged: r.exercisesWritten,
1481
+ setCompleted: r.setCompleted
1285
1482
  };
1286
1483
  }
1287
1484
  /**
@@ -1374,9 +1571,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1374
1571
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1375
1572
  }
1376
1573
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1377
- if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1574
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
1378
1575
  const body = {
1379
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1576
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1380
1577
  ...extra
1381
1578
  };
1382
1579
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
@@ -1386,17 +1583,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1386
1583
  }
1387
1584
  exercisesWritten += 1;
1388
1585
  }
1586
+ let setCompleted = false;
1389
1587
  if (mode === "log") {
1390
- const setBody = {
1391
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1392
- ...extra
1393
- };
1394
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1395
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1588
+ if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
1589
+ const setBody = {
1590
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1591
+ ...extra
1592
+ };
1593
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1594
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1595
+ setCompleted = true;
1596
+ }
1396
1597
  }
1397
1598
  return {
1398
1599
  savedWorkoutSetId,
1399
- exercisesWritten
1600
+ exercisesWritten,
1601
+ setCompleted
1400
1602
  };
1401
1603
  }
1402
1604
  /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
@@ -1472,7 +1674,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1472
1674
  savedWorkoutSetId,
1473
1675
  results
1474
1676
  });
1475
- out.push(written);
1677
+ out.push({
1678
+ savedWorkoutSetId: written.savedWorkoutSetId,
1679
+ exercisesLogged: written.exercisesLogged
1680
+ });
1476
1681
  }
1477
1682
  return out;
1478
1683
  }
@@ -1511,27 +1716,6 @@ async function logSessionForAthlete(client, args) {
1511
1716
  sets
1512
1717
  };
1513
1718
  }
1514
- /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1515
- function presentExerciseHistory(detail) {
1516
- return {
1517
- liftPRs: (detail.liftPRs ?? []).map((p) => ({
1518
- description: p.description ?? null,
1519
- reps: p.reps ?? null,
1520
- weight: p.weight ?? null,
1521
- units: p.units ?? null,
1522
- date: p.dateCompleted ?? null
1523
- })),
1524
- sessions: (detail.history ?? []).map((h) => ({
1525
- date: h.dateCompleted,
1526
- abr: h.abr ?? null,
1527
- estimated1RM: h.bestEstimated1RM ?? null,
1528
- sets: (h.sets ?? []).map((s) => ({
1529
- setNumber: s.setNumber,
1530
- value: s.formattedValue ?? null
1531
- }))
1532
- }))
1533
- };
1534
- }
1535
1719
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1536
1720
  function emailList(emails) {
1537
1721
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2640,7 +2824,7 @@ function historyInRange(presented, since, until) {
2640
2824
  //#region ../core/src/tools/reads.ts
2641
2825
  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.";
2642
2826
  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.";
2643
- 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.";
2827
+ 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 and carry NO per-session date — so this canNOT answer 'what did they do on <day>' (e.g. today); for a specific day use athlete_saved_workouts with startDate=endDate=that day instead. An empty list means no sessions that month.";
2644
2828
  function enc(value) {
2645
2829
  return encodeURIComponent(String(value));
2646
2830
  }
@@ -2944,25 +3128,35 @@ function registerAthleteTools(server, ctx) {
2944
3128
  * "Log for Athlete" flow. Kept in its own function so registerAthleteTools stays under the
2945
3129
  * oxlint max-lines-per-function cap.
2946
3130
  */
2947
- function registerAthleteLogTools(server, ctx) {
3131
+ function registerAthleteSavedWorkouts(server, ctx) {
2948
3132
  server.registerTool("athlete_saved_workouts", {
2949
3133
  title: "Roster athlete's saved workouts (with log ids)",
2950
- 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.",
3134
+ description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window. This is the DATE-PRECISE coach read: to answer 'what did <athlete> do/log on <day>' (e.g. today), pass startDate=endDate=that day — each row carries its date and the performed values (what the athlete actually logged), unlike athlete_training which is a whole-month overview with no per-session date. It is also the coach-side source of the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set, prescribe_athlete_set, and swap_athlete_exercise need. Get athleteId from list_athletes. The default view is COMPACT: one row per saved set, each carrying its program/programId, the savedWorkoutSetId, and every exercise's savedWorkoutSetExerciseId with prescribed/performed values — so you read those ids straight off it, no raw needed. An athlete enrolled in many programs returns one row per program; narrow to one with program (a case-insensitive title substring, e.g. 'bodybuilding' — no id lookup needed), or programId/teamId if you already have the id. raw:true returns the untouched API objects, but that blob is large and can be truncated for a high-enrollment athlete — prefer the program filter + the default view. athlete_training gives a whole-month overview but not these ids.",
2951
3135
  inputSchema: {
2952
3136
  athleteId: idParam,
2953
3137
  startDate: dateString,
2954
3138
  endDate: dateString,
3139
+ program: z.string().optional(),
3140
+ programId: idParam.optional(),
3141
+ teamId: idParam.optional(),
2955
3142
  raw: z.boolean().optional()
2956
3143
  },
2957
3144
  annotations: READ
2958
- }, ({ athleteId, startDate, endDate, raw }) => attempt(async () => {
2959
- const workouts = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate);
2960
- 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." });
2961
- return jsonResult(presentAthleteWorkouts(workouts), { hint: "Set raw:true to get savedWorkoutSetId + savedWorkoutSetExerciseId for log_athlete_set." });
3145
+ }, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
3146
+ const workouts = selectWorkoutsByProgram(await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate), definedProps({
3147
+ programTitle: program,
3148
+ programId: programId === void 0 ? void 0 : toId(programId),
3149
+ teamId: teamId === void 0 ? void 0 : toId(teamId)
3150
+ }));
3151
+ if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. This raw blob is large — if truncated, pass program (a title substring) to target one program, or use the default (compact) view which carries the same ids." });
3152
+ return jsonResult(presentLogTargets(workouts), { hint: "One row per saved set: savedWorkoutSetId plus each savedWorkoutSetExerciseId, with the program it belongs to. Pass both ids to log_athlete_set / prescribe_athlete_set. Filter with program (title substring), programId, or teamId if the athlete is on several programs." });
2962
3153
  }));
3154
+ }
3155
+ function registerAthleteLogTools(server, ctx) {
3156
+ registerAthleteSavedWorkouts(server, ctx);
2963
3157
  server.registerTool("log_athlete_set", {
2964
3158
  title: "Log set results for a roster athlete",
2965
- 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).",
3159
+ 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 — the API equivalent of the app's \"Log for Athlete\". Writes to that athlete's training log and shows in their history. Each set fills the next position in order; give a set a 1-based `slot` to place it at a specific position. A partial log records only the positions you send (plus any logged earlier) and leaves the rest unlogged. In a superset/circuit the block is marked done only once every exercise in it has logged results (the response's `setCompleted` reports whether it was). Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts for that athlete/day (its default view carries both — pass programId there if the athlete is on several programs). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
2966
3160
  inputSchema: {
2967
3161
  ...coachLogSetArgsSchema.shape,
2968
3162
  confirm: z.boolean().optional()
@@ -3003,7 +3197,7 @@ function registerAthleteLogTools(server, ctx) {
3003
3197
  function registerAthleteSwapTool(server, ctx) {
3004
3198
  server.registerTool("swap_athlete_exercise", {
3005
3199
  title: "Swap one exercise in a roster athlete's prescribed workout",
3006
- description: "Coach-facing write: replace one exercise in a roster athlete's scheduled workout with a different one, for that athlete only — the API equivalent of the app's per-athlete \"swap exercise\". The team/program prescription is left untouched, so other athletes on the same program keep the original exercise. Give savedWorkoutSetExerciseId (the athlete's own slot, from athlete_saved_workouts with raw:true) and exerciseId (the replacement, from exercise_resolve / exercise_search). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3200
+ description: "Coach-facing write: replace one exercise in a roster athlete's scheduled workout with a different one, for that athlete only — the API equivalent of the app's per-athlete \"swap exercise\". The team/program prescription is left untouched, so other athletes on the same program keep the original exercise. Give savedWorkoutSetExerciseId (the athlete's own slot, from athlete_saved_workouts — its default view lists it per program) and exerciseId (the replacement, from exercise_resolve / exercise_search). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3007
3201
  inputSchema: {
3008
3202
  ...swapAthleteExerciseArgsSchema.shape,
3009
3203
  confirm: z.boolean().optional()
@@ -3027,7 +3221,7 @@ function registerAthleteSwapTool(server, ctx) {
3027
3221
  function registerAthletePrescribeTool(server, ctx) {
3028
3222
  server.registerTool("prescribe_athlete_set", {
3029
3223
  title: "Prescribe reps/weight for a roster athlete's set",
3030
- description: "Coach-facing write: set the prescribed reps and/or weight for one of a roster athlete's scheduled workout sets, for that athlete only, WITHOUT marking it done — the API equivalent of the app's editing an athlete's prescribed values (\"prescribe weights for an athlete\"). The set stays open for the athlete to log against, and the team/program prescription is left untouched, so other athletes keep the original targets. param1 is reps, param2 is weight; pass one sets[] entry per prescribed set. The write REPLACES the slot's prescribed values (the sets you pass become the whole prescription, and an omitted param is cleared), so give the full per-set prescription you want. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. To record a set as PERFORMED instead, use log_athlete_set. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3224
+ description: "Coach-facing write: set the prescribed reps and/or weight for one of a roster athlete's scheduled workout sets, for that athlete only, WITHOUT marking it done — the API equivalent of the app's editing an athlete's prescribed values (\"prescribe weights for an athlete\"). The set stays open for the athlete to log against, and the team/program prescription is left untouched, so other athletes keep the original targets. param1 is reps, param2 is weight; pass one sets[] entry per prescribed set. The write REPLACES the slot's prescribed values (the sets you pass become the whole prescription, and an omitted param is cleared), so give the full per-set prescription you want. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts for that athlete/day — its default view lists both per program, so pass programId there if the athlete is on several. To record a set as PERFORMED instead, use log_athlete_set. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3031
3225
  inputSchema: {
3032
3226
  ...coachPrescribeSetArgsSchema.shape,
3033
3227
  confirm: z.boolean().optional()
@@ -3463,7 +3657,7 @@ var JsonFileLibraryCache = class {
3463
3657
  };
3464
3658
  //#endregion
3465
3659
  //#region package.json
3466
- var version = "1.3.0";
3660
+ var version = "1.5.0";
3467
3661
  //#endregion
3468
3662
  //#region src/server.ts
3469
3663
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/sdk": "^1.29.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "1.3.0",
25
- "@trainheroic-unofficial/js": "1.3.0"
24
+ "@trainheroic-unofficial/core": "1.5.0",
25
+ "@trainheroic-unofficial/js": "1.5.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",