@trainheroic-unofficial/core 1.6.1 → 1.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/index.d.mts CHANGED
@@ -30,6 +30,21 @@ type ToolContext = {
30
30
  declare function attempt(fn: () => Promise<CallToolResult>): Promise<CallToolResult>;
31
31
  /** Conservative per-result character cap, below the smallest host cap. */
32
32
  declare const DEFAULT_RESULT_BUDGET = 60000;
33
+ /**
34
+ * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
35
+ * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
36
+ * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
37
+ * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
38
+ */
39
+ declare function clipArray<T>(items: readonly T[], keep: number, hint?: string): {
40
+ items: T[];
41
+ __truncated: {
42
+ returned: number;
43
+ total: number;
44
+ omitted: number;
45
+ hint: string;
46
+ };
47
+ };
33
48
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
34
49
  declare function resultBudget(): number;
35
50
  /**
@@ -139,4 +154,4 @@ declare function registerWorkoutTools(server: McpServer, ctx: ToolContext): void
139
154
  /** Live messaging: list/read conversations, draft a message, and the gated send/delete. */
140
155
  declare function registerMessagingTools(server: McpServer, ctx: ToolContext): void;
141
156
  //#endregion
142
- export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
157
+ export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, apiCall, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/dist/index.mjs CHANGED
@@ -36,6 +36,23 @@ const DEFAULT_RESULT_BUDGET = 6e4;
36
36
  const MARKER_RESERVE = 300;
37
37
  const DEFAULT_ARRAY_HINT = "Result was truncated to fit the size budget. Narrow it with a filter/search argument or paginate to see the rest.";
38
38
  const DEFAULT_OBJECT_HINT = "Result was truncated to fit the size budget. Request a more specific id or sub-resource.";
39
+ /**
40
+ * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
41
+ * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
42
+ * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
43
+ * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
44
+ */
45
+ function clipArray(items, keep, hint) {
46
+ return {
47
+ items: items.slice(0, keep),
48
+ __truncated: {
49
+ returned: keep,
50
+ total: items.length,
51
+ omitted: items.length - keep,
52
+ hint: hint ?? DEFAULT_ARRAY_HINT
53
+ }
54
+ };
55
+ }
39
56
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
40
57
  function resultBudget() {
41
58
  const raw = (globalThis.process?.env)?.TH_MCP_RESULT_BUDGET;
@@ -92,16 +109,7 @@ function boundedSerialize(data, budget, hint) {
92
109
  }
93
110
  if (Array.isArray(data)) {
94
111
  const k = largestPrefixCount(data.map((el) => JSON.stringify(el) ?? "null"), budget - MARKER_RESERVE);
95
- const wrapped = {
96
- items: data.slice(0, k),
97
- __truncated: {
98
- returned: k,
99
- total: data.length,
100
- omitted: data.length - k,
101
- hint: hint ?? DEFAULT_ARRAY_HINT
102
- }
103
- };
104
- const out = JSON.stringify(wrapped);
112
+ const out = JSON.stringify(clipArray(data, k, hint));
105
113
  if (out.length <= budget) return out;
106
114
  } else if (isPlainObject(data)) {
107
115
  const key = largestArrayValuedKey(data);
@@ -491,7 +499,7 @@ function registerProfileTools(server, ctx, whoami, userId) {
491
499
  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 a high-level overview ('what's on my schedule this week', 'what have I been training lately') set summary:true to get one compact row per session (date, program, title, logged flag, and exerciseCount/performedCount — read performedCount against exerciseCount, e.g. 1 of 12 logged) instead of every set — a multi-program week of full detail is large, so prefer summary first, then re-query a single day without it to drill into that day's sets. 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.";
492
500
  const ATHLETE_LOG_TARGETS_DESC = "The savedWorkoutSetId + savedWorkoutSetExerciseId that athlete_log_set needs, read straight off your scheduled/logged workouts in an inclusive YYYY-MM-DD window — no raw needed. This is the self-service path for logging into a COACH-SCHEDULED workout: read the ids here, then pass them to athlete_log_set. The default view is COMPACT: one row per saved set, each carrying its program/programId, the savedWorkoutSetId, and every exercise's savedWorkoutSetExerciseId with prescribed/performed values. When several workouts fall on the same day (you're on more than one program), narrow to one with program (a case-insensitive title substring, e.g. 'bodybuilding' — no id lookup needed), or programId/teamId if you have the id. raw:true returns the untouched API objects, but that blob is large and can be truncated when several workouts share a date — prefer the program filter + the default view. For reading what you actually did (not the log ids), use athlete_workouts.";
493
501
  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. estimated1RM is a formula off the session's best set and reads high when a session mixes a heavy single with high-rep backdown work, so treat it as approximate, not a logged single. `liftPRs` are always all-time and ignore since/until, but each carries the date it was set, so filter those dates yourself to answer 'PRs set this year'. Set raw:true for the untouched API object. Get the exercise id from athlete_exercises.";
494
- 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). A common name returns several variants (e.g. plain 'Bench Press' id 1162 vs 'BARBELL BENCH PRESS'); each variant keeps its own separate history and PR board, so prefer the plain canonical entry, and if a PR or trend looks incomplete, the work may be split across variants — check the others.";
502
+ const ATHLETE_EXERCISES_DESC = "The exercises the athlete has logged (id + title + positional units). Call with no arguments to get the athlete's complete catalog, which often runs to several hundred entries; leave limit off when you want the whole list, since a no-q call returns everything by default. Pass q to free-text search by name (returns the top ranked matches, capped by limit, default 20). Use a returned id with athlete_exercise_history, athlete_personal_records, or athlete_exercise_stats (all of which require an exercise id). If a no-q result comes back wrapped with a __truncated marker, you passed a limit smaller than the catalog and are seeing a partial list; re-call without limit for all of it. A common name returns several variants (e.g. plain 'Bench Press' id 1162 vs 'BARBELL BENCH PRESS'); each variant keeps its own separate history and PR board, so prefer the plain canonical entry, and if a PR or trend looks incomplete, the work may be split across variants, so check the others.";
495
503
  function runAthleteWorkouts(ctx, args) {
496
504
  return attempt(async () => {
497
505
  const workouts = await fetchAthleteWorkouts(ctx.client, args.startDate, args.endDate);
@@ -504,6 +512,24 @@ function runAthleteWorkouts(ctx, args) {
504
512
  return jsonResult(selected, { hint: "Large? Set summary:true for one row per session, loggedOnly:true, pass limit, or narrow the dates." });
505
513
  });
506
514
  }
515
+ /**
516
+ * Body of the athlete_exercises handler, hoisted to module scope so registerExerciseTools stays
517
+ * under the oxlint max-lines-per-function cap (mirrors runAthleteWorkouts above).
518
+ */
519
+ function runAthleteExercises(ctx, args) {
520
+ const { q, limit } = args;
521
+ return attempt(async () => {
522
+ const searching = q !== void 0 && q.trim() !== "";
523
+ const items = (searching ? await searchExerciseHistory(ctx.client, q, limit ?? 20) : await fetchExerciseHistoryList(ctx.client)).map((r) => ({
524
+ id: r.id,
525
+ title: r.title,
526
+ isCircuit: r.isCircuit ?? false,
527
+ units: exerciseUnits(r.param1Type, r.param2Type)
528
+ }));
529
+ if (!searching && limit !== void 0 && items.length > limit) return jsonResult(clipArray(items, limit, "Partial catalog: re-call athlete_exercises without limit to get all of them."));
530
+ return jsonResult(items, { hint: searching ? "Ranked matches for q. Omit q for the full catalog." : "The athlete's full exercise catalog. Pass q to search by name." });
531
+ });
532
+ }
507
533
  /** Workouts, exercise catalog, per-exercise history/PRs/stats. */
508
534
  function registerExerciseTools$1(server, ctx, userId) {
509
535
  server.registerTool("athlete_workouts", {
@@ -524,18 +550,10 @@ function registerExerciseTools$1(server, ctx, userId) {
524
550
  description: ATHLETE_EXERCISES_DESC,
525
551
  inputSchema: {
526
552
  q: z.string().optional(),
527
- limit: z.number().int().positive().max(200).optional()
553
+ limit: z.number().int().positive().optional()
528
554
  },
529
555
  annotations: READ
530
- }, ({ q, limit }) => attempt(async () => {
531
- const items = (q !== void 0 && q.trim() !== "" ? await searchExerciseHistory(ctx.client, q, limit ?? 20) : await fetchExerciseHistoryList(ctx.client)).map((r) => ({
532
- id: r.id,
533
- title: r.title,
534
- isCircuit: r.isCircuit ?? false,
535
- units: exerciseUnits(r.param1Type, r.param2Type)
536
- }));
537
- return jsonResult(limit !== void 0 ? items.slice(0, limit) : items, { hint: "Pass q to search by name, or limit to cap the list." });
538
- }));
556
+ }, (args) => runAthleteExercises(ctx, args));
539
557
  server.registerTool("athlete_exercise_history", {
540
558
  title: "Exercise history + PRs",
541
559
  description: ATHLETE_EXERCISE_HISTORY_DESC,
@@ -701,6 +719,31 @@ function registerLogTool(server, ctx) {
701
719
  }));
702
720
  }
703
721
  /**
722
+ * The athlete's own per-exercise swap, in its own function so registerLogTool/registerSessionTools
723
+ * stay under the oxlint max-lines-per-function cap. Lets an athlete substitute a prescribed
724
+ * exercise in a coach-scheduled workout for a different one — the self-service equivalent of the
725
+ * app's "swap exercise", overriding only the athlete's own copy of that slot.
726
+ */
727
+ function registerSwapTool(server, ctx) {
728
+ server.registerTool("athlete_swap_exercise", {
729
+ title: "Swap one exercise in your scheduled workout",
730
+ description: "Athlete-facing write: substitute one prescribed exercise in your scheduled workout for a different one — the API equivalent of the app's \"swap exercise\". This is the way to change which movement a slot is BEFORE logging: session_add/remove only touch personal sessions, and athlete_log_set records results into a slot without changing its exercise, so use this when a COACH-SCHEDULED slot should be a different lift. It overrides only your copy of the slot; the team/program prescription is untouched. Give savedWorkoutSetExerciseId (the slot to change, from athlete_log_targets — each row lists it per exercise) and exerciseId (the replacement, from athlete_exercises). After swapping, log against the slot as usual with athlete_log_set. Requires confirmation (elicitation or confirm:true).",
731
+ inputSchema: {
732
+ ...swapAthleteExerciseArgsSchema.shape,
733
+ confirm: z.boolean().optional()
734
+ },
735
+ annotations: DESTRUCTIVE
736
+ }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
737
+ const sweId = toId(savedWorkoutSetExerciseId);
738
+ const exId = toId(exerciseId);
739
+ if (!await confirmGate(server, extra.requestId, `Swap the exercise in your saved workout slot ${sweId} to exercise ${exId}? This changes what that slot is prescribed (your copy only).`, confirm)) return errorResult(NOT_CONFIRMED);
740
+ return jsonResult(await swapAthleteExercise(ctx.client, {
741
+ savedWorkoutSetExerciseId: sweId,
742
+ exerciseId: exId
743
+ }));
744
+ }));
745
+ }
746
+ /**
704
747
  * Live tools over the logged-in user's own training (history, scheduled/completed workouts,
705
748
  * PRs, working maxes), plus a gated set-logging write. The athlete user id is
706
749
  * resolved once from /user/simple and reused across tools.
@@ -725,6 +768,7 @@ function registerAthleteTrainingTools(server, ctx) {
725
768
  registerLogTargetsTool(server, ctx);
726
769
  registerSessionTools(server, ctx);
727
770
  registerLogTool(server, ctx);
771
+ registerSwapTool(server, ctx);
728
772
  }
729
773
  //#endregion
730
774
  //#region src/tools/athletes.ts
@@ -1303,4 +1347,4 @@ function registerMessagingTools(server, ctx) {
1303
1347
  registerWrites(server, ctx);
1304
1348
  }
1305
1349
  //#endregion
1306
- export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
1350
+ export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/core",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
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": "1.6.1",
29
- "@trainheroic-unofficial/js": "1.6.1"
28
+ "@trainheroic-unofficial/dto": "1.7.1",
29
+ "@trainheroic-unofficial/js": "1.7.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.0.1",