@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.
Files changed (64) hide show
  1. package/README.md +323 -66
  2. package/assets/fonts/Inter_400Regular.ttf +0 -0
  3. package/assets/fonts/Inter_600SemiBold.ttf +0 -0
  4. package/assets/fonts/LICENSE.txt +93 -0
  5. package/assets/icon.png +0 -0
  6. package/assets/logo.png +0 -0
  7. package/assets/logo.svg +62 -0
  8. package/dist/charts/build.d.ts +71 -0
  9. package/dist/charts/build.js +276 -0
  10. package/dist/charts/labels.d.ts +38 -0
  11. package/dist/charts/labels.js +73 -0
  12. package/dist/charts/render.d.ts +10 -0
  13. package/dist/charts/render.js +26 -0
  14. package/dist/charts/svg.d.ts +47 -0
  15. package/dist/charts/svg.js +92 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +38 -0
  18. package/dist/dates.d.ts +22 -0
  19. package/dist/dates.js +71 -0
  20. package/dist/email.d.ts +58 -0
  21. package/dist/email.js +188 -0
  22. package/dist/garmin/gc.d.ts +25 -0
  23. package/dist/garmin/gc.js +81 -0
  24. package/dist/garmin/normalize.d.ts +20 -0
  25. package/dist/garmin/normalize.js +132 -0
  26. package/dist/index.js +207 -163
  27. package/dist/profile.d.ts +4 -0
  28. package/dist/profile.js +43 -0
  29. package/dist/science/associations.d.ts +56 -0
  30. package/dist/science/associations.js +102 -0
  31. package/dist/science/healthspan.d.ts +25 -0
  32. package/dist/science/healthspan.js +89 -0
  33. package/dist/science/hrv.d.ts +61 -0
  34. package/dist/science/hrv.js +119 -0
  35. package/dist/science/load.d.ts +107 -0
  36. package/dist/science/load.js +228 -0
  37. package/dist/science/performance.d.ts +93 -0
  38. package/dist/science/performance.js +191 -0
  39. package/dist/science/readiness.d.ts +47 -0
  40. package/dist/science/readiness.js +97 -0
  41. package/dist/science/recovery.d.ts +74 -0
  42. package/dist/science/recovery.js +173 -0
  43. package/dist/science/sleep.d.ts +79 -0
  44. package/dist/science/sleep.js +165 -0
  45. package/dist/science/stats.d.ts +50 -0
  46. package/dist/science/stats.js +201 -0
  47. package/dist/science/strength.d.ts +47 -0
  48. package/dist/science/strength.js +120 -0
  49. package/dist/store.d.ts +36 -0
  50. package/dist/store.js +78 -0
  51. package/dist/sync.d.ts +36 -0
  52. package/dist/sync.js +145 -0
  53. package/dist/tools.d.ts +463 -0
  54. package/dist/tools.js +792 -0
  55. package/dist/types.d.ts +143 -0
  56. package/dist/types.js +2 -0
  57. package/docs/SCIENCE.md +721 -0
  58. package/examples/ATHLETE-fr.md +72 -0
  59. package/examples/ATHLETE.md +74 -0
  60. package/examples/PLAN-fr.md +55 -0
  61. package/examples/PLAN.md +55 -0
  62. package/openclaw.plugin.json +158 -5
  63. package/package.json +14 -3
  64. package/skills/coach/SKILL.md +291 -208
@@ -0,0 +1,25 @@
1
+ /** Plugin configuration: parsing and defaults. Invalid values fall back to the default. */
2
+ import type { Sex } from "./types.ts";
3
+ export type CoachConfig = {
4
+ gcBinary: string;
5
+ timezone: string;
6
+ dataDir: string;
7
+ /** Days of recovery history kept in sync (baselines need 60 + margin). */
8
+ historyDays: number;
9
+ /** Days of activity history used for the load model. */
10
+ loadHistoryDays: number;
11
+ retentionDays: number;
12
+ cacheMinutes: number;
13
+ sex: Sex | null;
14
+ birthYear: number | null;
15
+ hrMax: number | null;
16
+ hrRest: number | null;
17
+ lthr: number | null;
18
+ sleepNeedHours: number | null;
19
+ hrZoneFloorsPctMax: number[];
20
+ allowWorkoutPush: boolean;
21
+ /** Language of chart labels. */
22
+ language: "en" | "fr";
23
+ };
24
+ export declare const DEFAULT_ZONE_FLOORS: number[];
25
+ export declare function parseConfig(raw: unknown): CoachConfig;
package/dist/config.js ADDED
@@ -0,0 +1,38 @@
1
+ /** Plugin configuration: parsing and defaults. Invalid values fall back to the default. */
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isValidTimezone } from "./dates.js";
5
+ export const DEFAULT_ZONE_FLOORS = [50, 60, 70, 80, 90];
6
+ function text(value) {
7
+ return typeof value === "string" && value.trim() ? value.trim() : null;
8
+ }
9
+ function numberIn(value, low, high) {
10
+ return typeof value === "number" && Number.isFinite(value) && value >= low && value <= high ? value : null;
11
+ }
12
+ export function parseConfig(raw) {
13
+ const cfg = (raw && typeof raw === "object" ? raw : {});
14
+ const timezone = text(cfg.timezone);
15
+ const floors = Array.isArray(cfg.hrZoneFloorsPctMax) ? cfg.hrZoneFloorsPctMax : null;
16
+ const floorsValid = floors !== null &&
17
+ floors.length === 5 &&
18
+ floors.every((value, index) => numberIn(value, 30, 99) !== null && (index === 0 || value > floors[index - 1]));
19
+ const sex = text(cfg.sex);
20
+ return {
21
+ gcBinary: text(cfg.gcBinary) ?? "gc",
22
+ timezone: timezone && isValidTimezone(timezone) ? timezone : Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
23
+ dataDir: text(cfg.dataDir) ?? path.join(os.homedir(), ".openclaw", "coach"),
24
+ historyDays: numberIn(cfg.historyDays, 30, 365) ?? 90,
25
+ loadHistoryDays: numberIn(cfg.loadHistoryDays, 42, 365) ?? 180,
26
+ retentionDays: numberIn(cfg.retentionDays, 90, 3650) ?? 730,
27
+ cacheMinutes: numberIn(cfg.cacheMinutes, 0, 1440) ?? 15,
28
+ sex: sex === "male" || sex === "female" ? sex : null,
29
+ birthYear: numberIn(cfg.birthYear, 1920, 2020),
30
+ hrMax: numberIn(cfg.hrMax, 120, 230),
31
+ hrRest: numberIn(cfg.hrRest, 25, 100),
32
+ lthr: numberIn(cfg.lthr, 100, 210),
33
+ sleepNeedHours: numberIn(cfg.sleepNeedHours, 6, 10),
34
+ hrZoneFloorsPctMax: floorsValid ? floors : DEFAULT_ZONE_FLOORS,
35
+ allowWorkoutPush: cfg.allowWorkoutPush === true,
36
+ language: text(cfg.language)?.toLowerCase().startsWith("fr") ? "fr" : "en",
37
+ };
38
+ }
@@ -0,0 +1,22 @@
1
+ /** Calendar-date helpers. Dates are `YYYY-MM-DD` strings in the athlete's timezone. */
2
+ export declare function isIsoDate(value: unknown): value is string;
3
+ export declare function addDays(date: string, days: number): string;
4
+ /** Whole days from `from` to `to` (positive when `to` is later). */
5
+ export declare function daysBetween(from: string, to: string): number;
6
+ /** Every date from `start` to `end`, both included. */
7
+ export declare function dateRange(start: string, end: string): string[];
8
+ /** 0 = Monday ... 6 = Sunday. */
9
+ export declare function weekdayIndex(date: string): number;
10
+ /** Monday of the week containing `date`. */
11
+ export declare function weekStart(date: string): string;
12
+ /** Today's calendar date in an IANA timezone. */
13
+ export declare function todayIn(timezone: string, now?: Date): string;
14
+ export declare function isValidTimezone(timezone: string): boolean;
15
+ /**
16
+ * Minutes after midnight of a local wall-clock timestamp (`YYYY-MM-DDTHH:MM:SS`,
17
+ * no zone suffix, as written by `gc daily`).
18
+ */
19
+ export declare function clockMinutes(localIso: string | null | undefined): number | null;
20
+ /** Epoch minutes of a local wall-clock timestamp, read as if it were UTC. */
21
+ export declare function localEpochMinutes(localIso: string | null | undefined): number | null;
22
+ export declare function formatClock(minutes: number): string;
package/dist/dates.js ADDED
@@ -0,0 +1,71 @@
1
+ /** Calendar-date helpers. Dates are `YYYY-MM-DD` strings in the athlete's timezone. */
2
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
3
+ const DAY_MS = 86_400_000;
4
+ export function isIsoDate(value) {
5
+ if (typeof value !== "string" || !ISO_DATE.test(value))
6
+ return false;
7
+ const time = Date.parse(`${value}T00:00:00Z`);
8
+ return Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === value;
9
+ }
10
+ function toUtc(date) {
11
+ return Date.parse(`${date}T00:00:00Z`);
12
+ }
13
+ export function addDays(date, days) {
14
+ return new Date(toUtc(date) + days * DAY_MS).toISOString().slice(0, 10);
15
+ }
16
+ /** Whole days from `from` to `to` (positive when `to` is later). */
17
+ export function daysBetween(from, to) {
18
+ return Math.round((toUtc(to) - toUtc(from)) / DAY_MS);
19
+ }
20
+ /** Every date from `start` to `end`, both included. */
21
+ export function dateRange(start, end) {
22
+ const out = [];
23
+ for (let day = start; day <= end; day = addDays(day, 1))
24
+ out.push(day);
25
+ return out;
26
+ }
27
+ /** 0 = Monday ... 6 = Sunday. */
28
+ export function weekdayIndex(date) {
29
+ return (new Date(toUtc(date)).getUTCDay() + 6) % 7;
30
+ }
31
+ /** Monday of the week containing `date`. */
32
+ export function weekStart(date) {
33
+ return addDays(date, -weekdayIndex(date));
34
+ }
35
+ /** Today's calendar date in an IANA timezone. */
36
+ export function todayIn(timezone, now = new Date()) {
37
+ // The en-CA locale formats dates as YYYY-MM-DD.
38
+ return new Intl.DateTimeFormat("en-CA", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
39
+ }
40
+ export function isValidTimezone(timezone) {
41
+ try {
42
+ new Intl.DateTimeFormat("en-CA", { timeZone: timezone });
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /**
50
+ * Minutes after midnight of a local wall-clock timestamp (`YYYY-MM-DDTHH:MM:SS`,
51
+ * no zone suffix, as written by `gc daily`).
52
+ */
53
+ export function clockMinutes(localIso) {
54
+ if (typeof localIso !== "string")
55
+ return null;
56
+ const match = /T(\d{2}):(\d{2})/.exec(localIso);
57
+ if (!match)
58
+ return null;
59
+ return Number(match[1]) * 60 + Number(match[2]);
60
+ }
61
+ /** Epoch minutes of a local wall-clock timestamp, read as if it were UTC. */
62
+ export function localEpochMinutes(localIso) {
63
+ if (typeof localIso !== "string")
64
+ return null;
65
+ const time = Date.parse(`${localIso.slice(0, 19)}Z`);
66
+ return Number.isFinite(time) ? Math.round(time / 60_000) : null;
67
+ }
68
+ export function formatClock(minutes) {
69
+ const wrapped = ((Math.round(minutes) % 1440) + 1440) % 1440;
70
+ return `${String(Math.floor(wrapped / 60)).padStart(2, "0")}:${String(wrapped % 60).padStart(2, "0")}`;
71
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The daily briefing as an e-mail: HTML (tables, inline CSS, one centred column), plain text and
3
+ * subject, built from results the models already computed. Pure functions, no I/O: the same input gives
4
+ * the same bytes, so the layout is tested and does not depend on which model assembles the message.
5
+ * Every text that comes from outside (the model's sentence and bullets) is escaped.
6
+ */
7
+ import { type Lang } from "./charts/labels.ts";
8
+ import type { Ceiling } from "./science/readiness.ts";
9
+ export type EmailChart = {
10
+ id: string;
11
+ cid: string;
12
+ displayWidth: number;
13
+ alt: string;
14
+ };
15
+ export type EmailSession = {
16
+ type: string | null;
17
+ name: string | null;
18
+ durationMin: number | null;
19
+ avgHr: number | null;
20
+ load: number | null;
21
+ };
22
+ export type EmailInput = {
23
+ lang: Lang;
24
+ date: string;
25
+ ceiling: Ceiling;
26
+ /** One sentence: what to do today. */
27
+ headline: string;
28
+ /** At most 3 bullets, main cause first. */
29
+ why: string[];
30
+ /** Cautions only. */
31
+ watch: string[];
32
+ charts: EmailChart[];
33
+ sleep: {
34
+ durationH: number | null;
35
+ needH: number | null;
36
+ efficiencyPct: number | null;
37
+ bedtime: string | null;
38
+ wakeTime: string | null;
39
+ } | null;
40
+ /** Sessions of the previous day. */
41
+ sessions: EmailSession[];
42
+ load: {
43
+ ctl: number | null;
44
+ atl: number | null;
45
+ tsb: number | null;
46
+ weekChangePct: number | null;
47
+ } | null;
48
+ };
49
+ export type BriefingEmail = {
50
+ subject: string;
51
+ html: string;
52
+ text: string;
53
+ };
54
+ export declare function defaultHeadline(lang: Lang, ceiling: Ceiling): string;
55
+ export declare function escapeHtml(value: string): string;
56
+ /** "mardi 17 novembre" / "Tuesday, November 17" for an ISO date, independent of the host time zone. */
57
+ export declare function longDate(date: string, lang: Lang): string;
58
+ export declare function renderBriefingEmail(input: EmailInput): BriefingEmail;
package/dist/email.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The daily briefing as an e-mail: HTML (tables, inline CSS, one centred column), plain text and
3
+ * subject, built from results the models already computed. Pure functions, no I/O: the same input gives
4
+ * the same bytes, so the layout is tested and does not depend on which model assembles the message.
5
+ * Every text that comes from outside (the model's sentence and bullets) is escaped.
6
+ */
7
+ import { LABELS } from "./charts/labels.js";
8
+ import { THEMES } from "./charts/svg.js";
9
+ const STRINGS = {
10
+ en: {
11
+ subject: (weekdayDate, ceiling) => `Briefing for ${weekdayDate}: ${ceiling}`,
12
+ banner: "Today's ceiling",
13
+ why: "Why",
14
+ watch: "To watch",
15
+ sleep: "Sleep",
16
+ yesterday: "Yesterday's session",
17
+ load: "Load",
18
+ duration: "Duration",
19
+ efficiency: "Efficiency",
20
+ bedtime: "Bedtime",
21
+ wake: "Wake-up",
22
+ noSession: "No session yesterday",
23
+ hr: "avg HR",
24
+ week: "7 days",
25
+ noData: "n/a",
26
+ footerFeel: "Tell me how you feel (fatigue, pain, motivation).",
27
+ footerDisclaimer: "This message is a training aid, not medical advice.",
28
+ meaning: {
29
+ rest: "Rest or very light movement only today.",
30
+ easy: "Easy aerobic session today (zones 1-2), no intensity.",
31
+ moderate: "Steady aerobic or tempo work is fine today; skip maximal or very long efforts.",
32
+ hard: "Nothing argues against your planned hard or long session today.",
33
+ },
34
+ },
35
+ fr: {
36
+ subject: (weekdayDate, ceiling) => `Briefing du ${weekdayDate} : ${ceiling}`,
37
+ banner: "Plafond du jour",
38
+ why: "Pourquoi",
39
+ watch: "À surveiller",
40
+ sleep: "Sommeil",
41
+ yesterday: "Séance d'hier",
42
+ load: "Charge",
43
+ duration: "Durée",
44
+ efficiency: "Efficacité",
45
+ bedtime: "Coucher",
46
+ wake: "Réveil",
47
+ noSession: "Aucune séance hier",
48
+ hr: "FC moy.",
49
+ week: "7 j",
50
+ noData: "n/d",
51
+ footerFeel: "Dis-moi comment tu te sens (fatigue, douleurs, motivation).",
52
+ footerDisclaimer: "Ce message est une aide à l'entraînement, pas un avis médical.",
53
+ meaning: {
54
+ rest: "Repos ou mouvement très léger uniquement aujourd'hui.",
55
+ easy: "Séance aérobie légère (zones 1-2) aujourd'hui, sans intensité.",
56
+ moderate: "Aérobie soutenu ou allure tempo possible ; évite les efforts maximaux ou très longs.",
57
+ hard: "Rien ne s'oppose à ta séance intense ou longue prévue aujourd'hui.",
58
+ },
59
+ },
60
+ };
61
+ export function defaultHeadline(lang, ceiling) {
62
+ return STRINGS[lang].meaning[ceiling];
63
+ }
64
+ export function escapeHtml(value) {
65
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
66
+ }
67
+ /** "mardi 17 novembre" / "Tuesday, November 17" for an ISO date, independent of the host time zone. */
68
+ export function longDate(date, lang) {
69
+ const formatter = new Intl.DateTimeFormat(lang === "fr" ? "fr-FR" : "en-US", { weekday: "long", day: "numeric", month: "long", timeZone: "UTC" });
70
+ return formatter.format(new Date(`${date}T12:00:00Z`));
71
+ }
72
+ const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
73
+ const TEXT = "#111827";
74
+ const MUTED = "#6b7280";
75
+ /** French puts a space before a colon. */
76
+ function colon(lang, label) {
77
+ return lang === "fr" ? `${label} :` : `${label}:`;
78
+ }
79
+ function num(value, digits, unit = "") {
80
+ return value === null || value === undefined || !Number.isFinite(value) ? null : `${value.toFixed(digits)}${unit}`;
81
+ }
82
+ function signed(value, digits, unit = "") {
83
+ if (value === null || value === undefined || !Number.isFinite(value))
84
+ return null;
85
+ return `${value > 0 ? "+" : value < 0 ? "−" : ""}${Math.abs(value).toFixed(digits)}${unit}`;
86
+ }
87
+ function image(chart, width) {
88
+ return `<img src="cid:${escapeHtml(chart.cid)}" width="${width}" alt="${escapeHtml(chart.alt)}" style="display:block;margin:0 auto;max-width:100%;height:auto;border:0">`;
89
+ }
90
+ function heading(label) {
91
+ return `<tr><td style="padding:20px 20px 4px 20px;font-size:17px;font-weight:600;color:${TEXT}">${escapeHtml(label)}</td></tr>`;
92
+ }
93
+ function bullets(items) {
94
+ const lis = items.map((item) => `<li style="margin:0 0 4px 0">${escapeHtml(item)}</li>`).join("");
95
+ return `<tr><td style="padding:0 20px 0 20px;font-size:15px;line-height:1.45;color:${TEXT}"><ul style="margin:4px 0 0 0;padding-left:20px">${lis}</ul></td></tr>`;
96
+ }
97
+ function imageRow(chart) {
98
+ return chart ? `<tr><td align="center" style="padding:16px 10px 0 10px">${image(chart, chart.displayWidth)}</td></tr>` : "";
99
+ }
100
+ /** The three figures people want without opening the images. */
101
+ function summaryColumns(input, t) {
102
+ const sleepLines = [];
103
+ if (input.sleep) {
104
+ const duration = num(input.sleep.durationH, 1);
105
+ const need = num(input.sleep.needH, 1);
106
+ if (duration)
107
+ sleepLines.push(`${t.duration}: ${duration} h${need ? ` / ${need} h` : ""}`);
108
+ const efficiency = num(input.sleep.efficiencyPct, 0, " %");
109
+ if (efficiency)
110
+ sleepLines.push(`${t.efficiency}: ${efficiency}`);
111
+ if (input.sleep.bedtime || input.sleep.wakeTime)
112
+ sleepLines.push(`${t.bedtime}: ${input.sleep.bedtime ?? t.noData}, ${t.wake}: ${input.sleep.wakeTime ?? t.noData}`);
113
+ }
114
+ if (!sleepLines.length)
115
+ sleepLines.push(t.noData);
116
+ const sessionLines = [];
117
+ for (const session of input.sessions) {
118
+ const label = session.name ?? session.type ?? "";
119
+ const parts = [label, session.durationMin !== null ? `${Math.round(session.durationMin)} min` : null, session.avgHr !== null ? `${t.hr} ${Math.round(session.avgHr)}` : null, session.load !== null ? `${t.load.toLowerCase()} ${Math.round(session.load)}` : null].filter(Boolean);
120
+ sessionLines.push(parts.join(", "));
121
+ }
122
+ if (!sessionLines.length)
123
+ sessionLines.push(t.noSession);
124
+ const loadLines = [];
125
+ if (input.load) {
126
+ const ctl = num(input.load.ctl, 1);
127
+ const atl = num(input.load.atl, 1);
128
+ const tsb = signed(input.load.tsb, 1);
129
+ const change = signed(input.load.weekChangePct, 0, " %");
130
+ if (ctl)
131
+ loadLines.push(`CTL: ${ctl}`);
132
+ if (atl)
133
+ loadLines.push(`ATL: ${atl}`);
134
+ if (tsb)
135
+ loadLines.push(`TSB: ${tsb}`);
136
+ if (change)
137
+ loadLines.push(`${t.week}: ${change}`);
138
+ }
139
+ if (!loadLines.length)
140
+ loadLines.push(t.noData);
141
+ return [
142
+ { title: t.sleep, lines: sleepLines },
143
+ { title: t.yesterday, lines: sessionLines },
144
+ { title: t.load, lines: loadLines },
145
+ ];
146
+ }
147
+ export function renderBriefingEmail(input) {
148
+ const t = STRINGS[input.lang];
149
+ const ceilingLabel = LABELS[input.lang].ceilings[input.ceiling];
150
+ const color = THEMES.light.ceiling[input.ceiling];
151
+ const chart = (id) => input.charts.find((candidate) => candidate.id === id);
152
+ const subject = t.subject(longDate(input.date, input.lang), ceilingLabel);
153
+ const rows = [];
154
+ rows.push(`<tr><td style="background:${color};padding:14px 20px;font-size:20px;font-weight:600;color:#ffffff">${escapeHtml(colon(input.lang, t.banner))} ${escapeHtml(ceilingLabel)}</td></tr>`);
155
+ rows.push(`<tr><td style="background:#f9fafb;padding:12px 20px;font-size:15px;line-height:1.45;color:${TEXT}">${escapeHtml(input.headline)}</td></tr>`);
156
+ const gauge = chart("recovery_gauge");
157
+ const ceiling = chart("ceiling");
158
+ if (gauge || ceiling) {
159
+ const cell = (item) => `<td width="50%" align="center" valign="top" style="padding:0 5px">${item ? image(item, Math.min(item.displayWidth, 280)) : ""}</td>`;
160
+ rows.push(`<tr><td style="padding:16px 10px 0 10px"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>${cell(gauge)}${cell(ceiling)}</tr></table></td></tr>`);
161
+ }
162
+ if (input.why.length)
163
+ rows.push(heading(colon(input.lang, t.why)), bullets(input.why));
164
+ rows.push(imageRow(chart("signals")), imageRow(chart("hrv_trend")), imageRow(chart("sleep_nights")), imageRow(chart("load_curve")));
165
+ if (input.watch.length)
166
+ rows.push(heading(colon(input.lang, t.watch)), bullets(input.watch));
167
+ const columns = summaryColumns(input, t);
168
+ const th = columns.map((column) => `<td width="33%" valign="top" style="padding:6px 8px;font-size:13px;font-weight:600;color:${TEXT};border:1px solid #d1d5db;background:#f3f4f6">${escapeHtml(column.title)}</td>`).join("");
169
+ const td = columns.map((column) => `<td width="33%" valign="top" style="padding:6px 8px;font-size:13px;line-height:1.5;color:${TEXT};border:1px solid #d1d5db">${column.lines.map(escapeHtml).join("<br>")}</td>`).join("");
170
+ rows.push(`<tr><td style="padding:20px 20px 0 20px"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse"><tr>${th}</tr><tr>${td}</tr></table></td></tr>`);
171
+ rows.push(`<tr><td align="center" style="padding:24px 20px 28px 20px;font-size:13px;line-height:1.5;color:${MUTED}">${escapeHtml(t.footerFeel)}<br>${escapeHtml(t.footerDisclaimer)}</td></tr>`);
172
+ const html = `<!DOCTYPE html><html lang="${input.lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(subject)}</title></head>` +
173
+ `<body style="margin:0;padding:0;background:#ffffff"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#ffffff"><tr><td align="center">` +
174
+ `<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;font-family:${FONT}">${rows.join("")}</table>` +
175
+ `</td></tr></table></body></html>`;
176
+ const text = [
177
+ `${colon(input.lang, t.banner)} ${ceilingLabel}`,
178
+ input.headline,
179
+ ...(input.why.length ? ["", colon(input.lang, t.why), ...input.why.map((item) => `- ${item}`)] : []),
180
+ ...(input.watch.length ? ["", colon(input.lang, t.watch), ...input.watch.map((item) => `- ${item}`)] : []),
181
+ "",
182
+ ...columns.flatMap((column) => [`${colon(input.lang, column.title)} ${column.lines.join(" ; ")}`]),
183
+ "",
184
+ t.footerFeel,
185
+ t.footerDisclaimer,
186
+ ].join("\n");
187
+ return { subject, html, text };
188
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Runs the garmin-cli binary (`gc`). Arguments are passed as an array to
3
+ * execFile, never through a shell, and callers validate every value coming
4
+ * from a tool call. Failures are returned as stable codes, never thrown, and
5
+ * never include the CLI's full output.
6
+ */
7
+ export type GcErrorCode = "not_configured" | "auth" | "rate_limited" | "timeout" | "unsupported" | "parse_error" | "connection" | "error";
8
+ export type GcResult<T = unknown> = {
9
+ ok: true;
10
+ data: T;
11
+ } | {
12
+ ok: false;
13
+ code: GcErrorCode;
14
+ message: string;
15
+ };
16
+ export declare function classifyGcError(error: {
17
+ code?: unknown;
18
+ killed?: boolean;
19
+ signal?: unknown;
20
+ } | null, stderr: string): GcErrorCode;
21
+ export type GcRunner = (args: string[], options?: {
22
+ timeoutMs?: number;
23
+ }) => Promise<GcResult>;
24
+ /** Builds a runner with its own concurrency limit (Garmin rate-limits bursts). */
25
+ export declare function createGcRunner(binary: string): GcRunner;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Runs the garmin-cli binary (`gc`). Arguments are passed as an array to
3
+ * execFile, never through a shell, and callers validate every value coming
4
+ * from a tool call. Failures are returned as stable codes, never thrown, and
5
+ * never include the CLI's full output.
6
+ */
7
+ import { execFile } from "node:child_process";
8
+ const DEFAULT_TIMEOUT_MS = 30_000;
9
+ const MAX_BUFFER_BYTES = 32 * 1024 * 1024;
10
+ const MAX_CONCURRENT = 3;
11
+ export function classifyGcError(error, stderr) {
12
+ if (error?.code === "ENOENT" || error?.code === "EACCES")
13
+ return "not_configured";
14
+ if (error?.killed || error?.signal === "SIGTERM")
15
+ return "timeout";
16
+ const text = stderr.toLowerCase();
17
+ // Checked first: a usage message mentions "--tokenstore" and must not read as an auth failure.
18
+ if (text.includes("no such command") || text.includes("no such option") || text.includes("usage:"))
19
+ return "unsupported";
20
+ if (text.includes("authentication") || text.includes("gc login") || text.includes("not logged in"))
21
+ return "auth";
22
+ if (text.includes("rate limit") || text.includes("too many requests") || text.includes("429"))
23
+ return "rate_limited";
24
+ if (text.includes("connection error") || text.includes("timed out") || text.includes("max retries"))
25
+ return "connection";
26
+ return "error";
27
+ }
28
+ const MESSAGES = {
29
+ not_configured: "The gc binary was not found or is not executable (check gcBinary).",
30
+ auth: "Garmin session missing or expired: run `gc login` in the Gateway environment.",
31
+ rate_limited: "Garmin Connect is rate limiting requests: wait before retrying.",
32
+ timeout: "The gc command timed out.",
33
+ unsupported: "This gc version does not support the command (garmin-cli >= 0.4.0 is required for `gc daily`).",
34
+ parse_error: "gc returned output that is not valid JSON.",
35
+ connection: "Could not reach Garmin Connect.",
36
+ error: "The gc command failed.",
37
+ };
38
+ /** Builds a runner with its own concurrency limit (Garmin rate-limits bursts). */
39
+ export function createGcRunner(binary) {
40
+ let active = 0;
41
+ const waiting = [];
42
+ const acquire = () => new Promise((resolve) => {
43
+ if (active < MAX_CONCURRENT) {
44
+ active += 1;
45
+ resolve();
46
+ }
47
+ else {
48
+ waiting.push(resolve);
49
+ }
50
+ });
51
+ const release = () => {
52
+ const next = waiting.shift();
53
+ if (next)
54
+ next();
55
+ else
56
+ active -= 1;
57
+ };
58
+ return async (args, options = {}) => {
59
+ await acquire();
60
+ try {
61
+ return await new Promise((resolve) => {
62
+ execFile(binary, [...args, "--format", "json"], { timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: MAX_BUFFER_BYTES }, (error, stdout, stderr) => {
63
+ if (error) {
64
+ const code = classifyGcError(error, String(stderr ?? ""));
65
+ resolve({ ok: false, code, message: MESSAGES[code] });
66
+ return;
67
+ }
68
+ try {
69
+ resolve({ ok: true, data: JSON.parse(String(stdout)) });
70
+ }
71
+ catch {
72
+ resolve({ ok: false, code: "parse_error", message: MESSAGES.parse_error });
73
+ }
74
+ });
75
+ });
76
+ }
77
+ finally {
78
+ release();
79
+ }
80
+ };
81
+ }
@@ -0,0 +1,20 @@
1
+ /** Turns gc output into the plugin's types. Unknown shapes give null fields, never guesses. */
2
+ import type { Split } from "../science/performance.ts";
3
+ import type { Activity, DayRecord } from "../types.ts";
4
+ type Json = Record<string, unknown>;
5
+ /** Validates the envelope of `gc daily` and returns its day records. */
6
+ export declare function parseDailyExport(payload: unknown): {
7
+ days: DayRecord[];
8
+ errors: Record<string, string>;
9
+ } | null;
10
+ /** True when the record holds at least one measured signal. */
11
+ export declare function hasSignal(day: DayRecord): boolean;
12
+ export declare function normalizeActivity(raw: unknown): Activity | null;
13
+ export declare function normalizeActivities(payload: unknown): Activity[];
14
+ /** Laps of `gc activities splits ID` (the `lapDTOs` list). */
15
+ export declare function normalizeSplits(payload: unknown): Split[];
16
+ /** Lactate-threshold heart rate from `gc metrics lactate-threshold`. */
17
+ export declare function lthrFromPayload(payload: unknown): number | null;
18
+ /** Garmin's own readiness, status and load figures for the day, reduced to a few fields. */
19
+ export declare function garminDaySignals(readiness: unknown, status: unknown): Json;
20
+ export {};
@@ -0,0 +1,132 @@
1
+ /** Turns gc output into the plugin's types. Unknown shapes give null fields, never guesses. */
2
+ import { isIsoDate } from "../dates.js";
3
+ import { isNum } from "../science/stats.js";
4
+ function obj(value) {
5
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
6
+ }
7
+ function num(source, ...keys) {
8
+ for (const key of keys) {
9
+ const value = source?.[key];
10
+ if (isNum(value))
11
+ return value;
12
+ }
13
+ return null;
14
+ }
15
+ function positive(source, ...keys) {
16
+ const value = num(source, ...keys);
17
+ return value !== null && value > 0 ? value : null;
18
+ }
19
+ /** Validates the envelope of `gc daily` and returns its day records. */
20
+ export function parseDailyExport(payload) {
21
+ const root = obj(payload);
22
+ if (!root || root.schemaVersion !== 1 || !Array.isArray(root.days))
23
+ return null;
24
+ const days = root.days.filter((day) => isIsoDate(obj(day)?.date) && Array.isArray(obj(day)?.sources));
25
+ const errors = obj(root.errors) ?? {};
26
+ return { days, errors: Object.fromEntries(Object.entries(errors).map(([key, value]) => [key, String(value)])) };
27
+ }
28
+ /** True when the record holds at least one measured signal. */
29
+ export function hasSignal(day) {
30
+ return Boolean(day.sleep || day.hrv || day.restingHr !== null || day.stress || day.bodyBattery || day.respiration || day.spo2);
31
+ }
32
+ export function normalizeActivity(raw) {
33
+ const a = obj(raw);
34
+ const id = a?.activityId;
35
+ const start = typeof a?.startTimeLocal === "string" ? a.startTimeLocal : null;
36
+ if (!a || (typeof id !== "number" && typeof id !== "string") || !start || !isIsoDate(start.slice(0, 10)))
37
+ return null;
38
+ const zones = [1, 2, 3, 4, 5].map((zone) => num(a, `hrTimeInZone_${zone}`));
39
+ const type = obj(a.activityType);
40
+ return {
41
+ id: String(id),
42
+ date: start.slice(0, 10),
43
+ startLocal: start.replace(" ", "T").slice(0, 19),
44
+ type: typeof type?.typeKey === "string" ? type.typeKey : "unknown",
45
+ name: typeof a.activityName === "string" ? a.activityName : null,
46
+ durationS: positive(a, "duration"),
47
+ movingS: positive(a, "movingDuration"),
48
+ distanceM: positive(a, "distance"),
49
+ elevGainM: num(a, "elevationGain"),
50
+ elevLossM: num(a, "elevationLoss"),
51
+ avgHr: positive(a, "averageHR"),
52
+ maxHr: positive(a, "maxHR"),
53
+ hrZonesS: zones.some((value) => value !== null && value > 0) ? zones.map((value) => value ?? 0) : null,
54
+ aerobicTE: positive(a, "aerobicTrainingEffect"),
55
+ anaerobicTE: num(a, "anaerobicTrainingEffect"),
56
+ garminLoad: positive(a, "activityTrainingLoad"),
57
+ avgSpeedMs: positive(a, "averageSpeed"),
58
+ gapSpeedMs: positive(a, "avgGradeAdjustedSpeed"),
59
+ avgPowerW: positive(a, "avgPower"),
60
+ normPowerW: positive(a, "normPower"),
61
+ kcal: positive(a, "calories"),
62
+ vo2max: positive(a, "vO2MaxValue"),
63
+ tempMinC: num(a, "minTemperature"),
64
+ tempMaxC: num(a, "maxTemperature"),
65
+ };
66
+ }
67
+ export function normalizeActivities(payload) {
68
+ if (!Array.isArray(payload))
69
+ return [];
70
+ return payload.map(normalizeActivity).filter((activity) => activity !== null);
71
+ }
72
+ /** Laps of `gc activities splits ID` (the `lapDTOs` list). */
73
+ export function normalizeSplits(payload) {
74
+ const laps = obj(payload)?.lapDTOs;
75
+ if (!Array.isArray(laps))
76
+ return [];
77
+ const out = [];
78
+ for (const raw of laps) {
79
+ const lap = obj(raw);
80
+ const durationS = positive(lap, "movingDuration", "duration");
81
+ const distanceM = positive(lap, "distance");
82
+ if (durationS === null || distanceM === null)
83
+ continue;
84
+ out.push({
85
+ durationS,
86
+ distanceM,
87
+ avgHr: positive(lap, "averageHR"),
88
+ elevGainM: num(lap, "elevationGain"),
89
+ elevLossM: num(lap, "elevationLoss"),
90
+ gapSpeedMs: positive(lap, "avgGradeAdjustedSpeed"),
91
+ });
92
+ }
93
+ return out;
94
+ }
95
+ /** Lactate-threshold heart rate from `gc metrics lactate-threshold`. */
96
+ export function lthrFromPayload(payload) {
97
+ const root = obj(payload);
98
+ const block = obj(root?.speed_and_heart_rate) ?? root;
99
+ const value = positive(block, "heartRate", "lactateThresholdHeartRate");
100
+ return value !== null && value >= 100 && value <= 210 ? Math.round(value) : null;
101
+ }
102
+ /** Garmin's own readiness, status and load figures for the day, reduced to a few fields. */
103
+ export function garminDaySignals(readiness, status) {
104
+ const first = Array.isArray(readiness) ? obj(readiness[0]) : obj(readiness);
105
+ const out = {};
106
+ if (first) {
107
+ out.trainingReadiness = {
108
+ score: num(first, "score"),
109
+ level: first.level ?? null,
110
+ recoveryTimeMin: num(first, "recoveryTime"),
111
+ acuteLoad: num(first, "acuteLoad"),
112
+ sleepScore: num(first, "sleepScore"),
113
+ hrvWeeklyAverageMs: num(first, "hrvWeeklyAverage"),
114
+ };
115
+ }
116
+ const root = obj(status);
117
+ const vo2 = obj(obj(root?.mostRecentVO2Max)?.generic);
118
+ if (vo2)
119
+ out.vo2max = { value: num(vo2, "vo2MaxPreciseValue", "vo2MaxValue"), date: vo2.calendarDate ?? null };
120
+ const latest = obj(obj(root?.mostRecentTrainingStatus)?.latestTrainingStatusData);
121
+ const device = latest ? obj(Object.values(latest)[0]) : null;
122
+ if (device) {
123
+ const acute = obj(device.acuteTrainingLoadDTO);
124
+ out.trainingStatus = {
125
+ phrase: device.trainingStatusFeedbackPhrase ?? null,
126
+ acuteLoad: num(acute, "dailyTrainingLoadAcute"),
127
+ chronicLoad: num(acute, "dailyTrainingLoadChronic"),
128
+ loadRatio: num(acute, "dailyAcuteChronicWorkloadRatio"),
129
+ };
130
+ }
131
+ return out;
132
+ }