Files
mcde/programs/dtchat
lotherk ea31073ce0 dtchat: exchange media keys and wire live calls into the UI (T6.5)
The local protocol gets media-key: each side sends its ephemeral X25519 public key (base64) and UDP port over the ready text connection; both derive the direction keys with HKDF-SHA256, the caller is the initiator. localui sends the key on Conversation > Call, answers an offer with its own key, creates the call with dc_call_new_bound on the listener port (TLS and media share the number), rings, and opens the call window; an incoming ring enables Answer. The Xt loop pumps the call: drain, Opus decode to the playback stream, capture and encode only while our own PTT is held, video frames to the window, ring timeout. dc_local_conn_remote_addr gives the numeric peer address; dc_call_new_bound binds the announced port. dc_call_talking() is now only our own key, dc_call_peer_talking() the peer's (a received PTT used to start our microphone too). The call window has an Answer button and lays the buttons above the video so they stay visible. --call-first and DTCHAT_TEST_TRUST/DTCHAT_TEST_AUTOANSWER/DTCHAT_TEST_PTT drive the test: two UI instances auto-paired, exchanged media-key, rang, answered, reached IN_CALL and carried 200 Opus frames caller->callee with the callee silent (audio out 200 on the receiver, audio in 200 on the sender); screenshot build/mcde-shots/dtchat-t65-live.png. The smoke still passes; test_media_call uses peer_talking; test_media_packet covers the base64 key exchange. The test switch is documented in the security review.
2026-11-17 08:49:25 +00:00
..

dtchat adapters -- a guide for authors
======================================

An adapter is a separate process that speaks one network protocol for dtchat.
It reads JSON lines on stdin, writes JSON lines on stdout and may write
anything to stderr (dtchat drains and discards it).  The core and the UI never
link a protocol library; an adapter can be written in C, C++, Go, Python or
anything that can read and write lines.

The normative contract is docs/reference/dtchat-adapter-protocol.txt (v1,
ipc=1).  This file is the short version and a skeleton.

1. Start and handshake
----------------------

dtchat starts the process as

    PATH --stdio

with three pipes.  Within 10 seconds the adapter must send one line:

    {"type":"hello","ipc":1,"protocol":"irc","version":"1.0",
     "caps":["text","channels","typing","sasl","tls"],
     "settings":[ ... ]}

`ipc` must be 1 and `protocol` is the protocol name.  `settings` describes the
account form; each entry has `key`, `label`, `type` (`text`, `secret`, `bool`,
`int`, `choice`, `info`, `button`), optional `default`, `required`, `help`,
`choices` and `action`.  `secret` values are stored in secrets.json, never in
the account file, and the UI shows only `*`.

Then dtchat sends:

    {"type":"configure","account":"name","settings":{...},"secrets":{...}}
    {"type":"connect"}

Answer with a state and then events:

    {"type":"state","state":"connecting"}
    {"type":"state","state":"online","detail":"server"}

`online` resets the restart backoff.

2. Commands (core -> adapter)
-----------------------------

    {"type":"send","conv":"#cde","text":"hello","client_id":"c1"}
    {"type":"join","conv":"#cde"}
    {"type":"answer","id":7,"value":"12345"}
    {"type":"disconnect"}
    {"type":"set_presence","show":"online","status":"..."}   (optional)
    {"type":"typing","conv":"#cde","on":true}                (optional)

`answer` replies to a request; `value` is a string or null for cancel.
`disconnect` means: say goodbye and exit.

3. Events (adapter -> core)
---------------------------

    {"type":"conversation","conv":"#cde","kind":"channel","title":"#cde"}
    {"type":"message","conv":"#cde","id":"m1","ts":...,
     "from":"alice","self":false,"kind":"text","text":"hi"}
    {"type":"sent","conv":"#cde","client_id":"c1","ts":...}
    {"type":"presence","buddy":"alice","show":"online","status":"brb"}
    {"type":"roster","conv":"#cde","contact":{"id":"alice","name":"Alice",
     "mode":"@"}}
    {"type":"typing","conv":"#cde","who":"alice","on":true}
    {"type":"log","level":"warn","text":"..."}
    {"type":"error","code":"auth","text":"Password rejected","fatal":false}
    {"type":"bye","reason":"requested"}

`kind` in a message is `text`, `action`, `notice` or `system`.  `fatal:true`
and `bye` mean: do not restart.  Any other exit is a crash; dtchat restarts
after 2, 4, 8 ... 60 seconds (reset by `online`).

4. Asking the person
--------------------

    {"type":"request","id":7,"kind":"code","title":"Telegram",
     "prompt":"Code from the app","secret":true}
    {"type":"request","id":8,"kind":"qr","title":"WhatsApp","hint":"...",
     "qr":{"width":33,"height":33,"data":"<base64, 1 byte per module>"}}

`kind` is `code`, `password`, `notice`, `qr` or `confirm`.  The answer comes
back as `{"type":"answer","id":7,"value":"..."}` (null = cancel).

5. Security
-----------

- Secrets arrive only in `configure`; never write them to stdout, stderr or
  a file of your own.
- Never run a shell from the adapter for a user-controlled string.
- dtchat starts adapters only from its adapter directory (plus an explicit
  path in tests); the adapter is a separate process and may crash without
  taking the UI down.
- A line over 1 MiB, a NUL or invalid JSON ends the process; keep stdout to
  one object per line.

6. Testing
----------

- lib/libDtChat/fake_adapter.c is a minimal adapter (`normal`, `crash`,
  `garbage` modes).
- lib/libDtChat/test_adapter.c starts it with dc_adapter_start() and checks
  the handshake, send/message, join/answer, stop/bye and the restart backoff.
- `tools/mcde-tests.sh` runs the tests; `make mcde-host` builds them.
- For a new adapter, add a `--selftest` that feeds hello/configure/connect
  through pipes and checks the answers without a network, then a fake server
  test for the protocol itself.

7. Skeleton (Python, for a first probe)
---------------------------------------

    #!/usr/bin/env python3
    import json, sys

    def send(obj):
        sys.stdout.write(json.dumps(obj) + "\n")
        sys.stdout.flush()

    send({"type":"hello","ipc":1,"protocol":"demo","version":"0.1",
          "caps":["text"],
          "settings":[{"key":"nick","label":"Nickname","type":"text",
                       "default":"you"}]})
    nick = "you"
    for line in sys.stdin:
        cmd = json.loads(line)
        t = cmd.get("type")
        if t == "configure":
            nick = (cmd.get("settings") or {}).get("nick", nick)
        elif t == "connect":
            send({"type":"state","state":"online"})
            send({"type":"conversation","conv":"lobby","kind":"channel",
                  "title":"Lobby"})
        elif t == "send":
            send({"type":"sent","conv":cmd["conv"],
                  "client_id":cmd.get("client_id")})
            send({"type":"message","conv":cmd["conv"],"from":"echo",
                  "kind":"text","text":cmd["text"]})
        elif t == "disconnect":
            send({"type":"bye","reason":"requested"})
            sys.exit(0)

Save it, `chmod +x`, and start it with a test adapter path; the UI and the
headless mode will show the lobby and echo your messages.

<!-- License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. -->