@sctg/openclaw-coach 2.1.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 CHANGED
@@ -127,6 +127,8 @@ Version 1's `coach_garmin_digest` is gone: replace it with `coach_daily_briefing
127
127
 
128
128
  | Key | Default | Description |
129
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). |
130
132
  | `gcBinary` | `gc` | Path to the garmin-cli binary. |
131
133
  | `timezone` | Gateway timezone | IANA timezone of the athlete (day boundaries). |
132
134
  | `dataDir` | `~/.openclaw/coach` | Local store directory. |
@@ -336,7 +338,7 @@ Gateway uses: that is health data, so choose the provider accordingly (see `docs
336
338
  ```bash
337
339
  npm ci
338
340
  npm run typecheck
339
- npm test # 42 tests, synthetic data, no Garmin access needed
341
+ npm test # 46 tests, synthetic data, no Garmin access needed
340
342
  npm run build
341
343
  ```
342
344
 
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,
@@ -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
+ }
@@ -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,7 +1,7 @@
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 { createGcRunner } from "./garmin/gc.js";
4
+ import { createGarminRunner } from "./garmin/backend.js";
5
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." }));
@@ -184,7 +184,7 @@ export default definePluginEntry({
184
184
  description: "Endurance and recovery coach: documented physiological models computed on Garmin data, with a coaching skill.",
185
185
  register(api) {
186
186
  const config = parseConfig(api.pluginConfig);
187
- const deps = { config, gc: createGcRunner(config.gcBinary) };
187
+ const deps = { config, gc: createGarminRunner(config) };
188
188
  for (const tool of TOOLS) {
189
189
  api.registerTool({
190
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;
package/dist/tools.js CHANGED
@@ -595,6 +595,9 @@ export async function dataStatus(deps, params) {
595
595
  advice.push("The gc binary was not found: install garmin-cli or set gcBinary in the plugin config.");
596
596
  if (Object.values(context.sync?.errors ?? {}).includes("auth"))
597
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.");
598
601
  if (cover.daysWithHrv < 14)
599
602
  advice.push(`HRV baseline needs 14 nights; ${cover.daysWithHrv} available.`);
600
603
  if (!isNum(context.profile.hrMax))
@@ -607,6 +610,7 @@ export async function dataStatus(deps, params) {
607
610
  date: context.date,
608
611
  timezone: deps.config.timezone,
609
612
  dataDir: deps.config.dataDir,
613
+ garminBackend: backend ?? "gc",
610
614
  sync: context.sync ?? "not requested (pass sync: true)",
611
615
  coverage: cover,
612
616
  profile: profileSummary(context.profile),
@@ -95,6 +95,15 @@
95
95
  "type": "string",
96
96
  "description": "Path to the garmin-cli `gc` binary (>= 0.4.0). Defaults to \"gc\" (resolved from PATH)."
97
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
+ },
98
107
  "timezone": {
99
108
  "type": "string",
100
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.1.0",
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",