@trainheroic-unofficial/coach-mcp 3.5.2 → 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.
Files changed (2) hide show
  1. package/dist/server.mjs +488 -136
  2. 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
- title: z.string().min(1),
420
- param_1_type: z.number().optional(),
421
- param_2_type: z.number().optional()
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,34 +1058,258 @@ 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
- /**
1037
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
1038
- * metadata that is safe to send to telemetry: never the path, query string, request body,
1039
- * response body, credentials, or session token.
1040
- */
1096
+ const MAX_REQUEST_KEYS = 50;
1097
+ const MAX_RESPONSE_DEPTH = 4;
1098
+ const MAX_RESPONSE_KEYS = 20;
1099
+ const MAX_RESPONSE_ITEMS = 10;
1100
+ const MAX_RESPONSE_NODES = 50;
1101
+ const MAX_RESPONSE_STRING = 2e3;
1102
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
1103
+ "code",
1104
+ "detail",
1105
+ "details",
1106
+ "error",
1107
+ "error_code",
1108
+ "errors",
1109
+ "message",
1110
+ "reason",
1111
+ "status",
1112
+ "status_code",
1113
+ "success"
1114
+ ]);
1115
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
1116
+ "data",
1117
+ "received",
1118
+ "response",
1119
+ "result"
1120
+ ]);
1121
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
1122
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
1123
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
1124
+ 0,
1125
+ 1,
1126
+ 2,
1127
+ 3,
1128
+ 4,
1129
+ 5,
1130
+ 6,
1131
+ 7,
1132
+ 10,
1133
+ 11,
1134
+ 12,
1135
+ 13,
1136
+ 14,
1137
+ 18
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
+ }
1144
+ function safeFieldName(key) {
1145
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
1146
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
1147
+ return key;
1148
+ }
1149
+ function boundedEntries(object, limit) {
1150
+ const entries = [];
1151
+ for (const key of Object.keys(object)) {
1152
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
1153
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
1154
+ if (entries.length >= limit) break;
1155
+ }
1156
+ return entries;
1157
+ }
1158
+ function safeRequestValue(key, value) {
1159
+ if (key === "is_circuit" && typeof value === "boolean") return value;
1160
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
1161
+ }
1162
+ function requestBodySummary(body) {
1163
+ if (Array.isArray(body)) return {
1164
+ type: "array",
1165
+ length: body.length
1166
+ };
1167
+ if (body && typeof body === "object") {
1168
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
1169
+ const keys = entries.map(([key]) => safeFieldName(key));
1170
+ const values = {};
1171
+ const arrayLengths = {};
1172
+ for (const [key, value] of entries) {
1173
+ const safeValue = safeRequestValue(key, value);
1174
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
1175
+ if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
1176
+ }
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 {
1182
+ type: "object",
1183
+ keys,
1184
+ ...Object.keys(values).length > 0 ? { values } : {},
1185
+ ...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
1186
+ ...span === null ? {} : { dateSpanDays: span }
1187
+ };
1188
+ }
1189
+ const primitive = typeof body;
1190
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
1191
+ }
1192
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
1193
+ if (budget.nodes <= 0) return "[Truncated]";
1194
+ budget.nodes -= 1;
1195
+ if (value === null) return null;
1196
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
1197
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
1198
+ if (typeof value === "string") return redactText(value);
1199
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
1200
+ if (Array.isArray(value)) {
1201
+ const result = [];
1202
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
1203
+ if (budget.nodes <= 0) {
1204
+ result.push("[Truncated]");
1205
+ break;
1206
+ }
1207
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
1208
+ }
1209
+ return result;
1210
+ }
1211
+ if (value && typeof value === "object") {
1212
+ const result = {};
1213
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
1214
+ if (budget.nodes <= 0) {
1215
+ result.truncated = "[Truncated]";
1216
+ break;
1217
+ }
1218
+ const safeKey = safeFieldName(key);
1219
+ const safeValue = safeRequestValue(key, item);
1220
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
1221
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
1222
+ else if (safeValue !== void 0) {
1223
+ budget.nodes -= 1;
1224
+ result[safeKey] = safeValue;
1225
+ }
1226
+ }
1227
+ return result;
1228
+ }
1229
+ return `[${typeof value}]`;
1230
+ }
1231
+ function responseBodyDiagnostics(body, budget, depth = 0) {
1232
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
1233
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
1234
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
1235
+ const object = body;
1236
+ const result = {};
1237
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
1238
+ if (activeBudget.nodes <= 0) {
1239
+ result.truncated = "[Truncated]";
1240
+ break;
1241
+ }
1242
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
1243
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
1244
+ continue;
1245
+ }
1246
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
1247
+ activeBudget.nodes -= 1;
1248
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
1249
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
1250
+ }
1251
+ }
1252
+ if (Object.keys(result).length > 0) return result;
1253
+ return { type: "object" };
1254
+ }
1255
+ function parseResponseText(text) {
1256
+ if (text.length === 0) return text;
1257
+ try {
1258
+ return JSON.parse(text);
1259
+ } catch {
1260
+ return text;
1261
+ }
1262
+ }
1263
+ function safeRequestBodySummary(body) {
1264
+ try {
1265
+ return requestBodySummary(body);
1266
+ } catch {
1267
+ return { type: "other" };
1268
+ }
1269
+ }
1270
+ function safeResponseBodyDiagnostics(body) {
1271
+ try {
1272
+ return responseBodyDiagnostics(body);
1273
+ } catch {
1274
+ return "[Unavailable]";
1275
+ }
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
+ }
1283
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
1041
1284
  var TrainHeroicHttpError = class extends Error {
1042
1285
  name = "TrainHeroicHttpError";
1043
1286
  method;
1044
1287
  status;
1045
1288
  host;
1046
- constructor(method, url, status) {
1289
+ requestBody;
1290
+ responseBody;
1291
+ constructor(method, url, status, diagnostics = {}) {
1047
1292
  const parsed = new URL(url);
1048
1293
  const normalizedMethod = method.toUpperCase();
1049
1294
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
1050
1295
  this.method = normalizedMethod;
1051
1296
  this.status = status;
1052
1297
  this.host = parsed.host;
1298
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
1299
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
1053
1300
  }
1054
1301
  };
1055
1302
  /** Call observability hooks without allowing them to change SDK behavior. */
1056
- function notifyHttpError(handler, method, url, status) {
1303
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1057
1304
  if (!handler) return;
1058
1305
  try {
1059
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
1306
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1060
1307
  } catch {}
1061
1308
  }
1062
1309
  //#endregion
1310
+ //#region ../js/src/transport.ts
1311
+ const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1312
+ //#endregion
1063
1313
  //#region ../js/src/auth.ts
1064
1314
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1065
1315
  /**
@@ -1083,7 +1333,7 @@ function authUrl() {
1083
1333
  */
1084
1334
  async function loginTrainHeroic(email, password, options = {}) {
1085
1335
  const url = authUrl();
1086
- const res = await fetch(url, {
1336
+ const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
1087
1337
  method: "POST",
1088
1338
  headers: {
1089
1339
  "content-type": "application/x-www-form-urlencoded",
@@ -1095,6 +1345,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1095
1345
  }).toString()
1096
1346
  });
1097
1347
  if (!res.ok) {
1348
+ await res.body?.cancel().catch(() => {});
1098
1349
  notifyHttpError(options.onHttpError, "POST", url, res.status);
1099
1350
  return null;
1100
1351
  }
@@ -1108,122 +1359,40 @@ async function loginTrainHeroic(email, password, options = {}) {
1108
1359
  };
1109
1360
  }
1110
1361
  //#endregion
1111
- //#region ../js/src/client.ts
1112
- const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1113
- const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1114
- /**
1115
- * Resolve an API host, allowing an env override. The override exists so a test harness can point
1116
- * the client at a local fake backend (and it doubles as a staging knob); production leaves these
1117
- * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
1118
- * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
1119
- * read per request (not at module load) so a value the harness sets in the child env always wins.
1120
- */
1121
- function envBase(key, fallback) {
1122
- const v = (globalThis.process?.env)?.[key];
1123
- return v && v.length > 0 ? v : fallback;
1124
- }
1125
- var TrainHeroicAuthError = class extends Error {
1126
- name = "TrainHeroicAuthError";
1127
- };
1362
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
1128
1363
  /**
1129
- * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
1130
- * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
1131
- * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
1132
- * TrainHeroic has no refresh token and sessions expire after ~1-2h.
1364
+ * Splits an array into smaller arrays of a specified length.
1133
1365
  *
1134
- * Anything that wants a session to outlive one client owns that itself: pass a previously
1135
- * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
1136
- * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
1137
- * invocation is a fresh process — because otherwise every operation replays the password.
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']]
1138
1385
  */
1139
- var TrainHeroicClient = class {
1140
- #email;
1141
- #password;
1142
- #onSession;
1143
- #onHttpError;
1144
- #sessionId;
1145
- #loginInFlight = null;
1146
- constructor(email, password, sessionId = null, options = {}) {
1147
- this.#email = email;
1148
- this.#password = password;
1149
- this.#sessionId = sessionId;
1150
- this.#onSession = options.onSession;
1151
- this.#onHttpError = options.onHttpError;
1152
- }
1153
- get sessionId() {
1154
- return this.#sessionId;
1155
- }
1156
- async #ensureSession() {
1157
- if (this.#sessionId) return this.#sessionId;
1158
- this.#loginInFlight ??= this.#login();
1159
- try {
1160
- return await this.#loginInFlight;
1161
- } finally {
1162
- this.#loginInFlight = null;
1163
- }
1164
- }
1165
- async #login() {
1166
- const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
1167
- if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
1168
- this.#sessionId = session.sessionId;
1169
- try {
1170
- this.#onSession?.(this.#sessionId);
1171
- } catch {}
1172
- return this.#sessionId;
1173
- }
1174
- async request(method, path, options = {}) {
1175
- const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
1176
- let session = await this.#ensureSession();
1177
- let res = await this.#send(method, url, session, options.body);
1178
- if (res.status === 401 || res.status === 403) {
1179
- if (this.#sessionId === session) this.#sessionId = null;
1180
- session = await this.#ensureSession();
1181
- res = await this.#send(method, url, session, options.body);
1182
- }
1183
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
1184
- const text = await res.text();
1185
- let data = text;
1186
- if (text.length > 0) try {
1187
- data = JSON.parse(text);
1188
- } catch {
1189
- data = text;
1190
- }
1191
- return {
1192
- status: res.status,
1193
- ok: res.ok,
1194
- data
1195
- };
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);
1196
1394
  }
1197
- #send(method, url, session, body) {
1198
- const upper = method.toUpperCase();
1199
- const headers = {
1200
- accept: "application/json",
1201
- "session-token": session
1202
- };
1203
- const init = {
1204
- method: upper,
1205
- headers
1206
- };
1207
- if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
1208
- headers["content-type"] = "application/json";
1209
- init.body = JSON.stringify(body);
1210
- }
1211
- return fetch(url, init);
1212
- }
1213
- };
1214
- //#endregion
1215
- //#region ../js/src/response-check.ts
1216
- /**
1217
- * Validate an API response against its (loose) expected shape and warn once on drift.
1218
- * Never throws: callers keep working via defensive coercion. This only surfaces a signal
1219
- * when TrainHeroic renames or drops a field we read.
1220
- */
1221
- function checkResponse(schema, data, label) {
1222
- const result = schema.safeParse(data);
1223
- if (result.success) return;
1224
- const issue = result.error.issues[0];
1225
- const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1226
- console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1395
+ return result;
1227
1396
  }
1228
1397
  //#endregion
1229
1398
  //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
@@ -1482,6 +1651,141 @@ function assertPositiveInteger(value, label) {
1482
1651
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1483
1652
  }
1484
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
1485
1789
  //#region ../js/src/athlete.ts
1486
1790
  async function getJson(client, path, label) {
1487
1791
  const res = await client.request("GET", path);
@@ -3166,12 +3470,15 @@ const ANALYTICS_BODY_KEY = {
3166
3470
  exerciseId: "exercise_id",
3167
3471
  useMetric: "use_metric"
3168
3472
  };
3473
+ const TRAINING_SUMMARY_USER_BATCH = 5;
3474
+ const TRAINING_SUMMARY_RANGE_DAYS = 90;
3475
+ const MAX_TRAINING_SUMMARY_REQUESTS = 100;
3169
3476
  /**
3170
3477
  * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
3171
3478
  * athlete metrics need one or more `userIds` (passed together — the report returns a row per
3172
3479
  * athlete). Throws a readable Error when a required input is missing or the call fails.
3173
3480
  */
3174
- async function queryAnalytics(client, args) {
3481
+ async function requestAnalytics(client, args) {
3175
3482
  const spec = ANALYTICS_METRICS[args.metric];
3176
3483
  const body = {};
3177
3484
  if (spec.scope === "team") {
@@ -3199,6 +3506,42 @@ async function queryAnalytics(client, args) {
3199
3506
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3200
3507
  return res.data;
3201
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
+ }
3202
3545
  /**
3203
3546
  * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
3204
3547
  * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
@@ -3226,9 +3569,9 @@ function toNum(v) {
3226
3569
  }
3227
3570
  /**
3228
3571
  * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
3229
- * analytics report already returns the team in one call — one row per logged session across all
3230
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
3231
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
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
3232
3575
  * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
3233
3576
  * all-time `fetchRosterActivity` snapshot, which has no date range.
3234
3577
  */
@@ -3352,6 +3695,7 @@ function classifyMainLift(title) {
3352
3695
  return null;
3353
3696
  }
3354
3697
  const DEFAULT_MONTHS = 12;
3698
+ const WORKOUT_RANGE_DAYS = 180;
3355
3699
  function pad2(n) {
3356
3700
  return String(n).padStart(2, "0");
3357
3701
  }
@@ -3369,12 +3713,18 @@ function isoDay(d) {
3369
3713
  */
3370
3714
  async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3371
3715
  const months = opts.months ?? DEFAULT_MONTHS;
3716
+ if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
3372
3717
  const now = opts.now ?? /* @__PURE__ */ new Date();
3373
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
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
+ }];
3374
3724
  const tally = /* @__PURE__ */ new Map();
3375
3725
  let workouts = [];
3376
3726
  try {
3377
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
3727
+ for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
3378
3728
  } catch {
3379
3729
  workouts = [];
3380
3730
  }
@@ -3717,7 +4067,9 @@ var ExerciseLibrary = class {
3717
4067
  };
3718
4068
  }
3719
4069
  async create(body) {
3720
- return this.#writeThrough(CREATE_PATH, body, "create");
4070
+ const requestBody = { ...body };
4071
+ if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
4072
+ return this.#writeThrough(CREATE_PATH, requestBody, "create");
3721
4073
  }
3722
4074
  async update(id, body) {
3723
4075
  return this.#writeThrough(UPDATE_PATH(id), body, "update");
@@ -3725,7 +4077,7 @@ var ExerciseLibrary = class {
3725
4077
  async #writeThrough(path, body, label) {
3726
4078
  await this.ensureFresh();
3727
4079
  const res = await this.#client.request("POST", path, { body });
3728
- if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
4080
+ if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
3729
4081
  const ex = unwrapEnvelope(res.data);
3730
4082
  if (ex && typeof ex === "object") {
3731
4083
  checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
@@ -4432,10 +4784,10 @@ function registerAnalyticsTools(server, ctx) {
4432
4784
  function registerExerciseUpdate(server, index) {
4433
4785
  server.registerTool("exercise_update", {
4434
4786
  title: "Update custom exercise",
4435
- description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Same body as exercise_create. Only works for exercises with can_edit:1. Requires confirmation (elicitation, or confirm:true).",
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).",
4436
4788
  inputSchema: {
4437
4789
  id: idParam,
4438
- exercise: exerciseCreateSchema,
4790
+ exercise: exerciseUpdateSchema,
4439
4791
  confirm: z.boolean().optional()
4440
4792
  },
4441
4793
  outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
@@ -4515,7 +4867,7 @@ function registerExerciseTools(server, ctx) {
4515
4867
  registerExerciseReads(server, index);
4516
4868
  server.registerTool("exercise_create", {
4517
4869
  title: "Create custom exercise",
4518
- 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.",
4519
4871
  inputSchema: { exercise: exerciseCreateSchema },
4520
4872
  outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4521
4873
  annotations: ADDITIVE
@@ -4853,7 +5205,7 @@ var JsonFileLibraryCache = class {
4853
5205
  };
4854
5206
  //#endregion
4855
5207
  //#region package.json
4856
- var version = "3.5.2";
5208
+ var version = "3.7.1";
4857
5209
  //#endregion
4858
5210
  //#region src/server.ts
4859
5211
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.5.2",
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.4.3",
24
- "@trainheroic-unofficial/js": "3.5.2",
25
- "@trainheroic-unofficial/core": "3.5.2"
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.3.0",
29
- "tsdown": "^0.22.14",
30
- "tsx": "^4.23.12",
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
  },