Repository navigation
channels: Matrix (REST /sync long-poll) + IRC (TIdIRC) bots - #86
Conversation
Two more picoclaw channels ported. MQTT deferred to its own PR
because Indy doesn't ship MQTT components and a clean port needs
us to write the MQTT 3.1.1 wire protocol from scratch — that's
its own piece of work and deserves dedicated review attention.
PasClaw.Channels.Matrix
TMatrixBot connects to any Matrix homeserver with a pre-
provisioned access token, runs the standard /sync long-poll
loop, and replies to inbound m.room.message events via
/rooms/<id>/send. Same shape as the Telegram bot — holds
Cfg/Provider/Registry, runs RunToolLoop inline — except
Matrix has to coexist with the gateway HTTP server, so the
sync loop lives on its own TThread (suspended-then-Start
idiom from the LINE/WhatsApp Codex P2 fix).
Endpoints:
GET /_matrix/client/v3/sync?since=<tok>&timeout=30000
PUT /_matrix/client/v3/rooms/<id>/send/m.room.message/<txn>
GET /_matrix/client/v3/account/whoami (one-shot at
startup so the
bot can ignore
its own echoes)
Walks rooms.join[roomId].timeline.events[] for each sync
response, filters type=m.room.message + content.msgtype=m.text,
drops messages where sender matches the bot's own user_id, and
hands the body to RunToolLoop. Reply goes back to the same
roomId. next_batch token threaded across iterations so we only
pull new events.
E2EE rooms surface as m.room.encrypted events which the bot
doesn't decrypt — those skip silently (documented gap).
PasClaw.Channels.IRC
TIRCBot wraps Indy's TIdIRC. Connects to one server, joins one
channel, listens via OnPrivateMessage. Reply addressing follows
the IRC convention: channel messages must be prefixed
"<botnick>:" or "<botnick>," for the bot to respond (anything
else is ignored — channel chatter would be loud otherwise);
direct PMs always get a reply. Channel replies prefix the
user's nick so they know it's aimed at them; PM replies don't.
Indy's TIdCmdTCPClient gives us the listener thread for free —
the bot doesn't need its own. Start connects + JOINs and
returns; RequestStop disconnects.
TLS deferred to a follow-up (TIdIRC accepts an IOHandler;
wiring TIdSSLIOHandlerSocketOpenSSL is straightforward when
someone needs it).
Supporting additions:
TJsonObject.Keys — new method on both backends (fpjson Names[],
System.JSON Pairs[]). Returns a caller-owned TStringList of
top-level keys. Matrix sync needs it to walk rooms.join's
dynamic-key map; previously the cron state code worked around
the missing API with an array-of-objects schema. Future
dynamic-key parsers (provider catalogs, MCP server maps) get
the cleaner API too.
PutJSON — sibling of PostJSON in PasClaw.Providers.HTTP. Same
UTF-8 body + JSON content-type + header machinery, just routes
through Http.Put. Matrix's /rooms/<id>/send is the first
caller; future PUT endpoints (Matrix profile updates, REST
resource upserts) reuse it.
Gateway wiring
--matrix --matrix-homeserver URL --matrix-token TOKEN
--irc --irc-server HOST [--irc-port N] --irc-nick NICK
[--irc-channel "#room"] [--irc-password PASS]
Env-var equivalents PASCLAW_MATRIX_HOMESERVER, _TOKEN, and
PASCLAW_IRC_SERVER/PORT/NICK/CHANNEL/PASSWORD match the
existing channel-bot pattern. Gateway banner picks up two
more lines when these are enabled. Lifecycle: both
Start/Stop sit alongside LINE/WhatsApp in the existing
try/finally block; the IRC bot needs no explicit
WaitForStop (TIdIRC.Disconnect is synchronous), Matrix
joins its thread.
dproj DCCReference entries for both new units. Makefile
unchanged — both live under src/pkg/channels which is already
on UNIT_DIRS.
README env-var table grows seven rows (two Matrix, five IRC).
Gateway example block grows --matrix and --irc lines.
Repository-layout channels/ row spells out the full set of nine.
Verified locally:
make builds clean under FPC 3.2.2.
pasclaw status / --help byte-identical to pre-change.
Existing channel bots (LINE, WhatsApp, Telegram) unchanged.
What's still left from picoclaw's channel catalog:
MQTT (next PR — needs hand-rolled wire protocol).
Chinese-ecosystem (DingTalk, Feishu, OneBot, QQ, WeCom,
Weixin) — skipped per maintainer.
Hardware (MaixCAM, Pico) — skipped per maintainer.
*_native variants (whatsapp_native) — skipped.
VK — long-poll bot API; identical shape to Telegram. Easy
follow-up, queued.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ba6d8b114b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not WhoAmI(FUserId) then | ||
| LogWarn('matrix: whoami failed — own messages may echo into the loop', []) |
There was a problem hiding this comment.
Stop startup when Matrix identity lookup fails
When /account/whoami fails transiently but /sync still succeeds, this continues with FUserId = ''. ProcessEvent only suppresses events whose sender equals FUserId, so every reply sent by PostSend is received again as a new user prompt, producing an unbounded reply loop that can spam the room and consume model API quota. Retry identity resolution or refuse to launch the sync thread until the bot user ID is known.
Useful? React with 👍 / 👎.
| URL := ApiURL('/_matrix/client/v3/sync?timeout=' + IntToStr(SYNC_TIMEOUT_MS)); | ||
| if FNextBatch <> '' then | ||
| URL := URL + '&since=' + FNextBatch; |
There was a problem hiding this comment.
Discard the initial Matrix timeline before processing events
On every gateway startup, the first request omits since and its response is passed directly to ProcessSync. The Matrix specification states that an initial /sync without since returns the most recent message events for each room, not an empty snapshot (syncing flow). Consequently, restarting the gateway replays recent room history through the model and posts duplicate answers. Perform an initial token-only sync or otherwise suppress timeline delivery until FNextBatch has been established.
Useful? React with 👍 / 👎.
| LoopCfg.OnToolCall := nil; | ||
| LoopCfg.OnToolResult := nil; | ||
|
|
||
| if RunToolLoop(LoopCfg, Msgs, Loop) and (Loop.Content <> '') then |
There was a problem hiding this comment.
Dispatch IRC model work outside the listener thread
For an addressed IRC message whose model or tool call is slow, this synchronous RunToolLoop executes inside OnPrivateMessage. Indy's listener implementation reads one line and invokes CommandHandlers.HandleCommand synchronously before reading the next line (TIdCmdTCPClientListeningThread.Run), and TIdIRC handles server PING through that same command pipeline. While the model is running, queued PING commands cannot be answered, so sufficiently slow requests cause the IRC server to disconnect the bot; dispatch the agent reply to a worker thread or queue.
Useful? React with 👍 / 👎.
…worker thread Three Codex reviews against the Matrix + IRC bots — all legit and material. PR #86 P1: Matrix /whoami failure caused an echo loop. Start used to warn-and-continue if /account/whoami failed transiently, leaving FUserId empty. ProcessEvent's "if Sender = FUserId" then matched Sender='' instead of the bot's actual user_id, so every outbound reply re-entered the loop as a fresh prompt — the bot would spam- reply to itself until the server kicked it or the API quota ran out. Fix: WhoAmIWithRetry(out UserId; Attempts) — calls WhoAmI in a loop with exponential-ish backoff (1s, 2s, 4s) between attempts, and watches FStopEvt so an in-flight RequestStop doesn't sit through the backoff. If all attempts fail, Start logs a hard error pointing at the token/homeserver and REFUSES to launch the sync thread. PR #86 P1: Initial /sync without a since= parameter replays history through the model. Per spec, the first sync returns whatever recent timeline the homeserver has cached for each joined room. Every restart would produce a duplicate run through the most recent few messages — the bot would re-answer them and look like it had time-travelled. Fix: InitialSyncToken — one-shot call to GET /sync?timeout=0&filter={"room":{"timeline":{"limit":0}}} to fetch the next_batch anchor with zero timeline events. Start runs it after /whoami passes, sets FNextBatch, then launches TMatrixSyncThread; the long-poll loop's first GetSync uses that token so the first delivered events are strictly NEW. Bails out the same way as WhoAmI if the token fetch fails. PR #86 P2: IRC RunToolLoop blocked Indy's TIdCmdTCPClient listener. OnPrivateMessage ran the agent inline. A slow turn (model + tool loop chasing fs_read / shell_exec / web_fetch) kept the listener from servicing server PINGs, the server killed the connection after its ping-timeout, and the bot disconnected from IRC. Fix: TIRCMessageWorker — self-freeing TThread per inbound message, same suspended-then-Start pattern from PR #78's LINE/WhatsApp worker fix. HandlePrivMessage now spawns one and returns immediately. The listener keeps PONGing on schedule; the worker runs RunToolLoop and FClient.Say asynchronously. Worker exception swallowed with a warn so a bug in the agent path doesn't bring down the IRC connection. Build: clean under FPC 3.2.2; both channel units compile with the new worker types and retry helpers resolving correctly through unit-private visibility. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Two more picoclaw channels ported. MQTT split out to its own PR — Indy doesn't ship MQTT components and a clean port requires writing the MQTT 3.1.1 wire protocol from scratch; that deserves dedicated review attention.
PasClaw.Channels.MatrixTMatrixBotconnects to any Matrix homeserver with a pre-provisioned access token, runs the standard/synclong-poll, and replies via/rooms/<id>/send. Same shape as Telegram (holdsCfg/Provider/Registry, runsRunToolLoopinline) but the sync loop lives on its ownTThread(suspended-then-Start, the Codex P2 idiom from PR #78) so it coexists with the gateway HTTP server.Walks
rooms.join[roomId].timeline.events[]per sync, filterstype=m.room.message+content.msgtype=m.text, drops sender==self, threadsnext_batchacross iterations. E2EE rooms surface asm.room.encryptedand skip silently (documented gap).PasClaw.Channels.IRCTIRCBotwraps Indy'sTIdIRC. Connects to one server, joins one channel, listens viaOnPrivateMessage. Reply addressing follows IRC convention: channel messages must be prefixed<botnick>:or<botnick>,for the bot to respond (anything else is ignored — channel chatter would be loud otherwise); direct PMs always get a reply. Channel replies prefix the user's nick.TIdCmdTCPClientgives us the listener thread for free — no worker thread needed. TLS deferred (TIdIRC accepts an IOHandler; wiringTIdSSLIOHandlerSocketOpenSSLis straightforward when needed).Supporting additions
TJsonObject.Keys— new method on both backends (fpjsonNames[], DelphiPairs[]). Returns a caller-ownedTStringListof top-level keys. Matrix sync needs it to walkrooms.join's dynamic-key map; the cron-state code worked around the missing API with an array-of-objects schema earlier. Future dynamic-key parsers benefit too.PutJSON— sibling ofPostJSONinPasClaw.Providers.HTTP. Same UTF-8 body + JSON content-type + header machinery, routes throughHttp.Put. Matrix's/rooms/<id>/sendis the first caller.CLI
Env-var equivalents
PASCLAW_MATRIX_HOMESERVER/_TOKENandPASCLAW_IRC_SERVER/_PORT/_NICK/_CHANNEL/_PASSWORDmatch the existing channel-bot pattern. Gateway banner picks up two more lines when enabled.Verification
make— clean build under FPC 3.2.2.pasclaw statusand--helpbyte-identical to pre-change.What's still left from picoclaw's channel catalog
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code