@trainheroic-unofficial/coach-mcp 2.0.1 → 2.1.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 +940 -811
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -317,13 +317,24 @@ const leaderboardSpecSchema = z.union([
317
317
  instruction: z.string().optional()
318
318
  })
319
319
  ]);
320
- /** A block (group of exercises); two exercises render as a superset. */
320
+ /**
321
+ * A block (group of exercises); two exercises render as a superset.
322
+ * Empty `exercises` is allowed only with a non-empty `instruction` — that is TrainHeroic's
323
+ * free-text Circuit / Conditioning block (type 1): title + instruction blurb, no linked lifts.
324
+ */
321
325
  const blockSpecSchema = z.object({
322
326
  title: z.string(),
323
327
  type: z.number().optional(),
324
328
  instruction: z.string().optional(),
325
329
  leaderboard: leaderboardSpecSchema.optional(),
326
330
  exercises: z.array(exerciseSpecSchema)
331
+ }).superRefine((block, ctx) => {
332
+ if (block.exercises.length > 0) return;
333
+ if ((block.instruction?.trim() ?? "") === "") ctx.addIssue({
334
+ code: "custom",
335
+ message: "A block with no exercises needs a non-empty instruction (text-only Circuit / Conditioning block). Otherwise provide at least one exercise.",
336
+ path: ["exercises"]
337
+ });
327
338
  });
328
339
  z.object({
329
340
  blocks: z.array(blockSpecSchema),
@@ -914,7 +925,7 @@ async function getJson(client, path, label) {
914
925
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
915
926
  return res.data;
916
927
  }
917
- async function getArray(client, path, label) {
928
+ async function getArray$1(client, path, label) {
918
929
  const res = await client.request("GET", path);
919
930
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
920
931
  return res.data;
@@ -984,25 +995,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
984
995
  }
985
996
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
986
997
  function fetchAthleteWorkouts(client, startDate, endDate) {
987
- return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
988
- }
989
- /**
990
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
991
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
992
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
993
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
994
- */
995
- function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
996
- return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
997
- }
998
- /**
999
- * A coach's month view of a roster athlete's logged sessions
1000
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1001
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1002
- * `userId` in each row is the roster athlete, not the calling coach.
1003
- */
1004
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1005
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
998
+ return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
1006
999
  }
1007
1000
  function nonEmpty(value) {
1008
1001
  return value !== void 0 && value !== null && String(value).trim() !== "";
@@ -1360,6 +1353,70 @@ function presentExerciseHistory(detail) {
1360
1353
  };
1361
1354
  }
1362
1355
  //#endregion
1356
+ //#region ../js/src/coach-athlete-calendar.ts
1357
+ async function getArray(client, path, label) {
1358
+ const res = await client.request("GET", path);
1359
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
1360
+ return res.data;
1361
+ }
1362
+ /**
1363
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1364
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1365
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1366
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1367
+ */
1368
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1369
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1370
+ }
1371
+ /**
1372
+ * A coach's month view of a roster athlete's logged sessions
1373
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1374
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1375
+ * `userId` in each row is the roster athlete, not the calling coach.
1376
+ */
1377
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1378
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1379
+ }
1380
+ /**
1381
+ * Resolve a roster athlete's coach-writable calendar program id
1382
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
1383
+ *
1384
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
1385
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
1386
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
1387
+ * from athlete-created `personal_cal` ad-hoc sessions.
1388
+ */
1389
+ async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
1390
+ const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
1391
+ const res = await client.request("GET", path);
1392
+ if (!res.ok) {
1393
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1394
+ throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
1395
+ }
1396
+ if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
1397
+ const programId = coerceInt(res.data.id);
1398
+ if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
1399
+ return {
1400
+ programId,
1401
+ title: str$1(res.data.title) ?? "",
1402
+ type: coerceInt(res.data.type),
1403
+ groupId: coerceInt(res.data.group_id)
1404
+ };
1405
+ }
1406
+ /**
1407
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
1408
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
1409
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
1410
+ */
1411
+ async function resolveBuildProgramId(client, args) {
1412
+ if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
1413
+ if (args.programId !== void 0) return args.programId;
1414
+ if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
1415
+ if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
1416
+ const [y, m] = parseWorkoutDate(args.date);
1417
+ return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1418
+ }
1419
+ //#endregion
1363
1420
  //#region ../js/src/exercise-set-payload.ts
1364
1421
  function slotData(exercise, key) {
1365
1422
  const value = exercise?.[key];
@@ -1837,856 +1894,910 @@ async function logSessionForAthlete(client, args) {
1837
1894
  sets
1838
1895
  };
1839
1896
  }
1840
- /** Normalize one-or-many emails into a deduped, trimmed list. */
1841
- function emailList(emails) {
1842
- return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1843
- }
1844
- /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
1845
- function rosterName(rec) {
1846
- const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
1847
- if (full !== "") return full;
1848
- const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
1849
- return combined !== "" ? combined : null;
1897
+ //#endregion
1898
+ //#region ../js/src/workout-encode.ts
1899
+ const LEADERBOARD_TYPE = {
1900
+ completion: 0,
1901
+ "for completion": 0,
1902
+ weight: 1,
1903
+ lb: 1,
1904
+ load: 1,
1905
+ reps: 2,
1906
+ rep: 2,
1907
+ rounds: 3,
1908
+ round: 3,
1909
+ time: 4,
1910
+ yards: 5,
1911
+ yd: 5,
1912
+ meters: 6,
1913
+ m: 6,
1914
+ feet: 7,
1915
+ ft: 7,
1916
+ calories: 8,
1917
+ cal: 8,
1918
+ cals: 8,
1919
+ miles: 10,
1920
+ mi: 10,
1921
+ inches: 12,
1922
+ in: 12,
1923
+ watts: 15,
1924
+ w: 15,
1925
+ velocity: 17,
1926
+ "m/s": 17,
1927
+ seconds: 18,
1928
+ sec: 18,
1929
+ s: 18
1930
+ };
1931
+ const LEADERBOARD_LABEL = {
1932
+ 0: "For Completion",
1933
+ 1: "Weight",
1934
+ 2: "Reps",
1935
+ 3: "Rounds",
1936
+ 4: "Time",
1937
+ 5: "Yards",
1938
+ 6: "Meters",
1939
+ 7: "Feet",
1940
+ 8: "Calories",
1941
+ 10: "Miles",
1942
+ 12: "Inches",
1943
+ 13: "Other",
1944
+ 15: "Watts",
1945
+ 16: "Percent",
1946
+ 17: "Velocity",
1947
+ 18: "Seconds"
1948
+ };
1949
+ function resolveLeaderboard(block) {
1950
+ const lb = block.leaderboard;
1951
+ if (lb === void 0 || lb === null) return {
1952
+ isRedzone: null,
1953
+ redzoneType: 0,
1954
+ smallerIsBetter: null,
1955
+ redzoneInstruction: ""
1956
+ };
1957
+ let unit;
1958
+ let instruction = "";
1959
+ let lowest;
1960
+ if (typeof lb === "object") {
1961
+ unit = lb.unit ?? lb.type;
1962
+ instruction = lb.instruction ?? "";
1963
+ lowest = lb.lowest_wins;
1964
+ } else unit = lb;
1965
+ let rz;
1966
+ if (typeof unit === "string") {
1967
+ const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
1968
+ if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
1969
+ rz = found;
1970
+ } else if (typeof unit === "number") rz = Math.trunc(unit);
1971
+ else throw new Error("Leaderboard requires a unit.");
1972
+ if (lowest === void 0) lowest = rz === 4 || rz === 18;
1973
+ return {
1974
+ isRedzone: 1,
1975
+ redzoneType: rz,
1976
+ smallerIsBetter: lowest ? 1 : 0,
1977
+ redzoneInstruction: instruction
1978
+ };
1850
1979
  }
1851
- /**
1852
- * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
1853
- * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
1854
- * and the warehouse store map the roster identically. Includes the account owner and
1855
- * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
1856
- */
1857
- async function fetchCoachRoster(client, ids) {
1858
- const res = await client.request("GET", "/v5/athletes");
1859
- if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1860
- const keep = ids && ids.length > 0 ? new Set(ids) : null;
1980
+ function slots(values, n = 10) {
1861
1981
  const out = [];
1862
- for (const row of res.data) {
1863
- if (typeof row !== "object" || row === null) continue;
1864
- const rec = row;
1865
- const id = coerceInt(rec.id);
1866
- if (id === null || id <= 0) continue;
1867
- if (keep && !keep.has(id)) continue;
1868
- out.push({
1869
- id,
1870
- name: rosterName(rec)
1871
- });
1872
- }
1982
+ for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
1873
1983
  return out;
1874
1984
  }
1875
- /**
1876
- * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1877
- * addresses (`POST /v5/emails/validate`), then invite the validated ones
1878
- * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
1879
- */
1880
- async function inviteAthletes(client, args) {
1881
- const list = emailList(args.emails);
1882
- if (list.length === 0) throw new Error("Provide at least one email address to invite.");
1883
- const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1884
- if (!validation.ok) {
1885
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1886
- throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1887
- }
1888
- const valid = Array.isArray(validation.data) ? validation.data : list;
1889
- if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1890
- const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1891
- teamType: 0,
1892
- teamId: args.teamId,
1893
- orgId: null,
1894
- emails: valid,
1895
- message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1896
- } });
1897
- if (!invite.ok) {
1898
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1899
- throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1985
+ function repsList(ex) {
1986
+ const reps = ex.reps;
1987
+ if (Array.isArray(reps)) return reps.map((r) => String(r));
1988
+ if (reps === void 0 || reps === null) return [];
1989
+ const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
1990
+ return Array.from({ length: sets }, () => String(reps));
1991
+ }
1992
+ /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
1993
+ function makeExercise(ex, workoutSetId, order, key) {
1994
+ const reps = repsList(ex);
1995
+ let instruction = ex.instr ?? "";
1996
+ if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
1997
+ const hasWeight = ex.weight !== void 0 && ex.weight !== null;
1998
+ const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
1999
+ let count = reps.length;
2000
+ if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2001
+ let param2Type;
2002
+ let param2Values;
2003
+ if (hasWeight) {
2004
+ param2Type = ex.param_2_type ?? 1;
2005
+ param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2006
+ } else {
2007
+ param2Type = 0;
2008
+ param2Values = null;
1900
2009
  }
1901
- return {
1902
- teamId: args.teamId,
1903
- invited: valid,
1904
- result: invite.data
2010
+ const entry = {
2011
+ exercise_id: ex.id,
2012
+ workout_set_id: workoutSetId,
2013
+ set_id: workoutSetId,
2014
+ setKey: workoutSetId,
2015
+ title: ex.title ?? "",
2016
+ instruction,
2017
+ order,
2018
+ param_1_type: ex.param_1_type ?? 3,
2019
+ param_2_type: param2Type,
2020
+ workout_set_exercise_template_id: null,
2021
+ no_sets: 0,
2022
+ param_count: count,
2023
+ set_num: count,
2024
+ key,
2025
+ video_url: "",
2026
+ thumbnail_url: "",
2027
+ tags: [],
2028
+ eType: "e",
2029
+ use_count: 0
1905
2030
  };
2031
+ const p1 = slots(reps);
2032
+ const p2 = slots(param2Values);
2033
+ for (let i = 0; i < 10; i += 1) {
2034
+ entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2035
+ entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2036
+ }
2037
+ return entry;
1906
2038
  }
1907
2039
  /**
1908
- * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1909
- * The API wants the target date as a structured object (with weekday and an isToday flag),
1910
- * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2040
+ * Default block type: text-only (empty exercises) blocks are Conditioning / Circuit (type 1);
2041
+ * structured exercise blocks default to Hypertrophy (type 2). An explicit `type` always wins.
1911
2042
  */
1912
- async function copySession(client, args) {
1913
- const [year, month, day] = parseWorkoutDate(args.toDate);
1914
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1915
- const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1916
- const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1917
- toProgramId: args.toProgramId,
1918
- pwId: args.pwId,
1919
- toDate: {
1920
- date: iso,
1921
- day,
1922
- month,
1923
- year,
1924
- dayOfWeek,
1925
- isToday: false
1926
- }
1927
- } });
1928
- if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
1929
- return res.data;
2043
+ function defaultBlockType(block) {
2044
+ if (block.type !== void 0) return block.type;
2045
+ return block.exercises.length === 0 ? 1 : 2;
1930
2046
  }
1931
- const ANALYTICS_METRIC_KEYS = [
1932
- "readiness-team",
1933
- "readiness-athlete",
1934
- "lift-1rm-history",
1935
- "training-summary-athlete",
1936
- "compliance-team",
1937
- "lift-progress-team",
1938
- "working-max-history"
1939
- ];
1940
- const ANALYTICS_METRICS = {
1941
- "readiness-team": {
1942
- path: "/v5/analytics/readiness/teams",
1943
- scope: "team",
1944
- inputs: ["date"],
1945
- requires: ["date"]
1946
- },
1947
- "readiness-athlete": {
1948
- path: "/v5/analytics/readiness/users",
1949
- scope: "user",
1950
- inputs: ["dateStart", "dateEnd"],
1951
- requires: ["dateStart", "dateEnd"]
1952
- },
1953
- "lift-1rm-history": {
1954
- path: "/v5/analytics/lift-one-rep-max-history/users",
1955
- scope: "user",
1956
- inputs: [
1957
- "dateStart",
1958
- "dateEnd",
1959
- "exerciseId",
1960
- "useMetric"
1961
- ],
1962
- requires: [
1963
- "dateStart",
1964
- "dateEnd",
1965
- "exerciseId"
1966
- ]
1967
- },
1968
- "training-summary-athlete": {
1969
- path: "/v5/analytics/training-summary/users",
1970
- scope: "user",
1971
- inputs: ["dateStart", "dateEnd"],
1972
- requires: ["dateStart", "dateEnd"]
1973
- },
1974
- "compliance-team": {
1975
- path: "/v5/analytics/compliance",
1976
- scope: "team",
1977
- inputs: ["dateStart", "dateEnd"],
1978
- requires: ["dateStart", "dateEnd"]
1979
- },
1980
- "lift-progress-team": {
1981
- path: "/v5/analytics/lift-progress/teams",
1982
- scope: "team",
1983
- inputs: [
1984
- "exerciseId",
1985
- "dateStart",
1986
- "dateEnd"
1987
- ],
1988
- requires: [
1989
- "exerciseId",
1990
- "dateStart",
1991
- "dateEnd"
1992
- ]
1993
- },
1994
- "working-max-history": {
1995
- path: "/v5/analytics/working-max-history/users",
1996
- scope: "user",
1997
- inputs: [
1998
- "exerciseId",
1999
- "dateStart",
2000
- "dateEnd",
2001
- "useMetric"
2002
- ],
2003
- requires: ["exerciseId"]
2047
+ function buildBlockPayload(blocks, workoutId) {
2048
+ return blocks.map((b, i) => {
2049
+ const lb = resolveLeaderboard(b);
2050
+ return {
2051
+ workout_id: workoutId,
2052
+ order: i + 1,
2053
+ type: defaultBlockType(b),
2054
+ instruction: b.instruction ?? "",
2055
+ is_redzone: lb.isRedzone,
2056
+ redzone_type: lb.redzoneType,
2057
+ smaller_is_better: lb.smallerIsBetter,
2058
+ redzone_instruction: lb.redzoneInstruction,
2059
+ exercises: [],
2060
+ exerciseKeys: [],
2061
+ key: `k::${workoutId}${i + 1}`,
2062
+ title: b.title
2063
+ };
2064
+ });
2065
+ }
2066
+ function unitOr(t) {
2067
+ return unitLabel(t) ?? "?";
2068
+ }
2069
+ /** Flag spec params the API will silently override to the exercise's fixed units. */
2070
+ function unitAdvisory(blockTitle, ex, defaults) {
2071
+ const notes = [];
2072
+ const warnings = [];
2073
+ const u = unitOr;
2074
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2075
+ 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).`);
2076
+ const sentP1 = ex.param_1_type;
2077
+ if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2078
+ const sp1 = Math.trunc(Number(sentP1));
2079
+ 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)}.`);
2080
+ } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2081
+ if (ex.weight !== void 0 && ex.weight !== null) {
2082
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2083
+ const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2084
+ if (sentP2 !== effP2) 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.`);
2085
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2004
2086
  }
2005
- };
2006
- const ANALYTICS_BODY_KEY = {
2007
- date: "date",
2008
- dateStart: "date_start",
2009
- dateEnd: "date_end",
2010
- exerciseId: "exercise_id",
2011
- useMetric: "use_metric"
2012
- };
2087
+ return {
2088
+ notes,
2089
+ warnings
2090
+ };
2091
+ }
2013
2092
  /**
2014
- * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2015
- * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2016
- * athlete). Throws a readable Error when a required input is missing or the call fails.
2093
+ * Run unit advisories across a whole block list against an exercise index. Shared by the
2094
+ * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2095
+ * index is loaded first, otherwise `defaults` returns null on a cold index and every
2096
+ * advisory is silently dropped.
2017
2097
  */
2018
- async function queryAnalytics(client, args) {
2019
- const spec = ANALYTICS_METRICS[args.metric];
2020
- const body = {};
2021
- if (spec.scope === "team") {
2022
- if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
2023
- body.teamId = args.teamId;
2024
- } else {
2025
- if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
2026
- body.user_ids = args.userIds.map((u) => String(u));
2027
- }
2028
- const inputs = {
2029
- date: args.date,
2030
- dateStart: args.dateStart,
2031
- dateEnd: args.dateEnd,
2032
- exerciseId: args.exerciseId,
2033
- useMetric: args.useMetric
2098
+ async function collectAdvisories(blocks, index) {
2099
+ await index.ensureFresh();
2100
+ const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2101
+ block: b,
2102
+ ex
2103
+ })));
2104
+ const defaults = await Promise.all(pairs.map((p) => {
2105
+ const id = Number(p.ex.id);
2106
+ return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2107
+ }));
2108
+ const notes = [];
2109
+ const warnings = [];
2110
+ pairs.forEach((p, i) => {
2111
+ const def = defaults[i];
2112
+ if (!def) return;
2113
+ const advisory = unitAdvisory(p.block.title, p.ex, def);
2114
+ notes.push(...advisory.notes);
2115
+ warnings.push(...advisory.warnings);
2116
+ });
2117
+ return {
2118
+ notes,
2119
+ warnings
2034
2120
  };
2035
- const missing = spec.requires.filter((k) => inputs[k] === void 0);
2036
- if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
2037
- for (const k of spec.inputs) {
2038
- const v = inputs[k];
2039
- if (v === void 0) continue;
2040
- body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
2041
- }
2042
- const res = await client.request("POST", spec.path, { body });
2043
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2044
- return res.data;
2045
2121
  }
2122
+ //#endregion
2123
+ //#region ../js/src/workout-session.ts
2046
2124
  /**
2047
- * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2048
- * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2049
- * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2050
- * given id, matched as a string. Throws when the roster fetch fails.
2125
+ * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2126
+ * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
2127
+ * `copySession` so the hint stays in one place.
2051
2128
  */
2052
- async function fetchTeamAthleteIds(client, teamId) {
2053
- const res = await client.request("GET", "/v5/athletes");
2054
- if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2055
- const rows = Array.isArray(res.data) ? res.data : [];
2056
- const want = String(teamId);
2057
- const ids = [];
2058
- for (const row of rows) {
2059
- if (row === null || typeof row !== "object") continue;
2060
- const rec = row;
2061
- if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2062
- const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2063
- if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2129
+ function calendarWriteError(method, path, status, detail) {
2130
+ const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2131
+ if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2132
+ return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
2133
+ }
2134
+ async function req(client, method, path, body) {
2135
+ const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2136
+ if (!res.ok) {
2137
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2138
+ throw calendarWriteError(method, path, res.status, detail);
2064
2139
  }
2065
- return ids;
2140
+ return res.data;
2066
2141
  }
2067
- function toNum(v) {
2068
- const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2069
- return Number.isFinite(n) ? n : 0;
2142
+ function createPath(opts) {
2143
+ if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2144
+ if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2145
+ const [y, m, d] = opts.date;
2146
+ return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2147
+ }
2148
+ async function buildSession(client, opts) {
2149
+ const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2150
+ const sess = await req(client, "POST", createPath(opts), {});
2151
+ checkResponse(sessionCreateResponseSchema, sess, "session create");
2152
+ const workoutId = Number(sess.workout_id);
2153
+ const pwId = Number(sess.id);
2154
+ const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2155
+ const byOrder = new Map(created.map((b) => [b.order, b.id]));
2156
+ let counter = 0;
2157
+ const payloads = blocks.map((block, i) => {
2158
+ const wsid = byOrder.get(i + 1);
2159
+ if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2160
+ return block.exercises.map((ex, j) => {
2161
+ counter += 1;
2162
+ return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2163
+ });
2164
+ });
2165
+ await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2166
+ if (opts.instruction !== void 0 && opts.instruction !== "") {
2167
+ const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2168
+ await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2169
+ }
2170
+ if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2171
+ return {
2172
+ pwId,
2173
+ workoutId
2174
+ };
2070
2175
  }
2071
2176
  /**
2072
- * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2073
- * analytics report already returns the team in one call — one row per logged session across all
2074
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2075
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2076
- * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2077
- * all-time `fetchRosterActivity` snapshot, which has no date range.
2177
+ * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2178
+ * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2179
+ * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2180
+ * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2078
2181
  */
2079
- async function teamVolume(client, args) {
2080
- if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2081
- const report = await queryAnalytics(client, {
2082
- metric: "training-summary-athlete",
2083
- userIds: args.athleteIds,
2084
- dateStart: args.dateStart,
2085
- dateEnd: args.dateEnd
2086
- });
2087
- const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2088
- const byAthlete = /* @__PURE__ */ new Map();
2089
- for (const row of rows) {
2090
- const athleteId = toNum(row.user_id);
2091
- if (athleteId === 0) continue;
2092
- const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2093
- const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2094
- const existing = byAthlete.get(athleteId);
2095
- if (existing) {
2096
- existing.sessions += 1;
2097
- existing.reps += toNum(row.reps);
2098
- existing.volume += toNum(row.volume);
2099
- if (date !== null) {
2100
- if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2101
- if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2102
- }
2103
- } else byAthlete.set(athleteId, {
2104
- athleteId,
2105
- name,
2106
- sessions: 1,
2107
- reps: toNum(row.reps),
2108
- volume: toNum(row.volume),
2109
- firstLoggedDate: date,
2110
- lastLoggedDate: date
2111
- });
2112
- }
2113
- const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2114
- const totals = athletes.reduce((acc, a) => ({
2115
- athletes: acc.athletes + 1,
2116
- sessions: acc.sessions + a.sessions,
2117
- reps: acc.reps + a.reps,
2118
- volume: acc.volume + a.volume
2119
- }), {
2120
- athletes: 0,
2121
- sessions: 0,
2122
- reps: 0,
2123
- volume: 0
2182
+ async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2183
+ const body = {
2184
+ ...pw,
2185
+ instruction,
2186
+ sets: blockIds,
2187
+ setKeys: blockIds
2188
+ };
2189
+ await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2190
+ }
2191
+ async function removeSession(client, programId, pwId) {
2192
+ await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2193
+ programId,
2194
+ pwId
2124
2195
  });
2196
+ }
2197
+ async function publishSession(client, pwId) {
2198
+ await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2199
+ }
2200
+ function str(value) {
2201
+ return value === void 0 || value === null ? "" : String(value);
2202
+ }
2203
+ async function readSession(client, programId, date, pwId) {
2204
+ const [y, m, d] = date;
2205
+ const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2206
+ checkResponse(programsEditResponseSchema, data, "programs edit");
2207
+ const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2208
+ if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2209
+ const setsObj = pw.sets ?? {};
2210
+ const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2125
2211
  return {
2126
- window: {
2127
- start: args.dateStart,
2128
- end: args.dateEnd
2129
- },
2130
- athletes,
2131
- totals
2212
+ pwId,
2213
+ date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2214
+ published: pw.published,
2215
+ instruction: str(pw.instruction),
2216
+ blocks
2132
2217
  };
2133
2218
  }
2134
- //#endregion
2135
- //#region ../js/src/main-lifts.ts
2136
- /**
2137
- * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2138
- * first family that matches, so the more specific / easily-confused families come before the broad
2139
- * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2140
- * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2141
- * This is the single place to edit the lift set.
2142
- */
2143
- const MAIN_LIFT_FAMILIES = [
2144
- {
2145
- key: "cleanjerk",
2146
- label: "Clean & Jerk",
2147
- matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2148
- },
2149
- {
2150
- key: "snatch",
2151
- label: "Snatch",
2152
- matches: (t) => t.includes("snatch")
2153
- },
2154
- {
2155
- key: "deadlift",
2156
- label: "Deadlift",
2157
- matches: (t) => t.includes("deadlift")
2158
- },
2159
- {
2160
- key: "squat",
2161
- label: "Squat",
2162
- matches: (t) => t.includes("squat")
2163
- },
2164
- {
2165
- key: "bench",
2166
- label: "Bench Press",
2167
- matches: (t) => t.includes("bench")
2168
- },
2169
- {
2170
- key: "overhead",
2171
- label: "Overhead Press",
2172
- matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2219
+ function readBlock(b) {
2220
+ const rz = coerceInt(b.redzone_type);
2221
+ let leaderboard = null;
2222
+ if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2223
+ const exercises = (Array.isArray(b.exercises) ? b.exercises : []).filter((ex) => coerceInt(ex.id) !== null || str(ex.title) !== "").sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2224
+ return {
2225
+ order: Number(b.order),
2226
+ title: str(b.title),
2227
+ instruction: str(b.instruction),
2228
+ leaderboard,
2229
+ exercises
2230
+ };
2231
+ }
2232
+ function readExercise(ex) {
2233
+ const reps = [];
2234
+ const load = [];
2235
+ for (let i = 1; i <= 10; i += 1) {
2236
+ const r = str(ex[`param_1_data_${i}`]);
2237
+ if (r !== "") reps.push(r);
2238
+ const w = str(ex[`param_2_data_${i}`]);
2239
+ if (w !== "") load.push(w);
2173
2240
  }
2174
- ];
2175
- /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2176
- function classifyMainLift(title) {
2177
- const t = title.toLowerCase();
2178
- for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2179
- return null;
2241
+ return {
2242
+ order: Number(ex.order),
2243
+ title: str(ex.title),
2244
+ reps,
2245
+ primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2246
+ load,
2247
+ loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2248
+ instruction: str(ex.instruction)
2249
+ };
2180
2250
  }
2181
- const DEFAULT_MONTHS = 12;
2182
- function pad2(n) {
2183
- return String(n).padStart(2, "0");
2251
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
2252
+ function emailList(emails) {
2253
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2184
2254
  }
2185
- /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2186
- function isoDay(d) {
2187
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2255
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2256
+ function rosterName(rec) {
2257
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2258
+ if (full !== "") return full;
2259
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2260
+ return combined !== "" ? combined : null;
2188
2261
  }
2189
2262
  /**
2190
- * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2191
- * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2192
- * record of performed sets — buckets every performed exercise into a lift family, and for each
2193
- * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2194
- * families they never trained are simply absent. (The monthly calendar summary is not used: it
2195
- * comes back empty for some accounts that have logged sets in the range endpoint.)
2263
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2264
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2265
+ * and the warehouse store map the roster identically. Includes the account owner and
2266
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2196
2267
  */
2197
- async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2198
- const months = opts.months ?? DEFAULT_MONTHS;
2199
- const now = opts.now ?? /* @__PURE__ */ new Date();
2200
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2201
- const tally = /* @__PURE__ */ new Map();
2202
- let workouts = [];
2203
- try {
2204
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2205
- } catch {
2206
- workouts = [];
2207
- }
2208
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2209
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2210
- const family = classifyMainLift(ex.title);
2211
- if (family === null) continue;
2212
- const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2213
- const prev = byId.get(ex.exerciseId);
2214
- byId.set(ex.exerciseId, {
2215
- count: (prev?.count ?? 0) + 1,
2216
- title: prev?.title ?? ex.title
2217
- });
2218
- tally.set(family, byId);
2219
- }
2220
- const lifts = [];
2221
- for (const family of MAIN_LIFT_FAMILIES) {
2222
- const byId = tally.get(family.key);
2223
- if (!byId || byId.size === 0) continue;
2224
- let best = null;
2225
- for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2226
- exerciseId,
2227
- count,
2228
- title
2229
- };
2230
- if (best) lifts.push({
2231
- family: family.key,
2232
- label: family.label,
2233
- exerciseId: best.exerciseId,
2234
- title: best.title
2268
+ async function fetchCoachRoster(client, ids) {
2269
+ const res = await client.request("GET", "/v5/athletes");
2270
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2271
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
2272
+ const out = [];
2273
+ for (const row of res.data) {
2274
+ if (typeof row !== "object" || row === null) continue;
2275
+ const rec = row;
2276
+ const id = coerceInt(rec.id);
2277
+ if (id === null || id <= 0) continue;
2278
+ if (keep && !keep.has(id)) continue;
2279
+ out.push({
2280
+ id,
2281
+ name: rosterName(rec)
2235
2282
  });
2236
2283
  }
2237
- return {
2238
- athleteId,
2239
- athleteName: null,
2240
- lifts
2241
- };
2242
- }
2243
- const PR_CONCURRENCY = 5;
2244
- /** The heaviest PR on an exercise's board (ties broken by more reps). */
2245
- function bestPr(liftPRs) {
2246
- let best = null;
2247
- for (const pr of liftPRs) {
2248
- const weight = coerceNum(pr.weight);
2249
- if (weight === null) continue;
2250
- const reps = coerceInt(pr.reps);
2251
- if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2252
- weight,
2253
- reps,
2254
- units: pr.units,
2255
- date: pr.date
2256
- };
2257
- }
2258
- return best;
2284
+ return out;
2259
2285
  }
2260
2286
  /**
2261
- * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2262
- * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2263
- * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2264
- * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2265
- * render a stable row of columns.
2287
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2288
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
2289
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2266
2290
  */
2267
- async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2268
- const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2269
- const byFamily = new Map(lifts.map((l) => [l.family, l]));
2291
+ async function inviteAthletes(client, args) {
2292
+ const list = emailList(args.emails);
2293
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2294
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2295
+ if (!validation.ok) {
2296
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2297
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2298
+ }
2299
+ const valid = Array.isArray(validation.data) ? validation.data : list;
2300
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2301
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2302
+ teamType: 0,
2303
+ teamId: args.teamId,
2304
+ orgId: null,
2305
+ emails: valid,
2306
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2307
+ } });
2308
+ if (!invite.ok) {
2309
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2310
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2311
+ }
2270
2312
  return {
2271
- athleteId,
2272
- athleteName,
2273
- prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2274
- const lift = byFamily.get(family.key);
2275
- const base = {
2276
- family: family.key,
2277
- label: family.label
2278
- };
2279
- const empty = {
2280
- exerciseId: null,
2281
- title: null,
2282
- weight: null,
2283
- reps: null,
2284
- units: null,
2285
- date: null
2286
- };
2287
- if (!lift) return {
2288
- ...base,
2289
- ...empty
2290
- };
2291
- const known = {
2292
- exerciseId: lift.exerciseId,
2293
- title: lift.title
2294
- };
2295
- try {
2296
- const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2297
- return {
2298
- ...base,
2299
- ...known,
2300
- weight: best?.weight ?? null,
2301
- reps: best?.reps ?? null,
2302
- units: best?.units ?? null,
2303
- date: best?.date ?? null
2304
- };
2305
- } catch {
2306
- return {
2307
- ...base,
2308
- ...known,
2309
- weight: null,
2310
- reps: null,
2311
- units: null,
2312
- date: null
2313
- };
2314
- }
2315
- })
2313
+ teamId: args.teamId,
2314
+ invited: valid,
2315
+ result: invite.data
2316
2316
  };
2317
2317
  }
2318
- const ROSTER_CONCURRENCY = 4;
2319
2318
  /**
2320
- * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2321
- * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2322
- * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2323
- * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2324
- * primitive the CLI, the MCP tool, and the warehouse store all build on.
2325
- */
2326
- async function fetchRosterMainLiftPRs(client, opts = {}) {
2327
- const roster = await fetchCoachRoster(client, opts.athleteIds);
2328
- const inner = {
2329
- ...opts.months !== void 0 ? { months: opts.months } : {},
2330
- ...opts.now !== void 0 ? { now: opts.now } : {}
2331
- };
2332
- return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2333
- const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2334
- return {
2335
- athleteId: athlete.id,
2336
- athleteName: result.athleteName ?? athlete.name,
2337
- prs: result.prs
2338
- };
2339
- });
2319
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
2320
+ *
2321
+ * The live API accepts `group_program` to point the team at an existing parent program /
2322
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
2323
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
2324
+ * the current title first so callers can re-link without renaming.
2325
+ */
2326
+ async function updateTeam(client, args) {
2327
+ if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
2328
+ let title = args.title;
2329
+ if (title === void 0) {
2330
+ const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
2331
+ if (!existing.ok) {
2332
+ const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
2333
+ throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
2334
+ }
2335
+ const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
2336
+ title = typeof rec?.title === "string" ? rec.title : "";
2337
+ if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
2338
+ }
2339
+ const body = { title };
2340
+ if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
2341
+ const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
2342
+ if (!res.ok) {
2343
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2344
+ throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
2345
+ }
2346
+ return res.data;
2340
2347
  }
2341
- //#endregion
2342
- //#region ../js/src/util.ts
2343
2348
  /**
2344
- * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2345
- * spread into an object under `exactOptionalPropertyTypes` without the per-key
2346
- * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2347
- * optional ones lose `undefined` from their value type.
2348
- *
2349
- * Example:
2350
- * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2349
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2350
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
2351
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2351
2352
  */
2352
- function definedProps(obj) {
2353
- const result = {};
2354
- for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2355
- return result;
2353
+ async function copySession(client, args) {
2354
+ const [year, month, day] = parseWorkoutDate(args.toDate);
2355
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2356
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2357
+ const path = "/2.0/coach/calendar/copyProgramWorkout";
2358
+ const res = await client.request("POST", path, { body: {
2359
+ toProgramId: args.toProgramId,
2360
+ pwId: args.pwId,
2361
+ toDate: {
2362
+ date: iso,
2363
+ day,
2364
+ month,
2365
+ year,
2366
+ dayOfWeek,
2367
+ isToday: false
2368
+ }
2369
+ } });
2370
+ if (!res.ok) {
2371
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2372
+ throw calendarWriteError("POST", path, res.status, detail);
2373
+ }
2374
+ return res.data;
2356
2375
  }
2357
- //#endregion
2358
- //#region ../js/src/workout-encode.ts
2359
- const LEADERBOARD_TYPE = {
2360
- completion: 0,
2361
- "for completion": 0,
2362
- weight: 1,
2363
- lb: 1,
2364
- load: 1,
2365
- reps: 2,
2366
- rep: 2,
2367
- rounds: 3,
2368
- round: 3,
2369
- time: 4,
2370
- yards: 5,
2371
- yd: 5,
2372
- meters: 6,
2373
- m: 6,
2374
- feet: 7,
2375
- ft: 7,
2376
- calories: 8,
2377
- cal: 8,
2378
- cals: 8,
2379
- miles: 10,
2380
- mi: 10,
2381
- inches: 12,
2382
- in: 12,
2383
- watts: 15,
2384
- w: 15,
2385
- velocity: 17,
2386
- "m/s": 17,
2387
- seconds: 18,
2388
- sec: 18,
2389
- s: 18
2390
- };
2391
- const LEADERBOARD_LABEL = {
2392
- 0: "For Completion",
2393
- 1: "Weight",
2394
- 2: "Reps",
2395
- 3: "Rounds",
2396
- 4: "Time",
2397
- 5: "Yards",
2398
- 6: "Meters",
2399
- 7: "Feet",
2400
- 8: "Calories",
2401
- 10: "Miles",
2402
- 12: "Inches",
2403
- 13: "Other",
2404
- 15: "Watts",
2405
- 16: "Percent",
2406
- 17: "Velocity",
2407
- 18: "Seconds"
2376
+ const ANALYTICS_METRIC_KEYS = [
2377
+ "readiness-team",
2378
+ "readiness-athlete",
2379
+ "lift-1rm-history",
2380
+ "training-summary-athlete",
2381
+ "compliance-team",
2382
+ "lift-progress-team",
2383
+ "working-max-history"
2384
+ ];
2385
+ const ANALYTICS_METRICS = {
2386
+ "readiness-team": {
2387
+ path: "/v5/analytics/readiness/teams",
2388
+ scope: "team",
2389
+ inputs: ["date"],
2390
+ requires: ["date"]
2391
+ },
2392
+ "readiness-athlete": {
2393
+ path: "/v5/analytics/readiness/users",
2394
+ scope: "user",
2395
+ inputs: ["dateStart", "dateEnd"],
2396
+ requires: ["dateStart", "dateEnd"]
2397
+ },
2398
+ "lift-1rm-history": {
2399
+ path: "/v5/analytics/lift-one-rep-max-history/users",
2400
+ scope: "user",
2401
+ inputs: [
2402
+ "dateStart",
2403
+ "dateEnd",
2404
+ "exerciseId",
2405
+ "useMetric"
2406
+ ],
2407
+ requires: [
2408
+ "dateStart",
2409
+ "dateEnd",
2410
+ "exerciseId"
2411
+ ]
2412
+ },
2413
+ "training-summary-athlete": {
2414
+ path: "/v5/analytics/training-summary/users",
2415
+ scope: "user",
2416
+ inputs: ["dateStart", "dateEnd"],
2417
+ requires: ["dateStart", "dateEnd"]
2418
+ },
2419
+ "compliance-team": {
2420
+ path: "/v5/analytics/compliance",
2421
+ scope: "team",
2422
+ inputs: ["dateStart", "dateEnd"],
2423
+ requires: ["dateStart", "dateEnd"]
2424
+ },
2425
+ "lift-progress-team": {
2426
+ path: "/v5/analytics/lift-progress/teams",
2427
+ scope: "team",
2428
+ inputs: [
2429
+ "exerciseId",
2430
+ "dateStart",
2431
+ "dateEnd"
2432
+ ],
2433
+ requires: [
2434
+ "exerciseId",
2435
+ "dateStart",
2436
+ "dateEnd"
2437
+ ]
2438
+ },
2439
+ "working-max-history": {
2440
+ path: "/v5/analytics/working-max-history/users",
2441
+ scope: "user",
2442
+ inputs: [
2443
+ "exerciseId",
2444
+ "dateStart",
2445
+ "dateEnd",
2446
+ "useMetric"
2447
+ ],
2448
+ requires: ["exerciseId"]
2449
+ }
2408
2450
  };
2409
- function resolveLeaderboard(block) {
2410
- const lb = block.leaderboard;
2411
- if (lb === void 0 || lb === null) return {
2412
- isRedzone: null,
2413
- redzoneType: 0,
2414
- smallerIsBetter: null,
2415
- redzoneInstruction: ""
2416
- };
2417
- let unit;
2418
- let instruction = "";
2419
- let lowest;
2420
- if (typeof lb === "object") {
2421
- unit = lb.unit ?? lb.type;
2422
- instruction = lb.instruction ?? "";
2423
- lowest = lb.lowest_wins;
2424
- } else unit = lb;
2425
- let rz;
2426
- if (typeof unit === "string") {
2427
- const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2428
- if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2429
- rz = found;
2430
- } else if (typeof unit === "number") rz = Math.trunc(unit);
2431
- else throw new Error("Leaderboard requires a unit.");
2432
- if (lowest === void 0) lowest = rz === 4 || rz === 18;
2433
- return {
2434
- isRedzone: 1,
2435
- redzoneType: rz,
2436
- smallerIsBetter: lowest ? 1 : 0,
2437
- redzoneInstruction: instruction
2438
- };
2439
- }
2440
- function slots(values, n = 10) {
2441
- const out = [];
2442
- for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2443
- return out;
2444
- }
2445
- function repsList(ex) {
2446
- const reps = ex.reps;
2447
- if (Array.isArray(reps)) return reps.map((r) => String(r));
2448
- if (reps === void 0 || reps === null) return [];
2449
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2450
- return Array.from({ length: sets }, () => String(reps));
2451
- }
2452
- /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2453
- function makeExercise(ex, workoutSetId, order, key) {
2454
- const reps = repsList(ex);
2455
- let instruction = ex.instr ?? "";
2456
- if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2457
- const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2458
- const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2459
- let count = reps.length;
2460
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2461
- let param2Type;
2462
- let param2Values;
2463
- if (hasWeight) {
2464
- param2Type = ex.param_2_type ?? 1;
2465
- param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2451
+ const ANALYTICS_BODY_KEY = {
2452
+ date: "date",
2453
+ dateStart: "date_start",
2454
+ dateEnd: "date_end",
2455
+ exerciseId: "exercise_id",
2456
+ useMetric: "use_metric"
2457
+ };
2458
+ /**
2459
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2460
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2461
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
2462
+ */
2463
+ async function queryAnalytics(client, args) {
2464
+ const spec = ANALYTICS_METRICS[args.metric];
2465
+ const body = {};
2466
+ if (spec.scope === "team") {
2467
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
2468
+ body.teamId = args.teamId;
2466
2469
  } else {
2467
- param2Type = 0;
2468
- param2Values = null;
2470
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
2471
+ body.user_ids = args.userIds.map((u) => String(u));
2469
2472
  }
2470
- const entry = {
2471
- exercise_id: ex.id,
2472
- workout_set_id: workoutSetId,
2473
- set_id: workoutSetId,
2474
- setKey: workoutSetId,
2475
- title: ex.title ?? "",
2476
- instruction,
2477
- order,
2478
- param_1_type: ex.param_1_type ?? 3,
2479
- param_2_type: param2Type,
2480
- workout_set_exercise_template_id: null,
2481
- no_sets: 0,
2482
- param_count: count,
2483
- set_num: count,
2484
- key,
2485
- video_url: "",
2486
- thumbnail_url: "",
2487
- tags: [],
2488
- eType: "e",
2489
- use_count: 0
2473
+ const inputs = {
2474
+ date: args.date,
2475
+ dateStart: args.dateStart,
2476
+ dateEnd: args.dateEnd,
2477
+ exerciseId: args.exerciseId,
2478
+ useMetric: args.useMetric
2490
2479
  };
2491
- const p1 = slots(reps);
2492
- const p2 = slots(param2Values);
2493
- for (let i = 0; i < 10; i += 1) {
2494
- entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2495
- entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2480
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
2481
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
2482
+ for (const k of spec.inputs) {
2483
+ const v = inputs[k];
2484
+ if (v === void 0) continue;
2485
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
2496
2486
  }
2497
- return entry;
2498
- }
2499
- function buildBlockPayload(blocks, workoutId) {
2500
- return blocks.map((b, i) => {
2501
- const lb = resolveLeaderboard(b);
2502
- return {
2503
- workout_id: workoutId,
2504
- order: i + 1,
2505
- type: b.type ?? 2,
2506
- instruction: b.instruction ?? "",
2507
- is_redzone: lb.isRedzone,
2508
- redzone_type: lb.redzoneType,
2509
- smaller_is_better: lb.smallerIsBetter,
2510
- redzone_instruction: lb.redzoneInstruction,
2511
- exercises: [],
2512
- exerciseKeys: [],
2513
- key: `k::${workoutId}${i + 1}`,
2514
- title: b.title
2515
- };
2516
- });
2517
- }
2518
- function unitOr(t) {
2519
- return unitLabel(t) ?? "?";
2487
+ const res = await client.request("POST", spec.path, { body });
2488
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2489
+ return res.data;
2520
2490
  }
2521
- /** Flag spec params the API will silently override to the exercise's fixed units. */
2522
- function unitAdvisory(blockTitle, ex, defaults) {
2523
- const notes = [];
2524
- const warnings = [];
2525
- const u = unitOr;
2526
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2527
- 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).`);
2528
- const sentP1 = ex.param_1_type;
2529
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2530
- const sp1 = Math.trunc(Number(sentP1));
2531
- 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)}.`);
2532
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2533
- if (ex.weight !== void 0 && ex.weight !== null) {
2534
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2535
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2536
- if (sentP2 !== effP2) 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.`);
2537
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2491
+ /**
2492
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2493
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2494
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2495
+ * given id, matched as a string. Throws when the roster fetch fails.
2496
+ */
2497
+ async function fetchTeamAthleteIds(client, teamId) {
2498
+ const res = await client.request("GET", "/v5/athletes");
2499
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2500
+ const rows = Array.isArray(res.data) ? res.data : [];
2501
+ const want = String(teamId);
2502
+ const ids = [];
2503
+ for (const row of rows) {
2504
+ if (row === null || typeof row !== "object") continue;
2505
+ const rec = row;
2506
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2507
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2508
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2538
2509
  }
2539
- return {
2540
- notes,
2541
- warnings
2542
- };
2510
+ return ids;
2511
+ }
2512
+ function toNum(v) {
2513
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2514
+ return Number.isFinite(n) ? n : 0;
2543
2515
  }
2544
2516
  /**
2545
- * Run unit advisories across a whole block list against an exercise index. Shared by the
2546
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2547
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2548
- * advisory is silently dropped.
2517
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2518
+ * analytics report already returns the team in one call — one row per logged session across all
2519
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2520
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2521
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2522
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
2549
2523
  */
2550
- async function collectAdvisories(blocks, index) {
2551
- await index.ensureFresh();
2552
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2553
- block: b,
2554
- ex
2555
- })));
2556
- const defaults = await Promise.all(pairs.map((p) => {
2557
- const id = Number(p.ex.id);
2558
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2559
- }));
2560
- const notes = [];
2561
- const warnings = [];
2562
- pairs.forEach((p, i) => {
2563
- const def = defaults[i];
2564
- if (!def) return;
2565
- const advisory = unitAdvisory(p.block.title, p.ex, def);
2566
- notes.push(...advisory.notes);
2567
- warnings.push(...advisory.warnings);
2524
+ async function teamVolume(client, args) {
2525
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2526
+ const report = await queryAnalytics(client, {
2527
+ metric: "training-summary-athlete",
2528
+ userIds: args.athleteIds,
2529
+ dateStart: args.dateStart,
2530
+ dateEnd: args.dateEnd
2531
+ });
2532
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2533
+ const byAthlete = /* @__PURE__ */ new Map();
2534
+ for (const row of rows) {
2535
+ const athleteId = toNum(row.user_id);
2536
+ if (athleteId === 0) continue;
2537
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2538
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2539
+ const existing = byAthlete.get(athleteId);
2540
+ if (existing) {
2541
+ existing.sessions += 1;
2542
+ existing.reps += toNum(row.reps);
2543
+ existing.volume += toNum(row.volume);
2544
+ if (date !== null) {
2545
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2546
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2547
+ }
2548
+ } else byAthlete.set(athleteId, {
2549
+ athleteId,
2550
+ name,
2551
+ sessions: 1,
2552
+ reps: toNum(row.reps),
2553
+ volume: toNum(row.volume),
2554
+ firstLoggedDate: date,
2555
+ lastLoggedDate: date
2556
+ });
2557
+ }
2558
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2559
+ const totals = athletes.reduce((acc, a) => ({
2560
+ athletes: acc.athletes + 1,
2561
+ sessions: acc.sessions + a.sessions,
2562
+ reps: acc.reps + a.reps,
2563
+ volume: acc.volume + a.volume
2564
+ }), {
2565
+ athletes: 0,
2566
+ sessions: 0,
2567
+ reps: 0,
2568
+ volume: 0
2568
2569
  });
2569
2570
  return {
2570
- notes,
2571
- warnings
2571
+ window: {
2572
+ start: args.dateStart,
2573
+ end: args.dateEnd
2574
+ },
2575
+ athletes,
2576
+ totals
2572
2577
  };
2573
2578
  }
2574
2579
  //#endregion
2575
- //#region ../js/src/workout-session.ts
2576
- async function req(client, method, path, body) {
2577
- const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2578
- if (!res.ok) {
2579
- const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2580
- throw new Error(`${method} ${path} failed (HTTP ${res.status}): ${detail}`);
2580
+ //#region ../js/src/main-lifts.ts
2581
+ /**
2582
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2583
+ * first family that matches, so the more specific / easily-confused families come before the broad
2584
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2585
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2586
+ * This is the single place to edit the lift set.
2587
+ */
2588
+ const MAIN_LIFT_FAMILIES = [
2589
+ {
2590
+ key: "cleanjerk",
2591
+ label: "Clean & Jerk",
2592
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2593
+ },
2594
+ {
2595
+ key: "snatch",
2596
+ label: "Snatch",
2597
+ matches: (t) => t.includes("snatch")
2598
+ },
2599
+ {
2600
+ key: "deadlift",
2601
+ label: "Deadlift",
2602
+ matches: (t) => t.includes("deadlift")
2603
+ },
2604
+ {
2605
+ key: "squat",
2606
+ label: "Squat",
2607
+ matches: (t) => t.includes("squat")
2608
+ },
2609
+ {
2610
+ key: "bench",
2611
+ label: "Bench Press",
2612
+ matches: (t) => t.includes("bench")
2613
+ },
2614
+ {
2615
+ key: "overhead",
2616
+ label: "Overhead Press",
2617
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2581
2618
  }
2582
- return res.data;
2619
+ ];
2620
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2621
+ function classifyMainLift(title) {
2622
+ const t = title.toLowerCase();
2623
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2624
+ return null;
2583
2625
  }
2584
- function createPath(opts) {
2585
- if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2586
- if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2587
- const [y, m, d] = opts.date;
2588
- return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2626
+ const DEFAULT_MONTHS = 12;
2627
+ function pad2(n) {
2628
+ return String(n).padStart(2, "0");
2589
2629
  }
2590
- async function buildSession(client, opts) {
2591
- const sess = await req(client, "POST", createPath(opts), {});
2592
- checkResponse(sessionCreateResponseSchema, sess, "session create");
2593
- const workoutId = Number(sess.workout_id);
2594
- const pwId = Number(sess.id);
2595
- const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(opts.blocks, workoutId));
2596
- const byOrder = new Map(created.map((b) => [b.order, b.id]));
2597
- let counter = 0;
2598
- const payloads = opts.blocks.map((block, i) => {
2599
- const wsid = byOrder.get(i + 1);
2600
- if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2601
- return block.exercises.map((ex, j) => {
2602
- counter += 1;
2603
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2630
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2631
+ function isoDay(d) {
2632
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2633
+ }
2634
+ /**
2635
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2636
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2637
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
2638
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2639
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
2640
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
2641
+ */
2642
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2643
+ const months = opts.months ?? DEFAULT_MONTHS;
2644
+ const now = opts.now ?? /* @__PURE__ */ new Date();
2645
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2646
+ const tally = /* @__PURE__ */ new Map();
2647
+ let workouts = [];
2648
+ try {
2649
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2650
+ } catch {
2651
+ workouts = [];
2652
+ }
2653
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2654
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2655
+ const family = classifyMainLift(ex.title);
2656
+ if (family === null) continue;
2657
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2658
+ const prev = byId.get(ex.exerciseId);
2659
+ byId.set(ex.exerciseId, {
2660
+ count: (prev?.count ?? 0) + 1,
2661
+ title: prev?.title ?? ex.title
2662
+ });
2663
+ tally.set(family, byId);
2664
+ }
2665
+ const lifts = [];
2666
+ for (const family of MAIN_LIFT_FAMILIES) {
2667
+ const byId = tally.get(family.key);
2668
+ if (!byId || byId.size === 0) continue;
2669
+ let best = null;
2670
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2671
+ exerciseId,
2672
+ count,
2673
+ title
2674
+ };
2675
+ if (best) lifts.push({
2676
+ family: family.key,
2677
+ label: family.label,
2678
+ exerciseId: best.exerciseId,
2679
+ title: best.title
2604
2680
  });
2605
- });
2606
- await Promise.all(payloads.map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2607
- if (opts.instruction !== void 0 && opts.instruction !== "") {
2608
- const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2609
- await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2610
2681
  }
2611
- if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2612
2682
  return {
2613
- pwId,
2614
- workoutId
2683
+ athleteId,
2684
+ athleteName: null,
2685
+ lifts
2615
2686
  };
2616
2687
  }
2688
+ const PR_CONCURRENCY = 5;
2689
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
2690
+ function bestPr(liftPRs) {
2691
+ let best = null;
2692
+ for (const pr of liftPRs) {
2693
+ const weight = coerceNum(pr.weight);
2694
+ if (weight === null) continue;
2695
+ const reps = coerceInt(pr.reps);
2696
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2697
+ weight,
2698
+ reps,
2699
+ units: pr.units,
2700
+ date: pr.date
2701
+ };
2702
+ }
2703
+ return best;
2704
+ }
2617
2705
  /**
2618
- * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2619
- * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2620
- * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2621
- * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2706
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2707
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2708
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2709
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2710
+ * render a stable row of columns.
2622
2711
  */
2623
- async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2624
- const body = {
2625
- ...pw,
2626
- instruction,
2627
- sets: blockIds,
2628
- setKeys: blockIds
2629
- };
2630
- await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2631
- }
2632
- async function removeSession(client, programId, pwId) {
2633
- await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2634
- programId,
2635
- pwId
2636
- });
2637
- }
2638
- async function publishSession(client, pwId) {
2639
- await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2640
- }
2641
- function str(value) {
2642
- return value === void 0 || value === null ? "" : String(value);
2643
- }
2644
- async function readSession(client, programId, date, pwId) {
2645
- const [y, m, d] = date;
2646
- const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2647
- checkResponse(programsEditResponseSchema, data, "programs edit");
2648
- const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2649
- if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2650
- const setsObj = pw.sets ?? {};
2651
- const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2712
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2713
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2714
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
2652
2715
  return {
2653
- pwId,
2654
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2655
- published: pw.published,
2656
- instruction: str(pw.instruction),
2657
- blocks
2716
+ athleteId,
2717
+ athleteName,
2718
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2719
+ const lift = byFamily.get(family.key);
2720
+ const base = {
2721
+ family: family.key,
2722
+ label: family.label
2723
+ };
2724
+ const empty = {
2725
+ exerciseId: null,
2726
+ title: null,
2727
+ weight: null,
2728
+ reps: null,
2729
+ units: null,
2730
+ date: null
2731
+ };
2732
+ if (!lift) return {
2733
+ ...base,
2734
+ ...empty
2735
+ };
2736
+ const known = {
2737
+ exerciseId: lift.exerciseId,
2738
+ title: lift.title
2739
+ };
2740
+ try {
2741
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2742
+ return {
2743
+ ...base,
2744
+ ...known,
2745
+ weight: best?.weight ?? null,
2746
+ reps: best?.reps ?? null,
2747
+ units: best?.units ?? null,
2748
+ date: best?.date ?? null
2749
+ };
2750
+ } catch {
2751
+ return {
2752
+ ...base,
2753
+ ...known,
2754
+ weight: null,
2755
+ reps: null,
2756
+ units: null,
2757
+ date: null
2758
+ };
2759
+ }
2760
+ })
2658
2761
  };
2659
2762
  }
2660
- function readBlock(b) {
2661
- const rz = coerceInt(b.redzone_type);
2662
- let leaderboard = null;
2663
- if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2664
- const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2665
- return {
2666
- order: Number(b.order),
2667
- title: str(b.title),
2668
- leaderboard,
2669
- exercises
2763
+ const ROSTER_CONCURRENCY = 4;
2764
+ /**
2765
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2766
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2767
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2768
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2769
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
2770
+ */
2771
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
2772
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
2773
+ const inner = {
2774
+ ...opts.months !== void 0 ? { months: opts.months } : {},
2775
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2670
2776
  };
2777
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2778
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2779
+ return {
2780
+ athleteId: athlete.id,
2781
+ athleteName: result.athleteName ?? athlete.name,
2782
+ prs: result.prs
2783
+ };
2784
+ });
2671
2785
  }
2672
- function readExercise(ex) {
2673
- const reps = [];
2674
- const load = [];
2675
- for (let i = 1; i <= 10; i += 1) {
2676
- const r = str(ex[`param_1_data_${i}`]);
2677
- if (r !== "") reps.push(r);
2678
- const w = str(ex[`param_2_data_${i}`]);
2679
- if (w !== "") load.push(w);
2680
- }
2681
- return {
2682
- order: Number(ex.order),
2683
- title: str(ex.title),
2684
- reps,
2685
- primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2686
- load,
2687
- loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2688
- instruction: str(ex.instruction)
2689
- };
2786
+ //#endregion
2787
+ //#region ../js/src/util.ts
2788
+ /**
2789
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2790
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
2791
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2792
+ * optional ones lose `undefined` from their value type.
2793
+ *
2794
+ * Example:
2795
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2796
+ */
2797
+ function definedProps(obj) {
2798
+ const result = {};
2799
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2800
+ return result;
2690
2801
  }
2691
2802
  //#endregion
2692
2803
  //#region ../js/src/messaging.ts
@@ -3093,7 +3204,7 @@ function registerEntityReads(server, ctx) {
3093
3204
  }));
3094
3205
  server.registerTool("get_program", {
3095
3206
  title: "Get program detail",
3096
- description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
3207
+ description: "Full nested program structure (blocks + sessions) live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). Some unrelated ids return HTTP 401 Cannot access program.",
3097
3208
  inputSchema: { programId: idParam },
3098
3209
  annotations: READ
3099
3210
  }, ({ programId }) => apiCall(ctx, "GET", `/3.0/coach/program/${enc(programId)}`, void 0, "This is a large, deep object. If it is truncated, fetch a narrower view (a specific session) instead."));
@@ -3379,19 +3490,25 @@ const ADDITIVE = {
3379
3490
  function registerTeamTools(server, ctx) {
3380
3491
  server.registerTool("team_create", {
3381
3492
  title: "Create a team",
3382
- description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite.",
3493
+ description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite. To point a new team at an existing calendar instead of its auto-created one, follow up with team_update groupProgram.",
3383
3494
  inputSchema: { title: z.string().min(1) },
3384
3495
  annotations: ADDITIVE
3385
3496
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
3386
3497
  server.registerTool("team_update", {
3387
- title: "Rename a team",
3388
- description: "Update a team's settings, e.g. its title (PUT /v5/teams/{teamId}).",
3498
+ title: "Update a team",
3499
+ description: "Update a team's title and/or reassign its calendar (PUT /v5/teams/{teamId}). Pass groupProgram (a program/calendar id — typically another team's group_program from list_teams, or get_team) to point this team at an existing parent program. At least one of title or groupProgram is required; when only groupProgram is set the current title is preserved.",
3389
3500
  inputSchema: {
3390
3501
  teamId: idParam,
3391
- title: z.string().min(1)
3502
+ title: z.string().min(1).optional(),
3503
+ groupProgram: idParam.optional()
3392
3504
  },
3393
3505
  annotations: ADDITIVE
3394
- }, ({ teamId, title }) => apiCall(ctx, "PUT", `/v5/teams/${toId(teamId)}`, { body: { title } }));
3506
+ }, ({ teamId, title, groupProgram }) => attempt(async () => {
3507
+ const args = { teamId: toId(teamId) };
3508
+ if (title !== void 0) args.title = title;
3509
+ if (groupProgram !== void 0) args.groupProgram = toId(groupProgram);
3510
+ return jsonResult(await updateTeam(ctx.client, args));
3511
+ }));
3395
3512
  server.registerTool("team_delete", {
3396
3513
  title: "Delete a team",
3397
3514
  description: "Delete a team (DELETE /v5/teams/{teamId}). Removes the team and its calendar from the live account; hard to undo. Requires confirmation (elicitation, or confirm:true).",
@@ -3535,13 +3652,14 @@ function registerExerciseTools(server, ctx) {
3535
3652
  }
3536
3653
  //#endregion
3537
3654
  //#region ../core/src/tools/workout.ts
3538
- /** Build a draft, read it back, and publish it. */
3655
+ /** Build a draft session (workout_build). */
3539
3656
  function registerBuild(server, ctx) {
3540
3657
  server.registerTool("workout_build", {
3541
3658
  title: "Build a workout session (draft)",
3542
- description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Two exercises in one block become a superset. Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Review, then workout_publish.",
3659
+ 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, a read-back, and unit advisories. Review, then workout_publish.",
3543
3660
  inputSchema: {
3544
- programId: z.number(),
3661
+ programId: z.number().optional(),
3662
+ athleteId: idParam.optional(),
3545
3663
  date: z.string().optional(),
3546
3664
  timelineDay: z.number().optional(),
3547
3665
  blocks: z.array(blockSpecSchema),
@@ -3552,11 +3670,16 @@ function registerBuild(server, ctx) {
3552
3670
  destructiveHint: false,
3553
3671
  openWorldHint: true
3554
3672
  }
3555
- }, ({ programId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3673
+ }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3556
3674
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
3675
+ const resolveArgs = {};
3676
+ if (programId !== void 0) resolveArgs.programId = programId;
3677
+ if (athleteId !== void 0) resolveArgs.athleteId = toId(athleteId);
3678
+ if (date !== void 0) resolveArgs.date = date;
3679
+ const resolved = await resolveBuildProgramId(ctx.client, resolveArgs);
3557
3680
  const typed = blocks;
3558
3681
  const opts = {
3559
- programId,
3682
+ programId: resolved,
3560
3683
  blocks: typed,
3561
3684
  publish: false
3562
3685
  };
@@ -3565,15 +3688,19 @@ function registerBuild(server, ctx) {
3565
3688
  if (instruction !== void 0) opts.instruction = instruction;
3566
3689
  const advisories = await collectAdvisories(typed, ctx.index);
3567
3690
  const built = await buildSession(ctx.client, opts);
3568
- const readback = opts.date ? await readSession(ctx.client, programId, opts.date, built.pwId) : null;
3691
+ const readback = opts.date ? await readSession(ctx.client, resolved, opts.date, built.pwId) : null;
3569
3692
  return jsonResult({
3570
3693
  ...built,
3694
+ programId: resolved,
3571
3695
  published: false,
3572
3696
  advisories,
3573
3697
  readback,
3574
3698
  note: "Draft created (unpublished). Review, then call workout_publish to make it athlete-facing."
3575
3699
  });
3576
3700
  }));
3701
+ }
3702
+ /** Read-back and publish for a built session. */
3703
+ function registerReadPublish(server, ctx) {
3577
3704
  server.registerTool("workout_read", {
3578
3705
  title: "Read a built session",
3579
3706
  description: "Read-back a session by programId, date (YYYY-M-D), and programWorkout id.",
@@ -3607,7 +3734,8 @@ function registerBuild(server, ctx) {
3607
3734
  await publishSession(ctx.client, pwId);
3608
3735
  return jsonResult({
3609
3736
  published: pwId,
3610
- readback: await readSession(ctx.client, programId, parseWorkoutDate(date), pwId)
3737
+ readback: await readSession(ctx.client, programId, parseWorkoutDate(date), pwId),
3738
+ note: "Published. Verify with workout_read (same programId/date/pwId). Do not use athlete_workouts to check a coach-published team session — that tool is the authenticated user's own athlete calendar, not a roster athlete's schedule. For a roster athlete's view use athlete_saved_workouts."
3611
3739
  });
3612
3740
  }));
3613
3741
  }
@@ -3651,7 +3779,7 @@ function registerLifecycle(server, ctx) {
3651
3779
  }));
3652
3780
  server.registerTool("session_copy", {
3653
3781
  title: "Copy a session to a date",
3654
- description: "Copy/repeat a session to a target date on a program (POST .../copyProgramWorkout). toDate is YYYY-M-D. Creates a new session; review and publish it separately.",
3782
+ description: "Copy/repeat a session to a target date on a program (POST .../copyProgramWorkout). toDate is YYYY-M-D. Creates a new session; review and publish it separately. toProgramId may be a team group_program or an athlete calendar program id (from /v5/calendars/athletes/{athleteId}?year=&month= / workout_build athleteId).",
3655
3783
  inputSchema: {
3656
3784
  toProgramId: z.number(),
3657
3785
  pwId: z.number(),
@@ -3681,6 +3809,7 @@ function registerLifecycle(server, ctx) {
3681
3809
  /** Workout building, read-back, publishing, and the session calendar lifecycle. */
3682
3810
  function registerWorkoutTools(server, ctx) {
3683
3811
  registerBuild(server, ctx);
3812
+ registerReadPublish(server, ctx);
3684
3813
  registerLifecycle(server, ctx);
3685
3814
  }
3686
3815
  //#endregion
@@ -3804,7 +3933,7 @@ var JsonFileLibraryCache = class {
3804
3933
  };
3805
3934
  //#endregion
3806
3935
  //#region package.json
3807
- var version = "2.0.1";
3936
+ var version = "2.1.0";
3808
3937
  //#endregion
3809
3938
  //#region src/server.ts
3810
3939
  function main() {