@trainheroic-unofficial/coach-mcp 4.1.1 → 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 +331 -169
  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;
@@ -1321,6 +1316,28 @@ var TrainHeroicHttpError = class extends Error {
1321
1316
  this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
1322
1317
  }
1323
1318
  };
1319
+ /**
1320
+ * True for statuses that mean TrainHeroic's servers could not be reached or did not answer: a
1321
+ * gateway failure (502, 503, 504) or a Cloudflare edge error (520-530). TrainHeroic sits behind
1322
+ * Cloudflare, so a 522 means the edge timed out connecting to TrainHeroic's origin. These describe
1323
+ * an upstream outage, so the same request can succeed when retried later.
1324
+ */
1325
+ function isTrainHeroicUnavailableStatus(status) {
1326
+ return status === 502 || status === 503 || status === 504 || status >= 520 && status <= 530;
1327
+ }
1328
+ /**
1329
+ * Thrown when TrainHeroic answers with an outage status (see `isTrainHeroicUnavailableStatus`).
1330
+ * The message tells the reader to retry later, so a model relaying it does not ask the user to
1331
+ * re-check credentials that are fine.
1332
+ */
1333
+ var TrainHeroicUnavailableError = class extends Error {
1334
+ name = "TrainHeroicUnavailableError";
1335
+ status;
1336
+ constructor(status) {
1337
+ super(`TrainHeroic is not responding right now (HTTP ${status}). Try again in a few minutes.`);
1338
+ this.status = status;
1339
+ }
1340
+ };
1324
1341
  /** Call observability hooks without allowing them to change SDK behavior. */
1325
1342
  function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1326
1343
  if (!handler) return;
@@ -1328,11 +1345,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1328
1345
  Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1329
1346
  } catch {}
1330
1347
  }
1331
- //#endregion
1332
- //#region ../js/src/transport.ts
1348
+ // ../js/src/transport.ts
1333
1349
  const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1334
- //#endregion
1335
- //#region ../js/src/auth.ts
1350
+ // ../js/src/auth.ts
1336
1351
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1337
1352
  /**
1338
1353
  * The login endpoint, allowing an env override so a test harness can authenticate against a local
@@ -1348,8 +1363,10 @@ function authUrl() {
1348
1363
  return DEFAULT_AUTH_URL;
1349
1364
  }
1350
1365
  /**
1351
- * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
1352
- * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
1366
+ * Authenticate against TrainHeroic. Returns the session bundle, or null when TrainHeroic
1367
+ * rejects the login. Throws `TrainHeroicUnavailableError` when TrainHeroic is unreachable (an
1368
+ * outage status such as a Cloudflare 522), so callers can tell the user to retry later.
1369
+ * TrainHeroic returns only { id, scope, role, session_id } (verified in
1353
1370
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
1354
1371
  * is sent as the `session-token` header and works against both API hosts.
1355
1372
  */
@@ -1369,6 +1386,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1369
1386
  if (!res.ok) {
1370
1387
  await res.body?.cancel().catch(() => {});
1371
1388
  notifyHttpError(options.onHttpError, "POST", url, res.status);
1389
+ if (isTrainHeroicUnavailableStatus(res.status)) throw new TrainHeroicUnavailableError(res.status);
1372
1390
  return null;
1373
1391
  }
1374
1392
  const data = await res.json().catch(() => null);
@@ -1380,8 +1398,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1380
1398
  role: data.role ?? ""
1381
1399
  };
1382
1400
  }
1383
- //#endregion
1384
- //#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
1385
1402
  /**
1386
1403
  * Splits an array into smaller arrays of a specified length.
1387
1404
  *
@@ -1416,8 +1433,7 @@ function chunk(arr, size) {
1416
1433
  }
1417
1434
  return result;
1418
1435
  }
1419
- //#endregion
1420
- //#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
1421
1437
  /**
1422
1438
  * Creates a duplicate-free version of an array.
1423
1439
  *
@@ -1436,13 +1452,12 @@ function chunk(arr, size) {
1436
1452
  function uniq(arr) {
1437
1453
  return [...new Set(arr)];
1438
1454
  }
1439
- //#endregion
1440
- //#region ../js/src/exercise-util.ts
1455
+ // ../js/src/exercise-util.ts
1441
1456
  /**
1442
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
1443
- * (the API forces param_1_type/param_2_type back to the library default on save), so
1444
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
1445
- * 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.
1446
1461
  */
1447
1462
  const PARAM_UNIT = {
1448
1463
  0: null,
@@ -1483,7 +1498,7 @@ function unitLabel(paramType) {
1483
1498
  return PARAM_UNIT[t] ?? null;
1484
1499
  }
1485
1500
  /**
1486
- * 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).
1487
1502
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
1488
1503
  * by role. A null entry is an unset slot.
1489
1504
  */
@@ -1672,8 +1687,7 @@ function createLimiter(max) {
1672
1687
  function assertPositiveInteger(value, label) {
1673
1688
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1674
1689
  }
1675
- //#endregion
1676
- //#region ../js/src/client.ts
1690
+ // ../js/src/client.ts
1677
1691
  const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1678
1692
  const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1679
1693
  const MAX_REQUEST_CONCURRENCY = 4;
@@ -1793,8 +1807,7 @@ var TrainHeroicClient = class {
1793
1807
  return this.#transport(url, init);
1794
1808
  }
1795
1809
  };
1796
- //#endregion
1797
- //#region ../js/src/response-check.ts
1810
+ // ../js/src/response-check.ts
1798
1811
  /**
1799
1812
  * Validate an API response against its (loose) expected shape and warn once on drift.
1800
1813
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
@@ -1807,8 +1820,7 @@ function checkResponse(schema, data, label) {
1807
1820
  const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1808
1821
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1809
1822
  }
1810
- //#endregion
1811
- //#region ../js/src/athlete.ts
1823
+ // ../js/src/athlete.ts
1812
1824
  async function getJson(client, path, label) {
1813
1825
  const res = await client.request("GET", path);
1814
1826
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2135,8 +2147,7 @@ function presentExerciseHistory(detail) {
2135
2147
  }))
2136
2148
  };
2137
2149
  }
2138
- //#endregion
2139
- //#region ../js/src/exercise-history.ts
2150
+ // ../js/src/exercise-history.ts
2140
2151
  /**
2141
2152
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2142
2153
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -2157,8 +2168,7 @@ function historyInRange(presented, since, until) {
2157
2168
  sessions
2158
2169
  };
2159
2170
  }
2160
- //#endregion
2161
- //#region ../js/src/coach-athlete-calendar.ts
2171
+ // ../js/src/coach-athlete-calendar.ts
2162
2172
  async function getArray(client, path, label) {
2163
2173
  const res = await client.request("GET", path);
2164
2174
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2173,14 +2183,34 @@ async function getArray(client, path, label) {
2173
2183
  function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
2174
2184
  return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
2175
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
+ };
2176
2195
  /**
2177
2196
  * A coach's month view of a roster athlete's logged sessions
2178
2197
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
2179
2198
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
2180
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.
2181
2203
  */
2182
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2183
- 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);
2184
2214
  }
2185
2215
  /**
2186
2216
  * Resolve a roster athlete's coach-writable calendar program id
@@ -2221,8 +2251,7 @@ async function resolveBuildProgramId(client, args) {
2221
2251
  const [y, m] = parseWorkoutDate(args.date);
2222
2252
  return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
2223
2253
  }
2224
- //#endregion
2225
- //#region ../js/src/exercise-set-payload.ts
2254
+ // ../js/src/exercise-set-payload.ts
2226
2255
  function slotData(exercise, key) {
2227
2256
  const value = exercise?.[key];
2228
2257
  return value === void 0 || value === null ? "" : String(value);
@@ -2290,8 +2319,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
2290
2319
  body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
2291
2320
  return body;
2292
2321
  }
2293
- //#endregion
2294
- //#region ../js/src/athlete-set-write.ts
2322
+ // ../js/src/athlete-set-write.ts
2295
2323
  const WRITE_CONCURRENCY = 4;
2296
2324
  /**
2297
2325
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -2723,8 +2751,7 @@ async function logSessionForAthlete(client, args) {
2723
2751
  sets
2724
2752
  };
2725
2753
  }
2726
- //#endregion
2727
- //#region ../js/src/util.ts
2754
+ // ../js/src/util.ts
2728
2755
  /**
2729
2756
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2730
2757
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -2739,8 +2766,7 @@ function definedProps(obj) {
2739
2766
  for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2740
2767
  return result;
2741
2768
  }
2742
- //#endregion
2743
- //#region ../js/src/workout-encode.ts
2769
+ // ../js/src/workout-encode.ts
2744
2770
  const LEADERBOARD_TYPE = {
2745
2771
  completion: 0,
2746
2772
  "for completion": 0,
@@ -2914,7 +2940,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2914
2940
  param2Type = ex.param_2_type ?? 1;
2915
2941
  param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2916
2942
  } else {
2917
- param2Type = 0;
2943
+ param2Type = ex.param_2_type ?? 0;
2918
2944
  param2Values = null;
2919
2945
  }
2920
2946
  const entry = {
@@ -2973,9 +2999,6 @@ function buildBlockPayload(blocks, workoutId) {
2973
2999
  };
2974
3000
  });
2975
3001
  }
2976
- function unitOr(t) {
2977
- return unitLabel(t) ?? "?";
2978
- }
2979
3002
  const UNIT_ALIASES = {
2980
3003
  rep: "reps",
2981
3004
  reps: "reps",
@@ -3013,74 +3036,171 @@ function statedUnit(value, label) {
3013
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.`);
3014
3037
  return normalized;
3015
3038
  }
3016
- 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";
3017
3052
  if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3018
3053
  const intended = statedUnit(stated, `${label} / ${field}`);
3019
- const fixed = unitLabel(fixedType);
3020
- 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.`);
3021
- if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3022
- }
3023
- /** Validate both populated slots against the library before any workout write. */
3024
- function validateExerciseUnits(blockTitle, ex, defaults) {
3025
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3026
- if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3027
- if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3028
- }
3029
- /** Flag spec params the API will silently override to the exercise's fixed units. */
3030
- 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) {
3031
3101
  const notes = [];
3032
3102
  const warnings = [];
3033
- const u = unitOr;
3034
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3103
+ const u = unitName;
3035
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).`);
3036
- const sentP1 = ex.param_1_type;
3037
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
3038
- const sp1 = Math.trunc(Number(sentP1));
3039
- 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)}.`);
3040
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
3041
- if (ex.weight !== void 0 && ex.weight !== null) {
3042
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3043
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
3044
- if (sentP2 !== effP2) {
3045
- 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.`);
3046
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
3047
- }
3048
- }
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)}.`);
3049
3110
  return {
3050
3111
  notes,
3051
3112
  warnings
3052
3113
  };
3053
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
+ }
3054
3122
  /**
3055
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
3056
- * then collect non-blocking advisories. The write path calls this before creating a workout;
3057
- * 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.
3058
3127
  */
3059
- async function collectAdvisories(blocks, index) {
3060
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
3061
- block: b,
3062
- ex
3063
- })));
3064
- 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))];
3065
3130
  const defaultsById = await index.currentDefaultsMany(ids);
3066
3131
  const notes = [];
3067
3132
  const warnings = [];
3068
- pairs.forEach((p) => {
3069
- const def = defaultsById.get(Number(p.ex.id));
3070
- 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.`);
3071
- validateExerciseUnits(p.block.title, p.ex, def);
3072
- const advisory = unitAdvisory(p.block.title, p.ex, def);
3073
- notes.push(...advisory.notes);
3074
- warnings.push(...advisory.warnings);
3075
- });
3076
3133
  return {
3077
- notes,
3078
- 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
+ }
3079
3152
  };
3080
3153
  }
3081
- //#endregion
3082
- //#region ../js/src/workout-session.ts
3154
+ // ../js/src/workout-session.ts
3083
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
+ }
3084
3204
  /**
3085
3205
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
3086
3206
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -3109,8 +3229,9 @@ async function buildSession(client, opts) {
3109
3229
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3110
3230
  const splitSummary = setSplitSummary(validatedBlocks);
3111
3231
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3112
- const advisories = await collectAdvisories(validatedBlocks, opts.index);
3113
- 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);
3114
3235
  const sess = await req(client, "POST", createPath(opts), {});
3115
3236
  checkResponse(sessionCreateResponseSchema, sess, "session create");
3116
3237
  const workoutId = Number(sess.workout_id);
@@ -3123,9 +3244,13 @@ async function buildSession(client, opts) {
3123
3244
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
3124
3245
  return block.exercises.map((ex, j) => {
3125
3246
  counter += 1;
3126
- 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
+ };
3127
3252
  });
3128
- }).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));
3129
3254
  if (opts.instruction !== void 0 && opts.instruction !== "") {
3130
3255
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
3131
3256
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -3174,6 +3299,7 @@ async function readSession(client, programId, date, pwId) {
3174
3299
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3175
3300
  return {
3176
3301
  pwId,
3302
+ workoutId: coerceInt(pw.workout_id),
3177
3303
  date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3178
3304
  published: pw.published,
3179
3305
  instruction: str(pw.instruction),
@@ -3576,9 +3702,26 @@ async function requestAnalytics(client, args) {
3576
3702
  body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
3577
3703
  }
3578
3704
  const res = await client.request("POST", spec.path, { body });
3579
- 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
+ }
3580
3709
  return res.data;
3581
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
+ }
3582
3725
  function reportRows(report) {
3583
3726
  if (report === null || typeof report !== "object") return null;
3584
3727
  const rows = report.rows;
@@ -3718,10 +3861,31 @@ async function createSessionTemplate(client, args) {
3718
3861
  if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
3719
3862
  return res.data;
3720
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
+ }
3721
3886
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
3722
3887
  const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
3723
- //#endregion
3724
- //#region ../js/src/main-lifts.ts
3888
+ // ../js/src/main-lifts.ts
3725
3889
  /**
3726
3890
  * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
3727
3891
  * first family that matches, so the more specific / easily-confused families come before the broad
@@ -3933,8 +4097,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
3933
4097
  };
3934
4098
  });
3935
4099
  }
3936
- //#endregion
3937
- //#region ../js/src/messaging.ts
4100
+ // ../js/src/messaging.ts
3938
4101
  const BUCKETS = [
3939
4102
  ["team", "teams"],
3940
4103
  ["athlete", "athletes"],
@@ -3989,8 +4152,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
3989
4152
  if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
3990
4153
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
3991
4154
  }
3992
- //#endregion
3993
- //#region ../js/src/library-cache.ts
4155
+ // ../js/src/library-cache.ts
3994
4156
  /** In-memory cache (no persistence). The default when none is supplied. */
3995
4157
  var MemoryLibraryCache = class {
3996
4158
  #snapshot = null;
@@ -4001,8 +4163,7 @@ var MemoryLibraryCache = class {
4001
4163
  this.#snapshot = snapshot;
4002
4164
  }
4003
4165
  };
4004
- //#endregion
4005
- //#region ../js/src/exercise-index.ts
4166
+ // ../js/src/exercise-index.ts
4006
4167
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
4007
4168
  const CREATE_PATH = "/2.0/coach/exercise/create";
4008
4169
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
@@ -4208,8 +4369,7 @@ var ExerciseLibrary = class {
4208
4369
  };
4209
4370
  }
4210
4371
  };
4211
- //#endregion
4212
- //#region ../core/src/tools/reads.ts
4372
+ // ../core/src/tools/reads.ts
4213
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.";
4214
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.";
4215
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.";
@@ -4267,6 +4427,20 @@ const SIMPLE_GETS = [
4267
4427
  path: SESSION_TEMPLATES_LIST_PATH
4268
4428
  }
4269
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
+ }
4270
4444
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
4271
4445
  function registerRosterReads(server, ctx) {
4272
4446
  server.registerTool("whoami", {
@@ -4382,9 +4556,7 @@ function registerEntityReads(server, ctx) {
4382
4556
  },
4383
4557
  outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
4384
4558
  annotations: READ
4385
- }, ({ athleteId, year, month }) => attempt(async () => {
4386
- 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." });
4387
- }));
4559
+ }, ({ athleteId, year, month }) => attempt(() => athleteTrainingResult(ctx, toId(athleteId), year, month)));
4388
4560
  server.registerTool("get_program", {
4389
4561
  title: "Get program detail",
4390
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.",
@@ -4451,8 +4623,7 @@ function registerCoachAthleteTeamCalendar(server, ctx) {
4451
4623
  annotations: READ
4452
4624
  }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
4453
4625
  }
4454
- //#endregion
4455
- //#region ../core/src/tools/main-lifts.ts
4626
+ // ../core/src/tools/main-lifts.ts
4456
4627
  const monthsParam = z.number().int().positive().max(36).optional();
4457
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.";
4458
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.";
@@ -4484,8 +4655,7 @@ function registerMainLiftTools(server, ctx) {
4484
4655
  }), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
4485
4656
  }));
4486
4657
  }
4487
- //#endregion
4488
- //#region ../core/src/tools/athlete-training.ts
4658
+ // ../core/src/tools/athlete-training.ts
4489
4659
  /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
4490
4660
  function mapSessionExercises(exercises) {
4491
4661
  return exercises.map((e) => {
@@ -4503,8 +4673,7 @@ function mapSessionExercises(exercises) {
4503
4673
  return mapped;
4504
4674
  });
4505
4675
  }
4506
- //#endregion
4507
- //#region ../core/src/tools/athletes.ts
4676
+ // ../core/src/tools/athletes.ts
4508
4677
  /** Normalize one-or-many emails into a deduped, trimmed list. */
4509
4678
  function asEmailList(emails) {
4510
4679
  return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -4703,8 +4872,7 @@ function registerAthletePrescribeTool(server, ctx) {
4703
4872
  }));
4704
4873
  }));
4705
4874
  }
4706
- //#endregion
4707
- //#region ../core/src/tools/teams.ts
4875
+ // ../core/src/tools/teams.ts
4708
4876
  /**
4709
4877
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
4710
4878
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -4810,8 +4978,7 @@ function registerTeamPublishSettings(server, ctx) {
4810
4978
  }));
4811
4979
  }));
4812
4980
  }
4813
- //#endregion
4814
- //#region ../core/src/tools/programs.ts
4981
+ // ../core/src/tools/programs.ts
4815
4982
  /** Standalone program writes. Program reads live in reads.ts. */
4816
4983
  function registerProgramTools(server, ctx) {
4817
4984
  server.registerTool("program_create", {
@@ -4843,9 +5010,8 @@ function registerProgramTools(server, ctx) {
4843
5010
  return jsonResult(await deleteProgram(ctx.client, id));
4844
5011
  }));
4845
5012
  }
4846
- //#endregion
4847
- //#region ../core/src/tools/analytics.ts
4848
- 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.";
4849
5015
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
4850
5016
  function registerAnalyticsTools(server, ctx) {
4851
5017
  server.registerTool("analytics_query", {
@@ -4874,8 +5040,7 @@ function registerAnalyticsTools(server, ctx) {
4874
5040
  useMetric
4875
5041
  })), { hint: "Narrow with a tighter date range or fewer athletes." })));
4876
5042
  }
4877
- //#endregion
4878
- //#region ../core/src/tools/exercises.ts
5043
+ // ../core/src/tools/exercises.ts
4879
5044
  function registerExerciseUpdate(server, index) {
4880
5045
  server.registerTool("exercise_update", {
4881
5046
  title: "Update custom exercise",
@@ -4915,7 +5080,7 @@ function registerExerciseDelete(server, index) {
4915
5080
  function registerExerciseReads(server, index) {
4916
5081
  server.registerTool("exercise_resolve", {
4917
5082
  title: "Resolve exercise name",
4918
- 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.",
4919
5084
  inputSchema: { name: z.string().min(1) },
4920
5085
  outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
4921
5086
  annotations: READ
@@ -4992,13 +5157,12 @@ function registerExerciseTools(server, ctx) {
4992
5157
  annotations: READ
4993
5158
  }, () => attempt(async () => jsonResult(await index.stats())));
4994
5159
  }
4995
- //#endregion
4996
- //#region ../core/src/tools/workout.ts
5160
+ // ../core/src/tools/workout.ts
4997
5161
  /** Build a draft session (workout_build). */
4998
5162
  function registerBuild(server, ctx) {
4999
5163
  server.registerTool("workout_build", {
5000
5164
  title: "Build a workout session (draft)",
5001
- 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.",
5002
5166
  inputSchema: {
5003
5167
  programId: z.number().optional(),
5004
5168
  athleteId: idParam.optional(),
@@ -5128,11 +5292,15 @@ function registerLifecycle(server, ctx) {
5128
5292
  }))));
5129
5293
  server.registerTool("session_save_as_template", {
5130
5294
  title: "Save a session to the library",
5131
- description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
5132
- 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,
5133
5297
  outputSchema: opaqueOutputSchema,
5134
5298
  annotations: ADDITIVE
5135
- }, ({ 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
+ }))));
5136
5304
  }
5137
5305
  function registerTemplateLibrary(server, ctx) {
5138
5306
  server.registerTool("session_template_create", {
@@ -5168,8 +5336,7 @@ function registerWorkoutTools(server, ctx) {
5168
5336
  registerLifecycle(server, ctx);
5169
5337
  registerTemplateLibrary(server, ctx);
5170
5338
  }
5171
- //#endregion
5172
- //#region ../core/src/tools/messaging.ts
5339
+ // ../core/src/tools/messaging.ts
5173
5340
  function registerReads(server, ctx) {
5174
5341
  server.registerTool("messaging_conversations", {
5175
5342
  title: "List conversations (live)",
@@ -5259,8 +5426,7 @@ function registerMessagingTools(server, ctx) {
5259
5426
  registerReads(server, ctx);
5260
5427
  registerWrites(server, ctx);
5261
5428
  }
5262
- //#endregion
5263
- //#region ../core/src/tools/coach.ts
5429
+ // ../core/src/tools/coach.ts
5264
5430
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
5265
5431
  function registerCoachTools(server, ctx) {
5266
5432
  registerReadTools(server, ctx);
@@ -5273,8 +5439,7 @@ function registerCoachTools(server, ctx) {
5273
5439
  registerWorkoutTools(server, ctx);
5274
5440
  registerMessagingTools(server, ctx);
5275
5441
  }
5276
- //#endregion
5277
- //#region ../js/src/node.ts
5442
+ // ../js/src/node.ts
5278
5443
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
5279
5444
  function defaultCachePath() {
5280
5445
  return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
@@ -5297,11 +5462,9 @@ var JsonFileLibraryCache = class {
5297
5462
  await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
5298
5463
  }
5299
5464
  };
5300
- //#endregion
5301
- //#region package.json
5302
- var version = "4.1.1";
5303
- //#endregion
5304
- //#region src/server.ts
5465
+ // package.json
5466
+ var version = "4.3.0";
5467
+ // src/server.ts
5305
5468
  function main() {
5306
5469
  const email = process.env.TRAINHEROIC_EMAIL;
5307
5470
  const password = process.env.TRAINHEROIC_PASSWORD;
@@ -5324,5 +5487,4 @@ function main() {
5324
5487
  });
5325
5488
  }
5326
5489
  main();
5327
- //#endregion
5328
5490
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "4.1.1",
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.1.1",
25
- "@trainheroic-unofficial/js": "4.1.1"
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",