@trainheroic-unofficial/coach-mcp 4.2.0 → 4.3.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 +304 -167
  2. package/package.json +8 -8
package/dist/server.mjs CHANGED
@@ -5,7 +5,7 @@ import { z } from "zod";
5
5
  import { mkdir, readFile, writeFile } from "node:fs/promises";
6
6
  import { homedir } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
- //#region ../dto/src/common.ts
8
+ // ../dto/src/common.ts
9
9
  /** An entity id as it arrives over the wire — a number or a numeric string. */
10
10
  const idSchema = z.union([z.string(), z.number()]);
11
11
  /**
@@ -14,8 +14,7 @@ const idSchema = z.union([z.string(), z.number()]);
14
14
  * a bad argument fails validation instead of becoming NaN in a URL or a query.
15
15
  */
16
16
  const idArgSchema = z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
17
- //#endregion
18
- //#region ../dto/src/athlete.ts
17
+ // ../dto/src/athlete.ts
19
18
  const intLike$1 = z.union([z.number(), z.string()]);
20
19
  const intLikeOrNull$1 = z.union([
21
20
  z.number(),
@@ -383,8 +382,7 @@ const presentedExerciseHistorySchema = z.object({
383
382
  });
384
383
  /** Presented history first so the loose raw detail schema cannot swallow it. */
385
384
  const exerciseHistoryOutputSchema = z.union([presentedExerciseHistorySchema, exerciseHistoryDetailSchema]);
386
- //#endregion
387
- //#region ../dto/src/exercise.ts
385
+ // ../dto/src/exercise.ts
388
386
  /**
389
387
  * A row presented for display. The raw param-type codes are dropped and the fixed
390
388
  * measurement units are surfaced positionally in `units`, ordered by entry slot
@@ -446,16 +444,14 @@ const exerciseUpdateSchema = z.looseObject({
446
444
  ...exerciseWriteShape,
447
445
  points_of_performance: z.string().optional()
448
446
  });
449
- //#endregion
450
- //#region ../dto/src/messaging.ts
447
+ // ../dto/src/messaging.ts
451
448
  /** A chat comment to draft or send: target stream, body text, optional threaded reply. */
452
449
  const commentDraftSchema = z.object({
453
450
  streamId: idSchema,
454
451
  text: z.string().min(1),
455
452
  replyTo: idSchema.optional()
456
453
  });
457
- //#endregion
458
- //#region ../dto/src/responses.ts
454
+ // ../dto/src/responses.ts
459
455
  const intLike = z.union([z.number(), z.string()]);
460
456
  const intLikeOrNull = z.union([
461
457
  z.number(),
@@ -495,8 +491,7 @@ const programCreateResponseSchema = z.looseObject({
495
491
  program_type: intLike
496
492
  }).optional()
497
493
  });
498
- //#endregion
499
- //#region ../dto/src/team.ts
494
+ // ../dto/src/team.ts
500
495
  /** Fields merged onto the program object for `POST /1.0/coach/team/updatePublishSettings`. */
501
496
  const teamPublishPatchObject = z.object({
502
497
  pub_enabled: z.union([z.number(), z.boolean()]).optional(),
@@ -505,8 +500,7 @@ const teamPublishPatchObject = z.object({
505
500
  pub_timezone: z.string().optional()
506
501
  });
507
502
  const teamPublishPatchSchema = teamPublishPatchObject.refine((v) => v.pub_enabled !== void 0 || v.pub_days !== void 0 || v.pub_time !== void 0 || v.pub_timezone !== void 0, { message: "Provide at least one pub_* field" });
508
- //#endregion
509
- //#region ../dto/src/tool-output.ts
503
+ // ../dto/src/tool-output.ts
510
504
  const nullableNumber = z.number().nullable();
511
505
  const nullableString = z.string().nullable();
512
506
  const truncationMarkerSchema = z.looseObject({
@@ -642,6 +636,7 @@ const workoutReadBlockOutputSchema = z.object({
642
636
  });
643
637
  const workoutReadOutputSchema = z.object({
644
638
  pwId: z.number(),
639
+ workoutId: z.number().nullable(),
645
640
  date: z.string(),
646
641
  published: z.json().optional(),
647
642
  instruction: z.string(),
@@ -710,8 +705,7 @@ const programDeletedOutputSchema = z.object({
710
705
  programId: z.number(),
711
706
  containerId: nullableNumber
712
707
  });
713
- //#endregion
714
- //#region ../dto/src/workout.ts
708
+ // ../dto/src/workout.ts
715
709
  /** A single exercise prescription inside a block. */
716
710
  const exerciseSpecSchema = z.object({
717
711
  id: z.union([z.number(), z.string()]),
@@ -723,8 +717,8 @@ const exerciseSpecSchema = z.object({
723
717
  ]).optional().describe("Primary slot values; may be reps, distance, or time. State primaryUnit."),
724
718
  sets: z.number().optional(),
725
719
  weight: z.union([z.number(), z.array(z.number())]).optional().describe("Secondary slot values; may be weight or time. State secondaryUnit."),
726
- primaryUnit: z.string().trim().min(1).optional().describe("Intended primary unit from exercise_resolve, such as reps, m, mi, or sec."),
727
- secondaryUnit: z.string().trim().min(1).optional().describe("Intended secondary unit from exercise_resolve, such as lb or sec."),
720
+ primaryUnit: z.string().trim().min(1).optional().describe("Unit of the primary values, such as reps, m, mi, or sec. A unit other than the exercise's default from exercise_resolve is set on this session."),
721
+ secondaryUnit: z.string().trim().min(1).optional().describe("Unit of the secondary values, such as lb, %max, RPE, or sec. A unit other than the exercise's default from exercise_resolve is set on this session."),
728
722
  rpe: z.union([z.number(), z.string()]).optional(),
729
723
  instr: z.string().optional(),
730
724
  param_1_type: z.number().optional(),
@@ -803,8 +797,13 @@ const sessionTemplateCreateSchema = z.object({
803
797
  title: z.string().min(1),
804
798
  instruction: z.string().optional()
805
799
  });
806
- //#endregion
807
- //#region ../core/src/context.ts
800
+ /** Input for copying an existing calendar session into the session library. */
801
+ const sessionSaveAsTemplateSchema = z.object({
802
+ workoutId: z.number().int().describe("The session's workout_id (workout_build returns it as workoutId)."),
803
+ pwId: z.number().int().describe("The session's programWorkout id (workout_build returns it as pwId)."),
804
+ title: z.string().trim().min(1).describe("Title of the new library template.")
805
+ });
806
+ // ../core/src/context.ts
808
807
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
809
808
  const idParam = idArgSchema;
810
809
  function toId(value) {
@@ -1011,8 +1010,7 @@ async function apiCall(ctx, method, path, options, hint) {
1011
1010
  return apiResponseResult(await ctx.client.request(method, path, options), hint);
1012
1011
  });
1013
1012
  }
1014
- //#endregion
1015
- //#region ../core/src/confirm.ts
1013
+ // ../core/src/confirm.ts
1016
1014
  /**
1017
1015
  * Returned when the user was asked and said no. It must not tell the model how to retry: the
1018
1016
  * refusal is the answer. (The `confirm: true` fallback for clients that cannot elicit is
@@ -1068,8 +1066,7 @@ function confirmGate(ctx, message, confirmArg) {
1068
1066
  }
1069
1067
  }) } });
1070
1068
  }
1071
- //#endregion
1072
- //#region ../core/src/instructions.ts
1069
+ // ../core/src/instructions.ts
1073
1070
  /**
1074
1071
  * Server-level guidance passed as the MCP `instructions` string. The host model receives it
1075
1072
  * in the initialize result and treats it like a system hint. Its job is to stop tool-layer
@@ -1079,8 +1076,7 @@ function confirmGate(ctx, message, confirmArg) {
1079
1076
  * leak further. This tells the host to keep that wiring internal and speak in app terms.
1080
1077
  */
1081
1078
  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.";
1082
- //#endregion
1083
- //#region ../js/src/date-window.ts
1079
+ // ../js/src/date-window.ts
1084
1080
  const DAY_MS = 864e5;
1085
1081
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
1086
1082
  const MAX_DATE_WINDOWS = 100;
@@ -1113,8 +1109,7 @@ function splitDateRange(start, end, maxDays) {
1113
1109
  });
1114
1110
  return windows;
1115
1111
  }
1116
- //#endregion
1117
- //#region ../js/src/http-error.ts
1112
+ // ../js/src/http-error.ts
1118
1113
  const MAX_REQUEST_KEYS = 50;
1119
1114
  const MAX_RESPONSE_DEPTH = 4;
1120
1115
  const MAX_RESPONSE_KEYS = 20;
@@ -1350,11 +1345,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1350
1345
  Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1351
1346
  } catch {}
1352
1347
  }
1353
- //#endregion
1354
- //#region ../js/src/transport.ts
1348
+ // ../js/src/transport.ts
1355
1349
  const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1356
- //#endregion
1357
- //#region ../js/src/auth.ts
1350
+ // ../js/src/auth.ts
1358
1351
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1359
1352
  /**
1360
1353
  * The login endpoint, allowing an env override so a test harness can authenticate against a local
@@ -1405,8 +1398,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1405
1398
  role: data.role ?? ""
1406
1399
  };
1407
1400
  }
1408
- //#endregion
1409
- //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
1401
+ // ../../node_modules/.pnpm/es-toolkit@1.53.2/node_modules/es-toolkit/dist/array/chunk.mjs
1410
1402
  /**
1411
1403
  * Splits an array into smaller arrays of a specified length.
1412
1404
  *
@@ -1441,8 +1433,7 @@ function chunk(arr, size) {
1441
1433
  }
1442
1434
  return result;
1443
1435
  }
1444
- //#endregion
1445
- //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
1436
+ // ../../node_modules/.pnpm/es-toolkit@1.53.2/node_modules/es-toolkit/dist/array/uniq.mjs
1446
1437
  /**
1447
1438
  * Creates a duplicate-free version of an array.
1448
1439
  *
@@ -1461,13 +1452,12 @@ function chunk(arr, size) {
1461
1452
  function uniq(arr) {
1462
1453
  return [...new Set(arr)];
1463
1454
  }
1464
- //#endregion
1465
- //#region ../js/src/exercise-util.ts
1455
+ // ../js/src/exercise-util.ts
1466
1456
  /**
1467
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
1468
- * (the API forces param_1_type/param_2_type back to the library default on save), so
1469
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
1470
- * metric workout. Keep in sync with the workout builder's unit table.
1457
+ * Display labels for TrainHeroic parameter types. Each library exercise has a default type per
1458
+ * slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
1459
+ * A session can set a different type on an exercise; the workout builder maps a stated unit
1460
+ * back to its type code through this table, so keep it in sync with the builder's unit aliases.
1471
1461
  */
1472
1462
  const PARAM_UNIT = {
1473
1463
  0: null,
@@ -1508,7 +1498,7 @@ function unitLabel(paramType) {
1508
1498
  return PARAM_UNIT[t] ?? null;
1509
1499
  }
1510
1500
  /**
1511
- * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
1501
+ * Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
1512
1502
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
1513
1503
  * by role. A null entry is an unset slot.
1514
1504
  */
@@ -1697,8 +1687,7 @@ function createLimiter(max) {
1697
1687
  function assertPositiveInteger(value, label) {
1698
1688
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1699
1689
  }
1700
- //#endregion
1701
- //#region ../js/src/client.ts
1690
+ // ../js/src/client.ts
1702
1691
  const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1703
1692
  const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1704
1693
  const MAX_REQUEST_CONCURRENCY = 4;
@@ -1818,8 +1807,7 @@ var TrainHeroicClient = class {
1818
1807
  return this.#transport(url, init);
1819
1808
  }
1820
1809
  };
1821
- //#endregion
1822
- //#region ../js/src/response-check.ts
1810
+ // ../js/src/response-check.ts
1823
1811
  /**
1824
1812
  * Validate an API response against its (loose) expected shape and warn once on drift.
1825
1813
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
@@ -1832,8 +1820,7 @@ function checkResponse(schema, data, label) {
1832
1820
  const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1833
1821
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1834
1822
  }
1835
- //#endregion
1836
- //#region ../js/src/athlete.ts
1823
+ // ../js/src/athlete.ts
1837
1824
  async function getJson(client, path, label) {
1838
1825
  const res = await client.request("GET", path);
1839
1826
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2160,8 +2147,7 @@ function presentExerciseHistory(detail) {
2160
2147
  }))
2161
2148
  };
2162
2149
  }
2163
- //#endregion
2164
- //#region ../js/src/exercise-history.ts
2150
+ // ../js/src/exercise-history.ts
2165
2151
  /**
2166
2152
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2167
2153
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -2182,8 +2168,7 @@ function historyInRange(presented, since, until) {
2182
2168
  sessions
2183
2169
  };
2184
2170
  }
2185
- //#endregion
2186
- //#region ../js/src/coach-athlete-calendar.ts
2171
+ // ../js/src/coach-athlete-calendar.ts
2187
2172
  async function getArray(client, path, label) {
2188
2173
  const res = await client.request("GET", path);
2189
2174
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2198,14 +2183,34 @@ async function getArray(client, path, label) {
2198
2183
  function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
2199
2184
  return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
2200
2185
  }
2186
+ /** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
2187
+ var CoachMonthSummaryError = class extends Error {
2188
+ name = "CoachMonthSummaryError";
2189
+ status;
2190
+ constructor(message, status) {
2191
+ super(message);
2192
+ this.status = status;
2193
+ }
2194
+ };
2201
2195
  /**
2202
2196
  * A coach's month view of a roster athlete's logged sessions
2203
2197
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
2204
2198
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
2205
2199
  * `userId` in each row is the roster athlete, not the calling coach.
2200
+ *
2201
+ * TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
2202
+ * read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
2206
2203
  */
2207
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2208
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
2204
+ async function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2205
+ const res = await client.request("GET", `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`);
2206
+ const label = `Coach athlete calendar summary for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}`;
2207
+ if (res.ok) {
2208
+ if (Array.isArray(res.data)) return res.data;
2209
+ throw new Error(`${label} returned an unexpected response shape.`);
2210
+ }
2211
+ const message = trainHeroicApiErrorMessage(label, res.status, res.data);
2212
+ if (res.status === 500) throw new CoachMonthSummaryError(`${message.endsWith(".") ? message : `${message}.`} TrainHeroic's month summary fails for some athletes whose date-range workout read still answers; read the same dates through the date-range read.`, res.status);
2213
+ throw new CoachMonthSummaryError(message, res.status);
2209
2214
  }
2210
2215
  /**
2211
2216
  * Resolve a roster athlete's coach-writable calendar program id
@@ -2246,8 +2251,7 @@ async function resolveBuildProgramId(client, args) {
2246
2251
  const [y, m] = parseWorkoutDate(args.date);
2247
2252
  return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
2248
2253
  }
2249
- //#endregion
2250
- //#region ../js/src/exercise-set-payload.ts
2254
+ // ../js/src/exercise-set-payload.ts
2251
2255
  function slotData(exercise, key) {
2252
2256
  const value = exercise?.[key];
2253
2257
  return value === void 0 || value === null ? "" : String(value);
@@ -2315,8 +2319,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
2315
2319
  body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
2316
2320
  return body;
2317
2321
  }
2318
- //#endregion
2319
- //#region ../js/src/athlete-set-write.ts
2322
+ // ../js/src/athlete-set-write.ts
2320
2323
  const WRITE_CONCURRENCY = 4;
2321
2324
  /**
2322
2325
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -2748,8 +2751,7 @@ async function logSessionForAthlete(client, args) {
2748
2751
  sets
2749
2752
  };
2750
2753
  }
2751
- //#endregion
2752
- //#region ../js/src/util.ts
2754
+ // ../js/src/util.ts
2753
2755
  /**
2754
2756
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2755
2757
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -2764,8 +2766,7 @@ function definedProps(obj) {
2764
2766
  for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2765
2767
  return result;
2766
2768
  }
2767
- //#endregion
2768
- //#region ../js/src/workout-encode.ts
2769
+ // ../js/src/workout-encode.ts
2769
2770
  const LEADERBOARD_TYPE = {
2770
2771
  completion: 0,
2771
2772
  "for completion": 0,
@@ -2939,7 +2940,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2939
2940
  param2Type = ex.param_2_type ?? 1;
2940
2941
  param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2941
2942
  } else {
2942
- param2Type = 0;
2943
+ param2Type = ex.param_2_type ?? 0;
2943
2944
  param2Values = null;
2944
2945
  }
2945
2946
  const entry = {
@@ -2998,9 +2999,6 @@ function buildBlockPayload(blocks, workoutId) {
2998
2999
  };
2999
3000
  });
3000
3001
  }
3001
- function unitOr(t) {
3002
- return unitLabel(t) ?? "?";
3003
- }
3004
3002
  const UNIT_ALIASES = {
3005
3003
  rep: "reps",
3006
3004
  reps: "reps",
@@ -3038,74 +3036,171 @@ function statedUnit(value, label) {
3038
3036
  if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
3039
3037
  return normalized;
3040
3038
  }
3041
- function validateSlotUnit(label, field, stated, paramType, fixedType, allowAddedWeight = false) {
3039
+ /** TrainHeroic param type codes keyed by their unit label (`sec` and `in` each name two). */
3040
+ const TYPES_BY_UNIT = (() => {
3041
+ const map = /* @__PURE__ */ new Map();
3042
+ for (const [code, unit] of Object.entries(PARAM_UNIT)) if (unit !== null) map.set(unit, [...map.get(unit) ?? [], Number(code)]);
3043
+ return map;
3044
+ })();
3045
+ /**
3046
+ * Pick the param type a populated slot is written with. An explicit `param_N_type` wins and
3047
+ * must agree with the stated unit. Otherwise the exercise's library default is kept when it
3048
+ * already has the stated unit, and any other unit maps to its own type code.
3049
+ */
3050
+ function resolveSlotType(label, slot, stated, explicit, libraryDefault) {
3051
+ const field = slot === 1 ? "primaryUnit" : "secondaryUnit";
3042
3052
  if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3043
3053
  const intended = statedUnit(stated, `${label} / ${field}`);
3044
- const fixed = unitLabel(fixedType);
3045
- if (intended !== fixed && !(allowAddedWeight && (fixedType === 0 || fixedType === null) && intended === "lb")) throw new Error(`${label}: ${field} ${intended} does not match the exercise's fixed ${fixed ?? "unset"} unit. Choose an exercise with the requested unit before building.`);
3046
- if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3047
- }
3048
- /** Validate both populated slots against the library before any workout write. */
3049
- function validateExerciseUnits(blockTitle, ex, defaults) {
3050
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3051
- if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3052
- if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3053
- }
3054
- /** Flag spec params the API will silently override to the exercise's fixed units. */
3055
- function unitAdvisory(blockTitle, ex, defaults) {
3054
+ if (explicit !== void 0) {
3055
+ if (unitLabel(explicit) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param_${slot}_type ${explicit} (${unitLabel(explicit) ?? "unset"}).`);
3056
+ return explicit;
3057
+ }
3058
+ if (libraryDefault !== null && unitLabel(libraryDefault) === intended) return libraryDefault;
3059
+ const [only, ...others] = TYPES_BY_UNIT.get(intended) ?? [];
3060
+ if (only === void 0) throw new Error(`${label}: ${field} ${intended} has no TrainHeroic param type.`);
3061
+ if (others.length === 0) return only;
3062
+ throw new Error(`${label}: ${field} ${intended} matches TrainHeroic param types ${[only, ...others].join(" and ")}; set param_${slot}_type to choose one.`);
3063
+ }
3064
+ /**
3065
+ * Return a copy of `ex` with `param_1_type` and `param_2_type` set to the types the encoder
3066
+ * writes. A slot without values always gets the library default (an explicit type there is
3067
+ * ignored, and `resolveExerciseUnits` warns about it), so only a slot with values can carry a
3068
+ * type that differs from the library.
3069
+ */
3070
+ function withResolvedParamTypes(label, ex, defaults) {
3071
+ const param1 = ex.reps === void 0 ? defaults.param1 ?? 3 : resolveSlotType(label, 1, ex.primaryUnit, ex.param_1_type, defaults.param1);
3072
+ const param2 = ex.weight === void 0 ? defaults.param2 ?? 0 : resolveSlotType(label, 2, ex.secondaryUnit, ex.param_2_type, defaults.param2);
3073
+ return {
3074
+ ...ex,
3075
+ param_1_type: param1,
3076
+ param_2_type: param2
3077
+ };
3078
+ }
3079
+ /**
3080
+ * The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
3081
+ * other than the library default. This is the one definition of a unit override: the advisory
3082
+ * notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
3083
+ * exactly these types.
3084
+ */
3085
+ function overriddenSlots(ex, defaults) {
3086
+ const overridden = [];
3087
+ if (ex.reps !== void 0 && ex.param_1_type !== defaults.param1) overridden.push(1);
3088
+ if (ex.weight !== void 0 && ex.param_2_type !== defaults.param2) overridden.push(2);
3089
+ return overridden;
3090
+ }
3091
+ /** A param type's unit label for advisory text; "unset" for a slot without a type. */
3092
+ function unitName(type) {
3093
+ return unitLabel(type) ?? "unset";
3094
+ }
3095
+ /**
3096
+ * Describe how a resolved exercise's units relate to its library defaults, and flag spec
3097
+ * fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
3098
+ * (from `resolveExerciseUnits`).
3099
+ */
3100
+ function unitAdvisory(label, ex, defaults) {
3056
3101
  const notes = [];
3057
3102
  const warnings = [];
3058
- const u = unitOr;
3059
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3103
+ const u = unitName;
3060
3104
  if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
3061
- const sentP1 = ex.param_1_type;
3062
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
3063
- const sp1 = Math.trunc(Number(sentP1));
3064
- warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
3065
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
3066
- if (ex.weight !== void 0 && ex.weight !== null) {
3067
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3068
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
3069
- if (sentP2 !== effP2) {
3070
- if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
3071
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
3072
- }
3073
- }
3105
+ const overrides = overriddenSlots(ex, defaults);
3106
+ if (overrides.includes(1)) notes.push(`${label}: primary values are in ${u(ex.param_1_type)}, set on this session in place of the exercise's default ${u(defaults.param1)}.`);
3107
+ else if (ex.reps !== void 0 && ex.param_1_type !== 3) notes.push(`${label}: values are in ${u(ex.param_1_type)} (the exercise's default primary unit).`);
3108
+ const addedLoad = ex.param_2_type === 1 && (defaults.param2 === 0 || defaults.param2 === null);
3109
+ if (overrides.includes(2) && !addedLoad) notes.push(`${label}: secondary values are in ${u(ex.param_2_type)}, set on this session in place of the exercise's default ${u(defaults.param2)}.`);
3074
3110
  return {
3075
3111
  notes,
3076
3112
  warnings
3077
3113
  };
3078
3114
  }
3115
+ /** Warn about explicit param types on slots without values, which the encoder ignores. */
3116
+ function ignoredTypeWarnings(label, ex) {
3117
+ const warnings = [];
3118
+ if (ex.reps === void 0 && ex.param_1_type !== void 0) warnings.push(`${label}: param_1_type ${ex.param_1_type} is ignored because reps has no values; the slot keeps the exercise's default.`);
3119
+ if (ex.weight === void 0 && ex.param_2_type !== void 0) warnings.push(`${label}: param_2_type ${ex.param_2_type} is ignored because weight has no values; the slot keeps the exercise's default.`);
3120
+ return warnings;
3121
+ }
3079
3122
  /**
3080
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
3081
- * then collect non-blocking advisories. The write path calls this before creating a workout;
3082
- * TrainHeroic silently replaces mismatched types.
3123
+ * Resolve every exercise's param types against current TrainHeroic exercise data and collect
3124
+ * non-blocking advisories. Throws, before anything is written, when a populated slot has no
3125
+ * stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
3126
+ * returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
3083
3127
  */
3084
- async function collectAdvisories(blocks, index) {
3085
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
3086
- block: b,
3087
- ex
3088
- })));
3089
- const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
3128
+ async function resolveExerciseUnits(blocks, index) {
3129
+ const ids = [...new Set(blocks.flatMap((b) => b.exercises.map((ex) => Number(ex.id))).filter(Number.isFinite))];
3090
3130
  const defaultsById = await index.currentDefaultsMany(ids);
3091
3131
  const notes = [];
3092
3132
  const warnings = [];
3093
- pairs.forEach((p) => {
3094
- const def = defaultsById.get(Number(p.ex.id));
3095
- if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
3096
- validateExerciseUnits(p.block.title, p.ex, def);
3097
- const advisory = unitAdvisory(p.block.title, p.ex, def);
3098
- notes.push(...advisory.notes);
3099
- warnings.push(...advisory.warnings);
3100
- });
3101
3133
  return {
3102
- notes,
3103
- warnings
3134
+ blocks: blocks.map((block) => ({
3135
+ ...block,
3136
+ exercises: block.exercises.map((ex) => {
3137
+ const label = `${block.title} / ${ex.title ?? ex.id}`;
3138
+ const def = defaultsById.get(Number(ex.id));
3139
+ if (!def) throw new Error(`${label}: exercise id ${ex.id} was not found in the library.`);
3140
+ const typed = withResolvedParamTypes(label, ex, def);
3141
+ const advisory = unitAdvisory(label, typed, def);
3142
+ notes.push(...advisory.notes);
3143
+ warnings.push(...ignoredTypeWarnings(label, ex), ...advisory.warnings);
3144
+ return typed;
3145
+ })
3146
+ })),
3147
+ defaultsById,
3148
+ advisories: {
3149
+ notes,
3150
+ warnings
3151
+ }
3104
3152
  };
3105
3153
  }
3106
- //#endregion
3107
- //#region ../js/src/workout-session.ts
3154
+ // ../js/src/workout-session.ts
3108
3155
  const EXERCISE_SAVE_CONCURRENCY = 4;
3156
+ const SAVE_EXERCISES_PATH = "/2.0/coach/calendar/saveWorkoutSetExercises";
3157
+ /**
3158
+ * Pair each sent entry with the row TrainHeroic returned for it. A block's rows are matched on
3159
+ * `order` (unique within one block's payload) and must carry the same `exercise_id` and an id.
3160
+ * Throws when the response is not a row array or a row is missing, because the caller cannot
3161
+ * then confirm which units TrainHeroic stored.
3162
+ */
3163
+ function matchSavedRows(saves, response, pwId) {
3164
+ if (!Array.isArray(response)) throw new Error(`saveWorkoutSetExercises returned an unexpected response shape for draft session ${pwId}.`);
3165
+ const rows = response.filter((row) => typeof row === "object" && row !== null);
3166
+ return saves.map((save) => {
3167
+ const row = rows.find((r) => coerceInt(r.order) === coerceInt(save.entry.order) && coerceInt(r.exercise_id) === coerceInt(save.entry.exercise_id));
3168
+ const id = coerceInt(row?.id);
3169
+ if (row === void 0 || id === null) throw new Error(`saveWorkoutSetExercises returned no row for exercise ${String(save.entry.exercise_id)} (order ${String(save.entry.order)}) on draft session ${pwId}.`);
3170
+ return {
3171
+ save,
3172
+ row,
3173
+ id
3174
+ };
3175
+ });
3176
+ }
3177
+ /** True when the stored row holds the requested type in every overridden slot. */
3178
+ function keepsOverrides(save, row) {
3179
+ return save.overrides.every((slot) => coerceInt(row[`param_${slot}_type`]) === coerceInt(save.entry[`param_${slot}_type`]));
3180
+ }
3181
+ /**
3182
+ * Save one block's exercises. TrainHeroic stores a newly inserted row with the exercise's
3183
+ * library param types whatever the request says, and keeps the requested types when the same
3184
+ * row is saved again with its `id`; the coach web app's unit picker saves single rows by id
3185
+ * the same way. So each row with an overridden slot (say %max load on a pounds lift) that the
3186
+ * insert stored in the library type is saved a second time by id. Throws when the second save
3187
+ * still does not hold the requested types, because the values would render in the wrong unit.
3188
+ */
3189
+ async function saveBlockExercises(client, pwId, saves) {
3190
+ const corrections = matchSavedRows(saves, await req(client, "POST", SAVE_EXERCISES_PATH, saves.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row)).map(({ save, id }) => ({
3191
+ entry: {
3192
+ ...save.entry,
3193
+ id
3194
+ },
3195
+ overrides: save.overrides
3196
+ }));
3197
+ if (corrections.length === 0) return;
3198
+ const unkept = matchSavedRows(corrections, await req(client, "POST", SAVE_EXERCISES_PATH, corrections.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row));
3199
+ if (unkept.length > 0) {
3200
+ const names = unkept.map(({ save, row }) => typeof row.title === "string" && row.title !== "" ? row.title : `exercise ${String(save.entry.exercise_id)}`).join(", ");
3201
+ throw new Error(`TrainHeroic did not keep the requested units for ${names} on draft session ${pwId}. Remove the draft or correct those exercises in the coach app.`);
3202
+ }
3203
+ }
3109
3204
  /**
3110
3205
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
3111
3206
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -3134,8 +3229,9 @@ async function buildSession(client, opts) {
3134
3229
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3135
3230
  const splitSummary = setSplitSummary(validatedBlocks);
3136
3231
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3137
- const advisories = await collectAdvisories(validatedBlocks, opts.index);
3138
- const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
3232
+ const resolved = await resolveExerciseUnits(validatedBlocks, opts.index);
3233
+ const advisories = resolved.advisories;
3234
+ const blocks = splitSummary === null ? resolved.blocks : splitOversizedBlocks(resolved.blocks);
3139
3235
  const sess = await req(client, "POST", createPath(opts), {});
3140
3236
  checkResponse(sessionCreateResponseSchema, sess, "session create");
3141
3237
  const workoutId = Number(sess.workout_id);
@@ -3148,9 +3244,13 @@ async function buildSession(client, opts) {
3148
3244
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
3149
3245
  return block.exercises.map((ex, j) => {
3150
3246
  counter += 1;
3151
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
3247
+ const defaults = resolved.defaultsById.get(Number(ex.id));
3248
+ return {
3249
+ entry: makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`),
3250
+ overrides: defaults === void 0 ? [] : overriddenSlots(ex, defaults)
3251
+ };
3152
3252
  });
3153
- }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
3253
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (saves) => saveBlockExercises(client, pwId, saves));
3154
3254
  if (opts.instruction !== void 0 && opts.instruction !== "") {
3155
3255
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
3156
3256
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -3199,6 +3299,7 @@ async function readSession(client, programId, date, pwId) {
3199
3299
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3200
3300
  return {
3201
3301
  pwId,
3302
+ workoutId: coerceInt(pw.workout_id),
3202
3303
  date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3203
3304
  published: pw.published,
3204
3305
  instruction: str(pw.instruction),
@@ -3601,9 +3702,26 @@ async function requestAnalytics(client, args) {
3601
3702
  body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
3602
3703
  }
3603
3704
  const res = await client.request("POST", spec.path, { body });
3604
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3705
+ if (!res.ok) {
3706
+ const message = trainHeroicApiErrorMessage(`Analytics ${args.metric}`, res.status, res.data);
3707
+ throw new Error(withHint(message, analyticsErrorHint(res.data)));
3708
+ }
3605
3709
  return res.data;
3606
3710
  }
3711
+ /**
3712
+ * Explain TrainHeroic's terse analytics rejections so the caller can fix its input.
3713
+ * lift-1rm-history answers "Invalid exercise id" for any exercise that is not a weighted lift
3714
+ * (verified with Run, Push-Up, and an unknown id; Back Squat succeeds).
3715
+ */
3716
+ function analyticsErrorHint(responseBody) {
3717
+ if (typeof responseBody === "string" && responseBody.includes("Invalid exercise id")) return "exerciseId must be a weighted lift such as Back Squat (id 1); bodyweight, distance, and unknown exercises are rejected.";
3718
+ return null;
3719
+ }
3720
+ /** Append a sentence of guidance to an error message that may or may not end in a period. */
3721
+ function withHint(message, hint) {
3722
+ if (hint === null) return message;
3723
+ return `${message.endsWith(".") ? message : `${message}.`} ${hint}`;
3724
+ }
3607
3725
  function reportRows(report) {
3608
3726
  if (report === null || typeof report !== "object") return null;
3609
3727
  const rows = report.rows;
@@ -3743,10 +3861,31 @@ async function createSessionTemplate(client, args) {
3743
3861
  if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
3744
3862
  return res.data;
3745
3863
  }
3864
+ /**
3865
+ * Copy an existing calendar session, with its blocks and exercises, into the coach's session
3866
+ * library as a new template
3867
+ * (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
3868
+ * the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
3869
+ * the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
3870
+ * has no `id`, or when the two ids are swapped.
3871
+ */
3872
+ async function saveSessionAsTemplate(client, args) {
3873
+ const title = args.title.trim();
3874
+ if (title === "") throw new Error("Session template title must not be blank.");
3875
+ const res = await client.request("POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${args.workoutId}`, { body: {
3876
+ id: args.pwId,
3877
+ title
3878
+ } });
3879
+ if (!res.ok) {
3880
+ const message = trainHeroicApiErrorMessage(`Saving session ${args.pwId} (workout ${args.workoutId}) as a template`, res.status, res.data);
3881
+ throw new Error(withHint(message, "Check that workoutId and pwId belong to the same session; a session read-back returns both."));
3882
+ }
3883
+ if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template save response is missing an id.");
3884
+ return res.data;
3885
+ }
3746
3886
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
3747
3887
  const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
3748
- //#endregion
3749
- //#region ../js/src/main-lifts.ts
3888
+ // ../js/src/main-lifts.ts
3750
3889
  /**
3751
3890
  * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
3752
3891
  * first family that matches, so the more specific / easily-confused families come before the broad
@@ -3958,8 +4097,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
3958
4097
  };
3959
4098
  });
3960
4099
  }
3961
- //#endregion
3962
- //#region ../js/src/messaging.ts
4100
+ // ../js/src/messaging.ts
3963
4101
  const BUCKETS = [
3964
4102
  ["team", "teams"],
3965
4103
  ["athlete", "athletes"],
@@ -4014,8 +4152,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
4014
4152
  if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
4015
4153
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
4016
4154
  }
4017
- //#endregion
4018
- //#region ../js/src/library-cache.ts
4155
+ // ../js/src/library-cache.ts
4019
4156
  /** In-memory cache (no persistence). The default when none is supplied. */
4020
4157
  var MemoryLibraryCache = class {
4021
4158
  #snapshot = null;
@@ -4026,8 +4163,7 @@ var MemoryLibraryCache = class {
4026
4163
  this.#snapshot = snapshot;
4027
4164
  }
4028
4165
  };
4029
- //#endregion
4030
- //#region ../js/src/exercise-index.ts
4166
+ // ../js/src/exercise-index.ts
4031
4167
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
4032
4168
  const CREATE_PATH = "/2.0/coach/exercise/create";
4033
4169
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
@@ -4233,8 +4369,7 @@ var ExerciseLibrary = class {
4233
4369
  };
4234
4370
  }
4235
4371
  };
4236
- //#endregion
4237
- //#region ../core/src/tools/reads.ts
4372
+ // ../core/src/tools/reads.ts
4238
4373
  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.";
4239
4374
  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.";
4240
4375
  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.";
@@ -4292,6 +4427,20 @@ const SIMPLE_GETS = [
4292
4427
  path: SESSION_TEMPLATES_LIST_PATH
4293
4428
  }
4294
4429
  ];
4430
+ /**
4431
+ * Body of the athlete_training handler. TrainHeroic's month summary answers HTTP 500 for some
4432
+ * athletes whose date-range read still works, so that failure names athlete_saved_workouts.
4433
+ */
4434
+ async function athleteTrainingResult(ctx, athleteId, year, month) {
4435
+ let raw;
4436
+ try {
4437
+ raw = await fetchCoachAthleteCalendarSummary(ctx.client, athleteId, year, month);
4438
+ } catch (error) {
4439
+ if (error instanceof CoachMonthSummaryError && error.status === 500) return errorResult(`${error.message} Call athlete_saved_workouts with startDate and endDate spanning the month.`);
4440
+ throw error;
4441
+ }
4442
+ return jsonResult(presentCoachAthleteTraining(raw, 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." });
4443
+ }
4295
4444
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
4296
4445
  function registerRosterReads(server, ctx) {
4297
4446
  server.registerTool("whoami", {
@@ -4407,9 +4556,7 @@ function registerEntityReads(server, ctx) {
4407
4556
  },
4408
4557
  outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
4409
4558
  annotations: READ
4410
- }, ({ athleteId, year, month }) => attempt(async () => {
4411
- 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." });
4412
- }));
4559
+ }, ({ athleteId, year, month }) => attempt(() => athleteTrainingResult(ctx, toId(athleteId), year, month)));
4413
4560
  server.registerTool("get_program", {
4414
4561
  title: "Get program detail",
4415
4562
  description: "Program detail live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). For standalone rows from list_programs, accepts either id (the container id) or group_program (the underlying program id); container ids are resolved automatically. If neither detail endpoint is available, returns calendar metadata and next-step guidance instead.",
@@ -4476,8 +4623,7 @@ function registerCoachAthleteTeamCalendar(server, ctx) {
4476
4623
  annotations: READ
4477
4624
  }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
4478
4625
  }
4479
- //#endregion
4480
- //#region ../core/src/tools/main-lifts.ts
4626
+ // ../core/src/tools/main-lifts.ts
4481
4627
  const monthsParam = z.number().int().positive().max(36).optional();
4482
4628
  const ATHLETE_DESC = "A roster athlete's personal records for the main barbell lifts (squat, bench press, deadlift, overhead press, clean & jerk, snatch). Pass athleteId from list_athletes — nothing else. It auto-discovers which exercise VARIANT the athlete actually logs for each lift (e.g. 'Back Squat', not the empty 'Squat' library entry) by scanning their recent training, so you do NOT resolve exercise ids yourself. Returns one row per lift family in a fixed order; a lift the athlete has not logged comes back with null fields (no PR yet). `months` (default 12) is how far back to look for the logged variants.";
4483
4629
  const ROSTER_DESC = "Every roster athlete's main-lift PRs in one call — the squad board for squat/bench/deadlift/overhead press/clean & jerk/snatch. Same per-athlete discovery as athlete_main_lift_prs, fanned out across the roster (bounded), so it makes many upstream calls; expect a few seconds on a big roster. Optional athleteIds restricts it to a subset (else the whole roster from /v5/athletes); `months` (default 12) sets the look-back for logged variants.";
@@ -4509,8 +4655,7 @@ function registerMainLiftTools(server, ctx) {
4509
4655
  }), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
4510
4656
  }));
4511
4657
  }
4512
- //#endregion
4513
- //#region ../core/src/tools/athlete-training.ts
4658
+ // ../core/src/tools/athlete-training.ts
4514
4659
  /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
4515
4660
  function mapSessionExercises(exercises) {
4516
4661
  return exercises.map((e) => {
@@ -4528,8 +4673,7 @@ function mapSessionExercises(exercises) {
4528
4673
  return mapped;
4529
4674
  });
4530
4675
  }
4531
- //#endregion
4532
- //#region ../core/src/tools/athletes.ts
4676
+ // ../core/src/tools/athletes.ts
4533
4677
  /** Normalize one-or-many emails into a deduped, trimmed list. */
4534
4678
  function asEmailList(emails) {
4535
4679
  return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -4728,8 +4872,7 @@ function registerAthletePrescribeTool(server, ctx) {
4728
4872
  }));
4729
4873
  }));
4730
4874
  }
4731
- //#endregion
4732
- //#region ../core/src/tools/teams.ts
4875
+ // ../core/src/tools/teams.ts
4733
4876
  /**
4734
4877
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
4735
4878
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -4835,8 +4978,7 @@ function registerTeamPublishSettings(server, ctx) {
4835
4978
  }));
4836
4979
  }));
4837
4980
  }
4838
- //#endregion
4839
- //#region ../core/src/tools/programs.ts
4981
+ // ../core/src/tools/programs.ts
4840
4982
  /** Standalone program writes. Program reads live in reads.ts. */
4841
4983
  function registerProgramTools(server, ctx) {
4842
4984
  server.registerTool("program_create", {
@@ -4868,9 +5010,8 @@ function registerProgramTools(server, ctx) {
4868
5010
  return jsonResult(await deleteProgram(ctx.client, id));
4869
5011
  }));
4870
5012
  }
4871
- //#endregion
4872
- //#region ../core/src/tools/analytics.ts
4873
- 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.";
5013
+ // ../core/src/tools/analytics.ts
5014
+ 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, a weighted lift such as Back Squat (lift-1rm-history answers 'Invalid exercise id' for bodyweight, distance, and unknown exercises). All dates are YYYY-MM-DD.";
4874
5015
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
4875
5016
  function registerAnalyticsTools(server, ctx) {
4876
5017
  server.registerTool("analytics_query", {
@@ -4899,8 +5040,7 @@ function registerAnalyticsTools(server, ctx) {
4899
5040
  useMetric
4900
5041
  })), { hint: "Narrow with a tighter date range or fewer athletes." })));
4901
5042
  }
4902
- //#endregion
4903
- //#region ../core/src/tools/exercises.ts
5043
+ // ../core/src/tools/exercises.ts
4904
5044
  function registerExerciseUpdate(server, index) {
4905
5045
  server.registerTool("exercise_update", {
4906
5046
  title: "Update custom exercise",
@@ -4940,7 +5080,7 @@ function registerExerciseDelete(server, index) {
4940
5080
  function registerExerciseReads(server, index) {
4941
5081
  server.registerTool("exercise_resolve", {
4942
5082
  title: "Resolve exercise name",
4943
- description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
5083
+ description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the exercise's default measurement units by entry slot; workout_build uses them unless a prescription states another unit. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
4944
5084
  inputSchema: { name: z.string().min(1) },
4945
5085
  outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
4946
5086
  annotations: READ
@@ -5017,13 +5157,12 @@ function registerExerciseTools(server, ctx) {
5017
5157
  annotations: READ
5018
5158
  }, () => attempt(async () => jsonResult(await index.stats())));
5019
5159
  }
5020
- //#endregion
5021
- //#region ../core/src/tools/workout.ts
5160
+ // ../core/src/tools/workout.ts
5022
5161
  /** Build a draft session (workout_build). */
5023
5162
  function registerBuild(server, ctx) {
5024
5163
  server.registerTool("workout_build", {
5025
5164
  title: "Build a workout session (draft)",
5026
- description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids and a read-back. For each exercise, state primaryUnit when reps is present and secondaryUnit when weight is present; these are positional values, even when the unit is distance or time. Use exercise_resolve to check the exercise's fixed units before building. A mismatch fails before the draft is created. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
5165
+ description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids and a read-back. For each exercise, state primaryUnit when reps is present and secondaryUnit when weight is present; these are positional values, even when the unit is distance or time. exercise_resolve lists each exercise's default units. A stated unit that differs from the default is set on this session, so % of max (secondaryUnit '%max') or RPE works on a built-in pounds lift and meters work on a miles exercise. A unit that conflicts with an explicit param_N_type fails before the draft is created. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
5027
5166
  inputSchema: {
5028
5167
  programId: z.number().optional(),
5029
5168
  athleteId: idParam.optional(),
@@ -5153,11 +5292,15 @@ function registerLifecycle(server, ctx) {
5153
5292
  }))));
5154
5293
  server.registerTool("session_save_as_template", {
5155
5294
  title: "Save a session to the library",
5156
- description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
5157
- inputSchema: { workoutId: z.number() },
5295
+ description: "Copy an existing calendar session, with its blocks and exercises, into the session library as a new template (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the session's workoutId and pwId (workout_build returns both; workout_read returns both for a session on a date) and a title for the template.",
5296
+ inputSchema: sessionSaveAsTemplateSchema.shape,
5158
5297
  outputSchema: opaqueOutputSchema,
5159
5298
  annotations: ADDITIVE
5160
- }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
5299
+ }, ({ workoutId, pwId, title }) => attempt(async () => jsonResult(await saveSessionAsTemplate(ctx.client, {
5300
+ workoutId,
5301
+ pwId,
5302
+ title
5303
+ }))));
5161
5304
  }
5162
5305
  function registerTemplateLibrary(server, ctx) {
5163
5306
  server.registerTool("session_template_create", {
@@ -5193,8 +5336,7 @@ function registerWorkoutTools(server, ctx) {
5193
5336
  registerLifecycle(server, ctx);
5194
5337
  registerTemplateLibrary(server, ctx);
5195
5338
  }
5196
- //#endregion
5197
- //#region ../core/src/tools/messaging.ts
5339
+ // ../core/src/tools/messaging.ts
5198
5340
  function registerReads(server, ctx) {
5199
5341
  server.registerTool("messaging_conversations", {
5200
5342
  title: "List conversations (live)",
@@ -5284,8 +5426,7 @@ function registerMessagingTools(server, ctx) {
5284
5426
  registerReads(server, ctx);
5285
5427
  registerWrites(server, ctx);
5286
5428
  }
5287
- //#endregion
5288
- //#region ../core/src/tools/coach.ts
5429
+ // ../core/src/tools/coach.ts
5289
5430
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
5290
5431
  function registerCoachTools(server, ctx) {
5291
5432
  registerReadTools(server, ctx);
@@ -5298,8 +5439,7 @@ function registerCoachTools(server, ctx) {
5298
5439
  registerWorkoutTools(server, ctx);
5299
5440
  registerMessagingTools(server, ctx);
5300
5441
  }
5301
- //#endregion
5302
- //#region ../js/src/node.ts
5442
+ // ../js/src/node.ts
5303
5443
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
5304
5444
  function defaultCachePath() {
5305
5445
  return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
@@ -5322,11 +5462,9 @@ var JsonFileLibraryCache = class {
5322
5462
  await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
5323
5463
  }
5324
5464
  };
5325
- //#endregion
5326
- //#region package.json
5327
- var version = "4.2.0";
5328
- //#endregion
5329
- //#region src/server.ts
5465
+ // package.json
5466
+ var version = "4.3.0";
5467
+ // src/server.ts
5330
5468
  function main() {
5331
5469
  const email = process.env.TRAINHEROIC_EMAIL;
5332
5470
  const password = process.env.TRAINHEROIC_PASSWORD;
@@ -5349,5 +5487,4 @@ function main() {
5349
5487
  });
5350
5488
  }
5351
5489
  main();
5352
- //#endregion
5353
5490
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,17 +19,17 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@modelcontextprotocol/server": "2.3.1",
23
- "zod": "^4.6.5",
24
- "@trainheroic-unofficial/core": "4.2.0",
25
- "@trainheroic-unofficial/js": "4.2.0"
22
+ "@modelcontextprotocol/server": "2.4.0",
23
+ "zod": "^4.6.7",
24
+ "@trainheroic-unofficial/core": "4.3.0",
25
+ "@trainheroic-unofficial/js": "4.3.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.6.4",
29
- "tsdown": "^0.23.0",
28
+ "@types/node": "^26.6.6",
29
+ "tsdown": "^0.23.7",
30
30
  "tsx": "^4.23.15",
31
31
  "typescript": "^7.0.2",
32
- "vitest": "^5.0.3"
32
+ "vitest": "^5.1.0"
33
33
  },
34
34
  "scripts": {
35
35
  "start": "tsx src/server.ts",