TAOS
DEVELOPER MANUAL // PYTHON SDK & RAW HTTP URLS

Building Bots on TaoS

Bots are first-class contacts in TaoS. Build with the official tao_bot Python library, or talk directly to the broker’s JSON HTTP endpoints from any language without a library.

Server Base URL
http://127.0.0.1:1033
All /v1/bot-api/* and /v1/* paths below are relative to this server origin.

Two Trust & Runtime Modes

On the wire, every bot is a normal TaoS account with an account_id that people add to their contacts or groups. You choose who holds the bot’s cryptographic keys:

1. Token Mode (Server-Trusted · /v1/bot-api/*)

The broker generates and stores the bot’s Ed25519 + X25519 keys encrypted under TAO_BOT_MASTER_KEY. Your bot authenticates with a Bearer token, sends/receives base64url plaintext over HTTP long-polling, and can publish Mini Apps. Chats with a token bot are readable by the server and clearly labeled in native clients.

2. Key-File Mode (End-to-End · /v1/*)

Your bot generates and keeps its own private keys in a local 0600 JSON state file, signs x-tao-* request headers, seals Envelope v2 ciphertexts, and connects over a signed WebSocket. The server cannot decrypt messages between humans and an E2EE bot.

PART I // PYTHON BOT LIBRARY (TAO_BOT) PYTHON 3.11+ · ASYNC & SYNC

Quickstart & Runtime Configuration

The Bot/ package (tao_bot) handles account registration or token auth, per-chat ordered queues (max_concurrency=8 by default), automatic thread preservation, retries, and graceful SIGTERM/SIGINT shutdown.

from tao_bot import Bot, Chat

bot = Bot(
    label="Helper Bot",
    base_url="http://127.0.0.1:1033",
    env_prefix="HELPER_BOT",
)

@bot.message
async def handle(chat: Chat):
    if chat.text.strip().lower() == "ping":
        return "pong"
    return chat.reply(f"Hello, {chat.sender_display_name or chat.account_id}!")

bot.run()

Running in Token Mode vs. Key-File Mode

# A) Token Mode (provision once via /v1/bot-api/bots, then pass token via env):
HELPER_BOT_TOKEN="taos_bot_..." uv run python my_bot.py --base-url https://taos.example.org

# B) End-to-End Key-File Mode (registers with TAO_INVITE_CODE on first run, stores keys in 0600 JSON):
TAO_INVITE_CODE="taos1:..." uv run python my_bot.py \
  --base-url https://taos.example.org \
  --state-file /var/lib/taos/helper-bot.json \
  --avatar-file avatar.png

Decorators & The Chat Object

Handlers can be synchronous or async functions, or async generators for live token streaming.

Decorator / Method Purpose
@bot.messageHandles incoming text, media, files, locations, and contact cards. Return str, bytes, None, or a chat.reply_*() builder.
@bot.buttonsHandles taps on inline buttons (chat.button carries title, chat_text, message_text).
@bot.secret / @bot.secret_requestReceives hidden one-time secret answers (API keys, passwords) that never stay in the visible timeline.
@bot.deleted / @bot.location_updateReacts to message deletion tombstones (chat.deleted) or live location updates.
@bot.call / @bot.call_recordAnswers/places LiveKit voice calls or processes call summary records.
@bot.startup / @bot.persist / @bot.errorLifecycle hooks for background tasks, custom state persistence, and error handling.
chat.reply(...) / await chat.send(...)Build a return reply (preserving thread_root_id) or send extra messages immediately mid-handler.
chat.stream(...)Stream growing text chunks in real time (batched automatically, notifying only on final done).
chat.reply_file / image / video / audioEncrypt and upload attachments automatically; download incoming attachments with await chat.download(att).
chat.react(emoji) / chat.mark_read()Toggle an emoji reaction on chat.target_message_id or send a read receipt.

Inline Buttons & Mini Apps in Python

Append the inline button syntax to any message text, or use TaoBotTokenClient in Token Mode to publish sandboxed HTML5 Mini Apps (up to 256 KiB) with shared JSON state and long-polled UI events:

from tao_bot import Bot, Chat, TaoBotTokenClient

# 1. Inline buttons syntax: :::[Button Title|Bubble Text=>callback_value]
@bot.message
def ask(chat: Chat):
    return "Confirm deployment?\n:::[Deploy|Deploy now=>deploy_yes] [Cancel|Cancel=>deploy_no]"

@bot.buttons
def on_button(chat: Chat):
    return f"Selected payload: {chat.button.message_text}"

# 2. Publishing & updating a Mini App (Token Mode):
client = TaoBotTokenClient(base_url="http://127.0.0.1:1033", token="taos_bot_...")
panel = await client.publish_mini_app(
    recipient_account_id=user_id,
    title="Server Status",
    html="<!doctype html><html><body>...</body></html>",
    pinned=True,
)
await client.set_mini_app_state(panel["instance_id"], {"cpu": 12}, expected_version=0)
events = await client.mini_app_event_stream(wait=25, limit=100)
PART II // WRITING BOTS WITHOUT A LIBRARY (RAW HTTP URLS) ANY LANGUAGE · JSON + BASE64URL

1. Provisioning & Authentication Headers

Server-trusted bots require TAO_BOT_MASTER_KEY (32-byte base64url key) and TAO_ADMIN_TOKEN on the server. Provisioning uses x-tao-admin-token; all bot runtime calls use Authorization: Bearer <token> (or x-tao-bot-token: <token>).

Method & URL Auth Header Request / Response JSON
POST/v1/bot-api/bots x-tao-admin-token {"display_name": "My Bot"} → {"account_id", "device_id", "token", "signing_public_key", "encryption_public_key"} (token shown once)
GET/v1/bot-api/bots/{account_id}/tokens x-tao-admin-token Lists token metadata (token_id, created_at, revoked_at) without raw secrets.
POST/v1/bot-api/bots/{account_id}/tokens x-tao-admin-token Mints an additional active token for zero-downtime rotation.
DELETE/v1/bot-api/bots/{account_id}/tokens/{token_id} x-tao-admin-token 204 No Content — immediately revokes that token.
GET/v1/bot-api/whoami Bearer <token> → {"account_id", "device_id", "display_name"}
PUT/v1/bot-api/profile Bearer <token> {"display_name": "My Bot", "avatar": {...}, "accepts_calls": false, "notification_sound": "rise"}

2. Receiving, Sending, Broadcasting & Deleting Messages

When a user adds a server-trusted bot by account_id, the subscription is auto-accepted on the server. Incoming messages are delivered at-least-once via long-polling and stay pending until acknowledged.

Method & URL Payload & Behavior
GET/v1/bot-api/updates?wait=25 Long-polls up to wait seconds (0–60). Returns:
{"updates": [{"message_id", "sender_account_id", "sender_display_name", "sent_at", "accepted_at_ms", "plaintext_b64", "chat_id"}]}
POST/v1/bot-api/updates/ack {"message_ids": ["msg_1", "msg_2"]} → {"acked_count": 2}. Always ack processed updates so they are not redelivered.
POST/v1/bot-api/messages {"recipient_account_id": "...", "plaintext_b64": "<base64url>", "push_behavior": "notify", "push_image_url": "https://..."} → {"message_id", "server_sequence", "accepted_at_ms"}. Use "suppress" for quiet messages, reactions, edits, stream chunks, and read receipts. Body limit: 32 MiB.
POST/v1/bot-api/broadcast {"plaintext_b64": "<base64url>", "push_behavior": "notify"} → {"recipient_count", "message_ids", "blocked", "frozen"}. Fans out individual encrypted envelopes to up to 5,000 accepted subscribers.
POST/v1/bot-api/messages/delete {"peer_account_id": "...", "client_message_ids": ["uuid"], "message_ids": [], "file_ids": []}. Writes and fans out deletion tombstones and removes stored copies.

3. Plaintext JSON Schema (Inside plaintext_b64)

plaintext_b64 is unpadded URL-safe Base64 (RFC 4648 §5) of UTF-8 bytes. Raw UTF-8 text works for simple messages, while structured v1 JSON unlocks threads, replies, buttons, Mini App launch buttons, reactions, edits, and live streaming:

// Standard message + thread reply + quote + Mini App launch button
{
  "version": "v1",
  "kind": "tao-silence-message",
  "client_message_id": "550e8400-e29b-41d4-a716-446655440000",
  "text": "Deployment ready.\n:::[Approve|Approve=>ok] [Abort|Abort=>abort]",
  "thread_root_id": "optional-root-message-id",
  "reply_to": {
    "message_id": "quoted-id",
    "author_account_id": "sender-base62-id",
    "text": "Quoted preview up to 200 chars"
  },
  "mini_app_action": {
    "type": "mini_app",
    "title": "Open Dashboard",
    "instance_id": "ma_instance_id"
  },
  "quiet": false
}

// Reaction (send with outer push_behavior: "suppress")
{"version": "v1", "kind": "tao-silence-reaction", "target_client_message_id": "uuid", "emoji": "👍", "action": "add", "reacted_at": 1763890000000}

// Edit own message (push_behavior: "suppress")
{"version": "v1", "kind": "tao-silence-edit", "target_client_message_id": "uuid", "text": "Updated text", "edited_at": 1763890005000}

// Streaming: 1) send tao-silence-message with "streaming": true, "text": "" (suppress)
//            2) send chunks with state: "append" (suppress)
//            3) finish with state: "done" and full "text" (push_behavior: "notify")
{"version": "v1", "kind": "tao-silence-stream", "target_client_message_id": "uuid", "delta": "chunk ", "state": "append"}
{"version": "v1", "kind": "tao-silence-stream", "target_client_message_id": "uuid", "text": "full final text", "state": "done"}

4. Files, Mini Apps & Voice Calls URLs

All routes below authenticate with Authorization: Bearer <bot_token>.

Method & URL Contract
POST/v1/bot-api/files/raw/{recipient} Raw binary upload of AES-256-GCM encrypted bytes for {recipient} account_id → {"file_id", "size_bytes", "sha256"}. Reference in message attachments via blob: {file_id, key_b64, sha256, size_bytes}. (JSON variant: POST /v1/bot-api/files).
GET/v1/bot-api/files/{file_id} Downloads encrypted file bytes (supports HTTP Range requests) when the bot is uploader, recipient, or granted reader.
POST/v1/bot-api/mini-apps {"recipient_account_id", "title", "html", "pinned": false, "icon": {"mime_type": "image/png", "data_b64": "..."}} → {"app_id", "instance_id", "title", "url"}. HTML max 256 KiB; square PNG/JPEG/WebP icon max 64 KiB.
PATCH/v1/bot-api/mini-apps/{instance_id} {"title"?: "...", "icon"?: {...} | null, "html"?: "<!doctype html>..."} → instance summary.
DELETE/v1/bot-api/mini-apps/{instance_id} → {"deleted_instance_id": "..."}
GET/ PUT/v1/bot-api/mini-apps/{instance_id}/state GET → {"instance_id", "state", "version"}; PUT {"expected_version": 0, "state": {...}} (409 on version conflict).
GET/v1/bot-api/mini-apps/events?wait=25&limit=100 Long-polls UI events across all owned Mini App instances (0–30s). Ack with POST /v1/bot-api/mini-apps/events/ack {"acks": [{"instance_id", "event_id"}]} (or per-instance /v1/bot-api/mini-apps/{id}/events[/ack]).
POST/ GET/v1/bot-api/calls Start call ({"recipient_account_id"}), long-poll calls (?after=0&wait=25), answer (POST /v1/bot-api/calls/{id}/answer), end (POST /v1/bot-api/calls/{id}/end {"reason"}).

Mini App In-WebView JavaScript Bridge

// Inside your Mini App HTML (<= 256 KiB, no external network):
const { state, version } = await window.tao.getState();
await window.tao.setState({ count: (state?.count ?? 0) + 1 });
await window.tao.sendEvent({ action: "refresh" });
window.tao.close();

5. Zero-Dependency Bot Example (Node.js 20+ / Standard Fetch)

A complete working bot with zero external packages — works in Node.js, Deno, Bun, or translates 1:1 to Go, Rust, or curl:

const BASE = "http://127.0.0.1:1033";
const TOKEN = process.env.TAO_BOT_TOKEN;
const headers = { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" };

const b64uEncode = (str) => Buffer.from(str, "utf8").toString("base64url");
const b64uDecode = (b64) => Buffer.from(b64, "base64url").toString("utf8");

while (true) {
  const res = await fetch(`${BASE}/v1/bot-api/updates?wait=25`, { headers });
  const { updates = [] } = await res.json();
  if (!updates.length) continue;

  const ackIds = [];
  for (const u of updates) {
    const raw = b64uDecode(u.plaintext_b64);
    let text = raw;
    try {
      const parsed = JSON.parse(raw);
      if (parsed?.kind === "tao-silence-message") text = parsed.text ?? "";
    } catch {}

    const reply = JSON.stringify({
      version: "v1",
      kind: "tao-silence-message",
      text: `Received: ${text}`,
    });
    await fetch(`${BASE}/v1/bot-api/messages`, {
      method: "POST",
      headers,
      body: JSON.stringify({
        recipient_account_id: u.sender_account_id,
        plaintext_b64: b64uEncode(reply),
      }),
    });
    ackIds.push(u.message_id);
  }

  await fetch(`${BASE}/v1/bot-api/updates/ack`, {
    method: "POST",
    headers,
    body: JSON.stringify({ message_ids: ackIds }),
  });
}
APPENDIX // END-TO-END SIGNED BOTS WITHOUT A LIBRARY (/V1/*) ED25519 + X25519 · ENVELOPE V2

Signed E2EE Bot URLs

If your bot must remain end-to-end encrypted against the server without using Python, generate Ed25519 + X25519 keys locally, sign each HTTP request with x-tao-account-id, x-tao-device-id, x-tao-timestamp, x-tao-nonce, and x-tao-signature (Ed25519 over METHOD, path, timestamp, nonce, SHA-256 body hash, account_id, device_id), and use the standard client routes:

POST /v1/accounts                        # register public key bundle v2 + invite code
PUT  /v1/accounts/me/profile             # set display_name, kind="bot", avatar
GET  /v1/subscriptions/pending           # poll incoming contact requests
POST /v1/subscriptions/accept            # accept subscription
GET  /v1/inbox/{device_id}               # drain pending Envelope v2 ciphertexts
POST /v1/inbox/{device_id}/ack           # acknowledge processed message_ids
POST /v1/live-tickets                    # mint single-use ticket (30s TTL)
GET  /v1/live/{device_id}?ticket=...     # live WebSocket stream
POST /v1/messages                        # send signed Envelope v2 ciphertext
PUT  /v1/bot/chats/{viewer_id}/banner    # update persistent top bot banner