# dtchat adapter protocol, version 1

Status: normative for dtchat's adapter processes.  Decided 2026-11-16.
Reference implementation: `lib/libDtChat/adapter.c`,
`lib/libDtChat/fake_adapter.c`, `lib/libDtChat/test_adapter.c`.
Public constants: `include/DtChat/Ipc.h` (`DC_IPC_VERSION`,
`DC_IPC_MAX_LINE`, `DC_JSON_MAX_DEPTH`).

An adapter is a separate process, one per account.  The core spawns it with
`PATH --stdio`, speaks JSON lines on its stdin/stdout, drains stderr to a log
and restarts it when it dies without saying `bye`.  The UI and the core never
link a protocol library; an adapter can be written in C, C++, Go or anything
else that can read and write lines.

## 1. Transport and framing

- One UTF-8 JSON **object** per line on stdout, `\n` terminated.
- At most `DC_IPC_MAX_LINE` = 1,048,576 bytes per line, without the `\n`.
- No NUL byte, no `\r`, no pretty-printed multi-line objects, no two
  objects on one line.  A trailing `\r` before `\n` is accepted and
  stripped for robustness; new adapters send `\n` only.
- stdout is the protocol; stderr is a free-text log.  Nothing else may be
  written to stdout.
- The core parses each line strictly (depth <= 32, valid UTF-8, no
  duplicate keys).  Invalid JSON, an over-long line or a NUL ends the
  adapter process; the core reports an `error` and applies the restart
  backoff.
- The core writes commands as one JSON object per line.  An adapter that
  cannot keep up may be slowed by the core's output buffer, but it must
  read continuously.

## 2. Lifecycle

1. The core forks/execs `PATH --stdio`; stdin/stdout/stderr are pipes.
2. The adapter sends `hello` immediately (within 10 seconds; the core
   kills and restarts a child that stays silent).
3. The core validates `hello` (`ipc` must be 1, `protocol` non-empty),
   forwards it to the UI (capabilities/settings schema), then sends
   `configure` and `connect`.
4. The adapter connects to its network and sends
   `state {"state":"online"}` (or `connecting`, `offline`, `error`).
   `online` resets the restart backoff.
5. Commands (`send`, `join`, `answer`, `disconnect`, optional
   `set_presence`/`typing`) flow from the core; events flow back.
6. `bye` or `error` with `"fatal":true` means "do not restart".
7. `disconnect` means "shut down cleanly": the adapter sends `bye` and
   exits.  The core waits 2 seconds, then sends `SIGTERM`.
8. Any other exit is a crash: the core restarts after 2, 4, 8 ... 60
   seconds.  A successful `online` resets the backoff to 2 seconds.

The core runs one adapter per account.  Two accounts of the same protocol
are two processes.

## 3. `hello` (adapter -> core, required)

```json
{"type":"hello","ipc":1,"protocol":"irc","version":"1.0",
 "caps":["text","channels","typing","sasl","tls"],
 "settings":[
   {"key":"host","label":"Server","type":"text","required":true},
   {"key":"port","label":"Port","type":"int","default":6697},
   {"key":"tls","label":"TLS","type":"bool","default":true},
   {"key":"nick","label":"Nickname","type":"text","required":true},
   {"key":"password","label":"Password","type":"secret"},
   {"key":"channels","label":"Channels","type":"text",
    "help":"comma separated"}
 ]}
```

| Field | Type | Required | Meaning |
|---|---|---|---|
| `type` | string | yes | `"hello"` |
| `ipc` | int | yes | protocol version; currently exactly 1 |
| `protocol` | string | yes | `irc`, `xmpp`, `telegram`, `whatsapp`, `local`, ... |
| `version` | string | no | adapter's own version, for logs/about |
| `caps` | array of string | no | `text`, `channels`, `muc`, `typing`, `files`, `audio`, `video`, `qr`, `contacts`, `history`, `roster`, `presence` |
| `settings` | array of objects | no | schema for the account dialog |

Unknown fields are ignored.  The core validates only `ipc` and `protocol`
in v1; a bad `hello` is an error and the child is restarted.

### 3.1 Settings schema

Each entry describes one field of the account dialog:

| Field | Type | Meaning |
|---|---|---|
| `key` | string | stored in `accounts.json` under `settings` |
| `label` | string | visible label |
| `type` | string | `text`, `secret`, `bool`, `int`, `choice`, `info`, `button` |
| `default` | any | initial value (`""`, `false`, `0`, ...) |
| `required` | bool | the UI refuses an empty value |
| `help` | string | one-line explanation |
| `choices` | array of `{value,label}` | only for `type:"choice"` |
| `action` | string | only for `type:"button"` (e.g. `logout`) |

`secret` fields are stored in `secrets.json`, never in `accounts.json` and
never in a log.  The UI renders `text` as `XmText`, `secret` with an echo
character, `bool` as a toggle, `int` as a numeric field, `choice` as an
option menu, `info` as a label and `button` as a push button.
`settings` is optional; an adapter without it gets an "Advanced" JSON
editor or no form.

## 4. Core -> adapter

All commands are objects with a `type` field.

### 4.1 `configure` (required once, after hello)

```json
{"type":"configure","account":"libera",
 "settings":{"host":"irc.libera.chat","port":6697,"tls":true,
             "nick":"kronos","channels":"#cde"},
 "secrets":{"password":"..."}}
```

`settings` and `secrets` are objects; missing values are absent, not null.
They contain exactly the keys from the hello schema.  The adapter must not
write secrets to stdout or stderr.

### 4.2 `connect`

```json
{"type":"connect"}
```

Start the network connection.  The adapter reports progress with `state`.

### 4.3 `send`

```json
{"type":"send","conv":"#cde","text":"hello","client_id":"c1"}
```

`client_id` is optional but recommended: the adapter echoes it in `sent`
so the UI can match the local echo.  `text` is UTF-8, may contain
newlines; the adapter is responsible for protocol-specific splitting and
limits (IRC: 512 bytes, split at UTF-8 boundaries).

### 4.4 `join`

```json
{"type":"join","conv":"#cde"}
```

Join a channel, MUC room or group.  The adapter answers with `conversation`.

### 4.5 `answer`

```json
{"type":"answer","id":7,"value":"12345"}
```

The answer to a `request`.  `value` is a string or `null` for cancel.

### 4.6 `disconnect`

```json
{"type":"disconnect"}
```

Shut down cleanly and exit; normally followed by `bye`.

### 4.7 Files

File transfer is optional (`files` in `caps`).  The core sends the path; the
adapter reads the file itself and computes its SHA-256 (hex), which travels
with the offer and is checked by the receiver at the end.  A transfer is
bounded by 32 MiB and 4 KiB blocks, and the receiver says yes or no before
any data flows:

```json
{"type":"file-send","conv":"bob@example.org","id":"f1",
 "name":"photo.jpg","path":"/home/alice/photo.jpg"}
{"type":"file-accept","id":"f1"}
{"type":"file-reject","id":"f1","reason":"no thanks"}
{"type":"file-cancel","id":"f1"}
```

`id` is chosen by the sender and identifies the transfer on both sides.

### 4.8 Optional commands

The core may send these through the generic JSON writer; adapters that do
not support them ignore them:

```json
{"type":"set_presence","show":"online","status":"in the office"}
{"type":"typing","conv":"#cde","on":true}
{"type":"part","conv":"#cde","reason":"bye"}
```

## 5. Adapter -> core

### 5.1 `state`

```json
{"type":"state","state":"online","detail":"irc.libera.chat"}
```

`state` is one of `offline`, `connecting`, `online`, `error`.  `detail` is
optional and shown in the account tooltip/status line.  `online` is the
only state the core interprets (it resets the backoff).

### 5.2 `conversation`

```json
{"type":"conversation","conv":"#cde","kind":"channel","title":"#cde",
 "topic":"the topic"}
```

`kind` is `direct`, `channel`, `group` or `nearby`.  For a MUC the adapter
sends the self-presence to `room/nick` (with the MUC `<x/>`), answers it with
a `conversation` of kind `group`, reports the other occupants as
`presence` events with `buddy` = `room/nick`, and files groupchat messages
under the room (`conv`) with the sender's nick in `from`.  The core creates or
updates the conversation.  `topic` is optional.

### 5.3 `message`

```json
{"type":"message","conv":"#cde","id":"m1","ts":1763298123,
 "from":"kronos","self":false,"kind":"text","text":"hallo"}
```

| Field | Type | Meaning |
|---|---|---|
| `conv` | string | conversation id inside the account |
| `id` | string | adapter message id, optional |
| `ts` | int | seconds since the epoch; 0 if unknown |
| `from` | string | display name |
| `self` | bool | our own message (echo) |
| `kind` | string | `text`, `action`, `notice`, `system` |
| `text` | string | UTF-8 body |

An adapter should not send an IRC `\x02`/`\x03` code in `text`; strip it
first (the core also strips it for display, but the model stays clean).

### 5.4 `sent`

```json
{"type":"sent","conv":"#cde","client_id":"c1","ts":1763298124}
```

Confirms a `send`.  `client_id` is echoed from the command; `ts` is the
server time when known.  A message another resource of the same account
sent (XMPP carbons) is a normal `message` event with `self` true and the
contact as `conv`; one another resource received has `self` false.

### 5.5 `presence`, `roster`, `typing`

```json
{"type":"presence","buddy":"alice","show":"online","away":"away",
 "status":"brb"}
{"type":"roster","contact":{"id":"alice","name":"Alice","online":true,
 "subscription":"both"}}
{"type":"typing","conv":"#cde","who":"alice","on":true}
```

`show` is `online`, `offline` or `subscribe`; `away` repeats the XMPP
`<show>` value (`away`, `dnd`, `xa`, `chat`) when there is one, so the two
meanings do not collide.  A roster event's `contact` carries the bare JID as
`id`, the name, the subscription and whether presence has been seen.  These
are passed to the UI; the core imposes no further structure in v1.

### 5.6 `file-*`

```json
{"type":"file-offer","conv":"bob@example.org","id":"f1",
 "name":"photo.jpg","size":123456,
 "sha256":"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"}
{"type":"file-data","id":"f1","data":"<base64>","size":4096}
{"type":"file-end","id":"f1","size":123456}
{"type":"file-sent","id":"f1","size":123456,
 "sha256":"b94d…fcde9"}
{"type":"file-reject","id":"f1","reason":"no thanks"}
{"type":"file-error","id":"f1","text":"the file is too large"}
```

An incoming offer means the adapter is holding the transfer open and waits
for `file-accept` or `file-reject`; after the accept the data arrives in
base64 chunks (`file-data`), and `file-end` closes it.  The receiver hashes
the bytes and refuses the file (`file-reject`, part file removed) when the
SHA-256 does not match the offer.  `file-sent` confirms our own outgoing
transfer.  A transfer that fails or exceeds the limit ends with `file-error`.  The UI may show the offer, write the chunks and rename
on `file-end`; the adapter itself never writes an incoming file.

### 5.7 `request`

The adapter needs something from the person: a login code, a password, a
QR code or a notice.

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

| Field | Type | Meaning |
|---|---|---|
| `id` | int | unique while the request is open; echoed in `answer` |
| `kind` | string | `code`, `password`, `notice`, `qr`, `confirm` |
| `title` | string | dialog title |
| `prompt` | string | question |
| `secret` | bool | hide the input |
| `hint` | string | extra line under the QR/notice |
| `qr` | object | `width`, `height`, `data` (base64, row-major, 1 = dark) |

The core answers with `{"type":"answer","id":7,"value":"..."}` or
`"value":null` for cancel.  A QR is a bitmap, not a terminal string: the
UI draws it into a Motif pixmap, so no QR library is needed.

### 5.7 `error`

```json
{"type":"error","fatal":false,"code":"auth","text":"Password rejected"}
```

`code` is a short stable string chosen by the adapter (`auth`, `network`,
`protocol`, `internal`, ...).  `fatal:true` means no restart; `false`
means the core may restart after the backoff.  `text` is shown to the
person.

### 5.8 `log`

```json
{"type":"log","level":"warn","text":"server sent an unknown CAP"}
```

Adapter diagnostics that are useful in the UI log but are not errors.
stderr remains the low-level log.

### 5.9 `bye`

```json
{"type":"bye","reason":"requested"}
```

The adapter is shutting down cleanly.  The core does not restart it.

## 6. Versioning and compatibility

- `ipc` is an integer; this document is version **1**.
- Additive changes (new optional fields, new event types, new `caps`
  values) do not change `ipc`.  Unknown fields and unknown event types
  must be ignored by both sides.
- A breaking change increments `ipc`; the core refuses any other value.
- `version` describes the adapter implementation, not the protocol; it is
  informational.
- Errors are not a fixed enum; `code` is a stable string, `text` is
  user-facing and may be translated by the adapter.

## 7. Security

- Secrets arrive only in `configure`; never write them to stdout/stderr
  or to a file other than the account store.
- The core is expected to start adapters only from
  `$(libexecdir)/dtchat` (plus the explicit test path); the generic
  `dc_adapter_start()` accepts the path its caller gives and never runs a
  shell.
- An adapter is not trusted with the UI process: it can crash without
  taking dtchat down.
- A line that is too long, contains NUL, or is not valid JSON kills the
  adapter and triggers the restart policy.

## 8. Reference session (IRC)

```
adapter: {"type":"hello","ipc":1,"protocol":"irc","version":"1.0",
          "caps":["text","channels","typing","sasl","tls"]}
core:    {"type":"configure","account":"libera","settings":{...},
          "secrets":{"password":"..."}}
core:    {"type":"connect"}
adapter: {"type":"state","state":"connecting"}
adapter: {"type":"state","state":"online","detail":"irc.libera.chat"}
core:    {"type":"join","conv":"#cde"}
adapter: {"type":"conversation","conv":"#cde","kind":"channel",
          "title":"#cde"}
adapter: {"type":"message","conv":"#cde","id":"m1","ts":1763298123,
          "from":"alice","self":false,"kind":"text","text":"hi"}
core:    {"type":"send","conv":"#cde","text":"hello","client_id":"c1"}
adapter: {"type":"sent","conv":"#cde","client_id":"c1","ts":1763298124}
adapter: {"type":"message","conv":"#cde","id":"m2","ts":1763298124,
          "from":"kronos","self":true,"kind":"text","text":"hello"}
core:    {"type":"disconnect"}
adapter: {"type":"bye","reason":"requested"}
```

## 9. Reference session (device pairing)

```
adapter: {"type":"hello","ipc":1,"protocol":"whatsapp","version":"1.0",
          "caps":["text","files","qr"]}
core:    {"type":"configure","account":"wa","settings":{},"secrets":{}}
core:    {"type":"connect"}
adapter: {"type":"request","id":1,"kind":"qr","title":"WhatsApp",
          "hint":"Scan with WhatsApp","qr":{"width":33,"height":33,
          "data":"..."}}
core:    {"type":"answer","id":1,"value":null}
adapter: {"type":"state","state":"online"}
```

## 10. Reference implementation and tests

- `lib/libDtChat/adapter.c` -- spawn, hello validation, configure/connect,
  routing, output buffer, stderr drain, restart backoff, stop/bye.
- `lib/libDtChat/fake_adapter.c` -- a minimal adapter used by the tests;
  modes `normal`, `crash` (exit after connect), `garbage` (invalid JSON).
- `lib/libDtChat/test_adapter.c` -- handshake, send/message echo,
  join/answer, stop, restart and invalid JSON.
- `make mcde-host` builds them; run
  `build/mcde-host/lib/libDtChat/test_adapter` or `tools/mcde-tests.sh`.

## 11. What v1 does not define

- Transport other than stdio (no TCP adapter protocol).
- Multiple accounts per adapter process.
- A binary channel for media: local audio/video stays in the core.
- Telegram/WhatsApp calls: their libraries do not expose a usable media
  stack; see `docs/reference/dtchat-upstream.txt`.
- A sandbox beyond the separate process and the paths above.

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