@trainheroic-unofficial/cli 1.0.0 → 1.1.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/README.md CHANGED
@@ -22,7 +22,7 @@ Needs Node >= 18 and an existing TrainHeroic account.
22
22
 
23
23
  ## Usage
24
24
 
25
- Set your TrainHeroic login in the environment (stored in plaintext and shell history — treat
25
+ Set your TrainHeroic login in the environment (stored in plaintext and shell history, so treat
26
26
  it as a secret), then run a command. Every command prints JSON to stdout.
27
27
 
28
28
  ```bash
@@ -33,24 +33,24 @@ trainheroic whoami # confirm auth; prints your ac
33
33
  trainheroic coach exercise resolve "Back Squat" # name -> exercise (id, units)
34
34
  ```
35
35
 
36
- **Driving this from an AI agent?** Run `trainheroic skill` first — it prints the full
36
+ **Driving this from an AI agent?** Run `trainheroic skill` first. It prints the full
37
37
  workflow guide (with copy-paste workout-spec examples) to stdout, version-matched to the
38
- binary; `trainheroic skill --full` adds the API and workout-creation reference docs. It's the
39
- fastest way to get the spec shapes right instead of guessing from flags.
38
+ binary. `trainheroic skill --full` adds the API and workout-creation reference docs, which is
39
+ the quickest path to getting spec shapes right.
40
40
 
41
- Commands split into three groups. `whoami` and `request` are **shared** (role-agnostic).
42
- Everything for managing a roster lives under **`coach`** — reads (`coach athletes`,
43
- `coach programs`, `coach teams`, `coach program <id>`, …), the exercise library
41
+ `whoami` and `request` are role-agnostic shared commands. Roster management lives under
42
+ **`coach`**, covering reads (`coach athletes`, `coach programs`, `coach teams`,
43
+ `coach program <id>`, …), the exercise library
44
44
  (`coach exercise resolve|search|get|sync|create|forget|stats`), the workout lifecycle
45
45
  (`coach workout build|read|publish|remove`), and messaging
46
- (`coach message list|read|draft|send|delete`). Your own training lives under **`athlete`**.
46
+ (`coach message list|read|draft|send|delete`). Your own training data lives under **`athlete`**.
47
47
  Run `trainheroic` with no command for the full reference. Dates are `Y-M-D` with a 1-based
48
48
  month, e.g. `2026-6-22` or `2026-06-22` for 22 June 2026.
49
49
 
50
50
  ### Building a workout
51
51
 
52
- `coach workout build` reads a workout spec — a JSON file (`--file`), an inline argument, or
53
- stdin — and writes it into a program on a date. `--program` is a program id (find it in the
52
+ `coach workout build` reads a workout spec (a JSON file via `--file`, an inline argument, or
53
+ stdin) and writes it into a program on a date. `--program` is a program id (find it in the
54
54
  program's URL in the TrainHeroic web app, or run `trainheroic coach programs`). The spec is
55
55
  `{ blocks, instruction? }` (a bare blocks array is also accepted). Each exercise's `id` is a
56
56
  library id; get one with `coach exercise resolve`. `reps` and `weight` take a scalar or a
@@ -58,7 +58,7 @@ per-set array (`"reps": [5, 5, 3]`); loads use the exercise's configured unit. T
58
58
  is `WorkoutSpec` in [`@trainheroic-unofficial/dto`](../dto).
59
59
 
60
60
  ```jsonc
61
- // day.json — one block with one exercise (id 41822 is a library exercise id)
61
+ // day.json: one block with one exercise (id 41822 is a library exercise id)
62
62
  {
63
63
  "instruction": "Warm up first.",
64
64
  "blocks": [
package/dist/cli.mjs CHANGED
@@ -155,6 +155,14 @@ z.object({
155
155
  endDate: dateString
156
156
  });
157
157
  /**
158
+ * One entered set: the value of each parameter slot (param 1 / param 2 — e.g. reps / weight).
159
+ * Shared by every logging write so the per-set shape is defined once.
160
+ */
161
+ const loggedSetSchema = z.object({
162
+ param1: z.union([z.number(), z.string()]).optional(),
163
+ param2: z.union([z.number(), z.string()]).optional()
164
+ });
165
+ /**
158
166
  * Args for the set-logging write. `date` (the workout's day) locates the saved
159
167
  * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
160
168
  * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
@@ -164,10 +172,7 @@ const logSetArgsSchema = z.object({
164
172
  savedWorkoutSetId: idArgSchema,
165
173
  results: z.array(z.object({
166
174
  savedWorkoutSetExerciseId: idArgSchema,
167
- sets: z.array(z.object({
168
- param1: z.union([z.number(), z.string()]).optional(),
169
- param2: z.union([z.number(), z.string()]).optional()
170
- })).min(1)
175
+ sets: z.array(loggedSetSchema).min(1)
171
176
  })).min(1)
172
177
  });
173
178
  /**
@@ -175,6 +180,25 @@ const logSetArgsSchema = z.object({
175
180
  * roster `athleteId` whose set is being logged on their behalf.
176
181
  */
177
182
  const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
+ /**
184
+ * Args for logging a whole session by exercise (rather than by saved-workout-set id). Each
185
+ * exercise carries its entered sets and an optional 1-based `order`. The athlete path creates
186
+ * or reuses a personal session for the date and logs against it; the coach path resolves each
187
+ * exercise to a set already prescribed on that date and logs against that.
188
+ */
189
+ const logSessionArgsSchema = z.object({
190
+ date: dateString,
191
+ exercises: z.array(z.object({
192
+ exerciseId: idArgSchema,
193
+ order: z.number().int().positive().optional(),
194
+ sets: z.array(loggedSetSchema).min(1)
195
+ })).min(1)
196
+ });
197
+ /**
198
+ * Args for the coach variant of {@link logSessionArgsSchema}: the same shape plus the roster
199
+ * `athleteId` whose session is being logged on their behalf.
200
+ */
201
+ const coachLogSessionArgsSchema = logSessionArgsSchema.extend({ athleteId: idArgSchema });
178
202
  //#endregion
179
203
  //#region ../dto/src/exercise.ts
180
204
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
@@ -1167,6 +1191,238 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1167
1191
  exercisesLogged
1168
1192
  };
1169
1193
  }
1194
+ /**
1195
+ * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
1196
+ * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
1197
+ * savedWorkoutId, and groupId.
1198
+ */
1199
+ async function createPersonalWorkout(client, date) {
1200
+ const res = await client.request("POST", "/v5/programWorkouts/personal", { body: { date } });
1201
+ if (!res.ok) throw new Error(`Create personal workout failed (HTTP ${res.status}).`);
1202
+ if (!isRecord(res.data)) throw new Error("Unexpected response from /v5/programWorkouts/personal.");
1203
+ const pw = isRecord(res.data.programWorkout) ? res.data.programWorkout : null;
1204
+ const sw = isRecord(res.data.savedWorkout) ? res.data.savedWorkout : null;
1205
+ if (!pw || !sw) throw new Error("Missing programWorkout or savedWorkout in response.");
1206
+ const programWorkoutId = coerceInt(pw.id);
1207
+ const workoutId = coerceInt(pw.workoutId);
1208
+ const savedWorkoutId = coerceInt(sw.id);
1209
+ const groupId = coerceInt(sw.group_id);
1210
+ if (!programWorkoutId || !workoutId || !savedWorkoutId || !groupId) throw new Error("Could not parse required ids from personal workout response.");
1211
+ return {
1212
+ programWorkoutId,
1213
+ workoutId,
1214
+ savedWorkoutId,
1215
+ groupId,
1216
+ date: typeof pw.date === "string" ? pw.date : date
1217
+ };
1218
+ }
1219
+ /**
1220
+ * PUT /v5/personalCalendar/workouts/{workoutId}/addExercises — add exercises to a personal
1221
+ * workout. Returns saved workout set objects: each top-level `id` is a savedWorkoutSetId
1222
+ * and `savedWorkoutSetExercises[].id` is a savedWorkoutSetExerciseId, both needed by
1223
+ * logAthleteSet.
1224
+ */
1225
+ async function addExercisesToWorkout(client, workoutId, exercises) {
1226
+ const res = await client.request("PUT", `/v5/personalCalendar/workouts/${workoutId}/addExercises`, { body: {
1227
+ exercises,
1228
+ circuits: []
1229
+ } });
1230
+ if (!res.ok) throw new Error(`Add exercises to workout failed (HTTP ${res.status}).`);
1231
+ return res.data;
1232
+ }
1233
+ /**
1234
+ * Find a personal-calendar session already on the given day. The range marks these with
1235
+ * `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
1236
+ * first one's workoutId, or null when the day has no personal session.
1237
+ */
1238
+ function findPersonalSessionWorkoutId(workouts) {
1239
+ for (const pw of workouts) {
1240
+ const rec = pw;
1241
+ if (rec.personal_cal === true) {
1242
+ const workoutId = coerceInt(rec.workout_id);
1243
+ if (workoutId !== null) return workoutId;
1244
+ }
1245
+ }
1246
+ return null;
1247
+ }
1248
+ /**
1249
+ * Map the `addExercisesToWorkout` response (an array of saved sets) to per-exercise saved ids.
1250
+ * Each set's `id` is a savedWorkoutSetId; each `savedWorkoutSetExercises[].id` is a
1251
+ * savedWorkoutSetExerciseId and `.exerciseId` is the catalog exercise id that was added.
1252
+ */
1253
+ function indexAddedExercises(added) {
1254
+ const out = [];
1255
+ const sets = Array.isArray(added) ? added : [];
1256
+ for (const s of sets) {
1257
+ if (!isRecord(s)) continue;
1258
+ const savedWorkoutSetId = coerceInt(s.id);
1259
+ if (savedWorkoutSetId === null) continue;
1260
+ const exercises = Array.isArray(s.savedWorkoutSetExercises) ? s.savedWorkoutSetExercises : [];
1261
+ for (const ex of exercises) {
1262
+ if (!isRecord(ex)) continue;
1263
+ const savedWorkoutSetExerciseId = coerceInt(ex.id);
1264
+ const exerciseId = coerceInt(ex.exerciseId ?? ex.exercise_id);
1265
+ if (savedWorkoutSetExerciseId === null || exerciseId === null) continue;
1266
+ out.push({
1267
+ exerciseId,
1268
+ savedWorkoutSetId,
1269
+ savedWorkoutSetExerciseId
1270
+ });
1271
+ }
1272
+ }
1273
+ return out;
1274
+ }
1275
+ /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
1276
+ function eachPrescribedExercise(workouts) {
1277
+ const rows = [];
1278
+ for (const pw of workouts) {
1279
+ const rec = pw;
1280
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1281
+ const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1282
+ if (!sw) continue;
1283
+ const sets = [...Array.isArray(sw.workoutSets) ? sw.workoutSets : [], ...Array.isArray(sw.addedWorkoutSets) ? sw.addedWorkoutSets : []];
1284
+ for (const s of sets) {
1285
+ if (!isRecord(s)) continue;
1286
+ const savedWorkoutSetId = coerceInt(s.id);
1287
+ if (savedWorkoutSetId === null) continue;
1288
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1289
+ for (const ex of exercises) if (isRecord(ex)) rows.push({
1290
+ savedWorkoutSetId,
1291
+ ex
1292
+ });
1293
+ }
1294
+ }
1295
+ return rows;
1296
+ }
1297
+ /**
1298
+ * Locate a single prescribed exercise on the given day's workouts, returning the saved set it
1299
+ * belongs to and its saved-set-exercise id. Used by the coach path, which can only log against
1300
+ * what is already on the athlete's calendar. Returns null when the exercise is not prescribed
1301
+ * that day.
1302
+ */
1303
+ function findPrescribedExercise(workouts, exerciseId, used) {
1304
+ for (const { savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
1305
+ const sweId = coerceInt(ex.id);
1306
+ if (sweId === null || used.has(sweId)) continue;
1307
+ if (coerceInt(ex.exercise_id) === exerciseId) return {
1308
+ savedWorkoutSetId,
1309
+ savedWorkoutSetExerciseId: sweId
1310
+ };
1311
+ }
1312
+ return null;
1313
+ }
1314
+ /** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
1315
+ function prescribedExerciseLabels(workouts) {
1316
+ const labels = [];
1317
+ for (const { ex } of eachPrescribedExercise(workouts)) {
1318
+ const id = coerceInt(ex.exercise_id);
1319
+ if (id === null) continue;
1320
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1321
+ labels.push(`${id} (${title})`);
1322
+ }
1323
+ return labels;
1324
+ }
1325
+ /** Group resolved exercises by saved set and write each set via the given log target. */
1326
+ async function logResolvedExercises(client, target, date, resolved) {
1327
+ const bySet = /* @__PURE__ */ new Map();
1328
+ for (const r of resolved) {
1329
+ const list = bySet.get(r.savedWorkoutSetId) ?? [];
1330
+ list.push({
1331
+ savedWorkoutSetExerciseId: r.savedWorkoutSetExerciseId,
1332
+ sets: [...r.sets]
1333
+ });
1334
+ bySet.set(r.savedWorkoutSetId, list);
1335
+ }
1336
+ const out = [];
1337
+ for (const [savedWorkoutSetId, results] of bySet) {
1338
+ const written = target.role === "coach" ? await logForAthlete(client, {
1339
+ athleteId: target.athleteId,
1340
+ date,
1341
+ savedWorkoutSetId,
1342
+ results
1343
+ }) : await logAthleteSet(client, {
1344
+ date,
1345
+ savedWorkoutSetId,
1346
+ results
1347
+ });
1348
+ out.push(written);
1349
+ }
1350
+ return out;
1351
+ }
1352
+ /**
1353
+ * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
1354
+ * required. Reuses a personal session already on the date when one exists (the API marks these
1355
+ * `personal_cal`), otherwise creates one; then adds the exercises and logs their entered sets.
1356
+ * This is the "log whatever I just did" path — extra accessory work, a makeup lift, an off-plan
1357
+ * gym session.
1358
+ */
1359
+ async function logAdHocSession(client, args) {
1360
+ if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1361
+ const existing = findPersonalSessionWorkoutId(await fetchAthleteWorkouts(client, args.date, args.date));
1362
+ const created = existing === null;
1363
+ const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
1364
+ const withOrder = args.exercises.map((e, i) => ({
1365
+ ...e,
1366
+ order: e.order ?? i + 1
1367
+ }));
1368
+ const index = indexAddedExercises(await addExercisesToWorkout(client, workoutId, withOrder.map((e) => ({
1369
+ exerciseId: e.exerciseId,
1370
+ order: e.order
1371
+ }))));
1372
+ const consumed = /* @__PURE__ */ new Set();
1373
+ const resolved = withOrder.map((e) => {
1374
+ const hit = index.find((m) => m.exerciseId === e.exerciseId && !consumed.has(m.savedWorkoutSetExerciseId));
1375
+ if (!hit) throw new Error(`Could not place exercise ${e.exerciseId} into the session after adding it. The add-exercises response did not return a saved set for it.`);
1376
+ consumed.add(hit.savedWorkoutSetExerciseId);
1377
+ return {
1378
+ exerciseId: e.exerciseId,
1379
+ savedWorkoutSetId: hit.savedWorkoutSetId,
1380
+ savedWorkoutSetExerciseId: hit.savedWorkoutSetExerciseId,
1381
+ sets: e.sets
1382
+ };
1383
+ });
1384
+ const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
1385
+ return {
1386
+ date: args.date,
1387
+ created,
1388
+ sets
1389
+ };
1390
+ }
1391
+ /**
1392
+ * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
1393
+ * off-plan session on another user's calendar (the personal-calendar endpoints are self-scoped),
1394
+ * so this logs against the session the athlete already has on that date: each requested exercise
1395
+ * is resolved to a prescribed saved set and its results are written via the coach "Log for
1396
+ * Athlete" surface. Throws a readable error naming the prescribed exercises when one is missing.
1397
+ */
1398
+ async function logSessionForAthlete(client, args) {
1399
+ if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1400
+ const day = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1401
+ const used = /* @__PURE__ */ new Set();
1402
+ const resolved = args.exercises.map((e) => {
1403
+ const hit = findPrescribedExercise(day, e.exerciseId, used);
1404
+ if (!hit) {
1405
+ const labels = prescribedExerciseLabels(day);
1406
+ const present = labels.length > 0 ? `Prescribed on ${args.date}: ${labels.join(", ")}.` : `Nothing is prescribed for athlete ${args.athleteId} on ${args.date}.`;
1407
+ throw new Error(`Exercise ${e.exerciseId} is not on athlete ${args.athleteId}'s calendar for ${args.date}, so there is no set to log it against. ${present} A coach can only log against an existing session; build/publish a session for the athlete first if it is missing.`);
1408
+ }
1409
+ used.add(hit.savedWorkoutSetExerciseId);
1410
+ return {
1411
+ exerciseId: e.exerciseId,
1412
+ ...hit,
1413
+ sets: e.sets
1414
+ };
1415
+ });
1416
+ const sets = await logResolvedExercises(client, {
1417
+ role: "coach",
1418
+ athleteId: args.athleteId
1419
+ }, args.date, resolved);
1420
+ return {
1421
+ date: args.date,
1422
+ created: false,
1423
+ sets
1424
+ };
1425
+ }
1170
1426
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1171
1427
  function presentExerciseHistory(detail) {
1172
1428
  return {
@@ -1381,6 +1637,94 @@ async function queryAnalytics(client, args) {
1381
1637
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1382
1638
  return res.data;
1383
1639
  }
1640
+ /**
1641
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
1642
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
1643
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
1644
+ * given id, matched as a string. Throws when the roster fetch fails.
1645
+ */
1646
+ async function fetchTeamAthleteIds(client, teamId) {
1647
+ const res = await client.request("GET", "/v5/athletes");
1648
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1649
+ const rows = Array.isArray(res.data) ? res.data : [];
1650
+ const want = String(teamId);
1651
+ const ids = [];
1652
+ for (const row of rows) {
1653
+ if (row === null || typeof row !== "object") continue;
1654
+ const rec = row;
1655
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
1656
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
1657
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
1658
+ }
1659
+ return ids;
1660
+ }
1661
+ function toNum(v) {
1662
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
1663
+ return Number.isFinite(n) ? n : 0;
1664
+ }
1665
+ /**
1666
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
1667
+ * analytics report already returns the team in one call — one row per logged session across all
1668
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
1669
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
1670
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
1671
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
1672
+ */
1673
+ async function teamVolume(client, args) {
1674
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
1675
+ const report = await queryAnalytics(client, {
1676
+ metric: "training-summary-athlete",
1677
+ userIds: args.athleteIds,
1678
+ dateStart: args.dateStart,
1679
+ dateEnd: args.dateEnd
1680
+ });
1681
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
1682
+ const byAthlete = /* @__PURE__ */ new Map();
1683
+ for (const row of rows) {
1684
+ const athleteId = toNum(row.user_id);
1685
+ if (athleteId === 0) continue;
1686
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
1687
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
1688
+ const existing = byAthlete.get(athleteId);
1689
+ if (existing) {
1690
+ existing.sessions += 1;
1691
+ existing.reps += toNum(row.reps);
1692
+ existing.volume += toNum(row.volume);
1693
+ if (date !== null) {
1694
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
1695
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
1696
+ }
1697
+ } else byAthlete.set(athleteId, {
1698
+ athleteId,
1699
+ name,
1700
+ sessions: 1,
1701
+ reps: toNum(row.reps),
1702
+ volume: toNum(row.volume),
1703
+ firstLoggedDate: date,
1704
+ lastLoggedDate: date
1705
+ });
1706
+ }
1707
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
1708
+ const totals = athletes.reduce((acc, a) => ({
1709
+ athletes: acc.athletes + 1,
1710
+ sessions: acc.sessions + a.sessions,
1711
+ reps: acc.reps + a.reps,
1712
+ volume: acc.volume + a.volume
1713
+ }), {
1714
+ athletes: 0,
1715
+ sessions: 0,
1716
+ reps: 0,
1717
+ volume: 0
1718
+ });
1719
+ return {
1720
+ window: {
1721
+ start: args.dateStart,
1722
+ end: args.dateEnd
1723
+ },
1724
+ athletes,
1725
+ totals
1726
+ };
1727
+ }
1384
1728
  //#endregion
1385
1729
  //#region ../js/src/util.ts
1386
1730
  /**
@@ -2039,7 +2383,8 @@ Coach — manage a roster (needs a coach account):
2039
2383
  coach program <id> | team <id> | team-codes <id>
2040
2384
 
2041
2385
  roster athlete reads (three lenses — pick by the question):
2042
- coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume (team-volume questions live HERE, not analytics-query). All-time snapshot, no date range. Get the full id list from 'coach athletes'.
2386
+ coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
2387
+ coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D team training volume scoped to a date window: per-athlete rows (only those who logged in range) + rolled-up totals (volume in lb). --team resolves the roster; --athletes passes ids directly.
2043
2388
  coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2044
2389
  coach athlete-training --athlete <id> --year <YYYY> --month <1-12> sessions the athlete LOGGED in one month (empty = nothing logged that month, not an error)
2045
2390
  coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
@@ -2048,6 +2393,11 @@ Coach — manage a roster (needs a coach account):
2048
2393
  coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes
2049
2394
  --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2050
2395
  and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2396
+ coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2397
+ log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2398
+ already on the athlete's calendar that day. The API can't put an off-plan session on an
2399
+ athlete's calendar, so an unprescribed exercise fails (it names what IS prescribed).
2400
+ JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2051
2401
 
2052
2402
  roster management:
2053
2403
  coach athlete-invite --team <id> --emails a@x,b@y [--message "..."] --yes
@@ -2103,7 +2453,9 @@ Athlete — the logged-in user's own training (a coach account works too):
2103
2453
  athlete stats <exerciseId> --date Y-M-D
2104
2454
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2105
2455
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2106
- athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date — no ad-hoc sessions; ids from 'athlete workouts ... --log-ids')
2456
+ athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete workouts ... --log-ids')
2457
+ athlete log-session --date Y-M-D <exercisesJson>|--file f --yes (log OFF-PLAN work with no prescription — creates/reuses a personal session for the date, then logs it; exerciseIds from 'athlete exercises')
2458
+ JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2107
2459
  `;
2108
2460
  function out(value) {
2109
2461
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
@@ -2445,6 +2797,41 @@ async function cmdAthleteLogSet(client, a) {
2445
2797
  results: mapped
2446
2798
  }));
2447
2799
  }
2800
+ const LOG_SESSION_USAGE = "athlete log-session --date Y-M-D <exercisesJson>|--file f --yes";
2801
+ /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
2802
+ function toSessionExercises(exercises) {
2803
+ return exercises.map((e) => {
2804
+ const sets = e.sets.map((s) => {
2805
+ const slot = {};
2806
+ if (s.param1 !== void 0) slot.param1 = s.param1;
2807
+ if (s.param2 !== void 0) slot.param2 = s.param2;
2808
+ return slot;
2809
+ });
2810
+ const mapped = {
2811
+ exerciseId: toInt(String(e.exerciseId), "exerciseId"),
2812
+ sets
2813
+ };
2814
+ if (e.order !== void 0) mapped.order = e.order;
2815
+ return mapped;
2816
+ });
2817
+ }
2818
+ async function cmdAthleteLogSession(client, a) {
2819
+ const { values, positionals } = parse(a, {
2820
+ date: { type: "string" },
2821
+ file: { type: "string" },
2822
+ yes: { type: "boolean" }
2823
+ });
2824
+ const date = isoDate(need(values.date, LOG_SESSION_USAGE), "--date");
2825
+ const args = validate(logSessionArgsSchema, {
2826
+ date,
2827
+ exercises: await jsonInput(positionals[0], values.file)
2828
+ }, "log-session args");
2829
+ if (values.yes !== true) fail(`logging a session on ${date} writes to your coach-visible log; add --yes.`);
2830
+ return out(await logAdHocSession(client, {
2831
+ date: args.date,
2832
+ exercises: toSessionExercises(args.exercises)
2833
+ }));
2834
+ }
2448
2835
  async function cmdAthlete(client, rest) {
2449
2836
  const [sub, ...a] = rest;
2450
2837
  switch (sub) {
@@ -2515,7 +2902,8 @@ async function cmdAthlete(client, rest) {
2515
2902
  }
2516
2903
  case "export": return cmdAthleteExport(client, a);
2517
2904
  case "log-set": return cmdAthleteLogSet(client, a);
2518
- default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set>");
2905
+ case "log-session": return cmdAthleteLogSession(client, a);
2906
+ default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session>");
2519
2907
  }
2520
2908
  }
2521
2909
  async function cmdSkill(rest) {
@@ -2559,7 +2947,7 @@ async function cmdInstallSkill() {
2559
2947
  }
2560
2948
  out({ installed });
2561
2949
  }
2562
- const COACH_USAGE = "usage: trainheroic coach <head-coach|athletes|programs|teams|notifications|analytics|program <id>|team <id>|team-codes <id>|roster-activity|athlete-training|athlete-lift-history|athlete-workouts|log-set|athlete-invite|athlete-archive|athlete-restore|team-create|team-update|team-delete|team-code-create|team-code-delete|session-copy|session-unpublish|session-save-template|analytics-query|exercise|workout|message>";
2950
+ const COACH_USAGE = "usage: trainheroic coach <head-coach|athletes|programs|teams|notifications|analytics|program <id>|team <id>|team-codes <id>|roster-activity|team-volume|athlete-training|athlete-lift-history|athlete-workouts|log-set|log-session|athlete-invite|athlete-archive|athlete-restore|team-create|team-update|team-delete|team-code-create|team-code-delete|session-copy|session-unpublish|session-save-template|analytics-query|exercise|workout|message>";
2563
2951
  const COACH_LOG_SET_USAGE = "coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson> --yes";
2564
2952
  async function cmdCoachLogSet(client, a) {
2565
2953
  const { values, positionals } = parse(a, {
@@ -2595,6 +2983,45 @@ async function cmdCoachLogSet(client, a) {
2595
2983
  results: mapped
2596
2984
  }));
2597
2985
  }
2986
+ const COACH_LOG_SESSION_USAGE = "coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes";
2987
+ async function cmdCoachLogSession(client, a) {
2988
+ const { values, positionals } = parse(a, {
2989
+ athlete: { type: "string" },
2990
+ date: { type: "string" },
2991
+ file: { type: "string" },
2992
+ yes: { type: "boolean" }
2993
+ });
2994
+ const athleteId = toInt(need(values.athlete, COACH_LOG_SESSION_USAGE), "--athlete");
2995
+ const args = validate(coachLogSessionArgsSchema, {
2996
+ athleteId,
2997
+ date: isoDate(need(values.date, COACH_LOG_SESSION_USAGE), "--date"),
2998
+ exercises: await jsonInput(positionals[0], values.file)
2999
+ }, "coach log-session args");
3000
+ if (values.yes !== true) fail(`logging a session for athlete ${athleteId} writes to their training log; add --yes.`);
3001
+ return out(await logSessionForAthlete(client, {
3002
+ athleteId,
3003
+ date: args.date,
3004
+ exercises: toSessionExercises(args.exercises)
3005
+ }));
3006
+ }
3007
+ async function cmdCoachTeamVolume(client, a) {
3008
+ const usage = "coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D";
3009
+ const { values } = parse(a, {
3010
+ team: { type: "string" },
3011
+ athletes: { type: "string" },
3012
+ start: { type: "string" },
3013
+ end: { type: "string" }
3014
+ });
3015
+ const dateStart = isoDate(need(values.start, usage), "--start");
3016
+ const dateEnd = isoDate(need(values.end, usage), "--end");
3017
+ const athleteIds = values.athletes !== void 0 ? idList(values.athletes, "--athletes") : await fetchTeamAthleteIds(client, toInt(need(values.team, usage), "--team"));
3018
+ if (athleteIds.length === 0) fail("no athletes resolved — pass --athletes <id,id,...> or a --team whose roster has athletes.");
3019
+ return out(await teamVolume(client, {
3020
+ athleteIds,
3021
+ dateStart,
3022
+ dateEnd
3023
+ }));
3024
+ }
2598
3025
  async function cmdCoachAthleteWorkouts(client, a) {
2599
3026
  const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
2600
3027
  const { values } = parse(a, {
@@ -2813,10 +3240,12 @@ async function cmdCoach(client, rest) {
2813
3240
  case "team": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team <id>"))}`));
2814
3241
  case "team-codes": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team-codes <id>"))}/teamCodes`));
2815
3242
  case "roster-activity": return cmdCoachRosterActivity(client, a);
3243
+ case "team-volume": return cmdCoachTeamVolume(client, a);
2816
3244
  case "athlete-training": return cmdCoachAthleteTraining(client, a);
2817
3245
  case "athlete-lift-history": return cmdCoachAthleteLiftHistory(client, a);
2818
3246
  case "athlete-workouts": return cmdCoachAthleteWorkouts(client, a);
2819
3247
  case "log-set": return cmdCoachLogSet(client, a);
3248
+ case "log-session": return cmdCoachLogSession(client, a);
2820
3249
  case "athlete-invite": return cmdCoachAthleteInvite(client, a);
2821
3250
  case "athlete-archive": return cmdCoachAthleteArchive(client, a);
2822
3251
  case "athlete-restore": return cmdCoachAthleteRestore(client, a);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.0.0",
25
- "@trainheroic-unofficial/js": "1.0.0"
24
+ "@trainheroic-unofficial/dto": "1.1.1",
25
+ "@trainheroic-unofficial/js": "1.1.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",
@@ -52,18 +52,19 @@ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`.
52
52
 
53
53
  ## What you can do
54
54
 
55
- | Goal | Command |
56
- | ------------------------------------- | -------------------------------------------------------------------- |
57
- | Lifetime totals + profile | `$TH athlete profile [--metric]` |
58
- | Scheduled / completed workouts | `$TH athlete workouts --start Y-M-D --end Y-M-D [--raw] [--summary]` |
59
- | Find an exercise you've logged | `$TH athlete exercises [--q <text>] [--limit N]` |
60
- | One lift's PRs + history over time | `$TH athlete history <exerciseId> [--raw]` |
61
- | Personal records for a lift | `$TH athlete prs <exerciseId>` |
62
- | Last performance + PR as of a date | `$TH athlete stats <exerciseId> --date Y-M-D` |
63
- | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
- | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
65
- | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
- | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
55
+ | Goal | Command |
56
+ | ------------------------------------- | ------------------------------------------------------------------------------ |
57
+ | Lifetime totals + profile | `$TH athlete profile [--metric]` |
58
+ | Scheduled / completed workouts | `$TH athlete workouts --start Y-M-D --end Y-M-D [--raw] [--summary]` |
59
+ | Find an exercise you've logged | `$TH athlete exercises [--q <text>] [--limit N]` |
60
+ | One lift's PRs + history over time | `$TH athlete history <exerciseId> [--raw]` |
61
+ | Personal records for a lift | `$TH athlete prs <exerciseId>` |
62
+ | Last performance + PR as of a date | `$TH athlete stats <exerciseId> --date Y-M-D` |
63
+ | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
+ | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
65
+ | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
+ | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
67
+ | Log an off-plan session (gated) | `$TH athlete log-session --date Y-M-D '[{"exerciseId":N,"sets":[...]}]' --yes` |
67
68
 
68
69
  ## Reading training
69
70
 
@@ -126,6 +127,21 @@ $TH athlete log-set --date 2026-06-01 --set 1593305783 --yes \
126
127
  check the result landed as intended. `param1`/`param2` are the entered values by entry slot
127
128
  (check the exercise's positional units first).
128
129
 
130
+ ### Logging an off-plan session
131
+
132
+ When you trained something a coach never scheduled (accessory work, a makeup lift, an
133
+ unplanned gym session), `log-set` has no set to target. Use `log-session` instead — it
134
+ creates (or reuses) a personal session for the date, adds the exercises, and logs them in one
135
+ call. Pass the exercises array directly; get each `exerciseId` from `$TH athlete exercises`:
136
+
137
+ ```bash
138
+ $TH athlete log-session --date 2026-06-21 --yes \
139
+ '[{"exerciseId": 1, "sets": [{"param1": 5, "param2": 185}, {"param1": 5, "param2": 185}]}]'
140
+ ```
141
+
142
+ Same coach-visible write and the same `--yes` gate as `log-set`. For a workout the coach
143
+ already scheduled, prefer `log-set` so it attaches to the prescription.
144
+
129
145
  ## Gotchas
130
146
 
131
147
  - `profile` must send `use_metric` and `stats` must send `date`, or the API returns 400.
@@ -86,17 +86,18 @@ response shape, or an area not covered here.
86
86
 
87
87
  ## What you can do
88
88
 
89
- | Area | How |
90
- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
91
- | Athletes | `$TH coach athletes`; `coach athlete-invite\|athlete-archive\|athlete-restore` |
92
- | Teams / join codes | `$TH coach teams\|team <id>\|team-codes <id>`; `coach team-create\|team-update\|team-delete\|team-code-create\|team-code-delete` |
93
- | Programs | `$TH coach programs`, `$TH coach program <id>` |
94
- | Exercises | `$TH coach exercise resolve\|search\|get\|sync\|create\|forget\|stats` (below) |
95
- | Sessions / workouts | `$TH coach workout build\|read\|publish\|remove`; `coach session-copy\|session-unpublish\|session-save-template` |
96
- | Roster training | `$TH coach roster-activity\|athlete-training\|athlete-lift-history\|athlete-workouts` (read another athlete's training) |
97
- | Log for an athlete | `$TH coach log-set` — record a roster athlete's reps/weights (real athletes only; see below) |
98
- | Messaging | `$TH coach message list\|read\|draft\|send\|delete` (below) |
99
- | Analytics | `$TH coach analytics` (category list); `$TH coach analytics-query --metric <key> ...` (the report) |
89
+ | Area | How |
90
+ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | Athletes | `$TH coach athletes`; `coach athlete-invite\|athlete-archive\|athlete-restore` |
92
+ | Teams / join codes | `$TH coach teams\|team <id>\|team-codes <id>`; `coach team-create\|team-update\|team-delete\|team-code-create\|team-code-delete` |
93
+ | Programs | `$TH coach programs`, `$TH coach program <id>` |
94
+ | Exercises | `$TH coach exercise resolve\|search\|get\|sync\|create\|forget\|stats` (below) |
95
+ | Sessions / workouts | `$TH coach workout build\|read\|publish\|remove`; `coach session-copy\|session-unpublish\|session-save-template` |
96
+ | Roster training | `$TH coach roster-activity\|athlete-training\|athlete-lift-history\|athlete-workouts` (read another athlete's training) |
97
+ | Team volume (windowed) | `$TH coach team-volume --team <id>\|--athletes <ids> --start Y-M-D --end Y-M-D` — date-scoped team volume (roster-activity is all-time) |
98
+ | Log for an athlete | `$TH coach log-set` (by set id) or `coach log-session` (by exercise) — record a roster athlete's reps/weights (real athletes only; see below) |
99
+ | Messaging | `$TH coach message list\|read\|draft\|send\|delete` (below) |
100
+ | Analytics | `$TH coach analytics` (category list); `$TH coach analytics-query --metric <key> ...` (the report) |
100
101
 
101
102
  ## Resolving exercises
102
103
 
@@ -189,6 +190,16 @@ $TH coach log-set --athlete 200004 --date 2026-06-22 --set 1594558978 --yes \
189
190
  '[{"savedWorkoutSetExerciseId":2714543789,"sets":[{"param1":"10","param2":"225"},{"param1":"10","param2":"225"}]}]'
190
191
  ```
191
192
 
193
+ To skip the id-hunting step, `coach log-session` logs by exerciseId instead: each exercise is
194
+ matched to a set already on the athlete's calendar for that date. The API has no way to put an
195
+ off-plan session on another athlete's calendar, so an exercise that is not prescribed that day
196
+ fails (the error names what is prescribed) — build/publish a session first if it is missing.
197
+
198
+ ```bash
199
+ $TH coach log-session --athlete 200004 --date 2026-06-22 --yes \
200
+ '[{"exerciseId":1,"sets":[{"param1":10,"param2":225},{"param1":10,"param2":225}]}]'
201
+ ```
202
+
192
203
  **Only works for real (invited) athletes.** TrainHeroic's seeded _demo_ athletes are
193
204
  read-only for results: the data-write returns `401` and the change never persists (the app
194
205
  shows it optimistically but it is not saved). The official app hits the same 401 on demo