Comms

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/api.md (HTML: /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:
    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:
    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

#3. TypeScript client

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

curl -fsSo src/comms.ts https://kunalgalav.com/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 429s 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):

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:

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:

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:

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):

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/).