From 2894c18fc556ae363ece92a5c1c91c2518c4f20a Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:57:00 +0000 Subject: [PATCH 1/5] Add trainingpeaks.com tools: login, page context, navigation and availability --- domains/trainingpeaks.com/README.md | 10 + domains/trainingpeaks.com/add_availability.js | 168 +++++++++++ .../trainingpeaks.com/delete_availability.js | 120 ++++++++ domains/trainingpeaks.com/get_page_context.js | 214 +++++++++++++ .../trainingpeaks.com/list_availability.js | 116 ++++++++ domains/trainingpeaks.com/login.js | 172 +++++++++++ domains/trainingpeaks.com/navigate_to_page.js | 66 +++++ lib/trainingpeaks-session.js | 44 +++ registry.json | 84 ++++++ tests/trainingpeaks.test.mjs | 280 ++++++++++++++++++ 10 files changed, 1274 insertions(+) create mode 100644 domains/trainingpeaks.com/README.md create mode 100644 domains/trainingpeaks.com/add_availability.js create mode 100644 domains/trainingpeaks.com/delete_availability.js create mode 100644 domains/trainingpeaks.com/get_page_context.js create mode 100644 domains/trainingpeaks.com/list_availability.js create mode 100644 domains/trainingpeaks.com/login.js create mode 100644 domains/trainingpeaks.com/navigate_to_page.js create mode 100644 lib/trainingpeaks-session.js create mode 100644 tests/trainingpeaks.test.mjs diff --git a/domains/trainingpeaks.com/README.md b/domains/trainingpeaks.com/README.md new file mode 100644 index 00000000..d55242ed --- /dev/null +++ b/domains/trainingpeaks.com/README.md @@ -0,0 +1,10 @@ +# trainingpeaks.com + +| tool | description | +|------|-------------| +| add_availability | Adds one Availability entry (days unable to train, or with limited availability) to the signed-in athlete's calendar and confirms it by reading it back. | +| delete_availability | Deletes one Availability entry by id after checking its start date, and confirms it is gone. | +| get_page_context | Describes the open TrainingPeaks page: page type, signed-in account, calendar range, open forms, live tools, loading state and next steps. | +| list_availability | Lists the signed-in athlete's Availability entries (days off) overlapping a date range of up to 365 days. | +| login | Signs in with username and password, submitting at most once, and confirms the signed-in account; an existing session is confirmed without submitting. | +| navigate_to_page | Schedules navigation to a TrainingPeaks app page (Home, Calendar, Dashboard, ATP, Settings, an Availability entry) and carries the app's site map. | diff --git a/domains/trainingpeaks.com/add_availability.js b/domains/trainingpeaks.com/add_availability.js new file mode 100644 index 00000000..7243fdc9 --- /dev/null +++ b/domains/trainingpeaks.com/add_availability.js @@ -0,0 +1,168 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "add_availability", + title: "Add availability (days off)", + description: "Add one Availability entry to the signed-in athlete's TrainingPeaks calendar, as the calendar's day menu > Add... > Availability form does: a date range (inclusive) when the athlete is unable to train, or has limited availability (optionally naming the sports still possible), with an optional reason (Vacation, Work, Sick, Injury, Appointment, Other) and description. Use it for vacations and other days off; coaches and TrainingPeaks plans see it on the calendar. Runs on https://app.trainingpeaks.com while signed in (use login first). Before writing it reads the range: an identical entry returns already_exists without writing, and any other overlapping entry is refused with overlap unless allow_overlap is true. It sends the form's save request once and never retries; on outcome_unknown call list_availability before trying again. Success is confirmed by reading the entry back. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\" }). Remove an entry with delete_availability.", + inputSchema: { + type: "object", additionalProperties: false, required: ["start_date", "end_date"], + properties: { + start_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "First day, YYYY-MM-DD." }, + end_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Last day (inclusive), YYYY-MM-DD; the same as start_date for one day, at most 364 days later." }, + availability: { enum: ["unavailable", "limited"], default: "unavailable", description: "unavailable: \"I am unable to train\"; limited: \"I have limited availability to train\"." }, + reason: { type: ["string", "null"], enum: ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other", null], default: null, description: "The form's Reason; null is \"No reason selected\"." }, + description: { type: "string", maxLength: 1000, default: "", description: "Free-text description shown on the entry." }, + available_sports: { + type: "array", uniqueItems: true, maxItems: 12, default: [], + items: { enum: ["swim", "bike", "run", "brick", "crosstrain", "mountain_bike", "strength", "custom", "xc_ski", "rowing", "walk", "other"] }, + description: "Only with availability limited: the sports the athlete can still do." + }, + allow_overlap: { type: "boolean", default: false, description: "Create the entry even though another entry overlaps these dates." }, + expected_account: { type: "string", minLength: 1, maxLength: 254, description: "Optional username the entry must be written to; refused as wrong_account otherwise." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "account", "entry", "next_step"], + properties: { + status: { enum: ["created", "already_exists"] }, + account: { type: "string" }, + entry: { + type: "object", additionalProperties: false, required: ["availability_id", "start_date", "end_date", "availability", "reason", "description", "available_sports"], + properties: { + availability_id: { type: "integer" }, start_date: { type: "string" }, end_date: { type: "string" }, + availability: { enum: ["unavailable", "limited"] }, + reason: { type: ["string", "null"] }, description: { type: "string" }, + available_sports: { type: "array", items: { type: "string" } } + } + }, + next_step: { type: "string" } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message", "write_attempted", "overlapping_entries"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "signed_out", "wrong_account", "overlap", "site_rejected", "outcome_unknown", "site_error"] }, + error_message: { type: "string", minLength: 1 }, + write_attempted: { type: "boolean" }, + overlapping_entries: { type: "array", items: { type: "object" } } + } + } + ] + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } + }, + execute: async input => { + // @xwebmcp-inline lib/trainingpeaks-session.js + // TrainingPeaks session and availability model shared by the trainingpeaks.com page tools. The app reads its own + // session token from tpapi.trainingpeaks.com with the browser's cookies; these helpers make the same requests. + const TP_APP_ORIGIN = "https://app.trainingpeaks.com"; + const TP_API = "https://tpapi.trainingpeaks.com"; + const TP_REASONS = ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other"]; + // Workout type ids the Availability form's sport checkboxes use. + const TP_SPORTS = { swim: 1, bike: 2, run: 3, brick: 4, crosstrain: 5, mountain_bike: 8, strength: 9, custom: 10, xc_ski: 11, rowing: 12, walk: 13, other: 100 }; + const tpSportName = id => Object.keys(TP_SPORTS).find(name => TP_SPORTS[name] === id) || "type_" + id; + // The signed-in user as the app sees it, or null when signed out. Never returns the token to the caller. + const tpSession = async () => { + try { + const tokenRes = await fetch(TP_API + "/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch(TP_API + "/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { token, user: { user_id: u.userId, username: String(u.userName || u.username || ""), is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null } }; + } catch { return null; } + }; + const tpDay = value => typeof value === "string" ? value.slice(0, 10) : null; + // One availability entry as the calendar shows it. + const tpAvailability = raw => ({ + availability_id: raw.id, + start_date: tpDay(raw.startDate), + end_date: tpDay(raw.endDate), + availability: raw.limitedAvailability ? "limited" : "unavailable", + reason: TP_REASONS.includes(raw.reason) ? raw.reason : null, + description: typeof raw.description === "string" ? raw.description.slice(0, 2000) : "", + available_sports: Array.isArray(raw.availableSportTypes) ? raw.availableSportTypes.map(tpSportName) : [] + }); + const tpIsDate = value => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value; + const tpDaysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 86400000); + // Availability entries overlapping [start, end], read the way the calendar reads them (at most 365 days per request). + const tpListAvailability = async (session, start, end) => { + const res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + start + "/" + end, { headers: { Authorization: "Bearer " + session.token } }); + if (!res.ok) throw new Error("TrainingPeaks answered " + res.status + " when reading availability."); + const rows = await res.json(); + return (Array.isArray(rows) ? rows : []).map(tpAvailability).sort((x, y) => x.start_date.localeCompare(y.start_date) || x.availability_id - y.availability_id); + }; + // @xwebmcp-end + let written = false; + const fail = (kind, message, overlapping = []) => ({ status: "error", error_kind: kind, error_message: message, write_attempted: written, overlapping_entries: overlapping }); + const KEYS = ["start_date", "end_date", "availability", "reason", "description", "available_sports", "allow_overlap", "expected_account"]; + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object with start_date and end_date."); + const extra = Object.keys(input).filter(k => !KEYS.includes(k)); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); + const start = input.start_date, end = input.end_date; + const availability = input.availability ?? "unavailable"; + const reason = input.reason ?? null; + const description = input.description ?? ""; + const sports = input.available_sports ?? []; + if (!tpIsDate(start) || !tpIsDate(end)) return fail("invalid_input", "start_date and end_date must be real dates in YYYY-MM-DD form."); + if (end < start) return fail("invalid_input", "end_date is before start_date."); + if (tpDaysBetween(start, end) > 364) return fail("invalid_input", "One entry can cover at most 365 days."); + if (!["unavailable", "limited"].includes(availability)) return fail("invalid_input", "availability must be unavailable or limited."); + if (reason !== null && !TP_REASONS.includes(reason)) return fail("invalid_input", "reason must be one of " + TP_REASONS.join(", ") + ", or null."); + if (typeof description !== "string" || description.length > 1000) return fail("invalid_input", "description must be a string of at most 1000 characters."); + if (!Array.isArray(sports) || sports.some(s => !(s in TP_SPORTS)) || new Set(sports).size !== sports.length) return fail("invalid_input", "available_sports must be distinct names from: " + Object.keys(TP_SPORTS).join(", ") + "."); + if (sports.length && availability !== "limited") return fail("invalid_input", "available_sports applies only with availability limited."); + if (input.allow_overlap !== undefined && typeof input.allow_overlap !== "boolean") return fail("invalid_input", "allow_overlap must be true or false."); + if (input.expected_account !== undefined && (typeof input.expected_account !== "string" || !input.expected_account.trim())) return fail("invalid_input", "expected_account must be a username."); + if (location.origin !== TP_APP_ORIGIN) return fail("wrong_page", "Open https://app.trainingpeaks.com/#calendar first (navigate_to_page({ url: \"#calendar\" }))."); + const session = await tpSession(); + if (!session) return fail("signed_out", "TrainingPeaks has no signed-in session in this browser; use login first."); + if (input.expected_account !== undefined && session.user.username.toLowerCase() !== input.expected_account.trim().toLowerCase()) return fail("wrong_account", "This browser is signed in to a different TrainingPeaks account than expected_account; nothing was written."); + if (session.user.is_athlete === false) return fail("wrong_account", "The signed-in account is not an athlete account; this tool writes only to the athlete's own calendar."); + const sameEntry = e => e.start_date === start && e.end_date === end && e.availability === availability; + let existing; + try { existing = await tpListAvailability(session, start, end); } catch (error) { return fail("site_error", String(error && error.message || error).slice(0, 300)); } + const identical = existing.find(sameEntry); + const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\" }) to see it on screen."; + if (identical) return { status: "already_exists", account: session.user.username, entry: identical, next_step: "Nothing was written. " + next }; + if (existing.length && input.allow_overlap !== true) return fail("overlap", "Other availability entries already overlap these dates; nothing was written. Change or delete them, or pass allow_overlap: true.", existing); + // The exact request the Availability form's Save button sends. + const body = { + personId: session.user.user_id, startDate: start, endDate: end, limitedAvailability: availability === "limited", + reason: reason || "", availableSportTypes: sports.map(s => TP_SPORTS[s]), description, type: availability === "limited" ? 2 : 1 + }; + let res; + written = true; + try { + res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability", { + method: "POST", headers: { Authorization: "Bearer " + session.token, "Content-Type": "application/json" }, body: JSON.stringify(body) + }); + } catch { + return fail("outcome_unknown", "The save request did not get an answer; it may still have been saved. Call list_availability for these dates before trying again."); + } + if (!res.ok) { + let detail = ""; + try { const data = await res.json(); detail = (data && (data.message || data.Message)) || ""; } catch { /* no JSON body */ } + return fail("site_rejected", "TrainingPeaks rejected the entry (" + res.status + (detail ? ": " + String(detail).slice(0, 200) : "") + ")."); + } + let createdId = null; + try { const data = await res.json(); if (data && Number.isInteger(data.id)) createdId = data.id; } catch { /* empty body */ } + let after; + try { after = await tpListAvailability(session, start, end); } catch { + return fail("outcome_unknown", "TrainingPeaks accepted the save request but the entry could not be read back; call list_availability for these dates."); + } + const created = after.find(e => createdId !== null ? e.availability_id === createdId : sameEntry(e) && !existing.some(o => o.availability_id === e.availability_id)); + if (!created) return fail("outcome_unknown", "TrainingPeaks accepted the save request but the new entry is not in the calendar's availability; call list_availability for these dates."); + return { status: "created", account: session.user.username, entry: created, next_step: next }; + } +}] diff --git a/domains/trainingpeaks.com/delete_availability.js b/domains/trainingpeaks.com/delete_availability.js new file mode 100644 index 00000000..dd9caa5c --- /dev/null +++ b/domains/trainingpeaks.com/delete_availability.js @@ -0,0 +1,120 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "delete_availability", + title: "Delete an availability entry", + description: "Delete one Availability entry from the signed-in athlete's TrainingPeaks calendar, as the entry's Delete button does after its \"This cannot be undone\" confirmation. Pass the availability_id from list_availability or add_availability together with the entry's start_date, which must still match: this guards against deleting a different entry. Runs on https://app.trainingpeaks.com while signed in. It sends the delete once and confirms the entry is gone by reading the calendar's availability again; on outcome_unknown call list_availability before trying again. Cannot be undone: re-create the entry with add_availability if needed. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\" }).", + inputSchema: { + type: "object", additionalProperties: false, required: ["availability_id", "start_date"], + properties: { + availability_id: { type: "integer", minimum: 1, description: "availability_id from list_availability or add_availability." }, + start_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "The entry's start_date, YYYY-MM-DD, as list_availability reported it." }, + expected_account: { type: "string", minLength: 1, maxLength: 254, description: "Optional username the entry must belong to." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "account", "deleted_entry", "next_step"], + properties: { + status: { const: "deleted" }, + account: { type: "string" }, + deleted_entry: { type: "object", description: "The entry as it was before deletion, in list_availability's shape." }, + next_step: { type: "string" } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message", "write_attempted"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "signed_out", "wrong_account", "not_found", "site_rejected", "outcome_unknown", "site_error"] }, + error_message: { type: "string", minLength: 1 }, + write_attempted: { type: "boolean" } + } + } + ] + }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false } + }, + execute: async input => { + // @xwebmcp-inline lib/trainingpeaks-session.js + // TrainingPeaks session and availability model shared by the trainingpeaks.com page tools. The app reads its own + // session token from tpapi.trainingpeaks.com with the browser's cookies; these helpers make the same requests. + const TP_APP_ORIGIN = "https://app.trainingpeaks.com"; + const TP_API = "https://tpapi.trainingpeaks.com"; + const TP_REASONS = ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other"]; + // Workout type ids the Availability form's sport checkboxes use. + const TP_SPORTS = { swim: 1, bike: 2, run: 3, brick: 4, crosstrain: 5, mountain_bike: 8, strength: 9, custom: 10, xc_ski: 11, rowing: 12, walk: 13, other: 100 }; + const tpSportName = id => Object.keys(TP_SPORTS).find(name => TP_SPORTS[name] === id) || "type_" + id; + // The signed-in user as the app sees it, or null when signed out. Never returns the token to the caller. + const tpSession = async () => { + try { + const tokenRes = await fetch(TP_API + "/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch(TP_API + "/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { token, user: { user_id: u.userId, username: String(u.userName || u.username || ""), is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null } }; + } catch { return null; } + }; + const tpDay = value => typeof value === "string" ? value.slice(0, 10) : null; + // One availability entry as the calendar shows it. + const tpAvailability = raw => ({ + availability_id: raw.id, + start_date: tpDay(raw.startDate), + end_date: tpDay(raw.endDate), + availability: raw.limitedAvailability ? "limited" : "unavailable", + reason: TP_REASONS.includes(raw.reason) ? raw.reason : null, + description: typeof raw.description === "string" ? raw.description.slice(0, 2000) : "", + available_sports: Array.isArray(raw.availableSportTypes) ? raw.availableSportTypes.map(tpSportName) : [] + }); + const tpIsDate = value => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value; + const tpDaysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 86400000); + // Availability entries overlapping [start, end], read the way the calendar reads them (at most 365 days per request). + const tpListAvailability = async (session, start, end) => { + const res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + start + "/" + end, { headers: { Authorization: "Bearer " + session.token } }); + if (!res.ok) throw new Error("TrainingPeaks answered " + res.status + " when reading availability."); + const rows = await res.json(); + return (Array.isArray(rows) ? rows : []).map(tpAvailability).sort((x, y) => x.start_date.localeCompare(y.start_date) || x.availability_id - y.availability_id); + }; + // @xwebmcp-end + let written = false; + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message, write_attempted: written }); + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be { availability_id, start_date }."); + const extra = Object.keys(input).filter(k => !["availability_id", "start_date", "expected_account"].includes(k)); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); + const id = input.availability_id, start = input.start_date; + if (!Number.isInteger(id) || id < 1) return fail("invalid_input", "availability_id must be a positive integer from list_availability."); + if (!tpIsDate(start)) return fail("invalid_input", "start_date must be a real date in YYYY-MM-DD form."); + if (input.expected_account !== undefined && (typeof input.expected_account !== "string" || !input.expected_account.trim())) return fail("invalid_input", "expected_account must be a username."); + if (location.origin !== TP_APP_ORIGIN) return fail("wrong_page", "Open https://app.trainingpeaks.com/#calendar first (navigate_to_page({ url: \"#calendar\" }))."); + const session = await tpSession(); + if (!session) return fail("signed_out", "TrainingPeaks has no signed-in session in this browser; use login first."); + if (input.expected_account !== undefined && session.user.username.toLowerCase() !== input.expected_account.trim().toLowerCase()) return fail("wrong_account", "This browser is signed in to a different TrainingPeaks account than expected_account; nothing was deleted."); + let before; + try { before = await tpListAvailability(session, start, start); } catch (error) { return fail("site_error", String(error && error.message || error).slice(0, 300)); } + const entry = before.find(e => e.availability_id === id); + if (!entry || entry.start_date !== start) return fail("not_found", "No availability entry " + id + " starting on " + start + " on this account; nothing was deleted. Check list_availability."); + written = true; + let res; + try { + res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + id, { method: "DELETE", headers: { Authorization: "Bearer " + session.token } }); + } catch { + return fail("outcome_unknown", "The delete request did not get an answer; it may still have happened. Call list_availability before trying again."); + } + if (!res.ok) return fail("site_rejected", "TrainingPeaks refused to delete the entry (" + res.status + ")."); + let after; + try { after = await tpListAvailability(session, start, start); } catch { + return fail("outcome_unknown", "TrainingPeaks accepted the delete but availability could not be read again; call list_availability."); + } + if (after.some(e => e.availability_id === id)) return fail("outcome_unknown", "TrainingPeaks accepted the delete but the entry is still listed; call list_availability."); + return { status: "deleted", account: session.user.username, deleted_entry: entry, next_step: "Reload the calendar with navigate_to_page({ url: \"#calendar\" }) to see the change on screen." }; + } +}] diff --git a/domains/trainingpeaks.com/get_page_context.js b/domains/trainingpeaks.com/get_page_context.js new file mode 100644 index 00000000..3f084be1 --- /dev/null +++ b/domains/trainingpeaks.com/get_page_context.js @@ -0,0 +1,214 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "get_page_context", + title: "Describe the open TrainingPeaks page", + description: "Describe the TrainingPeaks page open in this tab so you can decide what to do next: page type (the login page, the app's Home, Calendar, Dashboard, ATP plan or Settings, an open workout, activity or Availability entry, another trainingpeaks.com page), whether a user is signed in and which (username, user_id, athlete or not), on the Calendar the first and last dates it has drawn and today, whether an Availability form is open, whether the cookie-consent banner is covering the page, which WebMCP tools this page exposes now, whether the page is still loading, and suggested next steps. Call it after every navigation, after login, or whenever you are unsure where the tab is; navigate_to_page opens another page. Read-only: never clicks, types or navigates, and never returns a token or password. Pass wait_for_settled_seconds to wait for the page to finish loading.", + inputSchema: { + type: "object", additionalProperties: false, + properties: { + wait_for_settled_seconds: { type: "integer", minimum: 0, maximum: 30, default: 0, description: "Wait up to this long for loading states to clear before answering." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, + required: ["status", "current_url", "page_type", "open_item", "signed_in", "account", "calendar", "availability_form_open", "consent_banner_visible", "available_tools", "unsettled", "unsettled_reasons", "page_messages", "suggested_next_steps"], + properties: { + status: { const: "ok" }, + current_url: { type: "string" }, + page_type: { enum: ["login", "app_landing", "home", "calendar", "dashboard", "plan", "settings", "discover", "manage_athletes", "item", "website", "other"] }, + open_item: { + type: ["object", "null"], additionalProperties: false, required: ["item_type", "item_id"], + description: "The workout, activity or Availability entry the address opens, if any.", + properties: { item_type: { enum: ["workout", "activity", "availability"] }, item_id: { type: "integer" } } + }, + signed_in: { type: ["boolean", "null"], description: "null when it could not be determined." }, + account: { + type: ["object", "null"], additionalProperties: false, required: ["username", "user_id", "is_athlete"], + properties: { username: { type: "string" }, user_id: { type: "integer" }, is_athlete: { type: ["boolean", "null"] } } + }, + calendar: { + type: ["object", "null"], additionalProperties: false, required: ["first_drawn_date", "last_drawn_date", "today"], + description: "On the Calendar: the range of days it has drawn so far (it draws more while scrolling) and today's date.", + properties: { first_drawn_date: { type: ["string", "null"] }, last_drawn_date: { type: ["string", "null"] }, today: { type: ["string", "null"] } } + }, + availability_form_open: { type: "boolean", description: "The full-screen Availability form (Save, Cancel, Delete) is open." }, + consent_banner_visible: { type: "boolean", description: "The cookie-consent banner is showing; it can cover buttons near the bottom of the page. No tool answers it for the user." }, + available_tools: { type: ["array", "null"], items: { type: "string" }, description: "Tool names this page exposes now, or null when the page's tool list cannot be read." }, + unsettled: { type: "boolean" }, + unsettled_reasons: { type: "array", items: { enum: ["document_loading", "navigating", "app_loading", "busy_region"] } }, + page_messages: { type: "array", maxItems: 10, items: { type: "string", maxLength: 300 } }, + suggested_next_steps: { type: "array", items: { type: "string" } } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page"] }, + error_message: { type: "string", minLength: 1 } + } + } + ] + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } + }, + execute: async input => { + // @xwebmcp-inline lib/trainingpeaks-session.js + // TrainingPeaks session and availability model shared by the trainingpeaks.com page tools. The app reads its own + // session token from tpapi.trainingpeaks.com with the browser's cookies; these helpers make the same requests. + const TP_APP_ORIGIN = "https://app.trainingpeaks.com"; + const TP_API = "https://tpapi.trainingpeaks.com"; + const TP_REASONS = ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other"]; + // Workout type ids the Availability form's sport checkboxes use. + const TP_SPORTS = { swim: 1, bike: 2, run: 3, brick: 4, crosstrain: 5, mountain_bike: 8, strength: 9, custom: 10, xc_ski: 11, rowing: 12, walk: 13, other: 100 }; + const tpSportName = id => Object.keys(TP_SPORTS).find(name => TP_SPORTS[name] === id) || "type_" + id; + // The signed-in user as the app sees it, or null when signed out. Never returns the token to the caller. + const tpSession = async () => { + try { + const tokenRes = await fetch(TP_API + "/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch(TP_API + "/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { token, user: { user_id: u.userId, username: String(u.userName || u.username || ""), is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null } }; + } catch { return null; } + }; + const tpDay = value => typeof value === "string" ? value.slice(0, 10) : null; + // One availability entry as the calendar shows it. + const tpAvailability = raw => ({ + availability_id: raw.id, + start_date: tpDay(raw.startDate), + end_date: tpDay(raw.endDate), + availability: raw.limitedAvailability ? "limited" : "unavailable", + reason: TP_REASONS.includes(raw.reason) ? raw.reason : null, + description: typeof raw.description === "string" ? raw.description.slice(0, 2000) : "", + available_sports: Array.isArray(raw.availableSportTypes) ? raw.availableSportTypes.map(tpSportName) : [] + }); + const tpIsDate = value => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value; + const tpDaysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 86400000); + // Availability entries overlapping [start, end], read the way the calendar reads them (at most 365 days per request). + const tpListAvailability = async (session, start, end) => { + const res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + start + "/" + end, { headers: { Authorization: "Bearer " + session.token } }); + if (!res.ok) throw new Error("TrainingPeaks answered " + res.status + " when reading availability."); + const rows = await res.json(); + return (Array.isArray(rows) ? rows : []).map(tpAvailability).sort((x, y) => x.start_date.localeCompare(y.start_date) || x.availability_id - y.availability_id); + }; + // @xwebmcp-end + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message }); + if (input === undefined || input === null) input = {}; + if (typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object."); + const extra = Object.keys(input).find(k => k !== "wait_for_settled_seconds"); + if (extra) return fail("invalid_input", "Unrecognized input field \"" + extra + "\"."); + const wait = input.wait_for_settled_seconds ?? 0; + if (!Number.isInteger(wait) || wait < 0 || wait > 30) return fail("invalid_input", "wait_for_settled_seconds must be an integer from 0 to 30."); + if (!/(^|\.)trainingpeaks\.com$/.test(location.hostname)) return fail("wrong_page", "Open a trainingpeaks.com page first."); + + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + const visible = el => !!el && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden"; + const text = el => (el && el.textContent ? el.textContent : "").replace(/\s+/g, " ").trim(); + const inApp = location.origin === TP_APP_ORIGIN; + const route = inApp ? location.hash.replace(/^#\/?/, "") : ""; + const seg = route.split("/").filter(Boolean); + let pageType = "other"; + if (location.hostname === "home.trainingpeaks.com" && /^\/login\/?$/i.test(location.pathname)) pageType = "login"; + else if (!inApp) pageType = "website"; + else if (!seg.length) pageType = "app_landing"; + else pageType = { home: "home", calendar: "calendar", dashboard: "dashboard", plan: "plan", settings: "settings", discover: "discover", manageAthletes: "manage_athletes", workouts: "item", activities: "item", availability: "item" }[seg[0]] || "other"; + let openItem = null; + const ITEM_TYPES = { workouts: "workout", activities: "activity", availability: "availability" }; + for (let i = seg.length - 2; i >= 0; i--) { + if (ITEM_TYPES[seg[i]] && /^\d{1,12}$/.test(seg[i + 1])) { openItem = { item_type: ITEM_TYPES[seg[i]], item_id: Number(seg[i + 1]) }; break; } + } + + const reasons = () => { + const out = []; + if (document.readyState !== "complete") out.push("document_loading"); + const mark = globalThis.__xwebmcpTrainingPeaksNavigation; + if (mark && mark.from === location.href && Date.now() - mark.at < 20000) out.push("navigating"); + if (pageType === "calendar" && !document.querySelector(".day[data-date]")) out.push("app_loading"); + if (inApp && !document.querySelector(".frameworkMainWrapper, #main, [data-cy]")) out.push("app_loading"); + if ([...document.querySelectorAll('[aria-busy="true"], [role="progressbar"]')].some(visible)) out.push("busy_region"); + return [...new Set(out)]; + }; + if (wait > 0) { + const until = Date.now() + wait * 1000; + while (Date.now() < until && reasons().length) await sleep(250); + } + const unsettled = reasons(); + + const session = await tpSession(); + const signedIn = session ? true : pageType === "login" || inApp ? false : null; + const account = session ? session.user : null; + let calendar = null; + if (pageType === "calendar") { + const days = [...document.querySelectorAll(".day[data-date]")].map(d => d.dataset.date).filter(tpIsDate).sort(); + const today = document.querySelector(".day.today[data-date]"); + calendar = { first_drawn_date: days[0] || null, last_drawn_date: days[days.length - 1] || null, today: today ? today.dataset.date : null }; + } + const formOpen = [...document.querySelectorAll('[data-cy="availabilityEditor"]')].some(visible); + const banner = [...document.querySelectorAll("#onetrust-banner-sdk, #onetrust-pc-sdk")].some(visible); + + let tools = null; + try { + const mc = document.modelContext || navigator.modelContext; + if (mc && typeof mc.getTools === "function") tools = [...new Set(((await mc.getTools()) || []).map(t => String(t?.name ?? t).split(".").pop()).filter(Boolean))].sort(); + } catch { tools = null; } + const has = name => tools === null || tools.includes(name); + + const messages = []; + for (const el of document.querySelectorAll('[role="alert"], .validation-summary-errors, .MuiAlert-message')) { + const t = text(el).slice(0, 300); + if (t.length <= 3 || !visible(el) || messages.includes(t)) continue; + messages.push(t); + if (messages.length >= 10) break; + } + + const go = url => has("navigate_to_page") ? "navigate_to_page({ url: \"" + url + "\" })" : "open " + TP_APP_ORIGIN + "/" + url; + const steps = []; + if (unsettled.includes("navigating")) steps.push("A navigation was just scheduled: wait, then call get_page_context again and list tools again."); + else if (unsettled.length) steps.push("The page is still loading (" + unsettled.join(", ") + "): call get_page_context with wait_for_settled_seconds before acting."); + if (!session) { + if (has("login")) steps.push("Not signed in: use login with the user's TrainingPeaks username and password (from a credential store, never from chat)."); + else steps.push("Not signed in: the login tool signs in from any trainingpeaks.com page."); + } else { + if (formOpen) steps.push("An Availability form is open. Its Save and Delete are the user's; to change entries use add_availability or delete_availability, and leave the form with " + go("#calendar") + " (needs discard_form: true)."); + if (pageType === "calendar" || pageType === "item") { + if (has("list_availability")) steps.push("Use list_availability({ start_date, end_date }) to read days off (unavailable or limited) in a range."); + if (has("add_availability")) steps.push("Use add_availability({ start_date, end_date, availability: \"unavailable\", reason: \"Vacation\" }) to add days off; then " + go("#calendar") + " reloads the calendar to show it."); + } else if (pageType === "login" || pageType === "website" || pageType === "app_landing" || pageType === "other") { + steps.push("Signed in. Days off (Availability) live on the calendar: " + go("#calendar") + "."); + } else { + steps.push("For days off (Availability), " + go("#calendar") + "."); + } + if (account && account.is_athlete === false) steps.push("This is not an athlete account; the availability tools write only to the signed-in athlete's own calendar."); + } + if (banner) steps.push("The cookie-consent banner is showing and can cover buttons near the bottom of the page. Do not choose a consent option for the user."); + + return { + status: "ok", + current_url: location.href.slice(0, 2000), + page_type: pageType, + open_item: openItem, + signed_in: signedIn, + account, + calendar, + availability_form_open: formOpen, + consent_banner_visible: banner, + available_tools: tools, + unsettled: unsettled.length > 0, + unsettled_reasons: unsettled, + page_messages: messages, + suggested_next_steps: steps + }; + } +}] diff --git a/domains/trainingpeaks.com/list_availability.js b/domains/trainingpeaks.com/list_availability.js new file mode 100644 index 00000000..54c46fca --- /dev/null +++ b/domains/trainingpeaks.com/list_availability.js @@ -0,0 +1,116 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "list_availability", + title: "List availability (days off)", + description: "List the signed-in athlete's TrainingPeaks Availability entries (the calendar's \"unable to train\" and \"limited availability\" days, often used for vacations) that overlap a date range of at most 365 days. Each entry has its availability_id, start and end dates (inclusive), availability (unavailable or limited), reason, description and, for limited entries, the sports still possible. Runs on https://app.trainingpeaks.com while signed in (use login first). Read-only: it makes the same read the calendar makes and never clicks or navigates. An empty list means TrainingPeaks has no entry overlapping the range, not that the athlete is free.", + inputSchema: { + type: "object", additionalProperties: false, required: ["start_date", "end_date"], + properties: { + start_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "First day of the range, YYYY-MM-DD." }, + end_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Last day of the range, YYYY-MM-DD; at most 364 days after start_date." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "account", "start_date", "end_date", "entries"], + properties: { + status: { const: "ok" }, + account: { type: "string", description: "Username of the signed-in athlete the entries belong to." }, + start_date: { type: "string" }, end_date: { type: "string" }, + entries: { + type: "array", + items: { + type: "object", additionalProperties: false, required: ["availability_id", "start_date", "end_date", "availability", "reason", "description", "available_sports"], + properties: { + availability_id: { type: "integer" }, + start_date: { type: "string" }, end_date: { type: "string" }, + availability: { enum: ["unavailable", "limited"] }, + reason: { type: ["string", "null"], enum: ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other", null] }, + description: { type: "string" }, + available_sports: { type: "array", items: { type: "string" } } + } + } + } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "signed_out", "site_error"] }, + error_message: { type: "string", minLength: 1 } + } + } + ] + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } + }, + execute: async input => { + // @xwebmcp-inline lib/trainingpeaks-session.js + // TrainingPeaks session and availability model shared by the trainingpeaks.com page tools. The app reads its own + // session token from tpapi.trainingpeaks.com with the browser's cookies; these helpers make the same requests. + const TP_APP_ORIGIN = "https://app.trainingpeaks.com"; + const TP_API = "https://tpapi.trainingpeaks.com"; + const TP_REASONS = ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other"]; + // Workout type ids the Availability form's sport checkboxes use. + const TP_SPORTS = { swim: 1, bike: 2, run: 3, brick: 4, crosstrain: 5, mountain_bike: 8, strength: 9, custom: 10, xc_ski: 11, rowing: 12, walk: 13, other: 100 }; + const tpSportName = id => Object.keys(TP_SPORTS).find(name => TP_SPORTS[name] === id) || "type_" + id; + // The signed-in user as the app sees it, or null when signed out. Never returns the token to the caller. + const tpSession = async () => { + try { + const tokenRes = await fetch(TP_API + "/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch(TP_API + "/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { token, user: { user_id: u.userId, username: String(u.userName || u.username || ""), is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null } }; + } catch { return null; } + }; + const tpDay = value => typeof value === "string" ? value.slice(0, 10) : null; + // One availability entry as the calendar shows it. + const tpAvailability = raw => ({ + availability_id: raw.id, + start_date: tpDay(raw.startDate), + end_date: tpDay(raw.endDate), + availability: raw.limitedAvailability ? "limited" : "unavailable", + reason: TP_REASONS.includes(raw.reason) ? raw.reason : null, + description: typeof raw.description === "string" ? raw.description.slice(0, 2000) : "", + available_sports: Array.isArray(raw.availableSportTypes) ? raw.availableSportTypes.map(tpSportName) : [] + }); + const tpIsDate = value => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value; + const tpDaysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 86400000); + // Availability entries overlapping [start, end], read the way the calendar reads them (at most 365 days per request). + const tpListAvailability = async (session, start, end) => { + const res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + start + "/" + end, { headers: { Authorization: "Bearer " + session.token } }); + if (!res.ok) throw new Error("TrainingPeaks answered " + res.status + " when reading availability."); + const rows = await res.json(); + return (Array.isArray(rows) ? rows : []).map(tpAvailability).sort((x, y) => x.start_date.localeCompare(y.start_date) || x.availability_id - y.availability_id); + }; + // @xwebmcp-end + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message }); + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be { start_date, end_date }."); + const extra = Object.keys(input).filter(k => !["start_date", "end_date"].includes(k)); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); + const { start_date: start, end_date: end } = input; + if (!tpIsDate(start) || !tpIsDate(end)) return fail("invalid_input", "start_date and end_date must be real dates in YYYY-MM-DD form."); + if (end < start) return fail("invalid_input", "end_date is before start_date."); + if (tpDaysBetween(start, end) > 364) return fail("invalid_input", "TrainingPeaks reads at most 365 days at a time; split the range."); + if (location.origin !== TP_APP_ORIGIN) return fail("wrong_page", "Open https://app.trainingpeaks.com/#calendar first (navigate_to_page({ url: \"#calendar\" }))."); + const session = await tpSession(); + if (!session) return fail("signed_out", "TrainingPeaks has no signed-in session in this browser; use login first."); + try { + return { status: "ok", account: session.user.username, start_date: start, end_date: end, entries: await tpListAvailability(session, start, end) }; + } catch (error) { + return fail("site_error", String(error && error.message || error).slice(0, 300)); + } + } +}] diff --git a/domains/trainingpeaks.com/login.js b/domains/trainingpeaks.com/login.js new file mode 100644 index 00000000..d8755e33 --- /dev/null +++ b/domains/trainingpeaks.com/login.js @@ -0,0 +1,172 @@ +[{ + kind: "cdp", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "login", + description: "Sign in to TrainingPeaks (https://home.trainingpeaks.com/login) with a username and password, and confirm the session belongs to exactly that username. If the browser already has a TrainingPeaks session it submits nothing: the same username returns success with entry already_signed_in, a different one fails with wrong_account (sign out first; this tool never switches or signs out accounts). Otherwise it loads a fresh login page, waits for the page's own reCAPTCHA token, fills the Login form and submits it once; it never retries. Success leaves the tab on the TrainingPeaks app, where the other trainingpeaks.com tools run. A rejected password returns invalid_credentials: do not loop on it, the account may be locked. A second-factor prompt returns mfa_required and is left open in the page. The whole call is bounded to about 80 seconds, so invoke it with a timeout of at least 90 seconds. The password is only typed into the TrainingPeaks form and never returned.", + inputSchema: { + type: "object", additionalProperties: false, required: ["username", "password"], + properties: { + username: { type: "string", minLength: 1, maxLength: 254, pattern: "^\\S+$", description: "TrainingPeaks username (or account email) as typed into the Username field." }, + password: { type: "string", minLength: 1, maxLength: 256, description: "Account password; never returned or logged." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "logged_in", "account", "entry", "submission_attempted", "landing_url", "next_actions"], + properties: { + status: { const: "ok" }, logged_in: { const: true }, + account: { + type: "object", additionalProperties: false, required: ["username", "user_id", "is_athlete"], + properties: { username: { type: "string" }, user_id: { type: "integer" }, is_athlete: { type: ["boolean", "null"] } }, + description: "The signed-in user as TrainingPeaks reports it; username always matches the supplied username or email." + }, + entry: { enum: ["already_signed_in", "form_submitted"] }, + submission_attempted: { type: "boolean" }, + landing_url: { type: "string", format: "uri" }, + next_actions: { type: "array", items: { type: "string" } } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "logged_in", "error_kind", "error_message", "error_source", "step", "submission_attempted", "signed_in_account"], + properties: { + status: { const: "error" }, logged_in: { const: false }, + error_kind: { enum: ["invalid_input", "wrong_account", "invalid_credentials", "mfa_required", "captcha_unavailable", "locked_or_throttled", "recent_submission", "unknown"] }, + error_message: { type: "string", minLength: 1 }, + error_source: { enum: ["site", "tool"] }, + step: { enum: ["input", "session_check", "login_form", "before_submit", "after_submit"] }, + submission_attempted: { type: "boolean" }, + signed_in_account: { type: ["string", "null"], description: "For wrong_account: the username TrainingPeaks is actually signed in to." } + } + } + ] + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false } + }, + execute: async (input) => { + const LOGIN = "https://home.trainingpeaks.com/login"; + const MARKER = "xwebmcp.trainingpeaks.login_submitted_at"; + const startedAt = Date.now(); + const remaining = () => 80000 - (Date.now() - startedAt); + let step = "input"; + let submitted = false; + const fail = (kind, message, source = "tool", signedIn = null) => ({ status: "error", logged_in: false, error_kind: kind, error_message: message, error_source: source, step, submission_attempted: submitted, signed_in_account: signedIn }); + if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["username", "password"].includes(key))) return fail("invalid_input", "Input must be { username, password }; nothing was submitted."); + const { username, password } = input; + if (typeof username !== "string" || !username.trim() || username.trim().length > 254 || /\s/.test(username.trim())) return fail("invalid_input", "username must be 1-254 characters without spaces; nothing was submitted."); + if (typeof password !== "string" || !password.length || password.length > 256) return fail("invalid_input", "password must be 1-256 characters; nothing was submitted."); + const wanted = username.trim().toLowerCase(); + const matches = account => !!account && (account.username.toLowerCase() === wanted || (account.email || "").toLowerCase() === wanted); + const ok = (account, entry, url) => ({ + status: "ok", logged_in: true, entry, submission_attempted: submitted, landing_url: url, + account: { username: account.username, user_id: account.user_id, is_athlete: account.is_athlete }, + next_actions: ["Call get_page_context({ wait_for_settled_seconds: 10 }) and list tools again: the tab may be on another page and earlier tool_refs are no longer valid.", "For days off, open the calendar with navigate_to_page({ url: \"#calendar\" }) and use list_availability or add_availability."] + }); + // The signed-in user, read through the same session API the TrainingPeaks app uses; null when signed out. + const whoami = () => js(async () => { + try { + const tokenRes = await fetch("https://tpapi.trainingpeaks.com/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch("https://tpapi.trainingpeaks.com/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { username: String(u.userName || u.username || ""), email: u.email ? String(u.email) : null, user_id: u.userId, is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null }; + } catch { return null; } + }); + const read = () => js(() => { + const visible = e => !!e && e.getClientRects().length > 0 && getComputedStyle(e).visibility !== "hidden"; + const user = document.getElementById("Username"); + const pass = document.getElementById("Password"); + const errors = [...document.querySelectorAll(".validation-summary-errors li, .validation-summary-errors, .field-validation-error, [role=alert]")] + .filter(visible).map(e => e.textContent.trim()).filter(Boolean); + const codeField = [...document.querySelectorAll("input")].find(e => visible(e) && e.type !== "hidden" && e.type !== "password" && e.id !== "Username" && /one-time-code|otp|mfa|2fa|two.?factor|verification|code/i.test([e.autocomplete, e.id, e.name, e.placeholder, e.getAttribute("aria-label")].join(" "))); + const tokenField = document.getElementById("captcha-token"); + return { + url: location.href, host: location.hostname, path: location.pathname, + form: visible(user) && visible(pass) && visible(document.getElementById("btnSubmit")), + captcha_ready: !!(tokenField && tokenField.value), + error: errors[0] || null, + code_step: !!codeField || /\/(mfa|verify|two-?factor)/i.test(location.pathname), + marker: (() => { try { return Number(sessionStorage.getItem("xwebmcp.trainingpeaks.login_submitted_at")) || 0; } catch { return 0; } })() + }; + }); + let latest = null; + const poll = async (predicate, ms) => { + const deadline = Date.now() + Math.min(ms, remaining()); + while (Date.now() < deadline) { + try { latest = await read(); if (await predicate(latest)) return latest; } catch { /* the document is being replaced */ } + await waitMs(500); + } + return null; + }; + + step = "session_check"; + let info = null; + try { info = await pageInfo(); } catch { /* no usable page yet */ } + if (!info || !/^https:\/\/([a-z0-9-]+\.)*trainingpeaks\.com\//.test(info.url)) { + await gotoUrl(LOGIN); + await waitForLoad(30); + } + const current = await whoami(); + if (current) { + if (!matches(current)) return fail("wrong_account", "The browser is already signed in to a different TrainingPeaks account. Sign out before signing in as the supplied username; nothing was submitted.", "tool", current.username); + const here = await pageInfo(); + return ok(current, "already_signed_in", here.url); + } + + step = "login_form"; + // The page fetches a reCAPTCHA v3 token on load and it expires after two minutes, so always start from a fresh login page. + await gotoUrl(LOGIN); + await waitForLoad(30); + if (!await poll(s => s.form, 20000)) return fail("unknown", "The TrainingPeaks login form did not appear" + (latest ? " (the tab is on " + latest.host + latest.path + ")" : "") + "; nothing was submitted."); + step = "before_submit"; + if (latest.marker && Date.now() - latest.marker < 60000) return fail("recent_submission", "A sign-in was submitted from this tab less than a minute ago with no observed result. Check the page before invoking again; nothing was submitted."); + if (!await poll(s => s.captcha_ready, 15000)) return fail("captcha_unavailable", "The login page's reCAPTCHA token was not issued, so the form would be rejected; nothing was submitted."); + if (remaining() < 30000) return fail("unknown", "Too little time remains to observe the result; nothing was submitted."); + await fillInput("#Username", username.trim()); + await fillInput("#Password", password); + const filled = await js(expected => document.getElementById("Username").value.trim().toLowerCase() === expected && document.getElementById("Password").value.length > 0 && document.activeElement === document.getElementById("Password"), { arg: wanted }); + if (!filled) return fail("unknown", "The login form did not accept the typed values; nothing was submitted."); + await js(key => { try { sessionStorage.setItem(key, String(Date.now())); } catch { /* storage unavailable */ } }, { arg: MARKER }); + // Press Enter in the focused Password field: the cookie-consent overlay can cover the Login button, and a + // keyboard submit sends the same form without making a consent choice for the user. + try { + submitted = true; + await pressKey("Enter"); + } catch (error) { + if (!submitted) { + await js(key => { try { sessionStorage.removeItem(key); } catch { /* storage unavailable */ } }, { arg: MARKER }); + return fail("unknown", "The login form could not be submitted (" + String(error && error.message || error).slice(0, 120) + "); nothing was submitted."); + } + } + + step = "after_submit"; + let account = null; + const done = await poll(async s => { + if (s.code_step || (s.error && s.path.toLowerCase().startsWith("/login"))) return true; + if (s.form) return false; + account = await whoami(); + return !!account; + }, remaining() - 1000); + const clearMarker = async () => { try { await js(key => { try { sessionStorage.removeItem(key); } catch { /* storage unavailable */ } }, { arg: MARKER }); } catch { /* now on another origin */ } }; + if (!done) return fail("unknown", "No result was observed after submitting the form; the sign-in may still complete. Check the page before invoking again."); + if (account) { + await clearMarker(); + if (!matches(account)) return fail("wrong_account", "TrainingPeaks signed in, but to a different account than the supplied username. Sign out and try again.", "site", account.username); + return ok(account, "form_submitted", done.url); + } + await clearMarker(); + if (done.code_step) return fail("mfa_required", "TrainingPeaks asked for a second factor, which this tool does not enter; finish it in the page.", "site"); + const text = done.error; + if (/too many|locked|try again later/i.test(text)) return fail("locked_or_throttled", "TrainingPeaks: " + text, "site"); + if (/incorrect|invalid|wrong|not found|password|username/i.test(text)) return fail("invalid_credentials", "TrainingPeaks: " + text, "site"); + return fail("unknown", "TrainingPeaks: " + text, "site"); + } +}] diff --git a/domains/trainingpeaks.com/navigate_to_page.js b/domains/trainingpeaks.com/navigate_to_page.js new file mode 100644 index 00000000..202e5ce5 --- /dev/null +++ b/domains/trainingpeaks.com/navigate_to_page.js @@ -0,0 +1,66 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "navigate_to_page", + title: "Open a page in the TrainingPeaks app", + description: "Navigate this tab to a page of the TrainingPeaks web app (https://app.trainingpeaks.com), whose pages are # routes. The tab changes after this tool returns; then call get_page_context({ wait_for_settled_seconds: 10 }) and list tools again, because tool_refs can change. Passing the address already open reloads it, which is how to show changes made by add_availability or delete_availability. Pages:\n- #home - Home: the athlete's events, goals and performance summary\n- #calendar - Calendar of workouts, notes and Availability (days off); list_availability, add_availability and delete_availability work from here\n- #calendar/athletes/USER_ID/availability/AVAILABILITY_ID - Opens one Availability entry's form (user_id from get_page_context, availability_id from list_availability); its Save and Delete are left to the user or to the availability tools\n- #dashboard - Dashboard charts (fitness, fatigue, form)\n- #plan - ATP, the Annual Training Plan\n- #settings - Account and athlete settings\nExample: navigate_to_page({ url: \"#calendar\" })\nurl is a # route, a path on app.trainingpeaks.com, or a full https://app.trainingpeaks.com URL; other sites and hosts are refused (sign in with the login tool, not by opening the login page). While an Availability form is open it refuses to leave unless discard_form is true, because leaving drops unsaved edits. The result says the navigation was scheduled, not that the page loaded.", + inputSchema: { + type: "object", additionalProperties: false, required: ["url"], + properties: { + url: { type: "string", minLength: 1, maxLength: 2000, pattern: "^(#|/(?!/)|https://app\\.trainingpeaks\\.com([/?#]|$))", description: "A # route such as \"#calendar\", a path on app.trainingpeaks.com, or a full https://app.trainingpeaks.com URL." }, + discard_form: { type: "boolean", default: false, description: "Leave an open Availability form, dropping unsaved edits." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "from_url", "to_url", "reload", "next_step"], + properties: { status: { const: "navigation_scheduled" }, from_url: { type: "string" }, to_url: { type: "string" }, reload: { type: "boolean" }, next_step: { type: "string" } } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "form_open"] }, + error_message: { type: "string", minLength: 1 } + } + } + ] + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true } + }, + execute: async input => { + const APP = "https://app.trainingpeaks.com"; + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message }); + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object, e.g. { url: \"#calendar\" }."); + const extra = Object.keys(input).filter(k => !["url", "discard_form"].includes(k)); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + ": pass the page as url, e.g. { url: \"#calendar\" }."); + if (input.discard_form !== undefined && typeof input.discard_form !== "boolean") return fail("invalid_input", "discard_form must be true or false."); + const raw = typeof input.url === "string" ? input.url.trim() : ""; + const absolute = /^[a-z][a-z0-9+.-]*:/i.test(raw); + if (!raw || raw.length > 2000 || raw.includes("\\") || (!absolute && !raw.startsWith("#") && (!raw.startsWith("/") || raw.startsWith("//")))) return fail("invalid_input", "url must be a # route such as \"#calendar\", a path starting with a single \"/\", or a full https://app.trainingpeaks.com URL."); + let target; + try { target = new URL(raw.startsWith("#") ? "/" + raw : raw, APP); } catch { return fail("invalid_input", "url is not a valid address."); } + if (target.origin !== APP || target.username || target.password) return fail("invalid_input", "url must stay on https://app.trainingpeaks.com; use the login tool to sign in."); + if (!/(^|\.)trainingpeaks\.com$/.test(location.hostname)) return fail("wrong_page", "Open a trainingpeaks.com page first."); + const formOpen = [...document.querySelectorAll('[data-cy="availabilityEditor"]')].some(e => e.getClientRects().length > 0); + if (formOpen && input.discard_form !== true) return fail("form_open", "An Availability form is open; leaving drops its unsaved edits. Ask the user to save or cancel it, or pass discard_form: true."); + const from = location.href; + const to = target.href; + const reload = to === from || (to === APP + "/" && from === APP + "/"); + globalThis.__xwebmcpTrainingPeaksNavigation = { from, to, at: Date.now() }; + const sameDocument = location.origin === APP && target.pathname === location.pathname && target.search === location.search && !reload; + // Return first: a reload or a cross-document navigation destroys this document and this tool's result. + setTimeout(() => { + if (reload) location.reload(); + else if (sameDocument) location.hash = target.hash; + else location.assign(to); + }, 100); + return { + status: "navigation_scheduled", from_url: from, to_url: to, reload, + next_step: "Wait, then call get_page_context({ wait_for_settled_seconds: 10 }) to confirm where the tab is, and list tools again (tool_refs can change)." + }; + } +}] diff --git a/lib/trainingpeaks-session.js b/lib/trainingpeaks-session.js new file mode 100644 index 00000000..0bef2ee6 --- /dev/null +++ b/lib/trainingpeaks-session.js @@ -0,0 +1,44 @@ +// TrainingPeaks session and availability model shared by the trainingpeaks.com page tools. The app reads its own +// session token from tpapi.trainingpeaks.com with the browser's cookies; these helpers make the same requests. +const TP_APP_ORIGIN = "https://app.trainingpeaks.com"; +const TP_API = "https://tpapi.trainingpeaks.com"; +const TP_REASONS = ["Appointment", "Injury", "Sick", "Vacation", "Work", "Other"]; +// Workout type ids the Availability form's sport checkboxes use. +const TP_SPORTS = { swim: 1, bike: 2, run: 3, brick: 4, crosstrain: 5, mountain_bike: 8, strength: 9, custom: 10, xc_ski: 11, rowing: 12, walk: 13, other: 100 }; +const tpSportName = id => Object.keys(TP_SPORTS).find(name => TP_SPORTS[name] === id) || "type_" + id; +// The signed-in user as the app sees it, or null when signed out. Never returns the token to the caller. +const tpSession = async () => { + try { + const tokenRes = await fetch(TP_API + "/users/v3/token", { credentials: "include" }); + if (!tokenRes.ok) return null; + const body = await tokenRes.json(); + const token = body && body.token && body.token.access_token; + if (!token) return null; + const userRes = await fetch(TP_API + "/users/v3/user", { headers: { Authorization: "Bearer " + token } }); + if (!userRes.ok) return null; + const data = await userRes.json(); + const u = data && (data.user || data); + if (!u || typeof u.userId !== "number") return null; + return { token, user: { user_id: u.userId, username: String(u.userName || u.username || ""), is_athlete: typeof u.isAthlete === "boolean" ? u.isAthlete : null } }; + } catch { return null; } +}; +const tpDay = value => typeof value === "string" ? value.slice(0, 10) : null; +// One availability entry as the calendar shows it. +const tpAvailability = raw => ({ + availability_id: raw.id, + start_date: tpDay(raw.startDate), + end_date: tpDay(raw.endDate), + availability: raw.limitedAvailability ? "limited" : "unavailable", + reason: TP_REASONS.includes(raw.reason) ? raw.reason : null, + description: typeof raw.description === "string" ? raw.description.slice(0, 2000) : "", + available_sports: Array.isArray(raw.availableSportTypes) ? raw.availableSportTypes.map(tpSportName) : [] +}); +const tpIsDate = value => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(value + "T00:00:00Z").toISOString().slice(0, 10) === value; +const tpDaysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 86400000); +// Availability entries overlapping [start, end], read the way the calendar reads them (at most 365 days per request). +const tpListAvailability = async (session, start, end) => { + const res = await fetch(TP_API + "/fitness/v1/athletes/" + session.user.user_id + "/availability/" + start + "/" + end, { headers: { Authorization: "Bearer " + session.token } }); + if (!res.ok) throw new Error("TrainingPeaks answered " + res.status + " when reading availability."); + const rows = await res.json(); + return (Array.isArray(rows) ? rows : []).map(tpAvailability).sort((x, y) => x.start_date.localeCompare(y.start_date) || x.availability_id - y.availability_id); +}; diff --git a/registry.json b/registry.json index 24d0d6a6..25ab6a12 100644 --- a/registry.json +++ b/registry.json @@ -4322,6 +4322,90 @@ "qa_agent": "agt_cb155ebc4a11ce54cc4c" } }, + { + "domain": "trainingpeaks.com", + "tool": "add_availability", + "file": "domains/trainingpeaks.com/add_availability.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back. Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Live creation not yet exercised." + }, + { + "domain": "trainingpeaks.com", + "tool": "delete_availability", + "file": "domains/trainingpeaks.com/delete_availability.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Sends the entry's Delete request (DELETE fitness/v1/athletes/{id}/availability/{availabilityId}; captured from the confirmation dialog on 2026-11-27 with the request stubbed) once, only when the id and start_date match an entry of the signed-in athlete, and confirms it is gone. Builder live run 2026-11-27: a mismatched start_date returned not_found without deleting. Live deletion not yet exercised." + }, + { + "domain": "trainingpeaks.com", + "tool": "get_page_context", + "file": "domains/trainingpeaks.com/get_page_context.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Read-only page summary: page type from host and # route, open workout/activity/availability item, signed-in account from the app's session API, the calendar's drawn date range and today, open Availability form, cookie-consent banner, live tool names, unsettled reasons and next steps. Builder live run 2026-11-27, signed in: calendar, an open Availability entry and dashboard reported as expected. Login page signed out is fixture-tested only." + }, + { + "domain": "trainingpeaks.com", + "tool": "list_availability", + "file": "domains/trainingpeaks.com/list_availability.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Reads fitness/v1/athletes/{id}/availability/{start}/{end}, the request the calendar makes, for the signed-in athlete; ranges over 365 days are refused as TrainingPeaks does. Builder live run 2026-11-27 read two existing entries (limited with a sport, and unavailable)." + }, + { + "domain": "trainingpeaks.com", + "tool": "login", + "file": "domains/trainingpeaks.com/login.js", + "kind": "cdp", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Signs in on home.trainingpeaks.com/login once, after the page's own reCAPTCHA v3 token is issued, and confirms the account through the app's session API (users/v3/token and users/v3/user); an existing session for another username is wrong_account. CDP because the form submit leaves the login document and the caller needs the signed-in account read afterwards. Submits with Enter in the Password field because the cookie-consent overlay can cover the Login button (observed live: a click was intercepted). Builder live run 2026-11-27: one form_submitted success invoked through a vault webmcp_invoke binding. Not exercised live: invalid_credentials, mfa_required, captcha_unavailable (fixture-tested)." + }, + { + "domain": "trainingpeaks.com", + "tool": "navigate_to_page", + "file": "domains/trainingpeaks.com/navigate_to_page.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Schedules a same-tab navigation to an app.trainingpeaks.com route 100 ms after returning: a hash change within the app, a full load from other trainingpeaks.com hosts, or a reload when the address is already open (used to show availability changes, since the calendar does not refresh after an API write). Refuses other hosts, protocol-relative and javascript: URLs, and leaving an open Availability form unless discard_form is true. Builder live run 2026-11-27: form_open refusal, discard to #calendar, reload of #calendar, #dashboard, and refused login-host and protocol-relative URLs." + }, { "domain": "ubereats.com", "tool": "add_to_cart", diff --git a/tests/trainingpeaks.test.mjs b/tests/trainingpeaks.test.mjs new file mode 100644 index 00000000..ac96e311 --- /dev/null +++ b/tests/trainingpeaks.test.mjs @@ -0,0 +1,280 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { runInNewContext } from "node:vm"; +import { conforms, plain } from "./fixtures/purelymail/server.mjs"; + +// Fabricated account; nothing here contacts TrainingPeaks. +const USER = { userId: 4242, userName: "fixture-athlete", isAthlete: true }; +const API = "https://tpapi.trainingpeaks.com"; +const source = name => readFileSync(new URL(`../domains/trainingpeaks.com/${name}.js`, import.meta.url), "utf8"); + +// A stand-in for the availability API the calendar uses. +function site({ signedIn = true, user = USER, entries = [], postStatus = 200, postThrows = false, deleteStatus = 200 } = {}) { + const rows = entries.map(e => ({ ...e })); + const requests = []; + let nextId = 900; + const json = (status, body) => ({ ok: status >= 200 && status < 300, status, json: async () => body }); + const fetch = async (url, options = {}) => { + const method = options.method || "GET"; + requests.push({ url, method, body: options.body ?? null, auth: options.headers?.Authorization ?? null }); + if (url === API + "/users/v3/token") return signedIn ? json(200, { token: { access_token: "fixture-token" } }) : json(401, null); + if (url === API + "/users/v3/user") return json(200, { user }); + const list = new RegExp(`^${API}/fitness/v1/athletes/${user.userId}/availability/(\\d{4}-\\d{2}-\\d{2})/(\\d{4}-\\d{2}-\\d{2})$`).exec(url); + if (list && method === "GET") return json(200, rows.filter(r => r.startDate.slice(0, 10) <= list[2] && r.endDate.slice(0, 10) >= list[1])); + if (url === `${API}/fitness/v1/athletes/${user.userId}/availability` && method === "POST") { + if (postThrows) throw new TypeError("Failed to fetch"); + if (postStatus !== 200) return json(postStatus, { message: "Bad request" }); + const b = JSON.parse(options.body); + const row = { id: nextId++, personId: b.personId, startDate: b.startDate + "T00:00:00", endDate: b.endDate + "T00:00:00", limitedAvailability: b.limitedAvailability, type: b.type, reason: b.reason, description: b.description, availableSportTypes: b.availableSportTypes }; + rows.push(row); + return json(200, row); + } + const del = new RegExp(`^${API}/fitness/v1/athletes/${user.userId}/availability/(\\d+)$`).exec(url); + if (del && method === "DELETE") { + if (deleteStatus === 200) rows.splice(rows.findIndex(r => r.id === Number(del[1])), 1); + return json(deleteStatus, null); + } + throw new Error("unexpected request " + method + " " + url); + }; + return { fetch, rows, requests, writes: () => requests.filter(r => r.method !== "GET") }; +} + +const element = (props = {}) => ({ getClientRects: () => [1], textContent: "", dataset: {}, ...props }); +function page(name, { href = "https://app.trainingpeaks.com/#calendar", api = site(), selectors = {}, tools = null } = {}) { + const url = new URL(href); + const scheduled = []; + const location = { + get href() { return url.href; }, get origin() { return url.origin; }, get hostname() { return url.hostname; }, + get pathname() { return url.pathname; }, get search() { return url.search; }, + get hash() { return url.hash; }, set hash(v) { url.hash = v; scheduled.push({ hash: v }); }, + assign: to => scheduled.push({ assign: to }), reload: () => scheduled.push({ reload: true }) + }; + const document = { + readyState: "complete", + querySelector: sel => (selectors[sel] || [])[0] || null, + querySelectorAll: sel => sel.split(",").flatMap(part => selectors[part.trim()] || []), + modelContext: tools ? { getTools: async () => tools.map(name => ({ name: "custom.trainingpeaks.com." + name })) } : undefined + }; + const context = { + fetch: api.fetch, location, document, navigator: {}, URL, Date, Math, JSON, Promise, Number, String, Object, Array, Set, RegExp, + getComputedStyle: () => ({ visibility: "visible" }), + setTimeout: (fn, ms) => { if (ms === 100) fn(); else Promise.resolve().then(fn); } + }; + context.globalThis = context; + const [definition] = runInNewContext(`(${source(name)})`, context); + return { + definition, scheduled, api, + run: async input => { + const result = plain(await definition.execute(input)); + assert.ok(conforms(definition.tool.outputSchema, result), "output matches schema: " + JSON.stringify(result)); + assert.ok(!JSON.stringify(result).includes("fixture-token"), "the session token is never returned"); + return result; + } + }; +} + +const JUNE = { id: 11, personId: USER.userId, startDate: "2026-05-04T00:00:00", endDate: "2026-05-08T00:00:00", limitedAvailability: false, type: 1, reason: "Vacation", description: "fixture trip", availableSportTypes: [] }; + +test("list_availability reads the range the calendar reads and maps entries", async () => { + const p = page("list_availability", { api: site({ entries: [JUNE, { ...JUNE, id: 12, startDate: "2026-04-27T00:00:00", endDate: "2026-04-29T00:00:00", limitedAvailability: true, type: 2, reason: "Work", availableSportTypes: [2] }] }) }); + const result = await p.run({ start_date: "2026-04-01", end_date: "2026-05-31" }); + assert.equal(result.account, "fixture-athlete"); + assert.deepEqual(result.entries.map(e => [e.availability_id, e.availability, e.available_sports]), [[12, "limited", ["bike"]], [11, "unavailable", []]]); + assert.equal(p.api.requests.at(-1).url, `${API}/fitness/v1/athletes/4242/availability/2026-04-01/2026-05-31`); +}); + +test("list_availability rejects bad ranges, other pages and signed-out sessions before reading", async () => { + assert.equal((await page("list_availability").run({ start_date: "2026-01-01", end_date: "2027-06-01" })).error_kind, "invalid_input"); + assert.equal((await page("list_availability").run({ start_date: "2026-02-30", end_date: "2026-03-01" })).error_kind, "invalid_input"); + assert.equal((await page("list_availability").run({ start_date: "2026-01-01", end_date: "2026-01-02", extra: 1 })).error_kind, "invalid_input"); + assert.equal((await page("list_availability", { href: "https://home.trainingpeaks.com/login" }).run({ start_date: "2026-01-01", end_date: "2026-01-02" })).error_kind, "wrong_page"); + assert.equal((await page("list_availability", { api: site({ signedIn: false }) }).run({ start_date: "2026-01-01", end_date: "2026-01-02" })).error_kind, "signed_out"); +}); + +test("add_availability sends the form's exact save request once and confirms it by reading it back", async () => { + const p = page("add_availability"); + const result = await p.run({ start_date: "2026-12-20", end_date: "2026-12-28", reason: "Vacation", description: "trip" }); + assert.equal(result.status, "created"); + assert.deepEqual(result.entry, { availability_id: 900, start_date: "2026-12-20", end_date: "2026-12-28", availability: "unavailable", reason: "Vacation", description: "trip", available_sports: [] }); + const writes = p.api.writes(); + assert.equal(writes.length, 1); + assert.equal(writes[0].url, `${API}/fitness/v1/athletes/4242/availability`); + assert.deepEqual(JSON.parse(writes[0].body), { personId: 4242, startDate: "2026-12-20", endDate: "2026-12-28", limitedAvailability: false, reason: "Vacation", availableSportTypes: [], description: "trip", type: 1 }); + const limited = page("add_availability"); + await limited.run({ start_date: "2026-12-01", end_date: "2026-12-01", availability: "limited", available_sports: ["run", "swim"] }); + assert.deepEqual(JSON.parse(limited.api.writes()[0].body), { personId: 4242, startDate: "2026-12-01", endDate: "2026-12-01", limitedAvailability: true, reason: "", availableSportTypes: [3, 1], description: "", type: 2 }); +}); + +test("add_availability writes nothing for identical, overlapping, wrong-account or invalid requests", async () => { + const same = page("add_availability", { api: site({ entries: [JUNE] }) }); + const existing = await same.run({ start_date: "2026-05-04", end_date: "2026-05-08", reason: "Vacation" }); + assert.equal(existing.status, "already_exists"); + assert.equal(existing.entry.availability_id, 11); + const overlap = page("add_availability", { api: site({ entries: [JUNE] }) }); + const refused = await overlap.run({ start_date: "2026-05-07", end_date: "2026-05-10" }); + assert.equal(refused.error_kind, "overlap"); + assert.equal(refused.overlapping_entries[0].availability_id, 11); + assert.equal(refused.write_attempted, false); + for (const input of [ + { start_date: "2026-12-02", end_date: "2026-12-01" }, + { start_date: "2026-12-01", end_date: "2026-12-01", available_sports: ["run"] }, + { start_date: "2026-12-01", end_date: "2026-12-01", reason: "Holiday" }, + { start_date: "2026-12-01", end_date: "2026-12-01", expected_account: "someone-else" } + ]) { + const p = page("add_availability"); + const result = await p.run(input); + assert.equal(result.status, "error", JSON.stringify(input)); + assert.equal(p.api.writes().length, 0); + } + const allowed = page("add_availability", { api: site({ entries: [JUNE] }) }); + assert.equal((await allowed.run({ start_date: "2026-05-07", end_date: "2026-05-10", allow_overlap: true })).status, "created"); +}); + +test("add_availability reports a rejected or unanswered save without retrying", async () => { + const rejected = page("add_availability", { api: site({ postStatus: 400 }) }); + const result = await rejected.run({ start_date: "2026-12-01", end_date: "2026-12-01" }); + assert.equal(result.error_kind, "site_rejected"); + assert.match(result.error_message, /400: Bad request/); + const lost = page("add_availability", { api: site({ postThrows: true }) }); + const unknown = await lost.run({ start_date: "2026-12-01", end_date: "2026-12-01" }); + assert.equal(unknown.error_kind, "outcome_unknown"); + assert.equal(unknown.write_attempted, true); + assert.equal(lost.api.writes().length, 1); +}); + +test("delete_availability deletes only the entry whose id and start date match, then confirms it is gone", async () => { + const p = page("delete_availability", { api: site({ entries: [JUNE] }) }); + const mismatch = await p.run({ availability_id: 11, start_date: "2026-05-05" }); + assert.equal(mismatch.error_kind, "not_found"); + assert.equal(p.api.writes().length, 0); + const result = await p.run({ availability_id: 11, start_date: "2026-05-04" }); + assert.equal(result.status, "deleted"); + assert.equal(result.deleted_entry.availability_id, 11); + assert.deepEqual(p.api.writes().map(w => [w.method, w.url]), [["DELETE", `${API}/fitness/v1/athletes/4242/availability/11`]]); + assert.equal(p.api.rows.length, 0); + const refused = page("delete_availability", { api: site({ entries: [JUNE], deleteStatus: 403 }) }); + assert.equal((await refused.run({ availability_id: 11, start_date: "2026-05-04" })).error_kind, "site_rejected"); +}); + +test("navigate_to_page schedules app routes after returning, reloads the open address, and guards forms and hosts", async () => { + const p = page("navigate_to_page"); + const result = await p.run({ url: "#dashboard" }); + assert.deepEqual([result.status, result.to_url, result.reload], ["navigation_scheduled", "https://app.trainingpeaks.com/#dashboard", false]); + assert.deepEqual(p.scheduled, [{ hash: "#dashboard" }]); + const again = page("navigate_to_page"); + assert.equal((await again.run({ url: "#calendar" })).reload, true); + assert.deepEqual(again.scheduled, [{ reload: true }]); + const fromLogin = page("navigate_to_page", { href: "https://home.trainingpeaks.com/login" }); + await fromLogin.run({ url: "https://app.trainingpeaks.com/#calendar" }); + assert.deepEqual(fromLogin.scheduled, [{ assign: "https://app.trainingpeaks.com/#calendar" }]); + for (const url of ["https://home.trainingpeaks.com/login", "//example.com/#calendar", "javascript:alert(1)", "calendar"]) { + const bad = page("navigate_to_page"); + assert.equal((await bad.run({ url })).error_kind, "invalid_input", url); + assert.equal(bad.scheduled.length, 0); + } + const form = { '[data-cy="availabilityEditor"]': [element()] }; + const guarded = page("navigate_to_page", { href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", selectors: form }); + assert.equal((await guarded.run({ url: "#calendar" })).error_kind, "form_open"); + assert.equal(guarded.scheduled.length, 0); + const discard = page("navigate_to_page", { href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", selectors: form }); + assert.equal((await discard.run({ url: "#calendar", discard_form: true })).status, "navigation_scheduled"); +}); + +test("get_page_context reports the page, account, calendar range, open item and next steps", async () => { + const days = ["2026-11-29", "2026-11-23", "2026-12-06"].map(date => element({ dataset: { date } })); + const tools = ["add_availability", "delete_availability", "get_page_context", "list_availability", "login", "navigate_to_page"]; + const p = page("get_page_context", { + href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", tools, + selectors: { ".day[data-date]": days, ".day.today[data-date]": [days[0]], '[data-cy="availabilityEditor"]': [element()], ".frameworkMainWrapper": [element()] } + }); + const result = await p.run({}); + assert.equal(result.page_type, "calendar"); + assert.deepEqual(result.open_item, { item_type: "availability", item_id: 11 }); + assert.deepEqual(result.account, { user_id: 4242, username: "fixture-athlete", is_athlete: true }); + assert.deepEqual(result.calendar, { first_drawn_date: "2026-11-23", last_drawn_date: "2026-12-06", today: "2026-11-29" }); + assert.equal(result.availability_form_open, true); + assert.deepEqual(result.available_tools, tools); + assert.ok(result.suggested_next_steps.some(s => s.includes("discard_form"))); + const login = await page("get_page_context", { href: "https://home.trainingpeaks.com/login", api: site({ signedIn: false }), tools: ["login"] }).run({}); + assert.deepEqual([login.page_type, login.signed_in, login.account], ["login", false, null]); + assert.ok(login.suggested_next_steps[0].startsWith("Not signed in: use login")); + assert.equal((await page("get_page_context", { href: "https://app.trainingpeaks.com/#plan" }).run({})).page_type, "plan"); + assert.equal((await page("get_page_context").run({ wait_for_settled_seconds: 99 })).error_kind, "invalid_input"); +}); + +// The login tool is a cdp tool: its helpers are stubbed and its page functions are recognized by their source. +function loginHarness({ sessionUser = null, afterSubmit = () => ({ user: USER }), captcha = true } = {}) { + let clock = 1_800_000_000_000; + let state = { url: "about:blank", user: sessionUser, form: false, error: null, code: false }; + let marker = 0; + const calls = { navigations: [], typed: {}, keys: [], clicks: 0 }; + const read = () => ({ url: state.url, host: new URL(state.url === "about:blank" ? "https://x.invalid" : state.url).hostname, path: state.url === "about:blank" ? "" : new URL(state.url).pathname, form: state.form, captcha_ready: captcha, error: state.error, code_step: state.code, marker }); + const context = { + Date: class extends Date { constructor(...a) { super(...(a.length ? a : [clock])); } static now() { return clock; } }, + pageInfo: async () => ({ url: state.url }), + gotoUrl: async url => { calls.navigations.push(url); state = { ...state, url, form: !state.user && url.includes("/login") }; }, + waitForLoad: async () => true, + waitMs: async ms => { clock += ms; }, + fillInput: async (selector, text) => { calls.typed[selector] = text; }, + click: async () => { calls.clicks++; }, + pressKey: async key => { + calls.keys.push(key); + const outcome = afterSubmit(); + state = outcome.user ? { url: "https://app.trainingpeaks.com/", user: outcome.user, form: false, error: null, code: false } : { ...state, ...outcome }; + }, + js: async (fn, options) => { + const text = fn.toString(); + if (text.includes("users/v3/token")) return state.user ? { username: state.user.userName, email: null, user_id: state.user.userId, is_athlete: state.user.isAthlete } : null; + if (text.includes("captcha-token")) return read(); + if (text.includes("setItem")) { marker = clock; return undefined; } + if (text.includes("removeItem")) { marker = 0; return undefined; } + if (text.includes("activeElement")) return (calls.typed["#Username"] || "").toLowerCase() === options.arg && !!calls.typed["#Password"]; + throw new Error("unexpected page function " + text.slice(0, 80)); + } + }; + const [definition] = runInNewContext(`(${source("login")})`, context); + return { + calls, + run: async input => { + const result = plain(await definition.execute(input)); + assert.ok(conforms(definition.tool.outputSchema, result), "output matches schema: " + JSON.stringify(result)); + assert.ok(!JSON.stringify(result).includes("fixture-password"), "the password never appears in the output"); + return result; + } + }; +} + +test("login confirms an existing session without submitting, and refuses another account", async () => { + const same = loginHarness({ sessionUser: USER }); + const ok = await same.run({ username: "Fixture-Athlete", password: "fixture-password" }); + assert.deepEqual([ok.status, ok.entry, ok.submission_attempted], ["ok", "already_signed_in", false]); + assert.equal(same.calls.keys.length, 0); + const other = loginHarness({ sessionUser: { ...USER, userName: "someone-else" } }); + const wrong = await other.run({ username: "fixture-athlete", password: "fixture-password" }); + assert.deepEqual([wrong.error_kind, wrong.signed_in_account, wrong.submission_attempted], ["wrong_account", "someone-else", false]); + assert.deepEqual(other.calls.typed, {}); +}); + +test("login submits once with Enter from a fresh login page and reports the signed-in account", async () => { + const h = loginHarness(); + const result = await h.run({ username: "fixture-athlete", password: "fixture-password" }); + assert.deepEqual([result.status, result.entry, result.account.username, result.account.user_id], ["ok", "form_submitted", "fixture-athlete", 4242]); + assert.deepEqual(h.calls.keys, ["Enter"]); + assert.equal(h.calls.clicks, 0, "the Login button can be covered by the consent banner, so it is not clicked"); + assert.ok(h.calls.navigations.every(url => url === "https://home.trainingpeaks.com/login")); +}); + +test("login reports rejected passwords, second factors and missing reCAPTCHA tokens without retrying", async () => { + const bad = loginHarness({ afterSubmit: () => ({ error: "Username or password is incorrect" }) }); + const rejected = await bad.run({ username: "fixture-athlete", password: "fixture-password" }); + assert.deepEqual([rejected.error_kind, rejected.submission_attempted], ["invalid_credentials", true]); + assert.equal(bad.calls.keys.length, 1); + const mfa = await loginHarness({ afterSubmit: () => ({ code: true }) }).run({ username: "fixture-athlete", password: "fixture-password" }); + assert.equal(mfa.error_kind, "mfa_required"); + const noToken = loginHarness({ captcha: false }); + const captcha = await noToken.run({ username: "fixture-athlete", password: "fixture-password" }); + assert.deepEqual([captcha.error_kind, captcha.submission_attempted], ["captcha_unavailable", false]); + assert.equal(noToken.calls.keys.length, 0); + assert.equal((await loginHarness().run({ username: "has space", password: "x" })).error_kind, "invalid_input"); +}); From b16fe8ea12fe8fb6c12e220d704e03520a21f00b Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:07:29 +0000 Subject: [PATCH 2/5] Add answer_cookie_banner and report the cookie banner in get_page_context --- domains/trainingpeaks.com/README.md | 3 +- .../trainingpeaks.com/answer_cookie_banner.js | 74 +++++++++++++++++++ domains/trainingpeaks.com/get_page_context.js | 27 +++++-- registry.json | 16 +++- tests/trainingpeaks.test.mjs | 52 ++++++++++++- 5 files changed, 160 insertions(+), 12 deletions(-) create mode 100644 domains/trainingpeaks.com/answer_cookie_banner.js diff --git a/domains/trainingpeaks.com/README.md b/domains/trainingpeaks.com/README.md index d55242ed..60ce4f19 100644 --- a/domains/trainingpeaks.com/README.md +++ b/domains/trainingpeaks.com/README.md @@ -3,8 +3,9 @@ | tool | description | |------|-------------| | add_availability | Adds one Availability entry (days unable to train, or with limited availability) to the signed-in athlete's calendar and confirms it by reading it back. | +| answer_cookie_banner | Answers the cookie-consent banner with the user's choice (Reject All or Accept Cookies) by pressing the site's button, and confirms it closed. | | delete_availability | Deletes one Availability entry by id after checking its start date, and confirms it is gone. | -| get_page_context | Describes the open TrainingPeaks page: page type, signed-in account, calendar range, open forms, live tools, loading state and next steps. | +| get_page_context | Describes the open TrainingPeaks page: page type, signed-in account, calendar range, open forms, cookie banner, live tools, loading state and next steps. | | list_availability | Lists the signed-in athlete's Availability entries (days off) overlapping a date range of up to 365 days. | | login | Signs in with username and password, submitting at most once, and confirms the signed-in account; an existing session is confirmed without submitting. | | navigate_to_page | Schedules navigation to a TrainingPeaks app page (Home, Calendar, Dashboard, ATP, Settings, an Availability entry) and carries the app's site map. | diff --git a/domains/trainingpeaks.com/answer_cookie_banner.js b/domains/trainingpeaks.com/answer_cookie_banner.js new file mode 100644 index 00000000..9e2d4f75 --- /dev/null +++ b/domains/trainingpeaks.com/answer_cookie_banner.js @@ -0,0 +1,74 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "answer_cookie_banner", + title: "Answer the cookie-consent banner", + description: "Answer TrainingPeaks' cookie-consent banner (\"We value your privacy\") by pressing its own Reject All or Accept Cookies button once, then confirm the banner closed and report the consent groups the site recorded. This is the user's privacy choice: pass the choice the user made, never pick one for them. While the banner is open its overlay covers the page and can block clicks, so get_page_context reports it as consent_banner_visible. If no banner is showing it does nothing and returns no_banner. It does not open or change Cookie Settings; if that panel is open it refuses with settings_open. The choice is stored in the browser's cookies, so it lasts only as long as this browser profile keeps them.", + inputSchema: { + type: "object", additionalProperties: false, required: ["choice"], + properties: { + choice: { enum: ["reject_all", "accept_all"], description: "reject_all presses Reject All (only strictly necessary cookies); accept_all presses Accept Cookies." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "choice", "banner_visible", "consent_groups"], + properties: { + status: { enum: ["answered", "no_banner"] }, + choice: { type: ["string", "null"], enum: ["reject_all", "accept_all", null], description: "The button pressed, or null when nothing was pressed." }, + banner_visible: { const: false }, + consent_groups: { + type: ["object", "null"], additionalProperties: { type: "boolean" }, + description: "Cookie categories the site now records as allowed (OneTrust group ids such as C0001 strictly necessary), or null when the site has not recorded them." + } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message", "pressed"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "settings_open", "button_missing", "not_confirmed"] }, + error_message: { type: "string", minLength: 1 }, + pressed: { type: "boolean" } + } + } + ] + }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } + }, + execute: async input => { + let pressed = false; + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message, pressed }); + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be { choice: \"reject_all\" | \"accept_all\" }."); + const extra = Object.keys(input).filter(k => k !== "choice"); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); + if (!["reject_all", "accept_all"].includes(input.choice)) return fail("invalid_input", "choice must be reject_all or accept_all, as the user decided."); + if (!/(^|\.)trainingpeaks\.com$/.test(location.hostname)) return fail("wrong_page", "Open a trainingpeaks.com page first."); + const visible = el => !!el && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden"; + const groups = () => { + const raw = (document.cookie.split(";").map(c => c.trim()).find(c => c.startsWith("OptanonConsent=")) || "").slice("OptanonConsent=".length); + const match = /(?:^|&)groups=([^&]*)/.exec(raw); + if (!match) return null; + const out = {}; + for (const pair of decodeURIComponent(match[1]).split(",")) { + const [id, on] = pair.split(":"); + if (/^[A-Za-z0-9_]+$/.test(id || "")) out[id] = on === "1"; + } + return out; + }; + const banner = () => visible(document.getElementById("onetrust-banner-sdk")); + if (visible(document.getElementById("onetrust-pc-sdk"))) return fail("settings_open", "The Cookie Settings panel is open; ask the user to finish or close it there."); + if (!banner()) return { status: "no_banner", choice: null, banner_visible: false, consent_groups: groups() }; + const button = document.getElementById(input.choice === "reject_all" ? "onetrust-reject-all-handler" : "onetrust-accept-btn-handler"); + if (!visible(button)) return fail("button_missing", "The banner has no visible " + (input.choice === "reject_all" ? "Reject All" : "Accept Cookies") + " button; nothing was pressed."); + pressed = true; + button.click(); + const until = Date.now() + 5000; + while (Date.now() < until && (banner() || !/(^|;\s*)OptanonAlertBoxClosed=/.test(document.cookie))) await new Promise(resolve => setTimeout(resolve, 200)); + if (banner()) return fail("not_confirmed", "The button was pressed but the banner is still showing; check the page before pressing again."); + return { status: "answered", choice: input.choice, banner_visible: false, consent_groups: groups() }; + } +}] diff --git a/domains/trainingpeaks.com/get_page_context.js b/domains/trainingpeaks.com/get_page_context.js index 3f084be1..3276f857 100644 --- a/domains/trainingpeaks.com/get_page_context.js +++ b/domains/trainingpeaks.com/get_page_context.js @@ -4,7 +4,7 @@ tool: { name: "get_page_context", title: "Describe the open TrainingPeaks page", - description: "Describe the TrainingPeaks page open in this tab so you can decide what to do next: page type (the login page, the app's Home, Calendar, Dashboard, ATP plan or Settings, an open workout, activity or Availability entry, another trainingpeaks.com page), whether a user is signed in and which (username, user_id, athlete or not), on the Calendar the first and last dates it has drawn and today, whether an Availability form is open, whether the cookie-consent banner is covering the page, which WebMCP tools this page exposes now, whether the page is still loading, and suggested next steps. Call it after every navigation, after login, or whenever you are unsure where the tab is; navigate_to_page opens another page. Read-only: never clicks, types or navigates, and never returns a token or password. Pass wait_for_settled_seconds to wait for the page to finish loading.", + description: "Describe the TrainingPeaks page open in this tab so you can decide what to do next: page type (the login page, the app's Home, Calendar, Dashboard, ATP plan or Settings, an open workout, activity or Availability entry, another trainingpeaks.com page), whether a user is signed in and which (username, user_id, athlete or not), on the Calendar the first and last dates it has drawn and today, whether an Availability form is open, whether the cookie-consent banner is showing and blocking clicks, which WebMCP tools this page exposes now, whether the page is still loading, and suggested next steps. Call it after every navigation, after login, or whenever you are unsure where the tab is; navigate_to_page opens another page. Read-only: never clicks, types or navigates, and never returns a token or password. Pass wait_for_settled_seconds to wait for the page to finish loading.", inputSchema: { type: "object", additionalProperties: false, properties: { @@ -16,7 +16,7 @@ oneOf: [ { type: "object", additionalProperties: false, - required: ["status", "current_url", "page_type", "open_item", "signed_in", "account", "calendar", "availability_form_open", "consent_banner_visible", "available_tools", "unsettled", "unsettled_reasons", "page_messages", "suggested_next_steps"], + required: ["status", "current_url", "page_type", "open_item", "signed_in", "account", "calendar", "availability_form_open", "cookie_banner", "available_tools", "unsettled", "unsettled_reasons", "page_messages", "suggested_next_steps"], properties: { status: { const: "ok" }, current_url: { type: "string" }, @@ -37,7 +37,16 @@ properties: { first_drawn_date: { type: ["string", "null"] }, last_drawn_date: { type: ["string", "null"] }, today: { type: ["string", "null"] } } }, availability_form_open: { type: "boolean", description: "The full-screen Availability form (Save, Cancel, Delete) is open." }, - consent_banner_visible: { type: "boolean", description: "The cookie-consent banner is showing; it can cover buttons near the bottom of the page. No tool answers it for the user." }, + cookie_banner: { + type: "object", additionalProperties: false, required: ["visible", "settings_open", "blocks_page", "answered"], + description: "TrainingPeaks' cookie-consent banner (OneTrust). answer_cookie_banner answers it with the user's choice.", + properties: { + visible: { type: "boolean", description: "The \"We value your privacy\" banner is showing." }, + settings_open: { type: "boolean", description: "The Cookie Settings panel is open." }, + blocks_page: { type: "boolean", description: "The banner's dark overlay covers the page, so clicks on the page are intercepted." }, + answered: { type: "boolean", description: "The browser has a stored answer to the banner." } + } + }, available_tools: { type: ["array", "null"], items: { type: "string" }, description: "Tool names this page exposes now, or null when the page's tool list cannot be read." }, unsettled: { type: "boolean" }, unsettled_reasons: { type: "array", items: { enum: ["document_loading", "navigating", "app_loading", "busy_region"] } }, @@ -156,7 +165,12 @@ calendar = { first_drawn_date: days[0] || null, last_drawn_date: days[days.length - 1] || null, today: today ? today.dataset.date : null }; } const formOpen = [...document.querySelectorAll('[data-cy="availabilityEditor"]')].some(visible); - const banner = [...document.querySelectorAll("#onetrust-banner-sdk, #onetrust-pc-sdk")].some(visible); + const cookieBanner = { + visible: visible(document.getElementById("onetrust-banner-sdk")), + settings_open: visible(document.getElementById("onetrust-pc-sdk")), + blocks_page: [...document.querySelectorAll(".onetrust-pc-dark-filter")].some(visible), + answered: /(^|;\s*)OptanonAlertBoxClosed=/.test(document.cookie) + }; let tools = null; try { @@ -192,7 +206,8 @@ } if (account && account.is_athlete === false) steps.push("This is not an athlete account; the availability tools write only to the signed-in athlete's own calendar."); } - if (banner) steps.push("The cookie-consent banner is showing and can cover buttons near the bottom of the page. Do not choose a consent option for the user."); + if (cookieBanner.settings_open) steps.push("The Cookie Settings panel is open; the user finishes or closes it there."); + else if (cookieBanner.visible) steps.push("The cookie-consent banner is showing" + (cookieBanner.blocks_page ? " and its overlay blocks clicks on the page" : "") + ". Ask the user whether to Reject All or Accept Cookies, then " + (has("answer_cookie_banner") ? "answer_cookie_banner({ choice: \"reject_all\" })" : "press that button") + " with their choice; never choose for them."); return { status: "ok", @@ -203,7 +218,7 @@ account, calendar, availability_form_open: formOpen, - consent_banner_visible: banner, + cookie_banner: cookieBanner, available_tools: tools, unsettled: unsettled.length > 0, unsettled_reasons: unsettled, diff --git a/registry.json b/registry.json index 25ab6a12..5e730e04 100644 --- a/registry.json +++ b/registry.json @@ -4336,6 +4336,20 @@ "last_verified": null, "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back. Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Live creation not yet exercised." }, + { + "domain": "trainingpeaks.com", + "tool": "answer_cookie_banner", + "file": "domains/trainingpeaks.com/answer_cookie_banner.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Presses the OneTrust banner's own Reject All or Accept Cookies button once, for an explicit choice passed by the caller (never a default), and confirms the banner closed and the OptanonAlertBoxClosed cookie was set; reports the recorded consent groups. Does nothing without a banner and refuses while Cookie Settings is open. Page kind: the click does not navigate. Fixture-tested; live run pending." + }, { "domain": "trainingpeaks.com", "tool": "delete_availability", @@ -4362,7 +4376,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Read-only page summary: page type from host and # route, open workout/activity/availability item, signed-in account from the app's session API, the calendar's drawn date range and today, open Availability form, cookie-consent banner, live tool names, unsettled reasons and next steps. Builder live run 2026-11-27, signed in: calendar, an open Availability entry and dashboard reported as expected. Login page signed out is fixture-tested only." + "notes": "Read-only page summary: page type from host and # route, open workout/activity/availability item, signed-in account from the app's session API, the calendar's drawn date range and today, open Availability form, the cookie-consent banner (showing, Cookie Settings open, overlay blocking clicks, already answered), live tool names, unsettled reasons and next steps. Builder live run 2026-11-27, signed in: calendar, an open Availability entry and dashboard reported as expected. Login page signed out is fixture-tested only." }, { "domain": "trainingpeaks.com", diff --git a/tests/trainingpeaks.test.mjs b/tests/trainingpeaks.test.mjs index ac96e311..5737d2f1 100644 --- a/tests/trainingpeaks.test.mjs +++ b/tests/trainingpeaks.test.mjs @@ -41,7 +41,7 @@ function site({ signedIn = true, user = USER, entries = [], postStatus = 200, po } const element = (props = {}) => ({ getClientRects: () => [1], textContent: "", dataset: {}, ...props }); -function page(name, { href = "https://app.trainingpeaks.com/#calendar", api = site(), selectors = {}, tools = null } = {}) { +function page(name, { href = "https://app.trainingpeaks.com/#calendar", api = site(), selectors = {}, tools = null, cookie = "" } = {}) { const url = new URL(href); const scheduled = []; const location = { @@ -52,6 +52,8 @@ function page(name, { href = "https://app.trainingpeaks.com/#calendar", api = si }; const document = { readyState: "complete", + get cookie() { return typeof cookie === "function" ? cookie() : cookie; }, + getElementById: id => (selectors["#" + id] || [])[0] || null, querySelector: sel => (selectors[sel] || [])[0] || null, querySelectorAll: sel => sel.split(",").flatMap(part => selectors[part.trim()] || []), modelContext: tools ? { getTools: async () => tools.map(name => ({ name: "custom.trainingpeaks.com." + name })) } : undefined @@ -185,8 +187,8 @@ test("get_page_context reports the page, account, calendar range, open item and const days = ["2026-11-29", "2026-11-23", "2026-12-06"].map(date => element({ dataset: { date } })); const tools = ["add_availability", "delete_availability", "get_page_context", "list_availability", "login", "navigate_to_page"]; const p = page("get_page_context", { - href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", tools, - selectors: { ".day[data-date]": days, ".day.today[data-date]": [days[0]], '[data-cy="availabilityEditor"]': [element()], ".frameworkMainWrapper": [element()] } + href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", tools: [...tools, "answer_cookie_banner"], + selectors: { "#onetrust-banner-sdk": [element()], ".onetrust-pc-dark-filter": [element()], ".day[data-date]": days, ".day.today[data-date]": [days[0]], '[data-cy="availabilityEditor"]': [element()], ".frameworkMainWrapper": [element()] } }); const result = await p.run({}); assert.equal(result.page_type, "calendar"); @@ -194,15 +196,57 @@ test("get_page_context reports the page, account, calendar range, open item and assert.deepEqual(result.account, { user_id: 4242, username: "fixture-athlete", is_athlete: true }); assert.deepEqual(result.calendar, { first_drawn_date: "2026-11-23", last_drawn_date: "2026-12-06", today: "2026-11-29" }); assert.equal(result.availability_form_open, true); - assert.deepEqual(result.available_tools, tools); + assert.deepEqual(result.available_tools, [...tools, "answer_cookie_banner"].sort()); assert.ok(result.suggested_next_steps.some(s => s.includes("discard_form"))); + assert.deepEqual(result.cookie_banner, { visible: true, settings_open: false, blocks_page: true, answered: false }); + assert.ok(result.suggested_next_steps.some(s => s.includes("answer_cookie_banner") && s.includes("never choose for them"))); const login = await page("get_page_context", { href: "https://home.trainingpeaks.com/login", api: site({ signedIn: false }), tools: ["login"] }).run({}); assert.deepEqual([login.page_type, login.signed_in, login.account], ["login", false, null]); + assert.deepEqual(login.cookie_banner, { visible: false, settings_open: false, blocks_page: false, answered: false }); assert.ok(login.suggested_next_steps[0].startsWith("Not signed in: use login")); assert.equal((await page("get_page_context", { href: "https://app.trainingpeaks.com/#plan" }).run({})).page_type, "plan"); assert.equal((await page("get_page_context").run({ wait_for_settled_seconds: 99 })).error_kind, "invalid_input"); }); +// A OneTrust banner whose buttons record the choice in cookies and hide the banner, as the site's do. +function bannerPage({ shown = true, settingsOpen = false } = {}) { + const state = { shown, cookie: "OptanonConsent=isGpcEnabled=0&groups=C0001%3A1%2CC0002%3A0", pressed: [] }; + const press = (name, groups) => element({ click: () => { + state.pressed.push(name); + state.shown = false; + state.cookie = "OptanonConsent=isGpcEnabled=0&groups=" + encodeURIComponent(groups) + "; OptanonAlertBoxClosed=2026-11-27T20:00:00.000Z"; + } }); + const selectors = { + "#onetrust-banner-sdk": [element({ getClientRects: () => (state.shown ? [1] : []) })], + "#onetrust-pc-sdk": settingsOpen ? [element()] : [], + "#onetrust-reject-all-handler": [press("reject", "C0001:1,C0002:0,C0003:0,C0004:0")], + "#onetrust-accept-btn-handler": [press("accept", "C0001:1,C0002:1,C0003:1,C0004:1")] + }; + return { p: page("answer_cookie_banner", { selectors, cookie: () => state.cookie }), state }; +} + +test("answer_cookie_banner presses only the button for the user's choice and reports the recorded consent", async () => { + for (const [choice, button, marketing] of [["reject_all", "reject", false], ["accept_all", "accept", true]]) { + const { p, state } = bannerPage(); + const result = await p.run({ choice }); + assert.deepEqual(state.pressed, [button]); + assert.deepEqual([result.status, result.choice, result.banner_visible, result.consent_groups.C0001, result.consent_groups.C0004], ["answered", choice, false, true, marketing]); + } +}); + +test("answer_cookie_banner requires an explicit choice and presses nothing without a banner or with Cookie Settings open", async () => { + const { p, state } = bannerPage(); + for (const input of [{}, { choice: "close" }, { choice: "reject_all", extra: 1 }]) assert.equal((await p.run(input)).error_kind, "invalid_input"); + assert.deepEqual(state.pressed, []); + const none = bannerPage({ shown: false }); + const absent = await none.p.run({ choice: "reject_all" }); + assert.deepEqual([absent.status, absent.choice], ["no_banner", null]); + assert.deepEqual(none.state.pressed, []); + const settings = bannerPage({ settingsOpen: true }); + assert.equal((await settings.p.run({ choice: "accept_all" })).error_kind, "settings_open"); + assert.deepEqual(settings.state.pressed, []); +}); + // The login tool is a cdp tool: its helpers are stubbed and its page functions are recognized by their source. function loginHarness({ sessionUser = null, afterSubmit = () => ({ user: USER }), captcha = true } = {}) { let clock = 1_800_000_000_000; From 66c80d98dae0e0277cb42199c4507b387a2494a9 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:16:49 +0000 Subject: [PATCH 3/5] Default the cookie banner to Reject All and add reload to navigate_to_page --- domains/trainingpeaks.com/README.md | 2 +- domains/trainingpeaks.com/add_availability.js | 4 ++-- .../trainingpeaks.com/answer_cookie_banner.js | 17 ++++++++-------- .../trainingpeaks.com/delete_availability.js | 4 ++-- domains/trainingpeaks.com/get_page_context.js | 4 ++-- domains/trainingpeaks.com/navigate_to_page.js | 20 +++++++++++-------- registry.json | 6 +++--- tests/trainingpeaks.test.mjs | 13 +++++++++--- 8 files changed, 41 insertions(+), 29 deletions(-) diff --git a/domains/trainingpeaks.com/README.md b/domains/trainingpeaks.com/README.md index 60ce4f19..058ae161 100644 --- a/domains/trainingpeaks.com/README.md +++ b/domains/trainingpeaks.com/README.md @@ -3,7 +3,7 @@ | tool | description | |------|-------------| | add_availability | Adds one Availability entry (days unable to train, or with limited availability) to the signed-in athlete's calendar and confirms it by reading it back. | -| answer_cookie_banner | Answers the cookie-consent banner with the user's choice (Reject All or Accept Cookies) by pressing the site's button, and confirms it closed. | +| answer_cookie_banner | Answers the cookie-consent banner with Reject All by default, or Accept Cookies when asked, by pressing the site's button, and confirms it closed. | | delete_availability | Deletes one Availability entry by id after checking its start date, and confirms it is gone. | | get_page_context | Describes the open TrainingPeaks page: page type, signed-in account, calendar range, open forms, cookie banner, live tools, loading state and next steps. | | list_availability | Lists the signed-in athlete's Availability entries (days off) overlapping a date range of up to 365 days. | diff --git a/domains/trainingpeaks.com/add_availability.js b/domains/trainingpeaks.com/add_availability.js index 7243fdc9..19b47b2e 100644 --- a/domains/trainingpeaks.com/add_availability.js +++ b/domains/trainingpeaks.com/add_availability.js @@ -4,7 +4,7 @@ tool: { name: "add_availability", title: "Add availability (days off)", - description: "Add one Availability entry to the signed-in athlete's TrainingPeaks calendar, as the calendar's day menu > Add... > Availability form does: a date range (inclusive) when the athlete is unable to train, or has limited availability (optionally naming the sports still possible), with an optional reason (Vacation, Work, Sick, Injury, Appointment, Other) and description. Use it for vacations and other days off; coaches and TrainingPeaks plans see it on the calendar. Runs on https://app.trainingpeaks.com while signed in (use login first). Before writing it reads the range: an identical entry returns already_exists without writing, and any other overlapping entry is refused with overlap unless allow_overlap is true. It sends the form's save request once and never retries; on outcome_unknown call list_availability before trying again. Success is confirmed by reading the entry back. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\" }). Remove an entry with delete_availability.", + description: "Add one Availability entry to the signed-in athlete's TrainingPeaks calendar, as the calendar's day menu > Add... > Availability form does: a date range (inclusive) when the athlete is unable to train, or has limited availability (optionally naming the sports still possible), with an optional reason (Vacation, Work, Sick, Injury, Appointment, Other) and description. Use it for vacations and other days off; coaches and TrainingPeaks plans see it on the calendar. Runs on https://app.trainingpeaks.com while signed in (use login first). Before writing it reads the range: an identical entry returns already_exists without writing, and any other overlapping entry is refused with overlap unless allow_overlap is true. It sends the form's save request once and never retries; on outcome_unknown call list_availability before trying again. Success is confirmed by reading the entry back. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\", reload: true }). Remove an entry with delete_availability.", inputSchema: { type: "object", additionalProperties: false, required: ["start_date", "end_date"], properties: { @@ -133,7 +133,7 @@ let existing; try { existing = await tpListAvailability(session, start, end); } catch (error) { return fail("site_error", String(error && error.message || error).slice(0, 300)); } const identical = existing.find(sameEntry); - const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\" }) to see it on screen."; + const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }) to see it on screen."; if (identical) return { status: "already_exists", account: session.user.username, entry: identical, next_step: "Nothing was written. " + next }; if (existing.length && input.allow_overlap !== true) return fail("overlap", "Other availability entries already overlap these dates; nothing was written. Change or delete them, or pass allow_overlap: true.", existing); // The exact request the Availability form's Save button sends. diff --git a/domains/trainingpeaks.com/answer_cookie_banner.js b/domains/trainingpeaks.com/answer_cookie_banner.js index 9e2d4f75..a8199792 100644 --- a/domains/trainingpeaks.com/answer_cookie_banner.js +++ b/domains/trainingpeaks.com/answer_cookie_banner.js @@ -4,11 +4,11 @@ tool: { name: "answer_cookie_banner", title: "Answer the cookie-consent banner", - description: "Answer TrainingPeaks' cookie-consent banner (\"We value your privacy\") by pressing its own Reject All or Accept Cookies button once, then confirm the banner closed and report the consent groups the site recorded. This is the user's privacy choice: pass the choice the user made, never pick one for them. While the banner is open its overlay covers the page and can block clicks, so get_page_context reports it as consent_banner_visible. If no banner is showing it does nothing and returns no_banner. It does not open or change Cookie Settings; if that panel is open it refuses with settings_open. The choice is stored in the browser's cookies, so it lasts only as long as this browser profile keeps them.", + description: "Answer TrainingPeaks' cookie-consent banner (\"We value your privacy\") by pressing its own Reject All or Accept Cookies button once, then confirm the banner closed and report the consent groups the site recorded. choice defaults to reject_all, which keeps only strictly necessary cookies; pass accept_all only when the user chose it. While the banner is open its overlay covers the page and can block clicks, so get_page_context reports it as consent_banner_visible. If no banner is showing it does nothing and returns no_banner. It does not open or change Cookie Settings; if that panel is open it refuses with settings_open. The choice is stored in the browser's cookies, so it lasts only as long as this browser profile keeps them.", inputSchema: { - type: "object", additionalProperties: false, required: ["choice"], + type: "object", additionalProperties: false, properties: { - choice: { enum: ["reject_all", "accept_all"], description: "reject_all presses Reject All (only strictly necessary cookies); accept_all presses Accept Cookies." } + choice: { enum: ["reject_all", "accept_all"], default: "reject_all", description: "reject_all presses Reject All (only strictly necessary cookies); accept_all presses Accept Cookies." } } }, outputSchema: { @@ -42,10 +42,11 @@ execute: async input => { let pressed = false; const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message, pressed }); - if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be { choice: \"reject_all\" | \"accept_all\" }."); + if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object such as {} or { choice: \"accept_all\" }."); const extra = Object.keys(input).filter(k => k !== "choice"); if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); - if (!["reject_all", "accept_all"].includes(input.choice)) return fail("invalid_input", "choice must be reject_all or accept_all, as the user decided."); + const choice = input.choice ?? "reject_all"; + if (!["reject_all", "accept_all"].includes(choice)) return fail("invalid_input", "choice must be reject_all or accept_all."); if (!/(^|\.)trainingpeaks\.com$/.test(location.hostname)) return fail("wrong_page", "Open a trainingpeaks.com page first."); const visible = el => !!el && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden"; const groups = () => { @@ -62,13 +63,13 @@ const banner = () => visible(document.getElementById("onetrust-banner-sdk")); if (visible(document.getElementById("onetrust-pc-sdk"))) return fail("settings_open", "The Cookie Settings panel is open; ask the user to finish or close it there."); if (!banner()) return { status: "no_banner", choice: null, banner_visible: false, consent_groups: groups() }; - const button = document.getElementById(input.choice === "reject_all" ? "onetrust-reject-all-handler" : "onetrust-accept-btn-handler"); - if (!visible(button)) return fail("button_missing", "The banner has no visible " + (input.choice === "reject_all" ? "Reject All" : "Accept Cookies") + " button; nothing was pressed."); + const button = document.getElementById(choice === "reject_all" ? "onetrust-reject-all-handler" : "onetrust-accept-btn-handler"); + if (!visible(button)) return fail("button_missing", "The banner has no visible " + (choice === "reject_all" ? "Reject All" : "Accept Cookies") + " button; nothing was pressed."); pressed = true; button.click(); const until = Date.now() + 5000; while (Date.now() < until && (banner() || !/(^|;\s*)OptanonAlertBoxClosed=/.test(document.cookie))) await new Promise(resolve => setTimeout(resolve, 200)); if (banner()) return fail("not_confirmed", "The button was pressed but the banner is still showing; check the page before pressing again."); - return { status: "answered", choice: input.choice, banner_visible: false, consent_groups: groups() }; + return { status: "answered", choice, banner_visible: false, consent_groups: groups() }; } }] diff --git a/domains/trainingpeaks.com/delete_availability.js b/domains/trainingpeaks.com/delete_availability.js index dd9caa5c..b7f503e3 100644 --- a/domains/trainingpeaks.com/delete_availability.js +++ b/domains/trainingpeaks.com/delete_availability.js @@ -4,7 +4,7 @@ tool: { name: "delete_availability", title: "Delete an availability entry", - description: "Delete one Availability entry from the signed-in athlete's TrainingPeaks calendar, as the entry's Delete button does after its \"This cannot be undone\" confirmation. Pass the availability_id from list_availability or add_availability together with the entry's start_date, which must still match: this guards against deleting a different entry. Runs on https://app.trainingpeaks.com while signed in. It sends the delete once and confirms the entry is gone by reading the calendar's availability again; on outcome_unknown call list_availability before trying again. Cannot be undone: re-create the entry with add_availability if needed. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\" }).", + description: "Delete one Availability entry from the signed-in athlete's TrainingPeaks calendar, as the entry's Delete button does after its \"This cannot be undone\" confirmation. Pass the availability_id from list_availability or add_availability together with the entry's start_date, which must still match: this guards against deleting a different entry. Runs on https://app.trainingpeaks.com while signed in. It sends the delete once and confirms the entry is gone by reading the calendar's availability again; on outcome_unknown call list_availability before trying again. Cannot be undone: re-create the entry with add_availability if needed. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\", reload: true }).", inputSchema: { type: "object", additionalProperties: false, required: ["availability_id", "start_date"], properties: { @@ -115,6 +115,6 @@ return fail("outcome_unknown", "TrainingPeaks accepted the delete but availability could not be read again; call list_availability."); } if (after.some(e => e.availability_id === id)) return fail("outcome_unknown", "TrainingPeaks accepted the delete but the entry is still listed; call list_availability."); - return { status: "deleted", account: session.user.username, deleted_entry: entry, next_step: "Reload the calendar with navigate_to_page({ url: \"#calendar\" }) to see the change on screen." }; + return { status: "deleted", account: session.user.username, deleted_entry: entry, next_step: "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }) to see the change on screen." }; } }] diff --git a/domains/trainingpeaks.com/get_page_context.js b/domains/trainingpeaks.com/get_page_context.js index 3276f857..ab0f8a7c 100644 --- a/domains/trainingpeaks.com/get_page_context.js +++ b/domains/trainingpeaks.com/get_page_context.js @@ -198,7 +198,7 @@ if (formOpen) steps.push("An Availability form is open. Its Save and Delete are the user's; to change entries use add_availability or delete_availability, and leave the form with " + go("#calendar") + " (needs discard_form: true)."); if (pageType === "calendar" || pageType === "item") { if (has("list_availability")) steps.push("Use list_availability({ start_date, end_date }) to read days off (unavailable or limited) in a range."); - if (has("add_availability")) steps.push("Use add_availability({ start_date, end_date, availability: \"unavailable\", reason: \"Vacation\" }) to add days off; then " + go("#calendar") + " reloads the calendar to show it."); + if (has("add_availability")) steps.push("Use add_availability({ start_date, end_date, availability: \"unavailable\", reason: \"Vacation\" }) to add days off; then " + (has("navigate_to_page") ? "navigate_to_page({ url: \"#calendar\", reload: true })" : "reload the page") + " shows it on the calendar."); } else if (pageType === "login" || pageType === "website" || pageType === "app_landing" || pageType === "other") { steps.push("Signed in. Days off (Availability) live on the calendar: " + go("#calendar") + "."); } else { @@ -207,7 +207,7 @@ if (account && account.is_athlete === false) steps.push("This is not an athlete account; the availability tools write only to the signed-in athlete's own calendar."); } if (cookieBanner.settings_open) steps.push("The Cookie Settings panel is open; the user finishes or closes it there."); - else if (cookieBanner.visible) steps.push("The cookie-consent banner is showing" + (cookieBanner.blocks_page ? " and its overlay blocks clicks on the page" : "") + ". Ask the user whether to Reject All or Accept Cookies, then " + (has("answer_cookie_banner") ? "answer_cookie_banner({ choice: \"reject_all\" })" : "press that button") + " with their choice; never choose for them."); + else if (cookieBanner.visible) steps.push("The cookie-consent banner is showing" + (cookieBanner.blocks_page ? " and its overlay blocks clicks on the page" : "") + ". " + (has("answer_cookie_banner") ? "answer_cookie_banner({}) closes it with Reject All (only strictly necessary cookies); pass choice: \"accept_all\" only if the user wants it." : "Its Reject All button closes it with only strictly necessary cookies.") ); return { status: "ok", diff --git a/domains/trainingpeaks.com/navigate_to_page.js b/domains/trainingpeaks.com/navigate_to_page.js index 202e5ce5..414d1667 100644 --- a/domains/trainingpeaks.com/navigate_to_page.js +++ b/domains/trainingpeaks.com/navigate_to_page.js @@ -4,12 +4,13 @@ tool: { name: "navigate_to_page", title: "Open a page in the TrainingPeaks app", - description: "Navigate this tab to a page of the TrainingPeaks web app (https://app.trainingpeaks.com), whose pages are # routes. The tab changes after this tool returns; then call get_page_context({ wait_for_settled_seconds: 10 }) and list tools again, because tool_refs can change. Passing the address already open reloads it, which is how to show changes made by add_availability or delete_availability. Pages:\n- #home - Home: the athlete's events, goals and performance summary\n- #calendar - Calendar of workouts, notes and Availability (days off); list_availability, add_availability and delete_availability work from here\n- #calendar/athletes/USER_ID/availability/AVAILABILITY_ID - Opens one Availability entry's form (user_id from get_page_context, availability_id from list_availability); its Save and Delete are left to the user or to the availability tools\n- #dashboard - Dashboard charts (fitness, fatigue, form)\n- #plan - ATP, the Annual Training Plan\n- #settings - Account and athlete settings\nExample: navigate_to_page({ url: \"#calendar\" })\nurl is a # route, a path on app.trainingpeaks.com, or a full https://app.trainingpeaks.com URL; other sites and hosts are refused (sign in with the login tool, not by opening the login page). While an Availability form is open it refuses to leave unless discard_form is true, because leaving drops unsaved edits. The result says the navigation was scheduled, not that the page loaded.", + description: "Navigate this tab to a page of the TrainingPeaks web app (https://app.trainingpeaks.com), whose pages are # routes. The tab changes after this tool returns; then call get_page_context({ wait_for_settled_seconds: 10 }) and list tools again, because tool_refs can change. Passing the address already open, or reload: true, reloads the page; the app keeps showing cached calendar data after switching routes, so use navigate_to_page({ url: \"#calendar\", reload: true }) to show changes made by add_availability or delete_availability. Pages:\n- #home - Home: the athlete's events, goals and performance summary\n- #calendar - Calendar of workouts, notes and Availability (days off); list_availability, add_availability and delete_availability work from here\n- #calendar/athletes/USER_ID/availability/AVAILABILITY_ID - Opens one Availability entry's form (user_id from get_page_context, availability_id from list_availability); its Save and Delete are left to the user or to the availability tools\n- #dashboard - Dashboard charts (fitness, fatigue, form)\n- #plan - ATP, the Annual Training Plan\n- #settings - Account and athlete settings\nExample: navigate_to_page({ url: \"#calendar\" })\nurl is a # route, a path on app.trainingpeaks.com, or a full https://app.trainingpeaks.com URL; other sites and hosts are refused (sign in with the login tool, not by opening the login page). While an Availability form is open it refuses to leave unless discard_form is true, because leaving drops unsaved edits. The result says the navigation was scheduled, not that the page loaded.", inputSchema: { type: "object", additionalProperties: false, required: ["url"], properties: { url: { type: "string", minLength: 1, maxLength: 2000, pattern: "^(#|/(?!/)|https://app\\.trainingpeaks\\.com([/?#]|$))", description: "A # route such as \"#calendar\", a path on app.trainingpeaks.com, or a full https://app.trainingpeaks.com URL." }, - discard_form: { type: "boolean", default: false, description: "Leave an open Availability form, dropping unsaved edits." } + discard_form: { type: "boolean", default: false, description: "Leave an open Availability form, dropping unsaved edits." }, + reload: { type: "boolean", default: false, description: "Load the page fresh, so the app refetches its data instead of showing cached data." } } }, outputSchema: { @@ -35,9 +36,10 @@ const APP = "https://app.trainingpeaks.com"; const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message }); if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object, e.g. { url: \"#calendar\" }."); - const extra = Object.keys(input).filter(k => !["url", "discard_form"].includes(k)); + const extra = Object.keys(input).filter(k => !["url", "discard_form", "reload"].includes(k)); if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + ": pass the page as url, e.g. { url: \"#calendar\" }."); if (input.discard_form !== undefined && typeof input.discard_form !== "boolean") return fail("invalid_input", "discard_form must be true or false."); + if (input.reload !== undefined && typeof input.reload !== "boolean") return fail("invalid_input", "reload must be true or false."); const raw = typeof input.url === "string" ? input.url.trim() : ""; const absolute = /^[a-z][a-z0-9+.-]*:/i.test(raw); if (!raw || raw.length > 2000 || raw.includes("\\") || (!absolute && !raw.startsWith("#") && (!raw.startsWith("/") || raw.startsWith("//")))) return fail("invalid_input", "url must be a # route such as \"#calendar\", a path starting with a single \"/\", or a full https://app.trainingpeaks.com URL."); @@ -49,14 +51,16 @@ if (formOpen && input.discard_form !== true) return fail("form_open", "An Availability form is open; leaving drops its unsaved edits. Ask the user to save or cancel it, or pass discard_form: true."); const from = location.href; const to = target.href; - const reload = to === from || (to === APP + "/" && from === APP + "/"); + const reload = input.reload === true || to === from; globalThis.__xwebmcpTrainingPeaksNavigation = { from, to, at: Date.now() }; - const sameDocument = location.origin === APP && target.pathname === location.pathname && target.search === location.search && !reload; + const sameDocument = location.origin === APP && target.pathname === location.pathname && target.search === location.search; // Return first: a reload or a cross-document navigation destroys this document and this tool's result. setTimeout(() => { - if (reload) location.reload(); - else if (sameDocument) location.hash = target.hash; - else location.assign(to); + if (!sameDocument) location.assign(to); + else { + if (to !== from) location.hash = target.hash; + if (reload) location.reload(); + } }, 100); return { status: "navigation_scheduled", from_url: from, to_url: to, reload, diff --git a/registry.json b/registry.json index 5e730e04..6282dd98 100644 --- a/registry.json +++ b/registry.json @@ -4334,7 +4334,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back. Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Live creation not yet exercised." + "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back. Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Builder live run 2026-11-27: created three adjacent entries on the real account (two unavailable, one limited with bike), each read back with its id and shown on the calendar after navigate_to_page({ url: \"#calendar\", reload: true }); switching routes without a reload showed the cached calendar without them." }, { "domain": "trainingpeaks.com", @@ -4348,7 +4348,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Presses the OneTrust banner's own Reject All or Accept Cookies button once, for an explicit choice passed by the caller (never a default), and confirms the banner closed and the OptanonAlertBoxClosed cookie was set; reports the recorded consent groups. Does nothing without a banner and refuses while Cookie Settings is open. Page kind: the click does not navigate. Fixture-tested; live run pending." + "notes": "Presses the OneTrust banner's own Reject All or Accept Cookies button once, with choice defaulting to reject_all (only strictly necessary cookies), and confirms the banner closed and the OptanonAlertBoxClosed cookie was set; reports the recorded consent groups. Does nothing without a banner and refuses while Cookie Settings is open. Page kind: the click does not navigate. Builder live run 2026-11-27: {} pressed Reject All; the banner and its page-wide overlay closed and only C0001 (strictly necessary) was recorded, and get_page_context then reported answered true. accept_all and settings_open are fixture-tested only." }, { "domain": "trainingpeaks.com", @@ -4418,7 +4418,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Schedules a same-tab navigation to an app.trainingpeaks.com route 100 ms after returning: a hash change within the app, a full load from other trainingpeaks.com hosts, or a reload when the address is already open (used to show availability changes, since the calendar does not refresh after an API write). Refuses other hosts, protocol-relative and javascript: URLs, and leaving an open Availability form unless discard_form is true. Builder live run 2026-11-27: form_open refusal, discard to #calendar, reload of #calendar, #dashboard, and refused login-host and protocol-relative URLs." + "notes": "Schedules a same-tab navigation to an app.trainingpeaks.com route 100 ms after returning: a hash change within the app, a full load from other trainingpeaks.com hosts, or a reload when the address is already open or reload is true (the app shows cached calendar data after switching routes, observed live 2026-11-27, so availability changes need reload: true). Refuses other hosts, protocol-relative and javascript: URLs, and leaving an open Availability form unless discard_form is true. Builder live run 2026-11-27: form_open refusal, discard to #calendar, reload of #calendar, #dashboard, and refused login-host and protocol-relative URLs." }, { "domain": "ubereats.com", diff --git a/tests/trainingpeaks.test.mjs b/tests/trainingpeaks.test.mjs index 5737d2f1..6c55d741 100644 --- a/tests/trainingpeaks.test.mjs +++ b/tests/trainingpeaks.test.mjs @@ -167,6 +167,10 @@ test("navigate_to_page schedules app routes after returning, reloads the open ad const again = page("navigate_to_page"); assert.equal((await again.run({ url: "#calendar" })).reload, true); assert.deepEqual(again.scheduled, [{ reload: true }]); + const fresh = page("navigate_to_page", { href: "https://app.trainingpeaks.com/#dashboard" }); + assert.equal((await fresh.run({ url: "#calendar", reload: true })).reload, true); + assert.deepEqual(fresh.scheduled, [{ hash: "#calendar" }, { reload: true }], "switching routes alone shows cached calendar data"); + assert.equal((await page("navigate_to_page").run({ url: "#calendar", reload: "yes" })).error_kind, "invalid_input"); const fromLogin = page("navigate_to_page", { href: "https://home.trainingpeaks.com/login" }); await fromLogin.run({ url: "https://app.trainingpeaks.com/#calendar" }); assert.deepEqual(fromLogin.scheduled, [{ assign: "https://app.trainingpeaks.com/#calendar" }]); @@ -199,7 +203,7 @@ test("get_page_context reports the page, account, calendar range, open item and assert.deepEqual(result.available_tools, [...tools, "answer_cookie_banner"].sort()); assert.ok(result.suggested_next_steps.some(s => s.includes("discard_form"))); assert.deepEqual(result.cookie_banner, { visible: true, settings_open: false, blocks_page: true, answered: false }); - assert.ok(result.suggested_next_steps.some(s => s.includes("answer_cookie_banner") && s.includes("never choose for them"))); + assert.ok(result.suggested_next_steps.some(s => s.includes("answer_cookie_banner({}) closes it with Reject All"))); const login = await page("get_page_context", { href: "https://home.trainingpeaks.com/login", api: site({ signedIn: false }), tools: ["login"] }).run({}); assert.deepEqual([login.page_type, login.signed_in, login.account], ["login", false, null]); assert.deepEqual(login.cookie_banner, { visible: false, settings_open: false, blocks_page: false, answered: false }); @@ -234,10 +238,13 @@ test("answer_cookie_banner presses only the button for the user's choice and rep } }); -test("answer_cookie_banner requires an explicit choice and presses nothing without a banner or with Cookie Settings open", async () => { +test("answer_cookie_banner defaults to Reject All and presses nothing for bad input, without a banner or with Cookie Settings open", async () => { const { p, state } = bannerPage(); - for (const input of [{}, { choice: "close" }, { choice: "reject_all", extra: 1 }]) assert.equal((await p.run(input)).error_kind, "invalid_input"); + for (const input of [{ choice: "close" }, { choice: "reject_all", extra: 1 }]) assert.equal((await p.run(input)).error_kind, "invalid_input"); assert.deepEqual(state.pressed, []); + const byDefault = bannerPage(); + assert.equal((await byDefault.p.run({})).choice, "reject_all"); + assert.deepEqual(byDefault.state.pressed, ["reject"]); const none = bannerPage({ shown: false }); const absent = await none.p.run({ choice: "reject_all" }); assert.deepEqual([absent.status, absent.choice], ["no_banner", null]); From 195deb100c0dc5827b10cc64811420ca144f031f Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:21:08 +0000 Subject: [PATCH 4/5] Add get_calendar to read workouts and availability from the drawn calendar --- domains/trainingpeaks.com/README.md | 1 + domains/trainingpeaks.com/add_availability.js | 2 +- .../trainingpeaks.com/delete_availability.js | 2 +- domains/trainingpeaks.com/get_calendar.js | 144 ++++++++++++++++++ domains/trainingpeaks.com/get_page_context.js | 1 + registry.json | 14 ++ tests/trainingpeaks.test.mjs | 43 +++++- 7 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 domains/trainingpeaks.com/get_calendar.js diff --git a/domains/trainingpeaks.com/README.md b/domains/trainingpeaks.com/README.md index 058ae161..0e041657 100644 --- a/domains/trainingpeaks.com/README.md +++ b/domains/trainingpeaks.com/README.md @@ -5,6 +5,7 @@ | add_availability | Adds one Availability entry (days unable to train, or with limited availability) to the signed-in athlete's calendar and confirms it by reading it back. | | answer_cookie_banner | Answers the cookie-consent banner with Reject All by default, or Accept Cookies when asked, by pressing the site's button, and confirms it closed. | | delete_availability | Deletes one Availability entry by id after checking its start date, and confirms it is gone. | +| get_calendar | Reads the workouts and Availability tiles the open calendar shows for up to 62 drawn days, without clicking or scrolling. | | get_page_context | Describes the open TrainingPeaks page: page type, signed-in account, calendar range, open forms, cookie banner, live tools, loading state and next steps. | | list_availability | Lists the signed-in athlete's Availability entries (days off) overlapping a date range of up to 365 days. | | login | Signs in with username and password, submitting at most once, and confirms the signed-in account; an existing session is confirmed without submitting. | diff --git a/domains/trainingpeaks.com/add_availability.js b/domains/trainingpeaks.com/add_availability.js index 19b47b2e..74aec279 100644 --- a/domains/trainingpeaks.com/add_availability.js +++ b/domains/trainingpeaks.com/add_availability.js @@ -133,7 +133,7 @@ let existing; try { existing = await tpListAvailability(session, start, end); } catch (error) { return fail("site_error", String(error && error.message || error).slice(0, 300)); } const identical = existing.find(sameEntry); - const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }) to see it on screen."; + const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }), then get_calendar to check it on screen."; if (identical) return { status: "already_exists", account: session.user.username, entry: identical, next_step: "Nothing was written. " + next }; if (existing.length && input.allow_overlap !== true) return fail("overlap", "Other availability entries already overlap these dates; nothing was written. Change or delete them, or pass allow_overlap: true.", existing); // The exact request the Availability form's Save button sends. diff --git a/domains/trainingpeaks.com/delete_availability.js b/domains/trainingpeaks.com/delete_availability.js index b7f503e3..32bdbe22 100644 --- a/domains/trainingpeaks.com/delete_availability.js +++ b/domains/trainingpeaks.com/delete_availability.js @@ -115,6 +115,6 @@ return fail("outcome_unknown", "TrainingPeaks accepted the delete but availability could not be read again; call list_availability."); } if (after.some(e => e.availability_id === id)) return fail("outcome_unknown", "TrainingPeaks accepted the delete but the entry is still listed; call list_availability."); - return { status: "deleted", account: session.user.username, deleted_entry: entry, next_step: "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }) to see the change on screen." }; + return { status: "deleted", account: session.user.username, deleted_entry: entry, next_step: "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }), then get_calendar to check the change on screen." }; } }] diff --git a/domains/trainingpeaks.com/get_calendar.js b/domains/trainingpeaks.com/get_calendar.js new file mode 100644 index 00000000..4503be07 --- /dev/null +++ b/domains/trainingpeaks.com/get_calendar.js @@ -0,0 +1,144 @@ +[{ + kind: "page", + match: { url_patterns: ["https://trainingpeaks.com/*", "https://*.trainingpeaks.com/*"] }, + tool: { + name: "get_calendar", + title: "Read the calendar", + description: "Read what the open TrainingPeaks Calendar shows for a range of days (at most 62): each day's workouts (id, sport, title, whether planned, completed or skipped, and the duration, distance and TSS shown on the card) and its Availability tiles (availability_id and unavailable or limited). Use it to check the calendar after add_availability or delete_availability, or to see planned and completed training. Runs on https://app.trainingpeaks.com/#calendar. Read-only: it reads the days the calendar has already drawn and never clicks, scrolls or navigates; dates outside the drawn range are listed in not_drawn (get_page_context reports the drawn range). It does not prove the calendar is fresh: after writing through a tool, reload with navigate_to_page({ url: \"#calendar\", reload: true }) first. Availability reasons and descriptions are not on the tiles; read them with list_availability.", + inputSchema: { + type: "object", additionalProperties: false, + properties: { + start_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "First day, YYYY-MM-DD; defaults to today." }, + end_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Last day, YYYY-MM-DD; defaults to 13 days after start_date; at most 61 days after it." } + } + }, + outputSchema: { + type: "object", + oneOf: [ + { + type: "object", additionalProperties: false, required: ["status", "start_date", "end_date", "today", "drawn_range", "not_drawn", "days"], + properties: { + status: { const: "ok" }, + start_date: { type: "string" }, end_date: { type: "string" }, + today: { type: ["string", "null"] }, + drawn_range: { + type: "object", additionalProperties: false, required: ["first_date", "last_date"], + properties: { first_date: { type: ["string", "null"] }, last_date: { type: ["string", "null"] } } + }, + not_drawn: { type: "array", items: { type: "string" }, description: "Requested dates the calendar has not drawn, so they are not in days." }, + days: { + type: "array", + items: { + type: "object", additionalProperties: false, required: ["date", "workouts", "availability"], + properties: { + date: { type: "string" }, + workouts: { + type: "array", + items: { + type: "object", additionalProperties: false, required: ["workout_id", "sport", "title", "planned", "completed", "skipped", "duration", "distance", "tss"], + properties: { + workout_id: { type: "integer" }, + sport: { type: ["string", "null"] }, + title: { type: ["string", "null"] }, + planned: { type: "boolean" }, completed: { type: "boolean" }, skipped: { type: "boolean" }, + duration: { type: ["string", "null"], description: "As shown on the card, e.g. 1:30:00." }, + distance: { type: ["string", "null"], description: "As shown, with its unit, e.g. 25.0 mi." }, + tss: { type: ["number", "null"] } + } + } + }, + availability: { + type: "array", + items: { + type: "object", additionalProperties: false, required: ["availability_id", "availability"], + properties: { + availability_id: { type: "integer" }, + availability: { type: ["string", "null"], enum: ["unavailable", "limited", null], description: "From the tile's label; null when no drawn tile of this entry shows one." } + } + } + } + } + } + } + } + }, + { + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message"], + properties: { + status: { const: "error" }, + error_kind: { enum: ["invalid_input", "wrong_page", "not_ready"] }, + error_message: { type: "string", minLength: 1 } + } + } + ] + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } + }, + execute: async input => { + const fail = (kind, message) => ({ status: "error", error_kind: kind, error_message: message }); + if (input === undefined || input === null) input = {}; + if (typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object."); + const extra = Object.keys(input).filter(k => !["start_date", "end_date"].includes(k)); + if (extra.length) return fail("invalid_input", "Unknown input " + extra.join(", ") + "."); + const isDate = v => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && new Date(v + "T00:00:00Z").toISOString().slice(0, 10) === v; + const addDays = (v, n) => new Date(Date.parse(v + "T00:00:00Z") + n * 86400000).toISOString().slice(0, 10); + for (const key of ["start_date", "end_date"]) if (input[key] !== undefined && !isDate(input[key])) return fail("invalid_input", key + " must be a real date in YYYY-MM-DD form."); + if (location.origin !== "https://app.trainingpeaks.com" || !/^#\/?calendar(\/|$)/.test(location.hash)) return fail("wrong_page", "Open the calendar first: navigate_to_page({ url: \"#calendar\" })."); + const dayEls = [...document.querySelectorAll(".day[data-date]")].filter(d => isDate(d.dataset.date)); + if (!dayEls.length) return fail("not_ready", "The calendar has not drawn any days yet; call get_page_context({ wait_for_settled_seconds: 10 }) and try again."); + const todayEl = dayEls.find(d => d.classList.contains("today")); + const today = todayEl ? todayEl.dataset.date : null; + const start = input.start_date ?? today; + if (!start) return fail("invalid_input", "The calendar shows no today marker; pass start_date."); + const end = input.end_date ?? addDays(start, 13); + if (end < start) return fail("invalid_input", "end_date is before start_date."); + if (Date.parse(end) - Date.parse(start) > 61 * 86400000) return fail("invalid_input", "Read at most 62 days at a time."); + + const text = el => (el && el.textContent ? el.textContent : "").replace(/\s+/g, " ").trim() || null; + const byDate = new Map(dayEls.map(d => [d.dataset.date, d])); + const sorted = [...byDate.keys()].sort(); + // A multi-day availability entry draws a tile on each day but labels only the first tile of each week row. + const labels = new Map(); + for (const tile of document.querySelectorAll('.day[data-date] [data-cy="availabilityTile"]')) { + const id = Number(tile.getAttribute("data-reactid")); + const label = (text(tile) || "").toUpperCase(); + if (Number.isInteger(id) && /^(UNAVAILABLE|LIMITED)$/.test(label)) labels.set(id, label === "LIMITED" ? "limited" : "unavailable"); + } + const days = []; + const notDrawn = []; + for (let date = start; date <= end; date = addDays(date, 1)) { + const day = byDate.get(date); + if (!day) { notDrawn.push(date); continue; } + const workouts = []; + const availability = []; + for (const item of day.querySelectorAll(".activities > *")) { + if (item.getAttribute("data-cy") === "availabilityTile") { + const id = Number(item.getAttribute("data-reactid")); + if (Number.isInteger(id) && id > 0 && !availability.some(a => a.availability_id === id)) availability.push({ availability_id: id, availability: labels.get(id) ?? null }); + continue; + } + const id = Number(item.getAttribute("data-workoutid")); + if (!Number.isInteger(id) || id <= 0) continue; + const status = item.querySelector(".workoutComplianceStatus"); + const flag = name => !!status && status.classList.contains(name); + const tssText = text(item.querySelector(".keyStats .tss span")); + const tss = tssText !== null && /^\d+(\.\d+)?$/.test(tssText) ? Number(tssText) : null; + workouts.push({ + workout_id: id, + sport: text(item.querySelector(".sportType")), + title: text(item.querySelector("h6")), + planned: flag("planned"), completed: flag("complete"), skipped: flag("isSkipped"), + duration: text(item.querySelector(".keyStats .duration")), + distance: text(item.querySelector(".keyStats .distance")), + tss + }); + } + days.push({ date, workouts, availability }); + } + return { + status: "ok", start_date: start, end_date: end, today, + drawn_range: { first_date: sorted[0] || null, last_date: sorted[sorted.length - 1] || null }, + not_drawn: notDrawn, days + }; + } +}] diff --git a/domains/trainingpeaks.com/get_page_context.js b/domains/trainingpeaks.com/get_page_context.js index ab0f8a7c..1c836666 100644 --- a/domains/trainingpeaks.com/get_page_context.js +++ b/domains/trainingpeaks.com/get_page_context.js @@ -197,6 +197,7 @@ } else { if (formOpen) steps.push("An Availability form is open. Its Save and Delete are the user's; to change entries use add_availability or delete_availability, and leave the form with " + go("#calendar") + " (needs discard_form: true)."); if (pageType === "calendar" || pageType === "item") { + if (pageType === "calendar" && has("get_calendar")) steps.push("Use get_calendar({ start_date, end_date }) to read the workouts and Availability tiles the calendar shows on drawn days."); if (has("list_availability")) steps.push("Use list_availability({ start_date, end_date }) to read days off (unavailable or limited) in a range."); if (has("add_availability")) steps.push("Use add_availability({ start_date, end_date, availability: \"unavailable\", reason: \"Vacation\" }) to add days off; then " + (has("navigate_to_page") ? "navigate_to_page({ url: \"#calendar\", reload: true })" : "reload the page") + " shows it on the calendar."); } else if (pageType === "login" || pageType === "website" || pageType === "app_landing" || pageType === "other") { diff --git a/registry.json b/registry.json index 6282dd98..7a5e8d1b 100644 --- a/registry.json +++ b/registry.json @@ -4364,6 +4364,20 @@ "last_verified": null, "notes": "Sends the entry's Delete request (DELETE fitness/v1/athletes/{id}/availability/{availabilityId}; captured from the confirmation dialog on 2026-11-27 with the request stubbed) once, only when the id and start_date match an entry of the signed-in athlete, and confirms it is gone. Builder live run 2026-11-27: a mismatched start_date returned not_found without deleting. Live deletion not yet exercised." }, + { + "domain": "trainingpeaks.com", + "tool": "get_calendar", + "file": "domains/trainingpeaks.com/get_calendar.js", + "kind": "page", + "namespace": "trainingpeaks.com", + "url_patterns": [ + "https://trainingpeaks.com/*", + "https://*.trainingpeaks.com/*" + ], + "status": "draft", + "last_verified": null, + "notes": "Read-only: reads the calendar's drawn day containers (.day[data-date]) for up to 62 days: workout cards (id, sport, title, planned/complete/isSkipped flags, duration, distance, TSS as shown) and Availability tiles (id, and unavailable/limited joined from the labelled tile, since only the first tile of each week row is labelled). Never clicks or scrolls; undrawn dates are listed in not_drawn. Builder live run 2026-11-27 after a calendar reload: a 14-day range mapped every day of three adjacent availability entries (including unlabelled continuation tiles) to the right id and type, a past week returned completed, planned-and-completed and skipped workouts with their stats, and the default range was today plus 13 days. The not_drawn path is fixture-tested only (the live calendar had drawn every requested date)." + }, { "domain": "trainingpeaks.com", "tool": "get_page_context", diff --git a/tests/trainingpeaks.test.mjs b/tests/trainingpeaks.test.mjs index 6c55d741..f00aa39a 100644 --- a/tests/trainingpeaks.test.mjs +++ b/tests/trainingpeaks.test.mjs @@ -189,7 +189,7 @@ test("navigate_to_page schedules app routes after returning, reloads the open ad test("get_page_context reports the page, account, calendar range, open item and next steps", async () => { const days = ["2026-11-29", "2026-11-23", "2026-12-06"].map(date => element({ dataset: { date } })); - const tools = ["add_availability", "delete_availability", "get_page_context", "list_availability", "login", "navigate_to_page"]; + const tools = ["add_availability", "delete_availability", "get_calendar", "get_page_context", "list_availability", "login", "navigate_to_page"]; const p = page("get_page_context", { href: "https://app.trainingpeaks.com/#calendar/athletes/4242/availability/11", tools: [...tools, "answer_cookie_banner"], selectors: { "#onetrust-banner-sdk": [element()], ".onetrust-pc-dark-filter": [element()], ".day[data-date]": days, ".day.today[data-date]": [days[0]], '[data-cy="availabilityEditor"]': [element()], ".frameworkMainWrapper": [element()] } @@ -254,6 +254,47 @@ test("answer_cookie_banner defaults to Reject All and presses nothing for bad in assert.deepEqual(settings.state.pressed, []); }); +// Calendar day containers as the app draws them: a workout card and a three-day availability entry labelled only on its first tile. +function calendarDays() { + const node = (attrs = {}, children = {}, props = {}) => ({ + getAttribute: name => attrs[name] ?? null, + classList: { contains: name => (attrs.class || "").split(" ").includes(name) }, + querySelector: sel => children[sel] ?? null, + querySelectorAll: sel => children[sel] ?? [], + textContent: props.text ?? "", + dataset: props.dataset ?? {} + }); + const t = text => node({}, {}, { text }); + const workout = node({ "data-workoutid": "77" }, { + ".workoutComplianceStatus": node({ class: "workoutComplianceStatus planned complete notCompliant past" }), + ".sportType": t("Bike"), h6: t("Fixture Ride"), + ".keyStats .duration": t("1:00:00"), ".keyStats .distance": t("20.0 mi"), ".keyStats .tss span": t("60") + }); + const tile = label => node({ "data-cy": "availabilityTile", "data-reactid": "501" }, {}, { text: label }); + const day = (date, items, cls = "day") => node({ class: cls }, { ".activities > *": items }, { dataset: { date } }); + const tiles = [tile("UNAVAILABLE"), tile(""), tile("")]; + const days = [day("2026-12-24", [workout], "day today"), day("2026-12-25", [tiles[0]]), day("2026-12-26", [tiles[1]]), day("2026-12-27", [tiles[2]])]; + return { ".day[data-date]": days, '.day[data-date] [data-cy="availabilityTile"]': tiles }; +} + +test("get_calendar reads workouts and availability tiles from drawn days without clicking", async () => { + const p = page("get_calendar", { selectors: calendarDays() }); + const result = await p.run({ start_date: "2026-12-23", end_date: "2026-12-26" }); + assert.deepEqual(result.not_drawn, ["2026-12-23"]); + assert.deepEqual(result.drawn_range, { first_date: "2026-12-24", last_date: "2026-12-27" }); + assert.deepEqual(result.days[0].workouts, [{ workout_id: 77, sport: "Bike", title: "Fixture Ride", planned: true, completed: true, skipped: false, duration: "1:00:00", distance: "20.0 mi", tss: 60 }]); + assert.deepEqual(result.days.slice(1).map(d => d.availability), [[{ availability_id: 501, availability: "unavailable" }], [{ availability_id: 501, availability: "unavailable" }]]); + const byDefault = await page("get_calendar", { selectors: calendarDays() }).run({}); + assert.deepEqual([byDefault.start_date, byDefault.end_date, byDefault.today], ["2026-12-24", "2027-01-06", "2026-12-24"]); +}); + +test("get_calendar refuses other pages, long ranges and an undrawn calendar", async () => { + assert.equal((await page("get_calendar", { href: "https://app.trainingpeaks.com/#dashboard", selectors: calendarDays() }).run({})).error_kind, "wrong_page"); + assert.equal((await page("get_calendar", { selectors: calendarDays() }).run({ start_date: "2026-12-01", end_date: "2027-03-01" })).error_kind, "invalid_input"); + assert.equal((await page("get_calendar", { selectors: calendarDays() }).run({ start_date: "2026-12-02", end_date: "2026-12-01" })).error_kind, "invalid_input"); + assert.equal((await page("get_calendar").run({})).error_kind, "not_ready"); +}); + // The login tool is a cdp tool: its helpers are stubbed and its page functions are recognized by their source. function loginHarness({ sessionUser = null, afterSubmit = () => ({ user: USER }), captcha = true } = {}) { let clock = 1_800_000_000_000; From 469836355ffba09aa79385986048f92a0694030f Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:19:49 +0000 Subject: [PATCH 5/5] Check every stored field in add_availability and note inferred API shapes --- domains/trainingpeaks.com/add_availability.js | 23 ++++++++++++++----- registry.json | 6 ++--- tests/trainingpeaks.test.mjs | 21 ++++++++++++++--- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/domains/trainingpeaks.com/add_availability.js b/domains/trainingpeaks.com/add_availability.js index 74aec279..58582552 100644 --- a/domains/trainingpeaks.com/add_availability.js +++ b/domains/trainingpeaks.com/add_availability.js @@ -4,7 +4,7 @@ tool: { name: "add_availability", title: "Add availability (days off)", - description: "Add one Availability entry to the signed-in athlete's TrainingPeaks calendar, as the calendar's day menu > Add... > Availability form does: a date range (inclusive) when the athlete is unable to train, or has limited availability (optionally naming the sports still possible), with an optional reason (Vacation, Work, Sick, Injury, Appointment, Other) and description. Use it for vacations and other days off; coaches and TrainingPeaks plans see it on the calendar. Runs on https://app.trainingpeaks.com while signed in (use login first). Before writing it reads the range: an identical entry returns already_exists without writing, and any other overlapping entry is refused with overlap unless allow_overlap is true. It sends the form's save request once and never retries; on outcome_unknown call list_availability before trying again. Success is confirmed by reading the entry back. The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\", reload: true }). Remove an entry with delete_availability.", + description: "Add one Availability entry to the signed-in athlete's TrainingPeaks calendar, as the calendar's day menu > Add... > Availability form does: a date range (inclusive) when the athlete is unable to train, or has limited availability (optionally naming the sports still possible), with an optional reason (Vacation, Work, Sick, Injury, Appointment, Other) and description. Use it for vacations and other days off; coaches and TrainingPeaks plans see it on the calendar. Runs on https://app.trainingpeaks.com while signed in (use login first). Before writing it reads the range: an entry identical in every field returns already_exists without writing, and any other overlapping entry (including one with the same dates but a different reason, description or sports) is refused with overlap unless allow_overlap is true. It sends the form's save request once and never retries; on outcome_unknown call list_availability before trying again. Success is confirmed by reading the entry back and checking every field: if TrainingPeaks stored any field differently from what was sent, the result is saved_with_differences, naming the fields and returning the stored entry (it exists; fix it or delete it with delete_availability rather than adding it again). The calendar on screen does not refresh by itself: reload it with navigate_to_page({ url: \"#calendar\", reload: true }). Remove an entry with delete_availability.", inputSchema: { type: "object", additionalProperties: false, required: ["start_date", "end_date"], properties: { @@ -43,13 +43,14 @@ } }, { - type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message", "write_attempted", "overlapping_entries"], + type: "object", additionalProperties: false, required: ["status", "error_kind", "error_message", "write_attempted", "overlapping_entries", "saved_entry"], properties: { status: { const: "error" }, - error_kind: { enum: ["invalid_input", "wrong_page", "signed_out", "wrong_account", "overlap", "site_rejected", "outcome_unknown", "site_error"] }, + error_kind: { enum: ["invalid_input", "wrong_page", "signed_out", "wrong_account", "overlap", "site_rejected", "saved_with_differences", "outcome_unknown", "site_error"] }, error_message: { type: "string", minLength: 1 }, write_attempted: { type: "boolean" }, - overlapping_entries: { type: "array", items: { type: "object" } } + overlapping_entries: { type: "array", items: { type: "object" } }, + saved_entry: { type: ["object", "null"], description: "For saved_with_differences: the entry as TrainingPeaks stored it." } } } ] @@ -104,7 +105,7 @@ }; // @xwebmcp-end let written = false; - const fail = (kind, message, overlapping = []) => ({ status: "error", error_kind: kind, error_message: message, write_attempted: written, overlapping_entries: overlapping }); + const fail = (kind, message, overlapping = [], saved = null) => ({ status: "error", error_kind: kind, error_message: message, write_attempted: written, overlapping_entries: overlapping, saved_entry: saved }); const KEYS = ["start_date", "end_date", "availability", "reason", "description", "available_sports", "allow_overlap", "expected_account"]; if (!input || typeof input !== "object" || Array.isArray(input)) return fail("invalid_input", "Input must be an object with start_date and end_date."); const extra = Object.keys(input).filter(k => !KEYS.includes(k)); @@ -130,9 +131,17 @@ if (input.expected_account !== undefined && session.user.username.toLowerCase() !== input.expected_account.trim().toLowerCase()) return fail("wrong_account", "This browser is signed in to a different TrainingPeaks account than expected_account; nothing was written."); if (session.user.is_athlete === false) return fail("wrong_account", "The signed-in account is not an athlete account; this tool writes only to the athlete's own calendar."); const sameEntry = e => e.start_date === start && e.end_date === end && e.availability === availability; + // Fields of a stored entry that differ from what this call sends. + const wantedSports = [...sports].sort().join(","); + const differences = e => [ + ...(sameEntry(e) ? [] : ["dates_or_availability"]), + ...(e.reason === reason ? [] : ["reason"]), + ...(e.description === description ? [] : ["description"]), + ...([...e.available_sports].sort().join(",") === wantedSports ? [] : ["available_sports"]) + ]; let existing; try { existing = await tpListAvailability(session, start, end); } catch (error) { return fail("site_error", String(error && error.message || error).slice(0, 300)); } - const identical = existing.find(sameEntry); + const identical = existing.find(e => differences(e).length === 0); const next = "Reload the calendar with navigate_to_page({ url: \"#calendar\", reload: true }), then get_calendar to check it on screen."; if (identical) return { status: "already_exists", account: session.user.username, entry: identical, next_step: "Nothing was written. " + next }; if (existing.length && input.allow_overlap !== true) return fail("overlap", "Other availability entries already overlap these dates; nothing was written. Change or delete them, or pass allow_overlap: true.", existing); @@ -163,6 +172,8 @@ } const created = after.find(e => createdId !== null ? e.availability_id === createdId : sameEntry(e) && !existing.some(o => o.availability_id === e.availability_id)); if (!created) return fail("outcome_unknown", "TrainingPeaks accepted the save request but the new entry is not in the calendar's availability; call list_availability for these dates."); + const changed = differences(created); + if (changed.length) return fail("saved_with_differences", "TrainingPeaks saved entry " + created.availability_id + " but stored " + changed.join(", ") + " differently from what was sent. The entry exists: do not add it again; fix it in the calendar or delete it with delete_availability.", [], created); return { status: "created", account: session.user.username, entry: created, next_step: next }; } }] diff --git a/registry.json b/registry.json index 7a5e8d1b..1e224455 100644 --- a/registry.json +++ b/registry.json @@ -4334,7 +4334,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back. Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Builder live run 2026-11-27: created three adjacent entries on the real account (two unavailable, one limited with bike), each read back with its id and shown on the calendar after navigate_to_page({ url: \"#calendar\", reload: true }); switching routes without a reload showed the cached calendar without them." + "notes": "Sends the Availability form's own save request (POST fitness/v1/athletes/{id}/availability; body captured from the form on 2026-11-27 with the request stubbed) once, after reading the range: an identical entry is already_exists and other overlaps are refused unless allow_overlap. Confirms by reading the entry back and comparing every field; a field stored differently from what was sent is saved_with_differences with the stored entry (fixture-tested). already_exists requires every field to match; same dates with other details count as an overlap (live 2026-11-27: an identical call returned already_exists and a changed description returned overlap, neither writing). Uses the API rather than the form's date pickers; the calendar needs a reload to show the entry. Builder live run 2026-11-27: overlap, already_exists, wrong_account and invalid input wrote nothing. Builder live run 2026-11-27: created three adjacent entries on the real account (two unavailable, one limited with bike), each read back with its id and shown on the calendar after navigate_to_page({ url: \"#calendar\", reload: true }); switching routes without a reload showed the cached calendar without them. TrainingPeaks publishes no schema for tpapi (common OpenAPI/Swagger paths return 404 as of 2026-11-27); request shapes are inferred from the web app's own traffic, so a site change can break them without notice." }, { "domain": "trainingpeaks.com", @@ -4362,7 +4362,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Sends the entry's Delete request (DELETE fitness/v1/athletes/{id}/availability/{availabilityId}; captured from the confirmation dialog on 2026-11-27 with the request stubbed) once, only when the id and start_date match an entry of the signed-in athlete, and confirms it is gone. Builder live run 2026-11-27: a mismatched start_date returned not_found without deleting. Live deletion not yet exercised." + "notes": "Sends the entry's Delete request (DELETE fitness/v1/athletes/{id}/availability/{availabilityId}; captured from the confirmation dialog on 2026-11-27 with the request stubbed) once, only when the id and start_date match an entry of the signed-in athlete, and confirms it is gone. Builder live run 2026-11-27: a mismatched start_date returned not_found without deleting. Live deletion not yet exercised. TrainingPeaks publishes no schema for tpapi (common OpenAPI/Swagger paths return 404 as of 2026-11-27); request shapes are inferred from the web app's own traffic, so a site change can break them without notice." }, { "domain": "trainingpeaks.com", @@ -4404,7 +4404,7 @@ ], "status": "draft", "last_verified": null, - "notes": "Reads fitness/v1/athletes/{id}/availability/{start}/{end}, the request the calendar makes, for the signed-in athlete; ranges over 365 days are refused as TrainingPeaks does. Builder live run 2026-11-27 read two existing entries (limited with a sport, and unavailable)." + "notes": "Reads fitness/v1/athletes/{id}/availability/{start}/{end}, the request the calendar makes, for the signed-in athlete; ranges over 365 days are refused as TrainingPeaks does. Builder live run 2026-11-27 read two existing entries (limited with a sport, and unavailable). TrainingPeaks publishes no schema for tpapi (common OpenAPI/Swagger paths return 404 as of 2026-11-27); request shapes are inferred from the web app's own traffic, so a site change can break them without notice." }, { "domain": "trainingpeaks.com", diff --git a/tests/trainingpeaks.test.mjs b/tests/trainingpeaks.test.mjs index f00aa39a..97bbdab9 100644 --- a/tests/trainingpeaks.test.mjs +++ b/tests/trainingpeaks.test.mjs @@ -10,7 +10,7 @@ const API = "https://tpapi.trainingpeaks.com"; const source = name => readFileSync(new URL(`../domains/trainingpeaks.com/${name}.js`, import.meta.url), "utf8"); // A stand-in for the availability API the calendar uses. -function site({ signedIn = true, user = USER, entries = [], postStatus = 200, postThrows = false, deleteStatus = 200 } = {}) { +function site({ signedIn = true, user = USER, entries = [], postStatus = 200, postThrows = false, deleteStatus = 200, store = row => row } = {}) { const rows = entries.map(e => ({ ...e })); const requests = []; let nextId = 900; @@ -27,7 +27,7 @@ function site({ signedIn = true, user = USER, entries = [], postStatus = 200, po if (postStatus !== 200) return json(postStatus, { message: "Bad request" }); const b = JSON.parse(options.body); const row = { id: nextId++, personId: b.personId, startDate: b.startDate + "T00:00:00", endDate: b.endDate + "T00:00:00", limitedAvailability: b.limitedAvailability, type: b.type, reason: b.reason, description: b.description, availableSportTypes: b.availableSportTypes }; - rows.push(row); + rows.push(store(row)); return json(200, row); } const del = new RegExp(`^${API}/fitness/v1/athletes/${user.userId}/availability/(\\d+)$`).exec(url); @@ -110,7 +110,7 @@ test("add_availability sends the form's exact save request once and confirms it test("add_availability writes nothing for identical, overlapping, wrong-account or invalid requests", async () => { const same = page("add_availability", { api: site({ entries: [JUNE] }) }); - const existing = await same.run({ start_date: "2026-05-04", end_date: "2026-05-08", reason: "Vacation" }); + const existing = await same.run({ start_date: "2026-05-04", end_date: "2026-05-08", reason: "Vacation", description: "fixture trip" }); assert.equal(existing.status, "already_exists"); assert.equal(existing.entry.availability_id, 11); const overlap = page("add_availability", { api: site({ entries: [JUNE] }) }); @@ -133,6 +133,21 @@ test("add_availability writes nothing for identical, overlapping, wrong-account assert.equal((await allowed.run({ start_date: "2026-05-07", end_date: "2026-05-10", allow_overlap: true })).status, "created"); }); +test("add_availability checks every stored field and treats same-date entries with other details as overlaps", async () => { + const dropped = page("add_availability", { api: site({ store: row => ({ ...row, description: "", availableSportTypes: [] }) }) }); + const result = await dropped.run({ start_date: "2026-12-01", end_date: "2026-12-03", availability: "limited", available_sports: ["run"], description: "trip" }); + assert.equal(result.error_kind, "saved_with_differences"); + assert.match(result.error_message, /description, available_sports/); + assert.deepEqual([result.write_attempted, result.saved_entry.availability_id, result.saved_entry.description], [true, 900, ""]); + assert.equal(dropped.api.writes().length, 1); + const sportsInAnyOrder = page("add_availability"); + assert.equal((await sportsInAnyOrder.run({ start_date: "2026-12-01", end_date: "2026-12-01", availability: "limited", available_sports: ["swim", "run"] })).status, "created"); + const sameDates = page("add_availability", { api: site({ entries: [JUNE] }) }); + const refused = await sameDates.run({ start_date: "2026-05-04", end_date: "2026-05-08", reason: "Work" }); + assert.equal(refused.error_kind, "overlap"); + assert.equal(sameDates.api.writes().length, 0); +}); + test("add_availability reports a rejected or unanswered save without retrying", async () => { const rejected = page("add_availability", { api: site({ postStatus: 400 }) }); const result = await rejected.run({ start_date: "2026-12-01", end_date: "2026-12-01" });