@sctg/openclaw-coach 2.0.0 → 2.2.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 +33 -4
- package/assets/icon.png +0 -0
- package/dist/config.d.ts +5 -0
- package/dist/config.js +2 -0
- package/dist/email.d.ts +58 -0
- package/dist/email.js +188 -0
- package/dist/garmin/backend.d.ts +19 -0
- package/dist/garmin/backend.js +27 -0
- package/dist/garmin/gc.d.ts +2 -0
- package/dist/garmin/gc.js +4 -0
- package/dist/garmin/native.d.ts +27 -0
- package/dist/garmin/native.js +110 -0
- package/dist/index.js +22 -3
- package/dist/tools.d.ts +37 -0
- package/dist/tools.js +75 -0
- package/docs/SCIENCE.md +4 -0
- package/openclaw.plugin.json +15 -0
- package/package.json +4 -1
- package/skills/coach/SKILL.md +8 -0
package/README.md
CHANGED
|
@@ -116,6 +116,7 @@ configuration: the files are for the coach, the configuration is for the models.
|
|
|
116
116
|
| `coach_strength_analysis` | One strength session: volume, estimated 1RM | — |
|
|
117
117
|
| `coach_journal_log` | Subjective check-in, symptoms, habits | local journal |
|
|
118
118
|
| `coach_journal_insights` | Associations between habits and the following night | — |
|
|
119
|
+
| `coach_briefing_email` | Build the whole daily e-mail (subject, HTML, text, inline images), ready for any mail tool | PNG files in `dataDir/charts` |
|
|
119
120
|
| `coach_briefing_charts` | Render the day's figures as PNG images (gauge, ceiling, signals, HRV, load, sleep) for an email | PNG files in `dataDir/charts` |
|
|
120
121
|
| `coach_workout_push` | Create a workout in Garmin Connect (preview, then explicit confirmation) | **Garmin Connect** |
|
|
121
122
|
| `coach_data_status` | Coverage, sync errors, anchors in use | local store |
|
|
@@ -126,6 +127,8 @@ Version 1's `coach_garmin_digest` is gone: replace it with `coach_daily_briefing
|
|
|
126
127
|
|
|
127
128
|
| Key | Default | Description |
|
|
128
129
|
|---|---|---|
|
|
130
|
+
| `garminBackend` | `auto` | `native`: fetch in the Gateway process with [`@sctg/garmin-ts-client`](https://github.com/sctg-development/garmin-ts-client); `gc`: the garmin-cli binary; `auto`: native when the package and a token file are present, else gc. Creating workouts always uses `gc`. |
|
|
131
|
+
| `garminTokenFile` | `$GARMINTOKENS` or `~/.config/garmin-cli/tokens/garmin_tokens.json` | Token file of the native backend (the file `gc login` or `garmin-ts login` writes). |
|
|
129
132
|
| `gcBinary` | `gc` | Path to the garmin-cli binary. |
|
|
130
133
|
| `timezone` | Gateway timezone | IANA timezone of the athlete (day boundaries). |
|
|
131
134
|
| `dataDir` | `~/.openclaw/coach` | Local store directory. |
|
|
@@ -195,8 +198,31 @@ images until the reader allows them.
|
|
|
195
198
|
|
|
196
199
|
## Daily briefing e-mail
|
|
197
200
|
|
|
198
|
-
|
|
199
|
-
|
|
201
|
+
`coach_briefing_email` builds the whole message in code: subject, HTML (one centred 600 px column, ceiling
|
|
202
|
+
banner, recovery gauge and ceiling side by side, "why", signals, HRV, sleep, "to watch", a text summary table,
|
|
203
|
+
footer), a plain-text version and the list of inline images. The layout does not depend on the model, so a
|
|
204
|
+
small model produces the same mail as a large one. It sends nothing: pass `subject`, `bodyHtml`, `bodyText`
|
|
205
|
+
and `inlineImages` to any mail tool that supports inline images by content id (`send_email` of the
|
|
206
|
+
`sctg-mail` plugin does; with a tool that does not, send `bodyText` alone, the key figures are in it).
|
|
207
|
+
|
|
208
|
+
The model only writes the three sentences that need judgement, in the athlete's language: `headline` (what to
|
|
209
|
+
do today, with `ATHLETE.md` and `PLAN.md` in mind), `why` (up to 3 bullets) and `watch` (up to 4 cautions).
|
|
210
|
+
Left out, `headline` defaults to the meaning of the ceiling in the chosen language; `why` and `watch` default to the
|
|
211
|
+
rules and caveats of the models, which are in English, so they are used for English mails only and the sections
|
|
212
|
+
are omitted for French (the result's `notes` say so). Always pass all three; pass `watch: []` when there is nothing to watch. The fitness curve
|
|
213
|
+
is added on Sundays (`weekly: true` forces it).
|
|
214
|
+
|
|
215
|
+
Minimal automation prompt:
|
|
216
|
+
|
|
217
|
+
```text
|
|
218
|
+
Read ATHLETE.md and PLAN.md. Call coach_briefing_email with lang "fr", then write headline (one sentence: what
|
|
219
|
+
to do today, given my constraints), why (up to 3 bullets with figures and my personal reference) and watch
|
|
220
|
+
(cautions only), using only figures from coach_daily_briefing, and call coach_briefing_email again with them.
|
|
221
|
+
Send the result unchanged with send_email to <my address>: subject, bodyHtml, bodyText, inlineImages.
|
|
222
|
+
If the briefing is an error, send a short text mail instead. Reply only "sent" or the error.
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Create the job as an **isolated agent turn** with delivery disabled, because the mail leaves through
|
|
200
226
|
`send_email`, not through a chat channel:
|
|
201
227
|
|
|
202
228
|
```bash
|
|
@@ -208,7 +234,10 @@ openclaw cron add --name "Briefing entrainement" --cron "0 10 * * *" --tz Europe
|
|
|
208
234
|
job, use `openclaw cron edit <id> --message ...`.) A job that runs in the *main* session does not receive the
|
|
209
235
|
plugin's tools reliably: use an isolated one.
|
|
210
236
|
|
|
211
|
-
|
|
237
|
+
### Custom layout: the full prompt
|
|
238
|
+
|
|
239
|
+
If you want to control the HTML yourself, the model can assemble it from `coach_daily_briefing` and
|
|
240
|
+
`coach_briefing_charts` instead. The prompt below is the one used for the sample result. It is shown in English; the original is in French
|
|
212
241
|
and the e-mail is written in the language you ask for (`lang` of `coach_briefing_charts`, or the plugin's
|
|
213
242
|
`language` setting). Replace `<my address>` before using it.
|
|
214
243
|
|
|
@@ -309,7 +338,7 @@ Gateway uses: that is health data, so choose the provider accordingly (see `docs
|
|
|
309
338
|
```bash
|
|
310
339
|
npm ci
|
|
311
340
|
npm run typecheck
|
|
312
|
-
npm test #
|
|
341
|
+
npm test # 46 tests, synthetic data, no Garmin access needed
|
|
313
342
|
npm run build
|
|
314
343
|
```
|
|
315
344
|
|
package/assets/icon.png
ADDED
|
Binary file
|
package/dist/config.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
/** Plugin configuration: parsing and defaults. Invalid values fall back to the default. */
|
|
2
2
|
import type { Sex } from "./types.ts";
|
|
3
|
+
export type GarminBackend = "auto" | "native" | "gc";
|
|
3
4
|
export type CoachConfig = {
|
|
4
5
|
gcBinary: string;
|
|
6
|
+
/** `native`: @sctg/garmin-ts-client in-process; `gc`: the garmin-cli binary; `auto`: native when available, else gc. */
|
|
7
|
+
garminBackend: GarminBackend;
|
|
8
|
+
/** Token file of the native backend (default: $GARMINTOKENS or the file `gc login` writes). */
|
|
9
|
+
garminTokenFile: string | null;
|
|
5
10
|
timezone: string;
|
|
6
11
|
dataDir: string;
|
|
7
12
|
/** Days of recovery history kept in sync (baselines need 60 + margin). */
|
package/dist/config.js
CHANGED
|
@@ -19,6 +19,8 @@ export function parseConfig(raw) {
|
|
|
19
19
|
const sex = text(cfg.sex);
|
|
20
20
|
return {
|
|
21
21
|
gcBinary: text(cfg.gcBinary) ?? "gc",
|
|
22
|
+
garminBackend: cfg.garminBackend === "native" || cfg.garminBackend === "gc" ? cfg.garminBackend : "auto",
|
|
23
|
+
garminTokenFile: text(cfg.garminTokenFile),
|
|
22
24
|
timezone: timezone && isValidTimezone(timezone) ? timezone : Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
|
|
23
25
|
dataDir: text(cfg.dataDir) ?? path.join(os.homedir(), ".openclaw", "coach"),
|
|
24
26
|
historyDays: numberIn(cfg.historyDays, 30, 365) ?? 90,
|
package/dist/email.d.ts
ADDED
|
@@ -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("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
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,19 @@
|
|
|
1
|
+
/** Chooses how Garmin data is fetched: in-process with the native client, or through the `gc` binary. */
|
|
2
|
+
import type { CoachConfig } from "../config.ts";
|
|
3
|
+
import { type GcErrorCode, type GcRunner } from "./gc.ts";
|
|
4
|
+
import { type NativeGarmin } from "./native.ts";
|
|
5
|
+
export type BackendDeps = {
|
|
6
|
+
gc?: GcRunner;
|
|
7
|
+
load?: (tokenFile: string | null) => Promise<NativeGarmin | GcErrorCode>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* - `gc`: the CLI only.
|
|
11
|
+
* - `native`: the native client for what it implements; anything else (workout creation) is `unsupported`.
|
|
12
|
+
* - `auto` (default): native when the package and a token file are present, otherwise gc; commands the
|
|
13
|
+
* native client does not implement always go to gc. The choice is made once, on first use.
|
|
14
|
+
*/
|
|
15
|
+
export type GarminRunner = GcRunner & {
|
|
16
|
+
/** The backend that serves reads: `native`, `gc`, or `native-unavailable` (native requested, not usable). */
|
|
17
|
+
backend(): Promise<"native" | "gc" | "native-unavailable">;
|
|
18
|
+
};
|
|
19
|
+
export declare function createGarminRunner(config: Pick<CoachConfig, "gcBinary" | "garminBackend" | "garminTokenFile">, deps?: BackendDeps): GarminRunner;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createGcRunner, gcFailure } from "./gc.js";
|
|
2
|
+
import { isNativeCommand, loadNative, nativeRunner } from "./native.js";
|
|
3
|
+
export function createGarminRunner(config, deps = {}) {
|
|
4
|
+
const gc = deps.gc ?? createGcRunner(config.gcBinary);
|
|
5
|
+
if (config.garminBackend === "gc")
|
|
6
|
+
return Object.assign(gc, { backend: async () => "gc" });
|
|
7
|
+
const load = deps.load ?? ((tokenFile) => loadNative(tokenFile));
|
|
8
|
+
let native = null;
|
|
9
|
+
const resolveNative = () => {
|
|
10
|
+
native ??= load(config.garminTokenFile).then((result) => (typeof result === "string" ? result : nativeRunner(result)));
|
|
11
|
+
return native;
|
|
12
|
+
};
|
|
13
|
+
const run = async (args, options) => {
|
|
14
|
+
if (!isNativeCommand(args))
|
|
15
|
+
return gc(args, options);
|
|
16
|
+
const runner = await resolveNative();
|
|
17
|
+
if (typeof runner === "string")
|
|
18
|
+
return config.garminBackend === "native" ? gcFailure(runner) : gc(args, options);
|
|
19
|
+
return runner(args, options);
|
|
20
|
+
};
|
|
21
|
+
return Object.assign(run, {
|
|
22
|
+
backend: async () => {
|
|
23
|
+
const runner = await resolveNative();
|
|
24
|
+
return typeof runner === "string" ? (config.garminBackend === "native" ? "native-unavailable" : "gc") : "native";
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
}
|
package/dist/garmin/gc.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export declare function classifyGcError(error: {
|
|
|
18
18
|
killed?: boolean;
|
|
19
19
|
signal?: unknown;
|
|
20
20
|
} | null, stderr: string): GcErrorCode;
|
|
21
|
+
/** A failure result with the stable message for `code`, for runners other than the CLI. */
|
|
22
|
+
export declare function gcFailure(code: GcErrorCode): GcResult;
|
|
21
23
|
export type GcRunner = (args: string[], options?: {
|
|
22
24
|
timeoutMs?: number;
|
|
23
25
|
}) => Promise<GcResult>;
|
package/dist/garmin/gc.js
CHANGED
|
@@ -35,6 +35,10 @@ const MESSAGES = {
|
|
|
35
35
|
connection: "Could not reach Garmin Connect.",
|
|
36
36
|
error: "The gc command failed.",
|
|
37
37
|
};
|
|
38
|
+
/** A failure result with the stable message for `code`, for runners other than the CLI. */
|
|
39
|
+
export function gcFailure(code) {
|
|
40
|
+
return { ok: false, code, message: MESSAGES[code] };
|
|
41
|
+
}
|
|
38
42
|
/** Builds a runner with its own concurrency limit (Garmin rate-limits bursts). */
|
|
39
43
|
export function createGcRunner(binary) {
|
|
40
44
|
let active = 0;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native Garmin backend: runs the `gc` commands the coach uses in-process with @sctg/garmin-ts-client,
|
|
3
|
+
* returning the same JSON as the CLI (checked on a real account). The package is optional and loaded
|
|
4
|
+
* lazily, through a structural interface, so the coach compiles and runs without it.
|
|
5
|
+
*/
|
|
6
|
+
import { type GcErrorCode, type GcRunner } from "./gc.ts";
|
|
7
|
+
export interface NativeGarmin {
|
|
8
|
+
daily(options: {
|
|
9
|
+
start: string;
|
|
10
|
+
end?: string;
|
|
11
|
+
detail?: boolean;
|
|
12
|
+
}): Promise<unknown>;
|
|
13
|
+
activities(options: {
|
|
14
|
+
start: string;
|
|
15
|
+
end?: string;
|
|
16
|
+
}): Promise<unknown>;
|
|
17
|
+
activity(id: string, view?: ActivityView): Promise<unknown>;
|
|
18
|
+
metric(name: "training-readiness" | "training-status", date: string): Promise<unknown>;
|
|
19
|
+
lactateThreshold(): Promise<unknown>;
|
|
20
|
+
}
|
|
21
|
+
export type ActivityView = "splits" | "hr-zones" | "weather" | "exercise-sets";
|
|
22
|
+
/** True when the native backend implements the command (writes, such as `workouts create`, stay on gc). */
|
|
23
|
+
export declare function isNativeCommand(args: string[]): boolean;
|
|
24
|
+
/** Maps `gc` arguments to native calls. Failures become the stable codes the CLI runner reports. */
|
|
25
|
+
export declare function nativeRunner(api: NativeGarmin): GcRunner;
|
|
26
|
+
/** Loads the optional package. Returns the failure code instead of throwing: `auth` without a token file, `not_configured` without the package. */
|
|
27
|
+
export declare function loadNative(tokenFile: string | null, moduleName?: string): Promise<NativeGarmin | GcErrorCode>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Native Garmin backend: runs the `gc` commands the coach uses in-process with @sctg/garmin-ts-client,
|
|
11
|
+
* returning the same JSON as the CLI (checked on a real account). The package is optional and loaded
|
|
12
|
+
* lazily, through a structural interface, so the coach compiles and runs without it.
|
|
13
|
+
*/
|
|
14
|
+
import { gcFailure } from "./gc.js";
|
|
15
|
+
const ACTIVITY_VIEWS = ["get", "splits", "hr-zones", "weather", "exercise-sets"];
|
|
16
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
17
|
+
function flags(args) {
|
|
18
|
+
const positional = [];
|
|
19
|
+
const values = new Map();
|
|
20
|
+
const switches = new Set();
|
|
21
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
22
|
+
const arg = args[index];
|
|
23
|
+
if (arg === "--detail" || arg === "--no-detail")
|
|
24
|
+
switches.add(arg);
|
|
25
|
+
else if (arg.startsWith("--"))
|
|
26
|
+
values.set(arg, args[(index += 1)] ?? "");
|
|
27
|
+
else
|
|
28
|
+
positional.push(arg);
|
|
29
|
+
}
|
|
30
|
+
return { positional, values, switches };
|
|
31
|
+
}
|
|
32
|
+
/** True when the native backend implements the command (writes, such as `workouts create`, stay on gc). */
|
|
33
|
+
export function isNativeCommand(args) {
|
|
34
|
+
const [command, sub] = args;
|
|
35
|
+
if (command === "daily" || command === "activities")
|
|
36
|
+
return command === "daily" || !sub || sub.startsWith("--") || ACTIVITY_VIEWS.includes(sub);
|
|
37
|
+
return command === "metrics" && (sub === "training-readiness" || sub === "training-status" || sub === "lactate-threshold");
|
|
38
|
+
}
|
|
39
|
+
function code(error) {
|
|
40
|
+
const value = error?.code;
|
|
41
|
+
return value === "auth" || value === "rate_limited" || value === "connection" ? value : "error";
|
|
42
|
+
}
|
|
43
|
+
/** Maps `gc` arguments to native calls. Failures become the stable codes the CLI runner reports. */
|
|
44
|
+
export function nativeRunner(api) {
|
|
45
|
+
return async (args) => {
|
|
46
|
+
if (!isNativeCommand(args))
|
|
47
|
+
return gcFailure("unsupported");
|
|
48
|
+
const [command, ...rest] = args;
|
|
49
|
+
const { positional, values, switches } = flags(rest);
|
|
50
|
+
try {
|
|
51
|
+
let data;
|
|
52
|
+
if (command === "daily") {
|
|
53
|
+
const start = values.get("--start");
|
|
54
|
+
if (!start || !DATE.test(start))
|
|
55
|
+
return gcFailure("unsupported");
|
|
56
|
+
data = await api.daily({ start, end: values.get("--end"), detail: switches.has("--no-detail") ? false : switches.has("--detail") ? true : undefined });
|
|
57
|
+
}
|
|
58
|
+
else if (command === "activities" && positional.length > 0) {
|
|
59
|
+
const [view, id] = positional;
|
|
60
|
+
if (!id || !/^\d{1,20}$/.test(id))
|
|
61
|
+
return gcFailure("unsupported");
|
|
62
|
+
data = await api.activity(id, view === "get" ? undefined : view);
|
|
63
|
+
}
|
|
64
|
+
else if (command === "activities") {
|
|
65
|
+
const start = values.get("--start");
|
|
66
|
+
if (!start || !DATE.test(start))
|
|
67
|
+
return gcFailure("unsupported");
|
|
68
|
+
data = await api.activities({ start, end: values.get("--end") });
|
|
69
|
+
}
|
|
70
|
+
else if (positional[0] === "lactate-threshold") {
|
|
71
|
+
data = await api.lactateThreshold();
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
const date = positional[1];
|
|
75
|
+
if (!date || !DATE.test(date))
|
|
76
|
+
return gcFailure("unsupported");
|
|
77
|
+
data = await api.metric(positional[0], date);
|
|
78
|
+
}
|
|
79
|
+
return { ok: true, data };
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
return gcFailure(code(error));
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** Loads the optional package. Returns the failure code instead of throwing: `auth` without a token file, `not_configured` without the package. */
|
|
87
|
+
export async function loadNative(tokenFile, moduleName = "@sctg/garmin-ts-client") {
|
|
88
|
+
let mod;
|
|
89
|
+
try {
|
|
90
|
+
mod = (await import(__rewriteRelativeImportExtension(/* @vite-ignore */ moduleName)));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return "not_configured";
|
|
94
|
+
}
|
|
95
|
+
const client = mod.GarminClient.fromFile(tokenFile ?? undefined);
|
|
96
|
+
try {
|
|
97
|
+
await client.tokenInfo();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return "auth";
|
|
101
|
+
}
|
|
102
|
+
const call = (name, ...args) => mod[name](client, ...args);
|
|
103
|
+
return {
|
|
104
|
+
daily: (options) => call("daily", options),
|
|
105
|
+
activities: (options) => call("listActivities", options),
|
|
106
|
+
activity: (id, view) => call(view === undefined ? "getActivity" : { splits: "activitySplits", "hr-zones": "activityHrZones", weather: "activityWeather", "exercise-sets": "activityExerciseSets" }[view], id),
|
|
107
|
+
metric: (name, date) => call(name === "training-readiness" ? "trainingReadiness" : "trainingStatus", date),
|
|
108
|
+
lactateThreshold: () => call("lactateThreshold"),
|
|
109
|
+
};
|
|
110
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
3
|
import { parseConfig } from "./config.js";
|
|
4
|
-
import {
|
|
5
|
-
import { ToolInputError, activityDeepDive, briefingCharts, CHART_IDS, dailyBriefing, dataStatus, journalInsights, journalLog, strengthAnalysis, trainingLoad, trends, workoutPush, zonesAndPaces, } from "./tools.js";
|
|
4
|
+
import { createGarminRunner } from "./garmin/backend.js";
|
|
5
|
+
import { ToolInputError, activityDeepDive, briefingCharts, briefingEmail, CHART_IDS, dailyBriefing, dataStatus, journalInsights, journalLog, strengthAnalysis, trainingLoad, trends, workoutPush, zonesAndPaces, } from "./tools.js";
|
|
6
6
|
const DateParam = Type.Optional(Type.String({ description: "YYYY-MM-DD, 'today' or 'yesterday'. Default: today in the configured timezone." }));
|
|
7
7
|
const SyncParam = Type.Optional(Type.Boolean({ description: "Fetch new data from Garmin first (default true). Pass false to reuse the local store." }));
|
|
8
8
|
const ActivityIdParam = Type.String({ pattern: "^[0-9]{1,20}$", description: "Garmin activity id, as listed by coach_daily_briefing or coach_training_load." });
|
|
@@ -149,6 +149,25 @@ const TOOLS = [
|
|
|
149
149
|
run: briefingCharts,
|
|
150
150
|
summary: (r) => `${r.charts.length} chart(s) rendered, ${r.skipped.length} skipped.`,
|
|
151
151
|
},
|
|
152
|
+
{
|
|
153
|
+
name: "coach_briefing_email",
|
|
154
|
+
label: "Coach Briefing Email",
|
|
155
|
+
description: "Builds the complete daily briefing e-mail in code: subject, HTML (centred column, ceiling banner, recovery gauge, signals, HRV, sleep, " +
|
|
156
|
+
"text summary table), plain-text version and inline-image list. Pass subject, bodyHtml, bodyText and inlineImages to a mail tool " +
|
|
157
|
+
"(send_email) without rewriting them. Optionally supply headline, why and watch in the athlete's language to personalise the three " +
|
|
158
|
+
"sentences that need judgement. The load curve is added on Sundays. It does not send anything.",
|
|
159
|
+
parameters: Type.Object({
|
|
160
|
+
date: DateParam,
|
|
161
|
+
sync: SyncParam,
|
|
162
|
+
lang: Type.Optional(Type.Union([Type.Literal("en"), Type.Literal("fr")], { description: "Language of labels and default texts. Default: the plugin's `language` setting." })),
|
|
163
|
+
headline: Type.Optional(Type.String({ maxLength: 240, description: "One sentence: what to do today, taking ATHLETE.md and PLAN.md into account. Default: the meaning of the ceiling." })),
|
|
164
|
+
why: Type.Optional(Type.Array(Type.String({ maxLength: 240 }), { maxItems: 3, description: "Up to 3 bullets, main cause first, with figures and their personal reference. Default: the rules that set the ceiling, for English only; omitted for French when not supplied." })),
|
|
165
|
+
watch: Type.Optional(Type.Array(Type.String({ maxLength: 240 }), { maxItems: 4, description: "Cautions only (early warning, symptoms, sleep debt, load, missing data). Default: the briefing's caveats, for English only; omitted for French when not supplied. Pass [] when there is nothing to watch." })),
|
|
166
|
+
weekly: Type.Optional(Type.Boolean({ description: "Add the fitness/fatigue/form curve. Default: only on Sundays." })),
|
|
167
|
+
}),
|
|
168
|
+
run: briefingEmail,
|
|
169
|
+
summary: (r) => `E-mail built: "${r.subject}", ${r.inlineImages.length} inline image(s).`,
|
|
170
|
+
},
|
|
152
171
|
{
|
|
153
172
|
name: "coach_data_status",
|
|
154
173
|
label: "Coach Data Status",
|
|
@@ -165,7 +184,7 @@ export default definePluginEntry({
|
|
|
165
184
|
description: "Endurance and recovery coach: documented physiological models computed on Garmin data, with a coaching skill.",
|
|
166
185
|
register(api) {
|
|
167
186
|
const config = parseConfig(api.pluginConfig);
|
|
168
|
-
const deps = { config, gc:
|
|
187
|
+
const deps = { config, gc: createGarminRunner(config) };
|
|
169
188
|
for (const tool of TOOLS) {
|
|
170
189
|
api.registerTool({
|
|
171
190
|
name: tool.name,
|
package/dist/tools.d.ts
CHANGED
|
@@ -368,6 +368,7 @@ export declare function dataStatus(deps: Deps, params: {
|
|
|
368
368
|
date: string;
|
|
369
369
|
timezone: string;
|
|
370
370
|
dataDir: string;
|
|
371
|
+
garminBackend: string;
|
|
371
372
|
sync: string | SyncReport;
|
|
372
373
|
coverage: {
|
|
373
374
|
windowDays: number;
|
|
@@ -425,3 +426,39 @@ export declare function briefingCharts(deps: Deps, params: {
|
|
|
425
426
|
}[];
|
|
426
427
|
usage: string;
|
|
427
428
|
}>;
|
|
429
|
+
/**
|
|
430
|
+
* The whole daily briefing e-mail, built in code: subject, HTML, plain text and the inline-image list,
|
|
431
|
+
* ready to pass to any mail tool. The model may supply the three sentences that need judgement (headline,
|
|
432
|
+
* why, watch) in the athlete's language; everything else is deterministic.
|
|
433
|
+
*/
|
|
434
|
+
export declare function briefingEmail(deps: Deps, params: {
|
|
435
|
+
date?: unknown;
|
|
436
|
+
sync?: boolean;
|
|
437
|
+
lang?: string;
|
|
438
|
+
headline?: unknown;
|
|
439
|
+
why?: unknown;
|
|
440
|
+
watch?: unknown;
|
|
441
|
+
weekly?: boolean;
|
|
442
|
+
}): Promise<{
|
|
443
|
+
date: string;
|
|
444
|
+
lang: Lang;
|
|
445
|
+
ceiling: import("./science/readiness.ts").Ceiling;
|
|
446
|
+
status: {
|
|
447
|
+
recovery: import("./types.ts").DataStatus;
|
|
448
|
+
sleep: import("./types.ts").DataStatus;
|
|
449
|
+
load: import("./types.ts").DataStatus;
|
|
450
|
+
};
|
|
451
|
+
subject: string;
|
|
452
|
+
bodyHtml: string;
|
|
453
|
+
bodyText: string;
|
|
454
|
+
inlineImages: {
|
|
455
|
+
cid: string;
|
|
456
|
+
path: string;
|
|
457
|
+
}[];
|
|
458
|
+
skipped: {
|
|
459
|
+
id: ChartId;
|
|
460
|
+
reason: string;
|
|
461
|
+
}[];
|
|
462
|
+
notes: string[];
|
|
463
|
+
usage: string;
|
|
464
|
+
}>;
|
package/dist/tools.js
CHANGED
|
@@ -9,6 +9,7 @@ import { ceilingLadder, hrvChart, loadChart, recoveryGauge, signalsChart, sleepC
|
|
|
9
9
|
import { renderPng } from "./charts/render.js";
|
|
10
10
|
import { THEMES } from "./charts/svg.js";
|
|
11
11
|
import { addDays, dateRange, isIsoDate, todayIn, weekStart } from "./dates.js";
|
|
12
|
+
import { defaultHeadline, renderBriefingEmail } from "./email.js";
|
|
12
13
|
import { garminDaySignals, normalizeActivity, normalizeSplits } from "./garmin/normalize.js";
|
|
13
14
|
import { resolveProfile } from "./profile.js";
|
|
14
15
|
import { habitAssociations } from "./science/associations.js";
|
|
@@ -594,6 +595,9 @@ export async function dataStatus(deps, params) {
|
|
|
594
595
|
advice.push("The gc binary was not found: install garmin-cli or set gcBinary in the plugin config.");
|
|
595
596
|
if (Object.values(context.sync?.errors ?? {}).includes("auth"))
|
|
596
597
|
advice.push("Run `gc login` in the Gateway environment.");
|
|
598
|
+
const backend = await deps.gc.backend?.();
|
|
599
|
+
if (backend === "native-unavailable")
|
|
600
|
+
advice.push("garminBackend is native but @sctg/garmin-ts-client or its token file is missing: install the package and log in (`gc login` or `garmin-ts login`), or set garminBackend to auto.");
|
|
597
601
|
if (cover.daysWithHrv < 14)
|
|
598
602
|
advice.push(`HRV baseline needs 14 nights; ${cover.daysWithHrv} available.`);
|
|
599
603
|
if (!isNum(context.profile.hrMax))
|
|
@@ -606,6 +610,7 @@ export async function dataStatus(deps, params) {
|
|
|
606
610
|
date: context.date,
|
|
607
611
|
timezone: deps.config.timezone,
|
|
608
612
|
dataDir: deps.config.dataDir,
|
|
613
|
+
garminBackend: backend ?? "gc",
|
|
609
614
|
sync: context.sync ?? "not requested (pass sync: true)",
|
|
610
615
|
coverage: cover,
|
|
611
616
|
profile: profileSummary(context.profile),
|
|
@@ -719,3 +724,73 @@ export async function briefingCharts(deps, params) {
|
|
|
719
724
|
'<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.',
|
|
720
725
|
};
|
|
721
726
|
}
|
|
727
|
+
// --- coach_briefing_email -------------------------------------------------------------------------
|
|
728
|
+
const EMAIL_CHARTS = ["recovery_gauge", "ceiling", "signals", "hrv_trend", "sleep_nights"];
|
|
729
|
+
const MAX_LINE = 240;
|
|
730
|
+
function textList(value, name, max) {
|
|
731
|
+
if (value === undefined || value === null)
|
|
732
|
+
return undefined;
|
|
733
|
+
if (!Array.isArray(value) || value.length > max)
|
|
734
|
+
throw new ToolInputError(`${name} must be a list of at most ${max} short texts.`);
|
|
735
|
+
return value.map((item) => {
|
|
736
|
+
if (typeof item !== "string" || !item.trim() || item.length > MAX_LINE)
|
|
737
|
+
throw new ToolInputError(`Each item of ${name} must be a non-empty text of at most ${MAX_LINE} characters.`);
|
|
738
|
+
return item.trim();
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* The whole daily briefing e-mail, built in code: subject, HTML, plain text and the inline-image list,
|
|
743
|
+
* ready to pass to any mail tool. The model may supply the three sentences that need judgement (headline,
|
|
744
|
+
* why, watch) in the athlete's language; everything else is deterministic.
|
|
745
|
+
*/
|
|
746
|
+
export async function briefingEmail(deps, params) {
|
|
747
|
+
if (params.lang !== undefined && params.lang !== "en" && params.lang !== "fr")
|
|
748
|
+
throw new ToolInputError("lang must be 'en' or 'fr'.");
|
|
749
|
+
const lang = params.lang ?? deps.config.language;
|
|
750
|
+
if (params.headline !== undefined && params.headline !== null && (typeof params.headline !== "string" || !params.headline.trim() || params.headline.length > MAX_LINE)) {
|
|
751
|
+
throw new ToolInputError(`headline must be one non-empty sentence of at most ${MAX_LINE} characters.`);
|
|
752
|
+
}
|
|
753
|
+
const why = textList(params.why, "why", 3);
|
|
754
|
+
const watch = textList(params.watch, "watch", 4);
|
|
755
|
+
const headline = typeof params.headline === "string" ? params.headline.trim() : undefined;
|
|
756
|
+
// One sync at most: the briefing fetches, the charts reuse the local store.
|
|
757
|
+
const briefing = await dailyBriefing(deps, { date: params.date, sync: params.sync });
|
|
758
|
+
const weekly = params.weekly ?? new Date(`${briefing.date}T12:00:00Z`).getUTCDay() === 0;
|
|
759
|
+
const charts = await briefingCharts(deps, { date: briefing.date, sync: false, lang, theme: "light", charts: weekly ? [...EMAIL_CHARTS, "load_curve"] : EMAIL_CHARTS });
|
|
760
|
+
const night = briefing.sleep.lastNight;
|
|
761
|
+
const sessions = briefing.activities.yesterday.map((line) => ({ type: line.type, name: line.name, durationMin: line.durationMin, avgHr: line.avgHr, load: line.load }));
|
|
762
|
+
const email = renderBriefingEmail({
|
|
763
|
+
lang,
|
|
764
|
+
date: briefing.date,
|
|
765
|
+
ceiling: briefing.readiness.ceiling,
|
|
766
|
+
headline: headline || defaultHeadline(lang, briefing.readiness.ceiling),
|
|
767
|
+
// The rules and caveats of the models are written in English: they are a fallback for English mails only,
|
|
768
|
+
// never mixed into a French one.
|
|
769
|
+
why: why ?? (lang === "en" ? briefing.readiness.reasons.slice(0, 3).map((reason) => reason.detail) : []),
|
|
770
|
+
watch: watch ?? (lang === "en" ? briefing.readiness.caveats.slice(0, 4) : []),
|
|
771
|
+
charts: charts.charts.map((chart) => ({ id: chart.id, cid: chart.cid, displayWidth: chart.displayWidth, alt: chart.alt })),
|
|
772
|
+
sleep: night ? { durationH: night.durationH, needH: night.needH, efficiencyPct: night.efficiencyPct, bedtime: night.bedtime, wakeTime: night.wakeTime } : null,
|
|
773
|
+
sessions,
|
|
774
|
+
load: briefing.load.today ? { ctl: briefing.load.today.ctl, atl: briefing.load.today.atl, tsb: briefing.load.today.tsb, weekChangePct: briefing.load.weekChangePct } : null,
|
|
775
|
+
});
|
|
776
|
+
return {
|
|
777
|
+
date: briefing.date,
|
|
778
|
+
lang,
|
|
779
|
+
ceiling: briefing.readiness.ceiling,
|
|
780
|
+
status: { recovery: briefing.recovery.status, sleep: briefing.sleep.status, load: briefing.load.status },
|
|
781
|
+
subject: email.subject,
|
|
782
|
+
bodyHtml: email.html,
|
|
783
|
+
bodyText: email.text,
|
|
784
|
+
inlineImages: charts.charts.map((chart) => ({ cid: chart.cid, path: chart.path })),
|
|
785
|
+
skipped: charts.skipped,
|
|
786
|
+
notes: [
|
|
787
|
+
...(headline === undefined ? ["headline not supplied: a generic sentence was used."] : []),
|
|
788
|
+
...(why === undefined && lang !== "en" ? ["why not supplied: the section is omitted (default texts are English). Call again with why."] : []),
|
|
789
|
+
...(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."] : []),
|
|
790
|
+
],
|
|
791
|
+
usage: "Send subject, bodyHtml, bodyText and inlineImages unchanged with a mail tool that supports inline images by content id (send_email does). " +
|
|
792
|
+
"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) " +
|
|
793
|
+
"and watch (up to 4 cautions) written in the athlete's language, using only figures from coach_daily_briefing. " +
|
|
794
|
+
"If images cannot be sent, send bodyText alone: the key figures are in it.",
|
|
795
|
+
};
|
|
796
|
+
}
|
package/docs/SCIENCE.md
CHANGED
|
@@ -403,6 +403,10 @@ range (4.2), fitness/fatigue/form (4.6) and sleep against the need (4.5). **No c
|
|
|
403
403
|
anything**: the 7-day HRV line is the same mean of ln rMSSD as in 4.2, and a chart is omitted when its model
|
|
404
404
|
reports too little data. Colours encode the same bands as the text results; they are not clinical thresholds.
|
|
405
405
|
|
|
406
|
+
`coach_briefing_email` assembles these charts and the briefing's own fields into an e-mail with a fixed template. It adds
|
|
407
|
+
no figure: the default "why" and "to watch" texts are the rules and caveats of the readiness decision (4.7), verbatim.
|
|
408
|
+
Texts supplied by the model are limited in length and HTML-escaped.
|
|
409
|
+
|
|
406
410
|
## 5. Level of evidence by element
|
|
407
411
|
|
|
408
412
|
| Element | Nature | Level |
|
package/openclaw.plugin.json
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"coach_journal_insights",
|
|
22
22
|
"coach_workout_push",
|
|
23
23
|
"coach_briefing_charts",
|
|
24
|
+
"coach_briefing_email",
|
|
24
25
|
"coach_data_status"
|
|
25
26
|
]
|
|
26
27
|
},
|
|
@@ -75,6 +76,11 @@
|
|
|
75
76
|
"sideEffecting": true,
|
|
76
77
|
"replaySafe": true
|
|
77
78
|
},
|
|
79
|
+
"coach_briefing_email": {
|
|
80
|
+
"optional": false,
|
|
81
|
+
"sideEffecting": true,
|
|
82
|
+
"replaySafe": true
|
|
83
|
+
},
|
|
78
84
|
"coach_data_status": {
|
|
79
85
|
"optional": false,
|
|
80
86
|
"sideEffecting": false,
|
|
@@ -89,6 +95,15 @@
|
|
|
89
95
|
"type": "string",
|
|
90
96
|
"description": "Path to the garmin-cli `gc` binary (>= 0.4.0). Defaults to \"gc\" (resolved from PATH)."
|
|
91
97
|
},
|
|
98
|
+
"garminBackend": {
|
|
99
|
+
"type": "string",
|
|
100
|
+
"enum": ["auto", "native", "gc"],
|
|
101
|
+
"description": "How Garmin data is fetched: \"native\" runs @sctg/garmin-ts-client in the Gateway process, \"gc\" uses the garmin-cli binary, \"auto\" (default) uses native when the package and a token file are present and gc otherwise. Workout creation always uses gc."
|
|
102
|
+
},
|
|
103
|
+
"garminTokenFile": {
|
|
104
|
+
"type": "string",
|
|
105
|
+
"description": "Token file of the native backend. Defaults to $GARMINTOKENS or ~/.config/garmin-cli/tokens/garmin_tokens.json (the file `gc login` writes)."
|
|
106
|
+
},
|
|
92
107
|
"timezone": {
|
|
93
108
|
"type": "string",
|
|
94
109
|
"description": "IANA timezone of the athlete, used for day boundaries (e.g. Europe/Paris). Defaults to the Gateway timezone."
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sctg/openclaw-coach",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "AI endurance and recovery coach plugin for OpenClaw: documented physiological models (HRV baseline, recovery, sleep, training load, early warning) computed on Garmin Connect data via garmin-cli, with a coaching skill.",
|
|
5
5
|
"icon": "assets/logo.png",
|
|
6
6
|
"type": "module",
|
|
@@ -33,6 +33,9 @@
|
|
|
33
33
|
"@resvg/resvg-js": "2.6.2",
|
|
34
34
|
"typebox": "1.3.17"
|
|
35
35
|
},
|
|
36
|
+
"optionalDependencies": {
|
|
37
|
+
"@sctg/garmin-ts-client": "^0.1.0"
|
|
38
|
+
},
|
|
36
39
|
"devDependencies": {
|
|
37
40
|
"@types/node": "^22.20.3",
|
|
38
41
|
"openclaw": ">=2026.8.2",
|
package/skills/coach/SKILL.md
CHANGED
|
@@ -63,6 +63,7 @@ This is a coaching tool for a healthy, training adult. It is not a medical devic
|
|
|
63
63
|
| `coach_strength_analysis` | One strength session: sets, volume, estimated 1RM. |
|
|
64
64
|
| `coach_journal_log` | Record how the athlete feels, symptoms, session RPE, habits. |
|
|
65
65
|
| `coach_journal_insights` | Associations between logged habits and the following night. |
|
|
66
|
+
| `coach_briefing_email` | The complete daily e-mail built in code (subject, HTML, text, inline images). Optional `headline`, `why`, `watch`. |
|
|
66
67
|
| `coach_briefing_charts` | PNG charts (recovery gauge, ceiling, signals, HRV, load, sleep) to embed in an email or report. |
|
|
67
68
|
| `coach_workout_push` | Create a workout in Garmin Connect, after the athlete approves the preview. |
|
|
68
69
|
| `coach_data_status` | Coverage, sync errors, anchors in use, what to configure. |
|
|
@@ -222,6 +223,13 @@ that.
|
|
|
222
223
|
|
|
223
224
|
### Emailing the briefing with charts
|
|
224
225
|
|
|
226
|
+
Preferred: call `coach_briefing_email` (set `lang`). It returns `subject`, `bodyHtml`, `bodyText` and
|
|
227
|
+
`inlineImages`: send them unchanged with `send_email`. Do not rewrite the HTML. To personalise, call it again
|
|
228
|
+
with `headline` (one sentence: what to do today given `ATHLETE.md` and `PLAN.md`), `why` (up to 3 bullets) and
|
|
229
|
+
`watch` (cautions only), in the athlete's language and with figures taken only from `coach_daily_briefing`.
|
|
230
|
+
|
|
231
|
+
Manual assembly, only if you need a different layout:
|
|
232
|
+
|
|
225
233
|
1. `coach_daily_briefing`, then `coach_briefing_charts` (same date, `sync: false`; set `lang` to the language of the email).
|
|
226
234
|
2. Write the HTML email (inline CSS, one column of at most 600 px): ceiling and one-sentence advice first, then the
|
|
227
235
|
gauge and ceiling side by side, `signals`, the other charts that support the message, and a short table.
|