# Agora Health Voice

> Explore voice access to health and fitness data through reusable provider adapters.

Ask about sleep, heart rate, steps, distance and recent activities through authenticated tool calls. This TypeScript reference implementation pairs Agora Conversational AI Main v2, ARES STT, Agora-managed GPT-4o-mini and Murf Falcon TTS with a shared health-data provider interface: synthetic data is the default and powers the demo, and Garmin Personal API is the first validated live reference integration.

- Author: Ranga Jagannath
- Updated: 2026-11-17T06:56:55.345Z
- Guide language: unspecified
- Guide status: available
- Difficulty: Intermediate
- Categories: voice-ai
- Platforms: TypeScript, Web
- Use cases: Health & Wellness, Voice AI
- Capabilities: Conversational AI, Voice Agent, Tool Calling
- [Recipe page](https://recipes.agora.io/recipes/agora-health-voice)
- [Implementation repository](https://github.com/AgoraIO-Community/agora-health-voice)
- [Source recipe](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/README.md)
- [Raw source Markdown](https://raw.githubusercontent.com/AgoraIO-Community/agora-health-voice/main/README.md)
- [All recipes](https://recipes.agora.io/llms.txt)

## Implementation guide

# Agora Health Voice

Build a local voice assistant that answers questions about sleep, daily heart rate, steps, distance and recent activities using authenticated tool calls. This TypeScript recipe connects a browser to Agora Conversational AI, then routes measurement requests through a small, reusable health-data provider contract.

The default provider reads fictional fixtures: **no Garmin account, private health credentials or real health data are needed**. Garmin Personal API is the first live reference integration. Provider independence applies to health data; the voice stack is currently configured for Agora RTC, ARES speech recognition, Agora-managed GPT-4o-mini and Murf speech synthesis.

## Architecture

```mermaid
flowchart TB
    Browser["Browser: microphone and playback"] <-->|"RTC audio"| Agora["Agora Conversational AI"]
    Browser <-->|"Local session controls"| Local["Node: loopback port 3000"]
    Local -->|"Join / leave / status; server credentials"| Agora
    Agora --- Voice["ARES / managed GPT-4o-mini / Murf"]
    Agora -->|"HTTPS POST + session bearer"| Tunnel["HTTPS tunnel"]
    Tunnel -->|"Only port 3001"| Tools["Node: authenticated tool callbacks"]
    Tools <-->|"Normalized results"| Contract["HealthDataProvider"]
    Contract --- Synthetic["Default: fictional JSON fixtures"]
    Contract --- Garmin["Optional: Garmin Personal API"]
```

One conversational interface uses one configured health-data provider at a time; the synthetic and Garmin adapters share the same tools and browser.

One Node process binds two listeners on `127.0.0.1`. Port **3000** serves the browser and local Start/Stop controls; port **3001** serves tool callbacks. By default, tunnel only **3001**. The opt-in temporary mobile mode below separately protects browser access on **3000**. The callback listener returns `404` for the browser and session-control routes, and `401` for tool requests without a valid session bearer.

Implementation map: [browser](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/browser/main.ts), [local server and callbacks](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/server.ts), [Agora gateway](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/agora.ts), [tool schemas and normalization](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/tools.ts), [provider contract](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/providers/types.ts).

## Prerequisites and clone

Use Node.js **24 or later**, npm, Git and a modern browser. Local setup was assessed on macOS; other platforms have not been validated here. Voice additionally requires microphone permission, internet access, an Agora project with RTC token authentication and Conversational AI Main v2 access, Murf access, and an HTTPS tunnel utility.

```sh
git clone https://github.com/AgoraIO-Community/agora-health-voice.git
cd agora-health-voice
npm ci
cp .env.example .env
npm start
```

The repository is public; cloning does not require authorized GitHub access.

Before committing or pushing from **each clone**, install Gitleaks **8.30.1 or newer** and the repository's Git security hooks. Git does not install hooks automatically when cloning. On macOS, use `brew install gitleaks` if needed, then:

```sh
sh scripts/install_secret_hooks.sh
git config --local --get core.hooksPath  # expected: .githooks
```

See [Git secret protection](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/docs/git-secret-protection.md) for prerequisites and verification. The hooks scan staged contents and outgoing history, including removed secrets. Mobile passcode assignments and Quick Tunnel URLs are blocked outside exact, scoped documentation placeholders. Keep real values only in ignored local configuration; do not force-add credential files.

Open [http://localhost:3000](http://localhost:3000). Keep `HEALTH_DATA_PROVIDER=synthetic`. With all six voice settings blank, the page displays the synthetic indicator and setup state, with Start disabled. This is a credential-free setup preview, not an offline spoken conversation. `npm start` builds the application before starting the server.

## Enable synthetic voice

Keep credentials in the ignored `.env` file, on the server. The current configuration validator requires all six entries below when enabling voice:

| Setting | Current implementation |
|---|---|
| `AGORA_APP_ID` | Project identifier; also used by the browser to join RTC |
| `AGORA_APP_CERTIFICATE` | Server-only secret used to generate RTC and Agora control tokens |
| `AGORA_CUSTOMER_ID` | Legacy configuration field: required to be nonempty by startup validation, but unused by the current gateway |
| `AGORA_CUSTOMER_SECRET` | Legacy configuration field: required to be nonempty by startup validation, but unused by the current gateway |
| `MURF_API_KEY` | Server-side BYOK credential supplied to Agora for Murf synthesis |
| `TOOL_CALLBACK_ORIGIN` | Public HTTPS tunnel origin, without a path, query or embedded credentials |

The gateway authenticates control requests using `Authorization: agora token=...`, generated from the App ID and App Certificate. It does **not** use Customer ID/Secret for Basic authentication. Leave the legacy fields present to satisfy the existing validator; the application does not consume their values for authentication. No separate OpenAI key is configured: GPT-4o-mini uses Agora-managed credentials. Account access and service availability must be confirmed for your own Agora project.

1. Configure the voice entries locally. Do not paste credentials into source files, browser code, issue submissions or logs.
2. In another terminal, start an HTTPS tunnel to the callback listener. For [Cloudflare Quick Tunnels](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/):

   ```sh
   cloudflared tunnel --url http://127.0.0.1:3001
   ```

3. Set `TOOL_CALLBACK_ORIGIN` to the printed HTTPS origin. Restart `npm start` and reload the page. A new temporary tunnel normally has a different URL.
4. Select **Start**, allow microphone access and ask a question. A live session can incur Agora or Murf charges even with fictional data. If playback is blocked, select **Enable audio**.

See [Agora's join reference](https://docs.agora.io/en/api-reference/api-ref/conversational-ai/join) for the service API. Runtime configuration is in [src/agora.ts](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/src/agora.ts); this documentation update does not change it.

## Temporary HTTPS mobile testing (opt-in)

The default remains localhost-only. Mobile testing adds a separate exact browser origin and a dedicated high-entropy passcode; it does not reuse Agora credentials, the Garmin key, or callback bearers. The browser listener still binds to loopback. An origin allowlist alone is not authentication.

1. Start a **second** Quick Tunnel for the browser listener:

   ```sh
   cloudflared tunnel --url http://127.0.0.1:3000
   ```

   Keep the existing tool-callback tunnel pointing to **3001**. `TOOL_CALLBACK_ORIGIN` continues to describe only that callback tunnel. Use Cloudflare's normal host forwarding: do not override `Host` to localhost. The browser request must carry the configured public host. An optional `X-Forwarded-Host` must exactly match it; an optional `X-Forwarded-Proto` must be exactly `https`. RFC `Forwarded`, conflicting values, and forwarded-host/protocol headers on localhost requests are rejected.

2. Generate a dedicated passcode locally:

   ```sh
   node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("base64url") + "\n")'
   ```

   This command prints a secret to your own terminal. Do not share terminal output or paste it into chat, source code, URLs, or tunnel commands. Store it only in your ignored `.env`, preferably with owner-only permissions (`chmod 600 .env`). Add:

   ```dotenv
   MOBILE_BROWSER_ORIGIN=https://your-browser-tunnel.trycloudflare.com
   MOBILE_BROWSER_PASSCODE=<paste the generated passcode locally>
   ```

   Replace the origin with the exact HTTPS origin printed by the browser tunnel, **without a trailing slash**, path, query, fragment, credentials, or wildcard. Both settings are required together. Existing environment variables retain their meanings. These new settings remain server-only and are not returned by `/api/info`.

3. Restart with `npm start`. On mobile, open the browser tunnel's HTTPS URL and enter the passcode in the password form. Submit only through that HTTPS form. Authentication uses a random, host-only `Secure; HttpOnly; SameSite=Strict` cookie; JavaScript cannot read it. Start/Stop still requires the exact request origin and rejects cross-site requests. No CORS allowlist or proxy-wide trust is enabled. Microphone permission is requested by **Start Conversation** as before.

Access lasts at most one hour per login, with at most eight issued cookies retained in memory. Five failed passcode attempts trigger a one-minute shared cooldown. Restarting Node invalidates every issued cookie. There is no persistent account database or browser storage of the passcode. Login/logout does not start, stop, or extend a voice session; the existing voice-session cleanup and expiry still apply. To sign out on a device, clear this site's cookies. An authenticated same-origin `POST /mobile/logout` also revokes that cookie.

To disable testing, **Stop Conversation**, stop the browser tunnel, remove both `MOBILE_BROWSER_*` settings from `.env`, and restart Node. Close the mobile tab and clear its site data. Keep or stop the separate callback tunnel according to whether you are continuing local voice testing. A new Quick Tunnel URL requires an explicit origin update and restart. Rotate the passcode for each testing window.

This is temporary single-session testing, not a deployment mode. The existing single-session constraint remains shared between desktop and mobile. Voice still needs the existing Agora configuration and reachable authenticated callback tunnel. Actual mobile microphone capture, playback restrictions, and Cloudflare forwarding must be verified on your device.

## Tool calling and fixture demonstration

The model is instructed to call a tool for measurements, speak only returned values, preserve dates and explain missing data. Each synchronous callback uses a random per-session bearer and a five-second timeout. Inputs are validated before provider access; operational provider errors become `unavailable`, rather than fabricated measurements.

| Tool | Callback | Input |
|---|---|---|
| `getSleep` | `POST /tools/sleep` | `date`: `lastNight`, `today`, `yesterday` or exact `YYYY-MM-DD` |
| `getDailyHeartRate` | `POST /tools/heart-rate` | `date`: `today`, `yesterday` or exact date |
| `getDailyMovement` | `POST /tools/movement` | Same date input |
| `getRecentActivities` | `POST /tools/activities` | Integer `limit`, from 1 to 5 |

The [fictional fixture](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/fixtures/synthetic-health.json) anchors relative dates to **2025-02-14**, regardless of the actual day. The following are expected fixture answers, not a record of live spoken tests:

| Ask | Expected data |
|---|---|
| How did I sleep last night? | 7 hours 24 minutes on February 14, 2025 |
| What was my resting heart rate yesterday? | 56 bpm on February 13, 2025 |
| How many steps did I take yesterday, and how far did I go? | 8,240 steps and 5.91 km on February 13, 2025 |
| What were my last three activities? | Run, strength training and walk, newest first |
| What were my heart-rate readings on February 12, 2025? | 59 bpm resting; minimum and maximum missing |

Provider results use seconds, metres and bpm; the model may convert them for speech. Missing, unsupported and numeric zero remain distinct. See the [provider guide](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/docs/providers.md) to implement another source without changing browser behavior or tool schemas. `custom` currently selects the included Garmin adapter; arbitrary adapters are not loaded as plugins.

## Stop and session lifetime

Select **Stop** to close the microphone, leave RTC and request remote agent cleanup. The server revokes callback access immediately and checks for terminal remote status (`STOPPED` or `FAILED`); an inconclusive leave response is not treated as proof of shutdown. The UI supports retrying Stop when confirmation fails.

The browser and local server schedule cleanup at **three minutes from session creation**, including startup time. RTC credentials have a nominal 210-second lifetime. The join request also sets Agora's **30-second idle timeout**, which provides service-side idle cleanup after the participant leaves. These mechanisms are distinct: token expiry or a local timer is not proof that a remote agent has stopped.

**No remote maximum-duration parameter is sent in the current join request.** Some existing fallback messages refer to an Agora duration limit or waiting for expiry; they do not establish a remotely enforced three-minute cap. If cleanup cannot be confirmed, retry Stop and verify remote status through Agora's supported controls. Abrupt process termination can prevent local cleanup.

After the demonstration, stop the tunnel and Node server with Control-C in their respective terminals. Graceful server shutdown attempts remote cleanup.

## Validation and evidence

These commands validate the implementation without a live session:

```sh
npm run check
npm test
```

`npm run check` performs TypeScript checking without emitting files. `npm test` builds into `dist/` and runs Node tests; it does not load `.env`. Agora requests are mocked, and Garmin tests inject fictional credentials, responses and clocks instead of accessing the real key or API. Credential-file tests create and remove temporary files.

| Existing coverage | Scope |
|---|---|
| [Recipe tests](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/tests/recipe.test.mjs) | Fixture answers; dates, partial data and zero; invalid startup configuration; Agora payload structure; callback isolation/authentication/revocation; local expiry and lost-start recovery; stop confirmation; sanitized diagnostics; basic and single-tool modes |
| [Garmin tests](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/tests/garmin.test.mjs) | Credential-file permissions; token sharing, expiry and renewal; normalized measurements; missing data; local dates; pagination; malformed/oversized responses; request deadlines; shared tool contracts |
| [Browser tests](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/tests/browser.test.mjs) | UI/provider states; Start/Stop, cancellation, playback recovery and expiry; stage-specific diagnostics; network/HTTP/empty/invalid JSON failures; WebKit-style exceptions; cleanup retry preserves startup failures |
| [Mobile access tests](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/tests/browser-access.test.mjs) | Local defaults; exact HTTPS origins/hosts; passcode authentication; protected cookies, expiry, logout and rate limiting; cross-origin/proxy rejection; callback isolation |
| [Native login fixture](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/tests/native-login.fixture.mjs) | Separate manual browser regression: native form Origin, successful dummy authentication and authenticated redirect |
| [Secret-guard tests](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/scripts/test_secret_guard.py) | Separate hook tests in disposable repositories: staged/outgoing/history scans, removed secrets, tags, literal mobile passcodes and tunnel URLs, narrow placeholders, and scanner failure; requires Gitleaks |

Current offline validation on **13 November 2026**: **57/57 regression tests** and **23/23 secret-guard self-checks** passed, alongside TypeScript checking and the production build. The candidate source snapshot builds without `.env` or pre-existing `dist/` and reproduces the same redesigned UI HTML and generated browser bundle. The lockfile is unchanged; this snapshot check reused installed dependencies rather than performing a new network install. `npm start` rebuilds the committed UI source, so generated `dist/` files are not published.

Startup failures identify microphone access, `/api/start`, RTC client creation, RTC join, or microphone publication. HTTP diagnostics show only the operation, status, normalized content type and redirect flag. Backend messages are allowlisted; response bodies, cookies, credentials, personal measurements and raw SDK objects are not logged. A cleanup failure appends to the original startup failure and retains Stop retry behavior.

To repeat the native-form check after `npm run build`:

```sh
node tests/native-login.fixture.mjs
```

Open `http://localhost:3105`, enter the intentionally fictional passcode described by the fixture, and submit **Continue**. Success requires the browser-generated Origin, a protected opaque cookie, and an authenticated redirect. Stop the fixture with Control-C. It binds only to loopback, uses no real credentials or Agora sessions, and is separate from `npm test`. It translates only the exact local HTTP origin to the test gate's HTTPS origin; this verifies native form behavior without claiming a real HTTPS/device test.

Run the additional security checks before publication:

```sh
python3 scripts/test_secret_guard.py
python3 scripts/secret_guard.py staged
python3 scripts/secret_guard.py history
```

The staged scan covers the index; run it again after explicitly staging the approved files. The working candidate, generated bundle and local history also passed secret scans during this review. No secrets, personal measurements or active tunnel URLs are included in the recipe. Scanning is defense in depth; review recordings and screenshots separately before sharing.

**Owner-confirmed live evidence, reported on 13 November 2026:** successful iPhone HTTPS mobile authentication and a voice conversation using the Garmin provider. This is an owner report, not a live test performed by the reviewing agent. No personal measurements, credentials, active tunnel addresses or session artifacts are recorded here. It does not establish coverage of every health tool. Synthetic remains the default; Garmin (`HEALTH_DATA_PROVIDER=custom`) and mobile HTTPS testing remain optional. No additional live Agora sessions or Garmin API calls were made during this review.

Evidence recorded for recipe preparation on **10 November 2026**:

- Final offline pre-commit review: `npm run check` passed; `npm test` passed **32/32 tests** (19 recipe tests and 13 Garmin tests), with zero failures, skips or cancellations. Service requests were mocked. The separate secret-guard self-test passed all 11 reported checks in temporary repositories.
- **Owner-confirmed live result:** a successful end-to-end spoken steps query used real Garmin data through Agora Conversational AI. The owner independently verified the returned step count against Garmin Connect. The live test was not repeated during this documentation update. The exact prompt, test date, measurement date, numeric result and session artifact are not recorded here; none is inferred.
- That single spoken-steps result does not establish live sleep, heart-rate, distance or activity coverage, nor an end-to-end synthetic voice test. Mocked payload tests do not establish current service acceptance or speech accuracy.
- No live voice sessions or Garmin API calls were performed for this documentation update. The offline results above do not add any live-service validation.

For optional connection diagnosis, `VOICE_MODE=basic npm start` uses the same RTC/ARES/model/Murf stack without tools. `VOICE_MODE=single-tool npm start` tests one authenticated callback returning a fixed fictional count of 1,234. Both modes still use live voice services and require the existing voice configuration; neither verifies the four health tools. Default `VOICE_MODE=health` enables the health recipe. Optional `HEALTH_DEBUG=true` logs fixed callback-stage labels and status, excluding arguments, measurements and credentials.

## Limitations, privacy and publication

This is a local, single-session demonstration, not a multi-user health service. The prompt prohibits diagnoses or treatment advice; that instruction is not a guarantee of model behavior. No clinical accuracy or compliance certification is claimed. Daily heart rate is a summary, movement distance is separate from activity distance, and sleep supports duration only.

Synthetic operation needs no health credentials. Choosing Garmin exposes normalized real measurements to the conversational stack; audio, tool results and spoken output pass through the applicable Agora/model/Murf services, and callback traffic crosses the tunnel provider. Service privacy/retention terms still apply. The code requests `opt_out: true`; this is not a promise of zero retention across providers. Server diagnostics suppress secrets and measurement values. Do not publish personal data or session artifacts without review.

Garmin's cold authentication can exceed the tool's five-second timeout even when a direct provider operation succeeds. See [provider limits](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/docs/providers.md) before interpreting live availability.

The project is licensed under the [MIT License](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/LICENSE), with the approved notice `Copyright (c) 2026 Agora, Inc.`. See the [license status](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/docs/license-proposal.md) for scope. The public repository is owned by `AgoraIO-Community`; public availability does not itself authorize an Agora Recipes submission. Before submission:

- Preserve the public author credit **Ranga Jagannath**, as recorded in [submission Issue #110](https://github.com/AgoraIO-Community/agora-recipes/issues/110), separately from copyright ownership.
- The [refreshed security audit](https://github.com/AgoraIO-Community/agora-health-voice/blob/main/docs/git-secret-protection.md) passed the current working-file and complete local-history scans. Recheck any later changes before publication; hooks are local and must be installed in each clone.
- Follow the current [Agora Recipes contribution guide](https://github.com/AgoraIO-Community/agora-recipes/blob/staging/CONTRIBUTING.md): prepare catalog metadata in a separate fork checkout, branch from upstream `staging`, and target `staging` with the authorized PR. Include English metadata, unchanged author credit and at least one verified public material. Issue #110 is the existing submission context; the current process uses a direct PR rather than an issue-to-maintainer handoff. Once the recipe metadata and validation are complete, the contribution can be submitted as a pull request against `staging`.

Keep validation claims limited to the evidence above. Publishing a source-only recipe does not require additional Garmin features or a hosted service.


## Recipe prompt

You are implementing the "Agora Health Voice" recipe in this project.

Read the recipe markdown first:
https://raw.githubusercontent.com/AgoraIO-Community/agora-health-voice/main/README.md

Use the source repository for cross-reference:
https://github.com/AgoraIO-Community/agora-health-voice

Build this recipe into the user's app using the markdown as the implementation guide. Inspect related source files through the repository links when the recipe points to them. Ask before installing new dependencies.
