@trainheroic-unofficial/coach-mcp 3.1.1 → 3.3.0

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 +821 -152
  2. package/package.json +4 -4
package/dist/server.mjs CHANGED
@@ -27,12 +27,14 @@ const numLikeOrNull = z.union([
27
27
  z.string(),
28
28
  z.null()
29
29
  ]);
30
- z.looseObject({
30
+ /** `/user/simple` — the identity + tenant key (numeric `id`) for any logged-in account. */
31
+ const userSimpleSchema = z.looseObject({
31
32
  id: intLike$1,
32
33
  roles: z.array(z.string()).optional(),
33
34
  org_id: intLikeOrNull$1.optional()
34
35
  });
35
- z.looseObject({
36
+ /** `/v5/athleteProfile/summary` — lifetime training totals. Needs `use_metric` in the query. */
37
+ const athleteProfileSummarySchema = z.looseObject({
36
38
  reps_sum: z.number().optional(),
37
39
  volume_sum: z.number().optional(),
38
40
  sessions_count: z.number().optional(),
@@ -40,7 +42,8 @@ z.looseObject({
40
42
  last_logged_date: z.string().optional(),
41
43
  duration_hours: z.number().optional()
42
44
  });
43
- z.looseObject({
45
+ /** `/v5/users/{id}` — the detailed athlete profile (only the fields we surface). */
46
+ const athleteUserSchema = z.looseObject({
44
47
  id: intLike$1,
45
48
  email: z.string().optional(),
46
49
  name_first: z.string().optional(),
@@ -110,7 +113,8 @@ const liftPRSchema = z.looseObject({
110
113
  isMetric: z.boolean().optional(),
111
114
  description: z.string().optional()
112
115
  });
113
- z.looseObject({
116
+ /** `/v5/exercises/{id}/history` — the per-exercise PRs + session history. */
117
+ const exerciseHistoryDetailSchema = z.looseObject({
114
118
  liftPRs: z.array(liftPRSchema).optional(),
115
119
  singleParamPRs: z.array(z.unknown()).optional(),
116
120
  history: z.array(historyEntrySchema).optional()
@@ -147,7 +151,7 @@ const programWorkoutSchema = z.looseObject({
147
151
  team_title: z.string().optional(),
148
152
  summarizedSavedWorkout: z.unknown().optional()
149
153
  });
150
- z.array(programWorkoutSchema);
154
+ const programWorkoutListSchema = z.array(programWorkoutSchema);
151
155
  /** A `YYYY-MM-DD` date argument. The single definition reused across athlete tool inputs. */
152
156
  const dateString = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "expected YYYY-MM-DD");
153
157
  z.object({
@@ -234,8 +238,168 @@ z.object({
234
238
  programWorkoutId: idArgSchema,
235
239
  date: dateString
236
240
  });
241
+ const presentedNullNumber = z.number().nullable();
242
+ const presentedNullString = z.string().nullable();
243
+ /** Flattened exercise within a presented workout: prescriptions, logged results, units. */
244
+ const athleteWorkoutExerciseSchema = z.object({
245
+ exerciseId: presentedNullNumber,
246
+ title: z.string(),
247
+ instruction: presentedNullString,
248
+ units: z.array(presentedNullString),
249
+ prescribed: z.array(z.string()),
250
+ performed: z.array(z.string())
251
+ });
252
+ const athleteWorkoutBlockSchema = z.object({
253
+ order: z.number(),
254
+ title: presentedNullString,
255
+ instruction: presentedNullString,
256
+ isTest: z.boolean(),
257
+ exercises: z.array(athleteWorkoutExerciseSchema)
258
+ });
259
+ const athleteWorkoutViewSchema = z.object({
260
+ id: presentedNullNumber,
261
+ date: z.string(),
262
+ title: z.string(),
263
+ program: presentedNullString,
264
+ team: presentedNullString,
265
+ instruction: presentedNullString,
266
+ logged: z.boolean(),
267
+ personal: z.boolean(),
268
+ blocks: z.array(athleteWorkoutBlockSchema)
269
+ });
270
+ const athleteWorkoutSummarySchema = z.object({
271
+ id: presentedNullNumber,
272
+ date: z.string(),
273
+ title: z.string(),
274
+ program: presentedNullString,
275
+ team: presentedNullString,
276
+ logged: z.boolean(),
277
+ personal: z.boolean(),
278
+ exerciseCount: z.number().int().nonnegative(),
279
+ performedCount: z.number().int().nonnegative()
280
+ });
281
+ z.union([
282
+ z.array(athleteWorkoutSummarySchema),
283
+ z.array(athleteWorkoutViewSchema),
284
+ programWorkoutListSchema
285
+ ]);
286
+ z.looseObject({
287
+ summary: athleteProfileSummarySchema,
288
+ user: athleteUserSchema
289
+ });
290
+ z.array(z.object({
291
+ id: z.union([z.number(), z.string()]),
292
+ title: z.string(),
293
+ isCircuit: z.boolean(),
294
+ units: z.array(presentedNullString)
295
+ }));
296
+ const coachAthleteExerciseSchema = z.object({
297
+ exerciseId: presentedNullNumber,
298
+ title: z.string(),
299
+ summary: presentedNullString,
300
+ completed: z.boolean()
301
+ });
302
+ const coachAthleteSessionSchema = z.object({
303
+ workoutId: presentedNullNumber,
304
+ savedWorkoutId: presentedNullNumber,
305
+ title: z.string(),
306
+ logged: z.boolean(),
307
+ completed: z.boolean(),
308
+ rpe: presentedNullNumber,
309
+ durationMin: presentedNullNumber,
310
+ notes: presentedNullString,
311
+ exercises: z.array(coachAthleteExerciseSchema)
312
+ });
313
+ const coachAthleteTrainingOutputSchema = z.object({
314
+ athleteId: presentedNullNumber,
315
+ athleteName: presentedNullString,
316
+ year: z.number().int(),
317
+ month: z.number().int(),
318
+ sessions: z.array(coachAthleteSessionSchema)
319
+ });
320
+ const rosterActivityRowSchema = z.object({
321
+ athleteId: z.number(),
322
+ sessionsCount: presentedNullNumber,
323
+ firstLoggedDate: presentedNullString,
324
+ lastLoggedDate: presentedNullString,
325
+ totalReps: presentedNullNumber,
326
+ totalVolume: presentedNullNumber
327
+ });
328
+ const teamVolumeAthleteSchema = z.object({
329
+ athleteId: z.number(),
330
+ name: presentedNullString,
331
+ sessions: z.number(),
332
+ reps: z.number(),
333
+ volume: z.number(),
334
+ firstLoggedDate: presentedNullString,
335
+ lastLoggedDate: presentedNullString
336
+ });
337
+ const teamVolumeOutputSchema = z.object({
338
+ window: z.object({
339
+ start: z.string(),
340
+ end: z.string()
341
+ }),
342
+ athletes: z.array(teamVolumeAthleteSchema),
343
+ totals: z.object({
344
+ athletes: z.number(),
345
+ sessions: z.number(),
346
+ reps: z.number(),
347
+ volume: z.number()
348
+ })
349
+ });
350
+ const rosterActivityOutputSchema = z.array(rosterActivityRowSchema);
351
+ const presentedExerciseSessionSchema = z.object({
352
+ date: z.string(),
353
+ abr: presentedNullString,
354
+ estimated1RM: presentedNullNumber,
355
+ sets: z.array(z.object({
356
+ setNumber: z.number(),
357
+ value: presentedNullString
358
+ }))
359
+ });
360
+ const presentedExerciseHistorySchema = z.object({
361
+ liftPRs: z.array(z.object({
362
+ description: presentedNullString,
363
+ reps: presentedNullNumber,
364
+ weight: presentedNullNumber,
365
+ units: presentedNullString,
366
+ date: presentedNullString
367
+ })),
368
+ sessions: z.array(presentedExerciseSessionSchema)
369
+ });
370
+ /** Presented history first so the loose raw detail schema cannot swallow it. */
371
+ const exerciseHistoryOutputSchema = z.union([presentedExerciseHistorySchema, exerciseHistoryDetailSchema]);
237
372
  //#endregion
238
373
  //#region ../dto/src/exercise.ts
374
+ /**
375
+ * A row presented for display. The raw param-type codes are dropped and the fixed
376
+ * measurement units are surfaced positionally in `units`, ordered by entry slot
377
+ * (param 1, then param 2). Positional, not semantic: param 2 is not always the load
378
+ * — some exercises reverse the slots — so the units are not labelled by role.
379
+ */
380
+ const exerciseViewSchema = z.object({
381
+ id: z.number(),
382
+ title: z.string(),
383
+ can_edit: z.number(),
384
+ user_id: z.number().nullable(),
385
+ use_count: z.number(),
386
+ units: z.array(z.string().nullable())
387
+ });
388
+ /**
389
+ * Full library object from `exercise_get`: the stored row with param-type codes
390
+ * replaced by positional `units`. Extra API fields are preserved. Search/resolve
391
+ * use the strict `exerciseViewSchema` projection instead.
392
+ */
393
+ const exerciseGetOutputSchema = z.looseObject({
394
+ id: idSchema,
395
+ title: z.string(),
396
+ units: z.array(z.string().nullable())
397
+ });
398
+ /** The outcome of resolving a name: a single match (or null) plus ranked candidates. */
399
+ const exerciseResolveOutputSchema = z.object({
400
+ match: exerciseViewSchema.nullable(),
401
+ candidates: z.array(exerciseViewSchema)
402
+ });
239
403
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
240
404
  const exerciseCreateSchema = z.looseObject({
241
405
  title: z.string().min(1),
@@ -292,6 +456,209 @@ const programCreateResponseSchema = z.looseObject({
292
456
  }).optional()
293
457
  });
294
458
  //#endregion
459
+ //#region ../dto/src/team.ts
460
+ /** Fields merged onto the program object for `POST /1.0/coach/team/updatePublishSettings`. */
461
+ const teamPublishPatchObject = z.object({
462
+ pub_enabled: z.union([z.number(), z.boolean()]).optional(),
463
+ pub_days: z.unknown().optional(),
464
+ pub_time: z.unknown().optional(),
465
+ pub_timezone: z.string().optional()
466
+ });
467
+ const teamPublishPatchSchema = teamPublishPatchObject.refine((v) => v.pub_enabled !== void 0 || v.pub_days !== void 0 || v.pub_time !== void 0 || v.pub_timezone !== void 0, { message: "Provide at least one pub_* field" });
468
+ //#endregion
469
+ //#region ../dto/src/tool-output.ts
470
+ const nullableNumber = z.number().nullable();
471
+ const nullableString = z.string().nullable();
472
+ const truncationMarkerSchema = z.looseObject({
473
+ field: z.string().optional(),
474
+ returned: z.number().int().nonnegative().optional(),
475
+ total: z.number().int().nonnegative(),
476
+ omitted: z.number().int().nonnegative(),
477
+ hint: z.string()
478
+ });
479
+ /** Dedicated budget-fallback envelope. Never the natural tool shape. */
480
+ const truncatedOutputSchema = z.looseObject({
481
+ preview: z.string().optional(),
482
+ items: z.array(z.json()).optional(),
483
+ __truncated: truncationMarkerSchema
484
+ });
485
+ /**
486
+ * Add the shared size-budget fallback to a tool's natural result shape.
487
+ * Truncation is a dedicated `{ items|preview, __truncated }` envelope, so it cannot
488
+ * validate as the natural object and drop the marker.
489
+ */
490
+ function toolOutputSchema(schema) {
491
+ return z.union([truncatedOutputSchema, schema]);
492
+ }
493
+ /** Explicit passthrough for tools whose live API payload is not yet contracted. */
494
+ const opaqueOutputSchema = toolOutputSchema(z.json());
495
+ const logSetTargetOutputSchema = z.object({
496
+ date: z.string(),
497
+ workoutTitle: z.string(),
498
+ program: nullableString,
499
+ programId: nullableNumber,
500
+ team: nullableString,
501
+ teamId: nullableNumber,
502
+ savedWorkoutSetId: z.number(),
503
+ setTitle: nullableString,
504
+ exercises: z.array(z.object({
505
+ savedWorkoutSetExerciseId: z.number(),
506
+ title: z.string(),
507
+ units: z.array(nullableString),
508
+ prescribed: z.array(z.string()),
509
+ performed: z.array(z.string())
510
+ }))
511
+ });
512
+ const logTargetsOutputSchema = z.union([z.array(logSetTargetOutputSchema), programWorkoutListSchema]);
513
+ const messageDraftOutputSchema = z.object({
514
+ draft: z.literal(true),
515
+ note: z.string(),
516
+ would_POST: z.string(),
517
+ payload: z.json()
518
+ });
519
+ z.looseObject({
520
+ status: z.enum(["sent", "logged"]),
521
+ reference: z.string().optional(),
522
+ note: z.string()
523
+ });
524
+ const removedSessionOutputSchema = z.looseObject({ removed: z.union([z.boolean(), z.number()]) });
525
+ z.object({
526
+ removed: z.literal(true),
527
+ programWorkoutId: z.number(),
528
+ date: z.string()
529
+ });
530
+ const athleteInviteOutputSchema = z.object({
531
+ invited: z.literal(true),
532
+ teamId: z.number(),
533
+ result: z.json().optional()
534
+ });
535
+ const setLogOutputSchema = z.object({
536
+ savedWorkoutSetId: z.number(),
537
+ exercisesLogged: z.number().int().nonnegative(),
538
+ setCompleted: z.boolean()
539
+ });
540
+ const setPrescriptionOutputSchema = z.object({
541
+ savedWorkoutSetId: z.number(),
542
+ exercisesPrescribed: z.number().int().nonnegative()
543
+ });
544
+ const exerciseSwapOutputSchema = z.object({
545
+ savedWorkoutSetExerciseId: z.number(),
546
+ athleteId: nullableNumber,
547
+ newExerciseId: z.number(),
548
+ newExerciseTitle: nullableString,
549
+ originalTeamExerciseId: nullableNumber
550
+ });
551
+ const sessionLogSetOutputSchema = z.object({
552
+ savedWorkoutSetId: z.number(),
553
+ exercisesLogged: z.number().int().nonnegative()
554
+ });
555
+ const sessionLogOutputSchema = z.object({
556
+ date: z.string(),
557
+ created: z.boolean(),
558
+ sets: z.array(sessionLogSetOutputSchema),
559
+ scheduledAlternatives: z.array(z.object({
560
+ exerciseId: z.number(),
561
+ title: z.string(),
562
+ program: nullableString,
563
+ workoutTitle: z.string(),
564
+ savedWorkoutSetId: z.number(),
565
+ savedWorkoutSetExerciseId: z.number()
566
+ })).optional()
567
+ });
568
+ z.object({
569
+ programWorkoutId: z.number(),
570
+ workoutId: z.number(),
571
+ savedWorkoutId: z.number(),
572
+ groupId: z.number(),
573
+ date: z.string()
574
+ });
575
+ const workoutReadExerciseOutputSchema = z.object({
576
+ order: z.number(),
577
+ title: z.string(),
578
+ reps: z.array(z.string()),
579
+ primaryUnit: nullableString,
580
+ load: z.array(z.string()),
581
+ loadUnit: nullableString,
582
+ instruction: z.string()
583
+ });
584
+ const workoutReadBlockOutputSchema = z.object({
585
+ order: z.number(),
586
+ title: z.string(),
587
+ instruction: z.string(),
588
+ leaderboard: nullableString,
589
+ exercises: z.array(workoutReadExerciseOutputSchema)
590
+ });
591
+ const workoutReadOutputSchema = z.object({
592
+ pwId: z.number(),
593
+ date: z.string(),
594
+ published: z.json().optional(),
595
+ instruction: z.string(),
596
+ blocks: z.array(workoutReadBlockOutputSchema)
597
+ });
598
+ const workoutBuildOutputSchema = z.object({
599
+ pwId: z.number(),
600
+ workoutId: z.number(),
601
+ programId: z.number(),
602
+ published: z.literal(false),
603
+ advisories: z.object({
604
+ notes: z.array(z.string()),
605
+ warnings: z.array(z.string())
606
+ }),
607
+ readback: workoutReadOutputSchema.nullable(),
608
+ note: z.string()
609
+ });
610
+ const workoutPublishOutputSchema = z.object({
611
+ published: z.number(),
612
+ readback: workoutReadOutputSchema,
613
+ note: z.string()
614
+ });
615
+ const messageSentOutputSchema = z.object({
616
+ sent: z.literal(true),
617
+ comment: z.json()
618
+ });
619
+ const messageDeletedOutputSchema = z.object({
620
+ deleted: z.literal(true),
621
+ response: z.json().optional()
622
+ });
623
+ const exerciseDeletedOutputSchema = z.object({ deleted: z.number() });
624
+ const exerciseForgottenOutputSchema = z.object({ forgotten: z.number() });
625
+ const exerciseCreatedOutputSchema = exerciseResponseSchema;
626
+ const sessionTemplateCreatedOutputSchema = z.looseObject({ id: z.union([z.number(), z.string()]) });
627
+ const mainLiftPrOutputSchema = z.object({
628
+ family: z.enum([
629
+ "cleanjerk",
630
+ "snatch",
631
+ "deadlift",
632
+ "squat",
633
+ "bench",
634
+ "overhead"
635
+ ]),
636
+ label: z.string(),
637
+ exerciseId: nullableNumber,
638
+ title: nullableString,
639
+ weight: nullableNumber,
640
+ reps: nullableNumber,
641
+ units: nullableString,
642
+ date: nullableString
643
+ });
644
+ const athleteMainLiftPrsOutputSchema = z.object({
645
+ athleteId: z.number(),
646
+ athleteName: nullableString,
647
+ prs: z.array(mainLiftPrOutputSchema)
648
+ });
649
+ const programCreatedOutputSchema = z.object({
650
+ containerId: z.number(),
651
+ programId: z.number(),
652
+ title: z.string(),
653
+ kind: z.enum(["calendar", "fixed"]),
654
+ requestedName: z.string(),
655
+ nameApplied: z.boolean()
656
+ });
657
+ const programDeletedOutputSchema = z.object({
658
+ programId: z.number(),
659
+ containerId: nullableNumber
660
+ });
661
+ //#endregion
295
662
  //#region ../dto/src/workout.ts
296
663
  /** A single exercise prescription inside a block. */
297
664
  const exerciseSpecSchema = z.object({
@@ -357,6 +724,11 @@ function parseWorkoutDate(s) {
357
724
  parts[2]
358
725
  ];
359
726
  }
727
+ /** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
728
+ const sessionTemplateCreateSchema = z.object({
729
+ title: z.string().min(1),
730
+ instruction: z.string().optional()
731
+ });
360
732
  //#endregion
361
733
  //#region ../core/src/context.ts
362
734
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
@@ -366,6 +738,12 @@ function toId(value) {
366
738
  }
367
739
  const READ = {
368
740
  readOnlyHint: true,
741
+ destructiveHint: false,
742
+ openWorldHint: true
743
+ };
744
+ const ADDITIVE = {
745
+ readOnlyHint: false,
746
+ destructiveHint: false,
369
747
  openWorldHint: true
370
748
  };
371
749
  const SYNC = {
@@ -393,32 +771,36 @@ async function attempt(fn) {
393
771
  }
394
772
  /** Conservative per-result character cap, below the smallest host cap. */
395
773
  const DEFAULT_RESULT_BUDGET = 6e4;
774
+ /** Smallest cap that can still carry a useful structured truncation envelope. */
775
+ const MIN_RESULT_BUDGET = 256;
396
776
  /** Reserve for the `__truncated` marker so wrapping cannot push back over budget. */
397
777
  const MARKER_RESERVE = 300;
398
778
  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.";
399
779
  const DEFAULT_OBJECT_HINT = "Result was truncated to fit the size budget. Request a more specific id or sub-resource.";
400
780
  /**
401
781
  * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
402
- * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
403
- * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
404
- * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
782
+ * dropped. Every budget fallback that trims a list uses this envelope (`{ items, __truncated }`),
783
+ * including in-place object-array truncation (the sliced array becomes `items` and `field` names
784
+ * the original key). `athlete_exercises` uses the same helper for a client-side catalog cap.
405
785
  */
406
- function clipArray(items, keep, hint) {
786
+ function clipArray(items, keep, hint, field) {
787
+ const marker = {
788
+ returned: keep,
789
+ total: items.length,
790
+ omitted: items.length - keep,
791
+ hint: hint ?? DEFAULT_ARRAY_HINT
792
+ };
793
+ if (field !== void 0) marker.field = field;
407
794
  return {
408
795
  items: items.slice(0, keep),
409
- __truncated: {
410
- returned: keep,
411
- total: items.length,
412
- omitted: items.length - keep,
413
- hint: hint ?? DEFAULT_ARRAY_HINT
414
- }
796
+ __truncated: marker
415
797
  };
416
798
  }
417
799
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
418
800
  function resultBudget() {
419
801
  const raw = (globalThis.process?.env)?.TH_MCP_RESULT_BUDGET;
420
802
  const n = raw ? Number(raw) : NaN;
421
- return Number.isFinite(n) && n > 0 ? n : DEFAULT_RESULT_BUDGET;
803
+ return Number.isFinite(n) && n >= MIN_RESULT_BUDGET ? n : DEFAULT_RESULT_BUDGET;
422
804
  }
423
805
  function isPlainObject(value) {
424
806
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -435,7 +817,7 @@ function largestPrefixCount(pieces, charBudget) {
435
817
  }
436
818
  return k;
437
819
  }
438
- /** Last resort: cap a string at the budget and label it as truncated, non-JSON output. */
820
+ /** Cap diagnostic text. Tool errors are text-only and are not output-schema validated. */
439
821
  function hardCap(text, budget, hint) {
440
822
  if (text.length <= budget) return text;
441
823
  const note = `\n\n[TRUNCATED: output exceeded ${budget} chars and is NOT valid JSON. ${hint ?? "Narrow the query (filter, paginate, or fetch a specific id)."}]`;
@@ -455,56 +837,79 @@ function largestArrayValuedKey(obj) {
455
837
  }
456
838
  return best;
457
839
  }
458
- /**
459
- * Serialize `data` as JSON within `budget` characters. Small results are pretty-printed.
460
- * Oversized results degrade in order: trim a top-level array (wrapping it as
461
- * `{ items, __truncated }`), then a top-level object's largest array property (annotated
462
- * with `__truncated`), then a last-resort hard character cap. Pure and side-effect free.
463
- */
464
- function boundedSerialize(data, budget, hint) {
465
- if (typeof data === "string") return hardCap(data, budget, hint);
466
- const compact = JSON.stringify(data) ?? "null";
840
+ function jsonValue(data) {
841
+ return JSON.parse(JSON.stringify(data) ?? "null");
842
+ }
843
+ function previewEnvelope(source, budget, hint) {
844
+ const total = source.length;
845
+ const makeValue = (preview, markerHint) => ({
846
+ preview,
847
+ __truncated: {
848
+ total,
849
+ omitted: total - preview.length,
850
+ hint: markerHint
851
+ }
852
+ });
853
+ let markerHint = hint ?? "Narrow the query (filter, paginate, or fetch a specific id).";
854
+ while (JSON.stringify(makeValue("", markerHint)).length > budget && markerHint.length > 0) markerHint = markerHint.slice(0, -1);
855
+ if (JSON.stringify(makeValue("", markerHint)).length > budget) throw new RangeError("Result budget is too small for a structured truncation envelope.");
856
+ let keep = Math.max(0, budget - JSON.stringify(makeValue("", markerHint)).length);
857
+ let value = makeValue(source.slice(0, keep), markerHint);
858
+ while (JSON.stringify(value).length > budget && keep > 0) {
859
+ keep = Math.max(0, keep - (JSON.stringify(value).length - budget));
860
+ value = makeValue(source.slice(0, keep), markerHint);
861
+ }
862
+ return value;
863
+ }
864
+ function boundedResult(data, budget, hint) {
865
+ if (typeof data === "string" && data.length <= budget) return {
866
+ text: data,
867
+ value: data
868
+ };
869
+ const value = jsonValue(data);
870
+ const compact = JSON.stringify(value);
467
871
  if (compact.length <= budget) {
468
- const pretty = JSON.stringify(data, null, 2) ?? "null";
469
- return pretty.length <= budget ? pretty : compact;
470
- }
471
- if (Array.isArray(data)) {
472
- const k = largestPrefixCount(data.map((el) => JSON.stringify(el) ?? "null"), budget - MARKER_RESERVE);
473
- const out = JSON.stringify(clipArray(data, k, hint));
474
- if (out.length <= budget) return out;
475
- } else if (isPlainObject(data)) {
476
- const key = largestArrayValuedKey(data);
872
+ const pretty = JSON.stringify(value, null, 2);
873
+ return {
874
+ text: pretty.length <= budget ? pretty : compact,
875
+ value
876
+ };
877
+ }
878
+ if (Array.isArray(value)) {
879
+ const truncated = clipArray(value, largestPrefixCount(value.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint);
880
+ const text = JSON.stringify(truncated);
881
+ if (text.length <= budget) return {
882
+ text,
883
+ value: truncated
884
+ };
885
+ } else if (isPlainObject(value)) {
886
+ const key = largestArrayValuedKey(value);
477
887
  if (key !== null) {
478
- const arr = data[key];
479
- const pieces = arr.map((el) => JSON.stringify(el) ?? "null");
480
- const restLen = (JSON.stringify({
481
- ...data,
482
- [key]: []
483
- }) ?? "{}").length;
484
- const k = largestPrefixCount(pieces, Math.max(0, budget - MARKER_RESERVE - restLen));
485
- const clone = {
486
- ...data,
487
- [key]: arr.slice(0, k),
488
- __truncated: {
489
- field: key,
490
- returned: k,
491
- total: arr.length,
492
- omitted: arr.length - k,
493
- hint: hint ?? DEFAULT_OBJECT_HINT
494
- }
888
+ const array = value[key];
889
+ const truncated = clipArray(array, largestPrefixCount(array.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
890
+ const text = JSON.stringify(truncated);
891
+ if (text.length <= budget) return {
892
+ text,
893
+ value: truncated
495
894
  };
496
- const out = JSON.stringify(clone);
497
- if (out.length <= budget) return out;
498
895
  }
499
896
  }
500
- return hardCap(compact, budget, hint);
897
+ const truncated = previewEnvelope(typeof data === "string" ? data : compact, budget, hint);
898
+ return {
899
+ text: JSON.stringify(truncated),
900
+ value: truncated
901
+ };
501
902
  }
502
903
  /** A successful tool result carrying JSON (or text) for the model, size-bounded. */
503
904
  function jsonResult(data, opts) {
504
- return { content: [{
505
- type: "text",
506
- text: boundedSerialize(data, resultBudget(), opts?.hint)
507
- }] };
905
+ const { text, value } = boundedResult(data, resultBudget(), opts?.hint);
906
+ return {
907
+ content: [{
908
+ type: "text",
909
+ text
910
+ }],
911
+ structuredContent: value
912
+ };
508
913
  }
509
914
  /** A tool-level error: returned in-band (isError) so the model can self-correct. */
510
915
  function errorResult(message) {
@@ -1896,6 +2301,22 @@ async function logSessionForAthlete(client, args) {
1896
2301
  };
1897
2302
  }
1898
2303
  //#endregion
2304
+ //#region ../js/src/util.ts
2305
+ /**
2306
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2307
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
2308
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2309
+ * optional ones lose `undefined` from their value type.
2310
+ *
2311
+ * Example:
2312
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2313
+ */
2314
+ function definedProps(obj) {
2315
+ const result = {};
2316
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2317
+ return result;
2318
+ }
2319
+ //#endregion
1899
2320
  //#region ../js/src/workout-encode.ts
1900
2321
  const LEADERBOARD_TYPE = {
1901
2322
  completion: 0,
@@ -2288,6 +2709,45 @@ async function createProgram(client, args) {
2288
2709
  nameApplied: title === requestedName
2289
2710
  };
2290
2711
  }
2712
+ /**
2713
+ * Delete a standalone program (`DELETE /v5/programs/{programId}`).
2714
+ *
2715
+ * The live API 401s when the path id is a list_programs container id. Pass either id: this
2716
+ * resolves a container to its `group_program` first. Team calendars are not in that list; their
2717
+ * program id is deleted as given. This is not idempotent against an unknown failure.
2718
+ */
2719
+ async function deleteProgram(client, programId) {
2720
+ if (!Number.isInteger(programId) || programId <= 0) throw new Error("Program id must be a positive integer.");
2721
+ const programs = await client.request("GET", "/1.0/coach/programs");
2722
+ if (!programs.ok || !Array.isArray(programs.data)) {
2723
+ const detail = typeof programs.data === "string" ? programs.data : JSON.stringify(programs.data);
2724
+ throw new Error(`GET /1.0/coach/programs failed (HTTP ${programs.status}): ${detail}`);
2725
+ }
2726
+ let targetId = programId;
2727
+ let containerId = null;
2728
+ for (const item of programs.data) {
2729
+ if (!isRecord(item)) continue;
2730
+ const groupProgram = coerceInt(item.group_program);
2731
+ if (coerceInt(item.id) === programId && groupProgram !== null) {
2732
+ containerId = programId;
2733
+ targetId = groupProgram;
2734
+ break;
2735
+ }
2736
+ }
2737
+ const res = await client.request("DELETE", `/v5/programs/${targetId}`, { expectedStatuses: [
2738
+ 401,
2739
+ 403,
2740
+ 404
2741
+ ] });
2742
+ if (!res.ok) {
2743
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2744
+ throw new Error(`Program delete failed (HTTP ${res.status}): ${detail}`);
2745
+ }
2746
+ return {
2747
+ programId: targetId,
2748
+ containerId
2749
+ };
2750
+ }
2291
2751
  /** Normalize one-or-many emails into a deduped, trimmed list. */
2292
2752
  function emailList(emails) {
2293
2753
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2385,6 +2845,52 @@ async function updateTeam(client, args) {
2385
2845
  }
2386
2846
  return res.data;
2387
2847
  }
2848
+ /** Collapse the MCP/CLI XOR flags into a single publish target. */
2849
+ function teamPublishTarget(ids) {
2850
+ if (ids.programId !== void 0 && ids.teamId !== void 0) throw new Error("Pass programId or teamId, not both.");
2851
+ if (ids.programId !== void 0) return { programId: ids.programId };
2852
+ if (ids.teamId !== void 0) return { teamId: ids.teamId };
2853
+ throw new Error("Pass programId or teamId.");
2854
+ }
2855
+ async function programIdForTeam(client, teamId) {
2856
+ if (teamId <= 0) throw new Error("teamId must be positive.");
2857
+ const team = await client.request("GET", `/v5/teams/${teamId}`);
2858
+ if (!team.ok || !isRecord(team.data)) {
2859
+ const detail = typeof team.data === "string" ? team.data : JSON.stringify(team.data);
2860
+ throw new Error(`GET /v5/teams/${teamId} failed (HTTP ${team.status}): ${detail}`);
2861
+ }
2862
+ const resolved = coerceInt(team.data.group_program) ?? coerceInt(team.data.programId);
2863
+ if (resolved === null || resolved <= 0) throw new Error(`Team ${teamId} has no group_program.`);
2864
+ return resolved;
2865
+ }
2866
+ async function resolvePublishProgramId(client, target) {
2867
+ if ("programId" in target) return target.programId;
2868
+ return programIdForTeam(client, target.teamId);
2869
+ }
2870
+ /**
2871
+ * Update a team's auto-publish settings (`POST /1.0/coach/team/updatePublishSettings`).
2872
+ * The live API 500s on a partial body; it wants the full program object from
2873
+ * `GET /3.0/coach/program/{programId}` with `pub_*` fields merged on top.
2874
+ */
2875
+ async function updateTeamPublishSettings(client, args) {
2876
+ if (Object.keys(args.patch).length === 0) throw new Error("Provide at least one pub_* field to change.");
2877
+ const programId = await resolvePublishProgramId(client, args);
2878
+ if (programId <= 0) throw new Error("programId must be positive.");
2879
+ const current = await client.request("GET", `/3.0/coach/program/${programId}`);
2880
+ if (!current.ok || !isRecord(current.data)) {
2881
+ const detail = typeof current.data === "string" ? current.data : JSON.stringify(current.data);
2882
+ throw new Error(`GET /3.0/coach/program/${programId} failed (HTTP ${current.status}): ${detail}`);
2883
+ }
2884
+ const res = await client.request("POST", "/1.0/coach/team/updatePublishSettings", { body: {
2885
+ ...current.data,
2886
+ ...args.patch
2887
+ } });
2888
+ if (!res.ok) {
2889
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2890
+ throw new Error(`updatePublishSettings failed (HTTP ${res.status}): ${detail}`);
2891
+ }
2892
+ return res.data;
2893
+ }
2388
2894
  /**
2389
2895
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2390
2896
  * The API wants the target date as a structured object (with weekday and an isToday flag),
@@ -2617,6 +3123,23 @@ async function teamVolume(client, args) {
2617
3123
  totals
2618
3124
  };
2619
3125
  }
3126
+ /** Create a reusable session template in the coach library (`POST /v5/sessions/template`). */
3127
+ async function createSessionTemplate(client, args) {
3128
+ const title = args.title.trim();
3129
+ if (title === "") throw new Error("Session template title must not be blank.");
3130
+ const res = await client.request("POST", "/v5/sessions/template", { body: definedProps({
3131
+ title,
3132
+ instruction: args.instruction
3133
+ }) });
3134
+ if (!res.ok) {
3135
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
3136
+ throw new Error(`Session template create failed (HTTP ${res.status}): ${detail}`);
3137
+ }
3138
+ if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
3139
+ return res.data;
3140
+ }
3141
+ /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
3142
+ const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
2620
3143
  //#endregion
2621
3144
  //#region ../js/src/main-lifts.ts
2622
3145
  /**
@@ -2825,22 +3348,6 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
2825
3348
  });
2826
3349
  }
2827
3350
  //#endregion
2828
- //#region ../js/src/util.ts
2829
- /**
2830
- * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2831
- * spread into an object under `exactOptionalPropertyTypes` without the per-key
2832
- * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2833
- * optional ones lose `undefined` from their value type.
2834
- *
2835
- * Example:
2836
- * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2837
- */
2838
- function definedProps(obj) {
2839
- const result = {};
2840
- for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2841
- return result;
2842
- }
2843
- //#endregion
2844
3351
  //#region ../js/src/messaging.ts
2845
3352
  const BUCKETS = [
2846
3353
  ["team", "teams"],
@@ -2912,6 +3419,8 @@ var MemoryLibraryCache = class {
2912
3419
  //#region ../js/src/exercise-index.ts
2913
3420
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
2914
3421
  const CREATE_PATH = "/2.0/coach/exercise/create";
3422
+ const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
3423
+ const DELETE_PATH = (id) => `/v5/exercises/${id}`;
2915
3424
  const TTL_MS = 6048e5;
2916
3425
  function toStored(ex) {
2917
3426
  const id = coerceInt(ex.id);
@@ -3040,12 +3549,18 @@ var ExerciseLibrary = class {
3040
3549
  };
3041
3550
  }
3042
3551
  async create(body) {
3552
+ return this.#writeThrough(CREATE_PATH, body, "create");
3553
+ }
3554
+ async update(id, body) {
3555
+ return this.#writeThrough(UPDATE_PATH(id), body, "update");
3556
+ }
3557
+ async #writeThrough(path, body, label) {
3043
3558
  await this.ensureFresh();
3044
- const res = await this.#client.request("POST", CREATE_PATH, { body });
3045
- if (!res.ok) throw new Error(`Exercise create failed (HTTP ${res.status}).`);
3559
+ const res = await this.#client.request("POST", path, { body });
3560
+ if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
3046
3561
  const ex = unwrapEnvelope(res.data);
3047
3562
  if (ex && typeof ex === "object") {
3048
- checkResponse(exerciseResponseSchema, ex, "exercise create");
3563
+ checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
3049
3564
  const s = toStored(ex);
3050
3565
  if (s) {
3051
3566
  this.#byId.set(s.id, s);
@@ -3054,6 +3569,15 @@ var ExerciseLibrary = class {
3054
3569
  }
3055
3570
  return ex;
3056
3571
  }
3572
+ async remove(id) {
3573
+ const res = await this.#client.request("DELETE", DELETE_PATH(id), { expectedStatuses: [
3574
+ 401,
3575
+ 403,
3576
+ 404
3577
+ ] });
3578
+ if (!res.ok) throw new Error(`Exercise delete failed (HTTP ${res.status}).`);
3579
+ await this.recordDelete(id);
3580
+ }
3057
3581
  async recordDelete(id) {
3058
3582
  await this.ensureFresh();
3059
3583
  if (this.#byId.delete(id)) await this.#persist();
@@ -3100,12 +3624,6 @@ function enc(value) {
3100
3624
  }
3101
3625
  /** No-argument GET endpoints, registered from a table to keep the wiring compact. */
3102
3626
  const SIMPLE_GETS = [
3103
- {
3104
- name: "whoami",
3105
- title: "Who am I",
3106
- description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
3107
- path: "/user/simple"
3108
- },
3109
3627
  {
3110
3628
  name: "head_coach",
3111
3629
  title: "Head coach / org",
@@ -3124,19 +3642,51 @@ const SIMPLE_GETS = [
3124
3642
  description: "Unread counts including countMessagingNotViewed (cheap 'anything new?' poll).",
3125
3643
  path: "/v5/notifications/counts"
3126
3644
  },
3645
+ {
3646
+ name: "list_notifications",
3647
+ title: "Notification list",
3648
+ description: "Full notification list (GET /v5/notifications). Distinct from `notifications`, which returns unread counts only. Empty when there are no notifications.",
3649
+ path: "/v5/notifications"
3650
+ },
3651
+ {
3652
+ name: "list_subscriptions",
3653
+ title: "Program subscriptions",
3654
+ description: "Program subscriptions and subscribed teams (GET /1.0/coach/subscriptions). Returns `{subscriptions, teams}`.",
3655
+ path: "/1.0/coach/subscriptions"
3656
+ },
3657
+ {
3658
+ name: "list_prescription_templates",
3659
+ title: "Prescription templates",
3660
+ description: "Saved sets/reps schemes (GET /2.0/coach/workoutSetExercise/template). Use when picking a named prescription like '4 x 3' rather than typing set counts by hand.",
3661
+ path: "/2.0/coach/workoutSetExercise/template"
3662
+ },
3127
3663
  {
3128
3664
  name: "analytics_categories",
3129
3665
  title: "Analytics categories",
3130
3666
  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.",
3131
3667
  path: "/v5/analytics"
3668
+ },
3669
+ {
3670
+ name: "list_session_templates",
3671
+ title: "List session templates",
3672
+ description: "Session templates in the coach library (GET /1.0/coach/workouts). Use a template id with session_save_as_template's inverse: this lists saved templates; session_save_as_template writes one from an existing session. Empty when the library has no templates yet.",
3673
+ path: SESSION_TEMPLATES_LIST_PATH
3132
3674
  }
3133
3675
  ];
3134
3676
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
3135
3677
  function registerRosterReads(server, ctx) {
3678
+ server.registerTool("whoami", {
3679
+ title: "Who am I",
3680
+ description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
3681
+ inputSchema: {},
3682
+ outputSchema: toolOutputSchema(userSimpleSchema),
3683
+ annotations: READ
3684
+ }, () => apiCall(ctx, "GET", "/user/simple"));
3136
3685
  for (const t of SIMPLE_GETS) server.registerTool(t.name, {
3137
3686
  title: t.title,
3138
3687
  description: t.description,
3139
3688
  inputSchema: {},
3689
+ outputSchema: opaqueOutputSchema,
3140
3690
  annotations: READ
3141
3691
  }, () => apiCall(ctx, "GET", t.path));
3142
3692
  server.registerTool("list_athletes", {
@@ -3146,6 +3696,7 @@ function registerRosterReads(server, ctx) {
3146
3696
  q: z.string().optional(),
3147
3697
  limit: z.number().int().positive().max(500).optional()
3148
3698
  },
3699
+ outputSchema: toolOutputSchema(z.array(z.json())),
3149
3700
  annotations: READ
3150
3701
  }, ({ q, limit }) => attempt(async () => {
3151
3702
  const res = await ctx.client.request("GET", "/v5/athletes");
@@ -3162,13 +3713,7 @@ function registerRosterReads(server, ctx) {
3162
3713
  return needles.every((n) => hay.includes(n));
3163
3714
  });
3164
3715
  }
3165
- const total = rows.length;
3166
- if (limit !== void 0 && rows.length > limit) return jsonResult({
3167
- items: rows.slice(0, limit),
3168
- returned: limit,
3169
- total,
3170
- note: "Limited client-side. Raise limit or narrow with q for the rest."
3171
- });
3716
+ if (limit !== void 0 && rows.length > limit) return jsonResult(clipArray(rows, limit, "Limited client-side. Raise limit or narrow with q for the rest."));
3172
3717
  return jsonResult(rows, { hint: "Filter with q (name/email substring) or cap with limit to shrink this list." });
3173
3718
  }));
3174
3719
  server.registerTool("list_teams", {
@@ -3179,6 +3724,7 @@ function registerRosterReads(server, ctx) {
3179
3724
  pageSize: z.number().int().positive().optional(),
3180
3725
  q: z.string().optional()
3181
3726
  },
3727
+ outputSchema: opaqueOutputSchema,
3182
3728
  annotations: READ
3183
3729
  }, ({ page, pageSize, q }) => {
3184
3730
  const qs = new URLSearchParams();
@@ -3195,12 +3741,14 @@ function registerEntityReads(server, ctx) {
3195
3741
  title: "Get team",
3196
3742
  description: "Full team object by team id.",
3197
3743
  inputSchema: { teamId: idParam },
3744
+ outputSchema: opaqueOutputSchema,
3198
3745
  annotations: READ
3199
3746
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}`));
3200
3747
  server.registerTool("list_team_codes", {
3201
3748
  title: "List team access codes",
3202
3749
  description: "Join/access codes for a team.",
3203
3750
  inputSchema: { teamId: idParam },
3751
+ outputSchema: opaqueOutputSchema,
3204
3752
  annotations: READ
3205
3753
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
3206
3754
  server.registerTool("athlete_lift_history", {
@@ -3213,6 +3761,7 @@ function registerEntityReads(server, ctx) {
3213
3761
  since: dateString.optional(),
3214
3762
  until: dateString.optional()
3215
3763
  },
3764
+ outputSchema: toolOutputSchema(exerciseHistoryOutputSchema),
3216
3765
  annotations: READ
3217
3766
  }, ({ athleteId, exerciseId, raw, since, until }) => attempt(async () => {
3218
3767
  const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), toId(athleteId));
@@ -3226,6 +3775,7 @@ function registerEntityReads(server, ctx) {
3226
3775
  athleteIds: z.array(idParam).min(1),
3227
3776
  useMetric: z.boolean().optional()
3228
3777
  },
3778
+ outputSchema: toolOutputSchema(rosterActivityOutputSchema),
3229
3779
  annotations: READ
3230
3780
  }, ({ athleteIds, useMetric }) => attempt(async () => jsonResult(await fetchRosterActivity(ctx.client, athleteIds.map(toId), useMetric ?? false), { hint: "Sorted most-recently-active first; lastLoggedDate null = never logged. The top row is the most recently active athlete." })));
3231
3781
  server.registerTool("athlete_training", {
@@ -3236,6 +3786,7 @@ function registerEntityReads(server, ctx) {
3236
3786
  year: z.number().int(),
3237
3787
  month: z.number().int().min(1).max(12)
3238
3788
  },
3789
+ outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
3239
3790
  annotations: READ
3240
3791
  }, ({ athleteId, year, month }) => attempt(async () => {
3241
3792
  return jsonResult(presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month), toId(athleteId), year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
@@ -3244,6 +3795,7 @@ function registerEntityReads(server, ctx) {
3244
3795
  title: "Get program detail",
3245
3796
  description: "Program detail live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). For standalone rows from list_programs, accepts either id (the container id) or group_program (the underlying program id); container ids are resolved automatically. If neither detail endpoint is available, returns calendar metadata and next-step guidance instead.",
3246
3797
  inputSchema: { programId: idParam },
3798
+ outputSchema: opaqueOutputSchema,
3247
3799
  annotations: READ
3248
3800
  }, ({ programId }) => getProgram(ctx, toId(programId)));
3249
3801
  }
@@ -3278,6 +3830,7 @@ function registerTeamVolume(server, ctx) {
3278
3830
  dateStart: dateString,
3279
3831
  dateEnd: dateString
3280
3832
  },
3833
+ outputSchema: toolOutputSchema(teamVolumeOutputSchema),
3281
3834
  annotations: READ
3282
3835
  }, ({ teamId, athleteIds, dateStart, dateEnd }) => attempt(async () => {
3283
3836
  const ids = athleteIds !== void 0 && athleteIds.length > 0 ? athleteIds.map(toId) : teamId !== void 0 ? await fetchTeamAthleteIds(ctx.client, toId(teamId)) : [];
@@ -3291,9 +3844,19 @@ function registerTeamVolume(server, ctx) {
3291
3844
  }
3292
3845
  function registerReadTools(server, ctx) {
3293
3846
  registerRosterReads(server, ctx);
3847
+ registerCoachAthleteTeamCalendar(server, ctx);
3294
3848
  registerEntityReads(server, ctx);
3295
3849
  registerTeamVolume(server, ctx);
3296
3850
  }
3851
+ function registerCoachAthleteTeamCalendar(server, ctx) {
3852
+ server.registerTool("coach_athlete_team_calendar", {
3853
+ title: "Coach-athlete team calendar",
3854
+ description: "Companion calendar for a roster athlete (GET /v5/calendars/athletes/{id}/coachAthleteTeam). Distinct from workout_build's type-5 individual calendar. Returns title, logo, id, athlete_id, owner_user_id.",
3855
+ inputSchema: { athleteId: idParam },
3856
+ outputSchema: opaqueOutputSchema,
3857
+ annotations: READ
3858
+ }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
3859
+ }
3297
3860
  //#endregion
3298
3861
  //#region ../core/src/tools/main-lifts.ts
3299
3862
  const monthsParam = z.number().int().positive().max(36).optional();
@@ -3308,6 +3871,7 @@ function registerMainLiftTools(server, ctx) {
3308
3871
  athleteId: idParam,
3309
3872
  months: monthsParam
3310
3873
  },
3874
+ outputSchema: toolOutputSchema(athleteMainLiftPrsOutputSchema),
3311
3875
  annotations: READ
3312
3876
  }, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
3313
3877
  server.registerTool("roster_main_lift_prs", {
@@ -3317,6 +3881,7 @@ function registerMainLiftTools(server, ctx) {
3317
3881
  months: monthsParam,
3318
3882
  athleteIds: z.array(idParam).optional()
3319
3883
  },
3884
+ outputSchema: toolOutputSchema(z.array(athleteMainLiftPrsOutputSchema)),
3320
3885
  annotations: READ
3321
3886
  }, ({ months, athleteIds }) => attempt(async () => {
3322
3887
  return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
@@ -3367,6 +3932,7 @@ function registerAthleteTools(server, ctx) {
3367
3932
  message: z.string().optional(),
3368
3933
  confirm: z.boolean().optional()
3369
3934
  },
3935
+ outputSchema: toolOutputSchema(athleteInviteOutputSchema),
3370
3936
  annotations: DESTRUCTIVE
3371
3937
  }, ({ teamId, emails, message, confirm }, extra) => attempt(async () => {
3372
3938
  const list = asEmailList(emails);
@@ -3391,6 +3957,7 @@ function registerAthleteTools(server, ctx) {
3391
3957
  athleteIds: z.array(idParam).min(1),
3392
3958
  confirm: z.boolean().optional()
3393
3959
  },
3960
+ outputSchema: opaqueOutputSchema,
3394
3961
  annotations: DESTRUCTIVE
3395
3962
  }, ({ athleteIds, confirm }, extra) => attempt(async () => {
3396
3963
  const ids = athleteIds.map(toId);
@@ -3402,6 +3969,7 @@ function registerAthleteTools(server, ctx) {
3402
3969
  title: "Restore athletes",
3403
3970
  description: "Restore previously archived athletes to the active roster (PUT /v5/athletes/restore).",
3404
3971
  inputSchema: { athleteIds: z.array(idParam).min(1) },
3972
+ outputSchema: opaqueOutputSchema,
3405
3973
  annotations: {
3406
3974
  readOnlyHint: false,
3407
3975
  idempotentHint: true,
@@ -3432,6 +4000,7 @@ function registerAthleteSavedWorkouts(server, ctx) {
3432
4000
  teamId: idParam.optional(),
3433
4001
  raw: z.boolean().optional()
3434
4002
  },
4003
+ outputSchema: toolOutputSchema(logTargetsOutputSchema),
3435
4004
  annotations: READ
3436
4005
  }, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
3437
4006
  const workouts = selectWorkoutsByProgram(await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate), definedProps({
@@ -3452,6 +4021,7 @@ function registerAthleteLogTools(server, ctx) {
3452
4021
  ...coachLogSetArgsSchema.shape,
3453
4022
  confirm: z.boolean().optional()
3454
4023
  },
4024
+ outputSchema: toolOutputSchema(setLogOutputSchema),
3455
4025
  annotations: DESTRUCTIVE
3456
4026
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3457
4027
  const aId = toId(athleteId);
@@ -3471,6 +4041,7 @@ function registerAthleteLogTools(server, ctx) {
3471
4041
  ...coachLogSessionArgsSchema.shape,
3472
4042
  confirm: z.boolean().optional()
3473
4043
  },
4044
+ outputSchema: toolOutputSchema(sessionLogOutputSchema),
3474
4045
  annotations: DESTRUCTIVE
3475
4046
  }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
3476
4047
  const aId = toId(athleteId);
@@ -3495,6 +4066,7 @@ function registerAthleteSwapTool(server, ctx) {
3495
4066
  ...swapAthleteExerciseArgsSchema.shape,
3496
4067
  confirm: z.boolean().optional()
3497
4068
  },
4069
+ outputSchema: toolOutputSchema(exerciseSwapOutputSchema),
3498
4070
  annotations: DESTRUCTIVE
3499
4071
  }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
3500
4072
  const sweId = toId(savedWorkoutSetExerciseId);
@@ -3520,6 +4092,7 @@ function registerAthletePrescribeTool(server, ctx) {
3520
4092
  ...coachPrescribeSetArgsSchema.shape,
3521
4093
  confirm: z.boolean().optional()
3522
4094
  },
4095
+ outputSchema: toolOutputSchema(setPrescriptionOutputSchema),
3523
4096
  annotations: DESTRUCTIVE
3524
4097
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3525
4098
  const aId = toId(athleteId);
@@ -3535,11 +4108,6 @@ function registerAthletePrescribeTool(server, ctx) {
3535
4108
  }
3536
4109
  //#endregion
3537
4110
  //#region ../core/src/tools/teams.ts
3538
- const ADDITIVE$1 = {
3539
- readOnlyHint: false,
3540
- destructiveHint: false,
3541
- openWorldHint: true
3542
- };
3543
4111
  /**
3544
4112
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
3545
4113
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -3549,7 +4117,8 @@ function registerTeamTools(server, ctx) {
3549
4117
  title: "Create a team",
3550
4118
  description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite. To point a new team at an existing calendar instead of its auto-created one, follow up with team_update groupProgram.",
3551
4119
  inputSchema: { title: z.string().min(1) },
3552
- annotations: ADDITIVE$1
4120
+ outputSchema: opaqueOutputSchema,
4121
+ annotations: ADDITIVE
3553
4122
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
3554
4123
  server.registerTool("team_update", {
3555
4124
  title: "Update a team",
@@ -3559,7 +4128,8 @@ function registerTeamTools(server, ctx) {
3559
4128
  title: z.string().min(1).optional(),
3560
4129
  groupProgram: idParam.optional()
3561
4130
  },
3562
- annotations: ADDITIVE$1
4131
+ outputSchema: opaqueOutputSchema,
4132
+ annotations: ADDITIVE
3563
4133
  }, ({ teamId, title, groupProgram }) => attempt(async () => {
3564
4134
  const args = { teamId: toId(teamId) };
3565
4135
  if (title !== void 0) args.title = title;
@@ -3573,6 +4143,7 @@ function registerTeamTools(server, ctx) {
3573
4143
  teamId: idParam,
3574
4144
  confirm: z.boolean().optional()
3575
4145
  },
4146
+ outputSchema: opaqueOutputSchema,
3576
4147
  annotations: DESTRUCTIVE
3577
4148
  }, ({ teamId, confirm }, extra) => attempt(async () => {
3578
4149
  const id = toId(teamId);
@@ -3587,7 +4158,8 @@ function registerTeamTools(server, ctx) {
3587
4158
  teamId: idParam,
3588
4159
  type: z.number().int().optional()
3589
4160
  },
3590
- annotations: ADDITIVE$1
4161
+ outputSchema: opaqueOutputSchema,
4162
+ annotations: ADDITIVE
3591
4163
  }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
3592
4164
  server.registerTool("team_code_delete", {
3593
4165
  title: "Delete a team join code",
@@ -3596,6 +4168,7 @@ function registerTeamTools(server, ctx) {
3596
4168
  codeId: idParam,
3597
4169
  confirm: z.boolean().optional()
3598
4170
  },
4171
+ outputSchema: opaqueOutputSchema,
3599
4172
  annotations: DESTRUCTIVE
3600
4173
  }, ({ codeId, confirm }, extra) => attempt(async () => {
3601
4174
  const id = toId(codeId);
@@ -3603,14 +4176,41 @@ function registerTeamTools(server, ctx) {
3603
4176
  if (blocked) return blocked;
3604
4177
  return apiCall(ctx, "DELETE", `/v5/teamCodes/${id}`);
3605
4178
  }));
4179
+ registerTeamPublishSettings(server, ctx);
4180
+ }
4181
+ function registerTeamPublishSettings(server, ctx) {
4182
+ server.registerTool("team_publish_settings", {
4183
+ title: "Update team auto-publish",
4184
+ description: "Update a team's auto-publish settings (POST /1.0/coach/team/updatePublishSettings). Pass teamId or programId (the team's group_program). At least one of pub_enabled, pub_days, pub_time, pub_timezone is required. Athlete-facing — requires confirmation.",
4185
+ inputSchema: {
4186
+ teamId: idParam.optional(),
4187
+ programId: idParam.optional(),
4188
+ ...teamPublishPatchObject.shape,
4189
+ confirm: z.boolean().optional()
4190
+ },
4191
+ outputSchema: opaqueOutputSchema,
4192
+ annotations: DESTRUCTIVE
4193
+ }, ({ teamId, programId, pub_enabled, pub_days, pub_time, pub_timezone, confirm }, extra) => attempt(async () => {
4194
+ const blocked = confirmGate(extra, "Change auto-publish settings? This controls when athletes see programmed sessions.", confirm);
4195
+ if (blocked) return blocked;
4196
+ const patch = teamPublishPatchSchema.parse(definedProps({
4197
+ pub_enabled,
4198
+ pub_days,
4199
+ pub_time,
4200
+ pub_timezone
4201
+ }));
4202
+ const target = teamPublishTarget(definedProps({
4203
+ programId: programId !== void 0 ? toId(programId) : void 0,
4204
+ teamId: teamId !== void 0 ? toId(teamId) : void 0
4205
+ }));
4206
+ return jsonResult(await updateTeamPublishSettings(ctx.client, {
4207
+ ...target,
4208
+ patch
4209
+ }));
4210
+ }));
3606
4211
  }
3607
4212
  //#endregion
3608
4213
  //#region ../core/src/tools/programs.ts
3609
- const ADDITIVE = {
3610
- readOnlyHint: false,
3611
- destructiveHint: false,
3612
- openWorldHint: true
3613
- };
3614
4214
  /** Standalone program writes. Program reads live in reads.ts. */
3615
4215
  function registerProgramTools(server, ctx) {
3616
4216
  server.registerTool("program_create", {
@@ -3620,11 +4220,27 @@ function registerProgramTools(server, ctx) {
3620
4220
  kind: z.enum(PROGRAM_KINDS),
3621
4221
  name: z.string().trim().min(1)
3622
4222
  },
4223
+ outputSchema: toolOutputSchema(programCreatedOutputSchema),
3623
4224
  annotations: ADDITIVE
3624
4225
  }, ({ kind, name }) => attempt(async () => jsonResult(await createProgram(ctx.client, {
3625
4226
  kind,
3626
4227
  name
3627
4228
  }))));
4229
+ server.registerTool("program_delete", {
4230
+ title: "Delete a standalone program",
4231
+ description: "Delete a standalone calendar or fixed program (DELETE /v5/programs/{programId}). Accepts either list_programs id (container) or group_program (the underlying program id); container ids 401 if sent raw and are resolved automatically. Removes the calendar from the live account. Requires confirmation (elicitation, or confirm:true).",
4232
+ inputSchema: {
4233
+ programId: idParam,
4234
+ confirm: z.boolean().optional()
4235
+ },
4236
+ outputSchema: toolOutputSchema(programDeletedOutputSchema),
4237
+ annotations: DESTRUCTIVE
4238
+ }, ({ programId, confirm }, extra) => attempt(async () => {
4239
+ const id = toId(programId);
4240
+ const blocked = confirmGate(extra, `Delete standalone program ${id}? This removes the calendar from the live account.`, confirm);
4241
+ if (blocked) return blocked;
4242
+ return jsonResult(await deleteProgram(ctx.client, id));
4243
+ }));
3628
4244
  }
3629
4245
  //#endregion
3630
4246
  //#region ../core/src/tools/analytics.ts
@@ -3644,6 +4260,7 @@ function registerAnalyticsTools(server, ctx) {
3644
4260
  dateEnd: z.string().optional(),
3645
4261
  useMetric: z.boolean().optional()
3646
4262
  },
4263
+ outputSchema: opaqueOutputSchema,
3647
4264
  annotations: READ
3648
4265
  }, ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => attempt(async () => jsonResult(await queryAnalytics(ctx.client, definedProps({
3649
4266
  metric,
@@ -3658,17 +4275,42 @@ function registerAnalyticsTools(server, ctx) {
3658
4275
  }
3659
4276
  //#endregion
3660
4277
  //#region ../core/src/tools/exercises.ts
3661
- /**
3662
- * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
3663
- * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
3664
- * read correctly on both backends.
3665
- */
3666
- function registerExerciseTools(server, ctx) {
3667
- const index = ctx.index;
4278
+ function registerExerciseUpdate(server, index) {
4279
+ server.registerTool("exercise_update", {
4280
+ title: "Update custom exercise",
4281
+ 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.",
4282
+ inputSchema: {
4283
+ id: idParam,
4284
+ exercise: exerciseCreateSchema
4285
+ },
4286
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4287
+ annotations: ADDITIVE
4288
+ }, ({ id, exercise }) => attempt(async () => jsonResult(await index.update(toId(id), exercise))));
4289
+ }
4290
+ function registerExerciseDelete(server, index) {
4291
+ server.registerTool("exercise_delete", {
4292
+ title: "Delete custom exercise",
4293
+ description: "Delete a custom exercise on TrainHeroic (DELETE /v5/exercises/{id}) and drop it from the local mirror. Only works for exercises with can_edit:1. Built-in library exercises cannot be deleted. Requires confirmation (elicitation, or confirm:true). exercise_forget only clears the cache — use this to delete the live exercise.",
4294
+ inputSchema: {
4295
+ id: idParam,
4296
+ confirm: z.boolean().optional()
4297
+ },
4298
+ outputSchema: toolOutputSchema(exerciseDeletedOutputSchema),
4299
+ annotations: DESTRUCTIVE
4300
+ }, ({ id, confirm }, extra) => attempt(async () => {
4301
+ const exerciseId = toId(id);
4302
+ const blocked = confirmGate(extra, `Delete custom exercise ${exerciseId} from the live TrainHeroic library?`, confirm);
4303
+ if (blocked) return blocked;
4304
+ await index.remove(exerciseId);
4305
+ return jsonResult({ deleted: exerciseId });
4306
+ }));
4307
+ }
4308
+ function registerExerciseReads(server, index) {
3668
4309
  server.registerTool("exercise_resolve", {
3669
4310
  title: "Resolve exercise name",
3670
4311
  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.",
3671
4312
  inputSchema: { name: z.string().min(1) },
4313
+ outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
3672
4314
  annotations: READ
3673
4315
  }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
3674
4316
  server.registerTool("exercise_search", {
@@ -3678,12 +4320,14 @@ function registerExerciseTools(server, ctx) {
3678
4320
  query: z.string().min(1),
3679
4321
  limit: z.number().int().positive().max(100).optional()
3680
4322
  },
4323
+ outputSchema: toolOutputSchema(z.array(exerciseViewSchema)),
3681
4324
  annotations: READ
3682
4325
  }, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
3683
4326
  server.registerTool("exercise_get", {
3684
4327
  title: "Get exercise",
3685
4328
  description: "Full exercise object (with units) by id.",
3686
4329
  inputSchema: { id: idParam },
4330
+ outputSchema: toolOutputSchema(exerciseGetOutputSchema),
3687
4331
  annotations: READ
3688
4332
  }, ({ id }) => attempt(async () => {
3689
4333
  const ex = await index.get(toId(id));
@@ -3693,29 +4337,40 @@ function registerExerciseTools(server, ctx) {
3693
4337
  title: "Sync exercise library",
3694
4338
  description: "Refresh the cached exercise index from TrainHeroic.",
3695
4339
  inputSchema: { force: z.boolean().optional() },
4340
+ outputSchema: opaqueOutputSchema,
3696
4341
  annotations: SYNC
3697
4342
  }, ({ force }) => attempt(async () => {
3698
4343
  if (force ?? false) return jsonResult(await index.refresh());
3699
4344
  await index.ensureFresh();
3700
4345
  return jsonResult(await index.stats());
3701
4346
  }));
4347
+ }
4348
+ /**
4349
+ * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
4350
+ * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
4351
+ * read correctly on both backends.
4352
+ */
4353
+ function registerExerciseTools(server, ctx) {
4354
+ const index = ctx.index;
4355
+ registerExerciseReads(server, index);
3702
4356
  server.registerTool("exercise_create", {
3703
4357
  title: "Create custom exercise",
3704
4358
  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}.",
3705
4359
  inputSchema: { exercise: exerciseCreateSchema },
3706
- annotations: {
3707
- readOnlyHint: false,
3708
- destructiveHint: false,
3709
- openWorldHint: true
3710
- }
4360
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4361
+ annotations: ADDITIVE
3711
4362
  }, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
4363
+ registerExerciseUpdate(server, index);
4364
+ registerExerciseDelete(server, index);
3712
4365
  server.registerTool("exercise_forget", {
3713
4366
  title: "Forget exercise (cache only)",
3714
- description: "Remove an exercise from the local mirror only. Run after deleting it via the API.",
4367
+ description: "Remove an exercise from the local mirror only. Does not call TrainHeroic — use exercise_delete to delete the live custom exercise.",
3715
4368
  inputSchema: { id: idParam },
4369
+ outputSchema: toolOutputSchema(exerciseForgottenOutputSchema),
3716
4370
  annotations: {
3717
4371
  readOnlyHint: false,
3718
4372
  idempotentHint: true,
4373
+ destructiveHint: false,
3719
4374
  openWorldHint: false
3720
4375
  }
3721
4376
  }, ({ id }) => attempt(async () => {
@@ -3726,6 +4381,7 @@ function registerExerciseTools(server, ctx) {
3726
4381
  title: "Exercise index stats",
3727
4382
  description: "Row counts and sync state for the cached exercise index.",
3728
4383
  inputSchema: {},
4384
+ outputSchema: opaqueOutputSchema,
3729
4385
  annotations: READ
3730
4386
  }, () => attempt(async () => jsonResult(await index.stats())));
3731
4387
  }
@@ -3744,11 +4400,8 @@ function registerBuild(server, ctx) {
3744
4400
  blocks: z.array(blockSpecSchema),
3745
4401
  instruction: z.string().optional()
3746
4402
  },
3747
- annotations: {
3748
- readOnlyHint: false,
3749
- destructiveHint: false,
3750
- openWorldHint: true
3751
- }
4403
+ outputSchema: toolOutputSchema(workoutBuildOutputSchema),
4404
+ annotations: ADDITIVE
3752
4405
  }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3753
4406
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
3754
4407
  const resolveArgs = {};
@@ -3788,10 +4441,8 @@ function registerReadPublish(server, ctx) {
3788
4441
  date: z.string(),
3789
4442
  pwId: z.number()
3790
4443
  },
3791
- annotations: {
3792
- readOnlyHint: true,
3793
- openWorldHint: true
3794
- }
4444
+ outputSchema: toolOutputSchema(workoutReadOutputSchema),
4445
+ annotations: READ
3795
4446
  }, ({ programId, date, pwId }) => attempt(async () => jsonResult(await readSession(ctx.client, programId, parseWorkoutDate(date), pwId))));
3796
4447
  server.registerTool("workout_publish", {
3797
4448
  title: "Publish a session",
@@ -3802,11 +4453,8 @@ function registerReadPublish(server, ctx) {
3802
4453
  pwId: z.number(),
3803
4454
  confirm: z.boolean().optional()
3804
4455
  },
3805
- annotations: {
3806
- readOnlyHint: false,
3807
- destructiveHint: true,
3808
- openWorldHint: true
3809
- }
4456
+ outputSchema: toolOutputSchema(workoutPublishOutputSchema),
4457
+ annotations: DESTRUCTIVE
3810
4458
  }, ({ programId, date, pwId, confirm }, extra) => attempt(async () => {
3811
4459
  const blocked = confirmGate(extra, `Publish session ${pwId} on ${date}? This is athlete-facing and immediate.`, confirm);
3812
4460
  if (blocked) return blocked;
@@ -3828,11 +4476,8 @@ function registerLifecycle(server, ctx) {
3828
4476
  pwId: z.number(),
3829
4477
  confirm: z.boolean().optional()
3830
4478
  },
3831
- annotations: {
3832
- readOnlyHint: false,
3833
- destructiveHint: true,
3834
- openWorldHint: true
3835
- }
4479
+ outputSchema: toolOutputSchema(removedSessionOutputSchema),
4480
+ annotations: DESTRUCTIVE
3836
4481
  }, ({ programId, pwId, confirm }, extra) => attempt(async () => {
3837
4482
  const blocked = confirmGate(extra, `Delete session ${pwId}? This removes it from the live calendar and is hard to undo.`, confirm);
3838
4483
  if (blocked) return blocked;
@@ -3846,11 +4491,8 @@ function registerLifecycle(server, ctx) {
3846
4491
  pwId: z.number(),
3847
4492
  confirm: z.boolean().optional()
3848
4493
  },
3849
- annotations: {
3850
- readOnlyHint: false,
3851
- destructiveHint: true,
3852
- openWorldHint: true
3853
- }
4494
+ outputSchema: opaqueOutputSchema,
4495
+ annotations: DESTRUCTIVE
3854
4496
  }, ({ pwId, confirm }, extra) => attempt(async () => {
3855
4497
  const blocked = confirmGate(extra, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm);
3856
4498
  if (blocked) return blocked;
@@ -3864,11 +4506,8 @@ function registerLifecycle(server, ctx) {
3864
4506
  pwId: z.number(),
3865
4507
  toDate: z.string()
3866
4508
  },
3867
- annotations: {
3868
- readOnlyHint: false,
3869
- destructiveHint: false,
3870
- openWorldHint: true
3871
- }
4509
+ outputSchema: opaqueOutputSchema,
4510
+ annotations: ADDITIVE
3872
4511
  }, ({ toProgramId, pwId, toDate }) => attempt(async () => jsonResult(await copySession(ctx.client, {
3873
4512
  toProgramId,
3874
4513
  pwId,
@@ -3878,18 +4517,43 @@ function registerLifecycle(server, ctx) {
3878
4517
  title: "Save a session to the library",
3879
4518
  description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
3880
4519
  inputSchema: { workoutId: z.number() },
3881
- annotations: {
3882
- readOnlyHint: false,
3883
- destructiveHint: false,
3884
- openWorldHint: true
3885
- }
4520
+ outputSchema: opaqueOutputSchema,
4521
+ annotations: ADDITIVE
3886
4522
  }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
3887
4523
  }
4524
+ function registerTemplateLibrary(server, ctx) {
4525
+ server.registerTool("session_template_create", {
4526
+ title: "Create a session template",
4527
+ description: "Create an empty reusable session template in the library (POST /v5/sessions/template). Distinct from session_save_as_template, which copies an existing session. Pass title and optional instruction.",
4528
+ inputSchema: sessionTemplateCreateSchema.shape,
4529
+ outputSchema: toolOutputSchema(sessionTemplateCreatedOutputSchema),
4530
+ annotations: ADDITIVE
4531
+ }, ({ title, instruction }) => attempt(async () => jsonResult(await createSessionTemplate(ctx.client, definedProps({
4532
+ title,
4533
+ instruction
4534
+ })))));
4535
+ server.registerTool("session_template_delete", {
4536
+ title: "Delete a session template",
4537
+ description: "Delete a library session template (DELETE /v5/sessions/template/{id}). Requires confirmation (elicitation, or confirm:true).",
4538
+ inputSchema: {
4539
+ id: idParam,
4540
+ confirm: z.boolean().optional()
4541
+ },
4542
+ outputSchema: opaqueOutputSchema,
4543
+ annotations: DESTRUCTIVE
4544
+ }, ({ id, confirm }, extra) => attempt(async () => {
4545
+ const templateId = toId(id);
4546
+ const blocked = confirmGate(extra, `Delete session template ${templateId} from the library?`, confirm);
4547
+ if (blocked) return blocked;
4548
+ return apiCall(ctx, "DELETE", `/v5/sessions/template/${templateId}`);
4549
+ }));
4550
+ }
3888
4551
  /** Workout building, read-back, publishing, and the session calendar lifecycle. */
3889
4552
  function registerWorkoutTools(server, ctx) {
3890
4553
  registerBuild(server, ctx);
3891
4554
  registerReadPublish(server, ctx);
3892
4555
  registerLifecycle(server, ctx);
4556
+ registerTemplateLibrary(server, ctx);
3893
4557
  }
3894
4558
  //#endregion
3895
4559
  //#region ../core/src/tools/messaging.ts
@@ -3898,6 +4562,7 @@ function registerReads(server, ctx) {
3898
4562
  title: "List conversations (live)",
3899
4563
  description: "List chat streams (id, kind, title) live from the API; no setup needed. Use the id to read/draft/send.",
3900
4564
  inputSchema: {},
4565
+ outputSchema: opaqueOutputSchema,
3901
4566
  annotations: READ
3902
4567
  }, () => attempt(async () => {
3903
4568
  return jsonResult((await fetchStreams(ctx.client)).map(({ stream, kind }) => ({
@@ -3916,12 +4581,14 @@ function registerReads(server, ctx) {
3916
4581
  limit: z.number().int().positive().max(200).optional(),
3917
4582
  afterCommentId: idParam.optional()
3918
4583
  },
4584
+ outputSchema: opaqueOutputSchema,
3919
4585
  annotations: READ
3920
4586
  }, ({ streamId, limit, afterCommentId }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20, afterCommentId === void 0 ? void 0 : toId(afterCommentId)))));
3921
4587
  server.registerTool("message_draft", {
3922
4588
  title: "Draft a message (preview only)",
3923
4589
  description: "Preview the exact payload and target WITHOUT sending. Always safe.",
3924
4590
  inputSchema: commentDraftSchema.shape,
4591
+ outputSchema: toolOutputSchema(messageDraftOutputSchema),
3925
4592
  annotations: READ
3926
4593
  }, ({ streamId, text, replyTo }) => attempt(async () => {
3927
4594
  const id = toId(streamId);
@@ -3941,6 +4608,7 @@ function registerWrites(server, ctx) {
3941
4608
  ...commentDraftSchema.shape,
3942
4609
  confirm: z.boolean().optional()
3943
4610
  },
4611
+ outputSchema: toolOutputSchema(messageSentOutputSchema),
3944
4612
  annotations: DESTRUCTIVE
3945
4613
  }, ({ streamId, text, replyTo, confirm }, extra) => attempt(async () => {
3946
4614
  const id = toId(streamId);
@@ -3959,6 +4627,7 @@ function registerWrites(server, ctx) {
3959
4627
  commentId: idParam,
3960
4628
  confirm: z.boolean().optional()
3961
4629
  },
4630
+ outputSchema: toolOutputSchema(messageDeletedOutputSchema),
3962
4631
  annotations: DESTRUCTIVE
3963
4632
  }, ({ streamId, commentId, confirm }, extra) => attempt(async () => {
3964
4633
  const blocked = confirmGate(extra, `Delete comment ${toId(commentId)} from stream ${toId(streamId)}? Acts on the live account.`, confirm);
@@ -4014,7 +4683,7 @@ var JsonFileLibraryCache = class {
4014
4683
  };
4015
4684
  //#endregion
4016
4685
  //#region package.json
4017
- var version = "3.1.1";
4686
+ var version = "3.3.0";
4018
4687
  //#endregion
4019
4688
  //#region src/server.ts
4020
4689
  function main() {