@trainheroic-unofficial/coach-mcp 3.5.1 → 3.5.2
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.
- package/dist/server.mjs +329 -308
- package/package.json +3 -3
package/dist/server.mjs
CHANGED
|
@@ -745,15 +745,19 @@ z.object({
|
|
|
745
745
|
/**
|
|
746
746
|
* Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
|
|
747
747
|
* conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
|
|
748
|
-
* as a valid date. Each part must be
|
|
748
|
+
* as a valid date. Each part must be a run of digits (`Number("")` is 0, so a blank part such as
|
|
749
|
+
* the trailing one in "2026-9-" must be rejected explicitly), and month/day must be in range so
|
|
750
|
+
* a typo cannot land a session on a date the calendar does not have.
|
|
749
751
|
*/
|
|
750
752
|
function parseWorkoutDate(s) {
|
|
751
|
-
const parts = s.split("-")
|
|
752
|
-
if (parts.length !== 3 || parts.some((
|
|
753
|
+
const parts = s.split("-");
|
|
754
|
+
if (parts.length !== 3 || parts.some((p) => !/^\d+$/u.test(p))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
|
|
755
|
+
const [year, month, day] = parts.map(Number);
|
|
756
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) throw new Error(`date must be YYYY-M-D with a real month and day, got "${s}".`);
|
|
753
757
|
return [
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
758
|
+
year,
|
|
759
|
+
month,
|
|
760
|
+
day
|
|
757
761
|
];
|
|
758
762
|
}
|
|
759
763
|
/** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
|
|
@@ -837,12 +841,16 @@ function resultBudget() {
|
|
|
837
841
|
function isPlainObject(value) {
|
|
838
842
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
839
843
|
}
|
|
840
|
-
/**
|
|
841
|
-
|
|
844
|
+
/**
|
|
845
|
+
* Largest count k such that the JSON of the first k elements fits. Elements are serialized one
|
|
846
|
+
* at a time and the walk stops at the first overflow, so an oversized 10k-row result costs the
|
|
847
|
+
* serialization of the rows that fit, not of every row.
|
|
848
|
+
*/
|
|
849
|
+
function largestPrefixCount(elements, charBudget) {
|
|
842
850
|
let used = 2;
|
|
843
851
|
let k = 0;
|
|
844
|
-
for (const
|
|
845
|
-
const add =
|
|
852
|
+
for (const element of elements) {
|
|
853
|
+
const add = (JSON.stringify(element) ?? "null").length + (k > 0 ? 1 : 0);
|
|
846
854
|
if (used + add > charBudget) break;
|
|
847
855
|
used += add;
|
|
848
856
|
k += 1;
|
|
@@ -857,11 +865,12 @@ function hardCap(text, budget, hint) {
|
|
|
857
865
|
return text.slice(0, keep) + note;
|
|
858
866
|
}
|
|
859
867
|
function largestArrayValuedKey(obj) {
|
|
868
|
+
const arrayKeys = Object.keys(obj).filter((key) => Array.isArray(obj[key]));
|
|
869
|
+
if (arrayKeys.length <= 1) return arrayKeys[0] ?? null;
|
|
860
870
|
let best = null;
|
|
861
871
|
let bestLen = -1;
|
|
862
|
-
for (const
|
|
863
|
-
|
|
864
|
-
const len = (JSON.stringify(value) ?? "[]").length;
|
|
872
|
+
for (const key of arrayKeys) {
|
|
873
|
+
const len = (JSON.stringify(obj[key]) ?? "[]").length;
|
|
865
874
|
if (len > bestLen) {
|
|
866
875
|
best = key;
|
|
867
876
|
bestLen = len;
|
|
@@ -869,9 +878,6 @@ function largestArrayValuedKey(obj) {
|
|
|
869
878
|
}
|
|
870
879
|
return best;
|
|
871
880
|
}
|
|
872
|
-
function jsonValue(data) {
|
|
873
|
-
return JSON.parse(JSON.stringify(data) ?? "null");
|
|
874
|
-
}
|
|
875
881
|
function previewEnvelope(source, budget, hint) {
|
|
876
882
|
const total = source.length;
|
|
877
883
|
const makeValue = (preview, markerHint) => ({
|
|
@@ -898,8 +904,8 @@ function boundedResult(data, budget, hint) {
|
|
|
898
904
|
text: data,
|
|
899
905
|
value: data
|
|
900
906
|
};
|
|
901
|
-
const
|
|
902
|
-
const
|
|
907
|
+
const compact = JSON.stringify(data) ?? "null";
|
|
908
|
+
const value = JSON.parse(compact);
|
|
903
909
|
if (compact.length <= budget) {
|
|
904
910
|
const pretty = JSON.stringify(value, null, 2);
|
|
905
911
|
return {
|
|
@@ -908,7 +914,7 @@ function boundedResult(data, budget, hint) {
|
|
|
908
914
|
};
|
|
909
915
|
}
|
|
910
916
|
if (Array.isArray(value)) {
|
|
911
|
-
const truncated = clipArray(value, largestPrefixCount(value
|
|
917
|
+
const truncated = clipArray(value, largestPrefixCount(value, budget - MARKER_RESERVE), hint);
|
|
912
918
|
const text = JSON.stringify(truncated);
|
|
913
919
|
if (text.length <= budget) return {
|
|
914
920
|
text,
|
|
@@ -918,7 +924,7 @@ function boundedResult(data, budget, hint) {
|
|
|
918
924
|
const key = largestArrayValuedKey(value);
|
|
919
925
|
if (key !== null) {
|
|
920
926
|
const array = value[key];
|
|
921
|
-
const truncated = clipArray(array, largestPrefixCount(array
|
|
927
|
+
const truncated = clipArray(array, largestPrefixCount(array, budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
|
|
922
928
|
const text = JSON.stringify(truncated);
|
|
923
929
|
if (text.length <= budget) return {
|
|
924
930
|
text,
|
|
@@ -1220,6 +1226,26 @@ function checkResponse(schema, data, label) {
|
|
|
1220
1226
|
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
1221
1227
|
}
|
|
1222
1228
|
//#endregion
|
|
1229
|
+
//#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
|
|
1230
|
+
/**
|
|
1231
|
+
* Creates a duplicate-free version of an array.
|
|
1232
|
+
*
|
|
1233
|
+
* This function takes an array and returns a new array containing only the unique values
|
|
1234
|
+
* from the original array, preserving the order of first occurrence.
|
|
1235
|
+
*
|
|
1236
|
+
* @template T - The type of elements in the array.
|
|
1237
|
+
* @param arr - The array to process.
|
|
1238
|
+
* @returns A new array with only unique values from the original array.
|
|
1239
|
+
*
|
|
1240
|
+
* @example
|
|
1241
|
+
* const array = [1, 2, 2, 3, 4, 4, 5];
|
|
1242
|
+
* const result = uniq(array);
|
|
1243
|
+
* // result will be [1, 2, 3, 4, 5]
|
|
1244
|
+
*/
|
|
1245
|
+
function uniq(arr) {
|
|
1246
|
+
return [...new Set(arr)];
|
|
1247
|
+
}
|
|
1248
|
+
//#endregion
|
|
1223
1249
|
//#region ../js/src/exercise-util.ts
|
|
1224
1250
|
/**
|
|
1225
1251
|
* Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
|
|
@@ -1349,14 +1375,6 @@ function exerciseTitle(ex, fallback = "") {
|
|
|
1349
1375
|
return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
|
|
1350
1376
|
}
|
|
1351
1377
|
/**
|
|
1352
|
-
* True when a program-workout range item is a personal (athlete-created) session rather than a
|
|
1353
|
-
* coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
|
|
1354
|
-
* definition every consumer (presenter, find-or-create, the remove guard) reads through.
|
|
1355
|
-
*/
|
|
1356
|
-
function isPersonalSession(pw) {
|
|
1357
|
-
return isRecord(pw) && pw.personal_cal === true;
|
|
1358
|
-
}
|
|
1359
|
-
/**
|
|
1360
1378
|
* The `saved_workout` blob on a program-workout range item, or null if the athlete has no saved
|
|
1361
1379
|
* copy yet. Session notes, RPE, and set writes all resolve through this.
|
|
1362
1380
|
*/
|
|
@@ -1393,18 +1411,76 @@ function rankSearch(rows, query, limit) {
|
|
|
1393
1411
|
* on workerd, blowing the subrequest budget.
|
|
1394
1412
|
*/
|
|
1395
1413
|
async function mapPool(items, limit, fn) {
|
|
1414
|
+
assertPositiveInteger(limit, "Concurrency limit");
|
|
1396
1415
|
const out = Array.from({ length: items.length });
|
|
1397
1416
|
let next = 0;
|
|
1417
|
+
const state = { failure: null };
|
|
1398
1418
|
const worker = async () => {
|
|
1399
|
-
while (next < items.length) {
|
|
1419
|
+
while (next < items.length && state.failure === null) {
|
|
1400
1420
|
const i = next;
|
|
1401
1421
|
next += 1;
|
|
1402
|
-
|
|
1422
|
+
try {
|
|
1423
|
+
out[i] = await fn(items[i], i);
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
state.failure ??= { error };
|
|
1426
|
+
}
|
|
1403
1427
|
}
|
|
1404
1428
|
};
|
|
1405
1429
|
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
1430
|
+
if (state.failure !== null) throw state.failure.error;
|
|
1406
1431
|
return out;
|
|
1407
1432
|
}
|
|
1433
|
+
function createLimiter(max) {
|
|
1434
|
+
assertPositiveInteger(max, "Maximum concurrency");
|
|
1435
|
+
let active = 0;
|
|
1436
|
+
let cancelled = null;
|
|
1437
|
+
const waiting = [];
|
|
1438
|
+
const acquire = (finalizer) => new Promise((resolve, reject) => {
|
|
1439
|
+
if (cancelled !== null && !finalizer) reject(cancelled.error);
|
|
1440
|
+
else if (active < max) {
|
|
1441
|
+
active += 1;
|
|
1442
|
+
resolve();
|
|
1443
|
+
} else waiting.push({
|
|
1444
|
+
start: () => {
|
|
1445
|
+
active += 1;
|
|
1446
|
+
resolve();
|
|
1447
|
+
},
|
|
1448
|
+
abort: reject,
|
|
1449
|
+
finalizer
|
|
1450
|
+
});
|
|
1451
|
+
});
|
|
1452
|
+
const release = () => {
|
|
1453
|
+
active -= 1;
|
|
1454
|
+
waiting.shift()?.start();
|
|
1455
|
+
};
|
|
1456
|
+
return {
|
|
1457
|
+
async run(task) {
|
|
1458
|
+
await acquire(false);
|
|
1459
|
+
try {
|
|
1460
|
+
return await task();
|
|
1461
|
+
} finally {
|
|
1462
|
+
release();
|
|
1463
|
+
}
|
|
1464
|
+
},
|
|
1465
|
+
async runFinalizer(task) {
|
|
1466
|
+
await acquire(true);
|
|
1467
|
+
try {
|
|
1468
|
+
return await task();
|
|
1469
|
+
} finally {
|
|
1470
|
+
release();
|
|
1471
|
+
}
|
|
1472
|
+
},
|
|
1473
|
+
cancel(error) {
|
|
1474
|
+
cancelled ??= { error };
|
|
1475
|
+
const queued = waiting.splice(0);
|
|
1476
|
+
for (const entry of queued) if (entry.finalizer) waiting.push(entry);
|
|
1477
|
+
else entry.abort(error);
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
function assertPositiveInteger(value, label) {
|
|
1482
|
+
if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
|
|
1483
|
+
}
|
|
1408
1484
|
//#endregion
|
|
1409
1485
|
//#region ../js/src/athlete.ts
|
|
1410
1486
|
async function getJson(client, path, label) {
|
|
@@ -1439,39 +1515,25 @@ function sortRosterByRecency(rows) {
|
|
|
1439
1515
|
* summary becomes a null-data row (sorted last), not an error.
|
|
1440
1516
|
*/
|
|
1441
1517
|
async function fetchRosterActivity(client, athleteIds, useMetric = false) {
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
try {
|
|
1449
|
-
return {
|
|
1450
|
-
id,
|
|
1451
|
-
summary: await fetchAthleteProfileSummary(client, id, useMetric)
|
|
1452
|
-
};
|
|
1453
|
-
} catch {
|
|
1454
|
-
return {
|
|
1455
|
-
id,
|
|
1456
|
-
summary: null
|
|
1457
|
-
};
|
|
1458
|
-
}
|
|
1459
|
-
}));
|
|
1460
|
-
for (const { id, summary } of settled) {
|
|
1461
|
-
const count = summary?.sessions_count ?? null;
|
|
1462
|
-
const hasSessions = count !== null && count > 0;
|
|
1463
|
-
const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
|
|
1464
|
-
rows.push({
|
|
1465
|
-
athleteId: id,
|
|
1466
|
-
sessionsCount: count,
|
|
1467
|
-
firstLoggedDate: normDate(summary?.first_logged_date),
|
|
1468
|
-
lastLoggedDate: normDate(summary?.last_logged_date),
|
|
1469
|
-
totalReps: summary?.reps_sum ?? null,
|
|
1470
|
-
totalVolume: summary?.volume_sum ?? null
|
|
1471
|
-
});
|
|
1518
|
+
return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
|
|
1519
|
+
let summary;
|
|
1520
|
+
try {
|
|
1521
|
+
summary = await fetchAthleteProfileSummary(client, id, useMetric);
|
|
1522
|
+
} catch {
|
|
1523
|
+
summary = null;
|
|
1472
1524
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1525
|
+
const count = summary?.sessions_count ?? null;
|
|
1526
|
+
const hasSessions = count !== null && count > 0;
|
|
1527
|
+
const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
|
|
1528
|
+
return {
|
|
1529
|
+
athleteId: id,
|
|
1530
|
+
sessionsCount: count,
|
|
1531
|
+
firstLoggedDate: normDate(summary?.first_logged_date),
|
|
1532
|
+
lastLoggedDate: normDate(summary?.last_logged_date),
|
|
1533
|
+
totalReps: summary?.reps_sum ?? null,
|
|
1534
|
+
totalVolume: summary?.volume_sum ?? null
|
|
1535
|
+
};
|
|
1536
|
+
}));
|
|
1475
1537
|
}
|
|
1476
1538
|
function fetchExerciseHistoryDetail(client, exerciseId, userId) {
|
|
1477
1539
|
return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
|
|
@@ -1498,6 +1560,28 @@ function slotValues(ex, requireMade) {
|
|
|
1498
1560
|
}
|
|
1499
1561
|
return map;
|
|
1500
1562
|
}
|
|
1563
|
+
/**
|
|
1564
|
+
* The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
|
|
1565
|
+
* saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
|
|
1566
|
+
* coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
|
|
1567
|
+
* only prescription, since personal work has no template tree at all.
|
|
1568
|
+
*/
|
|
1569
|
+
function unmadeSlotValues(ex) {
|
|
1570
|
+
const map = slotValues(ex, false);
|
|
1571
|
+
for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
|
|
1572
|
+
return map;
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* The prescription for one exercise: the template row's slots, with any target the saved copy
|
|
1576
|
+
* still holds unperformed taking precedence per set index (that is what the athlete's app shows,
|
|
1577
|
+
* and where a per-athlete override lives). Without a template row the saved copy's unperformed
|
|
1578
|
+
* slots are the whole prescription.
|
|
1579
|
+
*/
|
|
1580
|
+
function prescriptionSlots(template, saved) {
|
|
1581
|
+
const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
|
|
1582
|
+
if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
|
|
1583
|
+
return map;
|
|
1584
|
+
}
|
|
1501
1585
|
/** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
|
|
1502
1586
|
function fmtSlot(slot) {
|
|
1503
1587
|
const has1 = slot.p1 !== null;
|
|
@@ -1507,10 +1591,6 @@ function fmtSlot(slot) {
|
|
|
1507
1591
|
if (has2) return `@ ${slot.p2}`;
|
|
1508
1592
|
return "";
|
|
1509
1593
|
}
|
|
1510
|
-
/** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
|
|
1511
|
-
function prescribedStrings(ex) {
|
|
1512
|
-
return [...slotValues(ex, false).values()].map(fmtSlot);
|
|
1513
|
-
}
|
|
1514
1594
|
/** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
|
|
1515
1595
|
function performedStrings(ex) {
|
|
1516
1596
|
return [...slotValues(ex, true).values()].map(fmtSlot);
|
|
@@ -1532,179 +1612,45 @@ function savedSets(saved) {
|
|
|
1532
1612
|
return out;
|
|
1533
1613
|
}
|
|
1534
1614
|
/**
|
|
1535
|
-
*
|
|
1536
|
-
*
|
|
1537
|
-
*
|
|
1615
|
+
* Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
|
|
1616
|
+
* list of range items, read straight off the saved copies. This is the cheap tally for callers
|
|
1617
|
+
* that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
|
|
1618
|
+
* and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
|
|
1538
1619
|
*/
|
|
1539
|
-
function
|
|
1540
|
-
const
|
|
1541
|
-
for (const
|
|
1542
|
-
const
|
|
1543
|
-
|
|
1544
|
-
const
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
}))
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
/** A prescription block, each exercise aligned with the slots the athlete logged against it. */
|
|
1572
|
-
function mergePrescriptionBlock(set, performedById, notesById) {
|
|
1573
|
-
const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
|
|
1574
|
-
return {
|
|
1575
|
-
order: coerceInt(set.order) ?? 0,
|
|
1576
|
-
title: str$1(set.title),
|
|
1577
|
-
instruction: str$1(set.instruction),
|
|
1578
|
-
isTest: coerceInt(set.is_test) === 1,
|
|
1579
|
-
exercises: exercises.filter(isRecord).map((ex) => {
|
|
1580
|
-
const id = coerceInt(ex.id);
|
|
1581
|
-
const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
|
|
1582
|
-
return mergeExercise(slotValues(ex, false), performed, {
|
|
1583
|
-
exerciseId: coerceInt(ex.exercise_id),
|
|
1584
|
-
title: typeof ex.title === "string" ? ex.title : "",
|
|
1585
|
-
instruction: str$1(ex.instruction),
|
|
1586
|
-
notes: id !== null ? notesById.get(id) ?? null : null,
|
|
1587
|
-
units: exerciseUnits(ex.param_1_type, ex.param_2_type)
|
|
1620
|
+
function performedExercises(workouts) {
|
|
1621
|
+
const out = [];
|
|
1622
|
+
for (const pw of workouts) {
|
|
1623
|
+
const rec = pw;
|
|
1624
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1625
|
+
const workout = isRecord(ssw.workout) ? ssw.workout : {};
|
|
1626
|
+
const templates = /* @__PURE__ */ new Map();
|
|
1627
|
+
for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
|
|
1628
|
+
if (!isRecord(set)) continue;
|
|
1629
|
+
const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
|
|
1630
|
+
for (const ex of exercises) {
|
|
1631
|
+
if (!isRecord(ex)) continue;
|
|
1632
|
+
const id = coerceInt(ex.id);
|
|
1633
|
+
if (id !== null) templates.set(id, {
|
|
1634
|
+
exerciseId: coerceInt(ex.exercise_id),
|
|
1635
|
+
title: exerciseTitle(ex)
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
const saved = savedWorkoutOf(pw);
|
|
1640
|
+
if (!saved) continue;
|
|
1641
|
+
for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
|
|
1642
|
+
const templateId = coerceInt(ex.workout_set_exercise_id);
|
|
1643
|
+
const template = templateId === null ? void 0 : templates.get(templateId);
|
|
1644
|
+
const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
|
|
1645
|
+
if (exerciseId === null || slotValues(ex, true).size === 0) continue;
|
|
1646
|
+
out.push({
|
|
1647
|
+
exerciseId,
|
|
1648
|
+
title: exerciseTitle(ex, template?.title)
|
|
1588
1649
|
});
|
|
1589
|
-
})
|
|
1590
|
-
};
|
|
1591
|
-
}
|
|
1592
|
-
/** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
|
|
1593
|
-
function mergeSavedBlock(set, exercises) {
|
|
1594
|
-
return {
|
|
1595
|
-
order: coerceInt(set.order) ?? 0,
|
|
1596
|
-
title: str$1(set.title),
|
|
1597
|
-
instruction: str$1(set.instruction),
|
|
1598
|
-
isTest: coerceInt(set.is_test) === 1,
|
|
1599
|
-
exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
|
|
1600
|
-
exerciseId: coerceInt(ex.exercise_id),
|
|
1601
|
-
title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
|
|
1602
|
-
instruction: str$1(ex.instruction),
|
|
1603
|
-
notes: str$1(ex.notes),
|
|
1604
|
-
units: exerciseUnits(ex.param_1_type, ex.param_2_type)
|
|
1605
|
-
}))
|
|
1606
|
-
};
|
|
1607
|
-
}
|
|
1608
|
-
/**
|
|
1609
|
-
* Flatten one `/3.0/athlete/programworkout/range` item into the canonical merged form, joining the
|
|
1610
|
-
* prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
|
|
1611
|
-
* (`summarizedSavedWorkout.saved_workout`). Prescription blocks are enriched with logged slots;
|
|
1612
|
-
* athlete-added / personal work with no prescription is appended as its own block.
|
|
1613
|
-
*/
|
|
1614
|
-
function mergeAthleteWorkout(raw) {
|
|
1615
|
-
const rec = raw;
|
|
1616
|
-
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1617
|
-
const workout = isRecord(ssw.workout) ? ssw.workout : {};
|
|
1618
|
-
const saved = savedWorkoutOf(rec) ?? {};
|
|
1619
|
-
const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
|
|
1620
|
-
const logged = savedSets(saved);
|
|
1621
|
-
const performedById = performedSlotsByExerciseId(logged);
|
|
1622
|
-
const notesById = notesByTemplateId(logged);
|
|
1623
|
-
const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
|
|
1624
|
-
const prescribedIds = /* @__PURE__ */ new Set();
|
|
1625
|
-
for (const s of prescriptionSets) {
|
|
1626
|
-
const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
1627
|
-
for (const ex of exs) {
|
|
1628
|
-
if (!isRecord(ex)) continue;
|
|
1629
|
-
const id = coerceInt(ex.id);
|
|
1630
|
-
if (id !== null) prescribedIds.add(id);
|
|
1631
1650
|
}
|
|
1632
1651
|
}
|
|
1633
|
-
for (const { set, exercises } of logged) {
|
|
1634
|
-
const extra = exercises.filter((ex) => {
|
|
1635
|
-
if (slotValues(ex, true).size === 0) return false;
|
|
1636
|
-
const id = coerceInt(ex.workout_set_exercise_id);
|
|
1637
|
-
return id === null || !prescribedIds.has(id);
|
|
1638
|
-
});
|
|
1639
|
-
if (extra.length > 0) blocks.push(mergeSavedBlock(set, extra));
|
|
1640
|
-
}
|
|
1641
|
-
return {
|
|
1642
|
-
id: coerceInt(rec.id),
|
|
1643
|
-
date: str$1(rec.date) ?? "",
|
|
1644
|
-
title: str$1(rec.workout_title) ?? "",
|
|
1645
|
-
program: str$1(rec.program_title),
|
|
1646
|
-
team: str$1(rec.team_title),
|
|
1647
|
-
instruction: str$1(workout.instruction),
|
|
1648
|
-
notes: str$1(saved.notes),
|
|
1649
|
-
rpe: coerceInt(saved.rpe),
|
|
1650
|
-
logged: blocks.some((b) => b.exercises.some((e) => e.sets.some((s) => s.performed !== null))),
|
|
1651
|
-
personal: isPersonalSession(rec),
|
|
1652
|
-
blocks
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
/** The per-set displays for one side (prescribed or performed), in slot order. */
|
|
1656
|
-
function sideStrings(sets, pick) {
|
|
1657
|
-
const out = [];
|
|
1658
|
-
for (const s of sets) {
|
|
1659
|
-
const slot = pick(s);
|
|
1660
|
-
if (slot) out.push(fmtSlot(slot));
|
|
1661
|
-
}
|
|
1662
1652
|
return out;
|
|
1663
1653
|
}
|
|
1664
|
-
function toStringExercise(ex) {
|
|
1665
|
-
return {
|
|
1666
|
-
exerciseId: ex.exerciseId,
|
|
1667
|
-
title: ex.title,
|
|
1668
|
-
instruction: ex.instruction,
|
|
1669
|
-
notes: ex.notes,
|
|
1670
|
-
units: ex.units,
|
|
1671
|
-
prescribed: sideStrings(ex.sets, (s) => s.prescribed),
|
|
1672
|
-
performed: sideStrings(ex.sets, (s) => s.performed)
|
|
1673
|
-
};
|
|
1674
|
-
}
|
|
1675
|
-
function toStringBlock(b) {
|
|
1676
|
-
return {
|
|
1677
|
-
order: b.order,
|
|
1678
|
-
title: b.title,
|
|
1679
|
-
instruction: b.instruction,
|
|
1680
|
-
isTest: b.isTest,
|
|
1681
|
-
exercises: b.exercises.map(toStringExercise)
|
|
1682
|
-
};
|
|
1683
|
-
}
|
|
1684
|
-
/**
|
|
1685
|
-
* Flatten one range item into a readable workout: each exercise carries its `prescribed` and
|
|
1686
|
-
* `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
|
|
1687
|
-
* prescription is appended as its own blocks. No `raw` is needed to see logged results.
|
|
1688
|
-
*/
|
|
1689
|
-
function presentAthleteWorkout(raw) {
|
|
1690
|
-
const w = mergeAthleteWorkout(raw);
|
|
1691
|
-
return {
|
|
1692
|
-
id: w.id,
|
|
1693
|
-
date: w.date,
|
|
1694
|
-
title: w.title,
|
|
1695
|
-
program: w.program,
|
|
1696
|
-
team: w.team,
|
|
1697
|
-
instruction: w.instruction,
|
|
1698
|
-
notes: w.notes,
|
|
1699
|
-
rpe: w.rpe,
|
|
1700
|
-
logged: w.logged,
|
|
1701
|
-
personal: w.personal,
|
|
1702
|
-
blocks: w.blocks.map(toStringBlock)
|
|
1703
|
-
};
|
|
1704
|
-
}
|
|
1705
|
-
function presentAthleteWorkouts(list) {
|
|
1706
|
-
return list.map(presentAthleteWorkout);
|
|
1707
|
-
}
|
|
1708
1654
|
/**
|
|
1709
1655
|
* Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
|
|
1710
1656
|
* every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
|
|
@@ -1743,6 +1689,16 @@ function presentLogTargets(list) {
|
|
|
1743
1689
|
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1744
1690
|
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
1745
1691
|
if (!saved) continue;
|
|
1692
|
+
const workout = isRecord(ssw.workout) ? ssw.workout : {};
|
|
1693
|
+
const templatesById = /* @__PURE__ */ new Map();
|
|
1694
|
+
for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
|
|
1695
|
+
if (!isRecord(tSet)) continue;
|
|
1696
|
+
const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
|
|
1697
|
+
for (const tEx of tExs) {
|
|
1698
|
+
const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
|
|
1699
|
+
if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1746
1702
|
const date = str$1(rec.date) ?? "";
|
|
1747
1703
|
const workoutTitle = str$1(rec.workout_title) ?? "";
|
|
1748
1704
|
const program = str$1(rec.program_title);
|
|
@@ -1757,12 +1713,14 @@ function presentLogTargets(list) {
|
|
|
1757
1713
|
const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
|
|
1758
1714
|
const id = coerceInt(ex.id);
|
|
1759
1715
|
if (id === null) return null;
|
|
1716
|
+
const templateId = coerceInt(ex.workout_set_exercise_id);
|
|
1717
|
+
const template = templateId === null ? void 0 : templatesById.get(templateId);
|
|
1760
1718
|
return {
|
|
1761
1719
|
savedWorkoutSetExerciseId: id,
|
|
1762
1720
|
title: exerciseTitle(ex),
|
|
1763
1721
|
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
1764
1722
|
notes: str$1(ex.notes),
|
|
1765
|
-
prescribed:
|
|
1723
|
+
prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
|
|
1766
1724
|
performed: performedStrings(ex)
|
|
1767
1725
|
};
|
|
1768
1726
|
}).filter((e) => e !== null);
|
|
@@ -1852,6 +1810,28 @@ function presentExerciseHistory(detail) {
|
|
|
1852
1810
|
};
|
|
1853
1811
|
}
|
|
1854
1812
|
//#endregion
|
|
1813
|
+
//#region ../js/src/exercise-history.ts
|
|
1814
|
+
/**
|
|
1815
|
+
* Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
|
|
1816
|
+
* The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
|
|
1817
|
+
* first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
|
|
1818
|
+
* window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
|
|
1819
|
+
* tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
|
|
1820
|
+
*/
|
|
1821
|
+
function historyInRange(presented, since, until) {
|
|
1822
|
+
if (since === void 0 && until === void 0) return presented;
|
|
1823
|
+
const sessions = presented.sessions.filter((s) => {
|
|
1824
|
+
const d = (s.date ?? "").slice(0, 10);
|
|
1825
|
+
if (since !== void 0 && d < since) return false;
|
|
1826
|
+
if (until !== void 0 && d > until) return false;
|
|
1827
|
+
return true;
|
|
1828
|
+
});
|
|
1829
|
+
return {
|
|
1830
|
+
...presented,
|
|
1831
|
+
sessions
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
//#endregion
|
|
1855
1835
|
//#region ../js/src/coach-athlete-calendar.ts
|
|
1856
1836
|
async function getArray(client, path, label) {
|
|
1857
1837
|
const res = await client.request("GET", path);
|
|
@@ -1986,6 +1966,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
|
|
|
1986
1966
|
}
|
|
1987
1967
|
//#endregion
|
|
1988
1968
|
//#region ../js/src/athlete-set-write.ts
|
|
1969
|
+
const WRITE_CONCURRENCY = 4;
|
|
1989
1970
|
/**
|
|
1990
1971
|
* Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
|
|
1991
1972
|
* {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
|
|
@@ -2188,6 +2169,41 @@ async function swapAthleteExercise(client, args) {
|
|
|
2188
2169
|
originalTeamExerciseId: coerceInt(template.exercise_id)
|
|
2189
2170
|
};
|
|
2190
2171
|
}
|
|
2172
|
+
function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
|
|
2173
|
+
const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
|
|
2174
|
+
assertUniqueExerciseResults(results);
|
|
2175
|
+
const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
|
|
2176
|
+
const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
|
|
2177
|
+
return {
|
|
2178
|
+
savedWorkoutSetId,
|
|
2179
|
+
exercises,
|
|
2180
|
+
rawSet,
|
|
2181
|
+
suffix,
|
|
2182
|
+
extra,
|
|
2183
|
+
writes: results.map((result) => {
|
|
2184
|
+
const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
|
|
2185
|
+
if (!ex) {
|
|
2186
|
+
const valid = exercises.map((candidate) => {
|
|
2187
|
+
const id = coerceInt(candidate.id);
|
|
2188
|
+
return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
|
|
2189
|
+
}).filter((label) => label !== null);
|
|
2190
|
+
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
2191
|
+
}
|
|
2192
|
+
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
2193
|
+
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
2194
|
+
return {
|
|
2195
|
+
id: result.savedWorkoutSetExerciseId,
|
|
2196
|
+
body: {
|
|
2197
|
+
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
|
|
2198
|
+
...extra
|
|
2199
|
+
}
|
|
2200
|
+
};
|
|
2201
|
+
})
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
function errorMessage(error) {
|
|
2205
|
+
return error instanceof Error ? error.message : String(error);
|
|
2206
|
+
}
|
|
2191
2207
|
/**
|
|
2192
2208
|
* Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
|
|
2193
2209
|
* {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
|
|
@@ -2201,36 +2217,40 @@ async function swapAthleteExercise(client, args) {
|
|
|
2201
2217
|
* the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
|
|
2202
2218
|
* open.
|
|
2203
2219
|
*/
|
|
2204
|
-
async function
|
|
2205
|
-
const { exercises, rawSet } =
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
const id = coerceInt(e.id);
|
|
2216
|
-
return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
|
|
2217
|
-
}).filter((x) => x !== null);
|
|
2218
|
-
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
2219
|
-
}
|
|
2220
|
-
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
2221
|
-
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
2222
|
-
const body = {
|
|
2223
|
-
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
|
|
2224
|
-
...extra
|
|
2220
|
+
async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
|
|
2221
|
+
const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
|
|
2222
|
+
const put = (path, body, failureMessage, finalizer = false) => {
|
|
2223
|
+
const request = async () => {
|
|
2224
|
+
try {
|
|
2225
|
+
const res = await client.request("PUT", path, { body });
|
|
2226
|
+
if (!res.ok) throw new Error(failureMessage(res.status));
|
|
2227
|
+
} catch (error) {
|
|
2228
|
+
limit.cancel(error);
|
|
2229
|
+
throw error;
|
|
2230
|
+
}
|
|
2225
2231
|
};
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
}
|
|
2231
|
-
|
|
2232
|
-
|
|
2232
|
+
return finalizer ? limit.runFinalizer(request) : limit.run(request);
|
|
2233
|
+
};
|
|
2234
|
+
const confirmed = [];
|
|
2235
|
+
try {
|
|
2236
|
+
await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
|
|
2237
|
+
await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
|
|
2238
|
+
return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
|
|
2239
|
+
});
|
|
2240
|
+
confirmed.push(id);
|
|
2241
|
+
if (sessionProgress) {
|
|
2242
|
+
const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
|
|
2243
|
+
sessionConfirmed.push(id);
|
|
2244
|
+
sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
|
|
2245
|
+
}
|
|
2246
|
+
});
|
|
2247
|
+
} catch (error) {
|
|
2248
|
+
if (sessionProgress || confirmed.length === 0) throw error;
|
|
2249
|
+
confirmed.sort((a, b) => a - b);
|
|
2250
|
+
throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
|
|
2233
2251
|
}
|
|
2252
|
+
const exercisesWritten = writes.length;
|
|
2253
|
+
const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
|
|
2234
2254
|
let setCompleted = false;
|
|
2235
2255
|
if (mode === "log") {
|
|
2236
2256
|
if (isSetFullyLogged(exercises, projectedCompletion)) {
|
|
@@ -2238,8 +2258,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
2238
2258
|
...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
|
|
2239
2259
|
...extra
|
|
2240
2260
|
};
|
|
2241
|
-
|
|
2242
|
-
|
|
2261
|
+
try {
|
|
2262
|
+
await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
|
|
2263
|
+
} catch (error) {
|
|
2264
|
+
throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
|
|
2265
|
+
}
|
|
2243
2266
|
setCompleted = true;
|
|
2244
2267
|
}
|
|
2245
2268
|
}
|
|
@@ -2249,6 +2272,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
2249
2272
|
setCompleted
|
|
2250
2273
|
};
|
|
2251
2274
|
}
|
|
2275
|
+
async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
|
|
2276
|
+
return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
|
|
2277
|
+
}
|
|
2252
2278
|
/**
|
|
2253
2279
|
* Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
|
|
2254
2280
|
* carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
|
|
@@ -2303,7 +2329,7 @@ function prescribedExerciseLabels(workouts) {
|
|
|
2303
2329
|
return labels;
|
|
2304
2330
|
}
|
|
2305
2331
|
/** Group resolved exercises by saved set and write each set via the given log target. */
|
|
2306
|
-
async function logResolvedExercises(client, target, workouts, resolved) {
|
|
2332
|
+
async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
|
|
2307
2333
|
const bySet = /* @__PURE__ */ new Map();
|
|
2308
2334
|
for (const r of resolved) {
|
|
2309
2335
|
const list = bySet.get(r.savedWorkoutSetId) ?? [];
|
|
@@ -2313,15 +2339,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
|
|
|
2313
2339
|
});
|
|
2314
2340
|
bySet.set(r.savedWorkoutSetId, list);
|
|
2315
2341
|
}
|
|
2316
|
-
const
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2342
|
+
const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
|
|
2343
|
+
const limit = createLimiter(WRITE_CONCURRENCY);
|
|
2344
|
+
const confirmedBySet = /* @__PURE__ */ new Map();
|
|
2345
|
+
const succeeded = [];
|
|
2346
|
+
try {
|
|
2347
|
+
return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
|
|
2348
|
+
const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
|
|
2349
|
+
succeeded.push(written.savedWorkoutSetId);
|
|
2350
|
+
return {
|
|
2351
|
+
savedWorkoutSetId: written.savedWorkoutSetId,
|
|
2352
|
+
exercisesLogged: written.exercisesWritten
|
|
2353
|
+
};
|
|
2322
2354
|
});
|
|
2355
|
+
} catch (error) {
|
|
2356
|
+
const completed = new Set(succeeded);
|
|
2357
|
+
const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
|
|
2358
|
+
if (incomplete.length === 0 && succeeded.length === 0) throw error;
|
|
2359
|
+
succeeded.sort((a, b) => a - b);
|
|
2360
|
+
const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
|
|
2361
|
+
const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
|
|
2362
|
+
throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
|
|
2323
2363
|
}
|
|
2324
|
-
return out;
|
|
2325
2364
|
}
|
|
2326
2365
|
/**
|
|
2327
2366
|
* Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
|
|
@@ -2351,7 +2390,7 @@ async function logSessionForAthlete(client, args) {
|
|
|
2351
2390
|
const sets = await logResolvedExercises(client, {
|
|
2352
2391
|
role: "coach",
|
|
2353
2392
|
athleteId: args.athleteId
|
|
2354
|
-
}, day, resolved);
|
|
2393
|
+
}, day, resolved, "Retry the same request to reconcile them.");
|
|
2355
2394
|
return {
|
|
2356
2395
|
date: args.date,
|
|
2357
2396
|
created: false,
|
|
@@ -2758,7 +2797,7 @@ async function readSession(client, programId, date, pwId) {
|
|
|
2758
2797
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2759
2798
|
return {
|
|
2760
2799
|
pwId,
|
|
2761
|
-
date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
|
|
2800
|
+
date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
|
|
2762
2801
|
published: pw.published,
|
|
2763
2802
|
instruction: str(pw.instruction),
|
|
2764
2803
|
blocks
|
|
@@ -2778,14 +2817,13 @@ function readBlock(b) {
|
|
|
2778
2817
|
};
|
|
2779
2818
|
}
|
|
2780
2819
|
function readExercise(ex) {
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
}
|
|
2820
|
+
let last = 0;
|
|
2821
|
+
for (let i = 1; i <= 10; i += 1) if (str(ex[`param_1_data_${i}`]) !== "" || str(ex[`param_2_data_${i}`]) !== "") last = i;
|
|
2822
|
+
const slots = Array.from({ length: last }, (_, k) => k + 1);
|
|
2823
|
+
const repsRaw = slots.map((i) => str(ex[`param_1_data_${i}`]));
|
|
2824
|
+
const loadRaw = slots.map((i) => str(ex[`param_2_data_${i}`]));
|
|
2825
|
+
const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
|
|
2826
|
+
const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
|
|
2789
2827
|
return {
|
|
2790
2828
|
order: Number(ex.order),
|
|
2791
2829
|
title: str(ex.title),
|
|
@@ -3340,8 +3378,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
|
3340
3378
|
} catch {
|
|
3341
3379
|
workouts = [];
|
|
3342
3380
|
}
|
|
3343
|
-
for (const
|
|
3344
|
-
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
3381
|
+
for (const ex of performedExercises(workouts)) {
|
|
3345
3382
|
const family = classifyMainLift(ex.title);
|
|
3346
3383
|
if (family === null) continue;
|
|
3347
3384
|
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
@@ -3586,6 +3623,7 @@ var ExerciseLibrary = class {
|
|
|
3586
3623
|
#byId = /* @__PURE__ */ new Map();
|
|
3587
3624
|
#loaded = false;
|
|
3588
3625
|
#fetchedAt = 0;
|
|
3626
|
+
#loading = null;
|
|
3589
3627
|
constructor(client, cache = new MemoryLibraryCache()) {
|
|
3590
3628
|
this.#client = client;
|
|
3591
3629
|
this.#cache = cache;
|
|
@@ -3613,8 +3651,11 @@ var ExerciseLibrary = class {
|
|
|
3613
3651
|
});
|
|
3614
3652
|
}
|
|
3615
3653
|
async ensureFresh() {
|
|
3616
|
-
if (
|
|
3617
|
-
|
|
3654
|
+
if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS) return;
|
|
3655
|
+
this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
|
|
3656
|
+
this.#loading = null;
|
|
3657
|
+
});
|
|
3658
|
+
await this.#loading;
|
|
3618
3659
|
}
|
|
3619
3660
|
async refresh() {
|
|
3620
3661
|
const res = await this.#client.request("GET", LIBRARY_PATH);
|
|
@@ -3633,6 +3674,7 @@ var ExerciseLibrary = class {
|
|
|
3633
3674
|
return presentExercise(s.raw);
|
|
3634
3675
|
}
|
|
3635
3676
|
async defaultsMany(ids) {
|
|
3677
|
+
await this.ensureFresh();
|
|
3636
3678
|
const result = /* @__PURE__ */ new Map();
|
|
3637
3679
|
for (const id of ids) {
|
|
3638
3680
|
const s = this.#byId.get(id);
|
|
@@ -3720,27 +3762,6 @@ var ExerciseLibrary = class {
|
|
|
3720
3762
|
}
|
|
3721
3763
|
};
|
|
3722
3764
|
//#endregion
|
|
3723
|
-
//#region ../core/src/history.ts
|
|
3724
|
-
/**
|
|
3725
|
-
* Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
|
|
3726
|
-
* The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
|
|
3727
|
-
* first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. Shared by
|
|
3728
|
-
* the athlete's own history tool and the coach's per-roster-athlete history tool.
|
|
3729
|
-
*/
|
|
3730
|
-
function historyInRange(presented, since, until) {
|
|
3731
|
-
if (since === void 0 && until === void 0) return presented;
|
|
3732
|
-
const sessions = presented.sessions.filter((s) => {
|
|
3733
|
-
const d = (s.date ?? "").slice(0, 10);
|
|
3734
|
-
if (since !== void 0 && d < since) return false;
|
|
3735
|
-
if (until !== void 0 && d > until) return false;
|
|
3736
|
-
return true;
|
|
3737
|
-
});
|
|
3738
|
-
return {
|
|
3739
|
-
...presented,
|
|
3740
|
-
sessions
|
|
3741
|
-
};
|
|
3742
|
-
}
|
|
3743
|
-
//#endregion
|
|
3744
3765
|
//#region ../core/src/tools/reads.ts
|
|
3745
3766
|
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.";
|
|
3746
3767
|
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.";
|
|
@@ -4832,7 +4853,7 @@ var JsonFileLibraryCache = class {
|
|
|
4832
4853
|
};
|
|
4833
4854
|
//#endregion
|
|
4834
4855
|
//#region package.json
|
|
4835
|
-
var version = "3.5.
|
|
4856
|
+
var version = "3.5.2";
|
|
4836
4857
|
//#endregion
|
|
4837
4858
|
//#region src/server.ts
|
|
4838
4859
|
function main() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/coach-mcp",
|
|
3
|
-
"version": "3.5.
|
|
3
|
+
"version": "3.5.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
"dependencies": {
|
|
22
22
|
"@modelcontextprotocol/server": "2.0.0",
|
|
23
23
|
"zod": "^4.4.3",
|
|
24
|
-
"@trainheroic-unofficial/
|
|
25
|
-
"@trainheroic-unofficial/
|
|
24
|
+
"@trainheroic-unofficial/js": "3.5.2",
|
|
25
|
+
"@trainheroic-unofficial/core": "3.5.2"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^26.3.0",
|