> ## Documentation Index
> Fetch the complete documentation index at: https://docs.technicallyfit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Cookbook

> Fifteen end-to-end integration recipes across four customer tracks in TypeScript and Python, showcasing TechnicallyFit as athletic performance infrastructure.

TechnicallyFit is **athletic performance infrastructure**: a deterministic training engine,
consent-first teammate data graph, real-time sensor gateway, multi-location equipment
inventory model, and cryptographic verification layer behind public `/v1` APIs and open
SDKs ([TypeScript](https://docs.technicallyfit.com/sdks/typescript.md) `@technicallyfit/sdk`, [Python](https://docs.technicallyfit.com/sdks/python.md)
`technicallyfit`, and `@technicallyfit/source-adapters`).

This cookbook organizes **15 runnable scenarios into 4 builder tracks** so you can jump
straight to your use case, whether you are an indie developer testing on a free personal
key, a performance coaching platform, a connected hardware maker, a testing combine, or a
multi-location gym operator.

## Scenarios by track

### Track 1: Start in 5 minutes (Free personal workspace and sandbox)

| # | Scenario | Built for | Required scopes | Mode |
| - | - | - | - | - |
| 1 | [Browse the exercise catalog, equipment, and training knowledge](#1-browse-the-exercise-catalog-equipment-and-training-knowledge) | Indie app builders, AI app developers | `reference:read` | Test or live (personal or org) |
| 2 | [Simulate a 6-week injury-return lifecycle in the sandbox](#2-simulate-a-6-week-injury-return-lifecycle-in-the-sandbox) | Any evaluating developer, QA and CI pipelines | Test key (`tf_test_*`) | Test only (free personal or org) |

### Track 2: Training engine, consent, and deterministic adaptation

| # | Scenario | Built for | Required scopes | Mode |
| - | - | - | - | - |
| 3 | [Onboard a teammate, send a claim invite, and handle consent](#3-onboard-a-teammate-send-a-claim-invite-and-handle-consent) | Gym chains, coaching platforms, member CRMs | `teammates:write`, `teammates:read` | Test, or organization live |
| 4 | [Ingest sets, observations, and body measurements with offline sync](#4-ingest-sets-observations-and-body-measurements-with-offline-sync) | Mobile workout apps, gym kiosks, smart scales | `events:write` | Test or live |
| 5 | [Generate a deterministic program and audit every revision](#5-generate-a-deterministic-program-and-audit-every-revision) | Fitness apps, digital health, coaching platforms | `programs:write`, `programs:read` | Test or live |
| 6 | [Read joint caution, recovery, and uncertainty without a wearable](#6-read-joint-caution-recovery-and-uncertainty-without-a-wearable) | PT and return-to-play clinics, sports performance staff | `body_state:read`, `teammates:write` | Test or live |
| 7 | [Run an async coach-in-the-loop proposal review workflow](#7-run-an-async-coach-in-the-loop-proposal-review-workflow) | Coaching platforms, academies, collegiate and pro S\&C | `events:write`, `proposals:read`, `proposals:write` | Organization live |
| 8 | [Adapt a workout live mid-session with one-tap undo](#8-adapt-a-workout-live-mid-session-with-one-tap-undo) | Interactive training apps, smart floor displays | `programs:read`, `programs:write`, `events:write` | Test or live |

### Track 3: Hardware, real-time telemetry, and verified records

| # | Scenario | Built for | Required scopes | Mode |
| - | - | - | - | - |
| 9 | [Stream live sensor data for real-time cues with reconnect recovery](#9-stream-live-sensor-data-for-real-time-cues-with-reconnect-recovery) | Wearable, velocity tracker, and smart rack makers | `events:write` | Test or live |
| 10 | [Build and certify a custom hardware source adapter](#10-build-and-certify-a-custom-hardware-source-adapter) | Hardware manufacturers, telemetry integrators | Offline kit (optional `tf_test_*` live check) | Local or test |
| 11 | [Issue and offline-verify a cryptographically attested record](#11-issue-and-offline-verify-a-cryptographically-attested-record) | Testing combines and labs (issuer) + scouts, colleges, leagues (verifier) | `measurements:write`, `attestations:write` (verification is public, no key) | Test or live, approved attestor |

### Track 4: Multi-location gyms, webhooks, and branded member apps

| # | Scenario | Built for | Required scopes | Mode |
| - | - | - | - | - |
| 12 | [Subscribe to outbound webhooks, fetch details, and rotate secrets with zero downtime](#12-subscribe-to-outbound-webhooks-fetch-details-and-rotate-secrets-with-zero-downtime) | Backend platform engineers | `webhooks:write`, `programs:read` | Test or live |
| 13 | [Handle a gym equipment outage with floor-wide program replanning](#13-handle-a-gym-equipment-outage-with-floor-wide-program-replanning) | Multi-location gym chains, facility operations teams | `locations:write`, `locations:read` | Test or live |
| 14 | [Sync gym visits, read traffic, discover PT leads, and flag at-risk members](#14-sync-gym-visits-read-traffic-discover-pt-leads-and-flag-at-risk-members) | Gym operators, retention and CRM teams | `locations:write`, `events:write`, `insights:read` | Organization live (or test) |
| 15 | [Launch a branded member app with Sign in with TechnicallyFit and drop-in components](#15-launch-a-branded-member-app-with-sign-in-with-technicallyfit-and-drop-in-components) | Gym brands, consumer fitness apps, university portals | OAuth `teammates:read`, `programs:read`, `record:read` | Live (teammate OAuth) |

## Setup

Set these two values once in your terminal. Every example in these docs reads them, so
no example has a host or a key typed into it.

```bash theme={null} theme={null}
export TF_API_BASE="https://api.technicallyfit.com"
export TF_API_KEY="tf_test_your_key_here"
```

Use a test key (it starts with `tf_test_`) while you build. Never paste a live key into a
page, a ticket or a chat.

Install the published SDK packages before running the recipes below:

```bash TypeScript theme={null}
npm install @technicallyfit/sdk @technicallyfit/source-adapters
```

```bash Python theme={null}
pip install technicallyfit
# Optional extra for Scenario 9 (live WebSocket streaming):
pip install 'technicallyfit[live]'
```

A personal workspace has a daily cap on program creations and sandbox week simulations,
which scenarios 2 and 5 use. Running both in TypeScript and in Python takes most of a
day's allowance. The numbers are in
[Rate limits](https://docs.technicallyfit.com/guides/rate-limits.md#personal-workspace-caps).

***

## Track 1: Start in 5 minutes

### 1. Browse the exercise catalog, equipment, and training knowledge

**Built for:** Indie fitness app builders and AI application developers starting on a free personal workspace.

**When to use this scenario:** You are building a smart exercise picker, movement-substitution screen, or training explainer and need canonical exercise IDs, drop-in alternatives, the standardized equipment taxonomy, and grounded training concepts from TechnicallyFit's knowledge graph.

**Required scopes and mode:** `reference:read`. Works in test or live mode with a free personal key or an organization key.

**What happens end-to-end:** Your app queries `GET /v1/exercises` filtered by equipment and muscle group, fetches drop-in substitutes via `GET /v1/exercises/{exercise_id}/alternatives`, checks the canonical equipment tokens via `GET /v1/equipment`, and looks up training concepts through `GET /v1/knowledge/search`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Query canonical exercises by equipment and primary muscle.
const catalog = await tf.GET('/v1/exercises', {
  params: {
    query: {
      equipment: 'barbell',
      muscle: 'quadriceps',
      limit: 10,
    },
  },
});
console.log(`Found ${String(catalog.total)} exercises (showing ${String(catalog.exercises.length)})`);

// 2. Fetch movement-pattern alternatives for the top match.
const first = catalog.exercises[0];
if (first) {
  const alternatives = await tf.GET('/v1/exercises/{exercise_id}/alternatives', {
    params: {
      path: { exercise_id: first.id },
      query: { limit: 5 },
    },
  });
  console.log('Primary:', first.name, '-> Alternatives:', alternatives.map((a) => a.name));
}

// 3. Read canonical equipment tokens and grounded training knowledge.
const taxonomy = await tf.GET('/v1/equipment');
const concepts = await tf.GET('/v1/knowledge/search', {
  params: { query: { q: 'autoregulation', limit: 3 } },
});
console.log(
  'Equipment tokens:',
  taxonomy.equipment.length,
  'Knowledge hits:',
  concepts.concepts.map((c) => c.name),
);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Query canonical exercises by equipment and primary muscle.
catalog = tf.list_exercises(equipment="barbell", muscle="quadriceps", limit=10)
print(f"Found {catalog['total']} exercises (showing {len(catalog['exercises'])})")

# 2. Fetch movement-pattern alternatives for the top match.
if catalog["exercises"]:
    first = catalog["exercises"][0]
    alternatives = tf.list_exercise_alternatives(first["id"], limit=5)
    print("Primary:", first["name"], "-> Alternatives:", [alt["name"] for alt in alternatives])

# 3. Read canonical equipment tokens and grounded training knowledge.
taxonomy = tf.list_equipment()
concepts = tf.search_knowledge(q="autoregulation", limit=3)
print(
    "Equipment tokens:",
    len(taxonomy["equipment"]),
    "Knowledge hits:",
    [c["name"] for c in concepts["concepts"]],
)
```

***

### 2. Simulate a 6-week injury-return lifecycle in the sandbox

**Built for:** Any developer evaluating the platform, plus automated QA and CI test suites.

**When to use this scenario:** You want to experience the full deterministic engine, body-state shifts, program re-planning, and test webhook delivery in under a minute without recruiting a single real test user or touching live data.

**Required scopes and mode:** Any **test key** (`tf_test_*`) from a free personal workspace or an organization workspace. Sandbox endpoints always reject live keys (`403`).

**What happens end-to-end:** `GET /v1/sandbox/presets` lists the built-in teammate histories, `POST /v1/sandbox/teammates` creates a deterministic simulated teammate (`returning_from_knee_injury` with `seed: 42` and 6 weeks of starting history), `POST /v1/sandbox/teammates/{simulated_id}/simulate` advances the simulated clock week by week under chosen behaviors (`on_plan`, `reports_pain`), and `GET /v1/teammates/{external_id}/body-state` shows the resulting left-knee caution before you clean up with `POST /v1/sandbox/reset`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Inspect available presets and weekly behaviors.
const catalog = await tf.GET('/v1/sandbox/presets');
console.log('Presets:', catalog.presets.map((p) => p.name));

// 2. Spawn a deterministic simulated teammate with 6 weeks of injury-return history.
const created = await tf.POST('/v1/sandbox/teammates', {
  body: {
    external_id: 'sim-knee-001',
    preset: 'returning_from_knee_injury',
    seed: 42,
  },
});
console.log('Seeded events:', created.history.events, 'Program job:', created.program_job_id);

// 3. Advance two simulated weeks: one clean week, then one week where knee pain flares up.
const week1 = await tf.POST('/v1/sandbox/teammates/{simulated_id}/simulate', {
  params: { path: { simulated_id: 'sim-knee-001' } },
  body: { behavior: 'on_plan', include_device_readings: true },
});
const week2 = await tf.POST('/v1/sandbox/teammates/{simulated_id}/simulate', {
  params: { path: { simulated_id: 'sim-knee-001' } },
  body: { behavior: 'reports_pain' },
});
console.log(
  'Week 1 accepted:',
  week1.events.accepted,
  'Week 2 replan requested:',
  week2.replan_requested,
);

// 4. Inspect how the engine updated left-knee caution and recovery.
const state = await tf.GET('/v1/teammates/{external_id}/body-state', {
  params: { path: { external_id: 'sim-knee-001' } },
});
const leftKnee = state.joints.find((j) => j.joint === 'knee' && j.side === 'left');
console.log('Left knee after week 2:', leftKnee);

// 5. Reset the sandbox when your test run finishes.
const reset = await tf.POST('/v1/sandbox/reset');
console.log('Removed simulated teammates:', reset.teammates_removed);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Inspect available presets and weekly behaviors.
catalog = tf.list_sandbox_presets()
print("Presets:", [p["name"] for p in catalog["presets"]])

# 2. Spawn a deterministic simulated teammate with 6 weeks of injury-return history.
created = tf.create_sandbox_teammate(
    {
        "external_id": "sim-knee-001",
        "preset": "returning_from_knee_injury",
        "seed": 42,
    }
)
print("Seeded events:", created["history"]["events"], "Program job:", created["program_job_id"])

# 3. Advance two simulated weeks: one clean week, then one week where knee pain flares up.
week1 = tf.simulate_sandbox_week(
    "sim-knee-001",
    {"behavior": "on_plan", "include_device_readings": True},
)
week2 = tf.simulate_sandbox_week(
    "sim-knee-001",
    {"behavior": "reports_pain"},
)
print(
    "Week 1 accepted:",
    week1["events"]["accepted"],
    "Week 2 replan requested:",
    week2["replan_requested"],
)

# 4. Inspect how the engine updated left-knee caution and recovery.
state = tf.get_teammate_body_state("sim-knee-001")
left_knee = next((j for j in state["joints"] if j["joint"] == "knee" and j["side"] == "left"), None)
print("Left knee after week 2:", left_knee)

# 5. Reset the sandbox when your test run finishes.
reset = tf.reset_sandbox()
print("Removed simulated teammates:", reset["teammates_removed"])
```

> [!TIP]
>
> See [Sandbox](https://docs.technicallyfit.com/guides/sandbox.md) for the full list of presets (`new_to_training`,
> `returning_from_knee_injury`, `endurance_runner`) and behaviors (`on_plan`,
> `misses_sessions`, `finds_it_hard`, `reports_pain`).

***

## Track 2: Training engine, consent, and deterministic adaptation

### 3. Onboard a teammate, send a claim invite, and handle consent

**Built for:** Gym chains, coaching platforms, and member CRMs syncing their existing member directory.

**When to use this scenario:** A new member joins your gym or app. You want to create their TechnicallyFit profile under your own stable `external_id`, hand them a claim link so they own their account, and write consent-aware reads that handle `403 consent_required` cleanly if the teammate declines or revokes an item later.

**Required scopes and mode:** `teammates:write`, `teammates:read` (plus `body_state:read` for the consent-gated read check). Works in test mode or organization live mode.

**What happens end-to-end:** `PUT /v1/teammates/{external_id}` idempotently creates an `unclaimed` placeholder you can already populate with history or a program. `POST /v1/teammates/{external_id}/invite` moves them to `invited` and returns a `claim_url` (or emails it) requesting specific consent items. Once claimed, reading a consent-gated surface raises `ConsentRequiredError` if the teammate turned that item off.

```typescript TypeScript theme={null}
import { ConsentRequiredError, createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Register or update the teammate under your own stable external_id.
const teammate = await tf.PUT('/v1/teammates/{external_id}', {
  params: { path: { external_id: 'member-1042' } },
  body: {
    display_name: 'Jordan Rivera',
    email: 'jordan@example.com',
    timezone: 'America/Chicago',
    metadata: { membership_tier: 'annual' },
  },
});
console.log('Upserted:', teammate.external_id, 'status:', teammate.status);

// 2. Generate a claim link to show inside your app (or pass delivery: 'email').
const invite = await tf.POST('/v1/teammates/{external_id}/invite', {
  params: { path: { external_id: 'member-1042' } },
  body: {
    delivery: 'link',
    request_consent: ['events', 'programs', 'body_state', 'usage_insights'],
  },
});
console.log('Invite status:', invite.status, 'claim URL:', invite.claim_url);

// 3. Always handle ConsentRequiredError on teammate-owned surfaces.
try {
  const state = await tf.GET('/v1/teammates/{external_id}/body-state', {
    params: { path: { external_id: 'member-1042' } },
  });
  console.log('Body state joints available:', state.joints.length);
} catch (error) {
  if (error instanceof ConsentRequiredError) {
    console.log('Teammate has not shared body state yet:', error.message);
  } else {
    throw error;
  }
}
```

```python Python theme={null}
import os

from technicallyfit import Client, ConsentRequiredError

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Register or update the teammate under your own stable external_id.
teammate = tf.upsert_teammate(
    "member-1042",
    {
        "display_name": "Jordan Rivera",
        "email": "jordan@example.com",
        "timezone": "America/Chicago",
        "metadata": {"membership_tier": "annual"},
    },
)
print("Upserted:", teammate["external_id"], "status:", teammate["status"])

# 2. Generate a claim link to show inside your app (or pass delivery="email").
invite = tf.invite_teammate(
    "member-1042",
    {
        "delivery": "link",
        "request_consent": ["events", "programs", "body_state", "usage_insights"],
    },
)
print("Invite status:", invite["status"], "claim URL:", invite.get("claim_url"))

# 3. Always handle ConsentRequiredError on teammate-owned surfaces.
try:
    state = tf.get_teammate_body_state("member-1042")
    print("Body state joints available:", len(state["joints"]))
except ConsentRequiredError as error:
    print("Teammate has not shared body state yet:", error)
```

> [!NOTE]
>
> Teammates own their accounts. Before a placeholder is claimed, your organization can
> populate events, goals, and programs; after claiming, the teammate decides every consent
> item and can revoke sharing at any time (emitting `teammate.disconnected` when sharing
> ends). See [Teammates and ownership](https://docs.technicallyfit.com/guides/teammates-and-ownership.md).

***

### 4. Ingest sets, observations, and body measurements with offline sync

**Built for:** Mobile workout apps, gym floor kiosks, and smart-scale sync backends.

**When to use this scenario:** Your client records completed sets, joint soreness check-ins, and body mass measurements in unreliable gym Wi-Fi environments, needs guaranteed deduplication across retries, and wants to undo an accidental entry cleanly without corrupting history.

**Required scopes and mode:** `events:write`. Works in test or live mode. `OfflineQueue` flushes in chunks through `POST /v1/events:bulk` (organization key).

**What happens end-to-end:** The SDK validates each event locally before sending. Sending via `tf.events.send` posts to `POST /v1/teammates/{external_id}/events` and returns a per-item status (`accepted`, `duplicate`, or `rejected` with a structured reason). `OfflineQueue` persists events while offline and flushes safely later without duplicates. If a user logged a wrong weight, `POST /v1/teammates/{external_id}/events/{event_id}:undo` takes the event back, rebuilds body state, and triggers re-planning.

```typescript TypeScript theme={null}
import {
  createClient,
  event,
  MemoryStorage,
  observation,
  OfflineQueue,
} from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

const completedSet = event.loggedSet({
  at: '2026-11-27T14:12:00Z',
  route: 'gym-app',
  recordId: 'session-882-set-1',
  movement: { name: 'Back Squat' },
  set: {
    number: 1,
    type: 'working',
    reps: 5,
    load: { value: 100, unit: 'kg' },
    effort: 7.5,
  },
});

const kneeSoreness = event.observation(
  observation.selfReport({
    quantity: 'soreness',
    joint: 'knee',
    side: 'left',
    value: 3,
    at: '2026-11-27T14:30:00Z',
    confidence: 0.9,
    recordId: 'checkin-882-soreness',
  }),
);

const bodyMass = event.observation(
  observation.measurement({
    quantity: 'body_mass',
    value: 78.4,
    unit: 'kg',
    at: '2026-11-27T08:15:00Z',
    route: 'gym-scale',
    recordId: 'scale-2026-11-27-1042',
    confidence: 0.95,
  }),
);

// 1. Send immediately and inspect every item's accepted/duplicate/rejected outcome.
const direct = await tf.events.send('member-1042', [completedSet, kneeSoreness]);
for (const item of direct.results) {
  if (item.status === 'rejected') {
    console.warn('Rejected event at index', item.index, item.reason);
  } else {
    console.log('Event', item.index, item.status, item.event_id);
  }
}

// 2. Queue offline readings and flush safely once connectivity returns.
const queue = new OfflineQueue({
  client: tf,
  storage: new MemoryStorage(),
  batchSize: 50,
});
await queue.add('member-1042', [bodyMass]);
const flushed = await queue.flush();
console.log('Flushed:', flushed.accepted, 'accepted,', flushed.duplicate, 'duplicates');

// 3. Take back a mislogged event (rebuilds body state and re-plans affected sessions).
const firstAccepted = direct.results.find((r) => r.status === 'accepted' && r.event_id);
if (firstAccepted?.event_id) {
  const undone = await tf.POST('/v1/teammates/{external_id}/events/{event_id}:undo', {
    params: { path: { external_id: 'member-1042', event_id: firstAccepted.event_id } },
  });
  console.log('Event taken back:', undone.id, undone.status, undone.taken_back_at);
}
```

```python Python theme={null}
import os

from technicallyfit import (
    Client,
    MemoryStorage,
    OfflineQueue,
    event,
    measurement,
    self_report,
)

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

completed_set = event.logged_set(
    at="2026-11-27T14:12:00Z",
    route="gym-app",
    record_id="session-882-set-1",
    movement={"name": "Back Squat"},
    number=1,
    set_type="working",
    reps=5,
    load={"value": 100, "unit": "kg"},
    effort=7.5,
)

knee_soreness = event.observation(
    self_report(
        quantity="soreness",
        joint="knee",
        side="left",
        value=3,
        at="2026-11-27T14:30:00Z",
        confidence=0.9,
        record_id="checkin-882-soreness",
    )
)

body_mass = event.observation(
    measurement(
        quantity="body_mass",
        value=78.4,
        unit="kg",
        at="2026-11-27T08:15:00Z",
        route="gym-scale",
        record_id="scale-2026-11-27-1042",
        confidence=0.95,
    )
)

# 1. Send immediately and inspect every item's accepted/duplicate/rejected outcome.
direct = tf.events.send("member-1042", [completed_set, knee_soreness])
for item in direct["results"]:
    if item["status"] == "rejected":
        print("Rejected event at index", item["index"], item.get("reason"))
    else:
        print("Event", item["index"], item["status"], item.get("event_id"))

# 2. Queue offline readings and flush safely once connectivity returns.
queue = OfflineQueue(tf, MemoryStorage(), batch_size=50)
queue.add("member-1042", [body_mass])
flushed = queue.flush()
print("Flushed:", flushed.accepted, "accepted,", flushed.duplicate, "duplicates")

# 3. Take back a mislogged event (rebuilds body state and re-plans affected sessions).
first_accepted = next((r for r in direct["results"] if r["status"] == "accepted" and r.get("event_id")), None)
if first_accepted is not None:
    undone = tf.undo_teammate_event("member-1042", first_accepted["event_id"])
    print("Event taken back:", undone["id"], undone["status"], undone["taken_back_at"])
```

> [!TIP]
>
> Replace `MemoryStorage` with a file, SQLite table, or device-storage adapter in production
> so queued events survive app restarts. See [Offline batching](https://docs.technicallyfit.com/sdks/offline-batching.md).

***

### 5. Generate a deterministic program and audit every revision

**Built for:** Fitness apps, digital health platforms, and coaching software that need auditable, scientifically constrained prescriptions rather than unconstrained LLM workouts.

**When to use this scenario:** You want to generate a multi-week training program tailored to a teammate's goal, schedule, and location equipment, display today's session immediately (including an on-demand `easier` or `harder` variant), and inspect the deterministic revision trail (`revision`, `engine_version`, and `cause.summary`).

**Required scopes and mode:** `programs:write` and `programs:read`. Works in test or live mode. After a teammate claims their account, they must allow `programs` consent.

**What happens end-to-end:** `POST /v1/teammates/{external_id}/programs` returns `202` with a job record. Your app polls `GET /v1/program-jobs/{job_id}` (or listens for the `program.revised` webhook in production), reads today's scheduled workout via `GET /v1/teammates/{external_id}/sessions/today`, and audits every change through `GET /v1/teammates/{external_id}/programs/{program_id}/revisions`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Start deterministic multi-week program generation with an idempotency key.
const job = await tf.POST('/v1/teammates/{external_id}/programs', {
  params: { path: { external_id: 'member-1042' } },
  body: {
    idempotency_key: 'program-2026-q4-member-1042',
    weeks: 8,
    sessions_per_week: 4,
    session_minutes: 60,
    training_weekdays: [0, 2, 4, 5],
    goal: {
      type: 'strength',
      title: 'Build squat strength',
      target: { quantity: 'squat_e1rm', value: 140, unit: 'kg' },
    },
    start: 'when_free',
  },
});

// 2. Poll the job (in production, subscribe to the `program.revised` webhook instead).
let current = await tf.GET('/v1/program-jobs/{job_id}', {
  params: { path: { job_id: job.id } },
});
while (current.status === 'queued' || current.status === 'running') {
  await new Promise((resolve) => setTimeout(resolve, 1500));
  current = await tf.GET('/v1/program-jobs/{job_id}', {
    params: { path: { job_id: job.id } },
  });
}

if (current.status !== 'succeeded' || !current.result) {
  throw new Error(`Program job ended with status ${current.status}`);
}

const programId = current.result.program_id;

// 3. Read today's session (pass effort: 'easier' or 'harder' for a non-destructive variant).
const today = await tf.GET('/v1/teammates/{external_id}/sessions/today', {
  params: {
    path: { external_id: 'member-1042' },
    query: { effort: 'as_planned' },
  },
});
console.log(
  'Today:',
  today.date,
  'Engine:',
  today.engine_version,
  'Blocks:',
  today.session?.blocks.length ?? 0,
);

// 4. Audit the immutable revision history with exact cause summaries.
const revisions = await tf.GET('/v1/teammates/{external_id}/programs/{program_id}/revisions', {
  params: {
    path: { external_id: 'member-1042', program_id: programId },
    query: { limit: 10 },
  },
});
for (const rev of revisions.data) {
  console.log(`Rev ${String(rev.revision)} (${rev.engine_version}): ${rev.cause.summary}`);
}
```

```python Python theme={null}
import os
import time

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Start deterministic multi-week program generation with an idempotency key.
job = tf.create_program(
    "member-1042",
    {
        "idempotency_key": "program-2026-q4-member-1042",
        "weeks": 8,
        "sessions_per_week": 4,
        "session_minutes": 60,
        "training_weekdays": [0, 2, 4, 5],
        "goal": {
            "type": "strength",
            "title": "Build squat strength",
            "target": {"quantity": "squat_e1rm", "value": 140, "unit": "kg"},
        },
        "start": "when_free",
    },
)

# 2. Poll the job (in production, subscribe to the `program.revised` webhook instead).
current = tf.get_program_job(job["id"])
while current["status"] in ("queued", "running"):
    time.sleep(1.5)
    current = tf.get_program_job(job["id"])

if current["status"] != "succeeded" or not current.get("result"):
    raise RuntimeError(f"Program job ended with status {current['status']}")

program_id = current["result"]["program_id"]

# 3. Read today's session (pass effort="easier" or "harder" for a non-destructive variant).
today = tf.get_today_session("member-1042", effort="as_planned")
session = today.get("session") or {}
print(
    "Today:",
    today["date"],
    "Engine:",
    today["engine_version"],
    "Blocks:",
    len(session.get("blocks", [])),
)

# 4. Audit the immutable revision history with exact cause summaries.
revisions = tf.list_program_revisions("member-1042", program_id, limit=10)
for rev in revisions["data"]:
    print(f"Rev {rev['revision']} ({rev['engine_version']}): {rev['cause']['summary']}")
```

***

### 6. Read joint caution, recovery, and uncertainty without a wearable

**Built for:** Physical therapy and return-to-play clinics, sports performance staff, and adaptive coaching apps.

**When to use this scenario:** You want to know how careful to be with every joint, how recovered it is from recent workload, and how much epistemic uncertainty remains, even when a teammate wears **zero devices**. Body state is computed purely from logged sets, self-reported soreness, and known constraints, and never alters a program unless you explicitly opt in.

**Required scopes and mode:** `body_state:read` and `teammates:write`. Works in test or live mode. Requires the teammate's `body_state` consent after claim.

**What happens end-to-end:** Your app reads per-joint `caution`, `recovery`, and `uncertainty` from `GET /v1/teammates/{external_id}/body-state`, flags joints with elevated caution or high uncertainty (meaning more observations are needed), and optionally turns on body-state-aware planning for this teammate through `PATCH /v1/teammates/{external_id}/settings`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Read per-joint caution, recovery, and epistemic uncertainty (works with zero hardware).
const state = await tf.GET('/v1/teammates/{external_id}/body-state', {
  params: { path: { external_id: 'member-1042' } },
});

const elevated = state.joints.filter((j) => j.caution >= 0.25);
for (const entry of elevated) {
  console.log(
    `${entry.joint} (${entry.side}): caution=${entry.caution.toFixed(2)}, recovery=${entry.recovery.toFixed(2)}, uncertainty=${entry.uncertainty.toFixed(2)}`,
  );
}

// 2. Opt this teammate into body-state-aware program planning (off by default).
const settings = await tf.PATCH('/v1/teammates/{external_id}/settings', {
  params: { path: { external_id: 'member-1042' } },
  body: { body_state_planner: true },
});
console.log('Body-state planner enabled:', settings.body_state_planner);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Read per-joint caution, recovery, and epistemic uncertainty (works with zero hardware).
state = tf.get_teammate_body_state("member-1042")

elevated = [j for j in state["joints"] if j["caution"] >= 0.25]
for entry in elevated:
    print(
        f"{entry['joint']} ({entry['side']}): "
        f"caution={entry['caution']:.2f}, "
        f"recovery={entry['recovery']:.2f}, "
        f"uncertainty={entry['uncertainty']:.2f}"
    )

# 2. Opt this teammate into body-state-aware program planning (off by default).
settings = tf.update_teammate_settings("member-1042", {"body_state_planner": True})
print("Body-state planner enabled:", settings["body_state_planner"])
```

> [!WARNING]
>
> Body state is a training-load estimate, not a medical diagnosis. Never present caution
> values as an injury diagnosis; when a teammate reports pain, direct them to a qualified
> clinician. See [Body state](https://docs.technicallyfit.com/guides/body-state.md).

***

### 7. Run an async coach-in-the-loop proposal review workflow

**Built for:** Coaching platforms, high-touch performance academies, and collegiate or professional strength and conditioning staffs.

**When to use this scenario:** Your coached teammates have human coaches who retain final authority over program changes. When a constraint or workload event suggests revising upcoming sessions, TechnicallyFit opens a pending proposal instead of silently overwriting the plan.

**Required scopes and mode:** `events:write`, `proposals:read`, and `proposals:write`. Requires organization **live** mode (test-mode events never create proposals).

**What happens end-to-end:** Sending a `constraint` event queues the engine asynchronously. When the engine proposes changes, TechnicallyFit pushes a `proposal.created` webhook to your backend. Your coaching UI reads the proposal diff via `GET /v1/proposals/{proposal_id}` (or lists pending proposals via `GET /v1/teammates/{external_id}/proposals`), displays the exact session changes to the coach, and records either `POST /v1/proposals/{proposal_id}/accept` or `POST /v1/proposals/{proposal_id}/decline` with the coach's reason.

```typescript TypeScript theme={null}
import { createClient, event } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// Step 1: Report a joint constraint (the engine evaluates it asynchronously).
await tf.events.send('member-1042', [
  event.constraint({
    action: 'add',
    joint: 'knee',
    side: 'left',
    constraintType: 'injury',
    severity: 'moderate',
    note: 'Patellar tendon irritation during deep flexion',
    at: '2026-11-27T10:00:00Z',
    idempotencyKey: 'constraint-knee-2026-11-27',
  }),
]);

// Step 2: Triggered from your `proposal.created` webhook handler (or coach inbox refresh).
export async function reviewProposal(
  proposalId: string,
  coachId: string,
  approve: boolean,
  declineReason?: string,
) {
  const proposal = await tf.GET('/v1/proposals/{proposal_id}', {
    params: { path: { proposal_id: proposalId } },
  });

  console.log('Proposal cause:', proposal.cause.summary);
  if (proposal.diff) {
    console.log('Diff summary:', proposal.diff.summary, 'Changes:', proposal.diff.changes.length);
  }

  if (approve) {
    const accepted = await tf.POST('/v1/proposals/{proposal_id}/accept', {
      params: { path: { proposal_id: proposal.id } },
      body: { coach_id: coachId },
    });
    console.log('Coach accepted:', accepted.status, 'at', accepted.decided_at);
    return accepted;
  }

  const declined = await tf.POST('/v1/proposals/{proposal_id}/decline', {
    params: { path: { proposal_id: proposal.id } },
    body: {
      coach_id: coachId,
      reason: declineReason ?? 'Keeping current block through Friday testing.',
    },
  });
  console.log('Coach declined:', declined.status, 'at', declined.decided_at);
  return declined;
}
```

```python Python theme={null}
import os

from technicallyfit import Client, event

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# Step 1: Report a joint constraint (the engine evaluates it asynchronously).
tf.events.send(
    "member-1042",
    [
        event.constraint(
            action="add",
            joint="knee",
            side="left",
            constraint_type="injury",
            severity="moderate",
            note="Patellar tendon irritation during deep flexion",
            at="2026-11-27T10:00:00Z",
            idempotency_key="constraint-knee-2026-11-27",
        )
    ],
)


# Step 2: Triggered from your `proposal.created` webhook handler (or coach inbox refresh).
def review_proposal(
    proposal_id: str,
    coach_id: str,
    approve: bool,
    decline_reason: str | None = None,
) -> dict:
    proposal = tf.get_proposal(proposal_id)
    print("Proposal cause:", proposal["cause"]["summary"])
    if proposal.get("diff"):
        print("Diff summary:", proposal["diff"]["summary"], "Changes:", len(proposal["diff"]["changes"]))

    if approve:
        accepted = tf.accept_proposal(proposal["id"], {"coach_id": coach_id})
        print("Coach accepted:", accepted["status"], "at", accepted["decided_at"])
        return accepted

    declined = tf.decline_proposal(
        proposal["id"],
        {
            "coach_id": coach_id,
            "reason": decline_reason or "Keeping current block through Friday testing.",
        },
    )
    print("Coach declined:", declined["status"], "at", declined["decided_at"])
    return declined
```

***

### 8. Adapt a workout live mid-session with one-tap undo

**Built for:** Interactive training apps, smart gym floor displays, and velocity-based training apps.

**When to use this scenario:** During a live workout, a teammate logs a set whose effort spikes far above target. TechnicallyFit's live adaptation adjusts remaining sets automatically while keeping the teammate in complete control via a single-tap undo (`:veto`).

**Required scopes and mode:** `programs:read`, `programs:write`, and `events:write`. Works in test or live mode where live adaptation is enabled.

**What happens end-to-end:** Your app enables a preset via `PUT /v1/teammates/{external_id}/adaptation-profile`, starts today's session via `POST /v1/teammates/{external_id}/sessions/today:start` and captures the baseline prescription, logs a high-effort set (`effort: 9.5`), reads the updated session from `GET /v1/teammates/{external_id}/sessions/today` to display before-vs-after remaining sets, and wires a one-tap Undo button to `POST /v1/teammates/{external_id}/adaptations/{adaptation_id}:veto` using the `adaptation_id` delivered on the `session.adapted` webhook.

```typescript TypeScript theme={null}
import { createClient, event } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Inspect available presets and enable the strength preset for the next session.
const presets = await tf.GET('/v1/adaptation-presets');
console.log('Presets:', presets.presets.map((p) => p.name));

await tf.PUT('/v1/teammates/{external_id}/adaptation-profile', {
  params: { path: { external_id: 'member-1042' } },
  body: { enabled: true, preset: 'strength' },
});

// 2. Start today's session and capture the initial block targets.
const started = await tf.POST('/v1/teammates/{external_id}/sessions/today:start', {
  params: { path: { external_id: 'member-1042' } },
  body: { effort: 'as_planned' },
});
const beforeLoad = started.session?.blocks[0]?.load;

// 3. Log a tough opening set whose effort is well above target.
await tf.events.send('member-1042', [
  event.loggedSet({
    at: '2026-11-27T15:05:00Z',
    route: 'gym-app',
    recordId: 'live-session-set-1',
    movement: { name: 'Back Squat' },
    set: {
      number: 1,
      type: 'working',
      reps: 5,
      load: { value: 120, unit: 'kg' },
      effort: 9.5,
    },
  }),
]);

// 4. Read today's session to compare before vs. after prescription.
const adapted = await tf.GET('/v1/teammates/{external_id}/sessions/today', {
  params: { path: { external_id: 'member-1042' } },
});
const afterLoad = adapted.session?.blocks[0]?.load;
console.log('Prescription revision:', started.revision, '->', adapted.revision, {
  beforeLoad,
  afterLoad,
});

// 5. Wire your app's "Undo adaptation" button to the `adaptation_id` received on `session.adapted`.
export async function undoLatestAdaptation(externalId: string, adaptationId: string) {
  const vetoed = await tf.POST('/v1/teammates/{external_id}/adaptations/{adaptation_id}:veto', {
    params: { path: { external_id: externalId, adaptation_id: adaptationId } },
  });
  console.log('Reverted adaptation:', vetoed.status, 'at', vetoed.vetoed_at);
  return vetoed;
}
```

```python Python theme={null}
import os

from technicallyfit import Client, event

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Inspect available presets and enable the strength preset for the next session.
presets = tf.list_adaptation_presets()
print("Presets:", [p["name"] for p in presets["presets"]])

tf.update_teammate_adaptation_profile(
    "member-1042",
    {"enabled": True, "preset": "strength"},
)

# 2. Start today's session and capture the initial block targets.
started = tf.start_today_session("member-1042", {"effort": "as_planned"})
before_blocks = (started.get("session") or {}).get("blocks", [])
before_load = before_blocks[0]["load"] if before_blocks else None

# 3. Log a tough opening set whose effort is well above target.
tf.events.send(
    "member-1042",
    [
        event.logged_set(
            at="2026-11-27T15:05:00Z",
            route="gym-app",
            record_id="live-session-set-1",
            movement={"name": "Back Squat"},
            number=1,
            set_type="working",
            reps=5,
            load={"value": 120, "unit": "kg"},
            effort=9.5,
        )
    ],
)

# 4. Read today's session to compare before vs. after prescription.
adapted = tf.get_today_session("member-1042")
after_blocks = (adapted.get("session") or {}).get("blocks", [])
after_load = after_blocks[0]["load"] if after_blocks else None
print(
    "Prescription revision:",
    started["revision"],
    "->",
    adapted["revision"],
    {"before_load": before_load, "after_load": after_load},
)


# 5. Wire your app's "Undo adaptation" button to the `adaptation_id` received on `session.adapted`.
def undo_latest_adaptation(external_id: str, adaptation_id: str) -> dict:
    vetoed = tf.veto_session_adaptation(external_id, adaptation_id)
    print("Reverted adaptation:", vetoed["status"], "at", vetoed["vetoed_at"])
    return vetoed
```

***

## Track 3: Hardware, real-time telemetry, and verified records

### 9. Stream live sensor data for real-time cues with reconnect recovery

**Built for:** Connected hardware makers (linear encoders, smart racks, wearables) and real-time training apps.

**When to use this scenario:** You are streaming live readings during an active set, such as Bluetooth GATT heart rate (`0x180D / 0x2A37`) or rep-by-rep bar velocity (`m/s`), want immediate server-evaluated cues when velocity drops past a threshold, need automatic checkpoint resume if basement gym Wi-Fi drops, and want the entire stream folded once into clean summary observations on close.

**Required scopes and mode:** `events:write`. Connects to the live gateway at `wss://live.technicallyfit.com`.

**What happens end-to-end:** `openLiveSession` (TypeScript) and `open_live_session` (Python) authenticate over WebSocket, decode standard BLE packets with `@technicallyfit/source-adapters` or send bar-velocity readings directly via `sendReadings` / `send_readings`, invoke `onCue` / `on_cue` when a live cue rule fires, recover transparently via `session.resume()` after a dropped socket without double-counting acknowledged batches, and fold the session into durable summary observations on `session.close()`.

```typescript TypeScript theme={null}
import { LiveSessionError, openLiveSession } from '@technicallyfit/sdk';
import { heartRateChestStrapAdapter } from '@technicallyfit/source-adapters';

const session = await openLiveSession({
  baseUrl: process.env.TF_LIVE_BASE ?? 'wss://live.technicallyfit.com',
  teammate: 'member-1042',
  credential: process.env.TF_API_KEY ?? '',
  onCue: (cue) => {
    console.log('Live cue:', cue.rule_id, cue.cue_id, cue.payload);
  },
});

// 1. Decode a standard Bluetooth GATT Heart Rate Measurement packet (flags 0x06, 152 bpm).
const hrEvents = heartRateChestStrapAdapter.toEvents({
  payload: new Uint8Array([0x06, 152]),
  receivedAt: '2026-11-27T15:10:00Z',
  deviceLabel: 'chest-strap-01',
  session: session.sessionId,
  setIndex: 0,
});

// 2. Stream heart rate and rep-by-rep bar velocity readings for live velocity-loss cues.
const batch: Record<string, unknown>[] = [
  ...hrEvents.map((item) => item.data as unknown as Record<string, unknown>),
  {
    quantity: 'bar_velocity',
    measure: 'mean',
    value: 0.72,
    unit: 'm/s',
    at: '2026-11-27T15:10:02Z',
    set_index: 0,
  },
  {
    quantity: 'bar_velocity',
    measure: 'mean',
    value: 0.54,
    unit: 'm/s',
    at: '2026-11-27T15:10:05Z',
    set_index: 0,
  },
];

try {
  const ack = await session.sendReadings(batch);
  console.log('Acknowledged batch:', ack.seq, 'accepted:', ack.accepted_count);
} catch (error) {
  // 3. If gym Wi-Fi drops, resume from last_ack_seq without losing cue cooldowns.
  if (error instanceof LiveSessionError && error.retryable) {
    const resumed = await session.resume();
    console.log('Resumed session:', resumed.sessionId, 'at seq:', resumed.lastAckSeq);
  } else {
    throw error;
  }
}

// 4. Close the session to fold the stream once into durable summary observations.
const closed = await session.close();
console.log('Session closed:', closed.session_id, 'readings:', closed.reading_count);
```

```python Python theme={null}
import os

from technicallyfit import LiveSessionError, open_live_session


def parse_ble_heart_rate(packet: bytes) -> int:
    """Decode BPM from a standard Bluetooth GATT 0x2A37 Heart Rate Measurement packet."""
    flags = packet[0]
    is_uint16 = bool(flags & 0x01)
    return int.from_bytes(packet[1:3], "little") if is_uint16 else packet[1]


session = open_live_session(
    base_url=os.environ.get("TF_LIVE_BASE", "wss://live.technicallyfit.com"),
    teammate="member-1042",
    credential=os.environ["TF_API_KEY"],
    on_cue=lambda cue: print("Live cue:", cue.rule_id, cue.cue_id, cue.payload),
)

bpm = parse_ble_heart_rate(bytes([0x06, 152]))
batch = [
    {
        "quantity": "heart_rate",
        "measure": "mean",
        "value": bpm,
        "unit": "bpm",
        "at": "2026-11-27T15:10:00Z",
        "set_index": 0,
    },
    {
        "quantity": "bar_velocity",
        "measure": "mean",
        "value": 0.72,
        "unit": "m/s",
        "at": "2026-11-27T15:10:02Z",
        "set_index": 0,
    },
    {
        "quantity": "bar_velocity",
        "measure": "mean",
        "value": 0.54,
        "unit": "m/s",
        "at": "2026-11-27T15:10:05Z",
        "set_index": 0,
    },
]

try:
    ack = session.send_readings(batch)
    print("Acknowledged batch:", ack.seq, "accepted:", ack.accepted_count)
except LiveSessionError as error:
    if error.retryable:
        resumed_id = session.resume()
        print("Resumed session:", resumed_id, "at seq:", session.last_ack_seq)
    else:
        raise

closed = session.close()
print("Session closed:", closed.session_id, "readings:", closed.reading_count)
```

***

### 10. Build and certify a custom hardware source adapter

**Built for:** Hardware manufacturers (velocity trackers, force plates, smart racks, smart scales) and telemetry integrators onboarding a custom device without waiting on bespoke vendor code.

**When to use this scenario:** Your hardware produces proprietary telemetry frames and you want to map them into TechnicallyFit's canonical `observation/1` contract, declare stream reducers, prove that your mapping passes every schema, provenance, neutrality, and deduplication rule offline (and optionally against a test teammate), and ship with confidence.

**Required scopes and mode:** Offline conformance requires **no API key**. Passing the optional `live` option to `runConformance` uses a test key (`tf_test_*`) with `events:write` and verifies `accepted` on first send and `duplicate` on replay.

**What happens end-to-end:** You define a `source-adapter/2` manifest naming a vendor-neutral `device.kind` and `instrument` (`linear_encoder`), implement a pure `toEvents(record)` mapper (in TypeScript with `@technicallyfit/source-adapters`, or validated locally in Python with `observation` builders before ingestion), and run `runConformance` across sample records to check all 12 offline rules (`manifest.valid`, `events.schema`, `events.registry`, `events.provenance`, `events.no_vouching`, `reducers.valid`, `record_id.stable`, `neutral.names`, and more).

```typescript TypeScript theme={null}
import {
  adapterProvenance,
  runConformance,
  SOURCE_ADAPTER_V2_SCHEMA,
} from '@technicallyfit/source-adapters';
import type { SourceAdapter, SourceAdapterManifest } from '@technicallyfit/source-adapters';

interface EncoderRepRecord {
  readonly id: string;
  readonly at: string;
  readonly deviceLabel: string;
  readonly meanMps: number;
  readonly peakMps: number;
}

const manifest: SourceAdapterManifest = {
  schema: SOURCE_ADAPTER_V2_SCHEMA,
  name: 'linear-encoder-vbt',
  version: '1.0.0',
  route: 'gym-floor-encoder',
  description: 'Maps linear encoder rep summaries into mean and peak bar velocity observations.',
  requested_limits: { may_store: true, vera_may_read: true },
  device: { kind: 'linear_encoder', instrument: 'linear_encoder' },
  record_types: [
    {
      type: 'rep_velocity',
      emits: 'observation',
      timing: { streaming: true, sample_rate_hz: 1, expected_delay_ms: 200 },
      reducers: [
        { id: 'rep_peak_bar_velocity', version: 1 },
        { id: 'set_velocity_loss', version: 1 },
      ],
      produces: [
        {
          quantity: 'bar_velocity',
          measure: 'mean',
          unit: 'm/s',
          body: 'none',
          default_confidence: 0.95,
        },
        {
          quantity: 'bar_velocity',
          measure: 'peak',
          unit: 'm/s',
          body: 'none',
          default_confidence: 0.95,
        },
        {
          quantity: 'velocity_loss',
          measure: null,
          unit: 'percent',
          body: 'none',
          default_confidence: 0.95,
        },
      ],
    },
  ],
};

const provenance = adapterProvenance(manifest);

const encoderAdapter: SourceAdapter<EncoderRepRecord> = {
  manifest,
  toEvents(record) {
    return [
      {
        type: 'observation',
        data: {
          schema: 'observation/1',
          quantity: 'bar_velocity',
          measure: 'mean',
          value: record.meanMps,
          unit: 'm/s',
          at: record.at,
          until: null,
          body: null,
          source: {
            route: manifest.route,
            device: record.deviceLabel,
            record_id: `${record.id}#bar_velocity.mean`,
          },
          confidence: 0.95,
          context: { adapter: provenance },
        },
      },
      {
        type: 'observation',
        data: {
          schema: 'observation/1',
          quantity: 'bar_velocity',
          measure: 'peak',
          value: record.peakMps,
          unit: 'm/s',
          at: record.at,
          until: null,
          body: null,
          source: {
            route: manifest.route,
            device: record.deviceLabel,
            record_id: `${record.id}#bar_velocity.peak`,
          },
          confidence: 0.95,
          context: { adapter: provenance },
        },
      },
    ];
  },
};

const report = await runConformance(encoderAdapter, [
  {
    type: 'rep_velocity',
    record: {
      id: 'set-1-rep-1',
      at: '2026-11-27T15:10:02Z',
      deviceLabel: 'rack-2-encoder',
      meanMps: 0.72,
      peakMps: 1.08,
    },
  },
]);

console.log('Conformance passed:', report.passed);
for (const check of report.checks) {
  if (!check.passed) console.error('Failed check:', check.id, check.detail);
}
```

```python Python theme={null}
import os
from typing import Any

from technicallyfit import Client, event, measurement, validate_observation

ADAPTER_PROVENANCE = "linear-encoder-vbt/1.0.0"
ROUTE = "gym-floor-encoder"


def map_encoder_rep(record: dict[str, Any]) -> list[dict[str, Any]]:
    """Pure, deterministic mapper emitting separate mean and peak velocity observations."""
    mean_obs = measurement(
        quantity="bar_velocity",
        measure="mean",
        value=record["mean_mps"],
        unit="m/s",
        at=record["at"],
        route=ROUTE,
        device=record["device_label"],
        record_id=f"{record['id']}#bar_velocity.mean",
        confidence=0.95,
        context={"adapter": ADAPTER_PROVENANCE},
    )
    peak_obs = measurement(
        quantity="bar_velocity",
        measure="peak",
        value=record["peak_mps"],
        unit="m/s",
        at=record["at"],
        route=ROUTE,
        device=record["device_label"],
        record_id=f"{record['id']}#bar_velocity.peak",
        confidence=0.95,
        context={"adapter": ADAPTER_PROVENANCE},
    )
    for obs in (mean_obs, peak_obs):
        # Raises ObservationValidationError, listing every problem, when one is not valid.
        validate_observation(obs)
    return [event.observation(mean_obs), event.observation(peak_obs)]


sample_events = map_encoder_rep(
    {
        "id": "set-1-rep-1",
        "at": "2026-11-27T15:10:02Z",
        "device_label": "rack-2-encoder",
        "mean_mps": 0.72,
        "peak_mps": 1.08,
    }
)

# Verify idempotent ingest against the teammate from scenario 3 (1st send: accepted, 2nd send: duplicate).
tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))
first = tf.events.send("member-1042", sample_events)
replay = tf.events.send("member-1042", sample_events)
print("First send:", first["summary"], "Replay:", replay["summary"])
```

> [!TIP]
>
> See [Adapting a source](https://docs.technicallyfit.com/guides/adapting-a-source.md) and [Supported devices](https://docs.technicallyfit.com/reference/supported-devices.md)
> for all built-in Bluetooth GATT starter adapters and `source-adapter/2` rules.

***

### 11. Issue and offline-verify a cryptographically attested record

**Built for:** Approved testing combines and performance labs (Issuer) plus scouts, colleges, leagues, and partner platforms (Offline Verifier, no API key required).

**When to use this scenario:** An approved facility records an official performance test (such as a 40-yard sprint timed with electronic timing gates), certifies it to Vouching Level 4 with an Ed25519 cryptographic attestation, and any third party verifies the signed envelope completely offline without holding a TechnicallyFit API key or accessing private account data.

| Vouching level | Meaning | How it is assigned |
| - | - | - |
| `1` | Self-reported or unvouched | Direct log or uncertified organization reading |
| `2` | Device or route captured | Arrived directly from a verified hardware capture route |
| `3` | Coach witnessed | Witnessed live by the teammate's active coach |
| `4` | Organization certified | Certified via `POST /v1/attestations` by an approved attestor and instrument |

**Required scopes and mode:** Part A (Issuer) requires `measurements:write` and `attestations:write`, in an organization workspace approved as an attestor. Any other workspace, a personal one included, gets `403` (`attestor_not_approved`). Part B (Verifier) uses only public endpoints (`GET /v1/attestations/keys` and `GET /v1/attestations/{attestation_id}/status`) with **no API key**.

**What happens end-to-end:** In Part A, the approved facility records the measurement and calls `POST /v1/attestations` to obtain a signed `attestation/1` envelope. In Part B, an independent third party caches TechnicallyFit's Ed25519 public key set, verifies the RFC 8785 canonical JSON signature offline via `verifyAttestation` / `verify_attestation`, and optionally checks live revocation status.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';
import { verifyAttestation } from '@technicallyfit/sdk/attestations';

const baseUrl = process.env.TF_API_BASE ?? 'https://api.technicallyfit.com';

// --- Part A: Approved Testing Facility (Issuer, holds organization API key) ---
const issuerClient = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl,
});

const recorded = await issuerClient.POST('/v1/teammates/{external_id}/measurements', {
  params: { path: { external_id: 'member-1042' } },
  body: {
    idempotency_key: 'combine-2026-40yd-1042',
    quantity: 'sprint_40yd_seconds',
    value: 4.62,
    unit: 's',
    observed_at: '2026-11-27T15:00:00Z',
    protocol: 'sprint_40yd',
    instrument: 'timing_gates',
    confidence: 1,
  },
});

const attestation = await issuerClient.POST('/v1/attestations', {
  body: {
    measurement_id: recorded.id,
    instrument_id: '8a4e2c1d-5b6f-4a7e-9c8d-1f2e3d4c5b6a',
  },
});

// --- Part B: Third-Party Verifier (NO API key, works completely offline) ---
// Fetch and cache the public key set once (standard public HTTPS GET, no auth header).
const keysResponse = await fetch(`${baseUrl}/v1/attestations/keys`);
const keys = await keysResponse.json();

// Verify the Ed25519 signature offline over RFC 8785 canonical JSON.
const verified = await verifyAttestation({ attestation, keys });
console.log(
  'Verified offline:',
  verified.statement.measurement.quantity,
  verified.statement.measurement.value,
  verified.statement.measurement.unit,
  'key:',
  verified.keyId,
);

// Optional online check to confirm the attestation has not been revoked or withdrawn.
const statusResponse = await fetch(
  `${baseUrl}/v1/attestations/${encodeURIComponent(verified.statement.attestation_id)}/status`,
);
const liveStatus = (await statusResponse.json()) as { status: string };
console.log('Live revocation status:', liveStatus.status);
```

```python Python theme={null}
import json
import os
import urllib.request

from technicallyfit import Client
from technicallyfit.attestations import verify_attestation

base_url = os.environ.get("TF_API_BASE", "https://api.technicallyfit.com").rstrip("/")

# --- Part A: Approved Testing Facility (Issuer, holds organization API key) ---
issuer_client = Client(os.environ["TF_API_KEY"], base_url=base_url)

recorded = issuer_client.record_teammate_measurement(
    "member-1042",
    {
        "idempotency_key": "combine-2026-40yd-1042",
        "quantity": "sprint_40yd_seconds",
        "value": 4.62,
        "unit": "s",
        "observed_at": "2026-11-27T15:00:00Z",
        "protocol": "sprint_40yd",
        "instrument": "timing_gates",
        "confidence": 1,
    },
)

attestation = issuer_client.create_attestation(
    {
        "measurement_id": recorded["id"],
        "instrument_id": "8a4e2c1d-5b6f-4a7e-9c8d-1f2e3d4c5b6a",
    }
)

# --- Part B: Third-Party Verifier (NO API key, works completely offline) ---
# Fetch and cache the public key set once (standard public HTTPS GET, no auth header).
with urllib.request.urlopen(f"{base_url}/v1/attestations/keys") as resp:
    keys = json.loads(resp.read().decode("utf-8"))

# Verify the Ed25519 signature offline over RFC 8785 canonical JSON.
verified = verify_attestation(attestation, keys)
measured = verified.statement["measurement"]
print(
    "Verified offline:",
    measured["quantity"],
    measured["value"],
    measured["unit"],
    "key:",
    verified.key_id,
)

# Optional online check to confirm the attestation has not been revoked or withdrawn.
attestation_id = verified.statement["attestation_id"]
with urllib.request.urlopen(f"{base_url}/v1/attestations/{attestation_id}/status") as resp:
    live_status = json.loads(resp.read().decode("utf-8"))
print("Live revocation status:", live_status["status"])
```

***

## Track 4: Multi-location gyms, webhooks, and branded member apps

### 12. Subscribe to outbound webhooks, fetch details, and rotate secrets with zero downtime

**Built for:** Backend platform engineers integrating TechnicallyFit into their CRM, coaching portal, or notification pipelines.

**When to use this scenario:** You want TechnicallyFit to push real-time notifications to your HTTPS server whenever a program changes, a coach proposal opens, or a teammate becomes at risk, without polling. You also need production-grade patterns: verifying raw bytes, deduplicating retries on `event.id`, fetching full details via the REST API, and rotating signing secrets with zero dropped deliveries.

**Required scopes and mode:** `webhooks:write` to register endpoints and rotate secrets, plus read scopes (such as `programs:read`) for follow-up detail fetches. Works in test or live mode.

**What happens end-to-end:** Webhooks are **outbound `POST` requests** pushed from TechnicallyFit to your server. Payloads carry IDs and summaries only (never full diffs or health values). Your handler verifies the raw body with `verifyWebhook` / `verify_webhook`, deduplicates on `event.id`, fetches fresh details over REST when needed, and passes `[newSecret, previousSecret]` during the overlap window returned by `POST /v1/webhook-endpoints/{id}/rotate-secret`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';
import { verifyWebhook, WebhookVerificationError } from '@technicallyfit/sdk/webhooks';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Register your HTTPS endpoint once and store `endpoint.secret` in your secret manager.
// Replace the URL with a public HTTPS address you control: a host that does not resolve
// to a public address is refused with `422` (`address_not_public`).
const endpoint = await tf.POST('/v1/webhook-endpoints', {
  body: {
    url: 'https://example.com/webhooks/technicallyfit',
    description: 'Program and retention alerts',
    events: ['program.revised', 'proposal.created', 'teammate.at_risk'],
  },
});
console.log('Endpoint:', endpoint.id, 'secret prefix:', endpoint.secret.slice(0, 10));

// 2. Rotate the secret with zero downtime: both secrets stay valid until previous_secret_expires_at.
const rotated = await tf.POST('/v1/webhook-endpoints/{id}/rotate-secret', {
  params: { path: { id: endpoint.id } },
});
const activeSecrets = [rotated.secret, endpoint.secret];
console.log('Previous secret valid until:', rotated.previous_secret_expires_at);

// 3. Inside your HTTP handler: verify raw bytes, dedupe on event.id, then fetch full details.
const seenEventIds = new Set<string>();

export async function handleWebhookRequest(
  rawBody: string | Uint8Array,
  headers: Record<string, string | string[] | undefined>,
): Promise<{ status: number }> {
  try {
    const verified = await verifyWebhook({
      rawBody,
      headers,
      secrets: activeSecrets,
    });

    if (seenEventIds.has(verified.id)) {
      return { status: 200 };
    }
    seenEventIds.add(verified.id);

    if (verified.type === 'program.revised') {
      const teammateId = String(verified.data.teammate);
      const today = await tf.GET('/v1/teammates/{external_id}/sessions/today', {
        params: { path: { external_id: teammateId } },
      });
      console.log('Refreshed session for', teammateId, 'rev:', today.revision);
    }

    return { status: 200 };
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      console.error('Rejected webhook:', error.reason);
      return { status: 400 };
    }
    throw error;
  }
}
```

```python Python theme={null}
import os
from collections.abc import Mapping
from typing import Any

from technicallyfit import Client, WebhookVerificationError, verify_webhook

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Register your HTTPS endpoint once and store endpoint["secret"] in your secret manager.
# Replace the URL with a public HTTPS address you control: a host that does not resolve
# to a public address is refused with 422 (address_not_public).
endpoint = tf.create_webhook_endpoint(
    {
        "url": "https://example.com/webhooks/technicallyfit",
        "description": "Program and retention alerts",
        "events": ["program.revised", "proposal.created", "teammate.at_risk"],
    }
)
print("Endpoint:", endpoint["id"], "secret prefix:", endpoint["secret"][:10])

# 2. Rotate the secret with zero downtime: both secrets stay valid until previous_secret_expires_at.
rotated = tf.rotate_webhook_endpoint_secret(endpoint["id"])
active_secrets = [rotated["secret"], endpoint["secret"]]
print("Previous secret valid until:", rotated["previous_secret_expires_at"])

# 3. Inside your HTTP handler: verify raw bytes, dedupe on event["id"], then fetch full details.
seen_event_ids: set[str] = set()


def handle_webhook_request(raw_body: bytes, headers: Mapping[str, Any]) -> int:
    try:
        verified = verify_webhook(raw_body, headers, active_secrets)
    except WebhookVerificationError as error:
        print("Rejected webhook:", error.reason)
        return 400

    event_id = verified["id"]
    if event_id in seen_event_ids:
        return 200
    seen_event_ids.add(event_id)

    if verified["type"] == "program.revised":
        teammate_id = str(verified["data"]["teammate"])
        today = tf.get_today_session(teammate_id)
        print("Refreshed session for", teammate_id, "rev:", today["revision"])

    return 200
```

> [!NOTE]
>
> Always verify `rawBody` before parsing JSON. Re-serializing parsed JSON changes whitespace
> or key ordering and breaks the HMAC-SHA256 signature check. See
> [Webhook verification](https://docs.technicallyfit.com/sdks/webhook-verification.md).

***

### 13. Handle a gym equipment outage with floor-wide program replanning

**Built for:** Multi-location gym chains and facility maintenance systems.

**When to use this scenario:** You run multiple clubs sharing a standard equipment baseline, and a machine (such as the leg press at your Northside club) breaks down until parts arrive. One API call updates that club's effective inventory and triggers TechnicallyFit to emit `location.inventory_changed` and adapt upcoming programs for teammates homed at that location.

**Required scopes and mode:** `locations:write` and `locations:read`. Works in test or live mode.

**What happens end-to-end:** `PUT /v1/locations/{location_external_id}` registers the club. `PUT /v1/inventory/baseline` defines the standard floor across every club. `PUT /v1/locations/{location_external_id}/overrides/{token}` marks `leg_press` as `out_of_service` with an expected `back_in_service_on` date. Reading `GET /v1/locations/{location_external_id}/inventory` returns the live effective inventory and unavailable list, and removing the override via `DELETE` restores it when repaired.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Register the club. An override on a location that does not exist is refused with `404`.
await tf.PUT('/v1/locations/{location_external_id}', {
  params: { path: { location_external_id: 'club-014' } },
  body: {
    name: 'Northside Strength',
    time_zone: 'America/Chicago',
    region: 'Midwest',
  },
});

// 2. Set the shared baseline equipment list carried across all locations.
await tf.PUT('/v1/inventory/baseline', {
  body: {
    items: [
      { token: 'barbell', count: 6 },
      { token: 'dumbbell', count: 2, attributes: { max_load_kg: 50 } },
      { token: 'leg_press', count: 2 },
      { token: 'cable_machine', count: 4 },
    ],
  },
});

// 3. Mark the leg press out of service at club-014 (triggers floor-wide replanning).
await tf.PUT('/v1/locations/{location_external_id}/overrides/{token}', {
  params: { path: { location_external_id: 'club-014', token: 'leg_press' } },
  body: {
    kind: 'out_of_service',
    back_in_service_on: '2026-12-05',
    note: 'Awaiting hydraulic pin replacement',
  },
});

// 4. Inspect club-014's effective inventory and unavailable items.
const inventory = await tf.GET('/v1/locations/{location_external_id}/inventory', {
  params: { path: { location_external_id: 'club-014' } },
});
console.log(
  'Available:',
  inventory.items.map((i) => i.token),
  'Unavailable:',
  inventory.unavailable.map((u) => `${u.token} (${u.reason})`),
);

// 5. Once repaired early, clear the override so programs can prescribe leg press again.
await tf.DELETE('/v1/locations/{location_external_id}/overrides/{token}', {
  params: { path: { location_external_id: 'club-014', token: 'leg_press' } },
});
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Register the club. An override on a location that does not exist is refused with 404.
tf.upsert_location(
    "club-014",
    {
        "name": "Northside Strength",
        "time_zone": "America/Chicago",
        "region": "Midwest",
    },
)

# 2. Set the shared baseline equipment list carried across all locations.
tf.replace_inventory_baseline(
    {
        "items": [
            {"token": "barbell", "count": 6},
            {"token": "dumbbell", "count": 2, "attributes": {"max_load_kg": 50}},
            {"token": "leg_press", "count": 2},
            {"token": "cable_machine", "count": 4},
        ]
    }
)

# 3. Mark the leg press out of service at club-014 (triggers floor-wide replanning).
tf.set_location_override(
    "club-014",
    "leg_press",
    {
        "kind": "out_of_service",
        "back_in_service_on": "2026-12-05",
        "note": "Awaiting hydraulic pin replacement",
    },
)

# 4. Inspect club-014's effective inventory and unavailable items.
inventory = tf.get_location_inventory("club-014")
print(
    "Available:",
    [item["token"] for item in inventory["items"]],
    "Unavailable:",
    [f"{u['token']} ({u['reason']})" for u in inventory["unavailable"]],
)

# 5. Once repaired early, clear the override so programs can prescribe leg press again.
tf.remove_location_override("club-014", "leg_press")
```

> [!TIP]
>
> Subscribe to `location.inventory_changed` to receive a count of homed teammates affected
> whenever a baseline, override, or out-of-service change lands. See
> [Locations and equipment](https://docs.technicallyfit.com/guides/locations-and-equipment.md).

***

### 14. Sync gym visits, read traffic, discover PT leads, and flag at-risk members

**Built for:** Gym operators, multi-club general managers, and retention/CRM teams.

**When to use this scenario:** You want your door-access system to feed visit check-ins into TechnicallyFit, read privacy-safe club traffic by day or hour, surface self-guided regulars who are ready for personal training (`ready_for_a_coach`), and trigger staff outreach for members slipping away (`once_and_gone` and `at-risk`).

**Required scopes and mode:** `locations:write`, `events:write`, and `insights:read`. Works in organization live mode (or test mode). Steps 1 and 2 also run in a personal workspace; the groups and at-risk reads (steps 3 and 4) need an organization workspace and answer `404` in a personal one.

**What happens end-to-end:** Your backend upserts a club via `PUT /v1/locations/{location_external_id}`, logs a door check-in (`visit_check_in`), queries `GET /v1/insights/traffic` for weekly/daily check-in volume (with groups smaller than `min_group_size: 5` automatically withheld for privacy), reads all six ready-made member cohorts via `GET /v1/insights/groups` (including `ready_for_a_coach` and `once_and_gone`), lists actionable members via `GET /v1/insights/groups/{key}/teammates`, and pulls retention alerts from `GET /v1/insights/at-risk`.

```typescript TypeScript theme={null}
import { createClient } from '@technicallyfit/sdk';

const tf = createClient({
  credential: process.env.TF_API_KEY ?? '',
  baseUrl: process.env.TF_API_BASE,
});

// 1. Register the club and send a door check-in event.
await tf.PUT('/v1/locations/{location_external_id}', {
  params: { path: { location_external_id: 'club-014' } },
  body: {
    name: 'Northside Strength',
    time_zone: 'America/Chicago',
    region: 'Midwest',
  },
});

await tf.POST('/v1/teammates/{external_id}/events', {
  params: { path: { external_id: 'member-1042' } },
  body: {
    events: [
      {
        type: 'visit_check_in',
        idempotency_key: 'door-7f3a9c',
        at: '2026-11-27T07:02:11Z',
        data: { location: 'club-014' },
      },
    ],
  },
});

// 2. Read weekly and daily traffic (groups under min_group_size are automatically withheld).
const traffic = await tf.GET('/v1/insights/traffic', {
  params: {
    query: { location: 'club-014', from: '2026-11-09', to: '2026-11-15', bucket: 'day' },
  },
});
for (const week of traffic.weeks) {
  console.log(
    `Week ${week.from}: active=${String(week.active_teammates.value)} (withheld=${String(week.active_teammates.withheld)})`,
  );
}

// 3. Read behavioral member groups and pull high-intent PT leads (`ready_for_a_coach`).
const groups = await tf.GET('/v1/insights/groups', {
  params: { query: { location: 'club-014' } },
});
for (const group of groups.data) {
  console.log(group.key, group.count.withheld ? '(withheld)' : group.count.value);
}

const ptLeads = await tf.GET('/v1/insights/groups/{key}/teammates', {
  params: {
    path: { key: 'ready_for_a_coach' },
    query: { location: 'club-014', limit: 25 },
  },
});
console.log('Ready for a coach:', ptLeads.data.map((m) => m.teammate));

// 4. List at-risk teammates for proactive staff outreach.
const atRisk = await tf.GET('/v1/insights/at-risk', {
  params: { query: { location: 'club-014', limit: 25 } },
});
console.log('At-risk teammates at club-014:', atRisk.data.length);
```

```python Python theme={null}
import os

from technicallyfit import Client

tf = Client(os.environ["TF_API_KEY"], base_url=os.environ.get("TF_API_BASE"))

# 1. Register the club and send a door check-in event.
tf.upsert_location(
    "club-014",
    {
        "name": "Northside Strength",
        "time_zone": "America/Chicago",
        "region": "Midwest",
    },
)

tf.send_teammate_events(
    "member-1042",
    {
        "events": [
            {
                "type": "visit_check_in",
                "idempotency_key": "door-7f3a9c",
                "at": "2026-11-27T07:02:11Z",
                "data": {"location": "club-014"},
            }
        ]
    },
)

# 2. Read weekly and daily traffic (groups under min_group_size are automatically withheld).
traffic = tf.get_traffic(
    location="club-014",
    from_="2026-11-09",
    to="2026-11-15",
    bucket="day",
)
for week in traffic["weeks"]:
    active = week["active_teammates"]
    print(f"Week {week['from']}: active={active['value']} (withheld={active['withheld']})")

# 3. Read behavioral member groups and pull high-intent PT leads (`ready_for_a_coach`).
groups = tf.list_groups(location="club-014")
for group in groups["data"]:
    count = "(withheld)" if group["count"]["withheld"] else group["count"]["value"]
    print(group["key"], count)

pt_leads = tf.list_group_teammates("ready_for_a_coach", location="club-014", limit=25)
print("Ready for a coach:", [m["teammate"] for m in pt_leads["data"]])

# 4. List at-risk teammates for proactive staff outreach.
at_risk = tf.list_at_risk(location="club-014", limit=25)
print("At-risk teammates at club-014:", len(at_risk["data"]))
```

***

### 15. Launch a branded member app with Sign in with TechnicallyFit and drop-in components

**Built for:** Gym brands, consumer fitness apps, and university athletics portals shipping a member-facing web or mobile app in an afternoon.

**When to use this scenario:** You want members to sign in to your branded web portal or mobile app using their own TechnicallyFit account (never shipping an organization API key onto client devices), pull your gym's brand theme from `GET /v1/app-config`, and embed TechnicallyFit's hosted drop-in components (`<tf-today-session>`, `<tf-record>`, and `<tf-live-cues>`) without building workout or verified-record screens from scratch.

**Required scopes and mode:** Sign in with TechnicallyFit OAuth (PKCE) tokens scoped to `teammates:read`, `programs:read`, and `record:read`. Organization API keys (`tf_live_*` / `tf_test_*`) are refused inside drop-in frames.

**What happens end-to-end:** Your app starts OAuth PKCE with `beginTeammateSignIn`, exchanges the redirect callback with `completeTeammateSignIn`, wraps the tokens in `RefreshingTeammateCredential` to call `GET /v1/app-config` and `GET /v1/teammates/@me`, and passes the in-memory teammate access token to `<tf-today-session>`, `<tf-record>`, and `<tf-live-cues>` via `setToken(token)` over `postMessage` (never in URLs or browser storage).

```typescript TypeScript theme={null}
import {
  beginTeammateSignIn,
  completeTeammateSignIn,
  createClient,
  RefreshingTeammateCredential,
} from '@technicallyfit/sdk';

const signInConfig = {
  issuer: process.env.TF_API_BASE ?? 'https://api.technicallyfit.com',
  clientId: 'tfc_northside_app',
  redirectUri: 'https://portal.northsidestrength.example/auth/callback',
  scopes: ['teammates:read', 'programs:read'] as const,
};

// 1. Start OAuth PKCE and open pending.url in the system browser.
const pending = await beginTeammateSignIn(signInConfig);

// 2. On redirect return, exchange the code, load brand config, and read @me.
export async function finishSignIn(callbackUrl: string) {
  const tokens = await completeTeammateSignIn(signInConfig, pending, callbackUrl);
  const credential = new RefreshingTeammateCredential(signInConfig, tokens);
  const memberClient = createClient({
    baseUrl: signInConfig.issuer,
    credential,
  });

  const [brand, me] = await Promise.all([
    memberClient.GET('/v1/app-config', {
      params: { query: { client_id: signInConfig.clientId } },
    }),
    memberClient.GET('/v1/teammates/@me'),
  ]);

  console.log('Brand:', brand.display_name, 'Accent:', brand.accent_color);
  console.log('Signed in as:', me.display_name, me.home_location_external_id);

  // Hand the in-memory access token to your drop-in elements via setToken(token).
  const accessToken = await credential.getToken();
  return { brand, me, accessToken };
}
```

```python Python theme={null}
import os

from technicallyfit import (
    Client,
    RefreshingTeammateCredential,
    TeammateSignInConfig,
    begin_teammate_sign_in,
    complete_teammate_sign_in,
)

sign_in_config = TeammateSignInConfig(
    issuer=os.environ.get("TF_API_BASE", "https://api.technicallyfit.com"),
    client_id="tfc_northside_app",
    redirect_uri="https://portal.northsidestrength.example/auth/callback",
    scopes=["teammates:read", "programs:read"],
)

# 1. Start OAuth PKCE and open pending.url in the system browser.
pending = begin_teammate_sign_in(sign_in_config)


# 2. On redirect return, exchange the code, load brand config, and read @me.
def finish_sign_in(callback_url: str) -> dict:
    tokens = complete_teammate_sign_in(sign_in_config, pending, callback_url)
    credential = RefreshingTeammateCredential(sign_in_config, tokens)
    member_client = Client(credential, base_url=sign_in_config.issuer)

    brand = member_client.get_app_config(client_id=sign_in_config.client_id)
    me = member_client.get_me()
    print("Brand:", brand["display_name"], "Accent:", brand["accent_color"])
    print("Signed in as:", me["display_name"], me.get("home_location_external_id"))
    return {"brand": brand, "me": me, "access_token": credential.get_token()}
```

```html Drop-in Components (HTML) theme={null}
<!-- Load once on any origin registered for your client_id -->
<script async src="https://technicallyfit.com/embeds/developer-v1.js"></script>

<tf-today-session
  id="today-session"
  client-id="tfc_northside_app"
  theme="light"
  accent="#02627b"
></tf-today-session>

<tf-record
  id="verified-record"
  client-id="tfc_northside_app"
  theme="dark"
  accent="#57ffbd"
></tf-record>

<tf-live-cues
  id="live-cues"
  client-id="tfc_northside_app"
  theme="light"
></tf-live-cues>

<script>
  // Pass the teammate OAuth token from memory via postMessage (never an org API key).
  const token = getTeammateAccessTokenFromMemory();
  document.getElementById('today-session').setToken(token);
  document.getElementById('verified-record').setToken(token);
  document.getElementById('live-cues').setToken(token);
</script>
```

> [!TIP]
>
> See [Sign in with TechnicallyFit](https://docs.technicallyfit.com/guides/sign-in-with-technicallyfit.md) and
> [Drop-in components](https://docs.technicallyfit.com/guides/drop-in-components.md) for origin allowlist rules, WCAG AA
> accent contrast checks, and mobile web view setup.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.