hevy-mcp 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -3
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +2 -2
- package/dist/{src-D1O3O9f2.mjs → src-B_mNqS1X.mjs} +29 -22
- package/dist/src-B_mNqS1X.mjs.map +1 -0
- package/package.json +2 -1
- package/server.json +2 -2
- package/dist/src-D1O3O9f2.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-B_mNqS1X.mjs","names":["name","version","z","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","fetch","createClient","api.getV1Workouts","api.getV1WorkoutsWorkoutid","api.postV1Workouts","api.putV1WorkoutsWorkoutid","api.getV1WorkoutsCount","api.getV1WorkoutsEvents","api.getV1Routines","api.getV1RoutinesRoutineid","api.postV1Routines","api.putV1RoutinesRoutineid","api.getV1ExerciseTemplates","api.getV1ExerciseTemplatesExercisetemplateid","api.getV1ExerciseHistoryExercisetemplateid","api.postV1ExerciseTemplates","api.getV1RoutineFolders","api.postV1RoutineFolders","api.getV1RoutineFoldersFolderid","api.getV1BodyMeasurements","api.getV1BodyMeasurementsDate","api.postV1BodyMeasurements","api.putV1BodyMeasurementsDate","api.getV1UserInfo","createKubbClient","serviceName","serviceVersion"],"sources":["../src/utils/telemetry.ts","../src/utils/metrics.ts","../src/utils/schemas.ts","../src/prompts/workouts.ts","../src/utils/pagination.ts","../src/generated/client/schemas/userInfoSchema.ts","../src/utils/hevy-http-error.ts","../src/utils/error-policy.ts","../src/utils/response-formatter.ts","../src/resources/hevy.ts","../src/server-metadata.ts","../src/utils/tool-helpers.ts","../src/tools/define-tool.ts","../src/utils/tool-annotations.ts","../src/utils/tool-descriptions.ts","../src/utils/json-parser.ts","../src/tools/input-schemas.ts","../src/tools/payload-mappers.ts","../src/tools/body-measurements.ts","../src/tools/folders.ts","../src/tools/routines.ts","../src/tools/templates.ts","../src/tools/user.ts","../src/tools/routine-discovery.ts","../src/tools/workflows.ts","../src/tools/workouts.ts","../src/tools/register.ts","../src/utils/error-handler.ts","../src/utils/cache.ts","../src/utils/exercise-template-catalog.ts","../src/generated/.kubb/fetch.ts","../src/generated/client/api/getV1BodyMeasurements.ts","../src/generated/client/api/getV1BodyMeasurementsDate.ts","../src/generated/client/api/getV1ExerciseHistoryExercisetemplateid.ts","../src/generated/client/api/getV1ExerciseTemplates.ts","../src/generated/client/api/getV1ExerciseTemplatesExercisetemplateid.ts","../src/generated/client/api/getV1RoutineFolders.ts","../src/generated/client/api/getV1RoutineFoldersFolderid.ts","../src/generated/client/api/getV1Routines.ts","../src/generated/client/api/getV1RoutinesRoutineid.ts","../src/generated/client/api/getV1UserInfo.ts","../src/generated/client/api/getV1Workouts.ts","../src/generated/client/api/getV1WorkoutsCount.ts","../src/generated/client/api/getV1WorkoutsEvents.ts","../src/generated/client/api/getV1WorkoutsWorkoutid.ts","../src/generated/client/api/postV1BodyMeasurements.ts","../src/generated/client/api/postV1ExerciseTemplates.ts","../src/generated/client/api/postV1RoutineFolders.ts","../src/generated/client/api/postV1Routines.ts","../src/generated/client/api/postV1Workouts.ts","../src/generated/client/api/putV1BodyMeasurementsDate.ts","../src/generated/client/api/putV1RoutinesRoutineid.ts","../src/generated/client/api/putV1WorkoutsWorkoutid.ts","../src/utils/hevyClientKubb.ts","../src/utils/hevyClient.ts","../src/utils/mcp-client-logger.ts","../src/tools/tool-runtime.ts","../src/shared-server.ts","../src/utils/config.ts","../src/utils/graceful-shutdown.ts","../src/utils/debug.ts","../src/utils/hevy-client-observability.ts","../src/utils/telemetry-wrapper.ts","../src/utils/observability-wrapper.ts","../src/utils/stdio-observability.ts","../src/utils/version-check.ts","../src/index.ts"],"sourcesContent":["/**\n * Centralized telemetry initialization.\n *\n * This module MUST be imported before any other application code.\n * It sets up OpenTelemetry with dual export: Sentry (error events +\n * traces) and an OTel Collector (traces + metrics to Honeycomb).\n *\n * Sentry SDK: error events, performance traces, release tracking\n * OTel Collector → Honeycomb: performance traces, metrics\n */\n\nimport * as Sentry from \"@sentry/node\";\nimport {\n\tSentryPropagator,\n\tSentrySampler,\n\tSentrySpanProcessor,\n} from \"@sentry/opentelemetry\";\nimport { trace, metrics } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { OTLPMetricExporter } from \"@opentelemetry/exporter-metrics-otlp-http\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport type {\n\tReadableSpan,\n\tSpan,\n\tSpanProcessor,\n} from \"@opentelemetry/sdk-trace\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport {\n\tMeterProvider,\n\tPeriodicExportingMetricReader,\n} from \"@opentelemetry/sdk-metrics\";\n\ndeclare const __HEVY_MCP_NAME__: string | undefined;\ndeclare const __HEVY_MCP_VERSION__: string | undefined;\ndeclare const __HEVY_MCP_BUILD__: boolean | undefined;\ndeclare const __OTEL_COLLECTOR_TOKEN__: string | undefined;\n\nconst name =\n\ttypeof __HEVY_MCP_NAME__ === \"string\" ? __HEVY_MCP_NAME__ : \"hevy-mcp\";\nconst version =\n\ttypeof __HEVY_MCP_VERSION__ === \"string\" ? __HEVY_MCP_VERSION__ : \"dev\";\n\n// Collector token is injected at build time from the OTEL_COLLECTOR_TOKEN\n// GitHub secret via tsdown.config.ts define. The collector forwards\n// traces and metrics to Honeycomb, keeping the Honeycomb API key off the\n// client. The collector endpoint is public (behind Cloudflare Tunnel).\nconst collectorToken =\n\ttypeof __OTEL_COLLECTOR_TOKEN__ === \"string\" && __OTEL_COLLECTOR_TOKEN__\n\t\t? __OTEL_COLLECTOR_TOKEN__\n\t\t: (process.env.OTEL_COLLECTOR_TOKEN ?? \"\");\n\nconst COLLECTOR_ENDPOINT = \"https://otel.chrisdoc.dev/v1\";\n\nconst sentryRelease = process.env.SENTRY_RELEASE ?? `${name}@${version}`;\n\nconst resource = resourceFromAttributes({\n\t\"service.name\": name,\n\t\"service.version\": version,\n});\n\nconst bakedDsn =\n\t\"https://ce696d8333b507acbf5203eb877bce0f@o4508975499575296.ingest.de.sentry.io/4509049671647312\";\nconst rawDsn = process.env.SENTRY_DSN ?? bakedDsn;\nconst isValidDsn =\n\ttypeof rawDsn === \"string\" && rawDsn.length > 0 && !rawDsn.startsWith(\"*\");\n\n// --- Sentry (error monitoring + traces) ---\nconst sentryClient = Sentry.init({\n\tdsn: isValidDsn ? rawDsn : undefined,\n\trelease: sentryRelease,\n\ttracesSampleRate: 1.0,\n\tsendDefaultPii: false,\n\tskipOpenTelemetrySetup: true,\n\tregisterEsmLoaderHooks: false,\n\tignoreErrors: [\"EPIPE\", \"broken pipe\"],\n});\n\n// --- OpenTelemetry tracer provider (dual export) ---\nlet currentUserHash: string | undefined;\n\nclass UserHashSpanProcessor implements SpanProcessor {\n\tonStart(span: Span): void {\n\t\tif (currentUserHash) {\n\t\t\tspan.setAttribute(\"user.hash\", currentUserHash);\n\t\t}\n\t}\n\n\tonEnd(_span: ReadableSpan): void {}\n\n\tasync forceFlush(): Promise<void> {}\n\n\tasync shutdown(): Promise<void> {}\n}\n\nconst spanProcessors: SpanProcessor[] = [\n\tnew UserHashSpanProcessor(),\n\tnew SentrySpanProcessor(),\n];\n\n// OTel Collector → Honeycomb traces — only if token is available\nif (collectorToken) {\n\tspanProcessors.push(\n\t\tnew BatchSpanProcessor(\n\t\t\tnew OTLPTraceExporter({\n\t\t\t\turl: `${COLLECTOR_ENDPOINT}/traces`,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${collectorToken}`,\n\t\t\t\t},\n\t\t\t}),\n\t\t),\n\t);\n}\n\nconst tracerProvider = new NodeTracerProvider({\n\tresource,\n\tsampler: sentryClient ? new SentrySampler(sentryClient) : undefined,\n\tspanProcessors,\n});\n\ntracerProvider.register({\n\tpropagator: new SentryPropagator(),\n\tcontextManager: new Sentry.SentryContextManager(),\n});\n\n// --- OpenTelemetry meter provider (→ Collector → Honeycomb metrics) ---\nif (collectorToken) {\n\tconst meterProvider = new MeterProvider({\n\t\tresource,\n\t\treaders: [\n\t\t\tnew PeriodicExportingMetricReader({\n\t\t\t\texporter: new OTLPMetricExporter({\n\t\t\t\t\turl: `${COLLECTOR_ENDPOINT}/metrics`,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${collectorToken}`,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\texportIntervalMillis: 10_000,\n\t\t\t}),\n\t\t],\n\t});\n\tmetrics.setGlobalMeterProvider(meterProvider);\n}\n\ntrace.setGlobalTracerProvider(tracerProvider);\n\n// Validate that Sentry + OpenTelemetry are wired correctly\nSentry.validateOpenTelemetrySetup();\n\n// --- Shared instances for the rest of the codebase ---\nexport const tracer = trace.getTracer(name);\nexport const meter = metrics.getMeter(name);\nexport { Sentry };\n\n/**\n * Bundled service identity — avoids passing name and version as\n * separate primitives throughout the codebase (Data Clumps smell).\n */\nexport interface ServiceInfo {\n\treadonly name: string;\n\treadonly version: string;\n}\n\nexport const serviceInfo: ServiceInfo = { name, version } as const;\n\n// Keep individual exports for backward compatibility\nexport { name as serviceName, version as serviceVersion };\n\n// --- User context for span attributes ---\nexport function setCurrentUserHash(hash: string): void {\n\tcurrentUserHash = hash;\n}\n","/**\n * Metric instruments for Honeycomb.\n *\n * These are created once from the shared meter provider and exported\n * for use throughout the codebase. All instruments are sent to Honeycomb\n * via the OTLP metrics exporter configured in telemetry.ts.\n */\n\nimport { meter } from \"./telemetry.js\";\n\n/** Total MCP tool invocations, grouped by tool name. */\nexport const toolInvocations = meter.createCounter(\"mcp.tool.invocations\", {\n\tdescription: \"Total MCP tool invocations\",\n});\n\n/** Total MCP tool errors, grouped by tool name and error type. */\nexport const toolErrors = meter.createCounter(\"mcp.tool.errors\", {\n\tdescription: \"Total MCP tool errors\",\n});\n\n/** MCP tool execution duration in milliseconds. */\nexport const toolDuration = meter.createHistogram(\"mcp.tool.duration_ms\", {\n\tdescription: \"MCP tool execution duration in milliseconds\",\n\tunit: \"ms\",\n});\n\n/** Total Hevy API calls, grouped by method, endpoint, and status code. */\nexport const apiCalls = meter.createCounter(\"hevy.api.calls\", {\n\tdescription: \"Total Hevy API calls\",\n});\n\n/** Hevy API response time in milliseconds. */\nexport const apiDuration = meter.createHistogram(\"hevy.api.duration_ms\", {\n\tdescription: \"Hevy API response time in milliseconds\",\n\tunit: \"ms\",\n});\n\n/** Total stdio JSON parse errors, grouped by failure location. */\nexport const stdioParseErrors = meter.createCounter(\"mcp.stdio.parse_errors\", {\n\tdescription: \"Total stdio JSON parse errors\",\n});\n\n/** Total server startup count, grouped by version. */\nexport const serverStartups = meter.createCounter(\"mcp.server.startups\", {\n\tdescription: \"Total server startup count\",\n});\n","import { z } from \"zod\";\n\nfunction coerceNullishNumberInput(value: unknown): unknown {\n\tif (value === null || value === undefined) {\n\t\treturn value;\n\t}\n\n\tif (typeof value !== \"string\") {\n\t\treturn value;\n\t}\n\n\tconst trimmed = value.trim();\n\tif (trimmed === \"\") {\n\t\treturn undefined;\n\t}\n\n\tconst lowered = trimmed.toLowerCase();\n\tif (lowered === \"null\") {\n\t\treturn null;\n\t}\n\tif (lowered === \"undefined\") {\n\t\treturn undefined;\n\t}\n\n\tconst asNumber = Number(trimmed);\n\tif (Number.isNaN(asNumber)) {\n\t\treturn value;\n\t}\n\n\treturn asNumber;\n}\n\nexport const zNullableInt = z.preprocess(\n\tcoerceNullishNumberInput,\n\tz.number().int().nullable().optional(),\n);\n\nexport const zNullableNumber = z.preprocess(\n\t(value) => (value === \"\" ? undefined : value),\n\tz.coerce.number().nullable().optional(),\n);\n\nexport const zOptionalRepRange = z.preprocess(\n\t(value) => (value === null ? undefined : value),\n\tz\n\t\t.object({\n\t\t\tstart: zNullableInt,\n\t\t\tend: zNullableInt,\n\t\t})\n\t\t.optional(),\n);\n\nconst setTypeValues = [\"warmup\", \"normal\", \"failure\", \"dropset\"] as const;\nexport const setTypeEnum = z.enum(setTypeValues).default(\"normal\");\n\nconst muscleGroupValues = [\n\t\"abdominals\",\n\t\"shoulders\",\n\t\"biceps\",\n\t\"triceps\",\n\t\"forearms\",\n\t\"quadriceps\",\n\t\"hamstrings\",\n\t\"calves\",\n\t\"glutes\",\n\t\"abductors\",\n\t\"adductors\",\n\t\"lats\",\n\t\"upper_back\",\n\t\"traps\",\n\t\"lower_back\",\n\t\"chest\",\n\t\"cardio\",\n\t\"neck\",\n\t\"full_body\",\n\t\"other\",\n] as const;\nexport const muscleGroupEnum = z.enum(muscleGroupValues);\n\nconst exerciseTypeValues = [\n\t\"weight_reps\",\n\t\"reps_only\",\n\t\"bodyweight_reps\",\n\t\"bodyweight_assisted_reps\",\n\t\"duration\",\n\t\"weight_duration\",\n\t\"distance_duration\",\n\t\"short_distance_weight\",\n] as const;\nexport const exerciseTypeEnum = z.enum(exerciseTypeValues);\n\nconst equipmentCategoryValues = [\n\t\"none\",\n\t\"barbell\",\n\t\"dumbbell\",\n\t\"kettlebell\",\n\t\"machine\",\n\t\"plate\",\n\t\"resistance_band\",\n\t\"suspension\",\n\t\"other\",\n] as const;\nexport const equipmentCategoryEnum = z.enum(equipmentCategoryValues);\nconst UTC_TIMESTAMP_MESSAGE = \"Must use the UTC format YYYY-MM-DDTHH:mm:ssZ\";\nexport const utcSecondTimestamp = z\n\t.string()\n\t.regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$/, UTC_TIMESTAMP_MESSAGE)\n\t.refine((value) => {\n\t\tconst parsed = new Date(value);\n\t\treturn (\n\t\t\t!Number.isNaN(parsed.getTime()) &&\n\t\t\tparsed.toISOString().replace(\".000Z\", \"Z\") === value\n\t\t);\n\t}, UTC_TIMESTAMP_MESSAGE);\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { utcSecondTimestamp } from \"../utils/schemas.js\";\n\n/** Register guided workout workflow prompts. */\nexport function registerWorkoutPrompts(server: McpServer) {\n\tserver.registerPrompt(\n\t\t\"analyze-workout-progress\",\n\t\t{\n\t\t\ttitle: \"Analyze Workout Progress\",\n\t\t\tdescription: \"Analyze recent workout and body-measurement trends.\",\n\t\t\targsSchema: {\n\t\t\t\tweeks: z.coerce\n\t\t\t\t\t.number()\n\t\t\t\t\t.int()\n\t\t\t\t\t.min(1)\n\t\t\t\t\t.max(12)\n\t\t\t\t\t.default(4)\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe(\"Number of recent weeks to analyze (1-12).\"),\n\t\t\t},\n\t\t},\n\t\t({ weeks = 4 }) => ({\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: [\n\t\t\t\t\t\t\t`Analyze my workout progress over the last ${weeks} weeks.`,\n\t\t\t\t\t\t\t\"Call get-training-summary with the requested weeks; it combines recent workouts and body measurements into one compact evidence set.\",\n\t\t\t\t\t\t\t\"Use the returned period, workout frequency, volume, exercise variety, session list, and measurement trend fields rather than issuing separate count and pagination calls.\",\n\t\t\t\t\t\t\t\"Base the analysis on retrieved evidence and discuss workout frequency, training volume, exercise variety, consistency, and body-measurement trends.\",\n\t\t\t\t\t\t\t\"Distinguish observations from suggestions, note missing or limited data, and do not make unsupported claims or medical conclusions.\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t);\n\n\tserver.registerPrompt(\n\t\t\"create-workout-from-routine\",\n\t\t{\n\t\t\ttitle: \"Create Workout From Routine\",\n\t\t\tdescription: \"Create a completed workout from an existing routine.\",\n\t\t\targsSchema: {\n\t\t\t\troutineId: z.string().min(1).describe(\"Routine ID to use as a guide.\"),\n\t\t\t\tstartTime: utcSecondTimestamp.describe(\n\t\t\t\t\t\"Workout start time in UTC as YYYY-MM-DDTHH:mm:ssZ.\",\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t({ routineId, startTime }) => ({\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: [\n\t\t\t\t\t\t\t`Create a workout from routine ${routineId}, starting at ${startTime}.`,\n\t\t\t\t\t\t\t\"First call get-routine with the routineId and map supported plan fields: routine title to workout title, plus each exerciseTemplateId, supersetId, exercise notes, and set type.\",\n\t\t\t\t\t\t\t\"Do not copy routine-only restSeconds or repRange fields into create-workout.\",\n\t\t\t\t\t\t\t\"Before calling create-workout, confirm or collect the user's actual completed set data for every set, including applicable weight, reps, distance, duration, RPE, or custom metric values.\",\n\t\t\t\t\t\t\t\"Also collect the required endTime in strict UTC YYYY-MM-DDTHH:mm:ssZ format and confirm any other missing required workout fields.\",\n\t\t\t\t\t\t\t\"Never invent completion data. If the actual results or endTime are unavailable, ask the user for them instead of creating the workout.\",\n\t\t\t\t\t\t\t\"Once confirmed, call create-workout with only fields supported by that tool.\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t);\n}\n","export interface PageResult<T> {\n\titems: readonly T[];\n\tpageCount?: number;\n}\n\nexport type PageLoader<T> = (\n\tpage: number,\n\tpageSize: number,\n) => PageResult<T> | PromiseLike<PageResult<T>>;\n\nexport async function fetchAllPages<T>(\n\tloader: PageLoader<T>,\n\tpageSize: number,\n): Promise<T[]> {\n\tconst items: T[] = [];\n\tlet page = 1;\n\n\twhile (true) {\n\t\tconst result = await loader(page, pageSize);\n\t\tif (result.items.length === 0) {\n\t\t\treturn items;\n\t\t}\n\t\t// The current page has already been appended before this boundary check.\n\t\titems.push(...result.items);\n\t\tconst pageCount = result.pageCount;\n\t\tif (\n\t\t\ttypeof pageCount !== \"number\" ||\n\t\t\t!Number.isSafeInteger(pageCount) ||\n\t\t\tpageCount <= page\n\t\t) {\n\t\t\treturn items;\n\t\t}\n\t\tpage += 1;\n\t}\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport { z } from \"zod/v4\";\n\nexport const userInfoSchema = z.object({\n id: z.optional(z.string().describe(\"The user ID.\")),\n name: z.optional(z.string().describe(\"The user's display name.\")),\n url: z.optional(z.string().describe(\"The user's public profile URL.\")),\n});\n","export const HEVY_RETRY_EXHAUSTED_ERROR_CODE = \"HEVY_RETRY_EXHAUSTED\";\nexport const HEVY_REQUEST_ABORTED_ERROR_CODE = \"HEVY_REQUEST_ABORTED\";\n\nexport interface HevyHttpErrorOptions {\n\tstatus?: number;\n\tstatusText?: string;\n\tdata?: unknown;\n\theaders?: Headers;\n\tmethod: string;\n\tendpoint: string;\n\tcode?: string;\n\tcause?: unknown;\n}\n\n/** Sanitized HTTP error that never contains credentials or full request URLs. */\nexport class HevyHttpError extends Error {\n\treadonly status?: number;\n\treadonly statusText?: string;\n\treadonly data?: unknown;\n\treadonly headers?: Headers;\n\treadonly method: string;\n\treadonly endpoint: string;\n\tcode?: string;\n\thevyRetryCount?: number;\n\thevyRetryExhausted?: boolean;\n\n\tconstructor(message: string, options: HevyHttpErrorOptions) {\n\t\tsuper(message, { cause: options.cause });\n\t\tthis.name = \"HevyHttpError\";\n\t\tthis.status = options.status;\n\t\tthis.statusText = options.statusText;\n\t\tthis.data = options.data;\n\t\tthis.headers = options.headers;\n\t\tthis.method = options.method;\n\t\tthis.endpoint = options.endpoint;\n\t\tthis.code = options.code;\n\t}\n}\n\nexport function isHevyHttpError(error: unknown): error is HevyHttpError {\n\treturn error instanceof HevyHttpError;\n}\n","import {\n\tHEVY_REQUEST_ABORTED_ERROR_CODE,\n\tHEVY_RETRY_EXHAUSTED_ERROR_CODE,\n\tisHevyHttpError,\n} from \"./hevy-http-error.js\";\n\n/** Specific error types for categorization and metrics. */\nexport enum ErrorType {\n\tAPI_ERROR = \"API_ERROR\",\n\tRATE_LIMIT = \"RATE_LIMIT\",\n\tVALIDATION_ERROR = \"VALIDATION_ERROR\",\n\tNOT_FOUND = \"NOT_FOUND\",\n\tNETWORK_ERROR = \"NETWORK_ERROR\",\n\tUNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nexport type SafeErrorCategory =\n\t| \"AggregateError\"\n\t| \"DOMException\"\n\t| \"Error\"\n\t| \"EvalError\"\n\t| \"HevyHttpError\"\n\t| \"RangeError\"\n\t| \"ReferenceError\"\n\t| \"SyntaxError\"\n\t| \"TypeError\"\n\t| \"URIError\"\n\t| \"UnknownError\";\n\nexport interface SafeStackFrame {\n\tsource: SafeSourceId;\n\tline: number;\n\tcolumn: number;\n}\n\nexport interface SafeErrorDiagnostic {\n\tcategory: SafeErrorCategory;\n\tcode?: string;\n\tstatus?: number;\n\tmethod?: string;\n\tendpoint?: string;\n\tframes?: SafeStackFrame[];\n}\n\ntype SafeSourceId =\n\t| \"error-handler\"\n\t| \"hevy-client\"\n\t| \"index\"\n\t| \"observability-wrapper\"\n\t| \"shared-server\"\n\t| \"worker\";\n\ntype RetryAwareError = {\n\thevyRetryCount?: number;\n\thevyRetryExhausted?: boolean;\n};\n\nconst SAFE_ERROR_CODES = new Set([\n\t\"EAI_AGAIN\",\n\t\"ECONNABORTED\",\n\t\"ECONNREFUSED\",\n\t\"ECONNRESET\",\n\t\"ENETUNREACH\",\n\t\"ENOTFOUND\",\n\t\"ERR_NETWORK\",\n\t\"ERR_SOCKET_TIMEOUT\",\n\t\"ETIMEDOUT\",\n\t\"HEVY_INVALID_ENDPOINT\",\n\tHEVY_REQUEST_ABORTED_ERROR_CODE,\n\tHEVY_RETRY_EXHAUSTED_ERROR_CODE,\n]);\n\nconst SAFE_HTTP_METHODS = new Set([\n\t\"DELETE\",\n\t\"GET\",\n\t\"HEAD\",\n\t\"OPTIONS\",\n\t\"PATCH\",\n\t\"POST\",\n\t\"PUT\",\n]);\n\nconst SAFE_ENDPOINTS = new Set([\n\t\"unknown\",\n\t\"/v1/body_measurements\",\n\t\"/v1/body_measurements/:date\",\n\t\"/v1/exercise_history/:exerciseTemplateId\",\n\t\"/v1/exercise_templates\",\n\t\"/v1/exercise_templates/:exerciseTemplateId\",\n\t\"/v1/routine_folders\",\n\t\"/v1/routine_folders/:folderId\",\n\t\"/v1/routines\",\n\t\"/v1/routines/:routineId\",\n\t\"/v1/user/info\",\n\t\"/v1/workouts\",\n\t\"/v1/workouts/:workoutId\",\n\t\"/v1/workouts/count\",\n\t\"/v1/workouts/events\",\n]);\n\nconst SAFE_SOURCE_SUFFIXES: ReadonlyArray<readonly [string, SafeSourceId]> = [\n\t[\"/src/utils/error-handler.ts\", \"error-handler\"],\n\t[\"/src/utils/hevyClientKubb.ts\", \"hevy-client\"],\n\t[\"/src/index.ts\", \"index\"],\n\t[\"/src/utils/observability-wrapper.ts\", \"observability-wrapper\"],\n\t[\"/src/shared-server.ts\", \"shared-server\"],\n\t[\"/src/worker.ts\", \"worker\"],\n];\n\nconst PROJECT_PATH_MARKER = \"/hevy-mcp/\";\nconst MAX_STACK_POSITION = 1_000_000;\n\nfunction normalizeHeaderValue(value: unknown): string | undefined {\n\tif (typeof value === \"string\") {\n\t\tconst trimmed = value.trim();\n\t\treturn trimmed.length > 0 ? trimmed : undefined;\n\t}\n\n\tif (typeof value === \"number\" && Number.isFinite(value)) {\n\t\treturn String(value);\n\t}\n\n\tif (Array.isArray(value) && value.length > 0) {\n\t\treturn normalizeHeaderValue(value[0]);\n\t}\n\n\treturn undefined;\n}\n\nfunction getHeaderValue(headers: unknown, key: string): string | undefined {\n\ttry {\n\t\tif (!headers || typeof headers !== \"object\") return undefined;\n\n\t\tif (\n\t\t\t\"get\" in headers &&\n\t\t\ttypeof (headers as { get?: unknown }).get === \"function\"\n\t\t) {\n\t\t\tconst value = (headers as { get: (headerName: string) => unknown }).get(\n\t\t\t\tkey,\n\t\t\t);\n\t\t\treturn normalizeHeaderValue(value);\n\t\t}\n\n\t\tconst headerRecord = headers as Record<string, unknown>;\n\t\treturn normalizeHeaderValue(\n\t\t\theaderRecord[key] ??\n\t\t\t\theaderRecord[key.toLowerCase()] ??\n\t\t\t\theaderRecord[key.toUpperCase()],\n\t\t);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Extract a valid HTTP status without retaining untrusted error metadata. */\nexport function extractErrorStatus(error: unknown): number | undefined {\n\ttry {\n\t\tif (!isHevyHttpError(error)) return undefined;\n\t\treturn error.status !== undefined &&\n\t\t\tNumber.isInteger(error.status) &&\n\t\t\terror.status >= 100 &&\n\t\t\terror.status <= 599\n\t\t\t? error.status\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Return whether the client exhausted its bounded transient retry policy. */\nexport function isRetryExhausted(error: unknown): boolean {\n\ttry {\n\t\treturn (\n\t\t\t!!error &&\n\t\t\ttypeof error === \"object\" &&\n\t\t\t(error as RetryAwareError).hevyRetryExhausted === true\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Interpret a Retry-After header as seconds from the supplied current time. */\nexport function getRetryAfterSeconds(\n\terror: unknown,\n\tnow = Date.now(),\n): number | undefined {\n\ttry {\n\t\tif (!isHevyHttpError(error)) return undefined;\n\t\tconst retryAfterHeader = getHeaderValue(error.headers, \"retry-after\");\n\t\tif (!retryAfterHeader) return undefined;\n\n\t\tconst seconds = Number(retryAfterHeader);\n\t\tif (Number.isFinite(seconds) && seconds >= 0) return seconds;\n\n\t\tconst retryAtMillis = Date.parse(retryAfterHeader);\n\t\tif (Number.isNaN(retryAtMillis)) return undefined;\n\t\treturn Math.ceil(Math.max(0, retryAtMillis - now) / 1000);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Map bounded Hevy HTTP statuses to stable user-facing messages. */\nexport function getStatusErrorMessage(status?: number): string | null {\n\tif (status === 401 || status === 403) {\n\t\treturn \"The Hevy API key is invalid or has expired. Check HEVY_API_KEY.\";\n\t}\n\tif (status === 404) return \"The requested resource was not found in Hevy.\";\n\tif (status === 409) {\n\t\treturn \"A conflict occurred (e.g., a body measurement already exists for this date). Use the update tool instead.\";\n\t}\n\tif (status === 422) {\n\t\treturn \"The request failed Hevy validation. Check the field values and try again.\";\n\t}\n\tif (status === 429) return \"Rate limited by Hevy. Please wait and retry.\";\n\tif (status !== undefined && status >= 500 && status <= 599) {\n\t\treturn \"Hevy API experienced an error. Please retry later.\";\n\t}\n\treturn null;\n}\n\nfunction formatSecondsLabel(seconds: number): string {\n\tconst roundedSeconds = Math.max(0, Math.round(seconds));\n\tconst suffix = roundedSeconds === 1 ? \"\" : \"s\";\n\treturn `${roundedSeconds} second${suffix}`;\n}\n\nfunction getRateLimitMessage(error: unknown): string {\n\tconst seconds = getRetryAfterSeconds(error);\n\tif (seconds !== undefined) {\n\t\treturn `Rate limited by Hevy (HTTP 429). Please wait about ${formatSecondsLabel(seconds)} before retrying.`;\n\t}\n\treturn \"Rate limited by Hevy (HTTP 429). Please wait and retry your request.\";\n}\n\nfunction getRetryExhaustedMessage(error: unknown): string {\n\tlet retryCount: unknown;\n\ttry {\n\t\tretryCount =\n\t\t\ttypeof error === \"object\" && error !== null\n\t\t\t\t? (error as RetryAwareError).hevyRetryCount\n\t\t\t\t: undefined;\n\t} catch {\n\t\tretryCount = undefined;\n\t}\n\tconst attemptCount =\n\t\ttypeof retryCount === \"number\" && Number.isFinite(retryCount)\n\t\t\t? retryCount + 1\n\t\t\t: undefined;\n\tif (attemptCount) {\n\t\treturn `Unable to complete the request after ${attemptCount} attempts to the Hevy API due to transient failures. Please try again shortly.`;\n\t}\n\treturn \"Unable to complete the request after multiple attempts to the Hevy API due to transient failures. Please try again shortly.\";\n}\n\n/** Classify an error using bounded status, names, and supplied text. */\nexport function determineErrorType(error: unknown, message: string): ErrorType {\n\tif (isRetryExhausted(error)) return ErrorType.NETWORK_ERROR;\n\tif (extractErrorStatus(error) === 429) return ErrorType.RATE_LIMIT;\n\n\tlet originalMessage = \"\";\n\tlet nameLower = \"\";\n\ttry {\n\t\tif (error instanceof Error) {\n\t\t\toriginalMessage = error.message.slice(0, 512);\n\t\t\tnameLower = error.name.toLowerCase();\n\t\t}\n\t} catch {\n\t\toriginalMessage = \"\";\n\t\tnameLower = \"\";\n\t}\n\tconst classificationText = `${message}\\n${originalMessage}`.toLowerCase();\n\n\tif (\n\t\tnameLower.includes(\"network\") ||\n\t\tclassificationText.includes(\"network\") ||\n\t\tclassificationText.includes(\"fetch\") ||\n\t\tclassificationText.includes(\"timeout\")\n\t) {\n\t\treturn ErrorType.NETWORK_ERROR;\n\t}\n\tif (\n\t\tnameLower.includes(\"validation\") ||\n\t\tclassificationText.includes(\"validation\") ||\n\t\tclassificationText.includes(\"invalid\") ||\n\t\tclassificationText.includes(\"required\")\n\t) {\n\t\treturn ErrorType.VALIDATION_ERROR;\n\t}\n\tif (\n\t\tclassificationText.includes(\"not found\") ||\n\t\tclassificationText.includes(\"404\") ||\n\t\tclassificationText.includes(\"does not exist\")\n\t) {\n\t\treturn ErrorType.NOT_FOUND;\n\t}\n\tif (\n\t\tnameLower.includes(\"api\") ||\n\t\tclassificationText.includes(\"api\") ||\n\t\tclassificationText.includes(\"server error\") ||\n\t\tclassificationText.includes(\"500\")\n\t) {\n\t\treturn ErrorType.API_ERROR;\n\t}\n\treturn ErrorType.UNKNOWN_ERROR;\n}\n\nfunction classifyError(error: unknown): SafeErrorCategory {\n\tif (isHevyHttpError(error)) return \"HevyHttpError\";\n\tif (error instanceof TypeError) return \"TypeError\";\n\tif (error instanceof RangeError) return \"RangeError\";\n\tif (error instanceof ReferenceError) return \"ReferenceError\";\n\tif (error instanceof SyntaxError) return \"SyntaxError\";\n\tif (error instanceof URIError) return \"URIError\";\n\tif (error instanceof EvalError) return \"EvalError\";\n\tif (error instanceof AggregateError) return \"AggregateError\";\n\tif (typeof DOMException !== \"undefined\" && error instanceof DOMException) {\n\t\treturn \"DOMException\";\n\t}\n\tif (error instanceof Error) return \"Error\";\n\treturn \"UnknownError\";\n}\n\nfunction getSafeCode(error: unknown): string | undefined {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn undefined;\n\t}\n\tconst code = error.code;\n\treturn typeof code === \"string\" && SAFE_ERROR_CODES.has(code)\n\t\t? code\n\t\t: undefined;\n}\n\nfunction getSafeMethod(error: unknown): string | undefined {\n\tif (!isHevyHttpError(error)) return undefined;\n\tconst method = error.method.toUpperCase();\n\treturn SAFE_HTTP_METHODS.has(method) ? method : undefined;\n}\n\nfunction getSafeEndpoint(error: unknown): string | undefined {\n\tif (!isHevyHttpError(error)) return undefined;\n\treturn SAFE_ENDPOINTS.has(error.endpoint) ? error.endpoint : undefined;\n}\n\nfunction parseSafeStackFrames(error: unknown): SafeStackFrame[] | undefined {\n\tif (!(error instanceof Error) || typeof error.stack !== \"string\") {\n\t\treturn undefined;\n\t}\n\n\tconst frames: SafeStackFrame[] = [];\n\tfor (const frameLine of error.stack.split(/\\r?\\n/).slice(1)) {\n\t\tconst match =\n\t\t\t/^\\s{4}at (?:[^()\\r\\n]+ \\()?([^()\\s\\r\\n]+):(\\d+):(\\d+)\\)?$/.exec(\n\t\t\t\tframeLine,\n\t\t\t);\n\t\tif (!match) continue;\n\t\tconst [, rawSource, rawLine, rawColumn] = match;\n\t\tif (!rawSource || !rawLine || !rawColumn) continue;\n\t\tif (\n\t\t\trawSource.includes(\"?\") ||\n\t\t\trawSource.includes(\"#\") ||\n\t\t\t(!rawSource.startsWith(\"/\") && !rawSource.startsWith(\"file:///\")) ||\n\t\t\t!rawSource.includes(PROJECT_PATH_MARKER)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst source = SAFE_SOURCE_SUFFIXES.find(([suffix]) =>\n\t\t\trawSource.endsWith(suffix),\n\t\t)?.[1];\n\t\tif (!source) continue;\n\t\tconst line = Number(rawLine);\n\t\tconst column = Number(rawColumn);\n\t\tif (\n\t\t\t!Number.isSafeInteger(line) ||\n\t\t\t!Number.isSafeInteger(column) ||\n\t\t\tline < 1 ||\n\t\t\tcolumn < 1 ||\n\t\t\tline > MAX_STACK_POSITION ||\n\t\t\tcolumn > MAX_STACK_POSITION\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tframes.push({ source, line, column });\n\t\tif (frames.length === 3) break;\n\t}\n\treturn frames.length > 0 ? frames : undefined;\n}\n\n/** Build bounded diagnostic metadata with no raw messages, payloads, or URLs. */\nexport function createSafeErrorDiagnostic(error: unknown): SafeErrorDiagnostic {\n\ttry {\n\t\tconst diagnostic: SafeErrorDiagnostic = { category: classifyError(error) };\n\t\tconst code = getSafeCode(error);\n\t\tconst status = extractErrorStatus(error);\n\t\tconst method = getSafeMethod(error);\n\t\tconst endpoint = getSafeEndpoint(error);\n\t\tconst frames = parseSafeStackFrames(error);\n\t\tif (code) diagnostic.code = code;\n\t\tif (status !== undefined) diagnostic.status = status;\n\t\tif (method) diagnostic.method = method;\n\t\tif (endpoint) diagnostic.endpoint = endpoint;\n\t\tif (frames) diagnostic.frames = frames;\n\t\treturn diagnostic;\n\t} catch {\n\t\treturn { category: \"UnknownError\" };\n\t}\n}\n\nexport interface ErrorPolicyResult {\n\ttype: ErrorType;\n\tmessage: string;\n\tdiagnostic: SafeErrorDiagnostic;\n}\n\n/** Resolve all bounded policy outputs used by MCP, telemetry, and reporting adapters. */\nexport function resolveErrorPolicy(\n\terror: unknown,\n\tdefaultMessage: string,\n\tnotInitializedMessage?: string,\n): ErrorPolicyResult {\n\tconst diagnostic = createSafeErrorDiagnostic(error);\n\tconst mappedMessage = getStatusErrorMessage(diagnostic.status);\n\tlet message =\n\t\tmappedMessage ??\n\t\t(diagnostic.status !== undefined\n\t\t\t? `Hevy API request failed (HTTP ${diagnostic.status}).`\n\t\t\t: defaultMessage);\n\tlet isNotInitialized = false;\n\ttry {\n\t\tisNotInitialized =\n\t\t\tBoolean(notInitializedMessage) &&\n\t\t\terror instanceof Error &&\n\t\t\terror.message === notInitializedMessage;\n\t} catch {\n\t\tisNotInitialized = false;\n\t}\n\tif (isNotInitialized) {\n\t\tmessage = notInitializedMessage ?? defaultMessage;\n\t} else if (isRetryExhausted(error)) {\n\t\tmessage = getRetryExhaustedMessage(error);\n\t} else if (diagnostic.status === 429) {\n\t\tmessage = getRateLimitMessage(error);\n\t}\n\treturn { type: determineErrorType(error, message), message, diagnostic };\n}\n","import type {\n\tCallToolResult,\n\tTextContent,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\n\nimport { userInfoSchema } from \"../generated/client/schemas/userInfoSchema.js\";\n\nimport type {\n\tBodyMeasurement,\n\tExerciseHistoryEntry,\n\tExerciseTemplate,\n\tGetV1WorkoutsEvents200,\n\tPostV1ExerciseTemplates200,\n\tRoutine,\n\tRoutineFolder,\n\tUserInfo,\n\tWorkout,\n} from \"../generated/client/types/index.js\";\nimport { createSafeErrorDiagnostic } from \"./safe-error-diagnostic.js\";\n\n/**\n * MCP tool response type aligned with MCP SDK CallToolResult while keeping\n * content narrowed to text blocks for this server.\n */\nexport type McpToolResponse = Omit<CallToolResult, \"content\"> & {\n\tcontent: TextContent[];\n};\n\ntype OutputShape = z.ZodRawShape;\ntype OutputFor<TShape extends OutputShape> = z.output<z.ZodObject<TShape>>;\n\nexport interface ResponseContract<TData> {\n\trender(data: TData): McpToolResponse;\n}\n\nexport interface StructuredResponseContract<\n\tTData,\n\tTShape extends OutputShape,\n> extends ResponseContract<TData> {\n\treadonly outputSchema: TShape;\n}\n\ninterface StructuredContractDefinition<TData, TShape extends OutputShape> {\n\treadonly outputSchema: TShape;\n\treadonly normalize: (data: TData) => unknown;\n\treadonly legacyJson: (output: OutputFor<TShape>) => unknown;\n\treadonly text?: (\n\t\tdata: TData,\n\t\toutput: OutputFor<TShape>,\n\t) => string | undefined;\n\treadonly additionalText?: (\n\t\tdata: TData,\n\t\toutput: OutputFor<TShape>,\n\t) => readonly string[];\n}\n\ninterface JsonContractPresentation {\n\treadonly json?: unknown;\n\treadonly text?: string;\n\treadonly additionalText?: readonly string[];\n}\n\nfunction jsonText(data: unknown): string {\n\treturn JSON.stringify(data, null, 2) ?? \"null\";\n}\n\nfunction textContent(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function defineStructuredResponseContract<\n\tconst TShape extends OutputShape,\n\tTData,\n>(\n\tdefinition: StructuredContractDefinition<TData, TShape>,\n): StructuredResponseContract<TData, TShape> {\n\treturn {\n\t\toutputSchema: definition.outputSchema,\n\t\trender(data) {\n\t\t\tconst structuredContent = z\n\t\t\t\t.object(definition.outputSchema)\n\t\t\t\t.parse(definition.normalize(data));\n\t\t\tconst text =\n\t\t\t\tdefinition.text?.(data, structuredContent) ??\n\t\t\t\tjsonText(definition.legacyJson(structuredContent));\n\t\t\tconst additionalText =\n\t\t\t\tdefinition.additionalText?.(data, structuredContent) ?? [];\n\n\t\t\treturn {\n\t\t\t\tcontent: [textContent(text), ...additionalText.map(textContent)],\n\t\t\t\tstructuredContent,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport function defineJsonResponseContract<TData>(\n\tpresent: (data: TData) => JsonContractPresentation,\n): ResponseContract<TData> {\n\treturn {\n\t\trender(data) {\n\t\t\tconst presentation = present(data);\n\t\t\tconst text = presentation.text ?? jsonText(presentation.json);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\ttextContent(text),\n\t\t\t\t\t...(presentation.additionalText ?? []).map(textContent),\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** The only public success-response entry point used by tool handlers. */\nexport function respond<TData>(\n\tcontract: ResponseContract<TData>,\n\tdata: TData,\n): McpToolResponse {\n\treturn contract.render(data);\n}\n\nconst optionalNullableNumber = z.number().nullable().optional();\n\nexport const formattedWorkoutSetSchema = z.object({\n\tindex: z.number().optional(),\n\ttype: z.string().optional(),\n\tweight: optionalNullableNumber,\n\treps: optionalNullableNumber,\n\tdistance: optionalNullableNumber,\n\tduration: optionalNullableNumber,\n\trpe: optionalNullableNumber,\n\tcustomMetric: optionalNullableNumber,\n});\n\nexport const formattedWorkoutExerciseSchema = z.object({\n\tindex: z.number().optional(),\n\tname: z.string().optional(),\n\texerciseTemplateId: z.string().optional(),\n\tnotes: z.string().nullable().optional(),\n\tsupersetsId: optionalNullableNumber,\n\tsets: z.array(formattedWorkoutSetSchema).optional(),\n});\n\nexport const formattedWorkoutSchema = z.object({\n\tid: z.string().optional(),\n\ttitle: z.string().optional(),\n\tdescription: z.string().nullable().optional(),\n\tstartTime: z.union([z.string(), z.number()]).optional(),\n\tendTime: z.union([z.string(), z.number()]).optional(),\n\tcreatedAt: z.string().optional(),\n\tupdatedAt: z.string().optional(),\n\tduration: z.string(),\n\texercises: z.array(formattedWorkoutExerciseSchema).optional(),\n});\n\nexport const formattedRoutineSetSchema = z.object({\n\tindex: z.number().optional(),\n\ttype: z.string().optional(),\n\tweight: optionalNullableNumber,\n\treps: optionalNullableNumber,\n\tdistance: optionalNullableNumber,\n\tduration: optionalNullableNumber,\n\tcustomMetric: optionalNullableNumber,\n\trepRange: z\n\t\t.object({\n\t\t\tstart: z.number().nullable().optional(),\n\t\t\tend: z.number().nullable().optional(),\n\t\t})\n\t\t.nullable()\n\t\t.optional(),\n\trpe: optionalNullableNumber,\n});\n\nexport const formattedRoutineExerciseSchema = z.object({\n\tname: z.string().optional(),\n\tindex: z.number().optional(),\n\texerciseTemplateId: z.string().optional(),\n\tnotes: z.string().nullable().optional(),\n\tsupersetId: optionalNullableNumber,\n\trestSeconds: z.union([z.string(), z.number()]).nullable().optional(),\n\tsets: z.array(formattedRoutineSetSchema).optional(),\n});\n\nexport const formattedRoutineSchema = z.object({\n\tid: z.string().optional(),\n\ttitle: z.string().optional(),\n\tfolderId: z.number().nullable().optional(),\n\tcreatedAt: z.string().optional(),\n\tupdatedAt: z.string().optional(),\n\texercises: z.array(formattedRoutineExerciseSchema).optional(),\n});\n\nexport const formattedRoutineFolderSchema = z.object({\n\tid: z.number().optional(),\n\ttitle: z.string().optional(),\n\tcreatedAt: z.string().optional(),\n\tupdatedAt: z.string().optional(),\n});\n\nexport const formattedExerciseTemplateSchema = z.object({\n\tid: z.string().optional(),\n\ttitle: z.string().optional(),\n\ttype: z.string().optional(),\n\tprimaryMuscleGroup: z.string().optional(),\n\tsecondaryMuscleGroups: z.array(z.string()).optional(),\n\tisCustom: z.boolean().optional(),\n});\n\nexport const formattedExerciseHistoryEntrySchema = z.object({\n\tworkoutId: z.string().optional(),\n\tworkoutTitle: z.string().optional(),\n\tworkoutStartTime: z.string().optional(),\n\tworkoutEndTime: z.string().optional(),\n\texerciseTemplateId: z.string().optional(),\n\tweight: optionalNullableNumber,\n\treps: optionalNullableNumber,\n\tdistance: optionalNullableNumber,\n\tduration: optionalNullableNumber,\n\trpe: optionalNullableNumber,\n\tcustomMetric: optionalNullableNumber,\n\tsetType: z.string().optional(),\n});\n\nexport const formattedBodyMeasurementSchema = z.object({\n\tdate: z.string(),\n\tweightKg: z.number().nullable(),\n\tleanMassKg: z.number().nullable(),\n\tfatPercent: z.number().nullable(),\n\tneckCm: z.number().nullable(),\n\tshoulderCm: z.number().nullable(),\n\tchestCm: z.number().nullable(),\n\tleftBicepCm: z.number().nullable(),\n\trightBicepCm: z.number().nullable(),\n\tleftForearmCm: z.number().nullable(),\n\trightForearmCm: z.number().nullable(),\n\tabdomen: z.number().nullable(),\n\twaist: z.number().nullable(),\n\thips: z.number().nullable(),\n\tleftThigh: z.number().nullable(),\n\trightThigh: z.number().nullable(),\n\tleftCalf: z.number().nullable(),\n\trightCalf: z.number().nullable(),\n});\nconst workflowTelemetrySchema = z.object({\n\tname: z.string(),\n\tpagination: z.record(z.string(), z.number().int().nonnegative()),\n\tcacheStatus: z.enum([\"hit\", \"miss\", \"not-used\"]),\n\titemsScanned: z.number().int().nonnegative(),\n});\n\nexport const trainingSummarySessionSchema = z.object({\n\tid: z.string().optional(),\n\ttitle: z.string().optional(),\n\tstartTime: z.string().optional(),\n\tendTime: z.string().optional(),\n\tdurationSeconds: z.number().int().nonnegative().nullable(),\n\texerciseCount: z.number().int().nonnegative(),\n\tsetCount: z.number().int().nonnegative(),\n});\n\nexport const compactRoutineSchema = z.object({\n\tid: z.string().optional(),\n\ttitle: z.string().optional(),\n\tfolderId: z.number().nullable(),\n\tupdatedAt: z.string().optional(),\n\texerciseCount: z.number().int().nonnegative(),\n\tsetCount: z.number().int().nonnegative(),\n});\n\nexport type WorkflowTelemetry = z.infer<typeof workflowTelemetrySchema>;\n\nexport type FormattedWorkoutSet = z.infer<typeof formattedWorkoutSetSchema>;\nexport type FormattedWorkoutExercise = z.infer<\n\ttypeof formattedWorkoutExerciseSchema\n>;\nexport type FormattedWorkout = z.infer<typeof formattedWorkoutSchema>;\nexport type FormattedRoutineSet = z.infer<typeof formattedRoutineSetSchema>;\nexport type FormattedRoutineExercise = z.infer<\n\ttypeof formattedRoutineExerciseSchema\n>;\nexport type FormattedRoutine = z.infer<typeof formattedRoutineSchema>;\nexport type FormattedRoutineFolder = z.infer<\n\ttypeof formattedRoutineFolderSchema\n>;\nexport type FormattedExerciseTemplate = z.infer<\n\ttypeof formattedExerciseTemplateSchema\n>;\nexport type FormattedExerciseHistoryEntry = z.infer<\n\ttypeof formattedExerciseHistoryEntrySchema\n>;\nexport type FormattedBodyMeasurement = z.infer<\n\ttypeof formattedBodyMeasurementSchema\n>;\n\nconst workoutsOutputSchema = {\n\tworkouts: z.array(formattedWorkoutSchema),\n} as const;\nconst workoutOutputSchema = {\n\tworkout: formattedWorkoutSchema.nullable(),\n} as const;\nconst workoutCountOutputSchema = { count: z.number().int() } as const;\nexport const formattedUpdatedWorkoutSchema = z.object({\n\ttype: z.literal(\"updated\"),\n\tworkout: formattedWorkoutSchema,\n});\n\nexport const formattedDeletedWorkoutSchema = z.object({\n\ttype: z.literal(\"deleted\"),\n\tid: z.string(),\n\tdeletedAt: z.string().optional(),\n});\n\nconst workoutEventsOutputSchema = {\n\tevents: z.array(\n\t\tz.union([formattedUpdatedWorkoutSchema, formattedDeletedWorkoutSchema]),\n\t),\n} as const;\nconst routinesOutputSchema = {\n\troutines: z.array(formattedRoutineSchema),\n} as const;\nconst routineOutputSchema = {\n\troutine: formattedRoutineSchema.nullable(),\n} as const;\nconst exerciseTemplatesOutputSchema = {\n\texerciseTemplates: z.array(formattedExerciseTemplateSchema),\n} as const;\nconst exerciseTemplateOutputSchema = {\n\texerciseTemplate: formattedExerciseTemplateSchema.nullable(),\n} as const;\nconst exerciseHistoryOutputSchema = {\n\texerciseHistory: z.array(formattedExerciseHistoryEntrySchema),\n} as const;\nconst routineFoldersOutputSchema = {\n\troutineFolders: z.array(formattedRoutineFolderSchema),\n} as const;\nconst routineFolderOutputSchema = {\n\troutineFolder: formattedRoutineFolderSchema.nullable(),\n} as const;\nconst bodyMeasurementsOutputSchema = {\n\tbodyMeasurements: z.array(formattedBodyMeasurementSchema),\n} as const;\nconst bodyMeasurementOutputSchema = {\n\tbodyMeasurement: formattedBodyMeasurementSchema.nullable(),\n} as const;\nconst userOutputSchema = { user: userInfoSchema.nullable() } as const;\nconst trainingSummaryOutputSchema = {\n\tperiod: z.object({\n\t\tstartDate: z.string(),\n\t\tendDate: z.string(),\n\t\tweeks: z.number().int().positive(),\n\t}),\n\tworkouts: z.object({\n\t\tcount: z.number().int().nonnegative(),\n\t\ttotalDurationSeconds: z.number().int().nonnegative(),\n\t\texerciseCount: z.number().int().nonnegative(),\n\t\tsetCount: z.number().int().nonnegative(),\n\t\tuniqueExerciseTemplateIds: z.array(z.string()),\n\t\tsessions: z.array(trainingSummarySessionSchema),\n\t}),\n\tbodyMeasurements: z.object({\n\t\tcount: z.number().int().nonnegative(),\n\t\tlatest: z\n\t\t\t.object({\n\t\t\t\tdate: z.string(),\n\t\t\t\tweightKg: z.number().nullable(),\n\t\t\t\tleanMassKg: z.number().nullable(),\n\t\t\t\tfatPercent: z.number().nullable(),\n\t\t\t})\n\t\t\t.nullable(),\n\t\tearliest: z\n\t\t\t.object({\n\t\t\t\tdate: z.string(),\n\t\t\t\tweightKg: z.number().nullable(),\n\t\t\t\tleanMassKg: z.number().nullable(),\n\t\t\t\tfatPercent: z.number().nullable(),\n\t\t\t})\n\t\t\t.nullable(),\n\t\tweightChangeKg: z.number().nullable(),\n\t}),\n\tworkflow: workflowTelemetrySchema,\n} as const;\nconst compactRoutinesOutputSchema = {\n\troutines: z.array(compactRoutineSchema),\n\tworkflow: workflowTelemetrySchema,\n} as const;\n\ntype ExerciseWithSupersetVariants = {\n\tsupersets_id?: number | null;\n\tsuperset_id?: number | null;\n};\n\nfunction getSupersetId(exercise: ExerciseWithSupersetVariants): number | null {\n\tif (exercise.superset_id !== undefined) {\n\t\treturn exercise.superset_id;\n\t}\n\n\tif (exercise.supersets_id !== undefined) {\n\t\treturn exercise.supersets_id;\n\t}\n\n\treturn null;\n}\n\n/**\n * Format a workout object for consistent presentation\n *\n * @param workout - The workout object from the API\n * @returns A formatted workout object with standardized properties\n */\nexport function formatWorkout(workout: Workout): FormattedWorkout {\n\treturn {\n\t\tid: workout.id,\n\t\ttitle: workout.title,\n\t\tdescription: workout.description,\n\t\tstartTime: workout.start_time,\n\t\tendTime: workout.end_time,\n\t\tcreatedAt: workout.created_at,\n\t\tupdatedAt: workout.updated_at,\n\t\tduration: calculateDuration(workout.start_time, workout.end_time),\n\t\texercises: workout.exercises?.map((exercise) => {\n\t\t\treturn {\n\t\t\t\tindex: exercise.index,\n\t\t\t\tname: exercise.title,\n\t\t\t\texerciseTemplateId: exercise.exercise_template_id,\n\t\t\t\tnotes: exercise.notes,\n\t\t\t\tsupersetsId: getSupersetId(exercise),\n\t\t\t\tsets: exercise.sets?.map((set) => ({\n\t\t\t\t\tindex: set.index,\n\t\t\t\t\ttype: set.type,\n\t\t\t\t\tweight: set.weight_kg,\n\t\t\t\t\treps: set.reps,\n\t\t\t\t\tdistance: set.distance_meters,\n\t\t\t\t\tduration: set.duration_seconds,\n\t\t\t\t\trpe: set.rpe,\n\t\t\t\t\tcustomMetric: set.custom_metric,\n\t\t\t\t})),\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/**\n * Format a routine object for consistent presentation\n *\n * @param routine - The routine object from the API\n * @returns A formatted routine object with standardized properties\n */\nexport function formatRoutine(routine: Routine): FormattedRoutine {\n\treturn {\n\t\tid: routine.id,\n\t\ttitle: routine.title,\n\t\tfolderId: routine.folder_id,\n\t\tcreatedAt: routine.created_at,\n\t\tupdatedAt: routine.updated_at,\n\t\texercises: routine.exercises?.map((exercise) => {\n\t\t\treturn {\n\t\t\t\tname: exercise.title,\n\t\t\t\tindex: exercise.index,\n\t\t\t\texerciseTemplateId: exercise.exercise_template_id,\n\t\t\t\tnotes: exercise.notes,\n\t\t\t\tsupersetId: getSupersetId(exercise),\n\t\t\t\trestSeconds: exercise.rest_seconds,\n\t\t\t\tsets: exercise.sets?.map((set) => ({\n\t\t\t\t\tindex: set.index,\n\t\t\t\t\ttype: set.type,\n\t\t\t\t\tweight: set.weight_kg,\n\t\t\t\t\treps: set.reps,\n\t\t\t\t\t...(set.rep_range !== undefined && { repRange: set.rep_range }),\n\t\t\t\t\tdistance: set.distance_meters,\n\t\t\t\t\tduration: set.duration_seconds,\n\t\t\t\t\t...(set.rpe !== undefined && { rpe: set.rpe }),\n\t\t\t\t\tcustomMetric: set.custom_metric,\n\t\t\t\t})),\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/**\n * Format a routine folder object for consistent presentation\n *\n * @param folder - The routine folder object from the API\n * @returns A formatted routine folder object with standardized properties\n */\nexport function formatRoutineFolder(\n\tfolder: RoutineFolder,\n): FormattedRoutineFolder {\n\treturn {\n\t\tid: folder.id,\n\t\ttitle: folder.title,\n\t\tcreatedAt: folder.created_at,\n\t\tupdatedAt: folder.updated_at,\n\t};\n}\n\n/**\n * Calculate duration between two ISO timestamp strings\n *\n * @param startTime - The start time as ISO string or timestamp\n * @param endTime - The end time as ISO string or timestamp\n * @returns A formatted duration string (e.g. \"1h 30m 45s\") or \"Unknown duration\" if inputs are invalid\n */\nexport function calculateDuration(\n\tstartTime: string | number | null | undefined,\n\tendTime: string | number | null | undefined,\n): string {\n\tif (!startTime || !endTime) return \"Unknown duration\";\n\n\ttry {\n\t\tconst start = new Date(startTime);\n\t\tconst end = new Date(endTime);\n\n\t\t// Validate dates\n\t\tif (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {\n\t\t\treturn \"Unknown duration\";\n\t\t}\n\n\t\tconst durationMs = end.getTime() - start.getTime();\n\n\t\t// Handle negative durations\n\t\tif (durationMs < 0) {\n\t\t\treturn \"Invalid duration (end time before start time)\";\n\t\t}\n\n\t\tconst hours = Math.floor(durationMs / (1000 * 60 * 60));\n\t\tconst minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));\n\t\tconst seconds = Math.floor((durationMs % (1000 * 60)) / 1000);\n\n\t\treturn `${hours}h ${minutes}m ${seconds}s`;\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"Error calculating duration\",\n\t\t\tcreateSafeErrorDiagnostic(error),\n\t\t);\n\t\treturn \"Unknown duration\";\n\t}\n}\n\n/**\n * Format an exercise template object for consistent presentation\n *\n * @param template - The exercise template object from the API\n * @returns A formatted exercise template object with standardized properties\n */\nexport function formatExerciseTemplate(\n\ttemplate: ExerciseTemplate,\n): FormattedExerciseTemplate {\n\treturn {\n\t\tid: template.id,\n\t\ttitle: template.title,\n\t\ttype: template.type,\n\t\tprimaryMuscleGroup: template.primary_muscle_group,\n\t\tsecondaryMuscleGroups: template.secondary_muscle_groups,\n\t\tisCustom: template.is_custom,\n\t};\n}\n\nexport function formatExerciseHistoryEntry(\n\tentry: ExerciseHistoryEntry,\n): FormattedExerciseHistoryEntry {\n\treturn {\n\t\tworkoutId: entry.workout_id,\n\t\tworkoutTitle: entry.workout_title,\n\t\tworkoutStartTime: entry.workout_start_time,\n\t\tworkoutEndTime: entry.workout_end_time,\n\t\texerciseTemplateId: entry.exercise_template_id,\n\t\tweight: entry.weight_kg,\n\t\treps: entry.reps,\n\t\tdistance: entry.distance_meters,\n\t\tduration: entry.duration_seconds,\n\t\trpe: entry.rpe,\n\t\tcustomMetric: entry.custom_metric,\n\t\tsetType: entry.set_type,\n\t};\n}\n\nexport function formatBodyMeasurement(\n\tmeasurement: BodyMeasurement,\n): FormattedBodyMeasurement {\n\treturn {\n\t\tdate: measurement.date,\n\t\tweightKg: measurement.weight_kg ?? null,\n\t\tleanMassKg: measurement.lean_mass_kg ?? null,\n\t\tfatPercent: measurement.fat_percent ?? null,\n\t\tneckCm: measurement.neck_cm ?? null,\n\t\tshoulderCm: measurement.shoulder_cm ?? null,\n\t\tchestCm: measurement.chest_cm ?? null,\n\t\tleftBicepCm: measurement.left_bicep_cm ?? null,\n\t\trightBicepCm: measurement.right_bicep_cm ?? null,\n\t\tleftForearmCm: measurement.left_forearm_cm ?? null,\n\t\trightForearmCm: measurement.right_forearm_cm ?? null,\n\t\tabdomen: measurement.abdomen ?? null,\n\t\twaist: measurement.waist ?? null,\n\t\thips: measurement.hips ?? null,\n\t\tleftThigh: measurement.left_thigh ?? null,\n\t\trightThigh: measurement.right_thigh ?? null,\n\t\tleftCalf: measurement.left_calf ?? null,\n\t\trightCalf: measurement.right_calf ?? null,\n\t};\n}\n\ntype WorkoutEvent = GetV1WorkoutsEvents200[\"events\"][number];\n\nfunction formatWorkoutEvent(event: WorkoutEvent) {\n\tif (event.type === \"updated\" && \"workout\" in event) {\n\t\treturn { type: \"updated\" as const, workout: formatWorkout(event.workout) };\n\t}\n\tif (event.type === \"deleted\" && \"id\" in event) {\n\t\treturn {\n\t\t\ttype: \"deleted\" as const,\n\t\t\tid: event.id,\n\t\t\tdeletedAt: event.deleted_at,\n\t\t};\n\t}\n\tthrow new Error(`Unsupported workout event type: ${event.type}`);\n}\n\nexport const workoutsResponse = defineStructuredResponseContract({\n\toutputSchema: workoutsOutputSchema,\n\tnormalize: (workouts: readonly Workout[] | undefined) => ({\n\t\tworkouts: workouts?.map(formatWorkout) ?? [],\n\t}),\n\tlegacyJson: ({ workouts }) => workouts,\n\ttext: (_data, { workouts }) =>\n\t\tworkouts.length === 0\n\t\t\t? \"No workouts found for the specified parameters\"\n\t\t\t: undefined,\n});\n\nexport const workoutResponse = defineStructuredResponseContract({\n\toutputSchema: workoutOutputSchema,\n\tnormalize: (data: {\n\t\tworkout: Workout | null | undefined;\n\t\tworkoutId: string;\n\t}) => ({ workout: data.workout ? formatWorkout(data.workout) : null }),\n\tlegacyJson: ({ workout }) => workout,\n\ttext: ({ workoutId }, { workout }) =>\n\t\tworkout === null ? `Workout with ID ${workoutId} not found` : undefined,\n});\n\nexport const workoutCountResponse = defineStructuredResponseContract({\n\toutputSchema: workoutCountOutputSchema,\n\tnormalize: (count: number) => ({ count }),\n\tlegacyJson: (output) => output,\n});\n\nexport const workoutEventsResponse = defineStructuredResponseContract({\n\toutputSchema: workoutEventsOutputSchema,\n\tnormalize: (data: {\n\t\tevents: readonly WorkoutEvent[] | undefined;\n\t\tsince: string;\n\t}) => ({ events: data.events?.map(formatWorkoutEvent) ?? [] }),\n\tlegacyJson: ({ events }) => events,\n\ttext: ({ since }, { events }) =>\n\t\tevents.length === 0\n\t\t\t? `No workout events found for the specified parameters since ${since}`\n\t\t\t: undefined,\n});\n\nexport const routinesResponse = defineStructuredResponseContract({\n\toutputSchema: routinesOutputSchema,\n\tnormalize: (routines: readonly Routine[] | undefined) => ({\n\t\troutines: routines?.map(formatRoutine) ?? [],\n\t}),\n\tlegacyJson: ({ routines }) => routines,\n\ttext: (_data, { routines }) =>\n\t\troutines.length === 0\n\t\t\t? \"No routines found for the specified parameters\"\n\t\t\t: undefined,\n});\n\nexport const routineResponse = defineStructuredResponseContract({\n\toutputSchema: routineOutputSchema,\n\tnormalize: (data: {\n\t\troutine: Routine | null | undefined;\n\t\troutineId: string;\n\t}) => ({ routine: data.routine ? formatRoutine(data.routine) : null }),\n\tlegacyJson: ({ routine }) => routine,\n\ttext: ({ routineId }, { routine }) =>\n\t\troutine === null ? `Routine with ID ${routineId} not found` : undefined,\n});\n\nexport const exerciseTemplatesResponse = defineStructuredResponseContract({\n\toutputSchema: exerciseTemplatesOutputSchema,\n\tnormalize: (templates: readonly ExerciseTemplate[] | undefined) => ({\n\t\texerciseTemplates: templates?.map(formatExerciseTemplate) ?? [],\n\t}),\n\tlegacyJson: ({ exerciseTemplates }) => exerciseTemplates,\n\ttext: (_data, { exerciseTemplates }) =>\n\t\texerciseTemplates.length === 0\n\t\t\t? \"No exercise templates found for the specified parameters\"\n\t\t\t: undefined,\n});\n\nexport const exerciseTemplateResponse = defineStructuredResponseContract({\n\toutputSchema: exerciseTemplateOutputSchema,\n\tnormalize: (data: {\n\t\texerciseTemplate: ExerciseTemplate | null | undefined;\n\t\texerciseTemplateId: string;\n\t}) => ({\n\t\texerciseTemplate: data.exerciseTemplate\n\t\t\t? formatExerciseTemplate(data.exerciseTemplate)\n\t\t\t: null,\n\t}),\n\tlegacyJson: ({ exerciseTemplate }) => exerciseTemplate,\n\ttext: ({ exerciseTemplateId }, { exerciseTemplate }) =>\n\t\texerciseTemplate === null\n\t\t\t? `Exercise template with ID ${exerciseTemplateId} not found`\n\t\t\t: undefined,\n});\n\nexport const exerciseHistoryResponse = defineStructuredResponseContract({\n\toutputSchema: exerciseHistoryOutputSchema,\n\tnormalize: (data: {\n\t\thistory: readonly ExerciseHistoryEntry[] | undefined;\n\t\texerciseTemplateId: string;\n\t}) => ({\n\t\texerciseHistory: data.history?.map(formatExerciseHistoryEntry) ?? [],\n\t}),\n\tlegacyJson: ({ exerciseHistory }) => exerciseHistory,\n\ttext: ({ exerciseTemplateId }, { exerciseHistory }) =>\n\t\texerciseHistory.length === 0\n\t\t\t? `No exercise history found for template ${exerciseTemplateId}`\n\t\t\t: undefined,\n});\n\nexport const searchExerciseTemplatesResponse = defineStructuredResponseContract(\n\t{\n\t\toutputSchema: exerciseTemplatesOutputSchema,\n\t\tnormalize: (data: {\n\t\t\tresults: readonly ExerciseTemplate[];\n\t\t\tquery: string;\n\t\t\tprimaryMuscleGroup?: string;\n\t\t}) => ({ exerciseTemplates: data.results.map(formatExerciseTemplate) }),\n\t\tlegacyJson: ({ exerciseTemplates }) => exerciseTemplates,\n\t\ttext: ({ query, primaryMuscleGroup }, { exerciseTemplates }) =>\n\t\t\texerciseTemplates.length === 0\n\t\t\t\t? `No exercise templates found matching \"${query}\"${primaryMuscleGroup ? ` with primary muscle group \"${primaryMuscleGroup}\"` : \"\"}`\n\t\t\t\t: undefined,\n\t},\n);\n\nexport const routineFoldersResponse = defineStructuredResponseContract({\n\toutputSchema: routineFoldersOutputSchema,\n\tnormalize: (folders: readonly RoutineFolder[] | undefined) => ({\n\t\troutineFolders: folders?.map(formatRoutineFolder) ?? [],\n\t}),\n\tlegacyJson: ({ routineFolders }) => routineFolders,\n\ttext: (_data, { routineFolders }) =>\n\t\troutineFolders.length === 0\n\t\t\t? \"No routine folders found for the specified parameters\"\n\t\t\t: undefined,\n});\n\nexport const routineFolderResponse = defineStructuredResponseContract({\n\toutputSchema: routineFolderOutputSchema,\n\tnormalize: (data: {\n\t\troutineFolder: RoutineFolder | null | undefined;\n\t\tfolderId: string;\n\t}) => ({\n\t\troutineFolder: data.routineFolder\n\t\t\t? formatRoutineFolder(data.routineFolder)\n\t\t\t: null,\n\t}),\n\tlegacyJson: ({ routineFolder }) => routineFolder,\n\ttext: ({ folderId }, { routineFolder }) =>\n\t\troutineFolder === null\n\t\t\t? `Routine folder with ID ${folderId} not found`\n\t\t\t: undefined,\n});\n\nexport const bodyMeasurementsResponse = defineStructuredResponseContract({\n\toutputSchema: bodyMeasurementsOutputSchema,\n\tnormalize: (measurements: readonly BodyMeasurement[] | undefined) => ({\n\t\tbodyMeasurements: measurements?.map(formatBodyMeasurement) ?? [],\n\t}),\n\tlegacyJson: ({ bodyMeasurements }) => bodyMeasurements,\n\ttext: (_data, { bodyMeasurements }) =>\n\t\tbodyMeasurements.length === 0\n\t\t\t? \"No body measurements found for the specified parameters\"\n\t\t\t: undefined,\n});\n\nexport const bodyMeasurementResponse = defineStructuredResponseContract({\n\toutputSchema: bodyMeasurementOutputSchema,\n\tnormalize: (data: {\n\t\tbodyMeasurement: BodyMeasurement | null | undefined;\n\t\tdate: string;\n\t}) => ({\n\t\tbodyMeasurement: data.bodyMeasurement\n\t\t\t? formatBodyMeasurement(data.bodyMeasurement)\n\t\t\t: null,\n\t}),\n\tlegacyJson: ({ bodyMeasurement }) => bodyMeasurement,\n\ttext: ({ date }, { bodyMeasurement }) =>\n\t\tbodyMeasurement === null\n\t\t\t? `No body measurement found for date ${date}`\n\t\t\t: undefined,\n});\n\nexport const userResponse = defineStructuredResponseContract({\n\toutputSchema: userOutputSchema,\n\tnormalize: (user: UserInfo | null | undefined) => ({ user: user ?? null }),\n\tlegacyJson: ({ user }) => user,\n\ttext: (_data, { user }) =>\n\t\tuser === null ? \"No user info found for the authenticated user\" : undefined,\n});\nexport type TrainingSummaryResult = z.output<\n\tz.ZodObject<typeof trainingSummaryOutputSchema>\n>;\nexport type CompactRoutinesResult = z.output<\n\tz.ZodObject<typeof compactRoutinesOutputSchema>\n>;\n\nexport const trainingSummaryResponse = defineStructuredResponseContract({\n\toutputSchema: trainingSummaryOutputSchema,\n\tnormalize: (data: TrainingSummaryResult) => data,\n\tlegacyJson: (output) => output,\n\ttext: (data) =>\n\t\tdata.workouts.count === 0 && data.bodyMeasurements.count === 0\n\t\t\t? \"No workouts or body measurements found for the specified period\"\n\t\t\t: undefined,\n});\n\nexport const compactRoutinesResponse = defineStructuredResponseContract({\n\toutputSchema: compactRoutinesOutputSchema,\n\tnormalize: (data: CompactRoutinesResult) => data,\n\tlegacyJson: ({ routines }) => routines,\n\ttext: (_data, { routines }) =>\n\t\troutines.length === 0 ? \"No routines found matching the query\" : undefined,\n});\n\nexport const createWorkoutResponse = defineJsonResponseContract(\n\t(workout: Workout | null | undefined) =>\n\t\tworkout\n\t\t\t? { json: formatWorkout(workout) }\n\t\t\t: { text: \"Failed to create workout: Server returned no data\" },\n);\n\nexport const updateWorkoutResponse = defineJsonResponseContract(\n\t(data: { workout: Workout | null | undefined; workoutId: string }) =>\n\t\tdata.workout\n\t\t\t? { json: formatWorkout(data.workout) }\n\t\t\t: { text: `Failed to update workout with ID ${data.workoutId}` },\n);\n\nconst repRangeDisplayWarningText =\n\t\"Note: Hevy's public API stores rep ranges (rep_range), but the Hevy apps may \" +\n\t\"not display them because they rely on an internal-only exercise field \" +\n\t\"(input_modifier). See https://github.com/chrisdoc/hevy-mcp/issues/261 for \" +\n\t\"details/workarounds.\";\n\nexport const createRoutineResponse = defineJsonResponseContract(\n\t(data: { routine: Routine | null | undefined; usesRepRanges: boolean }) =>\n\t\tdata.routine\n\t\t\t? {\n\t\t\t\t\tjson: formatRoutine(data.routine),\n\t\t\t\t\tadditionalText: data.usesRepRanges\n\t\t\t\t\t\t? [repRangeDisplayWarningText]\n\t\t\t\t\t\t: [],\n\t\t\t\t}\n\t\t\t: { text: \"Failed to create routine: Server returned no data\" },\n);\n\nexport const updateRoutineResponse = defineJsonResponseContract(\n\t(data: {\n\t\troutine: Routine | null | undefined;\n\t\troutineId: string;\n\t\tusesRepRanges: boolean;\n\t}) =>\n\t\tdata.routine\n\t\t\t? {\n\t\t\t\t\tjson: formatRoutine(data.routine),\n\t\t\t\t\tadditionalText: data.usesRepRanges\n\t\t\t\t\t\t? [repRangeDisplayWarningText]\n\t\t\t\t\t\t: [],\n\t\t\t\t}\n\t\t\t: { text: `Failed to update routine with ID ${data.routineId}` },\n);\n\nexport const createExerciseTemplateResponse = defineJsonResponseContract(\n\t(response: PostV1ExerciseTemplates200 | null | undefined) => ({\n\t\tjson: {\n\t\t\tid: response?.id,\n\t\t\tmessage: \"Exercise template created successfully\",\n\t\t},\n\t}),\n);\n\nexport const createRoutineFolderResponse = defineJsonResponseContract(\n\t(folder: RoutineFolder | null | undefined) =>\n\t\tfolder\n\t\t\t? { json: formatRoutineFolder(folder) }\n\t\t\t: {\n\t\t\t\t\ttext: \"Failed to create routine folder: Server returned no data\",\n\t\t\t\t},\n);\n\nexport const createBodyMeasurementResponse = defineJsonResponseContract(\n\t(date: string) => ({\n\t\ttext: `Body measurement for ${date} created successfully.`,\n\t}),\n);\n\nexport const updateBodyMeasurementResponse = defineJsonResponseContract(\n\t(date: string) => ({\n\t\ttext: `Body measurement for ${date} updated successfully.`,\n\t}),\n);\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ReadResourceResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n\tGetV1WorkoutsCount200,\n\tRoutineFolder,\n\tUserInfoResponse,\n} from \"../generated/client/types/index.js\";\nimport type { ToolRuntime } from \"../tools/tool-runtime.js\";\nimport { fetchAllPages } from \"../utils/pagination.js\";\nimport {\n\tformatExerciseTemplate,\n\tformatRoutineFolder,\n} from \"../utils/response-formatter.js\";\n\nconst JSON_MIME_TYPE = \"application/json\";\n\nfunction createJsonResourceResult(uri: URL, data: unknown): ReadResourceResult {\n\treturn {\n\t\tcontents: [\n\t\t\t{\n\t\t\t\turi: uri.toString(),\n\t\t\t\tmimeType: JSON_MIME_TYPE,\n\t\t\t\ttext: JSON.stringify(data),\n\t\t\t},\n\t\t],\n\t};\n}\n\nasync function fetchAllRoutineFolders(\n\truntime: ToolRuntime,\n): Promise<RoutineFolder[]> {\n\tconst client = runtime.getClient();\n\treturn fetchAllPages<RoutineFolder>(async (page, pageSize) => {\n\t\tconst data = await client.getRoutineFolders({ page, pageSize });\n\t\treturn {\n\t\t\titems: data?.routine_folders ?? [],\n\t\t\tpageCount: data?.page_count,\n\t\t};\n\t}, 10);\n}\n\nexport function registerHevyResources(\n\tserver: McpServer,\n\truntime: ToolRuntime,\n): void {\n\tserver.registerResource(\n\t\t\"user-profile\",\n\t\t\"hevy://user\",\n\t\t{\n\t\t\tdescription: \"Authenticated Hevy user profile\",\n\t\t\tmimeType: JSON_MIME_TYPE,\n\t\t},\n\t\tasync (uri) => {\n\t\t\tconst data: UserInfoResponse = await runtime.getClient().getUserInfo();\n\t\t\treturn createJsonResourceResult(uri, data?.data ?? null);\n\t\t},\n\t);\n\n\tserver.registerResource(\n\t\t\"workout-count\",\n\t\t\"hevy://workout-count\",\n\t\t{\n\t\t\tdescription: \"Total number of workouts in the Hevy account\",\n\t\t\tmimeType: JSON_MIME_TYPE,\n\t\t},\n\t\tasync (uri) => {\n\t\t\tconst data: GetV1WorkoutsCount200 = await runtime\n\t\t\t\t.getClient()\n\t\t\t\t.getWorkoutCount();\n\t\t\treturn createJsonResourceResult(uri, {\n\t\t\t\tcount: data?.workout_count ?? 0,\n\t\t\t});\n\t\t},\n\t);\n\n\tserver.registerResource(\n\t\t\"exercise-templates\",\n\t\t\"hevy://exercise-templates\",\n\t\t{\n\t\t\tdescription: \"Full formatted Hevy exercise template catalog\",\n\t\t\tmimeType: JSON_MIME_TYPE,\n\t\t},\n\t\tasync (uri) => {\n\t\t\tconst templates = await runtime.catalog.get();\n\t\t\treturn createJsonResourceResult(\n\t\t\t\turi,\n\t\t\t\ttemplates.map(formatExerciseTemplate),\n\t\t\t);\n\t\t},\n\t);\n\n\tserver.registerResource(\n\t\t\"routine-folders\",\n\t\t\"hevy://routine-folders\",\n\t\t{\n\t\t\tdescription: \"Full formatted list of Hevy routine folders\",\n\t\t\tmimeType: JSON_MIME_TYPE,\n\t\t},\n\t\tasync (uri) => {\n\t\t\tconst folders = await fetchAllRoutineFolders(runtime);\n\t\t\treturn createJsonResourceResult(uri, folders.map(formatRoutineFolder));\n\t\t},\n\t);\n}\n","declare const __HEVY_MCP_NAME__: string | undefined;\ndeclare const __HEVY_MCP_VERSION__: string | undefined;\n\nexport const SERVER_NAME =\n\ttypeof __HEVY_MCP_NAME__ === \"string\" ? __HEVY_MCP_NAME__ : \"hevy-mcp\";\nexport const SERVER_VERSION =\n\ttypeof __HEVY_MCP_VERSION__ === \"string\" ? __HEVY_MCP_VERSION__ : \"dev\";\n\nexport const SERVER_INSTRUCTIONS = [\n\t\"Hevy MCP connects clients to the authenticated user's Hevy workout-tracking data, including workouts, routines, exercise templates, routine folders, body measurements, and profile information. HEVY_API_KEY must contain a valid Hevy API key for local stdio use.\",\n\t\"Safety: all get-* and search-* tools are read-only. create-* and update-* tools mutate Hevy data. Creates are additive and non-idempotent, so repeating one can create duplicates. Updates can overwrite existing data. Delete operations are not available.\",\n\t\"Workflow: search exercise templates first, then use the returned template IDs when creating workouts or routines. To create a completed workout from a routine, fetch the routine as a plan, then obtain the actual completed sets and end time from the user; never invent completion data.\",\n\t\"Pagination: start at page 1 and fetch only the pages needed. Most list tools allow pageSize up to 10; get-exercise-templates allows up to 100.\",\n\t\"Rate limits and retries: minimize repeated calls. If Hevy returns HTTP 429, follow its retry guidance. Transient read requests retry automatically, but write requests do not; confirm uncertain write outcomes before trying again.\",\n].join(\"\\n\\n\");\n","/**\n * Type-safe utilities for MCP tool handlers\n */\n\nimport { z } from \"zod\";\nimport type { McpToolResponse } from \"./response-formatter.js\";\n\nexport const HEVY_CLIENT_NOT_INITIALIZED_ERROR =\n\t\"API client not initialized. Please provide HEVY_API_KEY.\";\n\n/**\n * Assert that the Hevy API client is initialized before running a tool.\n */\nexport function requireClient<TClient>(client: TClient | null): TClient {\n\tif (!client) {\n\t\tthrow new Error(HEVY_CLIENT_NOT_INITIALIZED_ERROR);\n\t}\n\n\treturn client;\n}\n\n/**\n * Infer TypeScript types from Zod schema objects\n *\n * @example\n * ```typescript\n * const schema = {\n * page: z.number(),\n * pageSize: z.number(),\n * } as const;\n *\n * type Params = InferToolParams<typeof schema>; // { page: number; pageSize: number }\n * ```\n */\nexport type InferToolParams<T extends Record<string, z.ZodTypeAny>> = z.infer<\n\tz.ZodObject<T>\n>;\n\n/**\n * Create a type-safe tool handler that validates and narrows args to inferred types\n *\n * This function wraps a handler with automatic Zod validation, ensuring runtime\n * type safety while maintaining compile-time type inference.\n *\n * @param schema - Zod schema object (e.g., { page: z.number(), ... })\n * @param handler - Handler function that receives validated, typed parameters\n * @returns A handler function that accepts Record<string, unknown> and validates it\n *\n * @example\n * ```typescript\n * const schema = {\n * page: z.coerce.number().int().gte(1).default(1),\n * pageSize: z.coerce.number().int().gte(1).lte(10).default(5),\n * } as const;\n *\n * const handler = createTypedToolHandler(schema, async (args) => {\n * // args is fully typed as { page: number; pageSize: number }\n * const { page, pageSize } = args;\n * // ...\n * });\n * ```\n */\nexport function createTypedToolHandler<T extends Record<string, z.ZodTypeAny>>(\n\tschema: T,\n\thandler: (args: InferToolParams<T>) => Promise<McpToolResponse>,\n): (args: Record<string, unknown>) => Promise<McpToolResponse> {\n\tconst zodSchema = z.object(schema);\n\treturn async (args: Record<string, unknown>) => {\n\t\tconst validated = zodSchema.parse(args);\n\t\treturn handler(validated);\n\t};\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { respond, type ResponseContract } from \"../utils/response-formatter.js\";\nimport {\n\tcreateTypedToolHandler,\n\ttype InferToolParams,\n} from \"../utils/tool-helpers.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\n\ntype ToolDefinitionBase<\n\tTSchema extends Record<string, z.ZodTypeAny>,\n\tTResult,\n> = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly inputSchema: TSchema;\n\treadonly annotations: ToolAnnotations;\n\treadonly responseContract: ResponseContract<TResult>;\n\texecute(\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<TSchema>,\n\t): Promise<TResult>;\n};\n\nexport type ToolDefinition<\n\tTSchema extends Record<string, z.ZodTypeAny>,\n\tTResult,\n> = ToolDefinitionBase<TSchema, TResult> &\n\t(\n\t\t| {\n\t\t\t\treadonly kind: \"read\";\n\t\t\t\treadonly outputSchema: z.ZodRawShape;\n\t\t }\n\t\t| {\n\t\t\t\treadonly kind: \"write\";\n\t\t\t\treadonly outputSchema?: never;\n\t\t }\n\t);\n\nexport function registerToolDefinition(\n\tserver: McpServer,\n\truntime: ToolRuntime,\n\tdefinition: ToolDefinition<Record<string, z.ZodTypeAny>, unknown>,\n): void {\n\tconst directHandler = createTypedToolHandler(\n\t\tdefinition.inputSchema,\n\t\tasync (args) =>\n\t\t\trespond(\n\t\t\t\tdefinition.responseContract,\n\t\t\t\tawait definition.execute(runtime, args),\n\t\t\t),\n\t);\n\tconst handler = runtime.wrapHandler(directHandler, definition.name);\n\tconst callback = (args: Record<string, unknown>) => handler(args);\n\n\tif (definition.kind === \"read\") {\n\t\tserver.registerTool(\n\t\t\tdefinition.name,\n\t\t\t{\n\t\t\t\tdescription: definition.description,\n\t\t\t\tinputSchema: definition.inputSchema,\n\t\t\t\toutputSchema: definition.outputSchema,\n\t\t\t\tannotations: definition.annotations,\n\t\t\t},\n\t\t\tcallback,\n\t\t);\n\t\treturn;\n\t}\n\n\tserver.tool(\n\t\tdefinition.name,\n\t\tdefinition.description,\n\t\tdefinition.inputSchema,\n\t\tdefinition.annotations,\n\t\tcallback,\n\t);\n}\n","/**\n * Shared MCP tool annotation factories.\n *\n * All hevy-mcp tools talk to the Hevy API, a closed, fully specified domain\n * limited to the authenticated user's own data, so openWorldHint is false\n * across the board.\n */\n\nimport type { ToolAnnotations } from \"@modelcontextprotocol/sdk/types.js\";\n\n/** Read-only tools (get-*, search-*): no side effects. */\nexport function readOnlyAnnotations(title: string): ToolAnnotations {\n\treturn { title, readOnlyHint: true, openWorldHint: false };\n}\n\n/** Create tools (create-*): additive writes, repeating creates duplicates. */\nexport function createAnnotations(title: string): ToolAnnotations {\n\treturn {\n\t\ttitle,\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: false,\n\t\topenWorldHint: false,\n\t};\n}\n\n/**\n * Update tools (update-*): PUT-style overwrites that replace prior data,\n * hence destructive; repeating the same call yields the same state.\n */\nexport function updateAnnotations(title: string): ToolAnnotations {\n\treturn {\n\t\ttitle,\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false,\n\t};\n}\n\n/** Delete tools (delete-*): destructive and idempotent. */\nexport function destructiveAnnotations(title: string): ToolAnnotations {\n\treturn {\n\t\ttitle,\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false,\n\t};\n}\n","interface ToolDescriptionParts {\n\tsummary: string;\n\taliases: readonly string[];\n\tuseCase: string;\n\timportantNotes: string;\n}\n\nexport function describeTool({\n\tsummary,\n\taliases,\n\tuseCase,\n\timportantNotes,\n}: ToolDescriptionParts): string {\n\treturn [\n\t\tsummary,\n\t\t`Aliases: ${aliases.join(\", \")}.`,\n\t\t`<use_case>${useCase}</use_case>`,\n\t\t`<important_notes>${importantNotes}</important_notes>`,\n\t].join(\" \");\n}\n","/**\n * Preprocessor to handle MCP clients that send JSON-stringified arrays\n * instead of native arrays for complex parameters.\n *\n * This is used with Zod's z.preprocess to handle cases where MCP clients\n * serialize complex nested structures as JSON strings.\n *\n * @param val - The value to potentially parse\n * @returns The parsed array if val is a valid JSON string, otherwise returns val unchanged\n */\nexport function parseJsonArray(val: unknown): unknown {\n\t// Handle case where MCP client sends JSON string instead of array\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(val);\n\t\t} catch {\n\t\t\t// Let Zod validation handle the error\n\t\t\treturn val;\n\t\t}\n\t}\n\treturn val;\n}\n","import { z } from \"zod\";\nimport type { BodyMeasurement } from \"../generated/client/types/index.js\";\nimport { parseJsonArray } from \"../utils/json-parser.js\";\nimport {\n\tsetTypeEnum,\n\tutcSecondTimestamp,\n\tzNullableInt,\n\tzNullableNumber,\n\tzOptionalRepRange,\n} from \"../utils/schemas.js\";\n\nexport interface PaginationShapeOptions {\n\tdefaultPageSize: number;\n\tmaxPageSize: number;\n\tintegerPage?: boolean;\n}\n\n/** Build the page and pageSize fields shared by paginated tools. */\nexport function paginationShape({\n\tdefaultPageSize,\n\tmaxPageSize,\n\tintegerPage = true,\n}: PaginationShapeOptions) {\n\tconst pageNumber = z.coerce.number().gte(1);\n\treturn {\n\t\tpage: integerPage ? pageNumber.int() : pageNumber,\n\t\tpageSize: z.coerce\n\t\t\t.number()\n\t\t\t.int()\n\t\t\t.gte(1)\n\t\t\t.lte(maxPageSize)\n\t\t\t.default(defaultPageSize),\n\t} as const;\n}\n\nexport const nonEmptyId = z.string().min(1);\n\nconst CALENDAR_DATE_MESSAGE = \"Date must be in YYYY-MM-DD format\";\nexport const calendarDate = z\n\t.string()\n\t.regex(/^\\d{4}-\\d{2}-\\d{2}$/, CALENDAR_DATE_MESSAGE)\n\t.refine((value) => {\n\t\tconst parsed = new Date(`${value}T00:00:00.000Z`);\n\t\treturn (\n\t\t\t!Number.isNaN(parsed.getTime()) && parsed.toISOString().startsWith(value)\n\t\t);\n\t}, CALENDAR_DATE_MESSAGE);\n\nexport const workoutSetShape = {\n\ttype: setTypeEnum,\n\tweight: z.coerce.number().optional().nullable(),\n\tweightKg: z.coerce.number().optional().nullable(),\n\treps: z.coerce.number().int().optional().nullable(),\n\tdistance: z.coerce.number().int().optional().nullable(),\n\tdistanceMeters: z.coerce.number().int().optional().nullable(),\n\tduration: z.coerce.number().int().optional().nullable(),\n\tdurationSeconds: z.coerce.number().int().optional().nullable(),\n\trpe: z.coerce.number().optional().nullable(),\n\tcustomMetric: z.coerce.number().optional().nullable(),\n} as const;\n\nexport const workoutExerciseShape = {\n\texerciseTemplateId: nonEmptyId,\n\tsupersetId: z.coerce.number().nullable().optional(),\n\tnotes: z.string().optional().nullable(),\n\tsets: z.array(z.object(workoutSetShape)),\n} as const;\n\nexport const workoutPayloadShape = {\n\ttitle: z.string().min(1),\n\tdescription: z.string().optional().nullable(),\n\tstartTime: utcSecondTimestamp,\n\tendTime: utcSecondTimestamp,\n\tisPrivate: z.boolean().default(false),\n\texercises: z.preprocess(\n\t\tparseJsonArray,\n\t\tz.array(z.object(workoutExerciseShape)),\n\t),\n} as const;\n\nexport const routineSetShape = {\n\ttype: setTypeEnum,\n\tweight: z.coerce.number().optional(),\n\tweightKg: z.coerce.number().optional(),\n\treps: zNullableInt,\n\tdistance: z.coerce.number().int().optional(),\n\tdistanceMeters: z.coerce.number().int().optional(),\n\tduration: z.coerce.number().int().optional(),\n\tdurationSeconds: z.coerce.number().int().optional(),\n\tcustomMetric: z.coerce.number().optional(),\n\trepRange: zOptionalRepRange,\n} as const;\n\nexport const routineExerciseShape = {\n\texerciseTemplateId: nonEmptyId,\n\tsupersetId: z.coerce.number().nullable().optional(),\n\trestSeconds: z.coerce.number().int().min(0).optional(),\n\tnotes: z.string().optional(),\n\tsets: z.array(z.object(routineSetShape)),\n} as const;\n\nexport const routinePayloadShape = {\n\ttitle: z.string().min(1),\n\tfolderId: z.coerce.number().nullable().optional(),\n\tnotes: z.string().optional(),\n\texercises: z.preprocess(\n\t\tparseJsonArray,\n\t\tz.array(z.object(routineExerciseShape)),\n\t),\n} as const;\n\nexport const bodyMeasurementFieldsSchema = {\n\tweightKg: zNullableNumber.describe(\"Body weight in kilograms\"),\n\tleanMassKg: zNullableNumber.describe(\"Lean body mass in kilograms\"),\n\tfatPercent: zNullableNumber.describe(\"Body fat percentage\"),\n\tneckCm: zNullableNumber.describe(\"Neck circumference in centimeters\"),\n\tshoulderCm: zNullableNumber.describe(\"Shoulder circumference in centimeters\"),\n\tchestCm: zNullableNumber.describe(\"Chest circumference in centimeters\"),\n\tleftBicepCm: zNullableNumber.describe(\n\t\t\"Left bicep circumference in centimeters\",\n\t),\n\trightBicepCm: zNullableNumber.describe(\n\t\t\"Right bicep circumference in centimeters\",\n\t),\n\tleftForearmCm: zNullableNumber.describe(\n\t\t\"Left forearm circumference in centimeters\",\n\t),\n\trightForearmCm: zNullableNumber.describe(\n\t\t\"Right forearm circumference in centimeters\",\n\t),\n\tabdomen: zNullableNumber.describe(\"Abdomen circumference in centimeters\"),\n\twaist: zNullableNumber.describe(\"Waist circumference in centimeters\"),\n\thips: zNullableNumber.describe(\"Hips circumference in centimeters\"),\n\tleftThigh: zNullableNumber.describe(\n\t\t\"Left thigh circumference in centimeters\",\n\t),\n\trightThigh: zNullableNumber.describe(\n\t\t\"Right thigh circumference in centimeters\",\n\t),\n\tleftCalf: zNullableNumber.describe(\"Left calf circumference in centimeters\"),\n\trightCalf: zNullableNumber.describe(\n\t\t\"Right calf circumference in centimeters\",\n\t),\n} as const;\n\nexport const measurementFieldToApiKey = {\n\tweightKg: \"weight_kg\",\n\tleanMassKg: \"lean_mass_kg\",\n\tfatPercent: \"fat_percent\",\n\tneckCm: \"neck_cm\",\n\tshoulderCm: \"shoulder_cm\",\n\tchestCm: \"chest_cm\",\n\tleftBicepCm: \"left_bicep_cm\",\n\trightBicepCm: \"right_bicep_cm\",\n\tleftForearmCm: \"left_forearm_cm\",\n\trightForearmCm: \"right_forearm_cm\",\n\tabdomen: \"abdomen\",\n\twaist: \"waist\",\n\thips: \"hips\",\n\tleftThigh: \"left_thigh\",\n\trightThigh: \"right_thigh\",\n\tleftCalf: \"left_calf\",\n\trightCalf: \"right_calf\",\n} as const satisfies Record<\n\tkeyof typeof bodyMeasurementFieldsSchema,\n\tkeyof Omit<BodyMeasurement, \"date\">\n>;\n\nexport type WorkoutSetInput = z.infer<z.ZodObject<typeof workoutSetShape>>;\nexport type WorkoutExerciseInput = z.infer<\n\tz.ZodObject<typeof workoutExerciseShape>\n>;\nexport type WorkoutPayloadInput = z.infer<\n\tz.ZodObject<typeof workoutPayloadShape>\n>;\nexport type RoutineSetInput = z.infer<z.ZodObject<typeof routineSetShape>>;\nexport type RoutineExerciseInput = z.infer<\n\tz.ZodObject<typeof routineExerciseShape>\n>;\nexport type RoutinePayloadInput = z.infer<\n\tz.ZodObject<typeof routinePayloadShape>\n>;\nexport type MeasurementFields = z.infer<\n\tz.ZodObject<typeof bodyMeasurementFieldsSchema>\n>;\n","import type {\n\tBodyMeasurement,\n\tPostRoutinesRequestBody,\n\tPostRoutinesRequestSet,\n\tPostRoutinesRequestSetTypeEnumKey,\n\tPostWorkoutsRequestBody,\n\tPostWorkoutsRequestSetRpeEnumKey,\n\tPostWorkoutsRequestSetTypeEnumKey,\n\tPutRoutinesRequestBody,\n\tPutRoutinesRequestSet,\n\tPutRoutinesRequestSetTypeEnumKey,\n} from \"../generated/client/types/index.js\";\nimport {\n\tmeasurementFieldToApiKey,\n\ttype MeasurementFields,\n\ttype RoutinePayloadInput,\n\ttype WorkoutPayloadInput,\n} from \"./input-schemas.js\";\n\nexport type WorkoutPayload = NonNullable<PostWorkoutsRequestBody[\"workout\"]>;\n\n/** Map the public camelCase workout input to the API's snake_case payload. */\nexport function buildWorkoutPayload(\n\tinput: WorkoutPayloadInput,\n): WorkoutPayload {\n\treturn {\n\t\ttitle: input.title,\n\t\tdescription: input.description ?? null,\n\t\tstart_time: input.startTime,\n\t\tend_time: input.endTime,\n\t\tis_private: input.isPrivate,\n\t\texercises: input.exercises.map((exercise) => ({\n\t\t\texercise_template_id: exercise.exerciseTemplateId,\n\t\t\tsuperset_id: exercise.supersetId ?? null,\n\t\t\tnotes: exercise.notes ?? null,\n\t\t\tsets: exercise.sets.map((set) => ({\n\t\t\t\ttype: set.type as PostWorkoutsRequestSetTypeEnumKey,\n\t\t\t\tweight_kg: set.weight ?? set.weightKg ?? null,\n\t\t\t\treps: set.reps ?? null,\n\t\t\t\tdistance_meters: set.distance ?? set.distanceMeters ?? null,\n\t\t\t\tduration_seconds: set.duration ?? set.durationSeconds ?? null,\n\t\t\t\trpe: (set.rpe as PostWorkoutsRequestSetRpeEnumKey | null) ?? null,\n\t\t\t\tcustom_metric: set.customMetric ?? null,\n\t\t\t})),\n\t\t})),\n\t};\n}\n\ntype RoutineRepRange = { start?: number; end?: number } | null;\n\nfunction buildRepRange(\n\trepRange: { start?: number | null; end?: number | null } | null | undefined,\n): RoutineRepRange {\n\tif (!repRange) {\n\t\treturn null;\n\t}\n\n\tconst start = repRange.start ?? undefined;\n\tconst end = repRange.end ?? undefined;\n\tif (start === undefined && end === undefined) {\n\t\treturn null;\n\t}\n\n\treturn { start, end };\n}\n\nfunction getFixedRepsFromRepRange(\n\trepRange: { start?: number | null; end?: number | null } | null | undefined,\n): number | null {\n\tif (!repRange) {\n\t\treturn null;\n\t}\n\tconst start = repRange.start ?? null;\n\tconst end = repRange.end ?? null;\n\tif (start === null || end === null || start !== end) {\n\t\treturn null;\n\t}\n\treturn start;\n}\n\nexport type RoutineCreatePayload = NonNullable<\n\tPostRoutinesRequestBody[\"routine\"]\n>;\nexport type RoutineUpdatePayload = NonNullable<\n\tPutRoutinesRequestBody[\"routine\"]\n>;\n\nexport type RoutinePayloadResult =\n\t| { payload: RoutineCreatePayload; usesRepRanges: boolean }\n\t| { payload: RoutineUpdatePayload; usesRepRanges: boolean };\n\nfunction buildRoutineSets(\n\tsets: RoutinePayloadInput[\"exercises\"][number][\"sets\"],\n\tmode: \"create\" | \"update\",\n): PostRoutinesRequestSet[] | PutRoutinesRequestSet[] {\n\treturn sets.map((set) => {\n\t\tconst repRange = buildRepRange(set.repRange);\n\t\tconst reps =\n\t\t\ttypeof set.reps === \"number\"\n\t\t\t\t? set.reps\n\t\t\t\t: getFixedRepsFromRepRange(repRange);\n\t\tconst common = {\n\t\t\tweight_kg: set.weight ?? set.weightKg ?? null,\n\t\t\treps: reps ?? null,\n\t\t\tdistance_meters: set.distance ?? set.distanceMeters ?? null,\n\t\t\tduration_seconds: set.duration ?? set.durationSeconds ?? null,\n\t\t\tcustom_metric: set.customMetric ?? null,\n\t\t};\n\n\t\tif (mode === \"create\") {\n\t\t\treturn {\n\t\t\t\t...common,\n\t\t\t\ttype: set.type as PostRoutinesRequestSetTypeEnumKey,\n\t\t\t\trep_range: repRange,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...common,\n\t\t\ttype: set.type as PutRoutinesRequestSetTypeEnumKey,\n\t\t\t...(repRange ? { rep_range: repRange } : {}),\n\t\t};\n\t});\n}\n\n/**\n * Build a routine wire payload. Create requests explicitly send null rep_range;\n * update requests omit it when no range is supplied.\n */\nexport function buildRoutinePayload(\n\tinput: RoutinePayloadInput,\n\tmode: \"create\",\n): { payload: RoutineCreatePayload; usesRepRanges: boolean };\nexport function buildRoutinePayload(\n\tinput: RoutinePayloadInput,\n\tmode: \"update\",\n): { payload: RoutineUpdatePayload; usesRepRanges: boolean };\nexport function buildRoutinePayload(\n\tinput: RoutinePayloadInput,\n\tmode: \"create\" | \"update\",\n): RoutinePayloadResult {\n\tlet usesRepRanges = false;\n\tconst exercises = input.exercises.map((exercise) => {\n\t\tconst sets = buildRoutineSets(exercise.sets, mode);\n\t\tif (\n\t\t\tsets.some(\n\t\t\t\t(set) =>\n\t\t\t\t\tset.rep_range != null &&\n\t\t\t\t\tgetFixedRepsFromRepRange(set.rep_range) === null,\n\t\t\t)\n\t\t) {\n\t\t\tusesRepRanges = true;\n\t\t}\n\t\treturn {\n\t\t\texercise_template_id: exercise.exerciseTemplateId,\n\t\t\tsuperset_id: exercise.supersetId ?? null,\n\t\t\trest_seconds: exercise.restSeconds ?? null,\n\t\t\tnotes: exercise.notes ?? null,\n\t\t\tsets,\n\t\t};\n\t});\n\n\tif (mode === \"create\") {\n\t\treturn {\n\t\t\tpayload: {\n\t\t\t\ttitle: input.title,\n\t\t\t\tfolder_id: input.folderId ?? null,\n\t\t\t\tnotes: input.notes ?? \"\",\n\t\t\t\texercises: exercises as RoutineCreatePayload[\"exercises\"],\n\t\t\t},\n\t\t\tusesRepRanges,\n\t\t};\n\t}\n\n\treturn {\n\t\tpayload: {\n\t\t\ttitle: input.title,\n\t\t\tnotes: input.notes ?? null,\n\t\t\texercises: exercises as RoutineUpdatePayload[\"exercises\"],\n\t\t},\n\t\tusesRepRanges,\n\t};\n}\n\nexport type MeasurementPayload = Omit<BodyMeasurement, \"date\">;\n\n/** Omit nullish measurement values because the API rejects explicit nulls. */\nexport function buildMeasurementPayload(\n\tfields: Partial<MeasurementFields>,\n): MeasurementPayload {\n\tconst payload: MeasurementPayload = {};\n\tfor (const [camelKey, apiKey] of Object.entries(measurementFieldToApiKey) as [\n\t\tkeyof MeasurementFields,\n\t\tkeyof MeasurementPayload,\n\t][]) {\n\t\tconst value = fields[camelKey];\n\t\tif (value != null) {\n\t\t\tpayload[apiKey] = value;\n\t\t}\n\t}\n\treturn payload;\n}\n","import type {\n\tGetV1BodyMeasurements200,\n\tGetV1BodyMeasurementsDate200,\n} from \"../generated/client/types/index.js\";\nimport {\n\tbodyMeasurementResponse,\n\tbodyMeasurementsResponse,\n\tcreateBodyMeasurementResponse,\n\tupdateBodyMeasurementResponse,\n} from \"../utils/response-formatter.js\";\nimport {\n\treadOnlyAnnotations,\n\tcreateAnnotations,\n\tupdateAnnotations,\n} from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\nimport {\n\tbodyMeasurementFieldsSchema,\n\tcalendarDate,\n\tpaginationShape,\n} from \"./input-schemas.js\";\nimport { buildMeasurementPayload } from \"./payload-mappers.js\";\n\nconst getBodyMeasurementsSchema = {\n\t...paginationShape({ defaultPageSize: 10, maxPageSize: 10 }),\n} as const;\n\nconst getBodyMeasurementSchema = {\n\tdate: calendarDate.describe(\"The date of the body measurement (YYYY-MM-DD)\"),\n} as const;\n\nconst createBodyMeasurementSchema = {\n\tdate: calendarDate.describe(\n\t\t\"The date of the body measurement (YYYY-MM-DD). Must be unique — returns 409 if an entry already exists for this date.\",\n\t),\n\t...bodyMeasurementFieldsSchema,\n} as const;\n\nconst updateBodyMeasurementSchema = {\n\tdate: calendarDate.describe(\n\t\t\"The date of the body measurement to update (YYYY-MM-DD). Must already exist — returns 404 otherwise.\",\n\t),\n\t...bodyMeasurementFieldsSchema,\n} as const;\n\nconst getBodyMeasurementsDefinition: ToolDefinition<\n\ttypeof getBodyMeasurementsSchema,\n\tGetV1BodyMeasurements200[\"body_measurements\"]\n> = {\n\tname: \"get-body-measurements\",\n\tdescription: describeTool({\n\t\tsummary: \"Read-only. Lists dated body measurements for the account.\",\n\t\taliases: [\"body stats history\", \"list weigh-ins\", \"measurement log\"],\n\t\tuseCase:\n\t\t\t\"Use to browse measurement history; use get-body-measurement for one exact date.\",\n\t\timportantNotes:\n\t\t\t\"Results are paginated; page starts at 1 and pageSize is limited to 10.\",\n\t}),\n\tinputSchema: getBodyMeasurementsSchema,\n\toutputSchema: bodyMeasurementsResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Body Measurements\"),\n\tkind: \"read\",\n\tresponseContract: bodyMeasurementsResponse,\n\texecute: async (runtime: ToolRuntime, args) => {\n\t\tconst { page, pageSize } = args;\n\t\tconst data: GetV1BodyMeasurements200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getBodyMeasurements({ page, pageSize });\n\t\treturn data?.body_measurements;\n\t},\n};\n\nconst getBodyMeasurementDefinition: ToolDefinition<\n\ttypeof getBodyMeasurementSchema,\n\t{\n\t\tbodyMeasurement: GetV1BodyMeasurementsDate200 | null | undefined;\n\t\tdate: string;\n\t}\n> = {\n\tname: \"get-body-measurement\",\n\tdescription: describeTool({\n\t\tsummary: \"Read-only. Retrieves the body measurement entry for one date.\",\n\t\taliases: [\"get weigh-in\", \"show body stats\", \"measurement by date\"],\n\t\tuseCase:\n\t\t\t\"Use when the exact measurement date is known; use get-body-measurements to browse dates.\",\n\t\timportantNotes:\n\t\t\t\"date must use YYYY-MM-DD; at most one entry exists per date.\",\n\t}),\n\tinputSchema: getBodyMeasurementSchema,\n\toutputSchema: bodyMeasurementResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Body Measurement\"),\n\tkind: \"read\",\n\tresponseContract: bodyMeasurementResponse,\n\texecute: async (runtime: ToolRuntime, args) => {\n\t\tconst { date } = args;\n\t\tconst data: GetV1BodyMeasurementsDate200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getBodyMeasurement(date);\n\t\treturn { bodyMeasurement: data, date };\n\t},\n};\n\nconst createBodyMeasurementDefinition: ToolDefinition<\n\ttypeof createBodyMeasurementSchema,\n\tstring\n> = {\n\tname: \"create-body-measurement\",\n\tdescription: describeTool({\n\t\tsummary: \"Writes to the Hevy account by creating a dated body measurement.\",\n\t\taliases: [\"log weigh-in\", \"add body stats\", \"record measurements\"],\n\t\tuseCase:\n\t\t\t\"Use for a date without an entry; use update-body-measurement when that date already exists.\",\n\t\timportantNotes:\n\t\t\t\"date must use YYYY-MM-DD and be unique. Null fields are omitted and cannot clear values; an existing date returns 409.\",\n\t}),\n\tinputSchema: createBodyMeasurementSchema,\n\tannotations: createAnnotations(\"Create Body Measurement\"),\n\tkind: \"write\",\n\tresponseContract: createBodyMeasurementResponse,\n\texecute: async (runtime: ToolRuntime, args) => {\n\t\tconst { date, ...fields } = args;\n\t\tawait runtime.getClient().createBodyMeasurement({\n\t\t\tdate,\n\t\t\t...buildMeasurementPayload(fields),\n\t\t});\n\t\treturn date;\n\t},\n};\n\nconst updateBodyMeasurementDefinition: ToolDefinition<\n\ttypeof updateBodyMeasurementSchema,\n\tstring\n> = {\n\tname: \"update-body-measurement\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Mutates the Hevy account by updating a body measurement for a date.\",\n\t\taliases: [\"edit weigh-in\", \"correct body stats\", \"change measurements\"],\n\t\tuseCase:\n\t\t\t\"Use to change fields on an existing date; use create-body-measurement for a new date.\",\n\t\timportantNotes:\n\t\t\t\"date must use YYYY-MM-DD and already exist. Provide at least one numeric field; nulls are omitted and cannot clear stored values.\",\n\t}),\n\tinputSchema: updateBodyMeasurementSchema,\n\tannotations: updateAnnotations(\"Update Body Measurement\"),\n\tkind: \"write\",\n\tresponseContract: updateBodyMeasurementResponse,\n\texecute: async (runtime: ToolRuntime, args) => {\n\t\tconst { date, ...fields } = args;\n\t\tconst payload = buildMeasurementPayload(fields);\n\t\tif (Object.keys(payload).length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t\"No measurement fields provided. Include at least one numeric measurement field (e.g. weightKg) to update.\",\n\t\t\t);\n\t\t}\n\t\tawait runtime.getClient().updateBodyMeasurement(date, payload);\n\t\treturn date;\n\t},\n};\n\nexport const bodyMeasurementToolDefinitions = [\n\tgetBodyMeasurementsDefinition,\n\tgetBodyMeasurementDefinition,\n\tcreateBodyMeasurementDefinition,\n\tupdateBodyMeasurementDefinition,\n] as const;\n","import { z } from \"zod\";\n// Import types from generated client\nimport type {\n\tGetV1RoutineFolders200,\n\tGetV1RoutineFoldersFolderid200,\n\tPostV1RoutineFolders201,\n\tRoutineFolder,\n} from \"../generated/client/types/index.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\nimport {\n\tcreateRoutineFolderResponse,\n\troutineFolderResponse,\n\troutineFoldersResponse,\n} from \"../utils/response-formatter.js\";\nimport {\n\tcreateAnnotations,\n\treadOnlyAnnotations,\n} from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport type { InferToolParams } from \"../utils/tool-helpers.js\";\nimport { nonEmptyId, paginationShape } from \"./input-schemas.js\";\n\nconst getRoutineFoldersSchema = paginationShape({\n\tdefaultPageSize: 5,\n\tmaxPageSize: 10,\n});\ntype GetRoutineFoldersParams = InferToolParams<typeof getRoutineFoldersSchema>;\n\nconst getRoutineFolderSchema = { folderId: nonEmptyId } as const;\ntype GetRoutineFolderParams = InferToolParams<typeof getRoutineFolderSchema>;\n\nconst createRoutineFolderSchema = {\n\tname: z.string().min(1),\n} as const;\ntype CreateRoutineFolderParams = InferToolParams<\n\ttypeof createRoutineFolderSchema\n>;\n\nconst getRoutineFoldersDefinition = {\n\tname: \"get-routine-folders\",\n\tdescription: describeTool({\n\t\tsummary: \"Read-only. Lists default and custom routine folders.\",\n\t\taliases: [\"list folders\", \"browse routine groups\", \"show plan folders\"],\n\t\tuseCase:\n\t\t\t\"Use to browse folder organization or discover folder IDs for routine creation.\",\n\t\timportantNotes:\n\t\t\t\"Results are paginated; page starts at 1 and pageSize is limited to 10.\",\n\t}),\n\tinputSchema: getRoutineFoldersSchema,\n\toutputSchema: routineFoldersResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Routine Folders\"),\n\tkind: \"read\" as const,\n\tresponseContract: routineFoldersResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: GetRoutineFoldersParams,\n\t): Promise<RoutineFolder[] | undefined> => {\n\t\tconst { page, pageSize } = args;\n\t\tconst data: GetV1RoutineFolders200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getRoutineFolders({\n\t\t\t\tpage,\n\t\t\t\tpageSize,\n\t\t\t});\n\n\t\treturn data?.routine_folders;\n\t},\n} satisfies ToolDefinition<\n\ttypeof getRoutineFoldersSchema,\n\tRoutineFolder[] | undefined\n>;\n\nconst getRoutineFolderDefinition = {\n\tname: \"get-routine-folder\",\n\tdescription: describeTool({\n\t\tsummary: \"Read-only. Retrieves one routine folder's metadata by ID.\",\n\t\taliases: [\"show folder\", \"folder details\", \"routine folder metadata\"],\n\t\tuseCase:\n\t\t\t\"Use for one known folder; use get-routine-folders to browse or discover folder IDs.\",\n\t\timportantNotes:\n\t\t\t\"Requires a folderId from get-routine-folders or a prior create response.\",\n\t}),\n\tinputSchema: getRoutineFolderSchema,\n\toutputSchema: routineFolderResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Routine Folder\"),\n\tkind: \"read\" as const,\n\tresponseContract: routineFolderResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: GetRoutineFolderParams,\n\t): Promise<{\n\t\troutineFolder: GetV1RoutineFoldersFolderid200 | null | undefined;\n\t\tfolderId: string;\n\t}> => {\n\t\tconst { folderId } = args;\n\t\tconst data: GetV1RoutineFoldersFolderid200 | null = await runtime\n\t\t\t.getClient()\n\t\t\t.getRoutineFolder(folderId);\n\n\t\treturn {\n\t\t\troutineFolder: data,\n\t\t\tfolderId,\n\t\t};\n\t},\n} satisfies ToolDefinition<\n\ttypeof getRoutineFolderSchema,\n\t{\n\t\troutineFolder: GetV1RoutineFoldersFolderid200 | null | undefined;\n\t\tfolderId: string;\n\t}\n>;\n\nconst createRoutineFolderDefinition = {\n\tname: \"create-routine-folder\",\n\tdescription: describeTool({\n\t\tsummary: \"Writes to the Hevy account by creating a new routine folder.\",\n\t\taliases: [\"add folder\", \"organize routines\", \"create plan group\"],\n\t\tuseCase:\n\t\t\t\"Use to create an organizational destination before assigning new routines to a folderId.\",\n\t\timportantNotes:\n\t\t\t\"Requires a non-empty name. Retrying or reusing a name can create duplicate folders.\",\n\t}),\n\tinputSchema: createRoutineFolderSchema,\n\tannotations: createAnnotations(\"Create Routine Folder\"),\n\tkind: \"write\" as const,\n\tresponseContract: createRoutineFolderResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: CreateRoutineFolderParams,\n\t): Promise<PostV1RoutineFolders201 | null | undefined> => {\n\t\tconst { name } = args;\n\t\treturn runtime.getClient().createRoutineFolder({\n\t\t\troutine_folder: {\n\t\t\t\ttitle: name,\n\t\t\t},\n\t\t});\n\t},\n} satisfies ToolDefinition<\n\ttypeof createRoutineFolderSchema,\n\tPostV1RoutineFolders201 | null | undefined\n>;\n\nexport const folderToolDefinitions = [\n\tgetRoutineFoldersDefinition,\n\tgetRoutineFolderDefinition,\n\tcreateRoutineFolderDefinition,\n] as const;\n","import { z } from \"zod\";\nimport type {\n\tGetV1Routines200,\n\tGetV1RoutinesRoutineid200,\n\tPostV1Routines201,\n\tPutV1RoutinesRoutineid200,\n} from \"../generated/client/types/index.js\";\nimport { parseJsonArray } from \"../utils/json-parser.js\";\nimport {\n\tcreateRoutineResponse,\n\troutineResponse,\n\troutinesResponse,\n\tupdateRoutineResponse,\n} from \"../utils/response-formatter.js\";\nimport {\n\tcreateAnnotations,\n\treadOnlyAnnotations,\n\tupdateAnnotations,\n} from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport {\n\tnonEmptyId,\n\tpaginationShape,\n\troutineExerciseShape,\n\troutinePayloadShape,\n} from \"./input-schemas.js\";\nimport { buildRoutinePayload } from \"./payload-mappers.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\n\nconst getRoutinesSchema = paginationShape({\n\tdefaultPageSize: 5,\n\tmaxPageSize: 10,\n});\n\ntype GetRoutinesResult = GetV1Routines200[\"routines\"];\nconst getRoutinesDefinition: ToolDefinition<\n\ttypeof getRoutinesSchema,\n\tGetRoutinesResult\n> = {\n\tname: \"get-routines\",\n\tdescription: describeTool({\n\t\tsummary: \"Read-only. Lists custom and default workout routines.\",\n\t\taliases: [\"list routines\", \"show workout plans\", \"browse saved routines\"],\n\t\tuseCase:\n\t\t\t\"Use to browse routines or discover a routine ID; use get-routine for one known routine.\",\n\t\timportantNotes:\n\t\t\t\"Results are paginated; page starts at 1 and pageSize is limited to 10.\",\n\t}),\n\tinputSchema: getRoutinesSchema,\n\tkind: \"read\",\n\toutputSchema: routinesResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Routines\"),\n\tresponseContract: routinesResponse,\n\texecute: async (runtime, { page, pageSize }) => {\n\t\tconst data: GetV1Routines200 = await runtime.getClient().getRoutines({\n\t\t\tpage,\n\t\t\tpageSize,\n\t\t});\n\t\treturn data?.routines;\n\t},\n};\n\nconst getRoutineSchema = { routineId: nonEmptyId } as const;\n\ntype GetRoutineResult = {\n\troutine: GetV1RoutinesRoutineid200[\"routine\"] | null;\n\troutineId: string;\n};\nconst getRoutineDefinition: ToolDefinition<\n\ttypeof getRoutineSchema,\n\tGetRoutineResult\n> = {\n\tname: \"get-routine\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only. Retrieves one routine and its exercise configuration by ID.\",\n\t\taliases: [\"show routine\", \"fetch workout plan\", \"routine details\"],\n\t\tuseCase:\n\t\t\t\"Use when the routineId is known; use get-routines to browse or discover IDs.\",\n\t\timportantNotes:\n\t\t\t\"Requires a routineId from get-routines or a prior create response.\",\n\t}),\n\tinputSchema: getRoutineSchema,\n\tkind: \"read\",\n\toutputSchema: routineResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Routine\"),\n\tresponseContract: routineResponse,\n\texecute: async (runtime, { routineId }) => {\n\t\tconst data: GetV1RoutinesRoutineid200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getRoutineById(String(routineId));\n\t\treturn { routine: data?.routine, routineId };\n\t},\n};\n\nconst routineExercisesSchema = z.preprocess(\n\tparseJsonArray,\n\tz.array(z.object(routineExerciseShape)),\n);\n\nconst createRoutineSchema = routinePayloadShape;\n\ntype CreateRoutineResult = {\n\troutine: PostV1Routines201 | null | undefined;\n\tusesRepRanges: boolean;\n};\nconst createRoutineDefinition: ToolDefinition<\n\ttypeof createRoutineSchema,\n\tCreateRoutineResult\n> = {\n\tname: \"create-routine\",\n\tdescription: describeTool({\n\t\tsummary: \"Writes to the Hevy account by creating a new workout routine.\",\n\t\taliases: [\"add routine\", \"build workout plan\", \"save training template\"],\n\t\tuseCase:\n\t\t\t\"Use to create a reusable plan; use create-workout to log a completed session.\",\n\t\timportantNotes:\n\t\t\t\"Requires exercise template IDs; folderId is optional. Retrying can create duplicates, and non-fixed rep ranges may not display in Hevy apps.\",\n\t}),\n\tinputSchema: createRoutineSchema,\n\tkind: \"write\",\n\tannotations: createAnnotations(\"Create Routine\"),\n\tresponseContract: createRoutineResponse,\n\texecute: async (runtime, args) => {\n\t\tconst { payload, usesRepRanges } = buildRoutinePayload(args, \"create\");\n\t\tconst data: PostV1Routines201 = await runtime\n\t\t\t.getClient()\n\t\t\t.createRoutine({ routine: payload });\n\t\treturn { routine: data, usesRepRanges };\n\t},\n};\n\nconst updateRoutineSchema = {\n\troutineId: nonEmptyId,\n\ttitle: z.string().min(1),\n\tnotes: z.string().optional(),\n\texercises: routineExercisesSchema,\n} as const;\n\ntype UpdateRoutineResult = {\n\troutine: PutV1RoutinesRoutineid200 | null | undefined;\n\troutineId: string;\n\tusesRepRanges: boolean;\n};\nconst updateRoutineDefinition: ToolDefinition<\n\ttypeof updateRoutineSchema,\n\tUpdateRoutineResult\n> = {\n\tname: \"update-routine\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Mutates the Hevy account by replacing an existing routine's content.\",\n\t\taliases: [\n\t\t\t\"edit routine\",\n\t\t\t\"revise workout plan\",\n\t\t\t\"replace routine exercises\",\n\t\t],\n\t\tuseCase:\n\t\t\t\"Use to change a known routine; use create-routine for a separate new plan.\",\n\t\timportantNotes:\n\t\t\t\"Requires routineId and the complete title and exercises payload; omitted exercises are removed. Non-fixed rep ranges may not display in Hevy apps.\",\n\t}),\n\tinputSchema: updateRoutineSchema,\n\tkind: \"write\",\n\tannotations: updateAnnotations(\"Update Routine\"),\n\tresponseContract: updateRoutineResponse,\n\texecute: async (runtime, args) => {\n\t\tconst { routineId } = args;\n\t\tconst { payload, usesRepRanges } = buildRoutinePayload(args, \"update\");\n\t\tconst data: PutV1RoutinesRoutineid200 = await runtime\n\t\t\t.getClient()\n\t\t\t.updateRoutine(routineId, { routine: payload });\n\t\treturn { routine: data, routineId, usesRepRanges };\n\t},\n};\n\nexport const routineToolDefinitions = [\n\tgetRoutinesDefinition,\n\tgetRoutineDefinition,\n\tcreateRoutineDefinition,\n\tupdateRoutineDefinition,\n] as const;\n","import { z } from \"zod\";\n// Import types from generated client\nimport type {\n\tGetV1ExerciseHistoryExercisetemplateid200,\n\tGetV1ExerciseTemplates200,\n\tGetV1ExerciseTemplatesExercisetemplateid200,\n\tPostV1ExerciseTemplates200,\n} from \"../generated/client/types/index.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\nimport {\n\tcreateExerciseTemplateResponse,\n\texerciseHistoryResponse,\n\texerciseTemplateResponse,\n\texerciseTemplatesResponse,\n\tsearchExerciseTemplatesResponse,\n} from \"../utils/response-formatter.js\";\nimport { createSafeErrorDiagnostic } from \"../utils/safe-error-diagnostic.js\";\nimport {\n\tcreateAnnotations,\n\treadOnlyAnnotations,\n} from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport { type InferToolParams } from \"../utils/tool-helpers.js\";\nimport { nonEmptyId, paginationShape } from \"./input-schemas.js\";\nimport {\n\tequipmentCategoryEnum,\n\texerciseTypeEnum,\n\tmuscleGroupEnum,\n} from \"../utils/schemas.js\";\n\nconst getExerciseTemplatesSchema = paginationShape({\n\tdefaultPageSize: 5,\n\tmaxPageSize: 100,\n});\n\nconst getExerciseTemplateSchema = {\n\texerciseTemplateId: nonEmptyId,\n} as const;\n\nconst getExerciseHistorySchema = {\n\texerciseTemplateId: nonEmptyId,\n\tstartDate: z\n\t\t.string()\n\t\t.datetime({ offset: true })\n\t\t.describe(\"ISO 8601 start date for filtering history\")\n\t\t.optional(),\n\tendDate: z\n\t\t.string()\n\t\t.datetime({ offset: true })\n\t\t.describe(\"ISO 8601 end date for filtering history\")\n\t\t.optional(),\n} as const;\n\nconst createExerciseTemplateSchema = {\n\ttitle: z.string().min(1),\n\texerciseType: exerciseTypeEnum,\n\tequipmentCategory: equipmentCategoryEnum,\n\tmuscleGroup: muscleGroupEnum,\n\totherMuscles: z.array(muscleGroupEnum).default([]),\n} as const;\n\nconst searchExerciseTemplatesSchema = {\n\tquery: z\n\t\t.string()\n\t\t.min(1)\n\t\t.describe(\n\t\t\t\"Case-insensitive substring to match against exercise template titles\",\n\t\t),\n\tprimaryMuscleGroup: muscleGroupEnum\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Optional filter to restrict results to a specific primary muscle group\",\n\t\t),\n\trefresh: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.default(false)\n\t\t.describe(\n\t\t\t\"Set to true to invalidate the catalog cache and re-fetch all templates from the API\",\n\t\t),\n} as const;\n\nconst getExerciseTemplatesDefinition = {\n\tname: \"get-exercise-templates\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only. Lists default and custom exercise templates with equipment and muscle metadata.\",\n\t\taliases: [\"browse exercises\", \"list exercise catalog\", \"show movements\"],\n\t\tuseCase:\n\t\t\t\"Use for page-by-page catalog browsing; use search-exercise-templates for a name lookup across the full catalog.\",\n\t\timportantNotes:\n\t\t\t\"Results are paginated; page starts at 1 and pageSize is limited to 100.\",\n\t}),\n\tinputSchema: getExerciseTemplatesSchema,\n\toutputSchema: exerciseTemplatesResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Exercise Templates\"),\n\tkind: \"read\" as const,\n\tresponseContract: exerciseTemplatesResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<typeof getExerciseTemplatesSchema>,\n\t) => {\n\t\tconst { page, pageSize } = args;\n\t\tconst data: GetV1ExerciseTemplates200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getExerciseTemplates({\n\t\t\t\tpage,\n\t\t\t\tpageSize,\n\t\t\t});\n\t\treturn data?.exercise_templates;\n\t},\n};\n\nconst getExerciseTemplateDefinition = {\n\tname: \"get-exercise-template\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only. Retrieves complete metadata for one exercise template by ID.\",\n\t\taliases: [\n\t\t\t\"show exercise details\",\n\t\t\t\"fetch movement\",\n\t\t\t\"exercise template info\",\n\t\t],\n\t\tuseCase:\n\t\t\t\"Use after locating an exact template; use search-exercise-templates when only a name is known.\",\n\t\timportantNotes:\n\t\t\t\"Requires an exerciseTemplateId from a template list, search, routine, or workout.\",\n\t}),\n\tinputSchema: getExerciseTemplateSchema,\n\toutputSchema: exerciseTemplateResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Exercise Template\"),\n\tkind: \"read\" as const,\n\tresponseContract: exerciseTemplateResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<typeof getExerciseTemplateSchema>,\n\t) => {\n\t\tconst { exerciseTemplateId } = args;\n\t\tconst data: GetV1ExerciseTemplatesExercisetemplateid200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getExerciseTemplate(exerciseTemplateId);\n\t\treturn {\n\t\t\texerciseTemplate: data,\n\t\t\texerciseTemplateId,\n\t\t};\n\t},\n};\n\nconst getExerciseHistoryDefinition = {\n\tname: \"get-exercise-history\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only. Retrieves past performed sets for one exercise template.\",\n\t\taliases: [\"exercise progress\", \"past sets\", \"movement history\"],\n\t\tuseCase:\n\t\t\t\"Use to analyze performance for one movement; use get-workouts for complete sessions.\",\n\t\timportantNotes:\n\t\t\t\"Requires an exerciseTemplateId. Optional startDate and endDate must be ISO 8601 datetimes with an offset.\",\n\t}),\n\tinputSchema: getExerciseHistorySchema,\n\toutputSchema: exerciseHistoryResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get Exercise History\"),\n\tkind: \"read\" as const,\n\tresponseContract: exerciseHistoryResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<typeof getExerciseHistorySchema>,\n\t) => {\n\t\tconst { exerciseTemplateId, startDate, endDate } = args;\n\t\tconst data: GetV1ExerciseHistoryExercisetemplateid200 = await runtime\n\t\t\t.getClient()\n\t\t\t.getExerciseHistory(exerciseTemplateId, {\n\t\t\t\t...(startDate ? { start_date: startDate } : {}),\n\t\t\t\t...(endDate ? { end_date: endDate } : {}),\n\t\t\t});\n\t\treturn {\n\t\t\thistory: data?.exercise_history,\n\t\t\texerciseTemplateId,\n\t\t};\n\t},\n};\n\nconst createExerciseTemplateDefinition = {\n\tname: \"create-exercise-template\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Writes to the Hevy account by creating a custom exercise template.\",\n\t\taliases: [\"add custom exercise\", \"create movement\", \"define exercise\"],\n\t\tuseCase:\n\t\t\t\"Use only when the needed movement is absent; search-exercise-templates should check existing templates first.\",\n\t\timportantNotes:\n\t\t\t\"Requires title, exercise type, equipment category, and primary muscle group. Retrying or reusing a title can create duplicates.\",\n\t}),\n\tinputSchema: createExerciseTemplateSchema,\n\tannotations: createAnnotations(\"Create Exercise Template\"),\n\tkind: \"write\" as const,\n\tresponseContract: createExerciseTemplateResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<typeof createExerciseTemplateSchema>,\n\t) => {\n\t\tconst {\n\t\t\ttitle,\n\t\t\texerciseType,\n\t\t\tequipmentCategory,\n\t\t\tmuscleGroup,\n\t\t\totherMuscles,\n\t\t} = args;\n\t\tconst response: PostV1ExerciseTemplates200 = await runtime\n\t\t\t.getClient()\n\t\t\t.createExerciseTemplate({\n\t\t\t\texercise: {\n\t\t\t\t\ttitle,\n\t\t\t\t\texercise_type: exerciseType,\n\t\t\t\t\tequipment_category: equipmentCategory,\n\t\t\t\t\tmuscle_group: muscleGroup,\n\t\t\t\t\tother_muscles: otherMuscles,\n\t\t\t\t},\n\t\t\t});\n\t\treturn response;\n\t},\n};\n\nconst searchExerciseTemplatesDefinition = {\n\tname: \"search-exercise-templates\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only for the Hevy account. Searches the full exercise template catalog by title substring.\",\n\t\taliases: [\"find exercise\", \"look up movement\", \"search exercise IDs\"],\n\t\tuseCase:\n\t\t\t\"Use when a name or partial name is known, especially to discover IDs for workouts and routines; use get-exercise-templates for page browsing.\",\n\t\timportantNotes:\n\t\t\t\"Matching is case-insensitive. The catalog is cached locally for 5 minutes; refresh:true re-fetches all pages and changes only local cache state.\",\n\t}),\n\tinputSchema: searchExerciseTemplatesSchema,\n\toutputSchema: searchExerciseTemplatesResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Search Exercise Templates\"),\n\tkind: \"read\" as const,\n\tresponseContract: searchExerciseTemplatesResponse,\n\texecute: async (\n\t\truntime: ToolRuntime,\n\t\targs: InferToolParams<typeof searchExerciseTemplatesSchema>,\n\t) => {\n\t\tconst _client = runtime.getClient();\n\t\tconst { query, primaryMuscleGroup, refresh } = args;\n\t\tconst templates = await runtime.catalog.get({\n\t\t\trefresh,\n\t\t\tonRefreshed: (refreshedCatalog, reason) => {\n\t\t\t\ttry {\n\t\t\t\t\truntime.logger?.({\n\t\t\t\t\t\tlevel: \"info\",\n\t\t\t\t\t\tlogger: \"hevy-cache\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\tmessage: \"Exercise template catalog refreshed\",\n\t\t\t\t\t\t\tcount: refreshedCatalog.length,\n\t\t\t\t\t\t\treason,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\"Failed to emit structured exercise template cache log\",\n\t\t\t\t\t\tcreateSafeErrorDiagnostic(error),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\n\t\tconst queryLower = query.toLowerCase();\n\t\tlet results = templates.filter((t) =>\n\t\t\t(t.title ?? \"\").toLowerCase().includes(queryLower),\n\t\t);\n\t\tif (primaryMuscleGroup !== undefined) {\n\t\t\tresults = results.filter(\n\t\t\t\t(t) => t.primary_muscle_group === primaryMuscleGroup,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tresults,\n\t\t\tquery,\n\t\t\tprimaryMuscleGroup,\n\t\t};\n\t},\n};\n\n/** Ordered exercise-template tools for composition by the shared server. */\nexport const templateToolDefinitions = [\n\tgetExerciseTemplatesDefinition,\n\tgetExerciseTemplateDefinition,\n\tgetExerciseHistoryDefinition,\n\tcreateExerciseTemplateDefinition,\n\tsearchExerciseTemplatesDefinition,\n] as const;\n","import type { UserInfoResponse } from \"../generated/client/types/index.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\nimport { userResponse } from \"../utils/response-formatter.js\";\nimport { readOnlyAnnotations } from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\n\nconst getUserInfoSchema = {} as const;\n\nconst getUserInfoDefinition: ToolDefinition<\n\ttypeof getUserInfoSchema,\n\tUserInfoResponse[\"data\"]\n> = {\n\tname: \"get-user-info\",\n\tdescription: describeTool({\n\t\tsummary:\n\t\t\t\"Read-only. Returns the authenticated account's user ID, display name, and public profile URL.\",\n\t\taliases: [\"who am I\", \"account info\", \"verify Hevy user\"],\n\t\tuseCase:\n\t\t\t\"Use to confirm which Hevy account is connected before reading or writing account data.\",\n\t\timportantNotes:\n\t\t\t\"Accepts no inputs and reports only the account associated with the configured credentials.\",\n\t}),\n\tinputSchema: getUserInfoSchema,\n\tkind: \"read\",\n\toutputSchema: userResponse.outputSchema,\n\tannotations: readOnlyAnnotations(\"Get User Info\"),\n\tresponseContract: userResponse,\n\texecute: async (runtime: ToolRuntime) => {\n\t\tconst data: UserInfoResponse = await runtime.getClient().getUserInfo();\n\t\treturn data?.data;\n\t},\n};\n\nexport const userToolDefinitions = [getUserInfoDefinition] as const;\n","import { z } from \"zod\";\nimport type {\n\tGetV1Routines200,\n\tRoutine,\n} from \"../generated/client/types/index.js\";\nimport {\n\tcompactRoutinesResponse,\n\ttype CompactRoutinesResult,\n} from \"../utils/response-formatter.js\";\nimport { readOnlyAnnotations } from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport type { InferToolParams } from \"../utils/tool-helpers.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\n\nconst routineDiscoverySchema = {\n\tquery: z\n\t\t.string()\n\t\t.min(1)\n\t\t.optional()\n\t\t.describe(\"Optional case-insensitive substring to match routine titles.\"),\n\tlimit: z.coerce\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(100)\n\t\t.default(20)\n\t\t.describe(\"Maximum compact routines to return (1-100).\"),\n} as const;\n\ntype RoutineDiscoveryParams = InferToolParams<typeof routineDiscoverySchema>;\n\nasync function discoverRoutines(\n\truntime: ToolRuntime,\n\t{ query, limit }: RoutineDiscoveryParams,\n): Promise<CompactRoutinesResult> {\n\tconst normalizedQuery = query?.toLocaleLowerCase();\n\tconst routines: Routine[] = [];\n\tlet page = 1;\n\tlet pages = 0;\n\tlet itemsScanned = 0;\n\tconst client = runtime.getClient();\n\n\twhile (routines.length < limit) {\n\t\tconst data: GetV1Routines200 = await client.getRoutines({\n\t\t\tpage,\n\t\t\tpageSize: 10,\n\t\t});\n\t\tpages = page;\n\t\tconst pageItems = data?.routines ?? [];\n\t\titemsScanned += pageItems.length;\n\t\tfor (const routine of pageItems) {\n\t\t\tif (\n\t\t\t\tnormalizedQuery &&\n\t\t\t\t!routine.title?.toLocaleLowerCase().includes(normalizedQuery)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\troutines.push(routine);\n\t\t\tif (routines.length >= limit) break;\n\t\t}\n\n\t\tconst pageCount = data?.page_count;\n\t\tif (\n\t\t\ttypeof pageCount !== \"number\" ||\n\t\t\t!Number.isSafeInteger(pageCount) ||\n\t\t\tpageCount <= page\n\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tpage += 1;\n\t}\n\n\treturn {\n\t\troutines: routines.slice(0, limit).map((routine) => ({\n\t\t\t...(routine.id ? { id: routine.id } : {}),\n\t\t\t...(routine.title ? { title: routine.title } : {}),\n\t\t\tfolderId: routine.folder_id ?? null,\n\t\t\t...(routine.updated_at ? { updatedAt: routine.updated_at } : {}),\n\t\t\texerciseCount: routine.exercises?.length ?? 0,\n\t\t\tsetCount:\n\t\t\t\troutine.exercises?.reduce(\n\t\t\t\t\t(total, exercise) => total + (exercise.sets?.length ?? 0),\n\t\t\t\t\t0,\n\t\t\t\t) ?? 0,\n\t\t})),\n\t\tworkflow: {\n\t\t\tname: \"routine-discovery\",\n\t\t\tpagination: { routines: pages },\n\t\t\tcacheStatus: \"not-used\",\n\t\t\titemsScanned,\n\t\t},\n\t};\n}\n\nexport const routineDiscoveryToolDefinitions = [\n\t{\n\t\tname: \"search-routines\",\n\t\tdescription: describeTool({\n\t\t\tsummary:\n\t\t\t\t\"Read-only. Discovers routines by title and returns compact metadata without full set payloads.\",\n\t\t\taliases: [\"find routine\", \"browse routine names\", \"compact routine list\"],\n\t\t\tuseCase:\n\t\t\t\t\"Use to find a routine ID or shortlist plans before calling get-routine for full exercise details.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Search scans routine pages at pageSize 10 and returns only IDs, titles, folder metadata, and exercise/set counts.\",\n\t\t}),\n\t\tinputSchema: routineDiscoverySchema,\n\t\toutputSchema: compactRoutinesResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Search Routines\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: compactRoutinesResponse,\n\t\texecute: async (runtime: ToolRuntime, args: RoutineDiscoveryParams) =>\n\t\t\tdiscoverRoutines(runtime, args),\n\t},\n] satisfies readonly ToolDefinition<Record<string, z.ZodTypeAny>, unknown>[];\n\nexport { discoverRoutines };\n","import { z } from \"zod\";\nimport type {\n\tBodyMeasurement,\n\tGetV1BodyMeasurements200,\n\tGetV1Workouts200,\n\tWorkout,\n} from \"../generated/client/types/index.js\";\nimport {\n\ttrainingSummaryResponse,\n\ttype TrainingSummaryResult,\n} from \"../utils/response-formatter.js\";\nimport { readOnlyAnnotations } from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport type { InferToolParams } from \"../utils/tool-helpers.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\n\nconst trainingSummarySchema = {\n\tweeks: z.coerce\n\t\t.number()\n\t\t.int()\n\t\t.min(1)\n\t\t.max(12)\n\t\t.default(4)\n\t\t.describe(\"Number of recent weeks to summarize (1-12).\"),\n} as const;\n\ntype TrainingSummaryParams = InferToolParams<typeof trainingSummarySchema>;\n\ntype RecentPageResult<T> = {\n\titems: readonly T[];\n\tpages: number;\n\titemsScanned: number;\n};\n\nconst MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction parseUtcDate(value: string): number | undefined {\n\tconst normalized = value.length === 10 ? `${value}T00:00:00.000Z` : value;\n\tconst timestamp = Date.parse(normalized);\n\treturn Number.isFinite(timestamp) ? timestamp : undefined;\n}\n\nasync function fetchRecentPages<T>(\n\tloader: (\n\t\tpage: number,\n\t\tpageSize: number,\n\t) => Promise<{ items: readonly T[]; pageCount?: number }>,\n\tpageSize: number,\n\tstartDate: string,\n\tendDate: string,\n\tgetDate: (item: T) => string | undefined,\n): Promise<RecentPageResult<T>> {\n\tconst items: T[] = [];\n\tlet page = 1;\n\tlet itemsScanned = 0;\n\tconst startTimestamp = parseUtcDate(startDate);\n\tconst endTimestamp = parseUtcDate(endDate);\n\tif (startTimestamp === undefined || endTimestamp === undefined) {\n\t\treturn { items, pages: 0, itemsScanned };\n\t}\n\tconst endExclusiveTimestamp = endTimestamp + MILLISECONDS_PER_DAY;\n\n\twhile (true) {\n\t\tconst result = await loader(page, pageSize);\n\t\titemsScanned += result.items.length;\n\t\tif (result.items.length === 0) break;\n\t\tfor (const item of result.items) {\n\t\t\tconst date = getDate(item);\n\t\t\tconst timestamp = date === undefined ? undefined : parseUtcDate(date);\n\t\t\tif (\n\t\t\t\ttimestamp !== undefined &&\n\t\t\t\ttimestamp >= startTimestamp &&\n\t\t\t\ttimestamp < endExclusiveTimestamp\n\t\t\t) {\n\t\t\t\titems.push(item);\n\t\t\t}\n\t\t}\n\n\t\tconst lastDate = result.items\n\t\t\t.map(getDate)\n\t\t\t.filter((date): date is string => date !== undefined)\n\t\t\t.at(-1);\n\t\tconst lastTimestamp =\n\t\t\tlastDate === undefined ? undefined : parseUtcDate(lastDate);\n\t\tif (lastTimestamp !== undefined && lastTimestamp < startTimestamp) {\n\t\t\tbreak;\n\t\t}\n\t\tconst pageCount = result.pageCount;\n\t\tif (\n\t\t\ttypeof pageCount !== \"number\" ||\n\t\t\t!Number.isSafeInteger(pageCount) ||\n\t\t\tpageCount <= page\n\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tpage += 1;\n\t}\n\treturn { items, pages: page, itemsScanned };\n}\n\nfunction utcDateString(date: Date): string {\n\treturn date.toISOString().slice(0, 10);\n}\n\nfunction getPeriod(weeks: number): {\n\tstartDate: string;\n\tendDate: string;\n} {\n\tconst end = new Date();\n\tconst start = new Date(end);\n\tstart.setUTCDate(start.getUTCDate() - weeks * 7);\n\treturn { startDate: utcDateString(start), endDate: utcDateString(end) };\n}\n\nfunction durationSeconds(workout: Workout): number | null {\n\tif (!workout.start_time || !workout.end_time) return null;\n\tconst duration =\n\t\tnew Date(workout.end_time).getTime() -\n\t\tnew Date(workout.start_time).getTime();\n\treturn Number.isFinite(duration) && duration >= 0\n\t\t? Math.floor(duration / 1000)\n\t\t: null;\n}\n\nfunction compactSession(\n\tworkout: Workout,\n): TrainingSummaryResult[\"workouts\"][\"sessions\"][number] {\n\tconst exercises = workout.exercises ?? [];\n\treturn {\n\t\t...(workout.id ? { id: workout.id } : {}),\n\t\t...(workout.title ? { title: workout.title } : {}),\n\t\t...(workout.start_time ? { startTime: workout.start_time } : {}),\n\t\t...(workout.end_time ? { endTime: workout.end_time } : {}),\n\t\tdurationSeconds: durationSeconds(workout),\n\t\texerciseCount: exercises.length,\n\t\tsetCount: exercises.reduce(\n\t\t\t(total, exercise) => total + (exercise.sets?.length ?? 0),\n\t\t\t0,\n\t\t),\n\t};\n}\n\nfunction compactMeasurement(\n\tmeasurement: BodyMeasurement,\n): NonNullable<TrainingSummaryResult[\"bodyMeasurements\"][\"latest\"]> {\n\treturn {\n\t\tdate: measurement.date,\n\t\tweightKg: measurement.weight_kg ?? null,\n\t\tleanMassKg: measurement.lean_mass_kg ?? null,\n\t\tfatPercent: measurement.fat_percent ?? null,\n\t};\n}\n\nexport async function getTrainingSummary(\n\truntime: ToolRuntime,\n\tweeks: number,\n): Promise<TrainingSummaryResult> {\n\tconst client = runtime.getClient();\n\tconst period = getPeriod(weeks);\n\tconst pageSize = 10;\n\tconst [workoutPages, measurementPages] = await Promise.all([\n\t\tfetchRecentPages(\n\t\t\tasync (page, pageSize) => {\n\t\t\t\tconst data: GetV1Workouts200 = await client.getWorkouts({\n\t\t\t\t\tpage,\n\t\t\t\t\tpageSize,\n\t\t\t\t});\n\t\t\t\treturn { items: data?.workouts ?? [], pageCount: data?.page_count };\n\t\t\t},\n\t\t\tpageSize,\n\t\t\tperiod.startDate,\n\t\t\tperiod.endDate,\n\t\t\t(workout) => workout.start_time,\n\t\t),\n\t\tfetchRecentPages(\n\t\t\tasync (page, pageSize) => {\n\t\t\t\tconst data: GetV1BodyMeasurements200 = await client.getBodyMeasurements(\n\t\t\t\t\t{\n\t\t\t\t\t\tpage,\n\t\t\t\t\t\tpageSize,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\titems: data?.body_measurements ?? [],\n\t\t\t\t\tpageCount: data?.page_count,\n\t\t\t\t};\n\t\t\t},\n\t\t\tpageSize,\n\t\t\tperiod.startDate,\n\t\t\tperiod.endDate,\n\t\t\t(measurement) => measurement.date,\n\t\t),\n\t]);\n\n\tconst workouts = workoutPages.items;\n\tconst sessions = workouts.map(compactSession);\n\tconst uniqueExerciseTemplateIds = [\n\t\t...new Set(\n\t\t\tworkouts.flatMap((workout) =>\n\t\t\t\t(workout.exercises ?? [])\n\t\t\t\t\t.map((exercise) => exercise.exercise_template_id)\n\t\t\t\t\t.filter((id): id is string => Boolean(id)),\n\t\t\t),\n\t\t),\n\t];\n\tconst measurements = [...measurementPages.items].sort((a, b) =>\n\t\ta.date.localeCompare(b.date),\n\t);\n\tconst earliestMeasurement = measurements[0];\n\tconst latestMeasurement = measurements.at(-1);\n\tconst earliest = earliestMeasurement\n\t\t? compactMeasurement(earliestMeasurement)\n\t\t: null;\n\tconst latest = latestMeasurement\n\t\t? compactMeasurement(latestMeasurement)\n\t\t: null;\n\tconst weightChangeKg =\n\t\tlatest?.weightKg !== null &&\n\t\tlatest?.weightKg !== undefined &&\n\t\tearliest?.weightKg !== null &&\n\t\tearliest?.weightKg !== undefined\n\t\t\t? latest.weightKg - earliest.weightKg\n\t\t\t: null;\n\n\treturn {\n\t\tperiod: { ...period, weeks },\n\t\tworkouts: {\n\t\t\tcount: workouts.length,\n\t\t\ttotalDurationSeconds: sessions.reduce(\n\t\t\t\t(total, session) => total + (session.durationSeconds ?? 0),\n\t\t\t\t0,\n\t\t\t),\n\t\t\texerciseCount: sessions.reduce(\n\t\t\t\t(total, session) => total + session.exerciseCount,\n\t\t\t\t0,\n\t\t\t),\n\t\t\tsetCount: sessions.reduce(\n\t\t\t\t(total, session) => total + session.setCount,\n\t\t\t\t0,\n\t\t\t),\n\t\t\tuniqueExerciseTemplateIds,\n\t\t\tsessions,\n\t\t},\n\t\tbodyMeasurements: {\n\t\t\tcount: measurements.length,\n\t\t\tlatest,\n\t\t\tearliest,\n\t\t\tweightChangeKg,\n\t\t},\n\t\tworkflow: {\n\t\t\tname: \"training-summary\",\n\t\t\tpagination: {\n\t\t\t\tworkouts: workoutPages.pages,\n\t\t\t\tbodyMeasurements: measurementPages.pages,\n\t\t\t},\n\t\t\tcacheStatus: \"not-used\",\n\t\t\titemsScanned: workoutPages.itemsScanned + measurementPages.itemsScanned,\n\t\t},\n\t};\n}\n\nexport const workflowToolDefinitions = [\n\t{\n\t\tname: \"get-training-summary\",\n\t\tdescription: describeTool({\n\t\t\tsummary:\n\t\t\t\t\"Read-only. Summarizes recent workout activity and body-measurement trends in one call.\",\n\t\t\taliases: [\n\t\t\t\t\"training progress\",\n\t\t\t\t\"progress summary\",\n\t\t\t\t\"recent training overview\",\n\t\t\t],\n\t\t\tuseCase:\n\t\t\t\t\"Use for a bounded progress review instead of separately counting and paging through workouts and body measurements.\",\n\t\t\timportantNotes:\n\t\t\t\t\"The summary covers the most recent 1-12 weeks, returns compact session evidence, and reports the pages and items scanned.\",\n\t\t}),\n\t\tinputSchema: trainingSummarySchema,\n\t\toutputSchema: trainingSummaryResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Get Training Summary\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: trainingSummaryResponse,\n\t\texecute: async (runtime: ToolRuntime, args: TrainingSummaryParams) =>\n\t\t\tgetTrainingSummary(runtime, args.weeks),\n\t},\n] satisfies readonly ToolDefinition<Record<string, z.ZodTypeAny>, unknown>[];\n\nexport { fetchRecentPages };\n","import { z } from \"zod\";\nimport type {\n\tGetV1Workouts200,\n\tGetV1WorkoutsCount200,\n\tGetV1WorkoutsEvents200,\n\tGetV1WorkoutsWorkoutid200,\n\tPostV1Workouts201,\n\tPutV1WorkoutsWorkoutid200,\n} from \"../generated/client/types/index.js\";\nimport { buildWorkoutPayload } from \"./payload-mappers.js\";\nimport {\n\tpaginationShape,\n\tnonEmptyId,\n\tworkoutPayloadShape,\n} from \"./input-schemas.js\";\nimport type { ToolDefinition } from \"./define-tool.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\nimport {\n\tcreateWorkoutResponse,\n\tupdateWorkoutResponse,\n\tworkoutCountResponse,\n\tworkoutEventsResponse,\n\tworkoutResponse,\n\tworkoutsResponse,\n} from \"../utils/response-formatter.js\";\nimport {\n\tcreateAnnotations,\n\treadOnlyAnnotations,\n\tupdateAnnotations,\n} from \"../utils/tool-annotations.js\";\nimport { describeTool } from \"../utils/tool-descriptions.js\";\nimport type { InferToolParams } from \"../utils/tool-helpers.js\";\n\nconst getWorkoutsSchema = paginationShape({\n\tdefaultPageSize: 5,\n\tmaxPageSize: 10,\n\tintegerPage: false,\n});\ntype GetWorkoutsParams = InferToolParams<typeof getWorkoutsSchema>;\n\nconst getWorkoutSchema = { workoutId: nonEmptyId } as const;\ntype GetWorkoutParams = InferToolParams<typeof getWorkoutSchema>;\n\nconst getWorkoutEventsSchema = {\n\t...paginationShape({ defaultPageSize: 5, maxPageSize: 10 }),\n\tsince: z.string().default(\"1970-01-01T00:00:00Z\"),\n} as const;\ntype GetWorkoutEventsParams = InferToolParams<typeof getWorkoutEventsSchema>;\n\nconst createWorkoutSchema = workoutPayloadShape;\ntype CreateWorkoutParams = InferToolParams<typeof createWorkoutSchema>;\n\nconst updateWorkoutSchema = {\n\tworkoutId: nonEmptyId,\n\t...workoutPayloadShape,\n} as const;\ntype UpdateWorkoutParams = InferToolParams<typeof updateWorkoutSchema>;\n\nexport const workoutToolDefinitions = [\n\t{\n\t\tname: \"get-workouts\",\n\t\tdescription: describeTool({\n\t\t\tsummary:\n\t\t\t\t\"Read-only. Lists workouts from newest to oldest with exercise and timing details.\",\n\t\t\taliases: [\"list workout history\", \"show recent workouts\", \"browse logs\"],\n\t\t\tuseCase:\n\t\t\t\t\"Use to browse or page through workout history; use get-workout when a workout ID is already known.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Results are paginated; page starts at 1 and pageSize is limited to 10.\",\n\t\t}),\n\t\tinputSchema: getWorkoutsSchema,\n\t\toutputSchema: workoutsResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Get Workouts\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: workoutsResponse,\n\t\texecute: async (runtime: ToolRuntime, args: GetWorkoutsParams) => {\n\t\t\tconst data: GetV1Workouts200 = await runtime.getClient().getWorkouts({\n\t\t\t\tpage: args.page,\n\t\t\t\tpageSize: args.pageSize,\n\t\t\t});\n\t\t\treturn data?.workouts;\n\t\t},\n\t},\n\t{\n\t\tname: \"get-workout\",\n\t\tdescription: describeTool({\n\t\t\tsummary:\n\t\t\t\t\"Read-only. Retrieves complete details for one workout by its ID.\",\n\t\t\taliases: [\"show workout\", \"fetch workout details\", \"open workout log\"],\n\t\t\tuseCase:\n\t\t\t\t\"Use after get-workouts identifies the exact workout; do not use for browsing multiple workouts.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Requires a workoutId discovered from a workout list, event, or prior create response.\",\n\t\t}),\n\t\tinputSchema: getWorkoutSchema,\n\t\toutputSchema: workoutResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Get Workout\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: workoutResponse,\n\t\texecute: async (runtime: ToolRuntime, args: GetWorkoutParams) => {\n\t\t\tconst data: GetV1WorkoutsWorkoutid200 = await runtime\n\t\t\t\t.getClient()\n\t\t\t\t.getWorkout(args.workoutId);\n\t\t\treturn { workout: data, workoutId: args.workoutId };\n\t\t},\n\t},\n\t{\n\t\tname: \"get-workout-count\",\n\t\tdescription: describeTool({\n\t\t\tsummary: \"Read-only. Returns the total workout count for the account.\",\n\t\t\taliases: [\"count workouts\", \"how many workouts\", \"workout total\"],\n\t\t\tuseCase:\n\t\t\t\t\"Use for totals, statistics, or estimating pages; use get-workouts for actual workout records.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Returns only a count and accepts no paging or date filters.\",\n\t\t}),\n\t\tinputSchema: {},\n\t\toutputSchema: workoutCountResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Get Workout Count\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: workoutCountResponse,\n\t\texecute: async (runtime: ToolRuntime) => {\n\t\t\tconst data: GetV1WorkoutsCount200 = await runtime\n\t\t\t\t.getClient()\n\t\t\t\t.getWorkoutCount();\n\t\t\treturn data?.workout_count ?? 0;\n\t\t},\n\t},\n\t{\n\t\tname: \"get-workout-events\",\n\t\tdescription: describeTool({\n\t\t\tsummary:\n\t\t\t\t\"Read-only. Lists workout update and delete events since a timestamp, newest first.\",\n\t\t\taliases: [\n\t\t\t\t\"sync workout changes\",\n\t\t\t\t\"workout change feed\",\n\t\t\t\t\"deleted workouts\",\n\t\t\t],\n\t\t\tuseCase:\n\t\t\t\t\"Use to incrementally synchronize a local workout cache; use get-workouts for the current workout list.\",\n\t\t\timportantNotes:\n\t\t\t\t\"since must be a timestamp string; events are paginated with pageSize at most 10, and the default since value reads from 1970.\",\n\t\t}),\n\t\tinputSchema: getWorkoutEventsSchema,\n\t\toutputSchema: workoutEventsResponse.outputSchema,\n\t\tannotations: readOnlyAnnotations(\"Get Workout Events\"),\n\t\tkind: \"read\" as const,\n\t\tresponseContract: workoutEventsResponse,\n\t\texecute: async (runtime: ToolRuntime, args: GetWorkoutEventsParams) => {\n\t\t\tconst data: GetV1WorkoutsEvents200 = await runtime\n\t\t\t\t.getClient()\n\t\t\t\t.getWorkoutEvents({\n\t\t\t\t\tpage: args.page,\n\t\t\t\t\tpageSize: args.pageSize,\n\t\t\t\t\tsince: args.since,\n\t\t\t\t});\n\t\t\treturn { events: data?.events, since: args.since };\n\t\t},\n\t},\n\t{\n\t\tname: \"create-workout\",\n\t\tdescription: describeTool({\n\t\t\tsummary: \"Writes to the Hevy account by creating a new workout.\",\n\t\t\taliases: [\"log workout\", \"add workout\", \"record training session\"],\n\t\t\tuseCase:\n\t\t\t\t\"Use to add a completed workout; use update-workout only when modifying an existing workout ID.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Requires UTC startTime/endTime in YYYY-MM-DDTHH:mm:ssZ form and exercise template IDs. Retrying can create duplicates.\",\n\t\t}),\n\t\tinputSchema: createWorkoutSchema,\n\t\tannotations: createAnnotations(\"Create Workout\"),\n\t\tkind: \"write\" as const,\n\t\tresponseContract: createWorkoutResponse,\n\t\texecute: async (runtime: ToolRuntime, args: CreateWorkoutParams) => {\n\t\t\tconst data: PostV1Workouts201 = await runtime.getClient().createWorkout({\n\t\t\t\tworkout: buildWorkoutPayload(args),\n\t\t\t});\n\t\t\treturn data;\n\t\t},\n\t},\n\t{\n\t\tname: \"update-workout\",\n\t\tdescription: describeTool({\n\t\t\tsummary: \"Mutates the Hevy account by replacing an existing workout.\",\n\t\t\taliases: [\n\t\t\t\t\"edit workout\",\n\t\t\t\t\"correct workout log\",\n\t\t\t\t\"replace workout details\",\n\t\t\t],\n\t\t\tuseCase:\n\t\t\t\t\"Use to revise a known workout; use create-workout for a new training session.\",\n\t\t\timportantNotes:\n\t\t\t\t\"Requires workoutId plus the complete title, times, privacy, exercises, and sets payload; omitted optional values may be cleared or defaulted.\",\n\t\t}),\n\t\tinputSchema: updateWorkoutSchema,\n\t\tannotations: updateAnnotations(\"Update Workout\"),\n\t\tkind: \"write\" as const,\n\t\tresponseContract: updateWorkoutResponse,\n\t\texecute: async (runtime: ToolRuntime, args: UpdateWorkoutParams) => {\n\t\t\tconst data: PutV1WorkoutsWorkoutid200 = await runtime\n\t\t\t\t.getClient()\n\t\t\t\t.updateWorkout(args.workoutId, {\n\t\t\t\t\tworkout: buildWorkoutPayload(args),\n\t\t\t\t});\n\t\t\treturn { workout: data, workoutId: args.workoutId };\n\t\t},\n\t},\n] satisfies readonly ToolDefinition<Record<string, z.ZodTypeAny>, unknown>[];\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { registerToolDefinition } from \"./define-tool.js\";\nimport { bodyMeasurementToolDefinitions } from \"./body-measurements.js\";\nimport { folderToolDefinitions } from \"./folders.js\";\nimport { routineToolDefinitions } from \"./routines.js\";\nimport { templateToolDefinitions } from \"./templates.js\";\nimport { userToolDefinitions } from \"./user.js\";\nimport { routineDiscoveryToolDefinitions } from \"./routine-discovery.js\";\nimport { workflowToolDefinitions } from \"./workflows.js\";\nimport { workoutToolDefinitions } from \"./workouts.js\";\nimport type { ToolRuntime } from \"./tool-runtime.js\";\n\nconst hevyToolDefinitions = [\n\t...workoutToolDefinitions,\n\t...routineToolDefinitions,\n\t...templateToolDefinitions,\n\t...folderToolDefinitions,\n\t...bodyMeasurementToolDefinitions,\n\t...userToolDefinitions,\n\t...workflowToolDefinitions,\n\t...routineDiscoveryToolDefinitions,\n] as const;\n\n/** Register every Hevy tool in its production ordering. */\nexport function registerHevyTools(\n\tserver: McpServer,\n\truntime: ToolRuntime,\n): void {\n\tfor (const definition of hevyToolDefinitions) {\n\t\tregisterToolDefinition(server, runtime, definition);\n\t}\n}\n","/**\n * Centralized error handling utility for MCP tools\n */\n\nimport { ErrorType, resolveErrorPolicy } from \"./error-policy.js\";\nimport type { McpToolResponse } from \"./response-formatter.js\";\nimport { HEVY_CLIENT_NOT_INITIALIZED_ERROR } from \"./tool-helpers.js\";\n\nexport { ErrorType } from \"./error-policy.js\";\n\n/**\n * Standard error response interface\n */\nexport interface ErrorResponse {\n\tmessage: string;\n\tcode?: string;\n\tdetails?: unknown;\n}\n\n/**\n * Enhanced error response with type categorization\n */\nexport interface EnhancedErrorResponse extends ErrorResponse {\n\ttype: ErrorType;\n}\n\n/** Structured debug context containing only bounded, safe metadata. */\nexport interface ErrorDebugContext {\n\tsourceContext?: string;\n\toriginalErrorMessage: string;\n\terrorCode?: string;\n\terrorType: ErrorType;\n\taxios?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\tmethod?: string;\n\t\turl?: string;\n\t};\n}\n\n/**\n * Create a standardized error response for MCP tools\n *\n * @param error - The error object or message\n * @param context - Optional context information about where the error occurred\n * @returns A formatted MCP tool response with error information\n */\nexport function createErrorResponse(\n\terror: unknown,\n\tcontext?: string,\n): McpToolResponse {\n\tconst policy = resolveErrorPolicy(\n\t\terror,\n\t\t\"The request failed unexpectedly. Please try again.\",\n\t\tHEVY_CLIENT_NOT_INITIALIZED_ERROR,\n\t);\n\tconst { diagnostic } = policy;\n\tconst axiosErrorContext: ErrorDebugContext[\"axios\"] | null =\n\t\tdiagnostic.status !== undefined ||\n\t\tdiagnostic.method !== undefined ||\n\t\tdiagnostic.endpoint !== undefined\n\t\t\t? {\n\t\t\t\t\tstatus: diagnostic.status,\n\t\t\t\t\tmethod: diagnostic.method,\n\t\t\t\t\turl: diagnostic.endpoint,\n\t\t\t\t}\n\t\t\t: null;\n\tconst errorContext: ErrorDebugContext = {\n\t\tsourceContext: context,\n\t\toriginalErrorMessage: `${diagnostic.category} occurred`,\n\t\terrorCode: diagnostic.code,\n\t\terrorType: policy.type,\n\t\taxios: axiosErrorContext ?? undefined,\n\t};\n\tconst contextPrefix = context ? `[${context}] ` : \"\";\n\tconst formattedMessage = `${contextPrefix}Error: ${policy.message}`;\n\n\tconsole.error(\"MCP tool failure\", diagnostic);\n\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: formattedMessage }],\n\t\tisError: true,\n\t\terrorContext,\n\t};\n}\n\n/**\n * Wrap an async function with standardized error handling\n *\n * This function preserves the parameter types of the wrapped function while\n * providing error handling. The returned function accepts Record<string, unknown>\n * (as required by MCP SDK) but internally casts to the original parameter type.\n *\n * @param fn - The async function to wrap\n * @param context - Context information for error messages\n * @returns A function that catches errors and returns standardized error responses\n */\nexport function withErrorHandling<TParams extends Record<string, unknown>>(\n\tfn: (args: TParams) => Promise<McpToolResponse>,\n\tcontext: string,\n\tonError?: (error: unknown, context: string, argumentKeyCount: number) => void,\n): (args: Record<string, unknown>) => Promise<McpToolResponse> {\n\treturn async (rawArgs: Record<string, unknown>) => {\n\t\tconst args = rawArgs ?? {};\n\t\ttry {\n\t\t\treturn await fn(args as TParams);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tonError?.(error, context, Object.keys(args).length);\n\t\t\t} catch {\n\t\t\t\tconsole.error(\"MCP error observer failure\", {\n\t\t\t\t\tcategory: \"ObserverError\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn createErrorResponse(error, context);\n\t\t}\n\t};\n}\n","export interface AsyncCacheOptions {\n\tttlMs: number;\n\tmaxSize: number;\n}\n\nexport interface CacheGetOptions {\n\trefresh?: boolean;\n}\n\ninterface CacheEntry<TValue> {\n\tvalue: TValue;\n\texpiresAt: number;\n}\n\ninterface InFlightEntry<TValue> {\n\tpromise: Promise<TValue>;\n\trequestId: number;\n}\n\n/**\n * Shared in-memory cache for async fetches with TTL, LRU eviction,\n * in-flight de-duplication, and explicit refresh/invalidation support.\n */\nexport class AsyncTtlCache<TKey, TValue> {\n\tprivate readonly ttlMs: number;\n\tprivate readonly maxSize: number;\n\tprivate readonly now: () => number;\n\tprivate readonly entries = new Map<TKey, CacheEntry<TValue>>();\n\tprivate readonly inFlight = new Map<TKey, InFlightEntry<TValue>>();\n\tprivate requestCounter = 0;\n\n\tconstructor(options: AsyncCacheOptions, now: () => number = Date.now) {\n\t\tconst { ttlMs, maxSize } = options;\n\t\tif (ttlMs <= 0) {\n\t\t\tthrow new Error(\"Cache ttlMs must be greater than 0.\");\n\t\t}\n\t\tif (maxSize <= 0) {\n\t\t\tthrow new Error(\"Cache maxSize must be greater than 0.\");\n\t\t}\n\n\t\tthis.ttlMs = ttlMs;\n\t\tthis.maxSize = maxSize;\n\t\tthis.now = now;\n\t}\n\n\tasync getOrFetch(\n\t\tkey: TKey,\n\t\tfetcher: () => Promise<TValue>,\n\t\toptions: CacheGetOptions = {},\n\t): Promise<TValue> {\n\t\tconst { refresh = false } = options;\n\n\t\tif (refresh) {\n\t\t\tthis.invalidate(key);\n\t\t} else {\n\t\t\tconst cachedEntry = this.entries.get(key);\n\t\t\tif (cachedEntry !== undefined) {\n\t\t\t\tif (cachedEntry.expiresAt > this.now()) {\n\t\t\t\t\tthis.markAsRecentlyUsed(key, cachedEntry);\n\t\t\t\t\treturn cachedEntry.value;\n\t\t\t\t}\n\n\t\t\t\tthis.entries.delete(key);\n\t\t\t}\n\n\t\t\tconst inFlightEntry = this.inFlight.get(key);\n\t\t\tif (inFlightEntry !== undefined) {\n\t\t\t\treturn inFlightEntry.promise;\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = ++this.requestCounter;\n\t\tconst request = (async () => {\n\t\t\ttry {\n\t\t\t\tconst value = await fetcher();\n\n\t\t\t\tif (this.isCurrentRequest(key, requestId)) {\n\t\t\t\t\tthis.setValue(key, value);\n\t\t\t\t}\n\n\t\t\t\treturn value;\n\t\t\t} finally {\n\t\t\t\tconst inFlightEntry = this.inFlight.get(key);\n\t\t\t\tif (inFlightEntry?.requestId === requestId) {\n\t\t\t\t\tthis.inFlight.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\n\t\tthis.inFlight.set(key, { promise: request, requestId });\n\t\treturn request;\n\t}\n\n\tinvalidate(key: TKey): void {\n\t\tthis.entries.delete(key);\n\t\tthis.inFlight.delete(key);\n\t}\n\n\tclear(): void {\n\t\tthis.entries.clear();\n\t\tthis.inFlight.clear();\n\t}\n\n\tget size(): number {\n\t\treturn this.entries.size;\n\t}\n\n\tprivate isCurrentRequest(key: TKey, requestId: number): boolean {\n\t\treturn this.inFlight.get(key)?.requestId === requestId;\n\t}\n\n\tprivate markAsRecentlyUsed(key: TKey, entry: CacheEntry<TValue>): void {\n\t\tthis.entries.delete(key);\n\t\tthis.entries.set(key, entry);\n\t}\n\n\tprivate setValue(key: TKey, value: TValue): void {\n\t\tthis.entries.delete(key);\n\t\tthis.entries.set(key, {\n\t\t\tvalue,\n\t\t\texpiresAt: this.now() + this.ttlMs,\n\t\t});\n\n\t\tthis.evictLeastRecentlyUsed();\n\t}\n\n\tprivate evictLeastRecentlyUsed(): void {\n\t\twhile (this.entries.size > this.maxSize) {\n\t\t\tconst oldestKey = this.entries.keys().next().value;\n\t\t\tif (oldestKey === undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.entries.delete(oldestKey);\n\t\t}\n\t}\n}\n","import type {\n\tExerciseTemplate,\n\tGetV1ExerciseTemplates200,\n} from \"../generated/client/types/index.js\";\nimport type { HevyClient } from \"./hevyClient.js\";\nimport { AsyncTtlCache } from \"./cache.js\";\nimport { fetchAllPages } from \"./pagination.js\";\n\nconst EXERCISE_TEMPLATE_CATALOG_CACHE_KEY = \"exercise-template-catalog\";\nconst EXERCISE_TEMPLATE_CATALOG_CACHE_TTL_MS = 5 * 60 * 1000;\nconst EXERCISE_TEMPLATE_CATALOG_CACHE_MAX_SIZE = 1;\n\nexport type ExerciseTemplateCatalogRefreshReason =\n\t| \"explicit-refresh\"\n\t| \"initial-load\"\n\t| \"ttl-expired\";\n\nexport interface ExerciseTemplateCatalogOptions {\n\trefresh?: boolean;\n\tonRefreshed?: (\n\t\tcatalog: ExerciseTemplate[],\n\t\treason: ExerciseTemplateCatalogRefreshReason,\n\t) => void;\n}\n\nexport interface ExerciseTemplateCatalog {\n\tget(options?: ExerciseTemplateCatalogOptions): Promise<ExerciseTemplate[]>;\n\treset(): void;\n}\n\n/** Create a cache owned by one MCP server/request lifecycle. */\nexport function createExerciseTemplateCatalog(\n\thevyClient: HevyClient,\n): ExerciseTemplateCatalog {\n\tconst cache = new AsyncTtlCache<string, ExerciseTemplate[]>({\n\t\tttlMs: EXERCISE_TEMPLATE_CATALOG_CACHE_TTL_MS,\n\t\tmaxSize: EXERCISE_TEMPLATE_CATALOG_CACHE_MAX_SIZE,\n\t});\n\n\treturn {\n\t\tget(options = {}) {\n\t\t\tconst reason = options.refresh\n\t\t\t\t? \"explicit-refresh\"\n\t\t\t\t: cache.size === 0\n\t\t\t\t\t? \"initial-load\"\n\t\t\t\t\t: \"ttl-expired\";\n\t\t\treturn cache.getOrFetch(\n\t\t\t\tEXERCISE_TEMPLATE_CATALOG_CACHE_KEY,\n\t\t\t\tasync () => {\n\t\t\t\t\tconst catalog = await fetchAllPages<ExerciseTemplate>(\n\t\t\t\t\t\tasync (page, pageSize) => {\n\t\t\t\t\t\t\tconst data: GetV1ExerciseTemplates200 =\n\t\t\t\t\t\t\t\tawait hevyClient.getExerciseTemplates({\n\t\t\t\t\t\t\t\t\tpage,\n\t\t\t\t\t\t\t\t\tpageSize,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\titems: data?.exercise_templates ?? [],\n\t\t\t\t\t\t\t\tpageCount: data?.page_count,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t\t100,\n\t\t\t\t\t);\n\t\t\t\t\toptions.onRefreshed?.(catalog, reason);\n\t\t\t\t\treturn catalog;\n\t\t\t\t},\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\t\treset() {\n\t\t\tcache.clear();\n\t\t},\n\t};\n}\n","/**\n * RequestCredentials\n */\nexport type RequestCredentials = \"omit\" | \"same-origin\" | \"include\";\n\n/**\n * Subset of FetchRequestConfig\n */\nexport type RequestConfig<TData = unknown> = {\n baseURL?: string;\n url?: string;\n method?: \"GET\" | \"PUT\" | \"PATCH\" | \"POST\" | \"DELETE\" | \"OPTIONS\" | \"HEAD\";\n params?: unknown;\n data?: TData | FormData;\n responseType?:\n | \"arraybuffer\"\n | \"blob\"\n | \"document\"\n | \"json\"\n | \"text\"\n | \"stream\";\n signal?: AbortSignal;\n headers?: [string, string][] | Record<string, string>;\n credentials?: RequestCredentials;\n};\n\n/**\n * Subset of FetchResponse\n */\nexport type ResponseConfig<TData = unknown> = {\n data: TData;\n status: number;\n statusText: string;\n headers: Headers;\n};\n\nlet _config: Partial<RequestConfig> = {};\n\nexport const getConfig = () => _config;\n\nexport const setConfig = (config: Partial<RequestConfig>) => {\n _config = config;\n return getConfig();\n};\n\nexport const mergeConfig = <T extends RequestConfig>(\n ...configs: Array<Partial<T>>\n): Partial<T> => {\n return configs.reduce<Partial<T>>((merged, config) => {\n return {\n ...merged,\n ...config,\n headers: {\n ...(Array.isArray(merged.headers)\n ? Object.fromEntries(merged.headers)\n : merged.headers),\n ...(Array.isArray(config.headers)\n ? Object.fromEntries(config.headers)\n : config.headers),\n },\n };\n }, {});\n};\n\nexport type ResponseErrorConfig<TError = unknown> = TError;\n\nexport type Client = <TData, _TError = unknown, TVariables = unknown>(\n config: RequestConfig<TVariables>\n) => Promise<ResponseConfig<TData>>;\n\nexport const fetch = async <TData, _TError = unknown, TVariables = unknown>(\n paramsConfig: RequestConfig<TVariables>\n): Promise<ResponseConfig<TData>> => {\n const normalizedParams = new URLSearchParams();\n\n const config = mergeConfig(getConfig(), paramsConfig);\n\n Object.entries(config.params || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n normalizedParams.append(key, value === null ? \"null\" : value.toString());\n }\n });\n\n let targetUrl = [config.baseURL, config.url].filter(Boolean).join(\"\");\n\n if (config.params) {\n targetUrl += `?${normalizedParams}`;\n }\n\n const response = await globalThis.fetch(targetUrl, {\n credentials: config.credentials || \"same-origin\",\n method: config.method?.toUpperCase(),\n body:\n config.data instanceof FormData\n ? config.data\n : JSON.stringify(config.data),\n signal: config.signal,\n headers: config.headers,\n });\n\n const data =\n [204, 205, 304].includes(response.status) || !response.body\n ? {}\n : await response.json();\n\n return {\n data: data as TData,\n status: response.status,\n statusText: response.statusText,\n headers: response.headers as Headers,\n };\n};\n\nfetch.getConfig = getConfig;\nfetch.setConfig = setConfig;\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1BodyMeasurementsQueryResponse,\n GetV1BodyMeasurementsQueryParams,\n GetV1BodyMeasurementsHeaderParams,\n GetV1BodyMeasurements400,\n GetV1BodyMeasurements404,\n} from \"../types/GetV1BodyMeasurements.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1BodyMeasurementsUrl() {\n const res = { method: \"GET\", url: `/v1/body_measurements` as const };\n return res;\n}\n\n/**\n * @summary Get a paginated list of body measurements for the authenticated user\n * {@link /v1/body_measurements}\n */\nexport async function getV1BodyMeasurements(\n headers: GetV1BodyMeasurementsHeaderParams,\n params?: GetV1BodyMeasurementsQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1BodyMeasurementsQueryResponse,\n ResponseErrorConfig<GetV1BodyMeasurements400 | GetV1BodyMeasurements404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1BodyMeasurementsUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1BodyMeasurementsDateQueryResponse,\n GetV1BodyMeasurementsDatePathParams,\n GetV1BodyMeasurementsDateHeaderParams,\n GetV1BodyMeasurementsDate404,\n} from \"../types/GetV1BodyMeasurementsDate.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1BodyMeasurementsDateUrl(\n date: GetV1BodyMeasurementsDatePathParams[\"date\"]\n) {\n const res = { method: \"GET\", url: `/v1/body_measurements/${date}` as const };\n return res;\n}\n\n/**\n * @summary Get a single body measurement by date\n * {@link /v1/body_measurements/:date}\n */\nexport async function getV1BodyMeasurementsDate(\n date: GetV1BodyMeasurementsDatePathParams[\"date\"],\n headers: GetV1BodyMeasurementsDateHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1BodyMeasurementsDateQueryResponse,\n ResponseErrorConfig<GetV1BodyMeasurementsDate404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1BodyMeasurementsDateUrl(date).url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1ExerciseHistoryExercisetemplateidQueryResponse,\n GetV1ExerciseHistoryExercisetemplateidPathParams,\n GetV1ExerciseHistoryExercisetemplateidQueryParams,\n GetV1ExerciseHistoryExercisetemplateidHeaderParams,\n GetV1ExerciseHistoryExercisetemplateid400,\n} from \"../types/GetV1ExerciseHistoryExercisetemplateid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1ExerciseHistoryExercisetemplateidUrl(\n exerciseTemplateId: GetV1ExerciseHistoryExercisetemplateidPathParams[\"exerciseTemplateId\"]\n) {\n const res = {\n method: \"GET\",\n url: `/v1/exercise_history/${exerciseTemplateId}` as const,\n };\n return res;\n}\n\n/**\n * @summary Get exercise history for a specific exercise template\n * {@link /v1/exercise_history/:exerciseTemplateId}\n */\nexport async function getV1ExerciseHistoryExercisetemplateid(\n exerciseTemplateId: GetV1ExerciseHistoryExercisetemplateidPathParams[\"exerciseTemplateId\"],\n headers: GetV1ExerciseHistoryExercisetemplateidHeaderParams,\n params?: GetV1ExerciseHistoryExercisetemplateidQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1ExerciseHistoryExercisetemplateidQueryResponse,\n ResponseErrorConfig<GetV1ExerciseHistoryExercisetemplateid400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1ExerciseHistoryExercisetemplateidUrl(\n exerciseTemplateId\n ).url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1ExerciseTemplatesQueryResponse,\n GetV1ExerciseTemplatesQueryParams,\n GetV1ExerciseTemplatesHeaderParams,\n GetV1ExerciseTemplates400,\n} from \"../types/GetV1ExerciseTemplates.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1ExerciseTemplatesUrl() {\n const res = { method: \"GET\", url: `/v1/exercise_templates` as const };\n return res;\n}\n\n/**\n * @summary Get a paginated list of exercise templates available on the account.\n * {@link /v1/exercise_templates}\n */\nexport async function getV1ExerciseTemplates(\n headers: GetV1ExerciseTemplatesHeaderParams,\n params?: GetV1ExerciseTemplatesQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1ExerciseTemplatesQueryResponse,\n ResponseErrorConfig<GetV1ExerciseTemplates400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1ExerciseTemplatesUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1ExerciseTemplatesExercisetemplateidQueryResponse,\n GetV1ExerciseTemplatesExercisetemplateidPathParams,\n GetV1ExerciseTemplatesExercisetemplateidHeaderParams,\n GetV1ExerciseTemplatesExercisetemplateid404,\n} from \"../types/GetV1ExerciseTemplatesExercisetemplateid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1ExerciseTemplatesExercisetemplateidUrl(\n exerciseTemplateId: GetV1ExerciseTemplatesExercisetemplateidPathParams[\"exerciseTemplateId\"]\n) {\n const res = {\n method: \"GET\",\n url: `/v1/exercise_templates/${exerciseTemplateId}` as const,\n };\n return res;\n}\n\n/**\n * @summary Get a single exercise template by id.\n * {@link /v1/exercise_templates/:exerciseTemplateId}\n */\nexport async function getV1ExerciseTemplatesExercisetemplateid(\n exerciseTemplateId: GetV1ExerciseTemplatesExercisetemplateidPathParams[\"exerciseTemplateId\"],\n headers: GetV1ExerciseTemplatesExercisetemplateidHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1ExerciseTemplatesExercisetemplateidQueryResponse,\n ResponseErrorConfig<GetV1ExerciseTemplatesExercisetemplateid404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1ExerciseTemplatesExercisetemplateidUrl(\n exerciseTemplateId\n ).url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1RoutineFoldersQueryResponse,\n GetV1RoutineFoldersQueryParams,\n GetV1RoutineFoldersHeaderParams,\n GetV1RoutineFolders400,\n} from \"../types/GetV1RoutineFolders.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1RoutineFoldersUrl() {\n const res = { method: \"GET\", url: `/v1/routine_folders` as const };\n return res;\n}\n\n/**\n * @summary Get a paginated list of routine folders available on the account.\n * {@link /v1/routine_folders}\n */\nexport async function getV1RoutineFolders(\n headers: GetV1RoutineFoldersHeaderParams,\n params?: GetV1RoutineFoldersQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1RoutineFoldersQueryResponse,\n ResponseErrorConfig<GetV1RoutineFolders400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1RoutineFoldersUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1RoutineFoldersFolderidQueryResponse,\n GetV1RoutineFoldersFolderidPathParams,\n GetV1RoutineFoldersFolderidHeaderParams,\n GetV1RoutineFoldersFolderid404,\n} from \"../types/GetV1RoutineFoldersFolderid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1RoutineFoldersFolderidUrl(\n folderId: GetV1RoutineFoldersFolderidPathParams[\"folderId\"]\n) {\n const res = {\n method: \"GET\",\n url: `/v1/routine_folders/${folderId}` as const,\n };\n return res;\n}\n\n/**\n * @summary Get a single routine folder by id.\n * {@link /v1/routine_folders/:folderId}\n */\nexport async function getV1RoutineFoldersFolderid(\n folderId: GetV1RoutineFoldersFolderidPathParams[\"folderId\"],\n headers: GetV1RoutineFoldersFolderidHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1RoutineFoldersFolderidQueryResponse,\n ResponseErrorConfig<GetV1RoutineFoldersFolderid404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1RoutineFoldersFolderidUrl(folderId).url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1RoutinesQueryResponse,\n GetV1RoutinesQueryParams,\n GetV1RoutinesHeaderParams,\n GetV1Routines400,\n} from \"../types/GetV1Routines.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1RoutinesUrl() {\n const res = { method: \"GET\", url: `/v1/routines` as const };\n return res;\n}\n\n/**\n * @summary Get a paginated list of routines\n * {@link /v1/routines}\n */\nexport async function getV1Routines(\n headers: GetV1RoutinesHeaderParams,\n params?: GetV1RoutinesQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1RoutinesQueryResponse,\n ResponseErrorConfig<GetV1Routines400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1RoutinesUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1RoutinesRoutineidQueryResponse,\n GetV1RoutinesRoutineidPathParams,\n GetV1RoutinesRoutineidHeaderParams,\n GetV1RoutinesRoutineid400,\n} from \"../types/GetV1RoutinesRoutineid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1RoutinesRoutineidUrl(\n routineId: GetV1RoutinesRoutineidPathParams[\"routineId\"]\n) {\n const res = { method: \"GET\", url: `/v1/routines/${routineId}` as const };\n return res;\n}\n\n/**\n * @summary Get a routine by its Id\n * {@link /v1/routines/:routineId}\n */\nexport async function getV1RoutinesRoutineid(\n routineId: GetV1RoutinesRoutineidPathParams[\"routineId\"],\n headers: GetV1RoutinesRoutineidHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1RoutinesRoutineidQueryResponse,\n ResponseErrorConfig<GetV1RoutinesRoutineid400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1RoutinesRoutineidUrl(routineId).url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1UserInfoQueryResponse,\n GetV1UserInfoHeaderParams,\n GetV1UserInfo404,\n} from \"../types/GetV1UserInfo.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1UserInfoUrl() {\n const res = { method: \"GET\", url: `/v1/user/info` as const };\n return res;\n}\n\n/**\n * @summary Get user info\n * {@link /v1/user/info}\n */\nexport async function getV1UserInfo(\n headers: GetV1UserInfoHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1UserInfoQueryResponse,\n ResponseErrorConfig<GetV1UserInfo404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1UserInfoUrl().url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1WorkoutsQueryResponse,\n GetV1WorkoutsQueryParams,\n GetV1WorkoutsHeaderParams,\n GetV1Workouts400,\n} from \"../types/GetV1Workouts.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1WorkoutsUrl() {\n const res = { method: \"GET\", url: `/v1/workouts` as const };\n return res;\n}\n\n/**\n * @summary Get a paginated list of workouts\n * {@link /v1/workouts}\n */\nexport async function getV1Workouts(\n headers: GetV1WorkoutsHeaderParams,\n params?: GetV1WorkoutsQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1WorkoutsQueryResponse,\n ResponseErrorConfig<GetV1Workouts400>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1WorkoutsUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1WorkoutsCountQueryResponse,\n GetV1WorkoutsCountHeaderParams,\n} from \"../types/GetV1WorkoutsCount.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1WorkoutsCountUrl() {\n const res = { method: \"GET\", url: `/v1/workouts/count` as const };\n return res;\n}\n\n/**\n * @summary Get the total number of workouts on the account\n * {@link /v1/workouts/count}\n */\nexport async function getV1WorkoutsCount(\n headers: GetV1WorkoutsCountHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1WorkoutsCountQueryResponse,\n ResponseErrorConfig<Error>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1WorkoutsCountUrl().url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1WorkoutsEventsQueryResponse,\n GetV1WorkoutsEventsQueryParams,\n GetV1WorkoutsEventsHeaderParams,\n GetV1WorkoutsEvents500,\n} from \"../types/GetV1WorkoutsEvents.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1WorkoutsEventsUrl() {\n const res = { method: \"GET\", url: `/v1/workouts/events` as const };\n return res;\n}\n\n/**\n * @description Returns a paginated array of workout events, indicating updates or deletions.\n * @summary Retrieve a paged list of workout events (updates or deletes) since a given date. Events are ordered from newest to oldest. The intention is to allow clients to keep their local cache of workouts up to date without having to fetch the entire list of workouts.\n * {@link /v1/workouts/events}\n */\nexport async function getV1WorkoutsEvents(\n headers: GetV1WorkoutsEventsHeaderParams,\n params?: GetV1WorkoutsEventsQueryParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1WorkoutsEventsQueryResponse,\n ResponseErrorConfig<GetV1WorkoutsEvents500>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1WorkoutsEventsUrl().url.toString(),\n params,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n GetV1WorkoutsWorkoutidQueryResponse,\n GetV1WorkoutsWorkoutidPathParams,\n GetV1WorkoutsWorkoutidHeaderParams,\n GetV1WorkoutsWorkoutid404,\n} from \"../types/GetV1WorkoutsWorkoutid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getGetV1WorkoutsWorkoutidUrl(\n workoutId: GetV1WorkoutsWorkoutidPathParams[\"workoutId\"]\n) {\n const res = { method: \"GET\", url: `/v1/workouts/${workoutId}` as const };\n return res;\n}\n\n/**\n * @summary Get a single workout’s complete details by the workoutId\n * {@link /v1/workouts/:workoutId}\n */\nexport async function getV1WorkoutsWorkoutid(\n workoutId: GetV1WorkoutsWorkoutidPathParams[\"workoutId\"],\n headers: GetV1WorkoutsWorkoutidHeaderParams,\n config: Partial<RequestConfig> & { client?: Client } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const res = await request<\n GetV1WorkoutsWorkoutidQueryResponse,\n ResponseErrorConfig<GetV1WorkoutsWorkoutid404>,\n unknown\n >({\n method: \"GET\",\n url: getGetV1WorkoutsWorkoutidUrl(workoutId).url.toString(),\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PostV1BodyMeasurementsMutationRequest,\n PostV1BodyMeasurementsMutationResponse,\n PostV1BodyMeasurementsHeaderParams,\n PostV1BodyMeasurements400,\n PostV1BodyMeasurements409,\n} from \"../types/PostV1BodyMeasurements.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPostV1BodyMeasurementsUrl() {\n const res = { method: \"POST\", url: `/v1/body_measurements` as const };\n return res;\n}\n\n/**\n * @summary Create a body measurement entry for a given date. Returns 409 if an entry already exists for that date.\n * {@link /v1/body_measurements}\n */\nexport async function postV1BodyMeasurements(\n data: PostV1BodyMeasurementsMutationRequest,\n headers: PostV1BodyMeasurementsHeaderParams,\n config: Partial<RequestConfig<PostV1BodyMeasurementsMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PostV1BodyMeasurementsMutationResponse,\n ResponseErrorConfig<PostV1BodyMeasurements400 | PostV1BodyMeasurements409>,\n PostV1BodyMeasurementsMutationRequest\n >({\n method: \"POST\",\n url: getPostV1BodyMeasurementsUrl().url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PostV1ExerciseTemplatesMutationRequest,\n PostV1ExerciseTemplatesMutationResponse,\n PostV1ExerciseTemplatesHeaderParams,\n PostV1ExerciseTemplates400,\n PostV1ExerciseTemplates403,\n} from \"../types/PostV1ExerciseTemplates.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPostV1ExerciseTemplatesUrl() {\n const res = { method: \"POST\", url: `/v1/exercise_templates` as const };\n return res;\n}\n\n/**\n * @summary Create a new custom exercise template.\n * {@link /v1/exercise_templates}\n */\nexport async function postV1ExerciseTemplates(\n data: PostV1ExerciseTemplatesMutationRequest,\n headers: PostV1ExerciseTemplatesHeaderParams,\n config: Partial<RequestConfig<PostV1ExerciseTemplatesMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PostV1ExerciseTemplatesMutationResponse,\n ResponseErrorConfig<\n PostV1ExerciseTemplates400 | PostV1ExerciseTemplates403\n >,\n PostV1ExerciseTemplatesMutationRequest\n >({\n method: \"POST\",\n url: getPostV1ExerciseTemplatesUrl().url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PostV1RoutineFoldersMutationRequest,\n PostV1RoutineFoldersMutationResponse,\n PostV1RoutineFoldersHeaderParams,\n PostV1RoutineFolders400,\n} from \"../types/PostV1RoutineFolders.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPostV1RoutineFoldersUrl() {\n const res = { method: \"POST\", url: `/v1/routine_folders` as const };\n return res;\n}\n\n/**\n * @summary Create a new routine folder. The folder will be created at index 0, and all other folders will have their indexes incremented.\n * {@link /v1/routine_folders}\n */\nexport async function postV1RoutineFolders(\n data: PostV1RoutineFoldersMutationRequest,\n headers: PostV1RoutineFoldersHeaderParams,\n config: Partial<RequestConfig<PostV1RoutineFoldersMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PostV1RoutineFoldersMutationResponse,\n ResponseErrorConfig<PostV1RoutineFolders400>,\n PostV1RoutineFoldersMutationRequest\n >({\n method: \"POST\",\n url: getPostV1RoutineFoldersUrl().url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PostV1RoutinesMutationRequest,\n PostV1RoutinesMutationResponse,\n PostV1RoutinesHeaderParams,\n PostV1Routines400,\n PostV1Routines403,\n} from \"../types/PostV1Routines.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPostV1RoutinesUrl() {\n const res = { method: \"POST\", url: `/v1/routines` as const };\n return res;\n}\n\n/**\n * @summary Create a new routine\n * {@link /v1/routines}\n */\nexport async function postV1Routines(\n data: PostV1RoutinesMutationRequest,\n headers: PostV1RoutinesHeaderParams,\n config: Partial<RequestConfig<PostV1RoutinesMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PostV1RoutinesMutationResponse,\n ResponseErrorConfig<PostV1Routines400 | PostV1Routines403>,\n PostV1RoutinesMutationRequest\n >({\n method: \"POST\",\n url: getPostV1RoutinesUrl().url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PostV1WorkoutsMutationRequest,\n PostV1WorkoutsMutationResponse,\n PostV1WorkoutsHeaderParams,\n PostV1Workouts400,\n} from \"../types/PostV1Workouts.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPostV1WorkoutsUrl() {\n const res = { method: \"POST\", url: `/v1/workouts` as const };\n return res;\n}\n\n/**\n * @summary Create a new workout\n * {@link /v1/workouts}\n */\nexport async function postV1Workouts(\n data: PostV1WorkoutsMutationRequest,\n headers: PostV1WorkoutsHeaderParams,\n config: Partial<RequestConfig<PostV1WorkoutsMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PostV1WorkoutsMutationResponse,\n ResponseErrorConfig<PostV1Workouts400>,\n PostV1WorkoutsMutationRequest\n >({\n method: \"POST\",\n url: getPostV1WorkoutsUrl().url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PutV1BodyMeasurementsDateMutationRequest,\n PutV1BodyMeasurementsDateMutationResponse,\n PutV1BodyMeasurementsDatePathParams,\n PutV1BodyMeasurementsDateHeaderParams,\n PutV1BodyMeasurementsDate400,\n PutV1BodyMeasurementsDate404,\n} from \"../types/PutV1BodyMeasurementsDate.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPutV1BodyMeasurementsDateUrl(\n date: PutV1BodyMeasurementsDatePathParams[\"date\"]\n) {\n const res = { method: \"PUT\", url: `/v1/body_measurements/${date}` as const };\n return res;\n}\n\n/**\n * @summary Update an existing body measurement entry for a given date. All fields are overwritten; omitted fields are set to null.\n * {@link /v1/body_measurements/:date}\n */\nexport async function putV1BodyMeasurementsDate(\n date: PutV1BodyMeasurementsDatePathParams[\"date\"],\n data: PutV1BodyMeasurementsDateMutationRequest,\n headers: PutV1BodyMeasurementsDateHeaderParams,\n config: Partial<RequestConfig<PutV1BodyMeasurementsDateMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PutV1BodyMeasurementsDateMutationResponse,\n ResponseErrorConfig<\n PutV1BodyMeasurementsDate400 | PutV1BodyMeasurementsDate404\n >,\n PutV1BodyMeasurementsDateMutationRequest\n >({\n method: \"PUT\",\n url: getPutV1BodyMeasurementsDateUrl(date).url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PutV1RoutinesRoutineidMutationRequest,\n PutV1RoutinesRoutineidMutationResponse,\n PutV1RoutinesRoutineidPathParams,\n PutV1RoutinesRoutineidHeaderParams,\n PutV1RoutinesRoutineid400,\n PutV1RoutinesRoutineid404,\n} from \"../types/PutV1RoutinesRoutineid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPutV1RoutinesRoutineidUrl(\n routineId: PutV1RoutinesRoutineidPathParams[\"routineId\"]\n) {\n const res = { method: \"PUT\", url: `/v1/routines/${routineId}` as const };\n return res;\n}\n\n/**\n * @summary Update an existing routine\n * {@link /v1/routines/:routineId}\n */\nexport async function putV1RoutinesRoutineid(\n routineId: PutV1RoutinesRoutineidPathParams[\"routineId\"],\n data: PutV1RoutinesRoutineidMutationRequest,\n headers: PutV1RoutinesRoutineidHeaderParams,\n config: Partial<RequestConfig<PutV1RoutinesRoutineidMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PutV1RoutinesRoutineidMutationResponse,\n ResponseErrorConfig<PutV1RoutinesRoutineid400 | PutV1RoutinesRoutineid404>,\n PutV1RoutinesRoutineidMutationRequest\n >({\n method: \"PUT\",\n url: getPutV1RoutinesRoutineidUrl(routineId).url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","/**\n * Generated by Kubb (https://kubb.dev/).\n * Do not edit manually.\n */\n\nimport type {\n Client,\n RequestConfig,\n ResponseErrorConfig,\n} from \"../../.kubb/fetch.ts\";\nimport type {\n PutV1WorkoutsWorkoutidMutationRequest,\n PutV1WorkoutsWorkoutidMutationResponse,\n PutV1WorkoutsWorkoutidPathParams,\n PutV1WorkoutsWorkoutidHeaderParams,\n PutV1WorkoutsWorkoutid400,\n} from \"../types/PutV1WorkoutsWorkoutid.ts\";\nimport { fetch } from \"../../.kubb/fetch.ts\";\n\nfunction getPutV1WorkoutsWorkoutidUrl(\n workoutId: PutV1WorkoutsWorkoutidPathParams[\"workoutId\"]\n) {\n const res = { method: \"PUT\", url: `/v1/workouts/${workoutId}` as const };\n return res;\n}\n\n/**\n * @summary Update an existing workout\n * {@link /v1/workouts/:workoutId}\n */\nexport async function putV1WorkoutsWorkoutid(\n workoutId: PutV1WorkoutsWorkoutidPathParams[\"workoutId\"],\n data: PutV1WorkoutsWorkoutidMutationRequest,\n headers: PutV1WorkoutsWorkoutidHeaderParams,\n config: Partial<RequestConfig<PutV1WorkoutsWorkoutidMutationRequest>> & {\n client?: Client;\n } = {}\n) {\n const { client: request = fetch, ...requestConfig } = config;\n\n const requestData = data;\n\n const res = await request<\n PutV1WorkoutsWorkoutidMutationResponse,\n ResponseErrorConfig<PutV1WorkoutsWorkoutid400>,\n PutV1WorkoutsWorkoutidMutationRequest\n >({\n method: \"PUT\",\n url: getPutV1WorkoutsWorkoutidUrl(workoutId).url.toString(),\n data: requestData,\n ...requestConfig,\n headers: { ...headers, ...requestConfig.headers },\n });\n return res.data;\n}\n","import type {\n\tRequestConfig,\n\tResponseConfig,\n} from \"../generated/.kubb/fetch.ts\";\nimport * as api from \"../generated/client/api\";\nimport type {\n\tGetV1BodyMeasurementsQueryParams,\n\tGetV1ExerciseHistoryExercisetemplateidQueryParams,\n\tGetV1ExerciseTemplatesQueryParams,\n\tGetV1RoutineFoldersQueryParams,\n\tGetV1RoutinesQueryParams,\n\tGetV1WorkoutsEventsQueryParams,\n\tGetV1WorkoutsQueryParams,\n\tPostV1BodyMeasurementsMutationRequest,\n\tPostV1ExerciseTemplatesMutationRequest,\n\tPostV1RoutineFoldersMutationRequest,\n\tPostV1RoutinesMutationRequest,\n\tPostV1WorkoutsMutationRequest,\n\tPutV1BodyMeasurementsDateMutationRequest,\n\tPutV1RoutinesRoutineidMutationRequest,\n\tPutV1WorkoutsWorkoutidMutationRequest,\n} from \"../generated/client/types\";\nimport {\n\tHEVY_REQUEST_ABORTED_ERROR_CODE,\n\tHEVY_RETRY_EXHAUSTED_ERROR_CODE,\n\tHevyHttpError,\n\tisHevyHttpError,\n} from \"./hevy-http-error.js\";\nimport type {\n\tMcpClientLogger,\n\tMcpClientLogMessage,\n} from \"./mcp-client-logger.js\";\n\ntype KubbClient = {\n\t<TData, _TError = unknown, TVariables = unknown>(\n\t\tconfig: RequestConfig<TVariables>,\n\t): Promise<ResponseConfig<TData>>;\n\tgetConfig: () => Partial<RequestConfig<unknown>>;\n\tsetConfig: (config: RequestConfig) => Partial<RequestConfig<unknown>>;\n};\n\nexport interface HevyRequestObservation {\n\tmethod: string;\n\tendpoint: string;\n\tstatus: number;\n\tdurationMs: number;\n\terror?: HevyHttpError;\n}\n\nexport interface HevyClientOptions {\n\tfetch?: typeof globalThis.fetch;\n\tlogger?: McpClientLogger;\n\tmaxGetRetries?: number;\n\tonRequestComplete?: (observation: HevyRequestObservation) => void;\n\tsleep?: (milliseconds: number) => Promise<void>;\n\ttimeoutMs?: number;\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = 30_000;\nexport const MAX_GET_RETRIES = 3;\nexport const RETRY_BACKOFF_BASE_MS = 300;\nexport { HEVY_RETRY_EXHAUSTED_ERROR_CODE };\nexport { HEVY_REQUEST_ABORTED_ERROR_CODE };\n\nconst RETRY_BACKOFF_MAX_MS = 5_000;\nconst RETRYABLE_STATUS_CODES = new Set([408, 429]);\nconst SAFE_STATIC_ENDPOINTS = new Set([\n\t\"/v1/body_measurements\",\n\t\"/v1/exercise_templates\",\n\t\"/v1/routine_folders\",\n\t\"/v1/routines\",\n\t\"/v1/user/info\",\n\t\"/v1/workouts\",\n\t\"/v1/workouts/count\",\n\t\"/v1/workouts/events\",\n]);\nconst SAFE_DYNAMIC_ENDPOINTS = [\n\t[\"/v1/body_measurements/\", \"/v1/body_measurements/:date\"],\n\t[\"/v1/exercise_history/\", \"/v1/exercise_history/:exerciseTemplateId\"],\n\t[\"/v1/exercise_templates/\", \"/v1/exercise_templates/:exerciseTemplateId\"],\n\t[\"/v1/routine_folders/\", \"/v1/routine_folders/:folderId\"],\n\t[\"/v1/routines/\", \"/v1/routines/:routineId\"],\n\t[\"/v1/workouts/\", \"/v1/workouts/:workoutId\"],\n] as const;\n\nfunction normalizePositiveInteger(value: number | undefined, fallback: number) {\n\treturn value === undefined || !Number.isFinite(value) || value <= 0\n\t\t? fallback\n\t\t: Math.max(1, Math.floor(value));\n}\n\nfunction normalizeMaxGetRetries(value: number | undefined) {\n\treturn value === undefined || !Number.isFinite(value) || value < 0\n\t\t? MAX_GET_RETRIES\n\t\t: Math.floor(value);\n}\n\nfunction defaultSleep(milliseconds: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nfunction getRequestContext(config: { method?: string; url?: string }) {\n\tconst method = (config.method ?? \"GET\").toUpperCase();\n\tconst rawEndpoint = (config.url ?? \"\").split(\"?\")[0] ?? \"\";\n\tlet endpoint = \"unknown\";\n\tif (SAFE_STATIC_ENDPOINTS.has(rawEndpoint)) {\n\t\tendpoint = rawEndpoint;\n\t} else {\n\t\tendpoint =\n\t\t\tSAFE_DYNAMIC_ENDPOINTS.find(([prefix]) =>\n\t\t\t\trawEndpoint.startsWith(prefix),\n\t\t\t)?.[1] ?? \"unknown\";\n\t}\n\treturn { method, endpoint };\n}\n\nfunction emitClientLog(\n\tlogger: McpClientLogger | undefined,\n\tmessage: McpClientLogMessage,\n): void {\n\ttry {\n\t\tlogger?.(message);\n\t} catch {\n\t\tconsole.error(\"Failed to emit structured Hevy API log\");\n\t}\n}\n\nfunction parseRetryAfterMs(value: string | null): number | undefined {\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) {\n\t\treturn Math.min(RETRY_BACKOFF_MAX_MS, Math.round(seconds * 1_000));\n\t}\n\tconst dateMillis = Date.parse(value);\n\treturn Number.isNaN(dateMillis)\n\t\t? undefined\n\t\t: Math.min(RETRY_BACKOFF_MAX_MS, Math.max(0, dateMillis - Date.now()));\n}\n\nfunction getRetryDelayMs(error: HevyHttpError, retryAttempt: number): number {\n\tconst exponential = Math.min(\n\t\tRETRY_BACKOFF_MAX_MS,\n\t\tRETRY_BACKOFF_BASE_MS * 2 ** Math.max(0, retryAttempt - 1),\n\t);\n\tconst retryAfter =\n\t\terror.status === 429\n\t\t\t? parseRetryAfterMs(error.headers?.get(\"retry-after\") ?? null)\n\t\t\t: undefined;\n\treturn retryAfter === undefined\n\t\t? exponential\n\t\t: Math.min(RETRY_BACKOFF_MAX_MS, Math.max(exponential, retryAfter));\n}\n\nfunction buildUrl(baseUrl: string, config: RequestConfig<unknown>): URL {\n\tif (!config.url?.startsWith(\"/v1/\")) {\n\t\tthrow new HevyHttpError(\"Invalid Hevy API endpoint\", {\n\t\t\tmethod: config.method ?? \"GET\",\n\t\t\tendpoint: \"unknown\",\n\t\t\tcode: \"HEVY_INVALID_ENDPOINT\",\n\t\t});\n\t}\n\tconst url = new URL(config.url, baseUrl);\n\tif (config.params && typeof config.params === \"object\") {\n\t\tfor (const [key, value] of Object.entries(config.params)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\turl.searchParams.append(key, value === null ? \"null\" : String(value));\n\t\t\t}\n\t\t}\n\t}\n\treturn url;\n}\n\nasync function parseResponseData(response: Response): Promise<unknown> {\n\tif ([204, 205, 304].includes(response.status) || !response.body) return {};\n\tconst text = await response.text();\n\tif (!text) return {};\n\ttry {\n\t\treturn JSON.parse(text) as unknown;\n\t} catch {\n\t\treturn text;\n\t}\n}\n\nfunction getNetworkCode(error: unknown): string {\n\treturn error instanceof DOMException && error.name === \"AbortError\"\n\t\t? \"ETIMEDOUT\"\n\t\t: \"ERR_NETWORK\";\n}\n\nfunction isRetryable(error: HevyHttpError): boolean {\n\tif (error.code === HEVY_REQUEST_ABORTED_ERROR_CODE) return false;\n\treturn (\n\t\terror.status === undefined ||\n\t\tRETRYABLE_STATUS_CODES.has(error.status) ||\n\t\t(error.status >= 500 && error.status <= 599)\n\t);\n}\n\nfunction createNativeClient(\n\tapiKey: string,\n\tbaseUrl: string,\n\toptions: HevyClientOptions,\n): KubbClient {\n\tconst fetchImplementation = options.fetch ?? globalThis.fetch;\n\tconst maxGetRetries = normalizeMaxGetRetries(options.maxGetRetries);\n\tconst timeoutMs = normalizePositiveInteger(\n\t\toptions.timeoutMs,\n\t\tDEFAULT_API_TIMEOUT_MS,\n\t);\n\tconst sleep = options.sleep ?? defaultSleep;\n\tlet clientConfig: Partial<RequestConfig<unknown>> = { baseURL: baseUrl };\n\n\tconst client = (async <TData, _TError = unknown, TVariables = unknown>(\n\t\tconfig: RequestConfig<TVariables>,\n\t): Promise<ResponseConfig<TData>> => {\n\t\tconst normalized = { ...clientConfig, ...config } as RequestConfig<unknown>;\n\t\tconst { method, endpoint } = getRequestContext(normalized);\n\t\tconst url = buildUrl(baseUrl, normalized);\n\t\tlet retryCount = 0;\n\n\t\twhile (true) {\n\t\t\tif (normalized.signal?.aborted) {\n\t\t\t\tthrow new HevyHttpError(\"Hevy API request was canceled\", {\n\t\t\t\t\tmethod,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tcode: HEVY_REQUEST_ABORTED_ERROR_CODE,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst startedAt = Date.now();\n\t\t\tconst controller = new AbortController();\n\t\t\tconst abortFromCaller = () => controller.abort();\n\t\t\tnormalized.signal?.addEventListener(\"abort\", abortFromCaller, {\n\t\t\t\tonce: true,\n\t\t\t});\n\t\t\tconst timeout = setTimeout(() => controller.abort(), timeoutMs);\n\t\t\ttry {\n\t\t\t\tconst headers = new Headers({ \"api-key\": apiKey });\n\t\t\t\tif (\n\t\t\t\t\tnormalized.data !== undefined &&\n\t\t\t\t\t!(normalized.data instanceof FormData)\n\t\t\t\t) {\n\t\t\t\t\theaders.set(\"content-type\", \"application/json\");\n\t\t\t\t}\n\t\t\t\tconst response = await fetchImplementation(url, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t\tbody:\n\t\t\t\t\t\tnormalized.data instanceof FormData\n\t\t\t\t\t\t\t? normalized.data\n\t\t\t\t\t\t\t: normalized.data === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: JSON.stringify(normalized.data),\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t});\n\t\t\t\tconst data = await parseResponseData(response);\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new HevyHttpError(\n\t\t\t\t\t\t`Hevy API request failed (HTTP ${response.status})`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\theaders: response.headers,\n\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\toptions.onRequestComplete?.({\n\t\t\t\t\tmethod,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tdata: data as TData,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\tconst error = isHevyHttpError(cause)\n\t\t\t\t\t? cause\n\t\t\t\t\t: new HevyHttpError(\n\t\t\t\t\t\t\tnormalized.signal?.aborted\n\t\t\t\t\t\t\t\t? \"Hevy API request was canceled\"\n\t\t\t\t\t\t\t\t: \"Hevy API network request failed\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t\t\tcode: normalized.signal?.aborted\n\t\t\t\t\t\t\t\t\t? HEVY_REQUEST_ABORTED_ERROR_CODE\n\t\t\t\t\t\t\t\t\t: getNetworkCode(cause),\n\t\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\toptions.onRequestComplete?.({\n\t\t\t\t\tmethod,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tstatus: error.status ?? 0,\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tconst canRetry = method === \"GET\" && isRetryable(error);\n\t\t\t\tif (!canRetry) {\n\t\t\t\t\temitClientLog(options.logger, {\n\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\tlogger: \"hevy-api\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\tmessage: \"Hevy API request failed\",\n\t\t\t\t\t\t\tstatus: error.status ?? null,\n\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (retryCount >= maxGetRetries) {\n\t\t\t\t\terror.hevyRetryExhausted = true;\n\t\t\t\t\terror.hevyRetryCount = retryCount;\n\t\t\t\t\terror.code = HEVY_RETRY_EXHAUSTED_ERROR_CODE;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tretryCount += 1;\n\t\t\t\tconst delayMs = getRetryDelayMs(error, retryCount);\n\t\t\t\temitClientLog(options.logger, {\n\t\t\t\t\tlevel: error.status === 429 ? \"warning\" : \"debug\",\n\t\t\t\t\tlogger: \"hevy-api\",\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tmessage: \"Retrying Hevy API request\",\n\t\t\t\t\t\tstatus: error.status ?? null,\n\t\t\t\t\t\tattempt: retryCount + 1,\n\t\t\t\t\t\tmaxAttempts: maxGetRetries + 1,\n\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tendpoint,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tawait sleep(delayMs);\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tnormalized.signal?.removeEventListener(\"abort\", abortFromCaller);\n\t\t\t}\n\t\t}\n\t}) as KubbClient;\n\n\tclient.getConfig = () => ({ ...clientConfig });\n\tclient.setConfig = (config: RequestConfig) => {\n\t\tclientConfig = { ...clientConfig, ...config, baseURL: baseUrl };\n\t\treturn client.getConfig();\n\t};\n\treturn client;\n}\n\nexport function createClient(\n\tapiKey: string,\n\tbaseUrl = \"https://api.hevyapp.com\",\n\toptions: HevyClientOptions = {},\n) {\n\tconst headers = { \"api-key\": apiKey };\n\tconst client = createNativeClient(apiKey, baseUrl, options);\n\treturn {\n\t\tgetWorkouts: (\n\t\t\tparams?: GetV1WorkoutsQueryParams,\n\t\t): ReturnType<typeof api.getV1Workouts> =>\n\t\t\tapi.getV1Workouts(headers, params, { client }),\n\t\tgetWorkout: (\n\t\t\tworkoutId: string,\n\t\t): ReturnType<typeof api.getV1WorkoutsWorkoutid> =>\n\t\t\tapi.getV1WorkoutsWorkoutid(workoutId, headers, { client }),\n\t\tcreateWorkout: (\n\t\t\tdata: PostV1WorkoutsMutationRequest,\n\t\t): ReturnType<typeof api.postV1Workouts> =>\n\t\t\tapi.postV1Workouts(data, headers, { client }),\n\t\tupdateWorkout: (\n\t\t\tworkoutId: string,\n\t\t\tdata: PutV1WorkoutsWorkoutidMutationRequest,\n\t\t): ReturnType<typeof api.putV1WorkoutsWorkoutid> =>\n\t\t\tapi.putV1WorkoutsWorkoutid(workoutId, data, headers, { client }),\n\t\tgetWorkoutCount: (): ReturnType<typeof api.getV1WorkoutsCount> =>\n\t\t\tapi.getV1WorkoutsCount(headers, { client }),\n\t\tgetWorkoutEvents: (\n\t\t\tparams?: GetV1WorkoutsEventsQueryParams,\n\t\t): ReturnType<typeof api.getV1WorkoutsEvents> =>\n\t\t\tapi.getV1WorkoutsEvents(headers, params, { client }),\n\t\tgetRoutines: (\n\t\t\tparams?: GetV1RoutinesQueryParams,\n\t\t): ReturnType<typeof api.getV1Routines> =>\n\t\t\tapi.getV1Routines(headers, params, { client }),\n\t\tgetRoutineById: (\n\t\t\troutineId: string,\n\t\t): ReturnType<typeof api.getV1RoutinesRoutineid> =>\n\t\t\tapi.getV1RoutinesRoutineid(routineId, headers, { client }),\n\t\tcreateRoutine: (\n\t\t\tdata: PostV1RoutinesMutationRequest,\n\t\t): ReturnType<typeof api.postV1Routines> =>\n\t\t\tapi.postV1Routines(data, headers, { client }),\n\t\tupdateRoutine: (\n\t\t\troutineId: string,\n\t\t\tdata: PutV1RoutinesRoutineidMutationRequest,\n\t\t): ReturnType<typeof api.putV1RoutinesRoutineid> =>\n\t\t\tapi.putV1RoutinesRoutineid(routineId, data, headers, { client }),\n\t\tgetExerciseTemplates: (\n\t\t\tparams?: GetV1ExerciseTemplatesQueryParams,\n\t\t): ReturnType<typeof api.getV1ExerciseTemplates> =>\n\t\t\tapi.getV1ExerciseTemplates(headers, params, { client }),\n\t\tgetExerciseTemplate: (\n\t\t\ttemplateId: string,\n\t\t): ReturnType<typeof api.getV1ExerciseTemplatesExercisetemplateid> =>\n\t\t\tapi.getV1ExerciseTemplatesExercisetemplateid(templateId, headers, {\n\t\t\t\tclient,\n\t\t\t}),\n\t\tgetExerciseHistory: (\n\t\t\texerciseTemplateId: string,\n\t\t\tparams?: GetV1ExerciseHistoryExercisetemplateidQueryParams,\n\t\t): ReturnType<typeof api.getV1ExerciseHistoryExercisetemplateid> =>\n\t\t\tapi.getV1ExerciseHistoryExercisetemplateid(\n\t\t\t\texerciseTemplateId,\n\t\t\t\theaders,\n\t\t\t\tparams,\n\t\t\t\t{ client },\n\t\t\t),\n\t\tcreateExerciseTemplate: (\n\t\t\tdata: PostV1ExerciseTemplatesMutationRequest,\n\t\t): ReturnType<typeof api.postV1ExerciseTemplates> =>\n\t\t\tapi.postV1ExerciseTemplates(data, headers, { client }),\n\t\tgetRoutineFolders: (\n\t\t\tparams?: GetV1RoutineFoldersQueryParams,\n\t\t): ReturnType<typeof api.getV1RoutineFolders> =>\n\t\t\tapi.getV1RoutineFolders(headers, params, { client }),\n\t\tcreateRoutineFolder: (\n\t\t\tdata: PostV1RoutineFoldersMutationRequest,\n\t\t): ReturnType<typeof api.postV1RoutineFolders> =>\n\t\t\tapi.postV1RoutineFolders(data, headers, { client }),\n\t\tgetRoutineFolder: (\n\t\t\tfolderId: string,\n\t\t): ReturnType<typeof api.getV1RoutineFoldersFolderid> =>\n\t\t\tapi.getV1RoutineFoldersFolderid(folderId, headers, { client }),\n\t\tgetBodyMeasurements: (\n\t\t\tparams?: GetV1BodyMeasurementsQueryParams,\n\t\t): ReturnType<typeof api.getV1BodyMeasurements> =>\n\t\t\tapi.getV1BodyMeasurements(headers, params, { client }),\n\t\tgetBodyMeasurement: (\n\t\t\tdate: string,\n\t\t): ReturnType<typeof api.getV1BodyMeasurementsDate> =>\n\t\t\tapi.getV1BodyMeasurementsDate(date, headers, { client }),\n\t\tcreateBodyMeasurement: (\n\t\t\tdata: PostV1BodyMeasurementsMutationRequest,\n\t\t): ReturnType<typeof api.postV1BodyMeasurements> =>\n\t\t\tapi.postV1BodyMeasurements(data, headers, { client }),\n\t\tupdateBodyMeasurement: (\n\t\t\tdate: string,\n\t\t\tdata: PutV1BodyMeasurementsDateMutationRequest,\n\t\t): ReturnType<typeof api.putV1BodyMeasurementsDate> =>\n\t\t\tapi.putV1BodyMeasurementsDate(date, data, headers, { client }),\n\t\tgetUserInfo: (\n\t\t\tconfig: Partial<RequestConfig> = {},\n\t\t): ReturnType<typeof api.getV1UserInfo> =>\n\t\t\tapi.getV1UserInfo(headers, { ...config, client }),\n\t};\n}\n","import type {\n\tGetV1BodyMeasurementsQueryParams,\n\tGetV1BodyMeasurementsQueryResponse,\n\tGetV1BodyMeasurementsDateQueryResponse,\n\tGetV1ExerciseHistoryExercisetemplateidQueryParams,\n\tGetV1ExerciseHistoryExercisetemplateidQueryResponse,\n\tGetV1ExerciseTemplatesQueryParams,\n\tGetV1ExerciseTemplatesQueryResponse,\n\tGetV1ExerciseTemplatesExercisetemplateidQueryResponse,\n\tGetV1RoutineFoldersQueryParams,\n\tGetV1RoutineFoldersQueryResponse,\n\tGetV1RoutineFoldersFolderidQueryResponse,\n\tGetV1RoutinesQueryParams,\n\tGetV1RoutinesQueryResponse,\n\tGetV1RoutinesRoutineidQueryResponse,\n\tGetV1UserInfoQueryResponse,\n\tGetV1WorkoutsEventsQueryParams,\n\tGetV1WorkoutsEventsQueryResponse,\n\tGetV1WorkoutsQueryParams,\n\tGetV1WorkoutsQueryResponse,\n\tGetV1WorkoutsCountQueryResponse,\n\tGetV1WorkoutsWorkoutidQueryResponse,\n\tPostV1BodyMeasurementsMutationRequest,\n\tPostV1BodyMeasurementsMutationResponse,\n\tPostV1ExerciseTemplatesMutationRequest,\n\tPostV1ExerciseTemplatesMutationResponse,\n\tPostV1RoutineFoldersMutationRequest,\n\tPostV1RoutineFoldersMutationResponse,\n\tPostV1RoutinesMutationRequest,\n\tPostV1RoutinesMutationResponse,\n\tPostV1WorkoutsMutationRequest,\n\tPostV1WorkoutsMutationResponse,\n\tPutV1BodyMeasurementsDateMutationRequest,\n\tPutV1BodyMeasurementsDateMutationResponse,\n\tPutV1RoutinesRoutineidMutationRequest,\n\tPutV1RoutinesRoutineidMutationResponse,\n\tPutV1WorkoutsWorkoutidMutationRequest,\n\tPutV1WorkoutsWorkoutidMutationResponse,\n} from \"../generated/client/types\";\nimport type { RequestConfig } from \"../generated/.kubb/fetch.ts\";\nimport { createClient as createKubbClient } from \"./hevyClientKubb.js\";\nimport type { HevyClientOptions } from \"./hevyClientKubb.js\";\n\nexport type { HevyClientOptions };\n\nexport interface HevyClient {\n\tgetWorkouts(\n\t\tparams?: GetV1WorkoutsQueryParams,\n\t): Promise<GetV1WorkoutsQueryResponse>;\n\tgetWorkout(workoutId: string): Promise<GetV1WorkoutsWorkoutidQueryResponse>;\n\tcreateWorkout(\n\t\tdata: PostV1WorkoutsMutationRequest,\n\t): Promise<PostV1WorkoutsMutationResponse>;\n\tupdateWorkout(\n\t\tworkoutId: string,\n\t\tdata: PutV1WorkoutsWorkoutidMutationRequest,\n\t): Promise<PutV1WorkoutsWorkoutidMutationResponse>;\n\tgetWorkoutCount(): Promise<GetV1WorkoutsCountQueryResponse>;\n\tgetWorkoutEvents(\n\t\tparams?: GetV1WorkoutsEventsQueryParams,\n\t): Promise<GetV1WorkoutsEventsQueryResponse>;\n\tgetRoutines(\n\t\tparams?: GetV1RoutinesQueryParams,\n\t): Promise<GetV1RoutinesQueryResponse>;\n\tgetRoutineById(\n\t\troutineId: string,\n\t): Promise<GetV1RoutinesRoutineidQueryResponse>;\n\tcreateRoutine(\n\t\tdata: PostV1RoutinesMutationRequest,\n\t): Promise<PostV1RoutinesMutationResponse>;\n\tupdateRoutine(\n\t\troutineId: string,\n\t\tdata: PutV1RoutinesRoutineidMutationRequest,\n\t): Promise<PutV1RoutinesRoutineidMutationResponse>;\n\tgetExerciseTemplates(\n\t\tparams?: GetV1ExerciseTemplatesQueryParams,\n\t): Promise<GetV1ExerciseTemplatesQueryResponse>;\n\tgetExerciseTemplate(\n\t\ttemplateId: string,\n\t): Promise<GetV1ExerciseTemplatesExercisetemplateidQueryResponse>;\n\tgetExerciseHistory(\n\t\texerciseTemplateId: string,\n\t\tparams?: GetV1ExerciseHistoryExercisetemplateidQueryParams,\n\t): Promise<GetV1ExerciseHistoryExercisetemplateidQueryResponse>;\n\tcreateExerciseTemplate(\n\t\tdata: PostV1ExerciseTemplatesMutationRequest,\n\t): Promise<PostV1ExerciseTemplatesMutationResponse>;\n\tgetRoutineFolders(\n\t\tparams?: GetV1RoutineFoldersQueryParams,\n\t): Promise<GetV1RoutineFoldersQueryResponse>;\n\tcreateRoutineFolder(\n\t\tdata: PostV1RoutineFoldersMutationRequest,\n\t): Promise<PostV1RoutineFoldersMutationResponse>;\n\tgetRoutineFolder(\n\t\tfolderId: string,\n\t): Promise<GetV1RoutineFoldersFolderidQueryResponse>;\n\tgetBodyMeasurements(\n\t\tparams?: GetV1BodyMeasurementsQueryParams,\n\t): Promise<GetV1BodyMeasurementsQueryResponse>;\n\tgetBodyMeasurement(\n\t\tdate: string,\n\t): Promise<GetV1BodyMeasurementsDateQueryResponse>;\n\tcreateBodyMeasurement(\n\t\tdata: PostV1BodyMeasurementsMutationRequest,\n\t): Promise<PostV1BodyMeasurementsMutationResponse>;\n\tupdateBodyMeasurement(\n\t\tdate: string,\n\t\tdata: PutV1BodyMeasurementsDateMutationRequest,\n\t): Promise<PutV1BodyMeasurementsDateMutationResponse>;\n\tgetUserInfo(\n\t\tconfig?: Partial<RequestConfig>,\n\t): Promise<GetV1UserInfoQueryResponse>;\n}\n\nexport function createClient(\n\tapiKey: string,\n\tbaseUrl?: string,\n\toptions: HevyClientOptions = {},\n): HevyClient {\n\treturn createKubbClient(apiKey, baseUrl, options);\n}\n","import type { LoggingMessageNotification } from \"@modelcontextprotocol/sdk/types.js\";\nimport { createSafeErrorDiagnostic } from \"./safe-error-diagnostic.js\";\n\nexport type McpClientLogMessage = LoggingMessageNotification[\"params\"];\nexport type McpClientLogger = (message: McpClientLogMessage) => void;\n\ninterface LoggingServer {\n\tisConnected(): boolean;\n\tsendLoggingMessage(message: McpClientLogMessage): Promise<void>;\n}\n\nconst SEND_FAILURE_MESSAGE =\n\t\"Failed to send structured log message to MCP client\";\nconst DISCONNECTED_MESSAGE =\n\t\"Skipped structured MCP client log because the server is not connected\";\n\n/**\n * Create a best-effort, fire-and-forget logger for an MCP server connection.\n * Logging failures are reported to stderr and never escape into tool behavior.\n */\nexport function createMcpClientLogger(server: LoggingServer): McpClientLogger {\n\treturn (message) => {\n\t\ttry {\n\t\t\tif (!server.isConnected()) {\n\t\t\t\tconsole.error(DISCONNECTED_MESSAGE);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvoid server.sendLoggingMessage(message).catch((error: unknown) => {\n\t\t\t\tconsole.error(SEND_FAILURE_MESSAGE, createSafeErrorDiagnostic(error));\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(SEND_FAILURE_MESSAGE, createSafeErrorDiagnostic(error));\n\t\t}\n\t};\n}\n","import type { McpClientLogger } from \"../utils/mcp-client-logger.js\";\nimport type { HevyClient } from \"../utils/hevyClient.js\";\nimport {\n\tHEVY_CLIENT_NOT_INITIALIZED_ERROR,\n\trequireClient,\n} from \"../utils/tool-helpers.js\";\nimport { withErrorHandling } from \"../utils/error-handler.js\";\nimport type { ExerciseTemplateCatalog } from \"../utils/exercise-template-catalog.js\";\nimport type { McpToolResponse } from \"../utils/response-formatter.js\";\n\nexport type ToolHandler = (\n\targs: Record<string, unknown>,\n) => Promise<McpToolResponse>;\n\nexport interface ToolRuntime {\n\treadonly client: HevyClient | null;\n\treadonly catalog: ExerciseTemplateCatalog;\n\treadonly logger?: McpClientLogger;\n\treadonly wrapHandler: typeof withErrorHandling;\n\tgetClient(): HevyClient;\n}\n\nexport interface CreateToolRuntimeOptions {\n\tclient: HevyClient | null;\n\tcatalog: ExerciseTemplateCatalog;\n\tlogger?: McpClientLogger;\n\twrapHandler?: typeof withErrorHandling;\n}\n\nexport function createToolRuntime({\n\tclient,\n\tcatalog,\n\tlogger,\n\twrapHandler = withErrorHandling,\n}: CreateToolRuntimeOptions): ToolRuntime {\n\treturn {\n\t\tclient,\n\t\tcatalog,\n\t\tlogger,\n\t\twrapHandler,\n\t\tgetClient: () => requireClient(client),\n\t};\n}\n\nexport { HEVY_CLIENT_NOT_INITIALIZED_ERROR };\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { registerWorkoutPrompts } from \"./prompts/workouts.js\";\nimport { registerHevyResources } from \"./resources/hevy.js\";\nimport {\n\tSERVER_INSTRUCTIONS,\n\tSERVER_NAME,\n\tSERVER_VERSION,\n} from \"./server-metadata.js\";\nimport { registerHevyTools } from \"./tools/register.js\";\nimport { withErrorHandling } from \"./utils/error-handler.js\";\nimport { createExerciseTemplateCatalog } from \"./utils/exercise-template-catalog.js\";\nimport { createClient } from \"./utils/hevyClient.js\";\nimport type { HevyClient } from \"./utils/hevyClient.js\";\nimport type { HevyClientOptions } from \"./utils/hevyClientKubb.js\";\nimport { createMcpClientLogger } from \"./utils/mcp-client-logger.js\";\nimport { createToolRuntime } from \"./tools/tool-runtime.js\";\n\nexport interface SharedServerOptions {\n\tapiKey: string;\n\tclientOptions?: HevyClientOptions;\n\thevyClient?: HevyClient;\n\tonToolsRegistered?: (count: number) => void;\n\twrapHandler?: typeof withErrorHandling;\n\twrapServer?: (server: McpServer) => McpServer;\n}\n\nfunction createToolCountingServer(server: McpServer) {\n\tlet count = 0;\n\tconst countingServer = new Proxy(server, {\n\t\tget(target, property, receiver) {\n\t\t\tif (property === \"tool\") {\n\t\t\t\treturn (...args: Parameters<McpServer[\"tool\"]>) => {\n\t\t\t\t\tconst result = target.tool(...args);\n\t\t\t\t\tcount += 1;\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (property === \"registerTool\") {\n\t\t\t\tconst registerTool: McpServer[\"registerTool\"] = (\n\t\t\t\t\tname,\n\t\t\t\t\tconfig,\n\t\t\t\t\tcallback,\n\t\t\t\t) => {\n\t\t\t\t\tconst result = target.registerTool(name, config, callback);\n\t\t\t\t\tcount += 1;\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\t\t\t\treturn registerTool;\n\t\t\t}\n\t\t\treturn Reflect.get(target, property, receiver);\n\t\t},\n\t});\n\treturn { server: countingServer, getCount: () => count };\n}\n\n/** Construct and register a complete MCP server without importing Node-only code. */\nexport function createSharedMcpServer(options: SharedServerOptions): McpServer {\n\tconst baseServer = new McpServer(\n\t\t{ name: SERVER_NAME, version: SERVER_VERSION },\n\t\t{ capabilities: { logging: {} }, instructions: SERVER_INSTRUCTIONS },\n\t);\n\tconst server = options.wrapServer?.(baseServer) ?? baseServer;\n\tconst logger = createMcpClientLogger(server);\n\tconst hevyClient =\n\t\toptions.hevyClient ??\n\t\tcreateClient(options.apiKey, \"https://api.hevyapp.com\", {\n\t\t\t...options.clientOptions,\n\t\t\tlogger,\n\t\t});\n\tconst runtime = createToolRuntime({\n\t\tclient: hevyClient,\n\t\tcatalog: createExerciseTemplateCatalog(hevyClient),\n\t\tlogger,\n\t\twrapHandler: options.wrapHandler ?? withErrorHandling,\n\t});\n\tconst counting = createToolCountingServer(server);\n\n\tregisterHevyTools(counting.server, runtime);\n\toptions.onToolsRegistered?.(counting.getCount());\n\n\tregisterWorkoutPrompts(server);\n\tregisterHevyResources(server, runtime);\n\treturn server;\n}\n","export interface HevyConfig {\n\tapiKey?: string;\n}\n\nexport function parseConfig(env: NodeJS.ProcessEnv): HevyConfig {\n\treturn {\n\t\tapiKey: env.HEVY_API_KEY || \"\",\n\t};\n}\n\nexport function assertApiKey(\n\tapiKey: string | undefined,\n): asserts apiKey is string {\n\tif (!apiKey) {\n\t\tconsole.error(\n\t\t\t\"Hevy API key is required. Provide it via the HEVY_API_KEY environment variable.\",\n\t\t);\n\t\tprocess.exit(1);\n\t}\n}\n","export type ShutdownSignal = \"SIGINT\" | \"SIGTERM\";\n\ninterface CloseTarget {\n\tclose(): Promise<void>;\n}\n\ninterface ProcessLike {\n\texitCode?: number | string | null;\n\texit(code?: number | string | null): never;\n\ton(signal: ShutdownSignal, listener: () => void): unknown;\n\tremoveListener(signal: ShutdownSignal, listener: () => void): unknown;\n}\n\ninterface FlushableStdout {\n\twrite(chunk: string, callback: (error?: Error | null) => void): boolean;\n}\n\ninterface ForcedExitTimer {\n\tunref(): void;\n}\n\ntype ScheduleForcedExit = (\n\tcallback: () => void,\n\ttimeoutMs: number,\n) => ForcedExitTimer;\n\ninterface GracefulShutdownOptions {\n\ttarget: CloseTarget;\n\tprocess?: ProcessLike;\n\tlogError?: (message: string) => void;\n\tflush?: () => Promise<void>;\n\tforcedExitTimeoutMs?: number;\n\tscheduleForcedExit?: ScheduleForcedExit;\n}\n\nexport interface GracefulShutdownController {\n\tcleanup(): void;\n\tgetShutdownPromise(): Promise<void> | undefined;\n}\n\nconst shutdownSignals: ShutdownSignal[] = [\"SIGINT\", \"SIGTERM\"];\n\n// Long enough for normal stdio flushing, but bounded so unrelated handles or a\n// stalled close cannot keep a signal-terminated process alive indefinitely.\nexport const FORCED_EXIT_TIMEOUT_MS = 5_000;\n\nexport function flushStdout(\n\tstdout: FlushableStdout = process.stdout,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\ttry {\n\t\t\tstdout.write(\"\", (error) => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve();\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\t});\n}\n\nexport function installGracefulShutdown({\n\ttarget,\n\tprocess: processLike = process,\n\tlogError = console.error,\n\tflush = flushStdout,\n\tforcedExitTimeoutMs = FORCED_EXIT_TIMEOUT_MS,\n\tscheduleForcedExit = setTimeout,\n}: GracefulShutdownOptions): GracefulShutdownController {\n\tlet listenersInstalled = true;\n\tlet shutdownSettled = false;\n\tlet shutdownPromise: Promise<void> | undefined;\n\n\tconst cleanup = () => {\n\t\tif (!listenersInstalled || (shutdownPromise && !shutdownSettled)) {\n\t\t\treturn;\n\t\t}\n\n\t\tlistenersInstalled = false;\n\t\tfor (const signal of shutdownSignals) {\n\t\t\tconst listener = signalListeners.get(signal);\n\t\t\tif (listener) {\n\t\t\t\tprocessLike.removeListener(signal, listener);\n\t\t\t}\n\t\t}\n\t};\n\n\tconst handleSignal = (signal: ShutdownSignal) => {\n\t\tif (shutdownPromise) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (processLike.exitCode == null) {\n\t\t\tprocessLike.exitCode = 0;\n\t\t}\n\n\t\tconst forcedExitTimer = scheduleForcedExit(() => {\n\t\t\tprocessLike.exit(processLike.exitCode ?? 0);\n\t\t}, forcedExitTimeoutMs);\n\t\t// This fallback must survive successful shutdown so it can terminate a\n\t\t// process held open by unrelated handles, without keeping the process alive\n\t\t// when the event loop drains normally.\n\t\tforcedExitTimer.unref();\n\n\t\tshutdownPromise = (async () => {\n\t\t\tlogError(`Shutting down gracefully after ${signal}`);\n\t\t\tlet shutdownFailed = false;\n\t\t\tlet shutdownError: unknown;\n\n\t\t\ttry {\n\t\t\t\tawait target.close();\n\t\t\t} catch (error) {\n\t\t\t\tshutdownFailed = true;\n\t\t\t\tshutdownError = error;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait flush();\n\t\t\t} catch (error) {\n\t\t\t\tif (!shutdownFailed) {\n\t\t\t\t\tshutdownError = error;\n\t\t\t\t}\n\t\t\t\tshutdownFailed = true;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (shutdownFailed) {\n\t\t\t\t\tconst message =\n\t\t\t\t\t\tshutdownError instanceof Error\n\t\t\t\t\t\t\t? shutdownError.message\n\t\t\t\t\t\t\t: \"Unknown shutdown error\";\n\t\t\t\t\tlogError(`Graceful shutdown failed: ${message}`);\n\t\t\t\t\tprocessLike.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tshutdownSettled = true;\n\t\t\t\tcleanup();\n\t\t\t}\n\t\t})();\n\t};\n\tconst signalListeners = new Map<ShutdownSignal, () => void>(\n\t\tshutdownSignals.map((signal) => [signal, () => handleSignal(signal)]),\n\t);\n\n\tfor (const signal of shutdownSignals) {\n\t\tconst listener = signalListeners.get(signal);\n\t\tif (listener) {\n\t\t\tprocessLike.on(signal, listener);\n\t\t}\n\t}\n\n\treturn {\n\t\tcleanup,\n\t\tgetShutdownPromise: () => shutdownPromise,\n\t};\n}\n","const DEBUG_PREFIX = \"[hevy-mcp:debug] \";\nconst MAX_DEBUG_RECORD_LENGTH = 8_192;\nconst MAX_REDACTION_DEPTH = 4;\nconst MAX_OBJECT_KEYS = 20;\n\ntype RedactedValue =\n\t| number\n\t| string\n\t| {\n\t\t\ttype: \"array\";\n\t\t\tlength: number;\n\t\t\titems: Record<string, RedactedValue> | \"[max-depth]\";\n\t\t\ttruncatedItems?: number;\n\t }\n\t| {\n\t\t\ttype: \"object\";\n\t\t\tfieldCount: number;\n\t\t\tfields: Record<string, RedactedValue> | \"[max-depth]\";\n\t\t\ttruncatedFields?: number;\n\t };\n\nexport function isDebugEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn env.HEVY_MCP_DEBUG === \"1\";\n}\n\nfunction redactValue(\n\tvalue: unknown,\n\tdepth: number,\n\tseen: WeakSet<object>,\n): RedactedValue {\n\tif (value === null) {\n\t\treturn \"[null]\";\n\t}\n\n\tif (typeof value !== \"object\") {\n\t\treturn `[${typeof value}]`;\n\t}\n\n\tif (seen.has(value)) {\n\t\treturn \"[circular]\";\n\t}\n\n\tif (Array.isArray(value)) {\n\t\tconst lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n\t\tconst length =\n\t\t\tlengthDescriptor &&\n\t\t\t\"value\" in lengthDescriptor &&\n\t\t\ttypeof lengthDescriptor.value === \"number\"\n\t\t\t\t? lengthDescriptor.value\n\t\t\t\t: 0;\n\t\tif (depth >= MAX_REDACTION_DEPTH) {\n\t\t\treturn { type: \"array\", length, items: \"[max-depth]\" };\n\t\t}\n\n\t\tseen.add(value);\n\t\ttry {\n\t\t\tconst itemCount = Math.min(length, MAX_OBJECT_KEYS);\n\t\t\tconst items: Record<string, RedactedValue> = {};\n\t\t\tfor (let index = 0; index < itemCount; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\t\t\tvalue,\n\t\t\t\t\tString(index),\n\t\t\t\t);\n\t\t\t\titems[`item-${index + 1}`] =\n\t\t\t\t\tdescriptor && \"value\" in descriptor\n\t\t\t\t\t\t? redactValue(descriptor.value, depth + 1, seen)\n\t\t\t\t\t\t: \"[empty-or-accessor]\";\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\ttype: \"array\",\n\t\t\t\tlength,\n\t\t\t\titems,\n\t\t\t\t...(length > MAX_OBJECT_KEYS\n\t\t\t\t\t? { truncatedItems: length - MAX_OBJECT_KEYS }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t} finally {\n\t\t\tseen.delete(value);\n\t\t}\n\t}\n\n\tconst keys = Object.keys(value);\n\tif (depth >= MAX_REDACTION_DEPTH) {\n\t\treturn {\n\t\t\ttype: \"object\",\n\t\t\tfieldCount: keys.length,\n\t\t\tfields: \"[max-depth]\",\n\t\t};\n\t}\n\n\tseen.add(value);\n\ttry {\n\t\tconst fields: Record<string, RedactedValue> = {};\n\t\tfor (const [index, rawKey] of keys.slice(0, MAX_OBJECT_KEYS).entries()) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, rawKey);\n\t\t\tfields[`field-${index + 1}`] =\n\t\t\t\tdescriptor && \"value\" in descriptor\n\t\t\t\t\t? redactValue(descriptor.value, depth + 1, seen)\n\t\t\t\t\t: \"[accessor]\";\n\t\t}\n\n\t\treturn {\n\t\t\ttype: \"object\",\n\t\t\tfieldCount: keys.length,\n\t\t\tfields,\n\t\t\t...(keys.length > MAX_OBJECT_KEYS\n\t\t\t\t? { truncatedFields: keys.length - MAX_OBJECT_KEYS }\n\t\t\t\t: {}),\n\t\t};\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Redact every input scalar while preserving bounded argument structure. */\nexport function redactToolArgs(args: unknown): RedactedValue {\n\ttry {\n\t\treturn redactValue(args, 0, new WeakSet<object>());\n\t} catch {\n\t\treturn \"[unavailable]\";\n\t}\n}\n\n/**\n * Write a single bounded structured debug record to stderr without throwing.\n */\nexport function debugLog(event: string, data: Record<string, unknown>): void {\n\tif (!isDebugEnabled()) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tconst record = JSON.stringify({ event, ...data });\n\t\tconst output =\n\t\t\trecord.length <= MAX_DEBUG_RECORD_LENGTH\n\t\t\t\t? record\n\t\t\t\t: JSON.stringify({ event, truncated: true });\n\t\tprocess.stderr.write(`${DEBUG_PREFIX}${output}\\n`);\n\t} catch {\n\t\t// Diagnostics must never affect tool or API behavior.\n\t}\n}\n","import { SpanStatusCode } from \"@opentelemetry/api\";\nimport { debugLog } from \"./debug.js\";\nimport type { HevyClientOptions } from \"./hevyClientKubb.js\";\nimport { apiCalls, apiDuration } from \"./metrics.js\";\nimport { createSafeErrorDiagnostic } from \"./safe-error-diagnostic.js\";\nimport { tracer } from \"./telemetry.js\";\n\n/** Node-only adapter; the Worker graph never imports telemetry or metrics. */\nexport function createNodeHevyClientOptions(): HevyClientOptions {\n\tconst rawTimeout = process.env.HEVY_MCP_API_TIMEOUT;\n\tconst parsedTimeout = rawTimeout ? Number(rawTimeout) : Number.NaN;\n\tconst timeoutMs =\n\t\tNumber.isFinite(parsedTimeout) && parsedTimeout > 0\n\t\t\t? Math.floor(parsedTimeout)\n\t\t\t: undefined;\n\treturn {\n\t\t...(timeoutMs ? { timeoutMs } : {}),\n\t\tonRequestComplete(observation) {\n\t\t\tconst span = tracer.startSpan(`hevy.api.${observation.method}`, {\n\t\t\t\tattributes: {\n\t\t\t\t\t\"http.method\": observation.method,\n\t\t\t\t\t\"http.status_code\": observation.status,\n\t\t\t\t\t\"hevy.api.endpoint\": observation.endpoint,\n\t\t\t\t},\n\t\t\t});\n\t\t\tspan.setStatus({\n\t\t\t\tcode: observation.error ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n\t\t\t});\n\t\t\tif (observation.error) {\n\t\t\t\tconst diagnostic = createSafeErrorDiagnostic(observation.error);\n\t\t\t\tspan.addEvent(\"hevy.api.failure\", {\n\t\t\t\t\t\"error.category\": diagnostic.category,\n\t\t\t\t\t...(diagnostic.code ? { \"error.code\": diagnostic.code } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t\tspan.end();\n\t\t\tapiCalls.add(1, {\n\t\t\t\tmethod: observation.method,\n\t\t\t\tendpoint: observation.endpoint,\n\t\t\t\tstatus_code: observation.status,\n\t\t\t});\n\t\t\tapiDuration.record(observation.durationMs, {\n\t\t\t\tmethod: observation.method,\n\t\t\t\tendpoint: observation.endpoint,\n\t\t\t});\n\t\t\tdebugLog(\"api_response\", {\n\t\t\t\tmethod: observation.method,\n\t\t\t\tendpoint: observation.endpoint,\n\t\t\t\tdurationMs: observation.durationMs,\n\t\t\t\tstatus: observation.status || null,\n\t\t\t});\n\t\t},\n\t};\n}\n","import { SpanStatusCode } from \"@opentelemetry/api\";\nimport { debugLog, isDebugEnabled, redactToolArgs } from \"./debug.js\";\nimport { resolveErrorPolicy } from \"./error-policy.js\";\nimport { toolDuration, toolErrors, toolInvocations } from \"./metrics.js\";\nimport type { McpToolResponse } from \"./response-formatter.js\";\nimport { tracer } from \"./telemetry.js\";\n\n/** Whitelist of safe argument keys that can be logged without exposing PII. */\nconst ARGUMENT_WHITELIST = new Set([\n\t\"page\",\n\t\"pageSize\",\n\t\"since\",\n\t\"workoutId\",\n\t\"routineId\",\n\t\"folderId\",\n\t\"exerciseTemplateId\",\n\t\"date\",\n\t\"startDate\",\n\t\"endDate\",\n\t\"updatedSince\",\n\t\"includeCustom\",\n\t\"limit\",\n\t\"offset\",\n\t\"refresh\",\n\t\"query\",\n\t\"primaryMuscleGroup\",\n]);\n\nfunction extractSafeArgs(\n\targs: Record<string, unknown>,\n): Record<string, string | number | boolean> {\n\tconst attributes: Record<string, string | number | boolean> = {};\n\tfor (const [key, value] of Object.entries(args)) {\n\t\tif (!ARGUMENT_WHITELIST.has(key)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (\n\t\t\ttypeof value !== \"string\" &&\n\t\t\ttypeof value !== \"number\" &&\n\t\t\ttypeof value !== \"boolean\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tattributes[`mcp.tool.args.${key}`] =\n\t\t\tkey === \"query\" && typeof value === \"string\" && value.length > 100\n\t\t\t\t? `${value.slice(0, 100)}...`\n\t\t\t\t: value;\n\t}\n\treturn attributes;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction getWorkflowTelemetry(result: McpToolResponse): {\n\tname: string;\n\tpagination: Record<string, number>;\n\tcacheStatus: string;\n\titemsScanned: number;\n} | null {\n\tconst structuredContent = result.structuredContent;\n\tif (!isRecord(structuredContent)) return null;\n\tconst workflow = structuredContent.workflow;\n\tif (!isRecord(workflow)) return null;\n\tconst name = workflow.name;\n\tconst paginationValue = workflow.pagination;\n\tconst cacheStatus = workflow.cacheStatus;\n\tconst itemsScanned = workflow.itemsScanned;\n\tif (\n\t\ttypeof name !== \"string\" ||\n\t\t!isRecord(paginationValue) ||\n\t\ttypeof cacheStatus !== \"string\" ||\n\t\ttypeof itemsScanned !== \"number\" ||\n\t\t!Number.isSafeInteger(itemsScanned) ||\n\t\titemsScanned < 0\n\t) {\n\t\treturn null;\n\t}\n\tconst pagination: Record<string, number> = {};\n\tfor (const [key, value] of Object.entries(paginationValue)) {\n\t\tif (\n\t\t\ttypeof value === \"number\" &&\n\t\t\tNumber.isSafeInteger(value) &&\n\t\t\tvalue >= 0\n\t\t) {\n\t\t\tpagination[key] = value;\n\t\t}\n\t}\n\treturn { name, pagination, cacheStatus, itemsScanned };\n}\n\n/**\n * Wrap an MCP tool handler with its existing OpenTelemetry span and metrics.\n */\nexport function withTelemetry<TParams extends Record<string, unknown>>(\n\tfn: (args: TParams) => Promise<McpToolResponse>,\n\tcontext: string,\n): (args: Record<string, unknown>) => Promise<McpToolResponse> {\n\treturn async (rawArgs: Record<string, unknown>) => {\n\t\tconst args = rawArgs ?? {};\n\t\tif (isDebugEnabled()) {\n\t\t\tdebugLog(\"tool_invocation\", {\n\t\t\t\ttool: context,\n\t\t\t\tparams: redactToolArgs(args),\n\t\t\t});\n\t\t}\n\t\tconst argumentKeyCount = Object.keys(args).length;\n\t\tconst startTime = Date.now();\n\t\tlet isError = false;\n\n\t\ttoolInvocations.add(1, { tool_name: context });\n\n\t\tconst safeArgs = extractSafeArgs(args);\n\t\tconst whitelistedKeys = Object.keys(safeArgs).map((key) =>\n\t\t\tkey.replace(\"mcp.tool.args.\", \"\"),\n\t\t);\n\n\t\treturn tracer.startActiveSpan(\n\t\t\t`mcp.tool.${context}`,\n\t\t\t{\n\t\t\t\tattributes: {\n\t\t\t\t\t\"mcp.tool.name\": context,\n\t\t\t\t\t\"workflow.name\": context,\n\t\t\t\t\t\"mcp.tool.args.key_count\": argumentKeyCount,\n\t\t\t\t\t\"mcp.tool.args.keys\": whitelistedKeys.join(\",\"),\n\t\t\t\t\t...safeArgs,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync (span) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await fn(args as TParams);\n\t\t\t\t\tisError = Boolean(result.isError);\n\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\tcode: isError ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n\t\t\t\t\t});\n\t\t\t\t\tspan.setAttribute(\"mcp.tool.result.is_error\", isError);\n\t\t\t\t\tif (result.content) {\n\t\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\t\"mcp.tool.result.content_count\",\n\t\t\t\t\t\t\tresult.content.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst textLength = result.content.reduce(\n\t\t\t\t\t\t\t(sum, item) => sum + (item.text?.length ?? 0),\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tspan.setAttribute(\"mcp.tool.result.text_length\", textLength);\n\t\t\t\t\t}\n\t\t\t\t\tconst workflow = getWorkflowTelemetry(result);\n\t\t\t\t\tif (workflow) {\n\t\t\t\t\t\tspan.setAttribute(\"workflow.name\", workflow.name);\n\t\t\t\t\t\tspan.setAttribute(\"workflow.cache_status\", workflow.cacheStatus);\n\t\t\t\t\t\tspan.setAttribute(\"workflow.items_scanned\", workflow.itemsScanned);\n\t\t\t\t\t\tfor (const [resource, pageCount] of Object.entries(\n\t\t\t\t\t\t\tworkflow.pagination,\n\t\t\t\t\t\t)) {\n\t\t\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\t\t`workflow.pagination.${resource}.pages`,\n\t\t\t\t\t\t\t\tpageCount,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tisError = true;\n\t\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\t\tconst policy = resolveErrorPolicy(error, \"\");\n\t\t\t\t\tconst { diagnostic } = policy;\n\t\t\t\t\tspan.addEvent(\"mcp.tool.failure\", {\n\t\t\t\t\t\t\"error.category\": diagnostic.category,\n\t\t\t\t\t\t...(diagnostic.code ? { \"error.code\": diagnostic.code } : {}),\n\t\t\t\t\t\t...(diagnostic.status !== undefined\n\t\t\t\t\t\t\t? { \"http.status_code\": diagnostic.status }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(diagnostic.method ? { \"http.method\": diagnostic.method } : {}),\n\t\t\t\t\t\t...(diagnostic.endpoint\n\t\t\t\t\t\t\t? { \"hevy.api.endpoint\": diagnostic.endpoint }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst errorType = policy.type;\n\t\t\t\t\tspan.setAttribute(\"error.type\", errorType);\n\n\t\t\t\t\ttoolErrors.add(1, {\n\t\t\t\t\t\ttool_name: context,\n\t\t\t\t\t\terror_type: errorType,\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\ttoolDuration.record(Date.now() - startTime, {\n\t\t\t\t\t\ttool_name: context,\n\t\t\t\t\t\tis_error: String(isError),\n\t\t\t\t\t});\n\t\t\t\t\tspan.end();\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t};\n}\n","import { withErrorHandling } from \"./error-handler.js\";\nimport type { McpToolResponse } from \"./response-formatter.js\";\nimport { resolveErrorPolicy } from \"./error-policy.js\";\nimport { Sentry } from \"./telemetry.js\";\nimport { withTelemetry } from \"./telemetry-wrapper.js\";\n\n/**\n * Wrap an MCP tool handler with telemetry inside error response handling.\n */\nexport function withObservability<TParams extends Record<string, unknown>>(\n\tfn: (args: TParams) => Promise<McpToolResponse>,\n\tcontext: string,\n): (args: Record<string, unknown>) => Promise<McpToolResponse> {\n\treturn withErrorHandling(\n\t\twithTelemetry(fn, context),\n\t\tcontext,\n\t\t(error, _toolContext, argumentKeyCount) => {\n\t\t\tconst { diagnostic } = resolveErrorPolicy(error, \"\");\n\t\t\tSentry.withScope((scope) => {\n\t\t\t\tscope.setTag(\"error.category\", diagnostic.category);\n\t\t\t\tif (diagnostic.code) scope.setTag(\"error.code\", diagnostic.code);\n\t\t\t\tif (diagnostic.status !== undefined) {\n\t\t\t\t\tscope.setTag(\"http.status_code\", String(diagnostic.status));\n\t\t\t\t}\n\t\t\t\tscope.setContext(\"mcpTool\", { argumentKeyCount });\n\t\t\t\tscope.setContext(\"safeError\", { ...diagnostic });\n\t\t\t\tSentry.captureMessage(\"MCP tool failure\", \"error\");\n\t\t\t});\n\t\t},\n\t);\n}\n","import { SpanStatusCode } from \"@opentelemetry/api\";\nimport type { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { deserializeMessage } from \"@modelcontextprotocol/sdk/shared/stdio.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { stdioParseErrors } from \"./metrics.js\";\nimport { createSafeErrorDiagnostic } from \"./safe-error-diagnostic.js\";\nimport { Sentry, tracer } from \"./telemetry.js\";\n\nconst UTF8_BOM = \"\\uFEFF\";\n/** Maximum escaped characters included in a malformed stdin shape preview. */\nconst STDIN_PARSE_SHAPE_PREVIEW_MAX_LENGTH = 200;\nconst REDACTED_CONTENT_MARKER = \"[REDACTED]\";\n\nexport interface StdioChunkSnapshot {\n\tlastChunkByteLength: number;\n\tlastChunkStartsWithUtf8Bom: boolean;\n}\n\ninterface MutableReadBuffer {\n\t_buffer?: Buffer;\n\treadMessage: () => JSONRPCMessage | null;\n}\n\ntype MutableStdioServerTransport = {\n\t_readBuffer?: MutableReadBuffer;\n\t_ondata?: (chunk: Buffer) => void;\n};\n\ninterface SdkPrivateStdioAdapter {\n\twrapOnData: (onChunk: (chunk: Buffer) => void) => void;\n\tinstallReadMessageHook: (\n\t\tonReadLine: (line: string) => JSONRPCMessage,\n\t) => boolean;\n}\n\n/**\n * Adapter boundary around MCP SDK stdio internals.\n *\n * MCP SDK v1.29.0 exposes public message-level hooks but does not expose a\n * public raw-chunk hook on `StdioServerTransport`. To capture chunk metadata,\n * we currently rely on private internals (`_ondata`, `_readBuffer`, `_buffer`)\n * in this one place.\n *\n * If those internals change in a future SDK release, this adapter should fail\n * closed and preserve default transport behavior (no instrumentation patching).\n */\nfunction createSdkPrivateStdioAdapter(\n\ttransport: StdioServerTransport,\n): SdkPrivateStdioAdapter {\n\tconst mutableTransport = transport as unknown as MutableStdioServerTransport;\n\n\treturn {\n\t\twrapOnData(onChunk) {\n\t\t\tconst originalOnData = mutableTransport._ondata;\n\t\t\tif (typeof originalOnData !== \"function\") {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmutableTransport._ondata = (chunk: Buffer) => {\n\t\t\t\tonChunk(chunk);\n\t\t\t\toriginalOnData(chunk);\n\t\t\t};\n\t\t},\n\t\tinstallReadMessageHook(onReadLine) {\n\t\t\tconst readBuffer = mutableTransport._readBuffer;\n\t\t\tif (!readBuffer || typeof readBuffer.readMessage !== \"function\") {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treadBuffer.readMessage = () => {\n\t\t\t\tconst buffer = readBuffer._buffer;\n\t\t\t\tif (!buffer) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst index = buffer.indexOf(\"\\n\");\n\t\t\t\tif (index === -1) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst lineBuffer = buffer.subarray(0, index);\n\t\t\t\treadBuffer._buffer = buffer.subarray(index + 1);\n\t\t\t\tconst line = lineBuffer.toString(\"utf8\").replace(/\\r$/, \"\");\n\t\t\t\treturn onReadLine(line);\n\t\t\t};\n\n\t\t\treturn true;\n\t\t},\n\t};\n}\n\nfunction hasUtf8BomPrefix(chunk: Buffer): boolean {\n\treturn (\n\t\tchunk.length >= 3 &&\n\t\tchunk[0] === 0xef &&\n\t\tchunk[1] === 0xbb &&\n\t\tchunk[2] === 0xbf\n\t);\n}\n\nfunction parseFailurePosition(error: unknown): number | null {\n\tif (!(error instanceof Error)) {\n\t\treturn null;\n\t}\n\n\tconst match = error.message.match(/position\\s+(\\d+)/i);\n\tif (!match || !match[1]) {\n\t\treturn null;\n\t}\n\n\tconst position = Number.parseInt(match[1], 10);\n\treturn Number.isFinite(position) ? position : null;\n}\n\nfunction getFailureLocation(\n\tfailurePosition: number | null,\n\tlineHadLeadingBom: boolean,\n): string {\n\tif (lineHadLeadingBom) {\n\t\treturn \"line_start_bom\";\n\t}\n\tif (failurePosition === 0) {\n\t\treturn \"line_start\";\n\t}\n\tif (failurePosition !== null) {\n\t\treturn \"line_body\";\n\t}\n\treturn \"unknown\";\n}\n\nfunction createStructuralShapePreview(line: string): {\n\tshapePreview: string;\n\ttruncated: boolean;\n} {\n\tlet shapePreview = \"\";\n\tlet inContentRun = false;\n\tlet inWhitespaceRun = false;\n\n\tconst append = (token: string): boolean => {\n\t\tif (\n\t\t\tshapePreview.length + token.length >\n\t\t\tSTDIN_PARSE_SHAPE_PREVIEW_MAX_LENGTH\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tshapePreview += token;\n\t\treturn true;\n\t};\n\n\tfor (const character of line) {\n\t\tif ('{}[]:,\"'.includes(character)) {\n\t\t\tinContentRun = false;\n\t\t\tinWhitespaceRun = false;\n\t\t\tif (!append(character === '\"' ? \"\\\\u0022\" : character)) {\n\t\t\t\treturn { shapePreview, truncated: true };\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (/\\s/u.test(character)) {\n\t\t\tinContentRun = false;\n\t\t\tif (!inWhitespaceRun) {\n\t\t\t\tif (!append(\"\\\\s\")) {\n\t\t\t\t\treturn { shapePreview, truncated: true };\n\t\t\t\t}\n\t\t\t\tinWhitespaceRun = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tinWhitespaceRun = false;\n\t\tif (!inContentRun) {\n\t\t\tif (!append(REDACTED_CONTENT_MARKER)) {\n\t\t\t\treturn { shapePreview, truncated: true };\n\t\t\t}\n\t\t\tinContentRun = true;\n\t\t}\n\t}\n\n\treturn {\n\t\tshapePreview,\n\t\ttruncated: false,\n\t};\n}\n\nfunction getSafeErrorKind(\n\terror: unknown,\n): \"SyntaxError\" | \"Error\" | \"UnknownError\" {\n\tif (error instanceof SyntaxError) {\n\t\treturn \"SyntaxError\";\n\t}\n\tif (error instanceof Error) {\n\t\treturn \"Error\";\n\t}\n\treturn \"UnknownError\";\n}\n\nfunction reportStdinParseFailure(\n\terror: unknown,\n\tline: string,\n\tlineByteLength: number,\n\tfailureLocation: string,\n\tfailurePosition: number | null,\n): void {\n\ttry {\n\t\tconst errorKind = getSafeErrorKind(error);\n\t\tconst { shapePreview, truncated } = createStructuralShapePreview(line);\n\t\tconst position = failurePosition === null ? \"unknown\" : failurePosition;\n\n\t\tconsole.error(\n\t\t\t`Failed to parse MCP stdin message: error_kind=${errorKind} line_bytes=${lineByteLength} failure_location=${failureLocation} failure_position=${position} shape_preview=\"${shapePreview}\" shape_preview_redacted=true shape_preview_truncated=${truncated}`,\n\t\t);\n\t} catch {\n\t\t// Diagnostics are best-effort and must not replace the parser error.\n\t}\n}\n\nexport function deserializeMessageWithObservability(\n\tline: string,\n\tchunkSnapshot: StdioChunkSnapshot,\n): JSONRPCMessage {\n\tconst lineHadLeadingBom = line.startsWith(UTF8_BOM);\n\tconst normalizedLine = lineHadLeadingBom ? line.slice(1) : line;\n\tconst lineByteLength = Buffer.byteLength(line);\n\n\treturn tracer.startActiveSpan(\n\t\t\"mcp.stdio.deserialize\",\n\t\t{\n\t\t\tattributes: {\n\t\t\t\t\"mcp.transport\": \"stdio\",\n\t\t\t\t\"mcp.stdio.parse.line.char_length\": line.length,\n\t\t\t\t\"mcp.stdio.parse.line.byte_length\": lineByteLength,\n\t\t\t\t\"mcp.stdio.parse.line.had_leading_bom\": lineHadLeadingBom,\n\t\t\t\t\"mcp.stdio.parse.line.bom_stripped\": lineHadLeadingBom,\n\t\t\t\t\"mcp.stdio.parse.chunk.last_byte_length\":\n\t\t\t\t\tchunkSnapshot.lastChunkByteLength,\n\t\t\t\t\"mcp.stdio.parse.chunk.last_had_utf8_bom\":\n\t\t\t\t\tchunkSnapshot.lastChunkStartsWithUtf8Bom,\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\ttry {\n\t\t\t\tconst message = deserializeMessage(normalizedLine);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\t\t\tif (message && typeof message === \"object\" && \"method\" in message) {\n\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\"mcp.method\",\n\t\t\t\t\t\tString((message as { method: unknown }).method),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn message;\n\t\t\t} catch (error) {\n\t\t\t\tconst diagnostic = createSafeErrorDiagnostic(error);\n\t\t\t\tconst failurePosition = parseFailurePosition(error);\n\t\t\t\tconst failureLocation = getFailureLocation(\n\t\t\t\t\tfailurePosition,\n\t\t\t\t\tlineHadLeadingBom,\n\t\t\t\t);\n\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tspan.addEvent(\"mcp.stdio.parse.failure\", {\n\t\t\t\t\t\"error.category\": diagnostic.category,\n\t\t\t\t});\n\t\t\t\tspan.setAttribute(\"mcp.stdio.parse.failure.location\", failureLocation);\n\t\t\t\tif (failurePosition !== null) {\n\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\"mcp.stdio.parse.failure.position\",\n\t\t\t\t\t\tfailurePosition,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tstdioParseErrors.add(1, { failure_location: failureLocation });\n\n\t\t\t\tSentry.withScope((scope) => {\n\t\t\t\t\tscope.setTag(\"mcp.transport\", \"stdio\");\n\t\t\t\t\tscope.setTag(\"mcp.stdio.parse.failure.location\", failureLocation);\n\t\t\t\t\tscope.setContext(\"mcpStdioParse\", {\n\t\t\t\t\t\tlineCharLength: line.length,\n\t\t\t\t\t\tlineByteLength,\n\t\t\t\t\t\tlineHadLeadingBom,\n\t\t\t\t\t\tbomStripped: lineHadLeadingBom,\n\t\t\t\t\t\tlastChunkByteLength: chunkSnapshot.lastChunkByteLength,\n\t\t\t\t\t\tlastChunkStartsWithUtf8Bom:\n\t\t\t\t\t\t\tchunkSnapshot.lastChunkStartsWithUtf8Bom,\n\t\t\t\t\t\tfailureLocation,\n\t\t\t\t\t\tfailurePosition,\n\t\t\t\t\t\tfailureStage: \"deserializeMessage\",\n\t\t\t\t\t\terrorCategory: diagnostic.category,\n\t\t\t\t\t});\n\t\t\t\t\tSentry.captureMessage(\"MCP stdin parse failure\", \"error\");\n\t\t\t\t});\n\n\t\t\t\treportStdinParseFailure(\n\t\t\t\t\terror,\n\t\t\t\t\tline,\n\t\t\t\t\tlineByteLength,\n\t\t\t\t\tfailureLocation,\n\t\t\t\t\tfailurePosition,\n\t\t\t\t);\n\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tspan.end();\n\t\t\t}\n\t\t},\n\t);\n}\n\nexport function createInstrumentedStdioTransport<\n\tT extends StdioServerTransport,\n>(transport: T): T {\n\tconst privateAdapter = createSdkPrivateStdioAdapter(transport);\n\tlet lastChunkSnapshot: StdioChunkSnapshot = {\n\t\tlastChunkByteLength: 0,\n\t\tlastChunkStartsWithUtf8Bom: false,\n\t};\n\n\tprivateAdapter.wrapOnData((chunk) => {\n\t\tlastChunkSnapshot = {\n\t\t\tlastChunkByteLength: chunk.byteLength,\n\t\t\tlastChunkStartsWithUtf8Bom: hasUtf8BomPrefix(chunk),\n\t\t};\n\t});\n\n\tconst didInstallReadMessageHook = privateAdapter.installReadMessageHook(\n\t\t(line) => deserializeMessageWithObservability(line, lastChunkSnapshot),\n\t);\n\tif (!didInstallReadMessageHook) {\n\t\treturn transport;\n\t}\n\n\treturn transport;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport semver from \"semver\";\n\nconst CACHE_TTL_MS = 24 * 60 * 60 * 1_000;\nconst REQUEST_TIMEOUT_MS = 3_000;\nconst REGISTRY_URL = \"https://registry.npmjs.org\";\n\ninterface UpdateCheckOptions {\n\tpackageName: string;\n\tcurrentVersion: string;\n}\n\ninterface CacheEntry {\n\tcheckedAt: number;\n\tlatestVersion: string;\n}\n\ninterface ImmediateHandle {\n\tunref(): unknown;\n}\n\ninterface VersionCheckDependencies {\n\tfetch: typeof fetch;\n\treadFile: typeof readFile;\n\tmkdir: typeof mkdir;\n\twriteFile: typeof writeFile;\n\trename: typeof rename;\n\tunlink: typeof unlink;\n\thomedir: typeof homedir;\n\trandomUUID: typeof randomUUID;\n\tpid: number;\n\tnow: () => number;\n\tenv: NodeJS.ProcessEnv;\n\twriteStderr: (message: string) => unknown;\n}\n\ninterface SchedulerDependencies {\n\tsetImmediate: (callback: () => void) => ImmediateHandle;\n\tcheckForUpdate: (\n\t\toptions: UpdateCheckOptions,\n\t\tdependencies?: Partial<VersionCheckDependencies>,\n\t) => Promise<void>;\n}\n\nconst defaultDependencies: VersionCheckDependencies = {\n\tfetch,\n\treadFile,\n\tmkdir,\n\twriteFile,\n\trename,\n\tunlink,\n\thomedir,\n\trandomUUID,\n\tpid: process.pid,\n\tnow: Date.now,\n\tenv: process.env,\n\twriteStderr: (message) => process.stderr.write(message),\n};\n\nconst defaultSchedulerDependencies: SchedulerDependencies = {\n\tsetImmediate,\n\tcheckForUpdate,\n};\n\nfunction getCachePath(dependencies: VersionCheckDependencies): string {\n\tconst cacheRoot =\n\t\tdependencies.env.XDG_CACHE_HOME || join(dependencies.homedir(), \".cache\");\n\treturn join(cacheRoot, \"hevy-mcp\", \"update-check.json\");\n}\n\nfunction parseCacheEntry(value: string, now: number): CacheEntry | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value);\n\t\tif (\n\t\t\ttypeof parsed !== \"object\" ||\n\t\t\tparsed === null ||\n\t\t\t!(\"checkedAt\" in parsed) ||\n\t\t\t!(\"latestVersion\" in parsed)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst { checkedAt, latestVersion } = parsed;\n\t\tif (\n\t\t\ttypeof checkedAt !== \"number\" ||\n\t\t\t!Number.isFinite(checkedAt) ||\n\t\t\ttypeof latestVersion !== \"string\" ||\n\t\t\t!semver.valid(latestVersion)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst age = now - checkedAt;\n\t\tif (age < 0 || age >= CACHE_TTL_MS) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn { checkedAt, latestVersion };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parseLatestVersion(value: unknown): string | undefined {\n\tif (typeof value !== \"object\" || value === null || !(\"dist-tags\" in value)) {\n\t\treturn undefined;\n\t}\n\n\tconst distTags = value[\"dist-tags\"];\n\tif (\n\t\ttypeof distTags !== \"object\" ||\n\t\tdistTags === null ||\n\t\t!(\"latest\" in distTags) ||\n\t\ttypeof distTags.latest !== \"string\" ||\n\t\t!semver.valid(distTags.latest)\n\t) {\n\t\treturn undefined;\n\t}\n\n\treturn distTags.latest;\n}\n\nfunction shouldNotifyAboutUpdate(\n\tcurrentVersion: string,\n\tlatestVersion: string,\n): boolean {\n\tconst current = semver.parse(currentVersion);\n\tconst latest = semver.parse(latestVersion);\n\n\tif (\n\t\t!current ||\n\t\t!latest ||\n\t\tlatest.prerelease.length > 0 ||\n\t\t!semver.gt(latest, current)\n\t) {\n\t\treturn false;\n\t}\n\n\tif (latest.major > current.major) {\n\t\treturn true;\n\t}\n\n\treturn latest.major === current.major && latest.minor - current.minor > 2;\n}\n\nasync function readFreshCachedVersion(\n\tcachePath: string,\n\tdependencies: VersionCheckDependencies,\n): Promise<string | undefined> {\n\ttry {\n\t\tconst cache = await dependencies.readFile(cachePath, \"utf8\");\n\t\treturn parseCacheEntry(cache, dependencies.now())?.latestVersion;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function fetchLatestVersion(\n\tpackageName: string,\n\tdependencies: VersionCheckDependencies,\n): Promise<string | undefined> {\n\ttry {\n\t\tconst response = await dependencies.fetch(\n\t\t\t`${REGISTRY_URL}/${encodeURIComponent(packageName)}`,\n\t\t\t{\n\t\t\t\theaders: {\n\t\t\t\t\tAccept: \"application/vnd.npm.install-v1+json\",\n\t\t\t\t},\n\t\t\t\tsignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n\t\t\t},\n\t\t);\n\t\tif (!response.ok) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn parseLatestVersion(await response.json());\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function writeCache(\n\tcachePath: string,\n\tentry: CacheEntry,\n\tdependencies: VersionCheckDependencies,\n): Promise<void> {\n\tconst temporaryPath = `${cachePath}.${dependencies.pid}.${dependencies.randomUUID()}.tmp`;\n\tconst payload = `${JSON.stringify(entry)}\\n`;\n\n\ttry {\n\t\tawait dependencies.mkdir(dirname(cachePath), { recursive: true });\n\t\tawait dependencies.writeFile(temporaryPath, payload, \"utf8\");\n\t} catch {\n\t\ttry {\n\t\t\tawait dependencies.unlink(temporaryPath);\n\t\t} catch {\n\t\t\t// Cache cleanup failures are non-fatal.\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait dependencies.rename(temporaryPath, cachePath);\n\t\treturn;\n\t} catch {\n\t\ttry {\n\t\t\tawait dependencies.writeFile(cachePath, payload, \"utf8\");\n\t\t} catch {\n\t\t\t// Cache writes are deliberately non-fatal.\n\t\t}\n\t}\n\n\ttry {\n\t\tawait dependencies.unlink(temporaryPath);\n\t} catch {\n\t\t// Cache cleanup failures are non-fatal.\n\t}\n}\n\nexport async function checkForUpdate(\n\toptions: UpdateCheckOptions,\n\toverrides: Partial<VersionCheckDependencies> = {},\n): Promise<void> {\n\ttry {\n\t\tif (!semver.valid(options.currentVersion)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst dependencies = { ...defaultDependencies, ...overrides };\n\t\tconst cachePath = getCachePath(dependencies);\n\t\tlet latestVersion = await readFreshCachedVersion(cachePath, dependencies);\n\n\t\tif (!latestVersion) {\n\t\t\tlatestVersion = await fetchLatestVersion(\n\t\t\t\toptions.packageName,\n\t\t\t\tdependencies,\n\t\t\t);\n\t\t\tif (!latestVersion) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait writeCache(\n\t\t\t\tcachePath,\n\t\t\t\t{ checkedAt: dependencies.now(), latestVersion },\n\t\t\t\tdependencies,\n\t\t\t);\n\t\t}\n\n\t\tif (shouldNotifyAboutUpdate(options.currentVersion, latestVersion)) {\n\t\t\tdependencies.writeStderr(\n\t\t\t\t`Update available for ${options.packageName}: current ${options.currentVersion}, latest ${latestVersion}. Notices are shown for newer major versions or when more than two minor versions behind. Update using your preferred installation method (for example, npm install -g ${options.packageName}@latest).\\n`,\n\t\t\t);\n\t\t}\n\t} catch {\n\t\t// Update checks must never interfere with the MCP server lifecycle.\n\t}\n}\n\nexport function scheduleUpdateCheck(\n\toptions: UpdateCheckOptions,\n\toverrides: Partial<SchedulerDependencies> = {},\n): void {\n\tconst dependencies = { ...defaultSchedulerDependencies, ...overrides };\n\tconst immediate = dependencies.setImmediate(() => {\n\t\tvoid dependencies.checkForUpdate(options).catch(() => undefined);\n\t});\n\timmediate.unref();\n}\n","// Telemetry must be initialized before any other imports so that\n// OpenTelemetry and Sentry are ready before application code runs.\nimport {\n\tSentry,\n\ttracer,\n\tserviceName,\n\tserviceVersion,\n\tsetCurrentUserHash,\n} from \"./utils/telemetry.js\";\nimport { serverStartups } from \"./utils/metrics.js\";\n\nimport { SpanStatusCode } from \"@opentelemetry/api\";\nimport { createHmac } from \"node:crypto\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { createSharedMcpServer } from \"./shared-server.js\";\nimport { assertApiKey, parseConfig } from \"./utils/config.js\";\nimport { installGracefulShutdown } from \"./utils/graceful-shutdown.js\";\nimport { isHevyHttpError } from \"./utils/hevy-http-error.js\";\nimport { createNodeHevyClientOptions } from \"./utils/hevy-client-observability.js\";\nimport { createClient } from \"./utils/hevyClient.js\";\nimport { withObservability } from \"./utils/observability-wrapper.js\";\nimport { createInstrumentedStdioTransport } from \"./utils/stdio-observability.js\";\nimport { scheduleUpdateCheck } from \"./utils/version-check.js\";\n\nconst name = serviceName;\nconst version = serviceVersion;\n\nconst HELP_TEXT = [\n\t\"Usage:\",\n\t\" hevy-mcp [options]\",\n\t\"\",\n\t\"Options:\",\n\t\" -h, --help Show this help message and exit\",\n\t\" -v, --version Show version and exit\",\n\t\"\",\n\t\"Environment:\",\n\t\" HEVY_API_KEY=<api-key> Hevy API key from Hevy app settings\",\n\t\" HEVY_MCP_DEBUG=1 Enable verbose diagnostics on stderr\",\n\t\"\",\n\t\"Examples:\",\n\t\" HEVY_API_KEY=your-key npx hevy-mcp\",\n].join(\"\\n\");\n\nfunction getCliAction(args: string[]): \"start\" | \"version\" | \"help\" {\n\tfor (const arg of args) {\n\t\tif (arg === \"--version\" || arg === \"-v\") {\n\t\t\treturn \"version\";\n\t\t}\n\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\treturn \"help\";\n\t\t}\n\t}\n\n\treturn \"start\";\n}\n\nconst HEVY_API_BASEURL = \"https://api.hevyapp.com\";\nconst STARTUP_PROBE_TIMEOUT_MS = 5_000;\n\nconst INVALID_API_KEY_MESSAGE =\n\t\"HEVY_API_KEY is invalid or expired. Please check your API key in the Hevy app under Settings > API Key.\";\nconst API_KEY_VALIDATION_WARNING =\n\t\"Warning: HEVY_API_KEY could not be validated during startup. Startup will continue; check your network connection and Hevy API availability.\";\nconst SAFE_NETWORK_ERROR_CODES = new Set([\n\t\"EAI_AGAIN\",\n\t\"ECONNABORTED\",\n\t\"ECONNREFUSED\",\n\t\"ECONNRESET\",\n\t\"ENETUNREACH\",\n\t\"ENOTFOUND\",\n\t\"ERR_NETWORK\",\n\t\"ERR_SOCKET_TIMEOUT\",\n\t\"ETIMEDOUT\",\n\t\"HEVY_RETRY_EXHAUSTED\",\n]);\n\nconst SENTRY_USER_ID_CONTEXT = \"hevy-mcp:sentry-user-id:v1\";\n\nfunction fingerprintApiKey(apiKey: string) {\n\t// HMAC-SHA-256 gives Sentry and OTel a deterministic pseudonymous user\n\t// hash without sending, logging, or storing the raw Hevy API key.\n\t// Trimmed to 10 characters to keep it compact and readable in traces.\n\treturn createHmac(\"sha256\", apiKey)\n\t\t.update(SENTRY_USER_ID_CONTEXT)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 10);\n}\nconst serverConfigSchema = z.object({\n\tapiKey: z\n\t\t.string()\n\t\t.min(1, \"Hevy API key is required\")\n\t\t.describe(\"Your Hevy API key (available in the Hevy app settings).\"),\n});\n\nexport const configSchema = serverConfigSchema;\ntype ServerConfig = z.infer<typeof serverConfigSchema>;\n\nfunction getHttpStatus(error: unknown): number | undefined {\n\tif (isHevyHttpError(error)) {\n\t\treturn error.status;\n\t}\n\tif (!error || typeof error !== \"object\" || !(\"response\" in error)) {\n\t\treturn undefined;\n\t}\n\n\tconst response = error.response;\n\tif (!response || typeof response !== \"object\" || !(\"status\" in response)) {\n\t\treturn undefined;\n\t}\n\n\treturn typeof response.status === \"number\" &&\n\t\tNumber.isInteger(response.status) &&\n\t\tresponse.status >= 100 &&\n\t\tresponse.status <= 599\n\t\t? response.status\n\t\t: undefined;\n}\n\nfunction getSafeValidationDiagnostic(error: unknown): string | undefined {\n\tconst status = getHttpStatus(error);\n\tif (status !== undefined) {\n\t\treturn `HTTP ${status}`;\n\t}\n\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn undefined;\n\t}\n\n\tconst code = error.code;\n\treturn typeof code === \"string\" && SAFE_NETWORK_ERROR_CODES.has(code)\n\t\t? code\n\t\t: undefined;\n}\n\nasync function validateApiKey(apiKey: string) {\n\t// Keep the startup probe separate from the normal MCP-aware client. The\n\t// server is not connected yet, so structured client logging is intentionally\n\t// omitted until the normal client is built below.\n\tconst startupProbeClient = createClient(apiKey, HEVY_API_BASEURL, {\n\t\tmaxGetRetries: 0,\n\t\ttimeoutMs: STARTUP_PROBE_TIMEOUT_MS,\n\t});\n\n\ttry {\n\t\tawait startupProbeClient.getUserInfo();\n\t} catch (error) {\n\t\tconst status = getHttpStatus(error);\n\t\tif (status === 401 || status === 403) {\n\t\t\tthrow new Error(INVALID_API_KEY_MESSAGE);\n\t\t}\n\n\t\tconst diagnostic = getSafeValidationDiagnostic(error);\n\t\tconsole.error(\n\t\t\tdiagnostic\n\t\t\t\t? `${API_KEY_VALIDATION_WARNING} Diagnostic: ${diagnostic}.`\n\t\t\t\t: API_KEY_VALIDATION_WARNING,\n\t\t);\n\t}\n}\n\nfunction buildServer(apiKey: string) {\n\treturn tracer.startActiveSpan(\n\t\t\"mcp.server.build\",\n\t\t{\n\t\t\tattributes: {\n\t\t\t\t\"mcp.server.name\": name,\n\t\t\t\t\"mcp.server.version\": version,\n\t\t\t\t\"mcp.transport\": \"stdio\",\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\ttry {\n\t\t\t\tconst server = createSharedMcpServer({\n\t\t\t\t\tapiKey,\n\t\t\t\t\tclientOptions: createNodeHevyClientOptions(),\n\t\t\t\t\twrapHandler: withObservability,\n\t\t\t\t\twrapServer: (baseServer) =>\n\t\t\t\t\t\tSentry.wrapMcpServerWithSentry(baseServer),\n\t\t\t\t\tonToolsRegistered: (count) =>\n\t\t\t\t\t\tspan.setAttribute(\"mcp.tools.count\", count),\n\t\t\t\t});\n\t\t\t\tconsole.error(\"Hevy client initialized with API key\");\n\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\t\t\treturn server;\n\t\t\t} catch (e) {\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tthrow e;\n\t\t\t} finally {\n\t\t\t\tspan.end();\n\t\t\t}\n\t\t},\n\t);\n}\n\nexport async function createServer({ config }: { config: ServerConfig }) {\n\tconst { apiKey } = serverConfigSchema.parse(config);\n\tconst userHash = fingerprintApiKey(apiKey);\n\tsetCurrentUserHash(userHash);\n\tSentry.setUser({ id: userHash });\n\tawait validateApiKey(apiKey);\n\treturn buildServer(apiKey);\n}\n\nexport default createServer;\n\nexport async function runServer() {\n\tconst args = process.argv.slice(2);\n\tconst cliAction = getCliAction(args);\n\n\tif (cliAction === \"version\") {\n\t\tconsole.error(`${name} v${version}`);\n\t\treturn;\n\t}\n\n\tif (cliAction === \"help\") {\n\t\tconsole.log(HELP_TEXT);\n\t\treturn;\n\t}\n\n\tserverStartups.add(1, { version });\n\n\t// Seed the user context before config validation so startup failures for a\n\t// supplied key retain the same trace correlation as normal tool calls.\n\tconst configuredApiKey = process.env.HEVY_API_KEY;\n\tconst initialUserHash = configuredApiKey\n\t\t? fingerprintApiKey(configuredApiKey)\n\t\t: undefined;\n\tif (initialUserHash) {\n\t\tsetCurrentUserHash(initialUserHash);\n\t\tSentry.setUser({ id: initialUserHash });\n\t}\n\n\tawait tracer.startActiveSpan(\n\t\t\"mcp.server.run\",\n\t\t{\n\t\t\tattributes: {\n\t\t\t\t\"mcp.transport\": \"stdio\",\n\t\t\t},\n\t\t},\n\t\tasync (span) => {\n\t\t\ttry {\n\t\t\t\tconst cfg = parseConfig(process.env);\n\t\t\t\tconst apiKey = cfg.apiKey;\n\t\t\t\tassertApiKey(apiKey);\n\n\t\t\t\tconst server = await createServer({ config: { apiKey } });\n\t\t\t\tconsole.error(\"Starting MCP server in stdio mode\");\n\t\t\t\tconst transport = createInstrumentedStdioTransport(\n\t\t\t\t\tnew StdioServerTransport(),\n\t\t\t\t);\n\n\t\t\t\tawait tracer.startActiveSpan(\n\t\t\t\t\t\"mcp.server.connect\",\n\t\t\t\t\t{\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"mcp.transport\": \"stdio\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tasync (connectSpan) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait server.connect(transport);\n\t\t\t\t\t\t\tconnectSpan.setStatus({ code: SpanStatusCode.OK });\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tconnectSpan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tconnectSpan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tscheduleUpdateCheck({\n\t\t\t\t\tpackageName: serviceName,\n\t\t\t\t\tcurrentVersion: serviceVersion,\n\t\t\t\t});\n\t\t\t\tinstallGracefulShutdown({ target: server });\n\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\t\t} catch (e) {\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tthrow e;\n\t\t\t} finally {\n\t\t\t\tspan.end();\n\t\t\t}\n\t\t},\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAMA,SAAAA;AAEN,MAAMC,YAAAA;AAON,MAAM,iBAAA;AAKN,MAAM,qBAAqB;AAE3B,MAAM,gBAAgB,QAAQ,IAAI,kBAAkB;AAEpD,MAAM,WAAW,uBAAuB;CACvC,gBAAgBD;CAChB,mBAAmBC;AACpB,CAAC;AAID,MAAM,SAAS,QAAQ,IAAI,cAAc;AACzC,MAAM,aACL,OAAO,WAAW,YAAY,OAAO,SAAS,KAAK,CAAC,OAAO,WAAW,GAAG;AAG1E,MAAM,eAAe,OAAO,KAAK;CAChC,KAAK,aAAa,SAAS,KAAA;CAC3B,SAAS;CACT,kBAAkB;CAClB,gBAAgB;CAChB,wBAAwB;CACxB,wBAAwB;CACxB,cAAc,CAAC,SAAS,aAAa;AACtC,CAAC;AAGD,IAAI;AAEJ,IAAM,wBAAN,MAAqD;CACpD,QAAQ,MAAkB;EACzB,IAAI,iBACH,KAAK,aAAa,aAAa,eAAe;CAEhD;CAEA,MAAM,OAA2B,CAAC;CAElC,MAAM,aAA4B,CAAC;CAEnC,MAAM,WAA0B,CAAC;AAClC;AAEA,MAAM,iBAAkC,CACvC,IAAI,sBAAsB,GAC1B,IAAI,oBAAoB,CACzB;AAIC,eAAe,KACd,IAAI,mBACH,IAAI,kBAAkB;CACrB,KAAK,GAAG,mBAAmB;CAC3B,SAAS,EACR,eAAe,UAAU,iBAC1B;AACD,CAAC,CACF,CACD;AAGD,MAAM,iBAAiB,IAAI,mBAAmB;CAC7C;CACA,SAAS,eAAe,IAA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