@trainheroic-unofficial/core 0.6.0 → 0.6.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/README.md +1 -1
- package/dist/index.mjs +75 -24
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ because they depend on its storage.
|
|
|
89
89
|
|
|
90
90
|
## Develop
|
|
91
91
|
|
|
92
|
-
Run `pnpm install` once at the repo root (Node >=
|
|
92
|
+
Run `pnpm install` once at the repo root (Node >= 24, pnpm 11), then from this package:
|
|
93
93
|
|
|
94
94
|
```bash
|
|
95
95
|
pnpm build # tsdown
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { blockSpecSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSetArgsSchema, parseWorkoutDate } from "@trainheroic-unofficial/dto";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, isRecord, logAthleteSet, presentAthleteWorkouts, presentExerciseHistory, publishSession, readLive, readSession, removeSession, searchExerciseHistory, sendComment } from "@trainheroic-unofficial/js";
|
|
3
|
+
import { addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, isRecord, logAthleteSet, presentAthleteWorkouts, presentExerciseHistory, publishSession, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment } from "@trainheroic-unofficial/js";
|
|
4
4
|
//#region src/context.ts
|
|
5
5
|
/** A tool argument that accepts a numeric id as a number or a string of digits. */
|
|
6
6
|
const idParam = idArgSchema;
|
|
@@ -199,7 +199,29 @@ async function confirmGate(server, requestId, message, confirmArg) {
|
|
|
199
199
|
*/
|
|
200
200
|
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.";
|
|
201
201
|
//#endregion
|
|
202
|
+
//#region src/history.ts
|
|
203
|
+
/**
|
|
204
|
+
* Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
|
|
205
|
+
* The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
|
|
206
|
+
* first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. Shared by
|
|
207
|
+
* the athlete's own history tool and the coach's per-roster-athlete history tool.
|
|
208
|
+
*/
|
|
209
|
+
function historyInRange(presented, since, until) {
|
|
210
|
+
if (since === void 0 && until === void 0) return presented;
|
|
211
|
+
const sessions = presented.sessions.filter((s) => {
|
|
212
|
+
const d = (s.date ?? "").slice(0, 10);
|
|
213
|
+
if (since !== void 0 && d < since) return false;
|
|
214
|
+
if (until !== void 0 && d > until) return false;
|
|
215
|
+
return true;
|
|
216
|
+
});
|
|
217
|
+
return {
|
|
218
|
+
...presented,
|
|
219
|
+
sessions
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
//#endregion
|
|
202
223
|
//#region src/tools/reads.ts
|
|
224
|
+
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 summary, so query each lift you care about (squat, bench, deadlift, …) and an empty result just means the athlete has not logged that lift. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
|
|
203
225
|
function enc(value) {
|
|
204
226
|
return encodeURIComponent(String(value));
|
|
205
227
|
}
|
|
@@ -220,7 +242,7 @@ const SIMPLE_GETS = [
|
|
|
220
242
|
{
|
|
221
243
|
name: "list_programs",
|
|
222
244
|
title: "List programs",
|
|
223
|
-
description: "Coach programs (standalone).
|
|
245
|
+
description: "Coach programs (standalone only). This is often empty even for an active coach, because most programming lives as a team's group-program: if it returns [], call list_teams and read each team's group_program — do not conclude the coach has no programs.",
|
|
224
246
|
path: "/1.0/coach/programs"
|
|
225
247
|
},
|
|
226
248
|
{
|
|
@@ -232,7 +254,7 @@ const SIMPLE_GETS = [
|
|
|
232
254
|
{
|
|
233
255
|
name: "analytics_categories",
|
|
234
256
|
title: "Analytics categories",
|
|
235
|
-
description: "
|
|
257
|
+
description: "TrainHeroic's raw analytics catalog. Its keys are the API's own names and do NOT match analytics_query's `metric` values — choose the metric straight from analytics_query's (self-describing) enum instead; you rarely need this tool.",
|
|
236
258
|
path: "/v5/analytics"
|
|
237
259
|
}
|
|
238
260
|
];
|
|
@@ -246,7 +268,7 @@ function registerRosterReads(server, ctx) {
|
|
|
246
268
|
}, () => apiCall(ctx, "GET", t.path));
|
|
247
269
|
server.registerTool("list_athletes", {
|
|
248
270
|
title: "List athletes",
|
|
249
|
-
description: "
|
|
271
|
+
description: "Every athlete on this coach's org roster, across all teams (not scoped to one team, and demo/placeholder athletes are included). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. There is no per-athlete team field here, so to attribute athletes to a team use the team's roster. Optional q (case-insensitive substring filter over each athlete record) and limit, applied client-side, to keep large rosters small.",
|
|
250
272
|
inputSchema: {
|
|
251
273
|
q: z.string().optional(),
|
|
252
274
|
limit: z.number().int().positive().max(500).optional()
|
|
@@ -275,7 +297,7 @@ function registerRosterReads(server, ctx) {
|
|
|
275
297
|
}));
|
|
276
298
|
server.registerTool("list_teams", {
|
|
277
299
|
title: "List teams",
|
|
278
|
-
description: "Coach teams. Optional pagination and search.",
|
|
300
|
+
description: "Coach teams. The headcount fields are easy to misread: member_count and athlete_count are enrolled-athlete counts and are commonly 0 (a coach-built team with no enrolled members), while athleteIds typically holds just the owner's id, NOT the full roster. For who is actually on the roster use list_athletes (org-wide). Each team's group_program id is the team's programming. Optional pagination and search.",
|
|
279
301
|
inputSchema: {
|
|
280
302
|
page: z.number().int().positive().optional(),
|
|
281
303
|
pageSize: z.number().int().positive().optional(),
|
|
@@ -305,6 +327,22 @@ function registerEntityReads(server, ctx) {
|
|
|
305
327
|
inputSchema: { teamId: idParam },
|
|
306
328
|
annotations: READ
|
|
307
329
|
}, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
|
|
330
|
+
server.registerTool("athlete_lift_history", {
|
|
331
|
+
title: "Athlete lift history + PRs (roster)",
|
|
332
|
+
description: ATHLETE_LIFT_HISTORY_DESC,
|
|
333
|
+
inputSchema: {
|
|
334
|
+
athleteId: idParam,
|
|
335
|
+
exerciseId: idParam,
|
|
336
|
+
raw: z.boolean().optional(),
|
|
337
|
+
since: dateString.optional(),
|
|
338
|
+
until: dateString.optional()
|
|
339
|
+
},
|
|
340
|
+
annotations: READ
|
|
341
|
+
}, ({ athleteId, exerciseId, raw, since, until }) => attempt(async () => {
|
|
342
|
+
const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), toId(athleteId));
|
|
343
|
+
if (raw === true) return jsonResult(detail);
|
|
344
|
+
return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
|
|
345
|
+
}));
|
|
308
346
|
server.registerTool("get_program", {
|
|
309
347
|
title: "Get program detail",
|
|
310
348
|
description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
|
|
@@ -329,7 +367,7 @@ function registerProfileTools(server, ctx, whoami, userId) {
|
|
|
329
367
|
}, () => attempt(async () => jsonResult(await whoami())));
|
|
330
368
|
server.registerTool("athlete_profile", {
|
|
331
369
|
title: "Athlete profile + lifetime totals",
|
|
332
|
-
description: "Lifetime training totals (
|
|
370
|
+
description: "Lifetime training totals in one call — all-time session count (summary.sessions_count), total reps and volume, first/last logged date — plus the profile (name, units, dob). Use this for any 'how many sessions all-time / total volume ever' question rather than summing athlete_workouts windows. Set useMetric for kg/metric totals.",
|
|
333
371
|
inputSchema: { useMetric: z.boolean().optional() },
|
|
334
372
|
annotations: READ
|
|
335
373
|
}, ({ useMetric }) => attempt(async () => {
|
|
@@ -348,7 +386,7 @@ function registerProfileTools(server, ctx, whoami, userId) {
|
|
|
348
386
|
}, () => attempt(async () => jsonResult(await fetchAthletePrefs(ctx.client))));
|
|
349
387
|
server.registerTool("athlete_working_maxes", {
|
|
350
388
|
title: "Working maxes",
|
|
351
|
-
description: "The athlete's working max per exercise (drives % prescriptions).",
|
|
389
|
+
description: "The athlete's working max per exercise (drives % prescriptions). An entry can carry a null value: the exercise has a working-max slot but no number has been set yet, which means there is effectively no working max for it.",
|
|
352
390
|
inputSchema: {},
|
|
353
391
|
annotations: READ
|
|
354
392
|
}, () => attempt(async () => jsonResult(await fetchWorkingMaxes(ctx.client))));
|
|
@@ -370,58 +408,71 @@ function registerProfileTools(server, ctx, whoami, userId) {
|
|
|
370
408
|
return jsonResult(await fetchLeaderboard(ctx.client, toId(workoutId), opts));
|
|
371
409
|
}));
|
|
372
410
|
}
|
|
411
|
+
const ATHLETE_WORKOUTS_DESC = "Workouts in an inclusive YYYY-MM-DD window, flattened to blocks/exercises. Each exercise carries both its `prescribed` sets (what the program called for) and `performed` sets (what the athlete actually logged); each workout has a top-level `logged` flag. Use `performed`/`logged` to tell what was recorded or done. That is the reliable signal: a session can hold logged sets while the API's own completion flags stay 0, and an empty `performed` means nothing was logged for that exercise. For 'did I record anything / what did I do', set loggedOnly:true to return only sessions with logged sets (it keeps whole sessions that have any logged set, so individual exercises inside can still show empty `performed`; it also shrinks a large result); limit returns the most recent N workouts (newest first). For 'what's my next workout', query a forward window from today; if it comes back empty, the most recent session is likely yesterday's still-unlogged one, so widen the window backward a day or two. Both filters apply to the presented view, not raw. raw:true returns the untouched API objects. This is a date-windowed fetch, NOT an aggregate: for lifetime totals (all-time session count, total volume, first/last logged date) call athlete_profile instead of summing windows — a multi-year range here can time out. Narrow the window if the result is truncated.";
|
|
412
|
+
const ATHLETE_EXERCISE_HISTORY_DESC = "Per-exercise PRs and the dated session time-series (sets performed, estimated 1RM). The returned `sessions` run all-time, newest first; pass since/until (YYYY-MM-DD, inclusive) to keep only sessions in that window — use it for 'last 3 months' / 'this year' questions so the result stays small. `liftPRs` are always all-time and ignore since/until. Set raw:true for the untouched API object. Get the exercise id from athlete_exercises.";
|
|
413
|
+
const ATHLETE_EXERCISES_DESC = "The exercises the athlete has logged (id + title + positional units). Pass q to free-text search by name; use the returned id with athlete_exercise_history, athlete_personal_records, or athlete_exercise_stats (all of which require an exercise id).";
|
|
373
414
|
/** Workouts, exercise catalog, per-exercise history/PRs/stats. */
|
|
374
415
|
function registerExerciseTools$1(server, ctx, userId) {
|
|
375
416
|
server.registerTool("athlete_workouts", {
|
|
376
417
|
title: "Workouts in a date range",
|
|
377
|
-
description:
|
|
418
|
+
description: ATHLETE_WORKOUTS_DESC,
|
|
378
419
|
inputSchema: {
|
|
379
420
|
startDate: dateString,
|
|
380
421
|
endDate: dateString,
|
|
381
|
-
raw: z.boolean().optional()
|
|
422
|
+
raw: z.boolean().optional(),
|
|
423
|
+
loggedOnly: z.boolean().optional(),
|
|
424
|
+
limit: z.number().int().positive().max(200).optional()
|
|
382
425
|
},
|
|
383
426
|
annotations: READ
|
|
384
|
-
}, ({ startDate, endDate, raw }) => attempt(async () => {
|
|
427
|
+
}, ({ startDate, endDate, raw, loggedOnly, limit }) => attempt(async () => {
|
|
385
428
|
const workouts = await fetchAthleteWorkouts(ctx.client, startDate, endDate);
|
|
386
|
-
|
|
429
|
+
if (raw === true) return jsonResult(workouts, { hint: "Narrow startDate/endDate to shrink this result." });
|
|
430
|
+
const opts = {};
|
|
431
|
+
if (loggedOnly !== void 0) opts.loggedOnly = loggedOnly;
|
|
432
|
+
if (limit !== void 0) opts.limit = limit;
|
|
433
|
+
return jsonResult(selectWorkouts(presentAthleteWorkouts(workouts), opts), { hint: "Large? Set loggedOnly:true, pass limit, or narrow startDate/endDate." });
|
|
387
434
|
}));
|
|
388
435
|
server.registerTool("athlete_exercises", {
|
|
389
436
|
title: "Search logged exercises",
|
|
390
|
-
description:
|
|
437
|
+
description: ATHLETE_EXERCISES_DESC,
|
|
391
438
|
inputSchema: {
|
|
392
439
|
q: z.string().optional(),
|
|
393
440
|
limit: z.number().int().positive().max(200).optional()
|
|
394
441
|
},
|
|
395
442
|
annotations: READ
|
|
396
443
|
}, ({ q, limit }) => attempt(async () => {
|
|
397
|
-
|
|
444
|
+
const items = (q !== void 0 && q.trim() !== "" ? await searchExerciseHistory(ctx.client, q, limit ?? 20) : await fetchExerciseHistoryList(ctx.client)).map((r) => ({
|
|
398
445
|
id: r.id,
|
|
399
446
|
title: r.title,
|
|
400
447
|
isCircuit: r.isCircuit ?? false,
|
|
401
448
|
units: exerciseUnits(r.param1Type, r.param2Type)
|
|
402
|
-
}))
|
|
449
|
+
}));
|
|
450
|
+
return jsonResult(limit !== void 0 ? items.slice(0, limit) : items, { hint: "Pass q to search by name, or limit to cap the list." });
|
|
403
451
|
}));
|
|
404
452
|
server.registerTool("athlete_exercise_history", {
|
|
405
453
|
title: "Exercise history + PRs",
|
|
406
|
-
description:
|
|
454
|
+
description: ATHLETE_EXERCISE_HISTORY_DESC,
|
|
407
455
|
inputSchema: {
|
|
408
456
|
exerciseId: idParam,
|
|
409
|
-
raw: z.boolean().optional()
|
|
457
|
+
raw: z.boolean().optional(),
|
|
458
|
+
since: dateString.optional(),
|
|
459
|
+
until: dateString.optional()
|
|
410
460
|
},
|
|
411
461
|
annotations: READ
|
|
412
|
-
}, ({ exerciseId, raw }) => attempt(async () => {
|
|
462
|
+
}, ({ exerciseId, raw, since, until }) => attempt(async () => {
|
|
413
463
|
const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), await userId());
|
|
414
|
-
|
|
464
|
+
if (raw === true) return jsonResult(detail);
|
|
465
|
+
return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
|
|
415
466
|
}));
|
|
416
467
|
server.registerTool("athlete_personal_records", {
|
|
417
468
|
title: "Exercise personal records",
|
|
418
|
-
description: "
|
|
469
|
+
description: "The all-time PR board for an exercise (reps/weight per rep-max, strength-standard filters). Get the exercise id from athlete_exercises. For a point-in-time snapshot use athlete_exercise_stats; for the dated session trend use athlete_exercise_history.",
|
|
419
470
|
inputSchema: { exerciseId: idParam },
|
|
420
471
|
annotations: READ
|
|
421
472
|
}, ({ exerciseId }) => attempt(async () => jsonResult(await fetchPersonalRecords(ctx.client, toId(exerciseId)))));
|
|
422
473
|
server.registerTool("athlete_exercise_stats", {
|
|
423
474
|
title: "Exercise stats (last performance + PR)",
|
|
424
|
-
description: "
|
|
475
|
+
description: "A point-in-time snapshot for an exercise: last performance and PR as of a date (YYYY-MM-DD, required by the API). Not a range query — for the all-time board use athlete_personal_records, for progress over time use athlete_exercise_history. Get the exercise id from athlete_exercises.",
|
|
425
476
|
inputSchema: {
|
|
426
477
|
exerciseId: idParam,
|
|
427
478
|
date: dateString
|
|
@@ -747,7 +798,7 @@ const BODY_KEY = {
|
|
|
747
798
|
function registerAnalyticsTools(server, ctx) {
|
|
748
799
|
server.registerTool("analytics_query", {
|
|
749
800
|
title: "Pull an analytics report",
|
|
750
|
-
description: "Read a TrainHeroic analytics report. `metric`
|
|
801
|
+
description: "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.",
|
|
751
802
|
inputSchema: {
|
|
752
803
|
metric: z.enum(METRIC_KEYS),
|
|
753
804
|
teamId: idParam.optional(),
|
|
@@ -797,13 +848,13 @@ function registerExerciseTools(server, ctx) {
|
|
|
797
848
|
const index = ctx.index;
|
|
798
849
|
server.registerTool("exercise_resolve", {
|
|
799
850
|
title: "Resolve exercise name",
|
|
800
|
-
description: "Map a name to an exercise id via the local mirror. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing.",
|
|
851
|
+
description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
|
|
801
852
|
inputSchema: { name: z.string().min(1) },
|
|
802
853
|
annotations: READ
|
|
803
854
|
}, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
|
|
804
855
|
server.registerTool("exercise_search", {
|
|
805
856
|
title: "Search exercises",
|
|
806
|
-
description: "Ranked fuzzy search over exercise titles. Returns candidates with units.",
|
|
857
|
+
description: "Ranked fuzzy search over exercise titles. Returns candidates with units. Each result's `can_edit` flag marks ownership: 1 = the coach's own custom exercise, 0 = a built-in library exercise — filter on it to answer 'do I have a custom exercise for X'. When you want one definitive id for a known name, use exercise_resolve instead.",
|
|
807
858
|
inputSchema: {
|
|
808
859
|
query: z.string().min(1),
|
|
809
860
|
limit: z.number().int().positive().max(100).optional()
|
|
@@ -1036,7 +1087,7 @@ function registerReads(server, ctx) {
|
|
|
1036
1087
|
}));
|
|
1037
1088
|
server.registerTool("messaging_read", {
|
|
1038
1089
|
title: "Read messages (live)",
|
|
1039
|
-
description: "Recent comments in a stream, live from the API (the stream is fetched whole, then trimmed to `limit
|
|
1090
|
+
description: "Recent comments in a stream, live from the API (the stream is fetched whole, then trimmed to `limit`, default 20). Each comment's `isAuthor` is true when the logged-in user sent it — to answer 'did an athlete message me', look for comments with isAuthor:false. Timestamps are Unix seconds. An empty result means the thread has no messages.",
|
|
1040
1091
|
inputSchema: {
|
|
1041
1092
|
streamId: idParam,
|
|
1042
1093
|
limit: z.number().int().positive().max(200).optional()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/core",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
"@cfworker/json-schema": "^4.1.1",
|
|
26
26
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
27
27
|
"zod": "^4.4.3",
|
|
28
|
-
"@trainheroic-unofficial/dto": "0.6.
|
|
29
|
-
"@trainheroic-unofficial/js": "0.6.
|
|
28
|
+
"@trainheroic-unofficial/dto": "0.6.2",
|
|
29
|
+
"@trainheroic-unofficial/js": "0.6.2"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/node": "^26.0.0",
|