Skip to content

Commit e05ebf3

Browse files
committed
feat(channels): add Matrix and LINE join introductions
Introduce on admitted bot joins using the existing sealed no-tools turn and durable room dedupe. Matrix uses room metadata and readable history; LINE uses group names and explicitly unavailable history. Mark Matrix bridge membership provenance without changing existing event delivery, invite handling, or auto-join. Exclude startup snapshots and already-joined profile updates, including startup connection recovery. Simplify snapshot budget accounting while preserving prompt bytes, metadata order, and oldest-first message dropping. Add channel config, docs, and regression coverage.
1 parent 36ac9b8 commit e05ebf3

25 files changed

Lines changed: 834 additions & 65 deletions
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"core": 2358,
3-
"channel": 3654,
4-
"plugin": 4046
3+
"channel": 3659,
4+
"plugin": 4095
55
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
c551e9fe5323e6b7ba78bd0ab018cc2a927ed65a05f655dcd0e09391790436ee config-baseline.json
1+
84addfb0bac7ee72b8e3a5d39a246f8b9833fbc7cd0e180f86e39b64690af416 config-baseline.json
22
f67e975229dc70957375558f54d317304e94dc7cc435899aaf21c06271d5ad7e config-baseline.core.json
3-
a99906b23a6ad272a3de46f0422b2a0ac8787481de119e227725308c8179287b config-baseline.channel.json
4-
580d4bb93216d5a12fc715f3fbbaf5fff7bef548237fc168be7dc1a922407567 config-baseline.plugin.json
3+
ef89bddca3bc38381c9eed3d6b506ba3142cd448a64490f8c90d587f029136ee config-baseline.channel.json
4+
b12595a08989418c9aca20cc6d0f24f45671490a6af8e332350c43b0801ddd76 config-baseline.plugin.json

‎docs/channels/index.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ install. Channels marked "official plugin" install with one command
6161

6262
## Group join introductions
6363

64-
Discord, Slack, and Telegram post one room-specific introduction when the bot
64+
Discord, LINE, Matrix, Slack, and Telegram post one room-specific introduction when the bot
6565
joins an allowed group, instead of joining silently. The introduction says what
6666
the room appears to be for and names a few concrete jobs the bot could take on
6767
there, grounded in what that platform can actually show it.
@@ -71,7 +71,7 @@ there, grounded in what that platform can actually show it.
7171
`channels.<channel>.accounts.<accountId>.joinIntro`. Resolution order is the
7272
account value, then the channel value, then the default of `true`. There is no
7373
per-room switch, because a room is only configurable after the bot has already
74-
joined it. Only Discord, Slack, and Telegram accept this option; other channels
74+
joined it. Only Discord, LINE, Matrix, Slack, and Telegram accept this option; other channels
7575
reject it rather than accepting a setting they never read.
7676

7777
**What it reads.** Core requests up to 100 recent messages plus room metadata,
@@ -80,14 +80,16 @@ messages first. What each platform can supply differs:
8080

8181
| Channel | Room metadata | Prior messages |
8282
| -------- | ---------------------------------------- | ----------------------------------------------- |
83-
| Slack | Channel name, purpose, topic | Up to 100 via conversation history |
8483
| Discord | Channel name, topic | Up to 100, only with `Read Message History` |
84+
| LINE | Group name; none for multi-person rooms | None - the Messaging API has no history reader |
85+
| Matrix | Room name, topic | Up to 100 readable room messages |
86+
| Slack | Channel name, purpose, topic | Up to 100 via conversation history |
8587
| Telegram | Group title, description, pinned message | None - the Bot API cannot read pre-join history |
8688

8789
When history is unavailable or unreadable, the introduction is still posted from
8890
room metadata alone and says what it can see rather than inventing activity.
8991

90-
**Where it posts.** Slack and Telegram introduce in the room that was joined.
92+
**Where it posts.** LINE, Matrix, Slack, and Telegram introduce in the room that was joined.
9193
Discord joins a server rather than a channel, so it uses the system channel when
9294
it can both view and send there, otherwise the first text channel that qualifies;
9395
if no channel qualifies, it records a skip instead of posting.
@@ -96,7 +98,9 @@ if no channel qualifies, it records a skip instead of posting.
9698
and room with a 90-day lifetime, so reconnects and gateway restarts do not repeat
9799
an introduction. Discord additionally ignores server-available events older than
98100
five minutes, so restarting never mass-introduces into servers the bot already
99-
belonged to. A re-invite after the claim expires introduces again.
101+
belonged to. Matrix ignores startup room snapshots and membership updates that
102+
leave the bot joined, such as display-name changes. An unaccepted Matrix invite
103+
does not trigger an introduction. A re-invite after the claim expires introduces again.
100104

101105
**Safety.** Room titles, topics, pinned text, and message history are third-party
102106
content, so they are wrapped as untrusted external content and the introduction

‎docs/channels/line.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,21 @@ LINE IDs are case-sensitive. Valid IDs look like:
160160
- Group: `C` + 32 hex chars
161161
- Room: `R` + 32 hex chars
162162

163+
## Group join introductions
164+
165+
When the bot joins an allowed group or multi-person room, it posts one
166+
introduction there. LINE exposes a group name through its group summary API, but
167+
no room name or topic for multi-person rooms. The Messaging API cannot read prior
168+
messages, so introductions use only available metadata and ask what the room
169+
wants the bot to take on rather than inventing activity.
170+
171+
Introductions are enabled by default. Set `channels.line.joinIntro: false` to
172+
disable them, or use `channels.line.accounts.<accountId>.joinIntro` to override
173+
one account. They never run in one-to-one user chats or when another member joins.
174+
See [group join introductions](/channels#group-join-introductions) for room
175+
admission, once-per-room behavior, and the no-tools turn that treats room content
176+
as untrusted.
177+
163178
## Message behavior
164179

165180
- Text is chunked at 5000 characters.

‎docs/channels/matrix.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,24 @@ Set `autoJoin: "allowlist"` plus `autoJoinAllowlist` to restrict accepted invite
9191
}
9292
```
9393

94+
### Group join introductions
95+
96+
When the bot joins an allowed group room, it posts one introduction grounded in
97+
the room name, topic, and up to 100 readable recent room messages. If reading
98+
history fails, the introduction uses only available metadata and does not invent
99+
room activity.
100+
101+
Introductions are enabled by default. Set `channels.matrix.joinIntro: false` to
102+
disable them, or use `channels.matrix.accounts.<accountId>.joinIntro` to override
103+
one account. Direct rooms never receive introductions. Only an actual join
104+
transition triggers one: an unaccepted invite, a startup snapshot of an existing
105+
room, or a profile update while already joined does not. This does not change
106+
[`autoJoin`](#auto-join), which defaults to `"off"`.
107+
108+
See [group join introductions](/channels#group-join-introductions) for room
109+
admission, once-per-room behavior, and the no-tools turn that treats room content
110+
as untrusted.
111+
94112
### Allowlist target formats
95113

96114
Matrix user IDs are case-sensitive. Copy the exact `@user:server` value Matrix reports for every allowlist, approver, and approval-target field. If an existing config used different casing, update it manually; OpenClaw cannot safely infer or rewrite the intended account because case-distinct IDs can identify different users.
@@ -887,6 +905,7 @@ Room allowlist keys (`groups`, legacy `rooms`) should be room IDs or aliases. Pl
887905

888906
### Reply behavior
889907

908+
- `joinIntro`: introduce when the bot joins an allowed group room. Default: `true`. Per-account override: `accounts.<accountId>.joinIntro`.
890909
- `replyToMode`: `"off"` (default), `"first"`, `"all"`, or `"batched"`.
891910
- `threadReplies`: `"off"` (top-level default resolves to `"inbound"` unless explicitly set), `"inbound"`, or `"always"`.
892911
- `threadBindings`: per-channel overrides for thread-bound session routing and lifecycle.

‎docs/gateway/config-channels.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,13 @@ With remote `imsg` v0.13.4, poll votes must use `pollOptionId`; its `poll.vote`
670670

671671
</Accordion>
672672

673+
### LINE
674+
675+
LINE is plugin-backed and configured under `channels.line`.
676+
677+
- `channels.line.joinIntro` defaults to `true`. When the bot joins an allowed group or multi-person room, it posts one introduction using the group name when available. LINE exposes no multi-person room name or topic, and its Messaging API cannot read prior messages. Set this option to `false` to disable introductions, or use `channels.line.accounts.<accountId>.joinIntro` for an account-specific override. Introductions happen once per room and never run in one-to-one user chats; see [group join introductions](/channels#group-join-introductions).
678+
- Full LINE configuration, webhook setup, and access policy are documented in [LINE](/channels/line).
679+
673680
### Matrix
674681

675682
Matrix is plugin-backed and configured under `channels.matrix`.
@@ -707,6 +714,7 @@ Matrix is plugin-backed and configured under `channels.matrix`.
707714
- `channels.matrix.network.dangerouslyAllowPrivateNetwork` allows private/internal homeservers. `proxy` and this network opt-in are independent controls.
708715
- `channels.matrix.defaultAccount` selects the preferred account in multi-account setups.
709716
- `channels.matrix.autoJoin` defaults to `"off"`, so invited rooms and fresh DM-style invites are ignored until you set `autoJoin: "allowlist"` with `autoJoinAllowlist` or `autoJoin: "always"`.
717+
- `channels.matrix.joinIntro` defaults to `true`. When the bot actually joins an allowed group room, it posts one introduction using the room name, topic, and up to 100 readable recent messages. A failed history read leaves a metadata-only introduction. Set this option to `false` to disable introductions, or use `channels.matrix.accounts.<accountId>.joinIntro` for an account-specific override. Introductions happen once per room; unaccepted invites, startup room snapshots, membership updates that leave the bot joined, and direct rooms do not trigger them. See [group join introductions](/channels#group-join-introductions).
710718
- `channels.matrix.execApprovals`: Matrix-native exec approval delivery and approver authorization.
711719
- `enabled`: `true`, `false`, or `"auto"` (default). In auto mode, exec approvals activate when approvers can be resolved from `approvers` or `commands.ownerAllowFrom`.
712720
- `approvers`: Matrix user IDs (e.g. `@owner:example.org`) allowed to approve exec requests.
@@ -798,7 +806,7 @@ Run multiple accounts per channel (each with its own `accountId`):
798806

799807
### Other plugin channels
800808

801-
Many plugin channels are configured as `channels.<id>` and documented in their dedicated channel pages (for example Feishu, LINE, Nextcloud Talk, Nostr, QQ Bot, Synology Chat, Twitch, and Zalo).
809+
Many plugin channels are configured as `channels.<id>` and documented in their dedicated channel pages (for example Feishu, Nextcloud Talk, Nostr, QQ Bot, Synology Chat, Twitch, and Zalo).
802810
See the full channel index: [Channels](/channels).
803811

804812
### Group chat mention gating
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
import type { messagingApi, webhook } from "@line/bot-sdk";
2+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
3+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { LineAccountConfig } from "./types.js";
5+
6+
type ReportChannelRoomJoin =
7+
typeof import("openclaw/plugin-sdk/channel-join-intro-runtime").reportChannelRoomJoin;
8+
9+
const { reportJoin, getGroupSummary, createClient } = vi.hoisted(() => {
10+
const summary = vi.fn<messagingApi.MessagingApiClient["getGroupSummary"]>();
11+
return {
12+
reportJoin: vi.fn<ReportChannelRoomJoin>(async () => ({ kind: "posted" })),
13+
getGroupSummary: summary,
14+
createClient: vi.fn(function () {
15+
return { getGroupSummary: summary };
16+
}),
17+
};
18+
});
19+
20+
vi.mock("openclaw/plugin-sdk/channel-join-intro-runtime", () => ({
21+
reportChannelRoomJoin: reportJoin,
22+
}));
23+
vi.mock("@line/bot-sdk", async (importOriginal) => {
24+
const actual = await importOriginal<typeof import("@line/bot-sdk")>();
25+
return {
26+
...actual,
27+
messagingApi: { ...actual.messagingApi, MessagingApiClient: createClient },
28+
};
29+
});
30+
31+
let handleLineWebhookEvents: typeof import("./bot-handlers.js").handleLineWebhookEvents;
32+
let resolveLineAccount: typeof import("./accounts.js").resolveLineAccount;
33+
34+
const groupId = `C${"a".repeat(32)}`;
35+
const roomId = `R${"b".repeat(32)}`;
36+
const userId = `U${"c".repeat(32)}`;
37+
const sources = [
38+
{ type: "group", groupId },
39+
{ type: "room", roomId },
40+
] as const;
41+
42+
function joinEvent(source: webhook.Source): webhook.JoinEvent {
43+
return {
44+
type: "join",
45+
source,
46+
replyToken: "join-reply",
47+
timestamp: 1_800_000_000_000,
48+
mode: "active",
49+
webhookEventId: "join-event",
50+
deliveryContext: { isRedelivery: false },
51+
};
52+
}
53+
54+
function createContext(config: LineAccountConfig = {}) {
55+
const cfg: OpenClawConfig = {
56+
agents: { list: [{ id: "main" }, { id: "room-agent" }] },
57+
bindings: [{ agentId: "room-agent", match: { channel: "line", accountId: "work" } }],
58+
channels: {
59+
line: {
60+
accounts: {
61+
work: {
62+
channelAccessToken: "line-work-token",
63+
channelSecret: "line-work-secret",
64+
groupPolicy: "allowlist",
65+
groupAllowFrom: [userId],
66+
...config,
67+
},
68+
},
69+
},
70+
},
71+
};
72+
return {
73+
cfg,
74+
account: resolveLineAccount({ cfg, accountId: "work" }),
75+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
76+
mediaMaxBytes: 1,
77+
processMessage: vi.fn(),
78+
};
79+
}
80+
81+
describe("LINE group join introductions", () => {
82+
beforeAll(async () => {
83+
({ handleLineWebhookEvents } = await import("./bot-handlers.js"));
84+
({ resolveLineAccount } = await import("./accounts.js"));
85+
});
86+
87+
beforeEach(() => {
88+
reportJoin.mockClear();
89+
createClient.mockClear();
90+
getGroupSummary.mockReset();
91+
getGroupSummary.mockResolvedValue({ groupId, groupName: "Incident Response" });
92+
});
93+
94+
afterAll(() => {
95+
vi.doUnmock("openclaw/plugin-sdk/channel-join-intro-runtime");
96+
vi.doUnmock("@line/bot-sdk");
97+
vi.resetModules();
98+
});
99+
100+
it.each(sources)(
101+
"introduces the bot in its joined $type without human sender authorization",
102+
async (source) => {
103+
const context = createContext();
104+
const conversationId = source.type === "group" ? source.groupId : source.roomId;
105+
106+
await handleLineWebhookEvents([joinEvent(source)], context);
107+
108+
expect(reportJoin).toHaveBeenCalledTimes(1);
109+
const params = reportJoin.mock.calls[0]?.[0];
110+
if (!params) {
111+
throw new Error("Expected a LINE join introduction");
112+
}
113+
expect(params).toMatchObject({
114+
cfg: context.cfg,
115+
channel: "line",
116+
accountId: "work",
117+
conversationId,
118+
deliverTo: conversationId,
119+
roomAllowed: true,
120+
route: {
121+
agentId: "room-agent",
122+
sessionKey: `agent:room-agent:line:group:${conversationId.toLowerCase()}`,
123+
},
124+
});
125+
await expect(params.resolveRoomContext({ messageLimit: 100 })).resolves.toEqual(
126+
source.type === "group"
127+
? { title: "Incident Response", historyUnavailable: true }
128+
: { historyUnavailable: true },
129+
);
130+
if (source.type === "group") {
131+
expect(getGroupSummary).toHaveBeenCalledWith(groupId);
132+
expect(createClient).toHaveBeenCalledWith({ channelAccessToken: "line-work-token" });
133+
} else {
134+
expect(getGroupSummary).not.toHaveBeenCalled();
135+
}
136+
expect(context.processMessage).not.toHaveBeenCalled();
137+
},
138+
);
139+
140+
it("keeps an honest thin snapshot when the group summary request fails", async () => {
141+
getGroupSummary.mockRejectedValue(new Error("LINE unavailable"));
142+
await handleLineWebhookEvents([joinEvent(sources[0])], createContext());
143+
144+
const params = reportJoin.mock.calls[0]?.[0];
145+
if (!params) {
146+
throw new Error("Expected a LINE join introduction");
147+
}
148+
await expect(params.resolveRoomContext({ messageLimit: 100 })).resolves.toEqual({
149+
historyUnavailable: true,
150+
});
151+
});
152+
153+
it.each([
154+
{ name: "a direct user chat", event: joinEvent({ type: "user", userId }) },
155+
{
156+
name: "a human member join",
157+
event: {
158+
...joinEvent(sources[0]),
159+
type: "memberJoined",
160+
joined: { members: [{ type: "user", userId }] },
161+
} satisfies webhook.MemberJoinedEvent,
162+
},
163+
])("does not introduce for $name", async ({ event }) => {
164+
const context = createContext();
165+
await handleLineWebhookEvents([event], context);
166+
167+
expect(reportJoin).not.toHaveBeenCalled();
168+
expect(getGroupSummary).not.toHaveBeenCalled();
169+
expect(context.processMessage).not.toHaveBeenCalled();
170+
});
171+
172+
it.each([
173+
{ name: "disabled group policy", config: { groupPolicy: "disabled" as const } },
174+
{ name: "a disabled group", config: { groups: { [groupId]: { enabled: false } } } },
175+
{ name: "disabled wildcard groups", config: { groups: { "*": { enabled: false } } } },
176+
])("reports denied admission for $name without reading metadata", async ({ config }) => {
177+
await handleLineWebhookEvents([joinEvent(sources[0])], createContext(config));
178+
179+
expect(reportJoin).toHaveBeenCalledWith(
180+
expect.objectContaining({ conversationId: groupId, roomAllowed: false }),
181+
);
182+
expect(getGroupSummary).not.toHaveBeenCalled();
183+
});
184+
});

0 commit comments

Comments
 (0)