@sctg/openclaw-coach 0.1.0 → 2.1.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.
- package/README.md +323 -66
- package/assets/fonts/Inter_400Regular.ttf +0 -0
- package/assets/fonts/Inter_600SemiBold.ttf +0 -0
- package/assets/fonts/LICENSE.txt +93 -0
- package/assets/icon.png +0 -0
- package/assets/logo.png +0 -0
- package/assets/logo.svg +62 -0
- package/dist/charts/build.d.ts +71 -0
- package/dist/charts/build.js +276 -0
- package/dist/charts/labels.d.ts +38 -0
- package/dist/charts/labels.js +73 -0
- package/dist/charts/render.d.ts +10 -0
- package/dist/charts/render.js +26 -0
- package/dist/charts/svg.d.ts +47 -0
- package/dist/charts/svg.js +92 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +38 -0
- package/dist/dates.d.ts +22 -0
- package/dist/dates.js +71 -0
- package/dist/email.d.ts +58 -0
- package/dist/email.js +188 -0
- package/dist/garmin/gc.d.ts +25 -0
- package/dist/garmin/gc.js +81 -0
- package/dist/garmin/normalize.d.ts +20 -0
- package/dist/garmin/normalize.js +132 -0
- package/dist/index.js +207 -163
- package/dist/profile.d.ts +4 -0
- package/dist/profile.js +43 -0
- package/dist/science/associations.d.ts +56 -0
- package/dist/science/associations.js +102 -0
- package/dist/science/healthspan.d.ts +25 -0
- package/dist/science/healthspan.js +89 -0
- package/dist/science/hrv.d.ts +61 -0
- package/dist/science/hrv.js +119 -0
- package/dist/science/load.d.ts +107 -0
- package/dist/science/load.js +228 -0
- package/dist/science/performance.d.ts +93 -0
- package/dist/science/performance.js +191 -0
- package/dist/science/readiness.d.ts +47 -0
- package/dist/science/readiness.js +97 -0
- package/dist/science/recovery.d.ts +74 -0
- package/dist/science/recovery.js +173 -0
- package/dist/science/sleep.d.ts +79 -0
- package/dist/science/sleep.js +165 -0
- package/dist/science/stats.d.ts +50 -0
- package/dist/science/stats.js +201 -0
- package/dist/science/strength.d.ts +47 -0
- package/dist/science/strength.js +120 -0
- package/dist/store.d.ts +36 -0
- package/dist/store.js +78 -0
- package/dist/sync.d.ts +36 -0
- package/dist/sync.js +145 -0
- package/dist/tools.d.ts +463 -0
- package/dist/tools.js +792 -0
- package/dist/types.d.ts +143 -0
- package/dist/types.js +2 -0
- package/docs/SCIENCE.md +721 -0
- package/examples/ATHLETE-fr.md +72 -0
- package/examples/ATHLETE.md +74 -0
- package/examples/PLAN-fr.md +55 -0
- package/examples/PLAN.md +55 -0
- package/openclaw.plugin.json +158 -5
- package/package.json +14 -3
- package/skills/coach/SKILL.md +291 -208
package/dist/tools.js
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool handlers. Each one loads the local store, syncs it with Garmin when
|
|
3
|
+
* asked, runs the models and returns a compact JSON result. Handlers take their
|
|
4
|
+
* dependencies as arguments so that tests can inject a fake `gc` and clock.
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs/promises";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { ceilingLadder, hrvChart, loadChart, recoveryGauge, signalsChart, sleepChart } from "./charts/build.js";
|
|
9
|
+
import { renderPng } from "./charts/render.js";
|
|
10
|
+
import { THEMES } from "./charts/svg.js";
|
|
11
|
+
import { addDays, dateRange, isIsoDate, todayIn, weekStart } from "./dates.js";
|
|
12
|
+
import { defaultHeadline, renderBriefingEmail } from "./email.js";
|
|
13
|
+
import { garminDaySignals, normalizeActivity, normalizeSplits } from "./garmin/normalize.js";
|
|
14
|
+
import { resolveProfile } from "./profile.js";
|
|
15
|
+
import { habitAssociations } from "./science/associations.js";
|
|
16
|
+
import { healthspanMarkers } from "./science/healthspan.js";
|
|
17
|
+
import { analyzeHrv, lnRmssd } from "./science/hrv.js";
|
|
18
|
+
import { analyzeLoad, dailyLoads, fitnessFatigue, intensityDistribution, plannedSessionLoad, projectLoads, sessionLoad, } from "./science/load.js";
|
|
19
|
+
import { ACTIVITY_ALGORITHM, ZONES_ALGORITHM, aerobicDecoupling, gradeAdjustedSpeed, predictTimeFromVdot, riegel, trainingPaces, vdot, zoneTables, } from "./science/performance.js";
|
|
20
|
+
import { decideReadiness } from "./science/readiness.js";
|
|
21
|
+
import { analyzeRecovery, analyzeWarning } from "./science/recovery.js";
|
|
22
|
+
import { analyzeSleep, describeNight } from "./science/sleep.js";
|
|
23
|
+
import { isNum, mean, round, roundOrNull, sum, valid } from "./science/stats.js";
|
|
24
|
+
import { STRENGTH_ALGORITHM, parseExerciseSets, summarizeStrength } from "./science/strength.js";
|
|
25
|
+
import { activitiesFrom, daysBetweenDates, loadStore, saveStore } from "./store.js";
|
|
26
|
+
import { coverage, syncStore } from "./sync.js";
|
|
27
|
+
export class ToolInputError extends Error {
|
|
28
|
+
}
|
|
29
|
+
/** One store operation at a time: two tool calls must not interleave a load and a save. */
|
|
30
|
+
let queue = Promise.resolve();
|
|
31
|
+
function exclusive(task) {
|
|
32
|
+
const run = queue.then(task, task);
|
|
33
|
+
queue = run.catch(() => undefined);
|
|
34
|
+
return run;
|
|
35
|
+
}
|
|
36
|
+
function resolveDate(value, today) {
|
|
37
|
+
if (value === undefined || value === null || value === "today")
|
|
38
|
+
return today;
|
|
39
|
+
if (value === "yesterday")
|
|
40
|
+
return addDays(today, -1);
|
|
41
|
+
if (!isIsoDate(value))
|
|
42
|
+
throw new ToolInputError("date must be YYYY-MM-DD, 'today' or 'yesterday'.");
|
|
43
|
+
if (value > today)
|
|
44
|
+
throw new ToolInputError("date is in the future.");
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
async function loadContext(deps, options) {
|
|
48
|
+
const { config } = deps;
|
|
49
|
+
const now = deps.now?.() ?? new Date();
|
|
50
|
+
const today = todayIn(config.timezone, now);
|
|
51
|
+
const date = resolveDate(options.date, today);
|
|
52
|
+
return exclusive(async () => {
|
|
53
|
+
const store = await loadStore(config.dataDir);
|
|
54
|
+
let sync = null;
|
|
55
|
+
if (options.sync !== false) {
|
|
56
|
+
sync = await syncStore(store, deps.gc, config, today, now);
|
|
57
|
+
await saveStore(config.dataDir, store);
|
|
58
|
+
}
|
|
59
|
+
const days = daysBetweenDates(store, dateRange(addDays(date, -(config.historyDays - 1)), date));
|
|
60
|
+
// The load series starts where the activity list is known to be complete: days
|
|
61
|
+
// before that are unknown, not rest days.
|
|
62
|
+
const wanted = addDays(date, -(config.loadHistoryDays - 1));
|
|
63
|
+
const loadStart = store.activitiesFrom && store.activitiesFrom > wanted ? store.activitiesFrom : wanted;
|
|
64
|
+
const activities = activitiesFrom(store, loadStart, date);
|
|
65
|
+
const profile = resolveProfile(config, days, activities, store.lthr?.value ?? null, date);
|
|
66
|
+
const loads = loadStart <= date && store.activitiesFrom ? dailyLoads(activities, profile, loadStart, date) : [];
|
|
67
|
+
return { today, date, store, sync, days, activities, loads, profile };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function profileSummary(profile) {
|
|
71
|
+
return {
|
|
72
|
+
sex: profile.sex,
|
|
73
|
+
hrMax: profile.hrMax,
|
|
74
|
+
hrMaxSource: profile.hrMaxSource,
|
|
75
|
+
hrRest: profile.hrRest,
|
|
76
|
+
hrRestSource: profile.hrRestSource,
|
|
77
|
+
lthr: profile.lthr,
|
|
78
|
+
lthrSource: profile.lthrSource,
|
|
79
|
+
sleepNeedH: round(profile.sleepNeedS / 3600, 1),
|
|
80
|
+
sleepNeedSource: profile.sleepNeedSource,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function paceText(speedMs) {
|
|
84
|
+
if (!isNum(speedMs) || speedMs <= 0)
|
|
85
|
+
return null;
|
|
86
|
+
const seconds = Math.round(1000 / speedMs);
|
|
87
|
+
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}/km`;
|
|
88
|
+
}
|
|
89
|
+
function clock(seconds) {
|
|
90
|
+
const total = Math.round(seconds);
|
|
91
|
+
const h = Math.floor(total / 3600);
|
|
92
|
+
const m = Math.floor((total % 3600) / 60);
|
|
93
|
+
const s = total % 60;
|
|
94
|
+
return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
|
|
95
|
+
}
|
|
96
|
+
function activityLine(activity, profile) {
|
|
97
|
+
const load = sessionLoad(activity, profile);
|
|
98
|
+
return {
|
|
99
|
+
id: activity.id,
|
|
100
|
+
date: activity.date,
|
|
101
|
+
start: activity.startLocal?.slice(11, 16) ?? null,
|
|
102
|
+
type: activity.type,
|
|
103
|
+
name: activity.name,
|
|
104
|
+
durationMin: roundOrNull(isNum(activity.durationS) ? activity.durationS / 60 : null, 0),
|
|
105
|
+
distanceKm: roundOrNull(isNum(activity.distanceM) ? activity.distanceM / 1000 : null, 2),
|
|
106
|
+
elevGainM: roundOrNull(activity.elevGainM, 0),
|
|
107
|
+
avgHr: activity.avgHr,
|
|
108
|
+
maxHr: activity.maxHr,
|
|
109
|
+
pace: paceText(activity.avgSpeedMs),
|
|
110
|
+
gradeAdjustedPace: paceText(activity.gapSpeedMs),
|
|
111
|
+
load: load.trimp,
|
|
112
|
+
loadMethod: load.method,
|
|
113
|
+
garminLoad: load.garmin,
|
|
114
|
+
aerobicTE: activity.aerobicTE,
|
|
115
|
+
anaerobicTE: activity.anaerobicTE,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function syncSummary(context) {
|
|
119
|
+
return {
|
|
120
|
+
assessedDate: context.date,
|
|
121
|
+
isToday: context.date === context.today,
|
|
122
|
+
sync: context.sync ? { fetchedDays: context.sync.fetchedDays, fetchedActivities: context.sync.fetchedActivities, errors: context.sync.errors } : "not requested",
|
|
123
|
+
dayErrors: context.days[context.days.length - 1]?.errors ?? {},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
// --- coach_daily_briefing -------------------------------------------------------------------------
|
|
127
|
+
export async function dailyBriefing(deps, params) {
|
|
128
|
+
const context = await loadContext(deps, params);
|
|
129
|
+
const { days, activities, loads, profile, date, store } = context;
|
|
130
|
+
const today = days[days.length - 1];
|
|
131
|
+
const journal = store.journal[date] ?? null;
|
|
132
|
+
const hrv = analyzeHrv(days);
|
|
133
|
+
const sleep = analyzeSleep(days, profile);
|
|
134
|
+
const recovery = analyzeRecovery(days, profile);
|
|
135
|
+
const warning = analyzeWarning(days);
|
|
136
|
+
const load = analyzeLoad(loads, activities, profile);
|
|
137
|
+
const readiness = decideReadiness({ hrv, recovery, warning, sleep, load, journal });
|
|
138
|
+
const [readinessResult, statusResult] = await Promise.all([
|
|
139
|
+
deps.gc(["metrics", "training-readiness", date]),
|
|
140
|
+
deps.gc(["metrics", "training-status", date]),
|
|
141
|
+
]);
|
|
142
|
+
const garmin = garminDaySignals(readinessResult.ok ? readinessResult.data : null, statusResult.ok ? statusResult.data : null);
|
|
143
|
+
const yesterday = addDays(date, -1);
|
|
144
|
+
return {
|
|
145
|
+
date,
|
|
146
|
+
data: { ...syncSummary(context), coverage: coverage(store, date, deps.config.historyDays) },
|
|
147
|
+
readiness,
|
|
148
|
+
recovery: { status: recovery.status, score: recovery.score, band: recovery.band, components: recovery.components, coverage: recovery.coverage, notes: recovery.notes, algorithm: recovery.algorithm },
|
|
149
|
+
signals: recovery.deviations,
|
|
150
|
+
hrv,
|
|
151
|
+
sleep,
|
|
152
|
+
earlyWarning: warning,
|
|
153
|
+
load: { ...load, intensity28: load.intensity28 },
|
|
154
|
+
garmin: {
|
|
155
|
+
...garmin,
|
|
156
|
+
hrvStatus: today?.hrv?.status ?? null,
|
|
157
|
+
bodyBattery: today?.bodyBattery ?? null,
|
|
158
|
+
stress: today?.stress ? { avg: today.stress.avg, max: today.stress.max } : null,
|
|
159
|
+
note: "Garmin's own scores, reported as such: proprietary models, shown for comparison.",
|
|
160
|
+
},
|
|
161
|
+
activities: {
|
|
162
|
+
today: activities.filter((activity) => activity.date === date).map((activity) => activityLine(activity, profile)),
|
|
163
|
+
yesterday: activities.filter((activity) => activity.date === yesterday).map((activity) => activityLine(activity, profile)),
|
|
164
|
+
},
|
|
165
|
+
journal,
|
|
166
|
+
profile: profileSummary(profile),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// --- coach_trends ---------------------------------------------------------------------------------
|
|
170
|
+
export async function trends(deps, params) {
|
|
171
|
+
const context = await loadContext(deps, { sync: params.sync });
|
|
172
|
+
const { days, activities, loads, profile, date } = context;
|
|
173
|
+
const span = Math.min(Math.max(Math.round(params.days ?? 28), 14), deps.config.historyDays);
|
|
174
|
+
const window = days.slice(-span);
|
|
175
|
+
const curve = fitnessFatigue(loads);
|
|
176
|
+
const curveByDate = new Map(curve.map((point) => [point.date, point]));
|
|
177
|
+
const weeks = new Map();
|
|
178
|
+
for (const day of window) {
|
|
179
|
+
const key = weekStart(day.date);
|
|
180
|
+
if (!weeks.has(key))
|
|
181
|
+
weeks.set(key, { days: [], activities: [] });
|
|
182
|
+
weeks.get(key)?.days.push(day);
|
|
183
|
+
}
|
|
184
|
+
for (const activity of activities)
|
|
185
|
+
weeks.get(weekStart(activity.date))?.activities.push(activity);
|
|
186
|
+
const weekly = [...weeks.entries()].map(([start, week]) => {
|
|
187
|
+
const inWindow = week.activities.filter((activity) => activity.date >= window[0].date);
|
|
188
|
+
const ln = valid(week.days.map(lnRmssd));
|
|
189
|
+
const lastDay = week.days[week.days.length - 1].date;
|
|
190
|
+
return {
|
|
191
|
+
weekStart: start,
|
|
192
|
+
daysInWindow: week.days.length,
|
|
193
|
+
hrvMs: ln.length ? round(Math.exp(mean(ln)), 0) : null,
|
|
194
|
+
restingHr: roundOrNull(mean(valid(week.days.map((day) => day.restingHr))), 0),
|
|
195
|
+
sleepH: roundOrNull(mean(valid(week.days.map((day) => (isNum(day.sleep?.durationS) ? day.sleep.durationS / 3600 : null)))), 2),
|
|
196
|
+
respiration: roundOrNull(mean(valid(week.days.map((day) => day.respiration?.sleepAvg))), 1),
|
|
197
|
+
load: round(sum(inWindow.map((activity) => sessionLoad(activity, profile).trimp ?? 0)), 0),
|
|
198
|
+
sessions: inWindow.length,
|
|
199
|
+
hours: round(sum(inWindow.map((activity) => activity.durationS ?? 0)) / 3600, 1),
|
|
200
|
+
distanceKm: round(sum(inWindow.map((activity) => activity.distanceM ?? 0)) / 1000, 1),
|
|
201
|
+
elevGainM: round(sum(inWindow.map((activity) => activity.elevGainM ?? 0)), 0),
|
|
202
|
+
fitnessAtEnd: curveByDate.get(lastDay)?.ctl ?? null,
|
|
203
|
+
formAtEnd: curveByDate.get(lastDay)?.tsb ?? null,
|
|
204
|
+
intensity: intensityDistribution(inWindow),
|
|
205
|
+
};
|
|
206
|
+
});
|
|
207
|
+
const result = {
|
|
208
|
+
date,
|
|
209
|
+
windowDays: span,
|
|
210
|
+
data: syncSummary(context),
|
|
211
|
+
weekly,
|
|
212
|
+
hrv: analyzeHrv(days),
|
|
213
|
+
sleep: analyzeSleep(days, profile),
|
|
214
|
+
load: analyzeLoad(loads, activities, profile),
|
|
215
|
+
healthspan: healthspanMarkers(days, activities, profile),
|
|
216
|
+
profile: profileSummary(profile),
|
|
217
|
+
};
|
|
218
|
+
if (params.includeDaily) {
|
|
219
|
+
result.daily = window.map((day) => ({
|
|
220
|
+
date: day.date,
|
|
221
|
+
hrvMs: day.hrv?.lastNightAvgMs ?? null,
|
|
222
|
+
restingHr: day.restingHr,
|
|
223
|
+
sleepH: roundOrNull(isNum(day.sleep?.durationS) ? day.sleep.durationS / 3600 : null, 1),
|
|
224
|
+
respiration: day.respiration?.sleepAvg ?? null,
|
|
225
|
+
spo2: day.spo2?.sleepAvg ?? null,
|
|
226
|
+
skinTempC: day.skinTempDeviationC,
|
|
227
|
+
load: curveByDate.get(day.date)?.load ?? null,
|
|
228
|
+
fitness: curveByDate.get(day.date)?.ctl ?? null,
|
|
229
|
+
fatigue: curveByDate.get(day.date)?.atl ?? null,
|
|
230
|
+
form: curveByDate.get(day.date)?.tsb ?? null,
|
|
231
|
+
}));
|
|
232
|
+
}
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
export async function trainingLoad(deps, params) {
|
|
236
|
+
const context = await loadContext(deps, { sync: params.sync });
|
|
237
|
+
const { activities, loads, profile, date } = context;
|
|
238
|
+
const analysis = analyzeLoad(loads, activities, profile);
|
|
239
|
+
const curve = fitnessFatigue(loads);
|
|
240
|
+
const result = {
|
|
241
|
+
date,
|
|
242
|
+
data: syncSummary(context),
|
|
243
|
+
load: analysis,
|
|
244
|
+
recentSessions: activities.filter((activity) => activity.date >= addDays(date, -13)).map((activity) => activityLine(activity, profile)),
|
|
245
|
+
weeklyCurve: curve.filter((_, index) => (curve.length - 1 - index) % 7 === 0).slice(-12),
|
|
246
|
+
profile: profileSummary(profile),
|
|
247
|
+
};
|
|
248
|
+
if (params.plan?.length) {
|
|
249
|
+
if (!analysis.today)
|
|
250
|
+
throw new ToolInputError("No load history yet: a plan cannot be projected.");
|
|
251
|
+
const byDate = new Map();
|
|
252
|
+
const rejected = [];
|
|
253
|
+
for (const session of params.plan) {
|
|
254
|
+
if (!isIsoDate(session.date) || session.date <= date || session.date > addDays(date, 120)) {
|
|
255
|
+
rejected.push(`${String(session.date)}: date must be within the next 120 days`);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const load = isNum(session.load) && session.load >= 0
|
|
259
|
+
? session.load
|
|
260
|
+
: isNum(session.durationMin) && isNum(session.zone)
|
|
261
|
+
? plannedSessionLoad(session.durationMin, session.zone, profile)
|
|
262
|
+
: null;
|
|
263
|
+
if (load === null) {
|
|
264
|
+
rejected.push(`${session.date}: give either load, or durationMin and zone (needs hrMax and hrRest)`);
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
byDate.set(session.date, (byDate.get(session.date) ?? 0) + load);
|
|
268
|
+
}
|
|
269
|
+
const lastDate = [...byDate.keys()].sort().pop();
|
|
270
|
+
if (lastDate) {
|
|
271
|
+
// Days of the plan without a session are rest days: load 0.
|
|
272
|
+
const planned = dateRange(addDays(date, 1), lastDate).map((day) => ({ date: day, load: byDate.get(day) ?? 0 }));
|
|
273
|
+
const projection = projectLoads(analysis.today, planned);
|
|
274
|
+
const end = projection[projection.length - 1];
|
|
275
|
+
result.projection = {
|
|
276
|
+
note: "Fitness-fatigue projection of the planned loads. Form (TSB) is fitness minus fatigue on the morning of each day.",
|
|
277
|
+
points: projection.filter((point, index) => byDate.has(point.date) || index === projection.length - 1),
|
|
278
|
+
atEnd: { date: end.date, fitness: end.ctl, fatigue: end.atl, formNextMorning: round(end.ctl - end.atl, 1) },
|
|
279
|
+
fitnessChange: round(end.ctl - analysis.today.ctl, 1),
|
|
280
|
+
peakFatigue: Math.max(...projection.map((point) => point.atl)),
|
|
281
|
+
lowestForm: Math.min(...projection.map((point) => point.tsb)),
|
|
282
|
+
rejected,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
result.projection = { rejected };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
// --- coach_activity_deep_dive ---------------------------------------------------------------------
|
|
292
|
+
const ACTIVITY_ID = /^\d{1,20}$/;
|
|
293
|
+
function requireActivityId(value) {
|
|
294
|
+
const id = typeof value === "number" ? String(value) : value;
|
|
295
|
+
if (typeof id !== "string" || !ACTIVITY_ID.test(id))
|
|
296
|
+
throw new ToolInputError("activityId must be a numeric Garmin activity id.");
|
|
297
|
+
return id;
|
|
298
|
+
}
|
|
299
|
+
/** `gc activities get` nests the figures under summaryDTO; flatten it to the list shape. */
|
|
300
|
+
function flattenActivityDetail(payload) {
|
|
301
|
+
const root = payload;
|
|
302
|
+
if (!root || typeof root !== "object")
|
|
303
|
+
return null;
|
|
304
|
+
const summary = (root.summaryDTO ?? {});
|
|
305
|
+
const start = typeof summary.startTimeLocal === "string" ? summary.startTimeLocal.replace("T", " ") : undefined;
|
|
306
|
+
return {
|
|
307
|
+
...summary,
|
|
308
|
+
activityId: root.activityId,
|
|
309
|
+
activityName: root.activityName,
|
|
310
|
+
activityType: root.activityTypeDTO ?? root.activityType,
|
|
311
|
+
startTimeLocal: start,
|
|
312
|
+
aerobicTrainingEffect: summary.trainingEffect ?? summary.aerobicTrainingEffect,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function zonesFromPayload(payload) {
|
|
316
|
+
if (!Array.isArray(payload))
|
|
317
|
+
return null;
|
|
318
|
+
const seconds = [0, 0, 0, 0, 0];
|
|
319
|
+
const floorsBpm = [0, 0, 0, 0, 0];
|
|
320
|
+
let found = false;
|
|
321
|
+
for (const raw of payload) {
|
|
322
|
+
const zone = raw?.zoneNumber;
|
|
323
|
+
if (!isNum(zone) || zone < 1 || zone > 5)
|
|
324
|
+
continue;
|
|
325
|
+
if (isNum(raw.secsInZone))
|
|
326
|
+
seconds[zone - 1] = raw.secsInZone;
|
|
327
|
+
if (isNum(raw.zoneLowBoundary))
|
|
328
|
+
floorsBpm[zone - 1] = raw.zoneLowBoundary;
|
|
329
|
+
found = true;
|
|
330
|
+
}
|
|
331
|
+
return found ? { seconds, floorsBpm } : null;
|
|
332
|
+
}
|
|
333
|
+
export async function activityDeepDive(deps, params) {
|
|
334
|
+
const id = requireActivityId(params.activityId);
|
|
335
|
+
const context = await loadContext(deps, { sync: false });
|
|
336
|
+
const [summary, splits, zones, weather] = await Promise.all([
|
|
337
|
+
deps.gc(["activities", "get", id]),
|
|
338
|
+
deps.gc(["activities", "splits", id]),
|
|
339
|
+
deps.gc(["activities", "hr-zones", id]),
|
|
340
|
+
deps.gc(["activities", "weather", id]),
|
|
341
|
+
]);
|
|
342
|
+
const errors = {};
|
|
343
|
+
for (const [name, result] of Object.entries({ summary, splits, zones, weather }))
|
|
344
|
+
if (!result.ok)
|
|
345
|
+
errors[name] = result.code;
|
|
346
|
+
const stored = context.store.activities[id] ?? null;
|
|
347
|
+
const activity = (summary.ok ? normalizeActivity(flattenActivityDetail(summary.data)) : null) ?? stored;
|
|
348
|
+
if (!activity)
|
|
349
|
+
return { activityId: id, errors, note: "Activity not found." };
|
|
350
|
+
const zoneData = zones.ok ? zonesFromPayload(zones.data) : null;
|
|
351
|
+
let profile = context.profile;
|
|
352
|
+
if (zoneData) {
|
|
353
|
+
activity.hrZonesS = zoneData.seconds;
|
|
354
|
+
// The activity's own zone boundaries are more exact than the configured percentages.
|
|
355
|
+
if (isNum(profile.hrMax) && zoneData.floorsBpm.every((value) => value > 0)) {
|
|
356
|
+
profile = { ...profile, hrZoneFloorsPctMax: zoneData.floorsBpm.map((bpm) => (bpm / profile.hrMax) * 100) };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const laps = splits.ok ? normalizeSplits(splits.data) : [];
|
|
360
|
+
const decoupling = aerobicDecoupling(laps);
|
|
361
|
+
const zoneTotal = activity.hrZonesS ? sum(activity.hrZonesS) : 0;
|
|
362
|
+
const w = weather.ok ? weather.data : null;
|
|
363
|
+
// Garmin's activity weather service reports degrees Fahrenheit.
|
|
364
|
+
const weatherC = isNum(w?.temp) ? round((w.temp - 32) * (5 / 9), 0) : null;
|
|
365
|
+
const flags = [];
|
|
366
|
+
if (isNum(weatherC) && weatherC >= 25)
|
|
367
|
+
flags.push(`heat (${weatherC} °C): heart rate is higher at a given pace, do not read it as lost fitness`);
|
|
368
|
+
if (decoupling && decoupling.decouplingPct > 5)
|
|
369
|
+
flags.push(`aerobic decoupling ${decoupling.decouplingPct} %: heart rate drifted upwards for the same output`);
|
|
370
|
+
if (isNum(activity.elevGainM) && isNum(activity.distanceM) && activity.elevGainM / activity.distanceM > 0.03) {
|
|
371
|
+
flags.push("hilly course: compare efforts with grade-adjusted pace or heart rate, not raw pace");
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
activityId: id,
|
|
375
|
+
algorithm: ACTIVITY_ALGORITHM,
|
|
376
|
+
summary: activityLine(activity, profile),
|
|
377
|
+
load: sessionLoad(activity, profile),
|
|
378
|
+
hrZones: activity.hrZonesS && zoneTotal > 0
|
|
379
|
+
? { minutes: activity.hrZonesS.map((seconds) => round(seconds / 60, 0)), pct: activity.hrZonesS.map((seconds) => round((seconds / zoneTotal) * 100, 0)), floorsBpm: zoneData?.floorsBpm ?? null }
|
|
380
|
+
: null,
|
|
381
|
+
decoupling,
|
|
382
|
+
efficiency: isNum(activity.avgHr) && isNum(activity.gapSpeedMs ?? activity.avgSpeedMs)
|
|
383
|
+
? { value: round(((activity.gapSpeedMs ?? activity.avgSpeedMs) * 60) / activity.avgHr, 3), unit: "m/min per bpm", note: "Compare only between similar efforts (same sport, duration, terrain, temperature)." }
|
|
384
|
+
: null,
|
|
385
|
+
splits: laps.slice(0, 60).map((lap, index) => {
|
|
386
|
+
const speed = lap.distanceM / lap.durationS;
|
|
387
|
+
const gradient = isNum(lap.elevGainM) || isNum(lap.elevLossM) ? ((lap.elevGainM ?? 0) - (lap.elevLossM ?? 0)) / lap.distanceM : null;
|
|
388
|
+
const flat = lap.gapSpeedMs ?? (gradient !== null ? gradeAdjustedSpeed(speed, gradient) : null);
|
|
389
|
+
return {
|
|
390
|
+
n: index + 1,
|
|
391
|
+
km: round(lap.distanceM / 1000, 2),
|
|
392
|
+
pace: paceText(speed),
|
|
393
|
+
gradeAdjustedPace: paceText(flat),
|
|
394
|
+
avgHr: lap.avgHr,
|
|
395
|
+
gainM: roundOrNull(lap.elevGainM, 0),
|
|
396
|
+
lossM: roundOrNull(lap.elevLossM, 0),
|
|
397
|
+
gradePct: gradient === null ? null : round(gradient * 100, 1),
|
|
398
|
+
};
|
|
399
|
+
}),
|
|
400
|
+
weather: w
|
|
401
|
+
? { temperatureC: weatherC, humidityPct: isNum(w.relativeHumidity) ? w.relativeHumidity : null, conditions: w.weatherTypeDTO?.desc ?? null, unitAssumption: "Garmin weather temperature converted from °F" }
|
|
402
|
+
: null,
|
|
403
|
+
deviceTemperatureC: { min: activity.tempMinC, max: activity.tempMaxC },
|
|
404
|
+
flags,
|
|
405
|
+
errors,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
// --- coach_zones_and_paces ------------------------------------------------------------------------
|
|
409
|
+
const STANDARD_DISTANCES = [
|
|
410
|
+
["5 km", 5000],
|
|
411
|
+
["10 km", 10000],
|
|
412
|
+
["half marathon", 21097.5],
|
|
413
|
+
["marathon", 42195],
|
|
414
|
+
];
|
|
415
|
+
export async function zonesAndPaces(deps, params) {
|
|
416
|
+
const context = await loadContext(deps, { sync: false });
|
|
417
|
+
const result = {
|
|
418
|
+
algorithm: ZONES_ALGORITHM,
|
|
419
|
+
profile: profileSummary(context.profile),
|
|
420
|
+
heartRateZones: zoneTables(context.profile),
|
|
421
|
+
zoneNote: "Prefer the threshold-anchored table when a recent lactate-threshold estimate exists. Zones from an age-predicted maximum are approximate (SD about 10 bpm). On steep or technical terrain use heart rate or perceived effort, not pace.",
|
|
422
|
+
};
|
|
423
|
+
if (isNum(params.raceDistanceM) && isNum(params.raceTimeS)) {
|
|
424
|
+
const value = vdot(params.raceDistanceM, params.raceTimeS);
|
|
425
|
+
if (value === null)
|
|
426
|
+
throw new ToolInputError("The race must last between 3.5 minutes and 5 hours.");
|
|
427
|
+
const paces = trainingPaces(value);
|
|
428
|
+
const text = (seconds) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}/km`;
|
|
429
|
+
const targets = isNum(params.targetDistanceM) ? [[`${params.targetDistanceM} m`, params.targetDistanceM]] : STANDARD_DISTANCES;
|
|
430
|
+
result.race = {
|
|
431
|
+
input: { distanceM: params.raceDistanceM, time: clock(params.raceTimeS) },
|
|
432
|
+
vdot: value,
|
|
433
|
+
trainingPaces: {
|
|
434
|
+
easy: `${text(paces.easy.slow)} to ${text(paces.easy.fast)}`,
|
|
435
|
+
marathon: text(paces.marathon),
|
|
436
|
+
threshold: text(paces.threshold),
|
|
437
|
+
interval: text(paces.interval),
|
|
438
|
+
repetition: text(paces.repetition),
|
|
439
|
+
},
|
|
440
|
+
predictions: targets.map(([label, meters]) => {
|
|
441
|
+
const byVdot = predictTimeFromVdot(value, meters);
|
|
442
|
+
return { distance: label, vdotModel: byVdot === null ? null : clock(byVdot), riegel: clock(riegel(params.raceTimeS, params.raceDistanceM, meters)) };
|
|
443
|
+
}),
|
|
444
|
+
note: "Flat-road equivalences from one race result. They assume training specific to the target distance and do not apply to trail or mountain races.",
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
return result;
|
|
448
|
+
}
|
|
449
|
+
// --- coach_strength_analysis ----------------------------------------------------------------------
|
|
450
|
+
export async function strengthAnalysis(deps, params) {
|
|
451
|
+
const id = requireActivityId(params.activityId);
|
|
452
|
+
const result = await deps.gc(["activities", "exercise-sets", id]);
|
|
453
|
+
if (!result.ok)
|
|
454
|
+
return { activityId: id, error: result.code, message: result.message };
|
|
455
|
+
const sets = parseExerciseSets(result.data);
|
|
456
|
+
return {
|
|
457
|
+
activityId: id,
|
|
458
|
+
algorithm: STRENGTH_ALGORITHM,
|
|
459
|
+
...summarizeStrength(sets),
|
|
460
|
+
notes: [
|
|
461
|
+
"Exercise names come from the watch's automatic recognition and can be wrong: confirm them with the athlete.",
|
|
462
|
+
"Estimated 1RM is computed only for sets of 1 to 10 repetitions, and assumes the set was taken close to failure.",
|
|
463
|
+
"No muscle-recovery score is computed: the watch records neither proximity to failure nor technique.",
|
|
464
|
+
],
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
// --- coach_journal_log / coach_journal_insights ---------------------------------------------------
|
|
468
|
+
const TAG = /^[a-z0-9][a-z0-9_]{0,39}$/;
|
|
469
|
+
export async function journalLog(deps, params) {
|
|
470
|
+
const now = deps.now?.() ?? new Date();
|
|
471
|
+
const today = todayIn(deps.config.timezone, now);
|
|
472
|
+
const date = resolveDate(params.date, today);
|
|
473
|
+
const tags = {};
|
|
474
|
+
for (const [rawKey, value] of Object.entries(params.tags ?? {})) {
|
|
475
|
+
const key = rawKey.trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
476
|
+
if (!TAG.test(key))
|
|
477
|
+
throw new ToolInputError(`Invalid tag name "${rawKey}": use letters, digits and underscores.`);
|
|
478
|
+
if (typeof value === "boolean" || (isNum(value) && value >= 0))
|
|
479
|
+
tags[key] = value;
|
|
480
|
+
else
|
|
481
|
+
throw new ToolInputError(`Tag "${rawKey}" must be true, false or a non-negative number.`);
|
|
482
|
+
}
|
|
483
|
+
const rating = (value, low, high, name) => {
|
|
484
|
+
if (value === undefined)
|
|
485
|
+
return undefined;
|
|
486
|
+
if (!isNum(value) || value < low || value > high)
|
|
487
|
+
throw new ToolInputError(`${name} must be between ${low} and ${high}.`);
|
|
488
|
+
return value;
|
|
489
|
+
};
|
|
490
|
+
const symptoms = Array.isArray(params.symptoms) ? params.symptoms.filter((item) => typeof item === "string").map((item) => item.slice(0, 80)).slice(0, 10) : undefined;
|
|
491
|
+
return exclusive(async () => {
|
|
492
|
+
const store = await loadStore(deps.config.dataDir);
|
|
493
|
+
const previous = store.journal[date];
|
|
494
|
+
const entry = {
|
|
495
|
+
...previous,
|
|
496
|
+
date,
|
|
497
|
+
tags: { ...previous?.tags, ...tags },
|
|
498
|
+
updatedAt: now.toISOString(),
|
|
499
|
+
};
|
|
500
|
+
const set = (key, value) => {
|
|
501
|
+
if (value !== undefined)
|
|
502
|
+
entry[key] = value;
|
|
503
|
+
};
|
|
504
|
+
set("rpe", rating(params.rpe, 0, 10, "rpe"));
|
|
505
|
+
set("fatigue", rating(params.fatigue, 1, 5, "fatigue"));
|
|
506
|
+
set("soreness", rating(params.soreness, 1, 5, "soreness"));
|
|
507
|
+
set("mood", rating(params.mood, 1, 5, "mood"));
|
|
508
|
+
set("sleepQuality", rating(params.sleepQuality, 1, 5, "sleepQuality"));
|
|
509
|
+
set("stress", rating(params.stress, 1, 5, "stress"));
|
|
510
|
+
set("symptoms", symptoms);
|
|
511
|
+
if (typeof params.notes === "string")
|
|
512
|
+
entry.notes = params.notes.slice(0, 500);
|
|
513
|
+
store.journal[date] = entry;
|
|
514
|
+
await saveStore(deps.config.dataDir, store);
|
|
515
|
+
return { saved: entry, entries: Object.keys(store.journal).length };
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
export async function journalInsights(deps, params) {
|
|
519
|
+
const context = await loadContext(deps, { sync: false });
|
|
520
|
+
const span = Math.min(Math.max(Math.round(params.days ?? 120), 30), deps.config.retentionDays);
|
|
521
|
+
const start = addDays(context.date, -(span - 1));
|
|
522
|
+
const days = Object.values(context.store.days).filter((day) => day.date >= start).sort((a, b) => a.date.localeCompare(b.date));
|
|
523
|
+
const journal = Object.values(context.store.journal).filter((entry) => entry.date >= start).sort((a, b) => a.date.localeCompare(b.date));
|
|
524
|
+
const ratings = (key) => roundOrNull(mean(valid(journal.slice(-7).map((entry) => entry[key]))), 1);
|
|
525
|
+
return {
|
|
526
|
+
windowDays: span,
|
|
527
|
+
journalDays: journal.length,
|
|
528
|
+
wellness7: { fatigue: ratings("fatigue"), soreness: ratings("soreness"), mood: ratings("mood"), sleepQuality: ratings("sleepQuality"), stress: ratings("stress"), scale: "1 = worst, 5 = best" },
|
|
529
|
+
...habitAssociations(days, journal),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
// --- coach_workout_push ---------------------------------------------------------------------------
|
|
533
|
+
const SPORTS = ["running", "cycling", "swimming", "strength_training", "walking", "hiking"];
|
|
534
|
+
const STEP_TYPES = ["warmup", "interval", "recovery", "cooldown", "rest"];
|
|
535
|
+
const TARGET = /^(?:no_target|(?:hr_zone|power_zone|pace_zone):[1-7]|(?:heart_rate|power|cadence):\d{2,4}(?:-\d{2,4})?)$/;
|
|
536
|
+
export async function workoutPush(deps, params) {
|
|
537
|
+
const name = typeof params.name === "string" ? params.name.trim() : "";
|
|
538
|
+
if (!name || name.length > 80)
|
|
539
|
+
throw new ToolInputError("name is required (80 characters at most).");
|
|
540
|
+
if (typeof params.sport !== "string" || !SPORTS.includes(params.sport))
|
|
541
|
+
throw new ToolInputError(`sport must be one of: ${SPORTS.join(", ")}.`);
|
|
542
|
+
if (!Array.isArray(params.steps) || !params.steps.length || params.steps.length > 60)
|
|
543
|
+
throw new ToolInputError("steps must hold 1 to 60 steps.");
|
|
544
|
+
const steps = [];
|
|
545
|
+
for (const raw of params.steps) {
|
|
546
|
+
if (!STEP_TYPES.includes(raw?.type))
|
|
547
|
+
throw new ToolInputError(`step type must be one of: ${STEP_TYPES.join(", ")}.`);
|
|
548
|
+
if (!isNum(raw.durationS) || raw.durationS < 10 || raw.durationS > 6 * 3600)
|
|
549
|
+
throw new ToolInputError("step durationS must be between 10 seconds and 6 hours.");
|
|
550
|
+
if (raw.target !== undefined && !TARGET.test(raw.target))
|
|
551
|
+
throw new ToolInputError(`invalid target "${raw.target}": use hr_zone:2, pace_zone:3, power_zone:4, heart_rate:150 or no_target.`);
|
|
552
|
+
steps.push({ type: raw.type, duration: Math.round(raw.durationS), ...(raw.target ? { target: raw.target } : {}) });
|
|
553
|
+
}
|
|
554
|
+
const context = await loadContext(deps, { sync: false });
|
|
555
|
+
let load = 0;
|
|
556
|
+
for (const step of steps) {
|
|
557
|
+
const zone = /^hr_zone:(\d)$/.exec(step.target ?? "");
|
|
558
|
+
// Steps without a heart-rate zone are assumed easy (zone 1 for rest/recovery, 2 otherwise).
|
|
559
|
+
const assumed = zone ? Number(zone[1]) : step.type === "rest" || step.type === "recovery" ? 1 : 2;
|
|
560
|
+
const part = plannedSessionLoad(step.duration / 60, Math.min(assumed, 5), context.profile);
|
|
561
|
+
load = part === null || load === null ? null : load + part;
|
|
562
|
+
}
|
|
563
|
+
const preview = {
|
|
564
|
+
name,
|
|
565
|
+
sport: params.sport,
|
|
566
|
+
totalMin: round(sum(steps.map((step) => step.duration)) / 60, 0),
|
|
567
|
+
steps,
|
|
568
|
+
estimatedLoad: load === null ? null : round(load, 0),
|
|
569
|
+
currentFitness: analyzeLoad(context.loads, context.activities, context.profile).today?.ctl ?? null,
|
|
570
|
+
};
|
|
571
|
+
if (!deps.config.allowWorkoutPush) {
|
|
572
|
+
return { created: false, preview, message: "Writing to Garmin Connect is disabled. Set allowWorkoutPush: true in the plugin config to enable it." };
|
|
573
|
+
}
|
|
574
|
+
if (params.confirm !== true) {
|
|
575
|
+
return { created: false, preview, message: "Preview only. Show it to the athlete; call again with confirm: true once they agree." };
|
|
576
|
+
}
|
|
577
|
+
const result = await deps.gc(["workouts", "create", "--name", name, "--sport", params.sport, "--steps", JSON.stringify(steps)], { timeoutMs: 60_000 });
|
|
578
|
+
if (result.ok) {
|
|
579
|
+
const data = result.data;
|
|
580
|
+
return { created: true, workoutId: data?.workoutId ?? null, preview, message: "Workout created in Garmin Connect. It reaches the watch at the next sync; it is not scheduled on a date." };
|
|
581
|
+
}
|
|
582
|
+
// gc prints a plain confirmation instead of JSON when Garmin returns no body.
|
|
583
|
+
if (result.code === "parse_error")
|
|
584
|
+
return { created: true, workoutId: null, preview, message: "Workout created (Garmin returned no identifier)." };
|
|
585
|
+
return { created: false, preview, error: result.code, message: result.message };
|
|
586
|
+
}
|
|
587
|
+
// --- coach_data_status ----------------------------------------------------------------------------
|
|
588
|
+
export async function dataStatus(deps, params) {
|
|
589
|
+
const context = await loadContext(deps, { sync: params.sync === true });
|
|
590
|
+
const cover = coverage(context.store, context.date, deps.config.historyDays);
|
|
591
|
+
const advice = [];
|
|
592
|
+
if (context.sync?.errors.daily === "unsupported" || context.sync?.errors.recent === "unsupported")
|
|
593
|
+
advice.push("Update garmin-cli to 0.4.0 or later: the `gc daily` command is missing.");
|
|
594
|
+
if (Object.values(context.sync?.errors ?? {}).includes("not_configured"))
|
|
595
|
+
advice.push("The gc binary was not found: install garmin-cli or set gcBinary in the plugin config.");
|
|
596
|
+
if (Object.values(context.sync?.errors ?? {}).includes("auth"))
|
|
597
|
+
advice.push("Run `gc login` in the Gateway environment.");
|
|
598
|
+
if (cover.daysWithHrv < 14)
|
|
599
|
+
advice.push(`HRV baseline needs 14 nights; ${cover.daysWithHrv} available.`);
|
|
600
|
+
if (!isNum(context.profile.hrMax))
|
|
601
|
+
advice.push("Set hrMax (measured maximum heart rate) in the plugin config: training load cannot be computed without it.");
|
|
602
|
+
if (context.profile.hrMaxSource === "age-formula")
|
|
603
|
+
advice.push("hrMax comes from an age formula: replace it with a measured value when possible.");
|
|
604
|
+
if (!context.profile.sex)
|
|
605
|
+
advice.push("Set sex in the plugin config for the correct training-load coefficients.");
|
|
606
|
+
return {
|
|
607
|
+
date: context.date,
|
|
608
|
+
timezone: deps.config.timezone,
|
|
609
|
+
dataDir: deps.config.dataDir,
|
|
610
|
+
sync: context.sync ?? "not requested (pass sync: true)",
|
|
611
|
+
coverage: cover,
|
|
612
|
+
profile: profileSummary(context.profile),
|
|
613
|
+
retentionDays: deps.config.retentionDays,
|
|
614
|
+
advice,
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
// --- coach_briefing_charts ------------------------------------------------------------------------
|
|
618
|
+
export const CHART_IDS = ["recovery_gauge", "ceiling", "signals", "hrv_trend", "load_curve", "sleep_nights"];
|
|
619
|
+
const CHART_KEEP_DAYS = 14;
|
|
620
|
+
/** Deletes chart folders (YYYY-MM-DD) older than the retention, never anything else. */
|
|
621
|
+
async function pruneCharts(root, today) {
|
|
622
|
+
let names;
|
|
623
|
+
try {
|
|
624
|
+
names = await fs.readdir(root);
|
|
625
|
+
}
|
|
626
|
+
catch {
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
const limit = addDays(today, -CHART_KEEP_DAYS);
|
|
630
|
+
for (const name of names) {
|
|
631
|
+
if (isIsoDate(name) && name < limit)
|
|
632
|
+
await fs.rm(path.join(root, name), { recursive: true, force: true });
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
export async function briefingCharts(deps, params) {
|
|
636
|
+
const requested = params.charts?.length ? params.charts : [...CHART_IDS];
|
|
637
|
+
for (const id of requested) {
|
|
638
|
+
if (!CHART_IDS.includes(id))
|
|
639
|
+
throw new ToolInputError(`Unknown chart '${id}'. Available: ${CHART_IDS.join(", ")}.`);
|
|
640
|
+
}
|
|
641
|
+
if (params.theme !== undefined && params.theme !== "light" && params.theme !== "dark")
|
|
642
|
+
throw new ToolInputError("theme must be 'light' or 'dark'.");
|
|
643
|
+
if (params.lang !== undefined && params.lang !== "en" && params.lang !== "fr")
|
|
644
|
+
throw new ToolInputError("lang must be 'en' or 'fr'.");
|
|
645
|
+
const lang = params.lang ?? deps.config.language;
|
|
646
|
+
const theme = THEMES[params.theme ?? "light"];
|
|
647
|
+
const context = await loadContext(deps, params);
|
|
648
|
+
const { days, activities, loads, profile, date, store } = context;
|
|
649
|
+
const hrv = analyzeHrv(days);
|
|
650
|
+
const sleep = analyzeSleep(days, profile);
|
|
651
|
+
const recovery = analyzeRecovery(days, profile);
|
|
652
|
+
const warning = analyzeWarning(days);
|
|
653
|
+
const load = analyzeLoad(loads, activities, profile);
|
|
654
|
+
const readiness = decideReadiness({ hrv, recovery, warning, sleep, load, journal: store.journal[date] ?? null });
|
|
655
|
+
const common = { theme, lang };
|
|
656
|
+
const builders = {
|
|
657
|
+
recovery_gauge: () => recoveryGauge({ ...common, score: recovery.score, band: recovery.band }),
|
|
658
|
+
ceiling: () => ceilingLadder({ ...common, ceiling: readiness.ceiling, suggestedLoad: readiness.suggestedLoad }),
|
|
659
|
+
signals: () => {
|
|
660
|
+
const rows = recovery.deviations;
|
|
661
|
+
if (!Object.values(rows).some((row) => row.z !== null))
|
|
662
|
+
return "No overnight signal has a personal baseline yet (about 14 nights are needed).";
|
|
663
|
+
return signalsChart({ ...common, rows });
|
|
664
|
+
},
|
|
665
|
+
hrv_trend: () => {
|
|
666
|
+
const window = days.slice(-28);
|
|
667
|
+
const series = days.map(lnRmssd);
|
|
668
|
+
const points = window.map((day, index) => {
|
|
669
|
+
const end = days.length - window.length + index;
|
|
670
|
+
const trend = valid(series.slice(Math.max(0, end - 6), end + 1));
|
|
671
|
+
const ln = series[end];
|
|
672
|
+
return { date: day.date, ms: ln === null ? null : Math.exp(ln), trendMs: trend.length >= 3 ? Math.exp(mean(trend)) : null };
|
|
673
|
+
});
|
|
674
|
+
if (!points.some((point) => point.ms !== null))
|
|
675
|
+
return "No HRV value in the last 28 days.";
|
|
676
|
+
return hrvChart({ ...common, points, range: hrv.baseline ? { lowMs: hrv.baseline.lowMs, highMs: hrv.baseline.highMs } : null });
|
|
677
|
+
},
|
|
678
|
+
load_curve: () => {
|
|
679
|
+
const curve = fitnessFatigue(loads).slice(-56);
|
|
680
|
+
if (curve.length < 14)
|
|
681
|
+
return "Fewer than 14 days of load history.";
|
|
682
|
+
return loadChart({ ...common, points: curve });
|
|
683
|
+
},
|
|
684
|
+
sleep_nights: () => {
|
|
685
|
+
const nights = days.slice(-14).map((day) => {
|
|
686
|
+
const night = describeNight(day, profile);
|
|
687
|
+
const s = day.sleep;
|
|
688
|
+
const hours = (seconds) => (isNum(seconds) ? seconds / 3600 : null);
|
|
689
|
+
return { date: day.date, hours: night?.durationH ?? null, deepH: hours(s?.deepS), lightH: hours(s?.lightS), remH: hours(s?.remS), needH: night?.needH ?? profile.sleepNeedS / 3600 };
|
|
690
|
+
});
|
|
691
|
+
if (!nights.some((night) => night.hours !== null))
|
|
692
|
+
return "No sleep recorded in the last 14 nights.";
|
|
693
|
+
return sleepChart({ ...common, nights });
|
|
694
|
+
},
|
|
695
|
+
};
|
|
696
|
+
const folder = path.join(deps.config.dataDir, "charts");
|
|
697
|
+
const directory = path.join(folder, date);
|
|
698
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
699
|
+
const charts = [];
|
|
700
|
+
const skipped = [];
|
|
701
|
+
for (const id of requested) {
|
|
702
|
+
const built = builders[id]();
|
|
703
|
+
if (typeof built === "string") {
|
|
704
|
+
skipped.push({ id, reason: built });
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
const rendered = await renderPng(built.svg);
|
|
708
|
+
const file = path.join(directory, `${id}.png`);
|
|
709
|
+
await fs.writeFile(file, rendered.png, { mode: 0o600 });
|
|
710
|
+
charts.push({ id, path: file, cid: `coach-${id}`, displayWidth: built.width, displayHeight: built.height, pixelWidth: rendered.width, pixelHeight: rendered.height, bytes: rendered.png.length, alt: built.alt });
|
|
711
|
+
}
|
|
712
|
+
await pruneCharts(folder, context.today);
|
|
713
|
+
return {
|
|
714
|
+
date,
|
|
715
|
+
lang,
|
|
716
|
+
theme: theme.name,
|
|
717
|
+
charts,
|
|
718
|
+
skipped,
|
|
719
|
+
usage: "Each chart is a PNG file. To embed it in an email, pass { cid, path } in send_email's inlineImages and reference it in the HTML as " +
|
|
720
|
+
'<img src="cid:CID" width="displayWidth" alt="alt" style="display:block;max-width:100%;height:auto">. Gauge and ceiling are 280 px wide: place them side by side in a two-cell table.',
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
// --- coach_briefing_email -------------------------------------------------------------------------
|
|
724
|
+
const EMAIL_CHARTS = ["recovery_gauge", "ceiling", "signals", "hrv_trend", "sleep_nights"];
|
|
725
|
+
const MAX_LINE = 240;
|
|
726
|
+
function textList(value, name, max) {
|
|
727
|
+
if (value === undefined || value === null)
|
|
728
|
+
return undefined;
|
|
729
|
+
if (!Array.isArray(value) || value.length > max)
|
|
730
|
+
throw new ToolInputError(`${name} must be a list of at most ${max} short texts.`);
|
|
731
|
+
return value.map((item) => {
|
|
732
|
+
if (typeof item !== "string" || !item.trim() || item.length > MAX_LINE)
|
|
733
|
+
throw new ToolInputError(`Each item of ${name} must be a non-empty text of at most ${MAX_LINE} characters.`);
|
|
734
|
+
return item.trim();
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* The whole daily briefing e-mail, built in code: subject, HTML, plain text and the inline-image list,
|
|
739
|
+
* ready to pass to any mail tool. The model may supply the three sentences that need judgement (headline,
|
|
740
|
+
* why, watch) in the athlete's language; everything else is deterministic.
|
|
741
|
+
*/
|
|
742
|
+
export async function briefingEmail(deps, params) {
|
|
743
|
+
if (params.lang !== undefined && params.lang !== "en" && params.lang !== "fr")
|
|
744
|
+
throw new ToolInputError("lang must be 'en' or 'fr'.");
|
|
745
|
+
const lang = params.lang ?? deps.config.language;
|
|
746
|
+
if (params.headline !== undefined && params.headline !== null && (typeof params.headline !== "string" || !params.headline.trim() || params.headline.length > MAX_LINE)) {
|
|
747
|
+
throw new ToolInputError(`headline must be one non-empty sentence of at most ${MAX_LINE} characters.`);
|
|
748
|
+
}
|
|
749
|
+
const why = textList(params.why, "why", 3);
|
|
750
|
+
const watch = textList(params.watch, "watch", 4);
|
|
751
|
+
const headline = typeof params.headline === "string" ? params.headline.trim() : undefined;
|
|
752
|
+
// One sync at most: the briefing fetches, the charts reuse the local store.
|
|
753
|
+
const briefing = await dailyBriefing(deps, { date: params.date, sync: params.sync });
|
|
754
|
+
const weekly = params.weekly ?? new Date(`${briefing.date}T12:00:00Z`).getUTCDay() === 0;
|
|
755
|
+
const charts = await briefingCharts(deps, { date: briefing.date, sync: false, lang, theme: "light", charts: weekly ? [...EMAIL_CHARTS, "load_curve"] : EMAIL_CHARTS });
|
|
756
|
+
const night = briefing.sleep.lastNight;
|
|
757
|
+
const sessions = briefing.activities.yesterday.map((line) => ({ type: line.type, name: line.name, durationMin: line.durationMin, avgHr: line.avgHr, load: line.load }));
|
|
758
|
+
const email = renderBriefingEmail({
|
|
759
|
+
lang,
|
|
760
|
+
date: briefing.date,
|
|
761
|
+
ceiling: briefing.readiness.ceiling,
|
|
762
|
+
headline: headline || defaultHeadline(lang, briefing.readiness.ceiling),
|
|
763
|
+
// The rules and caveats of the models are written in English: they are a fallback for English mails only,
|
|
764
|
+
// never mixed into a French one.
|
|
765
|
+
why: why ?? (lang === "en" ? briefing.readiness.reasons.slice(0, 3).map((reason) => reason.detail) : []),
|
|
766
|
+
watch: watch ?? (lang === "en" ? briefing.readiness.caveats.slice(0, 4) : []),
|
|
767
|
+
charts: charts.charts.map((chart) => ({ id: chart.id, cid: chart.cid, displayWidth: chart.displayWidth, alt: chart.alt })),
|
|
768
|
+
sleep: night ? { durationH: night.durationH, needH: night.needH, efficiencyPct: night.efficiencyPct, bedtime: night.bedtime, wakeTime: night.wakeTime } : null,
|
|
769
|
+
sessions,
|
|
770
|
+
load: briefing.load.today ? { ctl: briefing.load.today.ctl, atl: briefing.load.today.atl, tsb: briefing.load.today.tsb, weekChangePct: briefing.load.weekChangePct } : null,
|
|
771
|
+
});
|
|
772
|
+
return {
|
|
773
|
+
date: briefing.date,
|
|
774
|
+
lang,
|
|
775
|
+
ceiling: briefing.readiness.ceiling,
|
|
776
|
+
status: { recovery: briefing.recovery.status, sleep: briefing.sleep.status, load: briefing.load.status },
|
|
777
|
+
subject: email.subject,
|
|
778
|
+
bodyHtml: email.html,
|
|
779
|
+
bodyText: email.text,
|
|
780
|
+
inlineImages: charts.charts.map((chart) => ({ cid: chart.cid, path: chart.path })),
|
|
781
|
+
skipped: charts.skipped,
|
|
782
|
+
notes: [
|
|
783
|
+
...(headline === undefined ? ["headline not supplied: a generic sentence was used."] : []),
|
|
784
|
+
...(why === undefined && lang !== "en" ? ["why not supplied: the section is omitted (default texts are English). Call again with why."] : []),
|
|
785
|
+
...(watch === undefined && lang !== "en" ? ["watch not supplied: the section is omitted (default texts are English). Call again with watch, or [] if there is nothing to watch."] : []),
|
|
786
|
+
],
|
|
787
|
+
usage: "Send subject, bodyHtml, bodyText and inlineImages unchanged with a mail tool that supports inline images by content id (send_email does). " +
|
|
788
|
+
"Do not rewrite the HTML. To personalise, call this tool again with headline (one sentence on what to do today), why (up to 3 bullets) " +
|
|
789
|
+
"and watch (up to 4 cautions) written in the athlete's language, using only figures from coach_daily_briefing. " +
|
|
790
|
+
"If images cannot be sent, send bodyText alone: the key figures are in it.",
|
|
791
|
+
};
|
|
792
|
+
}
|