@sctg/openclaw-coach 2.0.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 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 |
@@ -195,8 +196,31 @@ images until the reader allows them.
195
196
 
196
197
  ## Daily briefing e-mail
197
198
 
198
- The plugin computes and draws; an OpenClaw automation (cron job) asks the agent to assemble and send the
199
- e-mail. Create it as an **isolated agent turn** with delivery disabled, because the mail leaves through
199
+ `coach_briefing_email` builds the whole message in code: subject, HTML (one centred 600 px column, ceiling
200
+ banner, recovery gauge and ceiling side by side, "why", signals, HRV, sleep, "to watch", a text summary table,
201
+ footer), a plain-text version and the list of inline images. The layout does not depend on the model, so a
202
+ small model produces the same mail as a large one. It sends nothing: pass `subject`, `bodyHtml`, `bodyText`
203
+ and `inlineImages` to any mail tool that supports inline images by content id (`send_email` of the
204
+ `sctg-mail` plugin does; with a tool that does not, send `bodyText` alone, the key figures are in it).
205
+
206
+ The model only writes the three sentences that need judgement, in the athlete's language: `headline` (what to
207
+ do today, with `ATHLETE.md` and `PLAN.md` in mind), `why` (up to 3 bullets) and `watch` (up to 4 cautions).
208
+ Left out, `headline` defaults to the meaning of the ceiling in the chosen language; `why` and `watch` default to the
209
+ rules and caveats of the models, which are in English, so they are used for English mails only and the sections
210
+ 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
211
+ is added on Sundays (`weekly: true` forces it).
212
+
213
+ Minimal automation prompt:
214
+
215
+ ```text
216
+ Read ATHLETE.md and PLAN.md. Call coach_briefing_email with lang "fr", then write headline (one sentence: what
217
+ to do today, given my constraints), why (up to 3 bullets with figures and my personal reference) and watch
218
+ (cautions only), using only figures from coach_daily_briefing, and call coach_briefing_email again with them.
219
+ Send the result unchanged with send_email to <my address>: subject, bodyHtml, bodyText, inlineImages.
220
+ If the briefing is an error, send a short text mail instead. Reply only "sent" or the error.
221
+ ```
222
+
223
+ Create the job as an **isolated agent turn** with delivery disabled, because the mail leaves through
200
224
  `send_email`, not through a chat channel:
201
225
 
202
226
  ```bash
@@ -208,7 +232,10 @@ openclaw cron add --name "Briefing entrainement" --cron "0 10 * * *" --tz Europe
208
232
  job, use `openclaw cron edit <id> --message ...`.) A job that runs in the *main* session does not receive the
209
233
  plugin's tools reliably: use an isolated one.
210
234
 
211
- The prompt below is the one used for the sample result. It is shown in English; the original is in French
235
+ ### Custom layout: the full prompt
236
+
237
+ If you want to control the HTML yourself, the model can assemble it from `coach_daily_briefing` and
238
+ `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
239
  and the e-mail is written in the language you ask for (`lang` of `coach_briefing_charts`, or the plugin's
213
240
  `language` setting). Replace `<my address>` before using it.
214
241
 
@@ -309,7 +336,7 @@ Gateway uses: that is health data, so choose the provider accordingly (see `docs
309
336
  ```bash
310
337
  npm ci
311
338
  npm run typecheck
312
- npm test # 40 tests, synthetic data, no Garmin access needed
339
+ npm test # 42 tests, synthetic data, no Garmin access needed
313
340
  npm run build
314
341
  ```
315
342
 
Binary file
@@ -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
+ }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { Type } from "typebox";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { parseConfig } from "./config.js";
4
4
  import { createGcRunner } from "./garmin/gc.js";
5
- import { ToolInputError, activityDeepDive, briefingCharts, CHART_IDS, dailyBriefing, dataStatus, journalInsights, journalLog, strengthAnalysis, trainingLoad, trends, workoutPush, zonesAndPaces, } from "./tools.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",
package/dist/tools.d.ts CHANGED
@@ -425,3 +425,39 @@ export declare function briefingCharts(deps: Deps, params: {
425
425
  }[];
426
426
  usage: string;
427
427
  }>;
428
+ /**
429
+ * The whole daily briefing e-mail, built in code: subject, HTML, plain text and the inline-image list,
430
+ * ready to pass to any mail tool. The model may supply the three sentences that need judgement (headline,
431
+ * why, watch) in the athlete's language; everything else is deterministic.
432
+ */
433
+ export declare function briefingEmail(deps: Deps, params: {
434
+ date?: unknown;
435
+ sync?: boolean;
436
+ lang?: string;
437
+ headline?: unknown;
438
+ why?: unknown;
439
+ watch?: unknown;
440
+ weekly?: boolean;
441
+ }): Promise<{
442
+ date: string;
443
+ lang: Lang;
444
+ ceiling: import("./science/readiness.ts").Ceiling;
445
+ status: {
446
+ recovery: import("./types.ts").DataStatus;
447
+ sleep: import("./types.ts").DataStatus;
448
+ load: import("./types.ts").DataStatus;
449
+ };
450
+ subject: string;
451
+ bodyHtml: string;
452
+ bodyText: string;
453
+ inlineImages: {
454
+ cid: string;
455
+ path: string;
456
+ }[];
457
+ skipped: {
458
+ id: ChartId;
459
+ reason: string;
460
+ }[];
461
+ notes: string[];
462
+ usage: string;
463
+ }>;
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";
@@ -719,3 +720,73 @@ export async function briefingCharts(deps, params) {
719
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.',
720
721
  };
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
+ }
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 |
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sctg/openclaw-coach",
3
- "version": "2.0.0",
3
+ "version": "2.1.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",
@@ -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.