# Using the Comms service: guide for agents

You're working on one of Kunal's apps and it needs to **notify him, ask him a question, or email someone**. Use this service instead of signing up for Resend, Twilio, SendGrid or a new Telegram bot integration. It's already running, always on, and needs only an API key.

Full reference: [`https://kunalgalav.com/messaging_service/api.md`](https://kunalgalav.com/messaging_service/api.md) (HTML: [`/messaging_service/docs/`](https://kunalgalav.com/messaging_service/docs/)).

---

## 1. Setup in a new project

1. **Get an API key from Kunal.** Keys can't be created through the API or the website. Ask him to run this in the comms-service repo:
   ```bash
   AWS_PROFILE=comms npm run create-app -- --name <this-app> --key-file .secrets/<this-app>.key
   ```
   Add `--telegram-bot <bot_username>` if the app should use Telegram. Each app gets its own bot, made with @BotFather, with its token stored first as `comms/telegram/<bot_username>` in Secrets Manager.
2. **Store the key as an environment variable or secret**, never in code:
   ```bash
   COMMS_API_KEY=ck_...                          # .env (gitignored) or the platform's secret store
   COMMS_BASE_URL=https://api.kunalgalav.com
   ```
3. **Webhooks (optional).** If the app has a public HTTPS endpoint, Kunal sets it with `npm run app -- set-webhook --app <app_id> --url <url>`. Then the app gets `button.clicked`, `message.received` and `message.status` events pushed to it, signed with the app's `webhook_secret`. Without a webhook, poll `GET /v1/messages/{id}`.

## 2. Rules

- **Never print, log or commit the API key or the webhook secret.** Read them from the environment.
- **Always send an `idempotency_key`** that names the event (e.g. `"backup-failed-2026-11-15"`). Then retries and re-runs don't send duplicates.
- **Put your own context in `metadata`** (device id, job id, …). It comes back on the message and in every webhook event, so you don't need your own lookup table.
- **Telegram goes to contact ids**, not usernames. `"me"` is Kunal. A new contact must open a link from `POST /v1/contacts/telegram-link` first. Until then you get `422 contact_not_linked`.
- **Email is in SES sandbox mode**: only verified recipients get mail, and everything else ends `failed`. Default to Kunal's own address unless told otherwise.
- **`202` means queued, not delivered.** Check `status` later if it matters.
- **Stay under the rate limit**: 60 sends a minute and 1,000 a day per app. A `429 rate_limited` means wait `Retry-After` seconds. Hitting the daily limit means something is looping, so fix it rather than retrying. Kunal gets an alert every time an app is limited.
- For **yes/no decisions**, prefer Telegram buttons. They're fast, and the answer comes back as a clean `button_id`.

## 3. TypeScript client

Download the one-file client into the project. It has no dependencies and needs Node 18+:

```bash
curl -fsSo src/comms.ts https://kunalgalav.com/messaging_service/sdk/comms.ts
```

It reads `COMMS_API_KEY` (and optional `COMMS_BASE_URL`) from the environment and gives you:

| Call | What it does |
|---|---|
| `comms.send(input)` | Queues an email or Telegram message and returns it with `status: "queued"` |
| `comms.get(id)` | The message now: `status`, `error`, `response.button_id` … |
| `comms.ask(input, { timeoutMs })` | Sends with buttons and polls until answered. Returns the button id, or `null` on timeout or failure |
| `comms.waitForStatus(id)` | Polls until the message leaves `queued` |
| `comms.telegramLink(contactId)` | A one-time link that connects someone's Telegram |
| `verifyWebhook(secret, header, rawBody)` | Checks an incoming webhook and returns the parsed event, or `null` |
| `createComms({ apiKey, baseUrl, maxRetries })` | A client with explicit settings |

Errors are thrown as `CommsError` with `status`, `code` (for example `"contact_not_linked"`) and `retryAfter`. The client waits out short `429`s by itself. It retries `5xx` and network errors only for sends that have an `idempotency_key`, so a retry can never send twice. Don't edit the downloaded file: download it again to update it.

## 4. Recipes

**Notify (fire and forget):**
```ts
await comms.send({ channel: "telegram", to: "me", body: "✅ Nightly backup finished (12.4 GB)", idempotency_key: `backup-ok-${today}` });
```

**Ask and act on the answer:**
```ts
const choice = await comms.ask({
  channel: "telegram",
  to: "me",
  subject: "🔥 Water heater",
  body: "On for 3 hours. Turn it off?",
  buttons: [{ id: "off", label: "Turn off" }, { id: "keep", label: "Keep on" }],
  metadata: { device: "heater-1" },
  idempotency_key: `heater-1-${hourStamp}`,
});
if (choice === "off") await heater.turnOff();
```

**Email:**
```ts
await comms.send({ channel: "email", to: ownerEmail, subject: "Weekly report", body: reportText, idempotency_key: `report-${week}` });
```

**Webhook handler (Express), when the app has a public URL:**
```ts
import { verifyWebhook } from "./comms";

app.post("/comms-webhook", express.raw({ type: "application/json" }), async (req, res) => {
  const evt = verifyWebhook(process.env.COMMS_WEBHOOK_SECRET!, req.header("x-comms-signature"), req.body.toString("utf8"));
  if (!evt) return res.sendStatus(401);
  res.sendStatus(200); // respond within 10 s, then work
  if (seen(evt.id)) return; // at-least-once delivery
  if (evt.type === "button.clicked" && evt.data.message.metadata?.device === "heater-1" && evt.data.button?.id === "off") {
    await heater.turnOff();
  }
});
```

**curl (quick test):**
```bash
curl -s https://api.kunalgalav.com/v1/messages \
  -H "authorization: Bearer $COMMS_API_KEY" -H 'content-type: application/json' \
  -d '{"channel":"telegram","to":"me","body":"Hello from curl"}'
```

## 5. Troubleshooting

| Symptom | Cause and fix |
|---|---|
| `401 unauthorized` | `COMMS_API_KEY` missing or wrong, or the key was rotated. Ask Kunal |
| `429 rate_limited` | Too many sends. Wait `retry_after` seconds. On the daily limit, look for a loop. Kunal can raise the limit with `npm run app -- set-limits` |
| `422 contact_not_linked` | Create a link with `comms.telegramLink("<contact>")` and have the person tap **Start** |
| `422 telegram_not_configured` | The app has no bot. Kunal runs `npm run telegram -- connect --app <id> --bot <username>` |
| `status: failed`, error mentions "not verified" | Email to an unverified address while in sandbox |
| `status: failed`, "bot was blocked" | The person blocked the bot. They need to unblock it and tap Start again |
| No webhook events | No webhook URL set, the endpoint isn't returning 2xx, or the signature check uses the parsed body instead of the raw body |

The service's source and owner tooling: the private `comms_agent` repo (see `docs/` and `scripts/`).
