> Every Taji docs page as Markdown: https://docs.taji.is/llms.txt

# Write a channel

You build `filechat`, a channel whose platform is two files, compose it into a kernel, and link, pair and talk to it over the wire. You need a checkout [built from source](https://docs.taji.is/guide/install.md), `jq` and no account.

A channel carries Taji's alerts to a messaging app and, if inbound, what you type there to your agent. It is a compiled-in plugin: a crate under `plugins/` that implements `taji_plugin::channel::Channel` (`engine/crates/taji-plugin/src/channel.rs`) and registers it with `Build::channel` in `Plugin::build`. `schema/taji.json` declares no channel, so a process plugin cannot be one ([which kind you need](https://docs.taji.is/plugins.md#which-kind-do-i-need)).

## 1. Write the crate

`filechat` hears each line appended to `<dir>/in` as from the sender `me` and appends each send to `<dir>/out`:

```sh
mkdir -p plugins/filechat/src
cat > plugins/filechat/Cargo.toml <<'EOF'
[package]
name = "filechat"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
taji-plugin = { path = "../../engine/crates/taji-plugin" }
tokio.workspace = true

[lints]
workspace = true
EOF
cat > plugins/filechat/taji-plugin.toml <<'EOF'
id = "filechat"
name = "File chat"
version = "0.1.0"
EOF
cat > plugins/filechat/src/lib.rs <<'EOF'
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use taji_plugin::channel::{Caps, Channel, Inbound, Inbox, Linked, Markup, Outbound, Secret};
use taji_plugin::report::{Failed, Report};
use taji_plugin::{Build, Manifest, Plugin, async_trait};

#[derive(Default)]
pub struct FileChat;

impl Plugin for FileChat {
    fn manifest(&self) -> Manifest {
        Manifest::parse(include_str!("../taji-plugin.toml"))
    }
    fn build(&self, b: &mut Build) {
        b.channel(Self);
    }
}

fn dir(secret: &Secret) -> Result<PathBuf, Failed> {
    let dir = PathBuf::from(secret.get("dir").map_or("", String::as_str));
    match dir.is_dir() {
        true => Ok(dir),
        false => Err(Failed::Refused("dir is not a directory".into())),
    }
}

fn lines(dir: &Path) -> Vec<String> {
    let text = std::fs::read_to_string(dir.join("in")).unwrap_or_default();
    text.lines().map(str::to_string).collect()
}

#[async_trait]
impl Channel for FileChat {
    fn id(&self) -> &'static str {
        "filechat"
    }
    fn name(&self) -> &'static str {
        "File chat"
    }
    fn fields(&self) -> &'static [&'static str] {
        &["dir"]
    }
    fn caps(&self) -> Caps {
        Caps {
            inbound: true,
            images: false,
            // Taji's own: a file documents no cap.
            text_limit: 4000,
        }
    }
    fn markup(&self) -> Markup {
        Markup::Plain
    }

    async fn link(&self, secret: Secret, _report: &Report) -> Result<Linked, Failed> {
        dir(&secret)?;
        Ok(Linked {
            secret,
            owner: None,
        })
    }

    async fn send(&self, secret: &Secret, owner: &str, msg: &Outbound) -> Result<String, Failed> {
        let path = dir(secret)?.join("out");
        let wrote = (std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path))
        .and_then(|mut f| writeln!(f, "to {owner}: {}", msg.text));
        wrote.map_err(|e| Failed::Unreached(e.to_string()))?;
        Ok(String::new())
    }

    async fn run(&self, secret: Secret, inbox: Inbox) -> Failed {
        let dir = match dir(&secret) {
            Ok(dir) => dir,
            Err(failed) => return failed,
        };
        let mut heard = lines(&dir).len();
        loop {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_or(0, |d| d.as_secs() as i64);
            for (n, text) in lines(&dir).into_iter().enumerate().skip(heard) {
                inbox.heard(Inbound {
                    id: n.to_string(),
                    sender: "me".into(),
                    at_utc: now,
                    text,
                });
                heard = n + 1;
            }
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    }
}
EOF
```

`owner: None` makes the kernel pair it by code. Each method answers one question:

| Method | Answers |
|---|---|
| `id`, `name`, `fields` | the wire word, the name, the secret fields its link takes |
| `caps` | `inbound`, `images`, `text_limit` |
| `link` | proves the fields; what to seal, and `owner` when the account is the owner's own |
| `send` | one message to the owner; the platform's id for it |
| `run` | hands each message whose sender the platform authenticated to `inbox`, until it breaks |
| `markup`, `send_framed`, `typing`, `unlink` | defaulted: Markdown, a framed message as its text, no typing signal, nothing to end. `unlink` runs on each unlink once `run`'s future is dropped, for an arm whose link leaves a session on the platform (sign the device out where the platform holds it, delete what the arm keeps); its `Failed` answers 502 `channel`, the channel unlinked all the same |

Two rules bind every arm:

- **Hold a 429, never resend it.** `taji_plugin::channel::Hold` is the arm's, as `Budget::hold` is a provider's: `limited` turns a 429 into `Failed::Unreached` and holds for its `Retry-After`, and `check`, before each call, refuses `Unreached` unsent until it passes. Nothing waits on it, so a held send answers at once and the kernel decides. A 429 naming no seconds holds nothing, and its error says so.
- **`text_limit` cites its cap:** the platform's documented one, or a comment saying it is Taji's own where none is documented, as `filechat`'s does.

The kernel does the rest (`engine/crates/taji/src/wire/channels.rs`): it seals the fields, issues the pairing code, drops every message not the owner's, renders Markdown into `markup`, cuts to `text_limit`, answers `taji` commands and asks everything else on the desk's Agent chat. The routes are the `channels` rows of the `//!` header of `engine/crates/taji/src/wire/mod.rs`.

## 2. Compose it into a kernel

Add `"plugins/filechat",` to the root `Cargo.toml`'s `members`, and `filechat = { path = "../../../plugins/filechat" }` to `[dev-dependencies]` in `engine/crates/taji-open/Cargo.toml`. Then write the binary and build:

```sh
cat > engine/crates/taji-open/examples/filechat.rs <<'EOF'
fn main() -> std::process::ExitCode {
    taji_open::kernel().add(filechat::FileChat::default).run()
}
EOF
CARGO_INCREMENTAL=0 cargo build -p taji-open --example filechat
```

The binary is `target/debug/examples/filechat`: Taji's kernel with your channel added.

## 3. Link and pair it

Define `W=$(mktemp -d)` and `boot`, `get` and `v` from [your first plugin](https://docs.taji.is/plugins/first-plugin.md#4-boot-a-kernel-with-your-plugin), with `boot` running `target/debug/examples/filechat` instead, then boot and read your row:

```sh
boot
get read/channels | jq -c '.[] | select(.id == "filechat") | {id, name, fields, inbound, state}'
```

You see `filechat`, its `fields` `["dir"]`, `inbound` `true` and `state` `unlinked`. `GET /read/channels` has one row of this shape for each arm the kernel holds; a stock kernel's, before yours is added:

```json file="examples/channel/channels.json" title="channels.json"
[
  {
    "id": "discord",
    "name": "Discord",
    "fields": [
      "token"
    ],
    "inbound": true,
    "state": "unlinked",
    "error": null,
    "qr": null,
    "code": null,
    "pair": null,
    "owner": null,
    "last_sent_utc": null
  },
  {
    "id": "slack",
    "name": "Slack",
    "fields": [
      "app_token",
      "bot_token"
    ],
    "inbound": true,
    "state": "unlinked",
    "error": null,
    "qr": null,
    "code": null,
    "pair": null,
    "owner": null,
    "last_sent_utc": null
  },
  {
    "id": "whatsapp",
    "name": "WhatsApp",
    "fields": [],
    "inbound": true,
    "state": "unlinked",
    "error": null,
    "qr": null,
    "code": null,
    "pair": null,
    "owner": null,
    "last_sent_utc": null
  },
  {
    "id": "webhook",
    "name": "Webhook",
    "fields": [
      "url"
    ],
    "inbound": false,
    "state": "unlinked",
    "error": null,
    "qr": null,
    "code": null,
    "pair": null,
    "owner": null,
    "last_sent_utc": null
  },
  {
    "id": "imessage",
    "name": "iMessage",
    "fields": [],
    "inbound": true,
    "state": "unlinked",
    "error": null,
    "qr": null,
    "code": null,
    "pair": null,
    "owner": null,
    "last_sent_utc": null
  }
]
```

*Captured 2026-12-03 on a keyless headless kernel.*

A row's `state` moves `unlinked`, `pairing` (linked, waiting for the code), `linked`, and `locked` when its secret is sealed in a vault this session has not opened. Open a vault to seal the fields, then link:

```sh
mkdir -p "$W/chat"
v link/vault/mint '{"password":"correct horse battery"}'
v channels/link "{\"channel\":\"filechat\",\"dir\":\"$W/chat\"}"
```

The link answers `{"channel":"filechat","pair":"<code>"}`, valid ten minutes. Send a line, the code, a command:

```sh
CODE=<code>
echo hello >> "$W/chat/in"; sleep 2
echo "$CODE" >> "$W/chat/in"; sleep 2
echo 'taji help' >> "$W/chat/in"; sleep 2
cat "$W/chat/out"
```

You see `to me: Linked to Taji.`, then `to me: Taji commands: taji new starts a new thread. …`, its backticks dropped for `Markup::Plain`. `hello`, before the code, was dropped unanswered (the state dir's `taji.log` says so), and its `channels.json` now reads `{"filechat":{"owner":"me"}}`.

## 4. Talk to it

Send from the wire, then as the owner:

```sh
v channels/send '{"text":"**hello** from the wire"}'
echo 'what is AAPL at?' >> "$W/chat/in"; sleep 5
tail -2 "$W/chat/out"
v ui/quit '{}'
```

`channels/send` answers `{"sent":[""]}`, the ids `send` returned. The lines are `to me: hello from the wire` and `to me: Open a conversation in Taji once.`: a non-command goes to the desk's agent, and this kernel has none.

To keep it, add its page ([template](https://docs.taji.is/contribute/docs.md#templates)); else undo the run:

```sh
rm -r plugins/filechat engine/crates/taji-open/examples/filechat.rs
git checkout -- Cargo.toml Cargo.lock engine/crates/taji-open/Cargo.toml
```

## If it fails

- **`channels/link` answers 502 `{"error":"channel","reason":"dir is not a directory"}`:** `link` refused the field. Make the directory and link again.
- **`channels/link` answers 409 `vault_locked`:** a channel with fields seals them, and the vault is not open. Mint or unlock it first (step 3).
- **The code is older than ten minutes:** it is void. `v channels/link '{"channel":"filechat"}'`, with no fields, pairs again off the sealed record and answers a new `pair`.

## Next

- A link form for the Connections page: a `[[link]]` whose `form` is the arm's `id`, in [the manifest](https://docs.taji.is/plugins/manifest.md); `plugins/webhook/taji-plugin.toml` is the smallest.
- Real arms: `plugins/webhook/src/lib.rs` (out only), `plugins/discord/src/gateway.rs` (inbound, paired by code), `plugins/imessage/src/lib.rs` (the owner's own account).
- `engine/crates/taji/scripts/channels_walk.py` walks a real platform from a phone, an agent attached.
