Skip to content

Commit 0cd2413

Browse files
feat: add session.identityLinks for cross-platform DM session linking (#1033)
Co-authored-by: Shadow <[email protected]>
1 parent 8ffb8cc commit 0cd2413

10 files changed

Lines changed: 100 additions & 2 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
- Heartbeat: tighten prompt guidance + suppress duplicate alerts for 24h. (#980) — thanks @voidserf.
2020
- Repo: ignore local identity files to avoid accidental commits. (#1001) — thanks @gerardward2007.
2121
- Sessions/Security: add `session.dmScope` for multi-user DM isolation and audit warnings. (#948) — thanks @Alphonse-arianee.
22+
- Sessions: add `session.identityLinks` for cross-platform DM session linking. (#1033) — thanks @thewilloftheshadow.
2223
- Plugins: add provider auth registry + `clawdbot models auth login` for plugin-driven OAuth/API key flows.
2324
- Skills: add user-invocable skill commands (sanitized + unique), native skill registration gating, and an opt-out for model invocation.
2425
- Onboarding: switch channels setup to a single-select loop with per-channel actions and disabled hints in the picker.

docs/concepts/session.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Use `session.dmScope` to control how **direct messages** are grouped:
1111
- `main` (default): all DMs share the main session for continuity.
1212
- `per-peer`: isolate by sender id across channels.
1313
- `per-channel-peer`: isolate by channel + sender (recommended for multi-user inboxes).
14+
Use `session.identityLinks` to map provider-prefixed peer ids to a canonical identity so the same person shares a DM session across channels when using `per-peer` or `per-channel-peer`.
1415

1516
## Gateway is the source of truth
1617
All session state is **owned by the gateway** (the “master” Clawdbot). UI clients (macOS app, WebChat, etc.) must query the gateway for session lists and token counts instead of reading local files.
@@ -42,6 +43,7 @@ the workspace is writable. See [Memory](/concepts/memory) and
4243
- Multiple phone numbers and channels can map to the same agent main key; they act as transports into one conversation.
4344
- `per-peer`: `agent:<agentId>:dm:<peerId>`.
4445
- `per-channel-peer`: `agent:<agentId>:<channel>:dm:<peerId>`.
46+
- If `session.identityLinks` matches a provider-prefixed peer id (for example `telegram:123`), the canonical key replaces `<peerId>` so the same person shares a session across channels.
4547
- Group chats isolate state: `agent:<agentId>:<channel>:group:<id>` (rooms/channels use `agent:<agentId>:<channel>:channel:<id>`).
4648
- Telegram forum topics append `:topic:<threadId>` to the group id for isolation.
4749
- Legacy `group:<id>` keys are still recognized for migration.
@@ -86,6 +88,9 @@ Send these as standalone messages so they register.
8688
session: {
8789
scope: "per-sender", // keep group keys separate
8890
dmScope: "main", // DM continuity (set per-channel-peer for shared inboxes)
91+
identityLinks: {
92+
alice: ["telegram:123456789", "discord:987654321012345678"]
93+
},
8994
idleMinutes: 120,
9095
resetTriggers: ["/new", "/reset"],
9196
store: "~/.clawdbot/agents/{agentId}/sessions/sessions.json",

docs/gateway/configuration.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,6 +2269,9 @@ Controls session scoping, idle expiry, reset triggers, and where the session sto
22692269
session: {
22702270
scope: "per-sender",
22712271
dmScope: "main",
2272+
identityLinks: {
2273+
alice: ["telegram:123456789", "discord:987654321012345678"]
2274+
},
22722275
idleMinutes: 60,
22732276
resetTriggers: ["/new", "/reset"],
22742277
// Default is already per-agent under ~/.clawdbot/agents/<agentId>/sessions/sessions.json
@@ -2297,6 +2300,8 @@ Fields:
22972300
- `main`: all DMs share the main session for continuity.
22982301
- `per-peer`: isolate DMs by sender id across channels.
22992302
- `per-channel-peer`: isolate DMs per channel + sender (recommended for multi-user inboxes).
2303+
- `identityLinks`: map canonical ids to provider-prefixed peers so the same person shares a DM session across channels when using `per-peer` or `per-channel-peer`.
2304+
- Example: `alice: ["telegram:123456789", "discord:987654321012345678"]`.
23002305
- `agentToAgent.maxPingPongTurns`: max reply-back turns between requester/target (0–5, default 5).
23012306
- `sendPolicy.default`: `allow` or `deny` fallback when no rule matches.
23022307
- `sendPolicy.rules[]`: match by `channel`, `chatType` (`direct|group|room`), or `keyPrefix` (e.g. `cron:`). First deny wins; otherwise allow.

docs/gateway/security.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ By default, Clawdbot routes **all DMs into the main session** so your assistant
133133
}
134134
```
135135

136-
This prevents cross-user context leakage while keeping group chats isolated. See [Session Management](/concepts/session) and [Configuration](/gateway/configuration).
136+
This prevents cross-user context leakage while keeping group chats isolated. If the same person contacts you on multiple channels, use `session.identityLinks` to collapse those DM sessions into one canonical identity. See [Session Management](/concepts/session) and [Configuration](/gateway/configuration).
137137

138138
## Allowlists (DM + groups) — terminology
139139

src/config/schema.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,8 @@ const FIELD_HELP: Record<string, string> = {
337337
"commands.useAccessGroups": "Enforce access-group allowlists/policies for commands.",
338338
"session.dmScope":
339339
'DM session scoping: "main" keeps continuity; "per-peer" or "per-channel-peer" isolates DM history (recommended for shared inboxes).',
340+
"session.identityLinks":
341+
"Map canonical identities to provider-prefixed peer IDs for DM session linking (example: telegram:123456).",
340342
"channels.telegram.configWrites":
341343
"Allow Telegram to write config in response to channel events/commands (default: true).",
342344
"channels.slack.configWrites":

src/config/types.base.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ export type SessionConfig = {
5757
scope?: SessionScope;
5858
/** DM session scoping (default: "main"). */
5959
dmScope?: DmScope;
60+
/** Map platform-prefixed identities (e.g. "telegram:123") to canonical DM peers. */
61+
identityLinks?: Record<string, string[]>;
6062
resetTriggers?: string[];
6163
idleMinutes?: number;
6264
heartbeatIdleMinutes?: number;

src/config/zod-schema.session.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export const SessionSchema = z
1313
dmScope: z
1414
.union([z.literal("main"), z.literal("per-peer"), z.literal("per-channel-peer")])
1515
.optional(),
16+
identityLinks: z.record(z.string(), z.array(z.string())).optional(),
1617
resetTriggers: z.array(z.string()).optional(),
1718
idleMinutes: z.number().int().positive().optional(),
1819
heartbeatIdleMinutes: z.number().int().positive().optional(),

src/routing/resolve-route.test.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,42 @@ describe("resolveAgentRoute", () => {
4444
expect(route.sessionKey).toBe("agent:main:whatsapp:dm:+15551234567");
4545
});
4646

47+
test("identityLinks collapses per-peer DM sessions across providers", () => {
48+
const cfg: ClawdbotConfig = {
49+
session: {
50+
dmScope: "per-peer",
51+
identityLinks: {
52+
alice: ["telegram:111111111", "discord:222222222222222222"],
53+
},
54+
},
55+
};
56+
const route = resolveAgentRoute({
57+
cfg,
58+
channel: "telegram",
59+
accountId: null,
60+
peer: { kind: "dm", id: "111111111" },
61+
});
62+
expect(route.sessionKey).toBe("agent:main:dm:alice");
63+
});
64+
65+
test("identityLinks applies to per-channel-peer DM sessions", () => {
66+
const cfg: ClawdbotConfig = {
67+
session: {
68+
dmScope: "per-channel-peer",
69+
identityLinks: {
70+
alice: ["telegram:111111111", "discord:222222222222222222"],
71+
},
72+
},
73+
};
74+
const route = resolveAgentRoute({
75+
cfg,
76+
channel: "discord",
77+
accountId: null,
78+
peer: { kind: "dm", id: "222222222222222222" },
79+
});
80+
expect(route.sessionKey).toBe("agent:main:discord:dm:alice");
81+
});
82+
4783
test("peer binding wins over account binding", () => {
4884
const cfg: ClawdbotConfig = {
4985
bindings: [

src/routing/resolve-route.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ export function buildAgentSessionKey(params: {
7070
peer?: RoutePeer | null;
7171
/** DM session scope. */
7272
dmScope?: "main" | "per-peer" | "per-channel-peer";
73+
identityLinks?: Record<string, string[]>;
7374
}): string {
7475
const channel = normalizeToken(params.channel) || "unknown";
7576
const peer = params.peer;
@@ -80,6 +81,7 @@ export function buildAgentSessionKey(params: {
8081
peerKind: peer?.kind ?? "dm",
8182
peerId: peer ? normalizeId(peer.id) || "unknown" : null,
8283
dmScope: params.dmScope,
84+
identityLinks: params.identityLinks,
8385
});
8486
}
8587

@@ -153,6 +155,7 @@ export function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentR
153155
});
154156

155157
const dmScope = input.cfg.session?.dmScope ?? "main";
158+
const identityLinks = input.cfg.session?.identityLinks;
156159

157160
const choose = (agentId: string, matchedBy: ResolvedAgentRoute["matchedBy"]) => {
158161
const resolvedAgentId = pickFirstExistingAgentId(input.cfg, agentId);
@@ -165,6 +168,7 @@ export function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentR
165168
channel,
166169
peer,
167170
dmScope,
171+
identityLinks,
168172
}),
169173
mainSessionKey: buildAgentMainSessionKey({
170174
agentId: resolvedAgentId,

src/routing/session-key.ts

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,23 @@ export function buildAgentPeerSessionKey(params: {
8888
channel: string;
8989
peerKind?: "dm" | "group" | "channel" | null;
9090
peerId?: string | null;
91+
identityLinks?: Record<string, string[]>;
9192
/** DM session scope. */
9293
dmScope?: "main" | "per-peer" | "per-channel-peer";
9394
}): string {
9495
const peerKind = params.peerKind ?? "dm";
9596
if (peerKind === "dm") {
9697
const dmScope = params.dmScope ?? "main";
97-
const peerId = (params.peerId ?? "").trim();
98+
let peerId = (params.peerId ?? "").trim();
99+
const linkedPeerId =
100+
dmScope === "main"
101+
? null
102+
: resolveLinkedPeerId({
103+
identityLinks: params.identityLinks,
104+
channel: params.channel,
105+
peerId,
106+
});
107+
if (linkedPeerId) peerId = linkedPeerId;
98108
if (dmScope === "per-channel-peer" && peerId) {
99109
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
100110
return `agent:${normalizeAgentId(params.agentId)}:${channel}:dm:${peerId}`;
@@ -112,6 +122,38 @@ export function buildAgentPeerSessionKey(params: {
112122
return `agent:${normalizeAgentId(params.agentId)}:${channel}:${peerKind}:${peerId}`;
113123
}
114124

125+
function resolveLinkedPeerId(params: {
126+
identityLinks?: Record<string, string[]>;
127+
channel: string;
128+
peerId: string;
129+
}): string | null {
130+
const identityLinks = params.identityLinks;
131+
if (!identityLinks) return null;
132+
const peerId = params.peerId.trim();
133+
if (!peerId) return null;
134+
const candidates = new Set<string>();
135+
const rawCandidate = normalizeToken(peerId);
136+
if (rawCandidate) candidates.add(rawCandidate);
137+
const channel = normalizeToken(params.channel);
138+
if (channel) {
139+
const scopedCandidate = normalizeToken(`${channel}:${peerId}`);
140+
if (scopedCandidate) candidates.add(scopedCandidate);
141+
}
142+
if (candidates.size === 0) return null;
143+
for (const [canonical, ids] of Object.entries(identityLinks)) {
144+
const canonicalName = canonical.trim();
145+
if (!canonicalName) continue;
146+
if (!Array.isArray(ids)) continue;
147+
for (const id of ids) {
148+
const normalized = normalizeToken(id);
149+
if (normalized && candidates.has(normalized)) {
150+
return canonicalName;
151+
}
152+
}
153+
}
154+
return null;
155+
}
156+
115157
export function buildGroupHistoryKey(params: {
116158
channel: string;
117159
accountId?: string | null;

0 commit comments

Comments
 (0)