@trainheroic-unofficial/coach-mcp 3.6.0 → 3.7.1
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 +316 -139
- package/package.json +7 -7
package/dist/server.mjs
CHANGED
|
@@ -414,11 +414,37 @@ const exerciseResolveOutputSchema = z.object({
|
|
|
414
414
|
match: exerciseViewSchema.nullable(),
|
|
415
415
|
candidates: z.array(exerciseViewSchema)
|
|
416
416
|
});
|
|
417
|
+
/** TrainHeroic's documented exercise parameter-type codes. */
|
|
418
|
+
const exerciseParamTypeSchema = z.union([
|
|
419
|
+
z.literal(0),
|
|
420
|
+
z.literal(1),
|
|
421
|
+
z.literal(2),
|
|
422
|
+
z.literal(3),
|
|
423
|
+
z.literal(4),
|
|
424
|
+
z.literal(5),
|
|
425
|
+
z.literal(6),
|
|
426
|
+
z.literal(7),
|
|
427
|
+
z.literal(10),
|
|
428
|
+
z.literal(11),
|
|
429
|
+
z.literal(12),
|
|
430
|
+
z.literal(13),
|
|
431
|
+
z.literal(14),
|
|
432
|
+
z.literal(18)
|
|
433
|
+
]);
|
|
434
|
+
const exerciseWriteShape = {
|
|
435
|
+
title: z.string().trim().min(1),
|
|
436
|
+
param_1_type: exerciseParamTypeSchema.optional(),
|
|
437
|
+
param_2_type: exerciseParamTypeSchema.optional()
|
|
438
|
+
};
|
|
417
439
|
/** Body for creating a custom exercise; extra fields the API accepts are preserved. */
|
|
418
440
|
const exerciseCreateSchema = z.looseObject({
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
441
|
+
...exerciseWriteShape,
|
|
442
|
+
points_of_performance: z.string().default("")
|
|
443
|
+
});
|
|
444
|
+
/** Body for updating a custom exercise without clearing fields the caller omitted. */
|
|
445
|
+
const exerciseUpdateSchema = z.looseObject({
|
|
446
|
+
...exerciseWriteShape,
|
|
447
|
+
points_of_performance: z.string().optional()
|
|
422
448
|
});
|
|
423
449
|
//#endregion
|
|
424
450
|
//#region ../dto/src/messaging.ts
|
|
@@ -1032,12 +1058,47 @@ function confirmGate(ctx, message, confirmArg) {
|
|
|
1032
1058
|
*/
|
|
1033
1059
|
const SERVER_INSTRUCTIONS = "Speak to the user in plain, everyday language about their training. Describe what you are doing in the TrainHeroic app's own terms (for example, say you are creating a workout rather than naming a tool). Do not surface internal tool names (the snake_case identifiers such as athlete_session_create), raw parameter names, or numeric ids in your replies unless the user explicitly asks for them; they are implementation details. The tool descriptions cross-reference each other by name only so you can chain them correctly. Keep that wiring to yourself.";
|
|
1034
1060
|
//#endregion
|
|
1061
|
+
//#region ../js/src/date-window.ts
|
|
1062
|
+
const DAY_MS = 864e5;
|
|
1063
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
1064
|
+
const MAX_DATE_WINDOWS = 100;
|
|
1065
|
+
function dayNumber(value) {
|
|
1066
|
+
if (!ISO_DAY.test(value)) return null;
|
|
1067
|
+
const timestamp = Date.parse(`${value}T00:00:00Z`);
|
|
1068
|
+
if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) return null;
|
|
1069
|
+
return timestamp / DAY_MS;
|
|
1070
|
+
}
|
|
1071
|
+
function isoDay$1(day) {
|
|
1072
|
+
return (/* @__PURE__ */ new Date(day * DAY_MS)).toISOString().slice(0, 10);
|
|
1073
|
+
}
|
|
1074
|
+
/** Number of calendar days in an inclusive ISO-date range, or null for an invalid range. */
|
|
1075
|
+
function dateSpanDays(start, end) {
|
|
1076
|
+
const first = dayNumber(start);
|
|
1077
|
+
const last = dayNumber(end);
|
|
1078
|
+
return first === null || last === null || first > last ? null : last - first + 1;
|
|
1079
|
+
}
|
|
1080
|
+
/** Split an inclusive ISO-date range into at most 100 ordered, non-overlapping windows. */
|
|
1081
|
+
function splitDateRange(start, end, maxDays) {
|
|
1082
|
+
const first = dayNumber(start);
|
|
1083
|
+
const last = dayNumber(end);
|
|
1084
|
+
if (first === null || last === null || first > last) return null;
|
|
1085
|
+
if (!Number.isSafeInteger(maxDays) || maxDays < 1) throw new RangeError("maxDays must be a positive integer.");
|
|
1086
|
+
if (Math.ceil((last - first + 1) / maxDays) > MAX_DATE_WINDOWS) throw new RangeError(`Date range is limited to ${MAX_DATE_WINDOWS} windows; narrow the range or increase the window size.`);
|
|
1087
|
+
const windows = [];
|
|
1088
|
+
for (let cursor = first; cursor <= last; cursor += maxDays) windows.push({
|
|
1089
|
+
start: isoDay$1(cursor),
|
|
1090
|
+
end: isoDay$1(Math.min(cursor + maxDays - 1, last))
|
|
1091
|
+
});
|
|
1092
|
+
return windows;
|
|
1093
|
+
}
|
|
1094
|
+
//#endregion
|
|
1035
1095
|
//#region ../js/src/http-error.ts
|
|
1036
1096
|
const MAX_REQUEST_KEYS = 50;
|
|
1037
1097
|
const MAX_RESPONSE_DEPTH = 4;
|
|
1038
1098
|
const MAX_RESPONSE_KEYS = 20;
|
|
1039
1099
|
const MAX_RESPONSE_ITEMS = 10;
|
|
1040
1100
|
const MAX_RESPONSE_NODES = 50;
|
|
1101
|
+
const MAX_RESPONSE_STRING = 2e3;
|
|
1041
1102
|
const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
|
|
1042
1103
|
"code",
|
|
1043
1104
|
"detail",
|
|
@@ -1075,6 +1136,11 @@ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
|
|
|
1075
1136
|
14,
|
|
1076
1137
|
18
|
|
1077
1138
|
]);
|
|
1139
|
+
/** Keep provider diagnostics useful while removing common credentials and direct identifiers. */
|
|
1140
|
+
function redactText(value) {
|
|
1141
|
+
const redacted = value.slice(0, MAX_RESPONSE_STRING).replace(/\bAuthorization(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&]+)/giu, (_match, separator) => `Authorization${separator}[Redacted]`).replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/giu, "Bearer [Redacted]").replace(/\b(password|passwd|secret|token|access[_-]?token|refresh[_-]?token|session(?:[_-]?(?:id|token))?|api[_-]?key|client[_-]?secret)(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&}\]]+)/giu, (_match, key, separator) => `${key}${separator}[Redacted]`).replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu, "[Redacted email]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/gu, "[Redacted IP]").replace(/\b\d{3}-\d{2}-\d{4}\b/gu, "[Redacted]").replace(/\b(?:bearer\s+)?[a-f0-9]{32,}\b/giu, "[Redacted]");
|
|
1142
|
+
return value.length <= MAX_RESPONSE_STRING ? redacted : `${redacted}…[truncated]`;
|
|
1143
|
+
}
|
|
1078
1144
|
function safeFieldName(key) {
|
|
1079
1145
|
if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
|
|
1080
1146
|
if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
|
|
@@ -1102,17 +1168,22 @@ function requestBodySummary(body) {
|
|
|
1102
1168
|
const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
|
|
1103
1169
|
const keys = entries.map(([key]) => safeFieldName(key));
|
|
1104
1170
|
const values = {};
|
|
1171
|
+
const arrayLengths = {};
|
|
1105
1172
|
for (const [key, value] of entries) {
|
|
1106
1173
|
const safeValue = safeRequestValue(key, value);
|
|
1107
1174
|
if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
|
|
1175
|
+
if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
|
|
1108
1176
|
}
|
|
1109
|
-
|
|
1177
|
+
const byKey = new Map(entries);
|
|
1178
|
+
const dateStart = byKey.get("date_start");
|
|
1179
|
+
const dateEnd = byKey.get("date_end");
|
|
1180
|
+
const span = typeof dateStart === "string" && typeof dateEnd === "string" ? dateSpanDays(dateStart, dateEnd) : null;
|
|
1181
|
+
return {
|
|
1110
1182
|
type: "object",
|
|
1111
1183
|
keys,
|
|
1112
|
-
values
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
keys
|
|
1184
|
+
...Object.keys(values).length > 0 ? { values } : {},
|
|
1185
|
+
...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
|
|
1186
|
+
...span === null ? {} : { dateSpanDays: span }
|
|
1116
1187
|
};
|
|
1117
1188
|
}
|
|
1118
1189
|
const primitive = typeof body;
|
|
@@ -1124,7 +1195,7 @@ function sanitizedDiagnosticValue(value, depth, budget, field) {
|
|
|
1124
1195
|
if (value === null) return null;
|
|
1125
1196
|
if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
|
|
1126
1197
|
if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
|
|
1127
|
-
if (typeof value === "string") return
|
|
1198
|
+
if (typeof value === "string") return redactText(value);
|
|
1128
1199
|
if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
|
|
1129
1200
|
if (Array.isArray(value)) {
|
|
1130
1201
|
const result = [];
|
|
@@ -1203,6 +1274,12 @@ function safeResponseBodyDiagnostics(body) {
|
|
|
1203
1274
|
return "[Unavailable]";
|
|
1204
1275
|
}
|
|
1205
1276
|
}
|
|
1277
|
+
/** Format a bounded provider diagnostic for an in-band tool or SDK error. */
|
|
1278
|
+
function trainHeroicApiErrorMessage(label, status, responseBody) {
|
|
1279
|
+
const diagnostic = safeResponseBodyDiagnostics(responseBody);
|
|
1280
|
+
const detail = diagnostic && typeof diagnostic === "object" && !Array.isArray(diagnostic) ? typeof diagnostic.message === "string" ? diagnostic.message : JSON.stringify(diagnostic) : typeof diagnostic === "string" ? diagnostic : JSON.stringify(diagnostic);
|
|
1281
|
+
return detail && detail !== "{\"type\":\"object\"}" ? `${label} failed (HTTP ${status}): ${detail}` : `${label} failed (HTTP ${status}).`;
|
|
1282
|
+
}
|
|
1206
1283
|
/** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
|
|
1207
1284
|
var TrainHeroicHttpError = class extends Error {
|
|
1208
1285
|
name = "TrainHeroicHttpError";
|
|
@@ -1230,6 +1307,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
|
|
|
1230
1307
|
} catch {}
|
|
1231
1308
|
}
|
|
1232
1309
|
//#endregion
|
|
1310
|
+
//#region ../js/src/transport.ts
|
|
1311
|
+
const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
|
|
1312
|
+
//#endregion
|
|
1233
1313
|
//#region ../js/src/auth.ts
|
|
1234
1314
|
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
1235
1315
|
/**
|
|
@@ -1253,7 +1333,7 @@ function authUrl() {
|
|
|
1253
1333
|
*/
|
|
1254
1334
|
async function loginTrainHeroic(email, password, options = {}) {
|
|
1255
1335
|
const url = authUrl();
|
|
1256
|
-
const res = await
|
|
1336
|
+
const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
|
|
1257
1337
|
method: "POST",
|
|
1258
1338
|
headers: {
|
|
1259
1339
|
"content-type": "application/x-www-form-urlencoded",
|
|
@@ -1265,6 +1345,7 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
1265
1345
|
}).toString()
|
|
1266
1346
|
});
|
|
1267
1347
|
if (!res.ok) {
|
|
1348
|
+
await res.body?.cancel().catch(() => {});
|
|
1268
1349
|
notifyHttpError(options.onHttpError, "POST", url, res.status);
|
|
1269
1350
|
return null;
|
|
1270
1351
|
}
|
|
@@ -1278,127 +1359,40 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
1278
1359
|
};
|
|
1279
1360
|
}
|
|
1280
1361
|
//#endregion
|
|
1281
|
-
//#region
|
|
1282
|
-
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
1283
|
-
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
1362
|
+
//#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
|
|
1284
1363
|
/**
|
|
1285
|
-
*
|
|
1286
|
-
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
1287
|
-
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
1288
|
-
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
1289
|
-
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
1290
|
-
*/
|
|
1291
|
-
function envBase(key, fallback) {
|
|
1292
|
-
const v = (globalThis.process?.env)?.[key];
|
|
1293
|
-
return v && v.length > 0 ? v : fallback;
|
|
1294
|
-
}
|
|
1295
|
-
var TrainHeroicAuthError = class extends Error {
|
|
1296
|
-
name = "TrainHeroicAuthError";
|
|
1297
|
-
};
|
|
1298
|
-
/**
|
|
1299
|
-
* Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
|
|
1300
|
-
* grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
|
|
1301
|
-
* *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
|
|
1302
|
-
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
1364
|
+
* Splits an array into smaller arrays of a specified length.
|
|
1303
1365
|
*
|
|
1304
|
-
*
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
1307
|
-
*
|
|
1366
|
+
* This function takes an input array and divides it into multiple smaller arrays,
|
|
1367
|
+
* each of a specified length. If the input array cannot be evenly divided,
|
|
1368
|
+
* the final sub-array will contain the remaining elements.
|
|
1369
|
+
*
|
|
1370
|
+
* @template T The type of elements in the array.
|
|
1371
|
+
* @param arr - The array to be chunked into smaller arrays.
|
|
1372
|
+
* @param size - The size of each smaller array. Must be a positive integer.
|
|
1373
|
+
* @returns A two-dimensional array where each sub-array has a maximum length of `size`.
|
|
1374
|
+
* @throws {Error} Throws an error if `size` is not a positive integer.
|
|
1375
|
+
*
|
|
1376
|
+
* @example
|
|
1377
|
+
* // Splits an array of numbers into sub-arrays of length 2
|
|
1378
|
+
* chunk([1, 2, 3, 4, 5], 2);
|
|
1379
|
+
* // Returns: [[1, 2], [3, 4], [5]]
|
|
1380
|
+
*
|
|
1381
|
+
* @example
|
|
1382
|
+
* // Splits an array of strings into sub-arrays of length 3
|
|
1383
|
+
* chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
|
|
1384
|
+
* // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
|
|
1308
1385
|
*/
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
this.#email = email;
|
|
1318
|
-
this.#password = password;
|
|
1319
|
-
this.#sessionId = sessionId;
|
|
1320
|
-
this.#onSession = options.onSession;
|
|
1321
|
-
this.#onHttpError = options.onHttpError;
|
|
1322
|
-
}
|
|
1323
|
-
get sessionId() {
|
|
1324
|
-
return this.#sessionId;
|
|
1325
|
-
}
|
|
1326
|
-
async #ensureSession() {
|
|
1327
|
-
if (this.#sessionId) return this.#sessionId;
|
|
1328
|
-
this.#loginInFlight ??= this.#login();
|
|
1329
|
-
try {
|
|
1330
|
-
return await this.#loginInFlight;
|
|
1331
|
-
} finally {
|
|
1332
|
-
this.#loginInFlight = null;
|
|
1333
|
-
}
|
|
1386
|
+
function chunk(arr, size) {
|
|
1387
|
+
if (!Number.isInteger(size) || size <= 0) throw new Error("Size must be an integer greater than zero.");
|
|
1388
|
+
const chunkLength = Math.ceil(arr.length / size);
|
|
1389
|
+
const result = Array(chunkLength);
|
|
1390
|
+
for (let index = 0; index < chunkLength; index++) {
|
|
1391
|
+
const start = index * size;
|
|
1392
|
+
const end = start + size;
|
|
1393
|
+
result[index] = arr.slice(start, end);
|
|
1334
1394
|
}
|
|
1335
|
-
|
|
1336
|
-
const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
|
|
1337
|
-
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
1338
|
-
this.#sessionId = session.sessionId;
|
|
1339
|
-
try {
|
|
1340
|
-
this.#onSession?.(this.#sessionId);
|
|
1341
|
-
} catch {}
|
|
1342
|
-
return this.#sessionId;
|
|
1343
|
-
}
|
|
1344
|
-
async request(method, path, options = {}) {
|
|
1345
|
-
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
1346
|
-
let session = await this.#ensureSession();
|
|
1347
|
-
let res = await this.#send(method, url, session, options.body);
|
|
1348
|
-
if (res.status === 401 || res.status === 403) {
|
|
1349
|
-
if (this.#sessionId === session) this.#sessionId = null;
|
|
1350
|
-
session = await this.#ensureSession();
|
|
1351
|
-
res = await this.#send(method, url, session, options.body);
|
|
1352
|
-
}
|
|
1353
|
-
const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
|
|
1354
|
-
let text;
|
|
1355
|
-
try {
|
|
1356
|
-
text = await res.text();
|
|
1357
|
-
} catch (error) {
|
|
1358
|
-
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
|
|
1359
|
-
throw error;
|
|
1360
|
-
}
|
|
1361
|
-
const data = parseResponseText(text);
|
|
1362
|
-
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
|
|
1363
|
-
requestBody: options.body,
|
|
1364
|
-
responseBody: data
|
|
1365
|
-
});
|
|
1366
|
-
return {
|
|
1367
|
-
status: res.status,
|
|
1368
|
-
ok: res.ok,
|
|
1369
|
-
data
|
|
1370
|
-
};
|
|
1371
|
-
}
|
|
1372
|
-
#send(method, url, session, body) {
|
|
1373
|
-
const upper = method.toUpperCase();
|
|
1374
|
-
const headers = {
|
|
1375
|
-
accept: "application/json",
|
|
1376
|
-
"session-token": session
|
|
1377
|
-
};
|
|
1378
|
-
const init = {
|
|
1379
|
-
method: upper,
|
|
1380
|
-
headers
|
|
1381
|
-
};
|
|
1382
|
-
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
1383
|
-
headers["content-type"] = "application/json";
|
|
1384
|
-
init.body = JSON.stringify(body);
|
|
1385
|
-
}
|
|
1386
|
-
return fetch(url, init);
|
|
1387
|
-
}
|
|
1388
|
-
};
|
|
1389
|
-
//#endregion
|
|
1390
|
-
//#region ../js/src/response-check.ts
|
|
1391
|
-
/**
|
|
1392
|
-
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
1393
|
-
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
1394
|
-
* when TrainHeroic renames or drops a field we read.
|
|
1395
|
-
*/
|
|
1396
|
-
function checkResponse(schema, data, label) {
|
|
1397
|
-
const result = schema.safeParse(data);
|
|
1398
|
-
if (result.success) return;
|
|
1399
|
-
const issue = result.error.issues[0];
|
|
1400
|
-
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
1401
|
-
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
1395
|
+
return result;
|
|
1402
1396
|
}
|
|
1403
1397
|
//#endregion
|
|
1404
1398
|
//#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
|
|
@@ -1657,6 +1651,141 @@ function assertPositiveInteger(value, label) {
|
|
|
1657
1651
|
if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
|
|
1658
1652
|
}
|
|
1659
1653
|
//#endregion
|
|
1654
|
+
//#region ../js/src/client.ts
|
|
1655
|
+
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
1656
|
+
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
1657
|
+
const MAX_REQUEST_CONCURRENCY = 4;
|
|
1658
|
+
/**
|
|
1659
|
+
* Resolve an API host, allowing an env override. The override exists so a test harness can point
|
|
1660
|
+
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
1661
|
+
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
1662
|
+
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
1663
|
+
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
1664
|
+
*/
|
|
1665
|
+
function envBase(key, fallback) {
|
|
1666
|
+
const v = (globalThis.process?.env)?.[key];
|
|
1667
|
+
return v && v.length > 0 ? v : fallback;
|
|
1668
|
+
}
|
|
1669
|
+
var TrainHeroicAuthError = class extends Error {
|
|
1670
|
+
name = "TrainHeroicAuthError";
|
|
1671
|
+
};
|
|
1672
|
+
/**
|
|
1673
|
+
* Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
|
|
1674
|
+
* grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
|
|
1675
|
+
* *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
|
|
1676
|
+
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
1677
|
+
*
|
|
1678
|
+
* Anything that wants a session to outlive one client owns that itself: pass a previously
|
|
1679
|
+
* acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
|
|
1680
|
+
* wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
|
|
1681
|
+
* invocation is a fresh process — because otherwise every operation replays the password.
|
|
1682
|
+
*/
|
|
1683
|
+
var TrainHeroicClient = class {
|
|
1684
|
+
#email;
|
|
1685
|
+
#password;
|
|
1686
|
+
#onSession;
|
|
1687
|
+
#onHttpError;
|
|
1688
|
+
#transport;
|
|
1689
|
+
#requestLimit = createLimiter(MAX_REQUEST_CONCURRENCY);
|
|
1690
|
+
#sessionId;
|
|
1691
|
+
#loginInFlight = null;
|
|
1692
|
+
constructor(email, password, sessionId = null, options = {}) {
|
|
1693
|
+
this.#email = email;
|
|
1694
|
+
this.#password = password;
|
|
1695
|
+
this.#sessionId = sessionId;
|
|
1696
|
+
this.#onSession = options.onSession;
|
|
1697
|
+
this.#onHttpError = options.onHttpError;
|
|
1698
|
+
this.#transport = options.transport ?? defaultTrainHeroicTransport;
|
|
1699
|
+
}
|
|
1700
|
+
get sessionId() {
|
|
1701
|
+
return this.#sessionId;
|
|
1702
|
+
}
|
|
1703
|
+
async #ensureSession() {
|
|
1704
|
+
if (this.#sessionId) return this.#sessionId;
|
|
1705
|
+
this.#loginInFlight ??= this.#login();
|
|
1706
|
+
try {
|
|
1707
|
+
return await this.#loginInFlight;
|
|
1708
|
+
} finally {
|
|
1709
|
+
this.#loginInFlight = null;
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
async #login() {
|
|
1713
|
+
const session = await loginTrainHeroic(this.#email, this.#password, {
|
|
1714
|
+
...this.#onHttpError ? { onHttpError: this.#onHttpError } : {},
|
|
1715
|
+
transport: this.#transport
|
|
1716
|
+
});
|
|
1717
|
+
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
1718
|
+
this.#sessionId = session.sessionId;
|
|
1719
|
+
try {
|
|
1720
|
+
this.#onSession?.(this.#sessionId);
|
|
1721
|
+
} catch {}
|
|
1722
|
+
return this.#sessionId;
|
|
1723
|
+
}
|
|
1724
|
+
async request(method, path, options = {}) {
|
|
1725
|
+
await this.#ensureSession();
|
|
1726
|
+
return this.#requestLimit.run(() => this.#request(method, path, options));
|
|
1727
|
+
}
|
|
1728
|
+
async #request(method, path, options) {
|
|
1729
|
+
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
1730
|
+
let session = await this.#ensureSession();
|
|
1731
|
+
let res = await this.#send(method, url, session, options.body);
|
|
1732
|
+
if (res.status === 401 || res.status === 403) {
|
|
1733
|
+
await res.body?.cancel().catch(() => {});
|
|
1734
|
+
if (this.#sessionId === session) this.#sessionId = null;
|
|
1735
|
+
session = await this.#ensureSession();
|
|
1736
|
+
res = await this.#send(method, url, session, options.body);
|
|
1737
|
+
}
|
|
1738
|
+
const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
|
|
1739
|
+
let text;
|
|
1740
|
+
try {
|
|
1741
|
+
text = await res.text();
|
|
1742
|
+
} catch (error) {
|
|
1743
|
+
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
|
|
1744
|
+
throw error;
|
|
1745
|
+
}
|
|
1746
|
+
const data = parseResponseText(text);
|
|
1747
|
+
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
|
|
1748
|
+
requestBody: options.body,
|
|
1749
|
+
responseBody: data
|
|
1750
|
+
});
|
|
1751
|
+
return {
|
|
1752
|
+
status: res.status,
|
|
1753
|
+
ok: res.ok,
|
|
1754
|
+
data
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
#send(method, url, session, body) {
|
|
1758
|
+
const upper = method.toUpperCase();
|
|
1759
|
+
const headers = {
|
|
1760
|
+
accept: "application/json",
|
|
1761
|
+
"session-token": session
|
|
1762
|
+
};
|
|
1763
|
+
const init = {
|
|
1764
|
+
method: upper,
|
|
1765
|
+
headers
|
|
1766
|
+
};
|
|
1767
|
+
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
1768
|
+
headers["content-type"] = "application/json";
|
|
1769
|
+
init.body = JSON.stringify(body);
|
|
1770
|
+
}
|
|
1771
|
+
return this.#transport(url, init);
|
|
1772
|
+
}
|
|
1773
|
+
};
|
|
1774
|
+
//#endregion
|
|
1775
|
+
//#region ../js/src/response-check.ts
|
|
1776
|
+
/**
|
|
1777
|
+
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
1778
|
+
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
1779
|
+
* when TrainHeroic renames or drops a field we read.
|
|
1780
|
+
*/
|
|
1781
|
+
function checkResponse(schema, data, label) {
|
|
1782
|
+
const result = schema.safeParse(data);
|
|
1783
|
+
if (result.success) return;
|
|
1784
|
+
const issue = result.error.issues[0];
|
|
1785
|
+
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
1786
|
+
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
1787
|
+
}
|
|
1788
|
+
//#endregion
|
|
1660
1789
|
//#region ../js/src/athlete.ts
|
|
1661
1790
|
async function getJson(client, path, label) {
|
|
1662
1791
|
const res = await client.request("GET", path);
|
|
@@ -3341,12 +3470,15 @@ const ANALYTICS_BODY_KEY = {
|
|
|
3341
3470
|
exerciseId: "exercise_id",
|
|
3342
3471
|
useMetric: "use_metric"
|
|
3343
3472
|
};
|
|
3473
|
+
const TRAINING_SUMMARY_USER_BATCH = 5;
|
|
3474
|
+
const TRAINING_SUMMARY_RANGE_DAYS = 90;
|
|
3475
|
+
const MAX_TRAINING_SUMMARY_REQUESTS = 100;
|
|
3344
3476
|
/**
|
|
3345
3477
|
* Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
|
|
3346
3478
|
* athlete metrics need one or more `userIds` (passed together — the report returns a row per
|
|
3347
3479
|
* athlete). Throws a readable Error when a required input is missing or the call fails.
|
|
3348
3480
|
*/
|
|
3349
|
-
async function
|
|
3481
|
+
async function requestAnalytics(client, args) {
|
|
3350
3482
|
const spec = ANALYTICS_METRICS[args.metric];
|
|
3351
3483
|
const body = {};
|
|
3352
3484
|
if (spec.scope === "team") {
|
|
@@ -3374,6 +3506,42 @@ async function queryAnalytics(client, args) {
|
|
|
3374
3506
|
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
3375
3507
|
return res.data;
|
|
3376
3508
|
}
|
|
3509
|
+
function reportRows(report) {
|
|
3510
|
+
if (report === null || typeof report !== "object") return null;
|
|
3511
|
+
const rows = report.rows;
|
|
3512
|
+
return Array.isArray(rows) ? rows : null;
|
|
3513
|
+
}
|
|
3514
|
+
/**
|
|
3515
|
+
* Query one analytics metric. Large training-summary reads are serialized as small user/date
|
|
3516
|
+
* batches because that endpoint otherwise spends roughly a minute building one oversized report
|
|
3517
|
+
* before its gateway returns 504. Rejects plans above 100 total requests.
|
|
3518
|
+
*/
|
|
3519
|
+
async function queryAnalytics(client, args) {
|
|
3520
|
+
if (args.metric !== "training-summary-athlete" || args.userIds === void 0 || args.userIds.length === 0 || args.dateStart === void 0 || args.dateEnd === void 0) return requestAnalytics(client, args);
|
|
3521
|
+
const windows = splitDateRange(args.dateStart, args.dateEnd, TRAINING_SUMMARY_RANGE_DAYS);
|
|
3522
|
+
if (windows === null) return requestAnalytics(client, args);
|
|
3523
|
+
const uniqueUserIds = [...new Set(args.userIds)];
|
|
3524
|
+
if (Math.ceil(uniqueUserIds.length / TRAINING_SUMMARY_USER_BATCH) * windows.length > MAX_TRAINING_SUMMARY_REQUESTS) throw new RangeError(`Training summary is limited to ${MAX_TRAINING_SUMMARY_REQUESTS} batched requests; narrow the date range or pass fewer athletes.`);
|
|
3525
|
+
const requests = chunk(uniqueUserIds, TRAINING_SUMMARY_USER_BATCH).flatMap((userIds) => windows.map((window) => ({
|
|
3526
|
+
...args,
|
|
3527
|
+
userIds,
|
|
3528
|
+
dateStart: window.start,
|
|
3529
|
+
dateEnd: window.end
|
|
3530
|
+
})));
|
|
3531
|
+
if (requests.length === 1) return requestAnalytics(client, requests[0]);
|
|
3532
|
+
let merged = null;
|
|
3533
|
+
for (const request of requests) {
|
|
3534
|
+
const report = await requestAnalytics(client, request);
|
|
3535
|
+
const rows = reportRows(report);
|
|
3536
|
+
if (rows === null) throw new Error("Training summary returned an unexpected batched report shape.");
|
|
3537
|
+
if (merged === null) merged = {
|
|
3538
|
+
...report,
|
|
3539
|
+
rows: [...rows]
|
|
3540
|
+
};
|
|
3541
|
+
else merged.rows.push(...rows);
|
|
3542
|
+
}
|
|
3543
|
+
return merged;
|
|
3544
|
+
}
|
|
3377
3545
|
/**
|
|
3378
3546
|
* Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
|
|
3379
3547
|
* place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
|
|
@@ -3401,9 +3569,9 @@ function toNum(v) {
|
|
|
3401
3569
|
}
|
|
3402
3570
|
/**
|
|
3403
3571
|
* Team-wide training volume over an inclusive date window. The `training-summary-athlete`
|
|
3404
|
-
* analytics report
|
|
3405
|
-
*
|
|
3406
|
-
* volume/reps
|
|
3572
|
+
* analytics report returns one row per logged session across all `athleteIds`; `queryAnalytics`
|
|
3573
|
+
* splits oversized requests and merges those rows before this function groups them by athlete,
|
|
3574
|
+
* sums volume/reps, counts sessions, and rolls the athletes up into a team total. Athletes who
|
|
3407
3575
|
* logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
|
|
3408
3576
|
* all-time `fetchRosterActivity` snapshot, which has no date range.
|
|
3409
3577
|
*/
|
|
@@ -3527,6 +3695,7 @@ function classifyMainLift(title) {
|
|
|
3527
3695
|
return null;
|
|
3528
3696
|
}
|
|
3529
3697
|
const DEFAULT_MONTHS = 12;
|
|
3698
|
+
const WORKOUT_RANGE_DAYS = 180;
|
|
3530
3699
|
function pad2(n) {
|
|
3531
3700
|
return String(n).padStart(2, "0");
|
|
3532
3701
|
}
|
|
@@ -3544,12 +3713,18 @@ function isoDay(d) {
|
|
|
3544
3713
|
*/
|
|
3545
3714
|
async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
3546
3715
|
const months = opts.months ?? DEFAULT_MONTHS;
|
|
3716
|
+
if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
|
|
3547
3717
|
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
3548
|
-
const
|
|
3718
|
+
const startDay = isoDay(new Date(now.getFullYear(), now.getMonth() - (months - 1), 1));
|
|
3719
|
+
const endDay = isoDay(now);
|
|
3720
|
+
const windows = splitDateRange(startDay, endDay, WORKOUT_RANGE_DAYS) ?? [{
|
|
3721
|
+
start: startDay,
|
|
3722
|
+
end: endDay
|
|
3723
|
+
}];
|
|
3549
3724
|
const tally = /* @__PURE__ */ new Map();
|
|
3550
3725
|
let workouts = [];
|
|
3551
3726
|
try {
|
|
3552
|
-
|
|
3727
|
+
for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
|
|
3553
3728
|
} catch {
|
|
3554
3729
|
workouts = [];
|
|
3555
3730
|
}
|
|
@@ -3892,7 +4067,9 @@ var ExerciseLibrary = class {
|
|
|
3892
4067
|
};
|
|
3893
4068
|
}
|
|
3894
4069
|
async create(body) {
|
|
3895
|
-
|
|
4070
|
+
const requestBody = { ...body };
|
|
4071
|
+
if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
|
|
4072
|
+
return this.#writeThrough(CREATE_PATH, requestBody, "create");
|
|
3896
4073
|
}
|
|
3897
4074
|
async update(id, body) {
|
|
3898
4075
|
return this.#writeThrough(UPDATE_PATH(id), body, "update");
|
|
@@ -3900,7 +4077,7 @@ var ExerciseLibrary = class {
|
|
|
3900
4077
|
async #writeThrough(path, body, label) {
|
|
3901
4078
|
await this.ensureFresh();
|
|
3902
4079
|
const res = await this.#client.request("POST", path, { body });
|
|
3903
|
-
if (!res.ok) throw new Error(`Exercise ${label}
|
|
4080
|
+
if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
|
|
3904
4081
|
const ex = unwrapEnvelope(res.data);
|
|
3905
4082
|
if (ex && typeof ex === "object") {
|
|
3906
4083
|
checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
|
|
@@ -4607,10 +4784,10 @@ function registerAnalyticsTools(server, ctx) {
|
|
|
4607
4784
|
function registerExerciseUpdate(server, index) {
|
|
4608
4785
|
server.registerTool("exercise_update", {
|
|
4609
4786
|
title: "Update custom exercise",
|
|
4610
|
-
description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror.
|
|
4787
|
+
description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Uses the same writable fields as exercise_create; omitted fields are left unchanged. Only works for exercises with can_edit:1. Requires confirmation (elicitation, or confirm:true).",
|
|
4611
4788
|
inputSchema: {
|
|
4612
4789
|
id: idParam,
|
|
4613
|
-
exercise:
|
|
4790
|
+
exercise: exerciseUpdateSchema,
|
|
4614
4791
|
confirm: z.boolean().optional()
|
|
4615
4792
|
},
|
|
4616
4793
|
outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
|
|
@@ -4690,7 +4867,7 @@ function registerExerciseTools(server, ctx) {
|
|
|
4690
4867
|
registerExerciseReads(server, index);
|
|
4691
4868
|
server.registerTool("exercise_create", {
|
|
4692
4869
|
title: "Create custom exercise",
|
|
4693
|
-
description: "Create a custom exercise (POST /2.0/coach/exercise/create) and write it through to the mirror. Body example: {\"title\":\"Sandbag Clean\",\"param_1_type\":3,\"param_2_type\":1}.",
|
|
4870
|
+
description: "Create a custom exercise (POST /2.0/coach/exercise/create) and write it through to the mirror. Body example: {\"title\":\"Sandbag Clean\",\"param_1_type\":3,\"param_2_type\":1}. The server supplies an empty points_of_performance value when it is omitted.",
|
|
4694
4871
|
inputSchema: { exercise: exerciseCreateSchema },
|
|
4695
4872
|
outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
|
|
4696
4873
|
annotations: ADDITIVE
|
|
@@ -5028,7 +5205,7 @@ var JsonFileLibraryCache = class {
|
|
|
5028
5205
|
};
|
|
5029
5206
|
//#endregion
|
|
5030
5207
|
//#region package.json
|
|
5031
|
-
var version = "3.
|
|
5208
|
+
var version = "3.7.1";
|
|
5032
5209
|
//#endregion
|
|
5033
5210
|
//#region src/server.ts
|
|
5034
5211
|
function main() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/coach-mcp",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -20,14 +20,14 @@
|
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
22
|
"@modelcontextprotocol/server": "2.0.0",
|
|
23
|
-
"zod": "^4.
|
|
24
|
-
"@trainheroic-unofficial/core": "3.
|
|
25
|
-
"@trainheroic-unofficial/js": "3.
|
|
23
|
+
"zod": "^4.6.3",
|
|
24
|
+
"@trainheroic-unofficial/core": "3.7.1",
|
|
25
|
+
"@trainheroic-unofficial/js": "3.7.1"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@types/node": "^26.
|
|
29
|
-
"tsdown": "^0.
|
|
30
|
-
"tsx": "^4.23.
|
|
28
|
+
"@types/node": "^26.5.1",
|
|
29
|
+
"tsdown": "^0.23.0",
|
|
30
|
+
"tsx": "^4.23.13",
|
|
31
31
|
"typescript": "^7.0.2",
|
|
32
32
|
"vitest": "^4.1.11"
|
|
33
33
|
},
|