refactor: unify peer kind to ChatType, rename dm to direct (#11881)

* fix: use .js extension for ESM imports of RoutePeerKind

The imports incorrectly used .ts extension which doesn't resolve
with moduleResolution: NodeNext. Changed to .js and added 'type'
import modifier.

* fix tsconfig

* refactor: unify peer kind to ChatType, rename dm to direct

- Replace RoutePeerKind with ChatType throughout codebase
- Change 'dm' literal values to 'direct' in routing/session keys
- Keep backward compat: normalizeChatType accepts 'dm' -> 'direct'
- Add ChatType export to plugin-sdk, deprecate RoutePeerKind
- Update session key parsing to accept both 'dm' and 'direct' markers
- Update all channel monitors and extensions to use ChatType

BREAKING CHANGE: Session keys now use 'direct' instead of 'dm'.
Existing 'dm' keys still work via backward compat layer.

* fix tests

* test: update session key expectations for dmdirect migration

- Fix test expectations to expect :direct: in generated output
- Add explicit backward compat test for normalizeChatType('dm')
- Keep input test data with :dm: keys to verify backward compat

* fix: accept legacy 'dm' in session key parsing for backward compat

getDmHistoryLimitFromSessionKey now accepts both :dm: and :direct:
to ensure old session keys continue to work correctly.

* test: add explicit backward compat tests for dmdirect migration

- session-key.test.ts: verify both :dm: and :direct: keys are valid
- getDmHistoryLimitFromSessionKey: verify both formats work

* feat: backward compat for resetByType.dm config key

* test: skip unix-path Nix tests on Windows
This commit is contained in:
max
2026-02-08 16:20:52 -08:00
committed by GitHub
parent 0b07e15b63
commit 223eee0a20
64 changed files with 377 additions and 185 deletions
+3 -3
View File
@@ -490,14 +490,14 @@ Use `bindings` to route Feishu DMs or groups to different agents.
agentId: "main", agentId: "main",
match: { match: {
channel: "feishu", channel: "feishu",
peer: { kind: "dm", id: "ou_xxx" }, peer: { kind: "direct", id: "ou_xxx" },
}, },
}, },
{ {
agentId: "clawd-fan", agentId: "clawd-fan",
match: { match: {
channel: "feishu", channel: "feishu",
peer: { kind: "dm", id: "ou_yyy" }, peer: { kind: "direct", id: "ou_yyy" },
}, },
}, },
{ {
@@ -514,7 +514,7 @@ Use `bindings` to route Feishu DMs or groups to different agents.
Routing fields: Routing fields:
- `match.channel`: `"feishu"` - `match.channel`: `"feishu"`
- `match.peer.kind`: `"dm"` or `"group"` - `match.peer.kind`: `"direct"` or `"group"`
- `match.peer.id`: user Open ID (`ou_xxx`) or group ID (`oc_xxx`) - `match.peer.id`: user Open ID (`ou_xxx`) or group ID (`oc_xxx`)
See [Get group/user IDs](#get-groupuser-ids) for lookup tips. See [Get group/user IDs](#get-groupuser-ids) for lookup tips.
+1 -1
View File
@@ -196,7 +196,7 @@ Pairing is a DM gate for unknown senders:
- Codes expire after 1 hour; pending requests are capped at 3 per channel. - Codes expire after 1 hour; pending requests are capped at 3 per channel.
**Can multiple people use different OpenClaw instances on one WhatsApp number?** **Can multiple people use different OpenClaw instances on one WhatsApp number?**
Yes, by routing each sender to a different agent via `bindings` (peer `kind: "dm"`, sender E.164 like `+15551234567`). Replies still come from the **same WhatsApp account**, and direct chats collapse to each agents main session, so use **one agent per person**. DM access control (`dmPolicy`/`allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent). Yes, by routing each sender to a different agent via `bindings` (peer `kind: "direct"`, sender E.164 like `+15551234567`). Replies still come from the **same WhatsApp account**, and direct chats collapse to each agent's main session, so use **one agent per person**. DM access control (`dmPolicy`/`allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent).
**Why do you ask for my phone number in the wizard?** **Why do you ask for my phone number in the wizard?**
The wizard uses it to set your **allowlist/owner** so your own DMs are permitted. Its not used for auto-sending. If you run on your personal WhatsApp number, use that same number and enable `channels.whatsapp.selfChatMode`. The wizard uses it to set your **allowlist/owner** so your own DMs are permitted. Its not used for auto-sending. If you run on your personal WhatsApp number, use that same number and enable `channels.whatsapp.selfChatMode`.
+13 -4
View File
@@ -82,7 +82,7 @@ This lets **multiple people** share one Gateway server while keeping their AI
## One WhatsApp number, multiple people (DM split) ## One WhatsApp number, multiple people (DM split)
You can route **different WhatsApp DMs** to different agents while staying on **one WhatsApp account**. Match on sender E.164 (like `+15551234567`) with `peer.kind: "dm"`. Replies still come from the same WhatsApp number (no peragent sender identity). You can route **different WhatsApp DMs** to different agents while staying on **one WhatsApp account**. Match on sender E.164 (like `+15551234567`) with `peer.kind: "direct"`. Replies still come from the same WhatsApp number (no peragent sender identity).
Important detail: direct chats collapse to the agents **main session key**, so true isolation requires **one agent per person**. Important detail: direct chats collapse to the agents **main session key**, so true isolation requires **one agent per person**.
@@ -97,8 +97,14 @@ Example:
], ],
}, },
bindings: [ bindings: [
{ agentId: "alex", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551230001" } } }, {
{ agentId: "mia", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551230002" } } }, agentId: "alex",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551230001" } },
},
{
agentId: "mia",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551230002" } },
},
], ],
channels: { channels: {
whatsapp: { whatsapp: {
@@ -260,7 +266,10 @@ Keep WhatsApp on the fast agent, but route one DM to Opus:
], ],
}, },
bindings: [ bindings: [
{ agentId: "opus", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551234567" } } }, {
agentId: "opus",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551234567" } },
},
{ agentId: "chat", match: { channel: "whatsapp" } }, { agentId: "chat", match: { channel: "whatsapp" } },
], ],
} }
+2 -2
View File
@@ -106,7 +106,7 @@ the workspace is writable. See [Memory](/concepts/memory) and
- Daily reset: defaults to **4:00 AM local time on the gateway host**. A session is stale once its last update is earlier than the most recent daily reset time. - Daily reset: defaults to **4:00 AM local time on the gateway host**. A session is stale once its last update is earlier than the most recent daily reset time.
- Idle reset (optional): `idleMinutes` adds a sliding idle window. When both daily and idle resets are configured, **whichever expires first** forces a new session. - Idle reset (optional): `idleMinutes` adds a sliding idle window. When both daily and idle resets are configured, **whichever expires first** forces a new session.
- Legacy idle-only: if you set `session.idleMinutes` without any `session.reset`/`resetByType` config, OpenClaw stays in idle-only mode for backward compatibility. - Legacy idle-only: if you set `session.idleMinutes` without any `session.reset`/`resetByType` config, OpenClaw stays in idle-only mode for backward compatibility.
- Per-type overrides (optional): `resetByType` lets you override the policy for `dm`, `group`, and `thread` sessions (thread = Slack/Discord threads, Telegram topics, Matrix threads when provided by the connector). - Per-type overrides (optional): `resetByType` lets you override the policy for `direct`, `group`, and `thread` sessions (thread = Slack/Discord threads, Telegram topics, Matrix threads when provided by the connector).
- Per-channel overrides (optional): `resetByChannel` overrides the reset policy for a channel (applies to all session types for that channel and takes precedence over `reset`/`resetByType`). - Per-channel overrides (optional): `resetByChannel` overrides the reset policy for a channel (applies to all session types for that channel and takes precedence over `reset`/`resetByType`).
- Reset triggers: exact `/new` or `/reset` (plus any extras in `resetTriggers`) start a fresh session id and pass the remainder of the message through. `/new <model>` accepts a model alias, `provider/model`, or provider name (fuzzy match) to set the new session model. If `/new` or `/reset` is sent alone, OpenClaw runs a short “hello” greeting turn to confirm the reset. - Reset triggers: exact `/new` or `/reset` (plus any extras in `resetTriggers`) start a fresh session id and pass the remainder of the message through. `/new <model>` accepts a model alias, `provider/model`, or provider name (fuzzy match) to set the new session model. If `/new` or `/reset` is sent alone, OpenClaw runs a short “hello” greeting turn to confirm the reset.
- Manual reset: delete specific keys from the store or remove the JSONL transcript; the next message recreates them. - Manual reset: delete specific keys from the store or remove the JSONL transcript; the next message recreates them.
@@ -157,7 +157,7 @@ Runtime override (owner only):
}, },
resetByType: { resetByType: {
thread: { mode: "daily", atHour: 4 }, thread: { mode: "daily", atHour: 4 },
dm: { mode: "idle", idleMinutes: 240 }, direct: { mode: "idle", idleMinutes: 240 },
group: { mode: "idle", idleMinutes: 120 }, group: { mode: "idle", idleMinutes: 120 },
}, },
resetByChannel: { resetByChannel: {
+3 -3
View File
@@ -765,7 +765,7 @@ Inbound messages are routed to an agent via bindings.
- `bindings[]`: routes inbound messages to an `agentId`. - `bindings[]`: routes inbound messages to an `agentId`.
- `match.channel` (required) - `match.channel` (required)
- `match.accountId` (optional; `*` = any account; omitted = default account) - `match.accountId` (optional; `*` = any account; omitted = default account)
- `match.peer` (optional; `{ kind: dm|group|channel, id }`) - `match.peer` (optional; `{ kind: direct|group|channel, id }`)
- `match.guildId` / `match.teamId` (optional; channel-specific) - `match.guildId` / `match.teamId` (optional; channel-specific)
Deterministic match order: Deterministic match order:
@@ -2760,7 +2760,7 @@ Controls session scoping, reset policy, reset triggers, and where the session st
}, },
resetByType: { resetByType: {
thread: { mode: "daily", atHour: 4 }, thread: { mode: "daily", atHour: 4 },
dm: { mode: "idle", idleMinutes: 240 }, direct: { mode: "idle", idleMinutes: 240 },
group: { mode: "idle", idleMinutes: 120 }, group: { mode: "idle", idleMinutes: 120 },
}, },
resetTriggers: ["/new", "/reset"], resetTriggers: ["/new", "/reset"],
@@ -2797,7 +2797,7 @@ Fields:
- `mode`: `daily` or `idle` (default: `daily` when `reset` is present). - `mode`: `daily` or `idle` (default: `daily` when `reset` is present).
- `atHour`: local hour (0-23) for the daily reset boundary. - `atHour`: local hour (0-23) for the daily reset boundary.
- `idleMinutes`: sliding idle window in minutes. When daily + idle are both configured, whichever expires first wins. - `idleMinutes`: sliding idle window in minutes. When daily + idle are both configured, whichever expires first wins.
- `resetByType`: per-session overrides for `dm`, `group`, and `thread`. - `resetByType`: per-session overrides for `direct`, `group`, and `thread`. Legacy `dm` key is accepted as an alias for `direct`.
- If you only set legacy `session.idleMinutes` without any `reset`/`resetByType`, OpenClaw stays in idle-only mode for backward compatibility. - If you only set legacy `session.idleMinutes` without any `reset`/`resetByType`, OpenClaw stays in idle-only mode for backward compatibility.
- `heartbeatIdleMinutes`: optional idle override for heartbeat checks (daily reset still applies when enabled). - `heartbeatIdleMinutes`: optional idle override for heartbeat checks (daily reset still applies when enabled).
- `agentToAgent.maxPingPongTurns`: max reply-back turns between requester/target (05, default 5). - `agentToAgent.maxPingPongTurns`: max reply-back turns between requester/target (05, default 5).
+1 -1
View File
@@ -803,7 +803,7 @@ See [/channels/telegram](/channels/telegram#access-control-dms--groups).
### Can multiple people use one WhatsApp number with different OpenClaw instances ### Can multiple people use one WhatsApp number with different OpenClaw instances
Yes, via **multi-agent routing**. Bind each sender's WhatsApp **DM** (peer `kind: "dm"`, sender E.164 like `+15551234567`) to a different `agentId`, so each person gets their own workspace and session store. Replies still come from the **same WhatsApp account**, and DM access control (`channels.whatsapp.dmPolicy` / `channels.whatsapp.allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent) and [WhatsApp](/channels/whatsapp). Yes, via **multi-agent routing**. Bind each sender's WhatsApp **DM** (peer `kind: "direct"`, sender E.164 like `+15551234567`) to a different `agentId`, so each person gets their own workspace and session store. Replies still come from the **same WhatsApp account**, and DM access control (`channels.whatsapp.dmPolicy` / `channels.whatsapp.allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent) and [WhatsApp](/channels/whatsapp).
### Can I run a fast chat agent and an Opus for coding agent ### Can I run a fast chat agent and an Opus for coding agent
+1 -1
View File
@@ -72,7 +72,7 @@ export type PluginRuntime = {
cfg: unknown; cfg: unknown;
channel: string; channel: string;
accountId: string; accountId: string;
peer: { kind: "dm" | "group" | "channel"; id: string }; peer: { kind: RoutePeerKind; id: string };
}): { sessionKey: string; accountId: string }; }): { sessionKey: string; accountId: string };
}; };
pairing: { pairing: {
+1 -1
View File
@@ -79,7 +79,7 @@ export type PluginRuntime = {
cfg: unknown; cfg: unknown;
channel: string; channel: string;
accountId: string; accountId: string;
peer: { kind: "dm" | "group" | "channel"; id: string }; peer: { kind: RoutePeerKind; id: string };
}): { sessionKey: string; accountId: string }; }): { sessionKey: string; accountId: string };
}; };
pairing: { pairing: {
+2 -2
View File
@@ -1804,7 +1804,7 @@ async function processMessage(
channel: "bluebubbles", channel: "bluebubbles",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
}); });
@@ -2442,7 +2442,7 @@ async function processReaction(
channel: "bluebubbles", channel: "bluebubbles",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: reaction.isGroup ? "group" : "dm", kind: reaction.isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
}); });
+1 -1
View File
@@ -652,7 +652,7 @@ export async function handleFeishuMessage(params: {
channel: "feishu", channel: "feishu",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? ctx.chatId : ctx.senderOpenId, id: isGroup ? ctx.chatId : ctx.senderOpenId,
}, },
}); });
+1 -1
View File
@@ -615,7 +615,7 @@ async function processMessageWithPipeline(params: {
channel: "googlechat", channel: "googlechat",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: spaceId, id: spaceId,
}, },
}); });
@@ -453,7 +453,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
cfg, cfg,
channel: "matrix", channel: "matrix",
peer: { peer: {
kind: isDirectMessage ? "dm" : "channel", kind: isDirectMessage ? "direct" : "channel",
id: isDirectMessage ? senderId : roomId, id: isDirectMessage ? senderId : roomId,
}, },
}); });
+21 -20
View File
@@ -1,5 +1,6 @@
import type { import type {
ChannelAccountSnapshot, ChannelAccountSnapshot,
ChatType,
OpenClawConfig, OpenClawConfig,
ReplyPayload, ReplyPayload,
RuntimeEnv, RuntimeEnv,
@@ -131,13 +132,13 @@ function isSystemPost(post: MattermostPost): boolean {
return Boolean(type); return Boolean(type);
} }
function channelKind(channelType?: string | null): "dm" | "group" | "channel" { function channelKind(channelType?: string | null): ChatType {
if (!channelType) { if (!channelType) {
return "channel"; return "channel";
} }
const normalized = channelType.trim().toUpperCase(); const normalized = channelType.trim().toUpperCase();
if (normalized === "D") { if (normalized === "D") {
return "dm"; return "direct";
} }
if (normalized === "G") { if (normalized === "G") {
return "group"; return "group";
@@ -145,8 +146,8 @@ function channelKind(channelType?: string | null): "dm" | "group" | "channel" {
return "channel"; return "channel";
} }
function channelChatType(kind: "dm" | "group" | "channel"): "direct" | "group" | "channel" { function channelChatType(kind: ChatType): "direct" | "group" | "channel" {
if (kind === "dm") { if (kind === "direct") {
return "direct"; return "direct";
} }
if (kind === "group") { if (kind === "group") {
@@ -469,11 +470,11 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
hasControlCommand, hasControlCommand,
}); });
const commandAuthorized = const commandAuthorized =
kind === "dm" kind === "direct"
? dmPolicy === "open" || senderAllowedForCommands ? dmPolicy === "open" || senderAllowedForCommands
: commandGate.commandAuthorized; : commandGate.commandAuthorized;
if (kind === "dm") { if (kind === "direct") {
if (dmPolicy === "disabled") { if (dmPolicy === "disabled") {
logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`); logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
return; return;
@@ -524,7 +525,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
} }
} }
if (kind !== "dm" && commandGate.shouldBlock) { if (kind !== "direct" && commandGate.shouldBlock) {
logInboundDrop({ logInboundDrop({
log: logVerboseMessage, log: logVerboseMessage,
channel: "mattermost", channel: "mattermost",
@@ -547,7 +548,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
teamId, teamId,
peer: { peer: {
kind, kind,
id: kind === "dm" ? senderId : channelId, id: kind === "direct" ? senderId : channelId,
}, },
}); });
@@ -559,11 +560,11 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
parentSessionKey: threadRootId ? baseSessionKey : undefined, parentSessionKey: threadRootId ? baseSessionKey : undefined,
}); });
const sessionKey = threadKeys.sessionKey; const sessionKey = threadKeys.sessionKey;
const historyKey = kind === "dm" ? null : sessionKey; const historyKey = kind === "direct" ? null : sessionKey;
const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId); const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
const wasMentioned = const wasMentioned =
kind !== "dm" && kind !== "direct" &&
((botUsername ? rawText.toLowerCase().includes(`@${botUsername.toLowerCase()}`) : false) || ((botUsername ? rawText.toLowerCase().includes(`@${botUsername.toLowerCase()}`) : false) ||
core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes)); core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
const pendingBody = const pendingBody =
@@ -590,7 +591,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
}); });
}; };
const oncharEnabled = account.chatmode === "onchar" && kind !== "dm"; const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : []; const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
const oncharResult = oncharEnabled const oncharResult = oncharEnabled
? stripOncharPrefix(rawText, oncharPrefixes) ? stripOncharPrefix(rawText, oncharPrefixes)
@@ -598,7 +599,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
const oncharTriggered = oncharResult.triggered; const oncharTriggered = oncharResult.triggered;
const shouldRequireMention = const shouldRequireMention =
kind !== "dm" && kind !== "direct" &&
core.channel.groups.resolveRequireMention({ core.channel.groups.resolveRequireMention({
cfg, cfg,
channel: "mattermost", channel: "mattermost",
@@ -615,7 +616,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
return; return;
} }
if (kind !== "dm" && shouldRequireMention && canDetectMention) { if (kind !== "direct" && shouldRequireMention && canDetectMention) {
if (!effectiveWasMentioned) { if (!effectiveWasMentioned) {
recordPendingHistory(); recordPendingHistory();
return; return;
@@ -637,7 +638,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
}); });
const fromLabel = formatInboundFromLabel({ const fromLabel = formatInboundFromLabel({
isGroup: kind !== "dm", isGroup: kind !== "direct",
groupLabel: channelDisplay || roomLabel, groupLabel: channelDisplay || roomLabel,
groupId: channelId, groupId: channelId,
groupFallback: roomLabel || "Channel", groupFallback: roomLabel || "Channel",
@@ -647,7 +648,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
const preview = bodyText.replace(/\s+/g, " ").slice(0, 160); const preview = bodyText.replace(/\s+/g, " ").slice(0, 160);
const inboundLabel = const inboundLabel =
kind === "dm" kind === "direct"
? `Mattermost DM from ${senderName}` ? `Mattermost DM from ${senderName}`
: `Mattermost message in ${roomLabel} from ${senderName}`; : `Mattermost message in ${roomLabel} from ${senderName}`;
core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, { core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
@@ -685,14 +686,14 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
}); });
} }
const to = kind === "dm" ? `user:${senderId}` : `channel:${channelId}`; const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
const mediaPayload = buildMattermostMediaPayload(mediaList); const mediaPayload = buildMattermostMediaPayload(mediaList);
const ctxPayload = core.channel.reply.finalizeInboundContext({ const ctxPayload = core.channel.reply.finalizeInboundContext({
Body: combinedBody, Body: combinedBody,
RawBody: bodyText, RawBody: bodyText,
CommandBody: bodyText, CommandBody: bodyText,
From: From:
kind === "dm" kind === "direct"
? `mattermost:${senderId}` ? `mattermost:${senderId}`
: kind === "group" : kind === "group"
? `mattermost:group:${channelId}` ? `mattermost:group:${channelId}`
@@ -703,7 +704,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
AccountId: route.accountId, AccountId: route.accountId,
ChatType: chatType, ChatType: chatType,
ConversationLabel: fromLabel, ConversationLabel: fromLabel,
GroupSubject: kind !== "dm" ? channelDisplay || roomLabel : undefined, GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : undefined,
GroupChannel: channelName ? `#${channelName}` : undefined, GroupChannel: channelName ? `#${channelName}` : undefined,
GroupSpace: teamId, GroupSpace: teamId,
SenderName: senderName, SenderName: senderName,
@@ -718,14 +719,14 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
ReplyToId: threadRootId, ReplyToId: threadRootId,
MessageThreadId: threadRootId, MessageThreadId: threadRootId,
Timestamp: typeof post.create_at === "number" ? post.create_at : undefined, Timestamp: typeof post.create_at === "number" ? post.create_at : undefined,
WasMentioned: kind !== "dm" ? effectiveWasMentioned : undefined, WasMentioned: kind !== "direct" ? effectiveWasMentioned : undefined,
CommandAuthorized: commandAuthorized, CommandAuthorized: commandAuthorized,
OriginatingChannel: "mattermost" as const, OriginatingChannel: "mattermost" as const,
OriginatingTo: to, OriginatingTo: to,
...mediaPayload, ...mediaPayload,
}); });
if (kind === "dm") { if (kind === "direct") {
const sessionCfg = cfg.session; const sessionCfg = cfg.session;
const storePath = core.channel.session.resolveStorePath(sessionCfg?.store, { const storePath = core.channel.session.resolveStorePath(sessionCfg?.store, {
agentId: route.agentId, agentId: route.agentId,
@@ -342,7 +342,7 @@ export function createMSTeamsMessageHandler(deps: MSTeamsMessageHandlerDeps) {
cfg, cfg,
channel: "msteams", channel: "msteams",
peer: { peer: {
kind: isDirectMessage ? "dm" : isChannel ? "channel" : "group", kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
id: isDirectMessage ? senderId : conversationId, id: isDirectMessage ? senderId : conversationId,
}, },
}); });
+1 -1
View File
@@ -228,7 +228,7 @@ export async function handleNextcloudTalkInbound(params: {
channel: CHANNEL_ID, channel: CHANNEL_ID,
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? roomToken : senderId, id: isGroup ? roomToken : senderId,
}, },
}); });
+3 -3
View File
@@ -101,7 +101,7 @@ const tlonOutbound: ChannelOutboundAdapter = {
error: new Error(`Invalid Tlon target. Use ${formatTargetHint()}`), error: new Error(`Invalid Tlon target. Use ${formatTargetHint()}`),
}; };
} }
if (parsed.kind === "dm") { if (parsed.kind === "direct") {
return { ok: true, to: parsed.ship }; return { ok: true, to: parsed.ship };
} }
return { ok: true, to: parsed.nest }; return { ok: true, to: parsed.nest };
@@ -127,7 +127,7 @@ const tlonOutbound: ChannelOutboundAdapter = {
try { try {
const fromShip = normalizeShip(account.ship); const fromShip = normalizeShip(account.ship);
if (parsed.kind === "dm") { if (parsed.kind === "direct") {
return await sendDm({ return await sendDm({
api, api,
fromShip, fromShip,
@@ -298,7 +298,7 @@ export const tlonPlugin: ChannelPlugin = {
if (!parsed) { if (!parsed) {
return target.trim(); return target.trim();
} }
if (parsed.kind === "dm") { if (parsed.kind === "direct") {
return parsed.ship; return parsed.ship;
} }
return parsed.nest; return parsed.nest;
+1 -1
View File
@@ -343,7 +343,7 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
channel: "tlon", channel: "tlon",
accountId: opts.accountId ?? undefined, accountId: opts.accountId ?? undefined,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? (groupChannel ?? senderShip) : senderShip, id: isGroup ? (groupChannel ?? senderShip) : senderShip,
}, },
}); });
+3 -3
View File
@@ -1,5 +1,5 @@
export type TlonTarget = export type TlonTarget =
| { kind: "dm"; ship: string } | { kind: "direct"; ship: string }
| { kind: "group"; nest: string; hostShip: string; channelName: string }; | { kind: "group"; nest: string; hostShip: string; channelName: string };
const SHIP_RE = /^~?[a-z-]+$/i; const SHIP_RE = /^~?[a-z-]+$/i;
@@ -32,7 +32,7 @@ export function parseTlonTarget(raw?: string | null): TlonTarget | null {
const dmPrefix = withoutPrefix.match(/^dm[/:](.+)$/i); const dmPrefix = withoutPrefix.match(/^dm[/:](.+)$/i);
if (dmPrefix) { if (dmPrefix) {
return { kind: "dm", ship: normalizeShip(dmPrefix[1]) }; return { kind: "direct", ship: normalizeShip(dmPrefix[1]) };
} }
const groupPrefix = withoutPrefix.match(/^(group|room)[/:](.+)$/i); const groupPrefix = withoutPrefix.match(/^(group|room)[/:](.+)$/i);
@@ -78,7 +78,7 @@ export function parseTlonTarget(raw?: string | null): TlonTarget | null {
} }
if (SHIP_RE.test(withoutPrefix)) { if (SHIP_RE.test(withoutPrefix)) {
return { kind: "dm", ship: normalizeShip(withoutPrefix) }; return { kind: "direct", ship: normalizeShip(withoutPrefix) };
} }
return null; return null;
+1 -1
View File
@@ -515,7 +515,7 @@ async function processMessageWithPipeline(params: {
channel: "zalo", channel: "zalo",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: chatId, id: chatId,
}, },
}); });
@@ -228,4 +228,18 @@ describe("getDmHistoryLimitFromSessionKey", () => {
} as OpenClawConfig; } as OpenClawConfig;
expect(getDmHistoryLimitFromSessionKey("telegram:dm:123", config)).toBe(5); expect(getDmHistoryLimitFromSessionKey("telegram:dm:123", config)).toBe(5);
}); });
describe("backward compatibility", () => {
it("accepts both legacy :dm: and new :direct: session keys", () => {
const config = {
channels: { telegram: { dmHistoryLimit: 10 } },
} as OpenClawConfig;
// Legacy format with :dm:
expect(getDmHistoryLimitFromSessionKey("telegram:dm:123", config)).toBe(10);
expect(getDmHistoryLimitFromSessionKey("agent:main:telegram:dm:123", config)).toBe(10);
// New format with :direct:
expect(getDmHistoryLimitFromSessionKey("telegram:direct:123", config)).toBe(10);
expect(getDmHistoryLimitFromSessionKey("agent:main:telegram:direct:123", config)).toBe(10);
});
});
}); });
+2 -1
View File
@@ -58,7 +58,8 @@ export function getDmHistoryLimitFromSessionKey(
const kind = providerParts[1]?.toLowerCase(); const kind = providerParts[1]?.toLowerCase();
const userIdRaw = providerParts.slice(2).join(":"); const userIdRaw = providerParts.slice(2).join(":");
const userId = stripThreadSuffix(userIdRaw); const userId = stripThreadSuffix(userIdRaw);
if (kind !== "dm") { // Accept both "direct" (new) and "dm" (legacy) for backward compat
if (kind !== "direct" && kind !== "dm") {
return undefined; return undefined;
} }
+5 -4
View File
@@ -190,15 +190,16 @@ function inferDeliveryFromSessionKey(agentSessionKey?: string): CronDelivery | n
} }
// buildAgentPeerSessionKey encodes peers as: // buildAgentPeerSessionKey encodes peers as:
// - dm:<peerId> // - direct:<peerId>
// - <channel>:dm:<peerId> // - <channel>:direct:<peerId>
// - <channel>:<accountId>:dm:<peerId> // - <channel>:<accountId>:direct:<peerId>
// - <channel>:group:<peerId> // - <channel>:group:<peerId>
// - <channel>:channel:<peerId> // - <channel>:channel:<peerId>
// Note: legacy keys may use "dm" instead of "direct".
// Threaded sessions append :thread:<id>, which we strip so delivery targets the parent peer. // Threaded sessions append :thread:<id>, which we strip so delivery targets the parent peer.
// NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved. // NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved.
const markerIndex = parts.findIndex( const markerIndex = parts.findIndex(
(part) => part === "dm" || part === "group" || part === "channel", (part) => part === "direct" || part === "dm" || part === "group" || part === "channel",
); );
if (markerIndex === -1) { if (markerIndex === -1) {
return null; return null;
+1 -1
View File
@@ -454,7 +454,7 @@ describe("initSessionState channel reset overrides", () => {
session: { session: {
store: storePath, store: storePath,
idleMinutes: 60, idleMinutes: 60,
resetByType: { dm: { mode: "idle", idleMinutes: 10 } }, resetByType: { direct: { mode: "idle", idleMinutes: 10 } },
resetByChannel: { discord: { mode: "idle", idleMinutes: 10080 } }, resetByChannel: { discord: { mode: "idle", idleMinutes: 10080 } },
}, },
} as OpenClawConfig; } as OpenClawConfig;
+9
View File
@@ -15,4 +15,13 @@ describe("normalizeChatType", () => {
expect(normalizeChatType("nope")).toBeUndefined(); expect(normalizeChatType("nope")).toBeUndefined();
expect(normalizeChatType("room")).toBeUndefined(); expect(normalizeChatType("room")).toBeUndefined();
}); });
describe("backward compatibility", () => {
it("accepts legacy 'dm' value and normalizes to 'direct'", () => {
// Legacy config/input may use "dm" - ensure smooth upgrade path
expect(normalizeChatType("dm")).toBe("direct");
expect(normalizeChatType("DM")).toBe("direct");
expect(normalizeChatType(" dm ")).toBe("direct");
});
});
}); });
+2 -2
View File
@@ -1,6 +1,6 @@
export type NormalizedChatType = "direct" | "group" | "channel"; export type ChatType = "direct" | "group" | "channel";
export function normalizeChatType(raw?: string): NormalizedChatType | undefined { export function normalizeChatType(raw?: string): ChatType | undefined {
const value = raw?.trim().toLowerCase(); const value = raw?.trim().toLowerCase();
if (!value) { if (!value) {
return undefined; return undefined;
+2 -2
View File
@@ -4,7 +4,7 @@ import type { MsgContext } from "../../auto-reply/templating.js";
import type { OpenClawConfig } from "../../config/config.js"; import type { OpenClawConfig } from "../../config/config.js";
import type { PollInput } from "../../polls.js"; import type { PollInput } from "../../polls.js";
import type { GatewayClientMode, GatewayClientName } from "../../utils/message-channel.js"; import type { GatewayClientMode, GatewayClientName } from "../../utils/message-channel.js";
import type { NormalizedChatType } from "../chat-type.js"; import type { ChatType } from "../chat-type.js";
import type { ChatChannelId } from "../registry.js"; import type { ChatChannelId } from "../registry.js";
import type { ChannelMessageActionName as ChannelMessageActionNameFromList } from "./message-action-names.js"; import type { ChannelMessageActionName as ChannelMessageActionNameFromList } from "./message-action-names.js";
@@ -162,7 +162,7 @@ export type ChannelGroupContext = {
}; };
export type ChannelCapabilities = { export type ChannelCapabilities = {
chatTypes: Array<NormalizedChatType | "thread">; chatTypes: Array<ChatType | "thread">;
polls?: boolean; polls?: boolean;
reactions?: boolean; reactions?: boolean;
edit?: boolean; edit?: boolean;
@@ -49,29 +49,37 @@ describe("Nix integration (U3, U5, U9)", () => {
}); });
}); });
it("STATE_DIR respects OPENCLAW_HOME when state override is unset", async () => { // Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
await withEnvOverride( it.skipIf(process.platform === "win32")(
{ OPENCLAW_HOME: "/custom/home", OPENCLAW_STATE_DIR: undefined }, "STATE_DIR respects OPENCLAW_HOME when state override is unset",
async () => { async () => {
const { STATE_DIR } = await import("./config.js"); await withEnvOverride(
expect(STATE_DIR).toBe(path.resolve("/custom/home/.openclaw")); { OPENCLAW_HOME: "/custom/home", OPENCLAW_STATE_DIR: undefined },
}, async () => {
); const { STATE_DIR } = await import("./config.js");
}); expect(STATE_DIR).toBe(path.resolve("/custom/home/.openclaw"));
},
);
},
);
it("CONFIG_PATH defaults to OPENCLAW_HOME/.openclaw/openclaw.json", async () => { // Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
await withEnvOverride( it.skipIf(process.platform === "win32")(
{ "CONFIG_PATH defaults to OPENCLAW_HOME/.openclaw/openclaw.json",
OPENCLAW_HOME: "/custom/home", async () => {
OPENCLAW_CONFIG_PATH: undefined, await withEnvOverride(
OPENCLAW_STATE_DIR: undefined, {
}, OPENCLAW_HOME: "/custom/home",
async () => { OPENCLAW_CONFIG_PATH: undefined,
const { CONFIG_PATH } = await import("./config.js"); OPENCLAW_STATE_DIR: undefined,
expect(CONFIG_PATH).toBe(path.resolve("/custom/home/.openclaw/openclaw.json")); },
}, async () => {
); const { CONFIG_PATH } = await import("./config.js");
}); expect(CONFIG_PATH).toBe(path.resolve("/custom/home/.openclaw/openclaw.json"));
},
);
},
);
it("CONFIG_PATH defaults to ~/.openclaw/openclaw.json when env not set", async () => { it("CONFIG_PATH defaults to ~/.openclaw/openclaw.json when env not set", async () => {
await withEnvOverride( await withEnvOverride(
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import type { SessionConfig } from "../types.base.js";
import { resolveSessionResetPolicy } from "./reset.js";
describe("resolveSessionResetPolicy", () => {
describe("backward compatibility: resetByType.dm → direct", () => {
it("uses resetByType.direct when available", () => {
const sessionCfg = {
resetByType: {
direct: { mode: "idle" as const, idleMinutes: 30 },
},
} satisfies SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("idle");
expect(policy.idleMinutes).toBe(30);
});
it("falls back to resetByType.dm (legacy) when direct is missing", () => {
// Simulating legacy config with "dm" key instead of "direct"
const sessionCfg = {
resetByType: {
dm: { mode: "idle" as const, idleMinutes: 45 },
},
} as unknown as SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("idle");
expect(policy.idleMinutes).toBe(45);
});
it("prefers resetByType.direct over resetByType.dm when both present", () => {
const sessionCfg = {
resetByType: {
direct: { mode: "daily" as const },
dm: { mode: "idle" as const, idleMinutes: 99 },
},
} as unknown as SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("daily");
});
it("does not use dm fallback for group/thread types", () => {
const sessionCfg = {
resetByType: {
dm: { mode: "idle" as const, idleMinutes: 45 },
},
} as unknown as SessionConfig;
const groupPolicy = resolveSessionResetPolicy({
sessionCfg,
resetType: "group",
});
// Should use default mode since group has no config and dm doesn't apply
expect(groupPolicy.mode).toBe("daily");
});
});
});
+9 -3
View File
@@ -3,7 +3,7 @@ import { normalizeMessageChannel } from "../../utils/message-channel.js";
import { DEFAULT_IDLE_MINUTES } from "./types.js"; import { DEFAULT_IDLE_MINUTES } from "./types.js";
export type SessionResetMode = "daily" | "idle"; export type SessionResetMode = "daily" | "idle";
export type SessionResetType = "dm" | "group" | "thread"; export type SessionResetType = "direct" | "group" | "thread";
export type SessionResetPolicy = { export type SessionResetPolicy = {
mode: SessionResetMode; mode: SessionResetMode;
@@ -46,7 +46,7 @@ export function resolveSessionResetType(params: {
if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) { if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) {
return "group"; return "group";
} }
return "dm"; return "direct";
} }
export function resolveThreadFlag(params: { export function resolveThreadFlag(params: {
@@ -88,7 +88,13 @@ export function resolveSessionResetPolicy(params: {
}): SessionResetPolicy { }): SessionResetPolicy {
const sessionCfg = params.sessionCfg; const sessionCfg = params.sessionCfg;
const baseReset = params.resetOverride ?? sessionCfg?.reset; const baseReset = params.resetOverride ?? sessionCfg?.reset;
const typeReset = params.resetOverride ? undefined : sessionCfg?.resetByType?.[params.resetType]; // Backward compat: accept legacy "dm" key as alias for "direct"
const typeReset = params.resetOverride
? undefined
: (sessionCfg?.resetByType?.[params.resetType] ??
(params.resetType === "direct"
? (sessionCfg?.resetByType as { dm?: SessionResetConfig } | undefined)?.dm
: undefined));
const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType); const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType);
const legacyIdleMinutes = params.resetOverride ? undefined : sessionCfg?.idleMinutes; const legacyIdleMinutes = params.resetOverride ? undefined : sessionCfg?.idleMinutes;
const mode = const mode =
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Skill } from "@mariozechner/pi-coding-agent"; import type { Skill } from "@mariozechner/pi-coding-agent";
import crypto from "node:crypto"; import crypto from "node:crypto";
import type { NormalizedChatType } from "../../channels/chat-type.js"; import type { ChatType } from "../../channels/chat-type.js";
import type { ChannelId } from "../../channels/plugins/types.js"; import type { ChannelId } from "../../channels/plugins/types.js";
import type { DeliveryContext } from "../../utils/delivery-context.js"; import type { DeliveryContext } from "../../utils/delivery-context.js";
import type { TtsAutoMode } from "../types.tts.js"; import type { TtsAutoMode } from "../types.tts.js";
@@ -9,7 +9,7 @@ export type SessionScope = "per-sender" | "global";
export type SessionChannelId = ChannelId | "webchat"; export type SessionChannelId = ChannelId | "webchat";
export type SessionChatType = NormalizedChatType; export type SessionChatType = ChatType;
export type SessionOrigin = { export type SessionOrigin = {
label?: string; label?: string;
+2 -1
View File
@@ -1,3 +1,4 @@
import type { ChatType } from "../channels/chat-type.js";
import type { AgentDefaultsConfig } from "./types.agent-defaults.js"; import type { AgentDefaultsConfig } from "./types.agent-defaults.js";
import type { HumanDelayConfig, IdentityConfig } from "./types.base.js"; import type { HumanDelayConfig, IdentityConfig } from "./types.base.js";
import type { GroupChatConfig } from "./types.messages.js"; import type { GroupChatConfig } from "./types.messages.js";
@@ -74,7 +75,7 @@ export type AgentBinding = {
match: { match: {
channel: string; channel: string;
accountId?: string; accountId?: string;
peer?: { kind: "dm" | "group" | "channel"; id: string }; peer?: { kind: ChatType; id: string };
guildId?: string; guildId?: string;
teamId?: string; teamId?: string;
}; };
+4 -2
View File
@@ -1,4 +1,4 @@
import type { NormalizedChatType } from "../channels/chat-type.js"; import type { ChatType } from "../channels/chat-type.js";
export type ReplyMode = "text" | "command"; export type ReplyMode = "text" | "command";
export type TypingMode = "never" | "instant" | "thinking" | "message"; export type TypingMode = "never" | "instant" | "thinking" | "message";
@@ -50,7 +50,7 @@ export type HumanDelayConfig = {
export type SessionSendPolicyAction = "allow" | "deny"; export type SessionSendPolicyAction = "allow" | "deny";
export type SessionSendPolicyMatch = { export type SessionSendPolicyMatch = {
channel?: string; channel?: string;
chatType?: NormalizedChatType; chatType?: ChatType;
keyPrefix?: string; keyPrefix?: string;
}; };
export type SessionSendPolicyRule = { export type SessionSendPolicyRule = {
@@ -71,6 +71,8 @@ export type SessionResetConfig = {
idleMinutes?: number; idleMinutes?: number;
}; };
export type SessionResetByTypeConfig = { export type SessionResetByTypeConfig = {
direct?: SessionResetConfig;
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm?: SessionResetConfig; dm?: SessionResetConfig;
group?: SessionResetConfig; group?: SessionResetConfig;
thread?: SessionResetConfig; thread?: SessionResetConfig;
+2 -2
View File
@@ -1,9 +1,9 @@
import type { NormalizedChatType } from "../channels/chat-type.js"; import type { ChatType } from "../channels/chat-type.js";
import type { AgentElevatedAllowFromConfig, SessionSendPolicyAction } from "./types.base.js"; import type { AgentElevatedAllowFromConfig, SessionSendPolicyAction } from "./types.base.js";
export type MediaUnderstandingScopeMatch = { export type MediaUnderstandingScopeMatch = {
channel?: string; channel?: string;
chatType?: NormalizedChatType; chatType?: ChatType;
keyPrefix?: string; keyPrefix?: string;
}; };
+7 -1
View File
@@ -22,7 +22,13 @@ export const BindingsSchema = z
accountId: z.string().optional(), accountId: z.string().optional(),
peer: z peer: z
.object({ .object({
kind: z.union([z.literal("dm"), z.literal("group"), z.literal("channel")]), kind: z.union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
]),
id: z.string(), id: z.string(),
}) })
.strict() .strict()
+7 -1
View File
@@ -378,7 +378,13 @@ export const MediaUnderstandingScopeSchema = z
.object({ .object({
channel: z.string().optional(), channel: z.string().optional(),
chatType: z chatType: z
.union([z.literal("direct"), z.literal("group"), z.literal("channel")]) .union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
])
.optional(), .optional(),
keyPrefix: z.string().optional(), keyPrefix: z.string().optional(),
}) })
+9 -1
View File
@@ -27,7 +27,13 @@ export const SessionSendPolicySchema = z
.object({ .object({
channel: z.string().optional(), channel: z.string().optional(),
chatType: z chatType: z
.union([z.literal("direct"), z.literal("group"), z.literal("channel")]) .union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
])
.optional(), .optional(),
keyPrefix: z.string().optional(), keyPrefix: z.string().optional(),
}) })
@@ -57,6 +63,8 @@ export const SessionSchema = z
reset: SessionResetConfigSchema.optional(), reset: SessionResetConfigSchema.optional(),
resetByType: z resetByType: z
.object({ .object({
direct: SessionResetConfigSchema.optional(),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm: SessionResetConfigSchema.optional(), dm: SessionResetConfigSchema.optional(),
group: SessionResetConfigSchema.optional(), group: SessionResetConfigSchema.optional(),
thread: SessionResetConfigSchema.optional(), thread: SessionResetConfigSchema.optional(),
@@ -87,12 +87,12 @@ describe("discord processDiscordMessage inbound contract", () => {
guildInfo: null, guildInfo: null,
guildSlug: "", guildSlug: "",
channelConfig: null, channelConfig: null,
baseSessionKey: "agent:main:discord:dm:u1", baseSessionKey: "agent:main:discord:direct:u1",
route: { route: {
agentId: "main", agentId: "main",
channel: "discord", channel: "discord",
accountId: "default", accountId: "default",
sessionKey: "agent:main:discord:dm:u1", sessionKey: "agent:main:discord:direct:u1",
mainSessionKey: "agent:main:main", mainSessionKey: "agent:main:main",
// oxlint-disable-next-line typescript/no-explicit-any // oxlint-disable-next-line typescript/no-explicit-any
} as any, } as any,
@@ -224,7 +224,7 @@ export async function preflightDiscordMessage(
accountId: params.accountId, accountId: params.accountId,
guildId: params.data.guild_id ?? undefined, guildId: params.data.guild_id ?? undefined,
peer: { peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel", kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? author.id : message.channelId, id: isDirectMessage ? author.id : message.channelId,
}, },
// Pass parent peer for thread binding inheritance // Pass parent peer for thread binding inheritance
+1 -1
View File
@@ -736,7 +736,7 @@ async function dispatchDiscordCommandInteraction(params: {
accountId, accountId,
guildId: interaction.guild?.id ?? undefined, guildId: interaction.guild?.id ?? undefined,
peer: { peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel", kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? user.id : channelId, id: isDirectMessage ? user.id : channelId,
}, },
parentPeer: threadParentId ? { kind: "channel", id: threadParentId } : undefined, parentPeer: threadParentId ? { kind: "channel", id: threadParentId } : undefined,
+2 -2
View File
@@ -1,4 +1,4 @@
import type { NormalizedChatType } from "../channels/chat-type.js"; import type { ChatType } from "../channels/chat-type.js";
import type { SessionEntry } from "../config/sessions.js"; import type { SessionEntry } from "../config/sessions.js";
import type { DeliveryContext } from "../utils/delivery-context.js"; import type { DeliveryContext } from "../utils/delivery-context.js";
@@ -19,7 +19,7 @@ export type GatewaySessionRow = {
subject?: string; subject?: string;
groupChannel?: string; groupChannel?: string;
space?: string; space?: string;
chatType?: NormalizedChatType; chatType?: ChatType;
origin?: SessionEntry["origin"]; origin?: SessionEntry["origin"];
updatedAt: number | null; updatedAt: number | null;
sessionId?: string; sessionId?: string;
+1 -1
View File
@@ -387,7 +387,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
channel: "imessage", channel: "imessage",
accountId: accountInfo.accountId, accountId: accountInfo.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? String(chatId ?? "unknown") : normalizeIMessageHandle(sender), id: isGroup ? String(chatId ?? "unknown") : normalizeIMessageHandle(sender),
}, },
}); });
+3 -3
View File
@@ -43,7 +43,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "@alice", target: "@alice",
}); });
expect(route?.sessionKey).toBe("agent:main:telegram:dm:@alice"); expect(route?.sessionKey).toBe("agent:main:telegram:direct:@alice");
expect(route?.chatType).toBe("direct"); expect(route?.chatType).toBe("direct");
}); });
@@ -64,7 +64,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "user:123", target: "user:123",
}); });
expect(route?.sessionKey).toBe("agent:main:dm:alice"); expect(route?.sessionKey).toBe("agent:main:direct:alice");
}); });
it("strips chat_* prefixes for BlueBubbles group session keys", async () => { it("strips chat_* prefixes for BlueBubbles group session keys", async () => {
@@ -88,7 +88,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "123456", target: "123456",
}); });
expect(route?.sessionKey).toBe("agent:main:zalouser:dm:123456"); expect(route?.sessionKey).toBe("agent:main:zalouser:direct:123456");
expect(route?.chatType).toBe("direct"); expect(route?.chatType).toBe("direct");
}); });
+29 -30
View File
@@ -1,4 +1,5 @@
import type { MsgContext } from "../../auto-reply/templating.js"; import type { MsgContext } from "../../auto-reply/templating.js";
import type { ChatType } from "../../channels/chat-type.js";
import type { ChannelId } from "../../channels/plugins/types.js"; import type { ChannelId } from "../../channels/plugins/types.js";
import type { OpenClawConfig } from "../../config/config.js"; import type { OpenClawConfig } from "../../config/config.js";
import type { ResolvedMessagingTarget } from "./target-resolver.js"; import type { ResolvedMessagingTarget } from "./target-resolver.js";
@@ -6,11 +7,7 @@ import { getChannelPlugin } from "../../channels/plugins/index.js";
import { recordSessionMetaFromInbound, resolveStorePath } from "../../config/sessions.js"; import { recordSessionMetaFromInbound, resolveStorePath } from "../../config/sessions.js";
import { parseDiscordTarget } from "../../discord/targets.js"; import { parseDiscordTarget } from "../../discord/targets.js";
import { parseIMessageTarget, normalizeIMessageHandle } from "../../imessage/targets.js"; import { parseIMessageTarget, normalizeIMessageHandle } from "../../imessage/targets.js";
import { import { buildAgentSessionKey, type RoutePeer } from "../../routing/resolve-route.js";
buildAgentSessionKey,
type RoutePeer,
type RoutePeerKind,
} from "../../routing/resolve-route.js";
import { resolveThreadSessionKeys } from "../../routing/session-key.js"; import { resolveThreadSessionKeys } from "../../routing/session-key.js";
import { import {
resolveSignalPeerId, resolveSignalPeerId,
@@ -94,10 +91,10 @@ function stripKindPrefix(raw: string): string {
function inferPeerKind(params: { function inferPeerKind(params: {
channel: ChannelId; channel: ChannelId;
resolvedTarget?: ResolvedMessagingTarget; resolvedTarget?: ResolvedMessagingTarget;
}): RoutePeerKind { }): ChatType {
const resolvedKind = params.resolvedTarget?.kind; const resolvedKind = params.resolvedTarget?.kind;
if (resolvedKind === "user") { if (resolvedKind === "user") {
return "dm"; return "direct";
} }
if (resolvedKind === "channel") { if (resolvedKind === "channel") {
return "channel"; return "channel";
@@ -112,7 +109,7 @@ function inferPeerKind(params: {
} }
return "group"; return "group";
} }
return "dm"; return "direct";
} }
function buildBaseSessionKey(params: { function buildBaseSessionKey(params: {
@@ -205,7 +202,7 @@ async function resolveSlackSession(
return null; return null;
} }
const isDm = parsed.kind === "user"; const isDm = parsed.kind === "user";
let peerKind: RoutePeerKind = isDm ? "dm" : "channel"; let peerKind: ChatType = isDm ? "direct" : "channel";
if (!isDm && /^G/i.test(parsed.id)) { if (!isDm && /^G/i.test(parsed.id)) {
// Slack mpim/group DMs share the G-prefix; detect to align session keys with inbound. // Slack mpim/group DMs share the G-prefix; detect to align session keys with inbound.
const channelType = await resolveSlackChannelType({ const channelType = await resolveSlackChannelType({
@@ -217,7 +214,7 @@ async function resolveSlackSession(
peerKind = "group"; peerKind = "group";
} }
if (channelType === "dm") { if (channelType === "dm") {
peerKind = "dm"; peerKind = "direct";
} }
} }
const peer: RoutePeer = { const peer: RoutePeer = {
@@ -240,14 +237,14 @@ async function resolveSlackSession(
sessionKey: threadKeys.sessionKey, sessionKey: threadKeys.sessionKey,
baseSessionKey, baseSessionKey,
peer, peer,
chatType: peerKind === "dm" ? "direct" : "channel", chatType: peerKind === "direct" ? "direct" : "channel",
from: from:
peerKind === "dm" peerKind === "direct"
? `slack:${parsed.id}` ? `slack:${parsed.id}`
: peerKind === "group" : peerKind === "group"
? `slack:group:${parsed.id}` ? `slack:group:${parsed.id}`
: `slack:channel:${parsed.id}`, : `slack:channel:${parsed.id}`,
to: peerKind === "dm" ? `user:${parsed.id}` : `channel:${parsed.id}`, to: peerKind === "direct" ? `user:${parsed.id}` : `channel:${parsed.id}`,
threadId, threadId,
}; };
} }
@@ -261,7 +258,7 @@ function resolveDiscordSession(
} }
const isDm = parsed.kind === "user"; const isDm = parsed.kind === "user";
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isDm ? "dm" : "channel", kind: isDm ? "direct" : "channel",
id: parsed.id, id: parsed.id,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -312,7 +309,7 @@ function resolveTelegramSession(
params.resolvedTarget.kind !== "user"); params.resolvedTarget.kind !== "user");
const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : chatId; const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : chatId;
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -342,7 +339,7 @@ function resolveWhatsAppSession(
} }
const isGroup = isWhatsAppGroupJid(normalized); const isGroup = isWhatsAppGroupJid(normalized);
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: normalized, id: normalized,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -409,7 +406,7 @@ function resolveSignalSession(
}); });
const peerId = sender ? resolveSignalPeerId(sender) : recipient; const peerId = sender ? resolveSignalPeerId(sender) : recipient;
const displayRecipient = sender ? resolveSignalRecipient(sender) : recipient; const displayRecipient = sender ? resolveSignalRecipient(sender) : recipient;
const peer: RoutePeer = { kind: "dm", id: peerId }; const peer: RoutePeer = { kind: "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -436,7 +433,7 @@ function resolveIMessageSession(
if (!handle) { if (!handle) {
return null; return null;
} }
const peer: RoutePeer = { kind: "dm", id: handle }; const peer: RoutePeer = { kind: "direct", id: handle };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -497,7 +494,7 @@ function resolveMatrixSession(
if (!rawId) { if (!rawId) {
return null; return null;
} }
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId }; const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -533,7 +530,7 @@ function resolveMSTeamsSession(
const conversationId = rawId.split(";")[0] ?? rawId; const conversationId = rawId.split(";")[0] ?? rawId;
const isChannel = !isUser && /@thread\.tacv2/i.test(conversationId); const isChannel = !isUser && /@thread\.tacv2/i.test(conversationId);
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isUser ? "dm" : isChannel ? "channel" : "group", kind: isUser ? "direct" : isChannel ? "channel" : "group",
id: conversationId, id: conversationId,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -574,7 +571,7 @@ function resolveMattermostSession(
if (!rawId) { if (!rawId) {
return null; return null;
} }
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId }; const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -619,7 +616,7 @@ function resolveBlueBubblesSession(
return null; return null;
} }
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -680,7 +677,7 @@ function resolveZaloSession(
} }
const isGroup = trimmed.toLowerCase().startsWith("group:"); const isGroup = trimmed.toLowerCase().startsWith("group:");
const peerId = stripKindPrefix(trimmed); const peerId = stripKindPrefix(trimmed);
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId }; const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -710,7 +707,7 @@ function resolveZalouserSession(
const isGroup = trimmed.toLowerCase().startsWith("group:"); const isGroup = trimmed.toLowerCase().startsWith("group:");
const peerId = stripKindPrefix(trimmed); const peerId = stripKindPrefix(trimmed);
// Keep DM vs group aligned with inbound sessions for Zalo Personal. // Keep DM vs group aligned with inbound sessions for Zalo Personal.
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId }; const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -735,7 +732,7 @@ function resolveNostrSession(
if (!trimmed) { if (!trimmed) {
return null; return null;
} }
const peer: RoutePeer = { kind: "dm", id: trimmed }; const peer: RoutePeer = { kind: "direct", id: trimmed };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -798,7 +795,7 @@ function resolveTlonSession(
peerId = normalizeTlonShip(trimmed); peerId = normalizeTlonShip(trimmed);
} }
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId }; const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg, cfg: params.cfg,
agentId: params.agentId, agentId: params.agentId,
@@ -851,7 +848,7 @@ function resolveFeishuSession(
} }
const peer: RoutePeer = { const peer: RoutePeer = {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: trimmed, id: trimmed,
}; };
const baseSessionKey = buildBaseSessionKey({ const baseSessionKey = buildBaseSessionKey({
@@ -893,10 +890,12 @@ function resolveFallbackSession(
channel: params.channel, channel: params.channel,
peer, peer,
}); });
const chatType = peerKind === "dm" ? "direct" : peerKind === "channel" ? "channel" : "group"; const chatType = peerKind === "direct" ? "direct" : peerKind === "channel" ? "channel" : "group";
const from = const from =
peerKind === "dm" ? `${params.channel}:${peerId}` : `${params.channel}:${peerKind}:${peerId}`; peerKind === "direct"
const toPrefix = peerKind === "dm" ? "user" : "channel"; ? `${params.channel}:${peerId}`
: `${params.channel}:${peerKind}:${peerId}`;
const toPrefix = peerKind === "direct" ? "user" : "channel";
return { return {
sessionKey: baseSessionKey, sessionKey: baseSessionKey,
baseSessionKey, baseSessionKey,
+2 -2
View File
@@ -154,7 +154,7 @@ export async function buildLineMessageContext(params: BuildLineMessageContextPar
channel: "line", channel: "line",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
}); });
@@ -328,7 +328,7 @@ export async function buildLinePostbackContext(params: {
channel: "line", channel: "line",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
}); });
+1 -1
View File
@@ -178,7 +178,7 @@ describe("applyMediaUnderstanding", () => {
Body: "<media:audio>", Body: "<media:audio>",
MediaUrl: "https://example.com/note.ogg", MediaUrl: "https://example.com/note.ogg",
MediaType: "audio/ogg", MediaType: "audio/ogg",
ChatType: "dm", ChatType: "direct",
}; };
const cfg: OpenClawConfig = { const cfg: OpenClawConfig = {
tools: { tools: {
+1 -1
View File
@@ -714,7 +714,7 @@ export class QmdMemoryManager implements MemorySearchManager {
const parts = normalized.split(":").filter(Boolean); const parts = normalized.split(":").filter(Boolean);
if ( if (
parts.length >= 2 && parts.length >= 2 &&
(parts[1] === "group" || parts[1] === "channel" || parts[1] === "dm") (parts[1] === "group" || parts[1] === "channel" || parts[1] === "direct" || parts[1] === "dm")
) { ) {
return parts[0]?.toLowerCase(); return parts[0]?.toLowerCase();
} }
+3
View File
@@ -118,6 +118,9 @@ export { ToolPolicySchema } from "../config/zod-schema.agent-runtime.js";
export type { RuntimeEnv } from "../runtime.js"; export type { RuntimeEnv } from "../runtime.js";
export type { WizardPrompter } from "../wizard/prompts.js"; export type { WizardPrompter } from "../wizard/prompts.js";
export { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../routing/session-key.js"; export { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../routing/session-key.js";
export type { ChatType } from "../channels/chat-type.js";
/** @deprecated Use ChatType instead */
export type { RoutePeerKind } from "../routing/resolve-route.js";
export { resolveAckReaction } from "../agents/identity.js"; export { resolveAckReaction } from "../agents/identity.js";
export type { ReplyPayload } from "../auto-reply/types.js"; export type { ReplyPayload } from "../auto-reply/types.js";
export type { ChunkMode } from "../auto-reply/chunk.js"; export type { ChunkMode } from "../auto-reply/chunk.js";
+45 -19
View File
@@ -9,7 +9,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: null, accountId: null,
peer: { kind: "dm", id: "+15551234567" }, peer: { kind: "direct", id: "+15551234567" },
}); });
expect(route.agentId).toBe("main"); expect(route.agentId).toBe("main");
expect(route.accountId).toBe("default"); expect(route.accountId).toBe("default");
@@ -25,9 +25,9 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: null, accountId: null,
peer: { kind: "dm", id: "+15551234567" }, peer: { kind: "direct", id: "+15551234567" },
}); });
expect(route.sessionKey).toBe("agent:main:dm:+15551234567"); expect(route.sessionKey).toBe("agent:main:direct:+15551234567");
}); });
test("dmScope=per-channel-peer isolates DM sessions per channel and sender", () => { test("dmScope=per-channel-peer isolates DM sessions per channel and sender", () => {
@@ -38,9 +38,9 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: null, accountId: null,
peer: { kind: "dm", id: "+15551234567" }, peer: { kind: "direct", id: "+15551234567" },
}); });
expect(route.sessionKey).toBe("agent:main:whatsapp:dm:+15551234567"); expect(route.sessionKey).toBe("agent:main:whatsapp:direct:+15551234567");
}); });
test("identityLinks collapses per-peer DM sessions across providers", () => { test("identityLinks collapses per-peer DM sessions across providers", () => {
@@ -56,9 +56,9 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "telegram", channel: "telegram",
accountId: null, accountId: null,
peer: { kind: "dm", id: "111111111" }, peer: { kind: "direct", id: "111111111" },
}); });
expect(route.sessionKey).toBe("agent:main:dm:alice"); expect(route.sessionKey).toBe("agent:main:direct:alice");
}); });
test("identityLinks applies to per-channel-peer DM sessions", () => { test("identityLinks applies to per-channel-peer DM sessions", () => {
@@ -74,9 +74,9 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "discord", channel: "discord",
accountId: null, accountId: null,
peer: { kind: "dm", id: "222222222222222222" }, peer: { kind: "direct", id: "222222222222222222" },
}); });
expect(route.sessionKey).toBe("agent:main:discord:dm:alice"); expect(route.sessionKey).toBe("agent:main:discord:direct:alice");
}); });
test("peer binding wins over account binding", () => { test("peer binding wins over account binding", () => {
@@ -87,7 +87,7 @@ describe("resolveAgentRoute", () => {
match: { match: {
channel: "whatsapp", channel: "whatsapp",
accountId: "biz", accountId: "biz",
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}, },
}, },
{ {
@@ -100,7 +100,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: "biz", accountId: "biz",
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}); });
expect(route.agentId).toBe("a"); expect(route.agentId).toBe("a");
expect(route.sessionKey).toBe("agent:a:main"); expect(route.sessionKey).toBe("agent:a:main");
@@ -177,7 +177,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: undefined, accountId: undefined,
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}); });
expect(defaultRoute.agentId).toBe("defaultacct"); expect(defaultRoute.agentId).toBe("defaultacct");
expect(defaultRoute.matchedBy).toBe("binding.account"); expect(defaultRoute.matchedBy).toBe("binding.account");
@@ -186,7 +186,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: "biz", accountId: "biz",
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}); });
expect(otherRoute.agentId).toBe("main"); expect(otherRoute.agentId).toBe("main");
}); });
@@ -204,7 +204,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: "biz", accountId: "biz",
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}); });
expect(route.agentId).toBe("any"); expect(route.agentId).toBe("any");
expect(route.matchedBy).toBe("binding.channel"); expect(route.matchedBy).toBe("binding.channel");
@@ -220,7 +220,7 @@ describe("resolveAgentRoute", () => {
cfg, cfg,
channel: "whatsapp", channel: "whatsapp",
accountId: "biz", accountId: "biz",
peer: { kind: "dm", id: "+1000" }, peer: { kind: "direct", id: "+1000" },
}); });
expect(route.agentId).toBe("home"); expect(route.agentId).toBe("home");
expect(route.sessionKey).toBe("agent:home:main"); expect(route.sessionKey).toBe("agent:home:main");
@@ -235,9 +235,9 @@ test("dmScope=per-account-channel-peer isolates DM sessions per account, channel
cfg, cfg,
channel: "telegram", channel: "telegram",
accountId: "tasks", accountId: "tasks",
peer: { kind: "dm", id: "7550356539" }, peer: { kind: "direct", id: "7550356539" },
}); });
expect(route.sessionKey).toBe("agent:main:telegram:tasks:dm:7550356539"); expect(route.sessionKey).toBe("agent:main:telegram:tasks:direct:7550356539");
}); });
test("dmScope=per-account-channel-peer uses default accountId when not provided", () => { test("dmScope=per-account-channel-peer uses default accountId when not provided", () => {
@@ -248,9 +248,9 @@ test("dmScope=per-account-channel-peer uses default accountId when not provided"
cfg, cfg,
channel: "telegram", channel: "telegram",
accountId: null, accountId: null,
peer: { kind: "dm", id: "7550356539" }, peer: { kind: "direct", id: "7550356539" },
}); });
expect(route.sessionKey).toBe("agent:main:telegram:default:dm:7550356539"); expect(route.sessionKey).toBe("agent:main:telegram:default:direct:7550356539");
}); });
describe("parentPeer binding inheritance (thread support)", () => { describe("parentPeer binding inheritance (thread support)", () => {
@@ -409,3 +409,29 @@ describe("parentPeer binding inheritance (thread support)", () => {
expect(route.matchedBy).toBe("default"); expect(route.matchedBy).toBe("default");
}); });
}); });
describe("backward compatibility: peer.kind dm → direct", () => {
test("legacy dm in config matches runtime direct peer", () => {
const cfg: OpenClawConfig = {
bindings: [
{
agentId: "alex",
match: {
channel: "whatsapp",
// Legacy config uses "dm" instead of "direct"
peer: { kind: "dm", id: "+15551234567" },
},
},
],
};
const route = resolveAgentRoute({
cfg,
channel: "whatsapp",
accountId: null,
// Runtime uses canonical "direct"
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.agentId).toBe("alex");
expect(route.matchedBy).toBe("binding.peer");
});
});
+8 -4
View File
@@ -1,5 +1,7 @@
import type { ChatType } from "../channels/chat-type.js";
import type { OpenClawConfig } from "../config/config.js"; import type { OpenClawConfig } from "../config/config.js";
import { resolveDefaultAgentId } from "../agents/agent-scope.js"; import { resolveDefaultAgentId } from "../agents/agent-scope.js";
import { normalizeChatType } from "../channels/chat-type.js";
import { listBindings } from "./bindings.js"; import { listBindings } from "./bindings.js";
import { import {
buildAgentMainSessionKey, buildAgentMainSessionKey,
@@ -10,10 +12,11 @@ import {
sanitizeAgentId, sanitizeAgentId,
} from "./session-key.js"; } from "./session-key.js";
export type RoutePeerKind = "dm" | "group" | "channel"; /** @deprecated Use ChatType from channels/chat-type.js */
export type RoutePeerKind = ChatType;
export type RoutePeer = { export type RoutePeer = {
kind: RoutePeerKind; kind: ChatType;
id: string; id: string;
}; };
@@ -89,7 +92,7 @@ export function buildAgentSessionKey(params: {
mainKey: DEFAULT_MAIN_KEY, mainKey: DEFAULT_MAIN_KEY,
channel, channel,
accountId: params.accountId, accountId: params.accountId,
peerKind: peer?.kind ?? "dm", peerKind: peer?.kind ?? "direct",
peerId: peer ? normalizeId(peer.id) || "unknown" : null, peerId: peer ? normalizeId(peer.id) || "unknown" : null,
dmScope: params.dmScope, dmScope: params.dmScope,
identityLinks: params.identityLinks, identityLinks: params.identityLinks,
@@ -137,7 +140,8 @@ function matchesPeer(
if (!m) { if (!m) {
return false; return false;
} }
const kind = normalizeToken(m.kind); // Backward compat: normalize "dm" to "direct" in config match rules
const kind = normalizeChatType(m.kind);
const id = normalizeId(m.id); const id = normalizeId(m.id);
if (!kind || !id) { if (!kind || !id) {
return false; return false;
+16
View File
@@ -23,3 +23,19 @@ describe("classifySessionKeyShape", () => {
expect(classifySessionKeyShape("subagent:worker")).toBe("legacy_or_alias"); expect(classifySessionKeyShape("subagent:worker")).toBe("legacy_or_alias");
}); });
}); });
describe("session key backward compatibility", () => {
it("classifies legacy :dm: session keys as valid agent keys", () => {
// Legacy session keys use :dm: instead of :direct:
// Both should be recognized as valid agent keys
expect(classifySessionKeyShape("agent:main:telegram:dm:123456")).toBe("agent");
expect(classifySessionKeyShape("agent:main:whatsapp:dm:+15551234567")).toBe("agent");
expect(classifySessionKeyShape("agent:main:discord:dm:user123")).toBe("agent");
});
it("classifies new :direct: session keys as valid agent keys", () => {
expect(classifySessionKeyShape("agent:main:telegram:direct:123456")).toBe("agent");
expect(classifySessionKeyShape("agent:main:whatsapp:direct:+15551234567")).toBe("agent");
expect(classifySessionKeyShape("agent:main:discord:direct:user123")).toBe("agent");
});
});
+7 -6
View File
@@ -1,3 +1,4 @@
import type { ChatType } from "../channels/chat-type.js";
import { parseAgentSessionKey, type ParsedAgentSessionKey } from "../sessions/session-key-utils.js"; import { parseAgentSessionKey, type ParsedAgentSessionKey } from "../sessions/session-key-utils.js";
export { export {
@@ -140,14 +141,14 @@ export function buildAgentPeerSessionKey(params: {
mainKey?: string | undefined; mainKey?: string | undefined;
channel: string; channel: string;
accountId?: string | null; accountId?: string | null;
peerKind?: "dm" | "group" | "channel" | null; peerKind?: ChatType | null;
peerId?: string | null; peerId?: string | null;
identityLinks?: Record<string, string[]>; identityLinks?: Record<string, string[]>;
/** DM session scope. */ /** DM session scope. */
dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer"; dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
}): string { }): string {
const peerKind = params.peerKind ?? "dm"; const peerKind = params.peerKind ?? "direct";
if (peerKind === "dm") { if (peerKind === "direct") {
const dmScope = params.dmScope ?? "main"; const dmScope = params.dmScope ?? "main";
let peerId = (params.peerId ?? "").trim(); let peerId = (params.peerId ?? "").trim();
const linkedPeerId = const linkedPeerId =
@@ -165,14 +166,14 @@ export function buildAgentPeerSessionKey(params: {
if (dmScope === "per-account-channel-peer" && peerId) { if (dmScope === "per-account-channel-peer" && peerId) {
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown"; const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
const accountId = normalizeAccountId(params.accountId); const accountId = normalizeAccountId(params.accountId);
return `agent:${normalizeAgentId(params.agentId)}:${channel}:${accountId}:dm:${peerId}`; return `agent:${normalizeAgentId(params.agentId)}:${channel}:${accountId}:direct:${peerId}`;
} }
if (dmScope === "per-channel-peer" && peerId) { if (dmScope === "per-channel-peer" && peerId) {
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown"; const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
return `agent:${normalizeAgentId(params.agentId)}:${channel}:dm:${peerId}`; return `agent:${normalizeAgentId(params.agentId)}:${channel}:direct:${peerId}`;
} }
if (dmScope === "per-peer" && peerId) { if (dmScope === "per-peer" && peerId) {
return `agent:${normalizeAgentId(params.agentId)}:dm:${peerId}`; return `agent:${normalizeAgentId(params.agentId)}:direct:${peerId}`;
} }
return buildAgentMainSessionKey({ return buildAgentMainSessionKey({
agentId: params.agentId, agentId: params.agentId,
@@ -414,7 +414,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig, cfg: config as OpenClawConfig,
channel: "signal", channel: "signal",
accountId: "default", accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") }, peer: { kind: "direct", id: normalizeE164("+15550001111") },
}); });
const events = peekSystemEvents(route.sessionKey); const events = peekSystemEvents(route.sessionKey);
expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true); expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true);
@@ -470,7 +470,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig, cfg: config as OpenClawConfig,
channel: "signal", channel: "signal",
accountId: "default", accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") }, peer: { kind: "direct", id: normalizeE164("+15550001111") },
}); });
const events = peekSystemEvents(route.sessionKey); const events = peekSystemEvents(route.sessionKey);
expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true); expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true);
+2 -2
View File
@@ -77,7 +77,7 @@ export function createSignalEventHandler(deps: SignalEventHandlerDeps) {
channel: "signal", channel: "signal",
accountId: deps.accountId, accountId: deps.accountId,
peer: { peer: {
kind: entry.isGroup ? "group" : "dm", kind: entry.isGroup ? "group" : "direct",
id: entry.isGroup ? (entry.groupId ?? "unknown") : entry.senderPeerId, id: entry.isGroup ? (entry.groupId ?? "unknown") : entry.senderPeerId,
}, },
}); });
@@ -370,7 +370,7 @@ export function createSignalEventHandler(deps: SignalEventHandlerDeps) {
channel: "signal", channel: "signal",
accountId: deps.accountId, accountId: deps.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? (groupId ?? "unknown") : senderPeerId, id: isGroup ? (groupId ?? "unknown") : senderPeerId,
}, },
}); });
@@ -120,7 +120,7 @@ describe("monitorSlackProvider tool results", () => {
bindings: [ bindings: [
{ {
agentId: "rich", agentId: "rich",
match: { channel: "slack", peer: { kind: "dm", id: "U1" } }, match: { channel: "slack", peer: { kind: "direct", id: "U1" } },
}, },
], ],
messages: { messages: {
+1 -1
View File
@@ -188,7 +188,7 @@ export async function prepareSlackMessage(params: {
accountId: account.accountId, accountId: account.accountId,
teamId: ctx.teamId || undefined, teamId: ctx.teamId || undefined,
peer: { peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group", kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? (message.user ?? "unknown") : message.channel, id: isDirectMessage ? (message.user ?? "unknown") : message.channel,
}, },
}); });
+1 -1
View File
@@ -373,7 +373,7 @@ export function registerSlackMonitorSlashCommands(params: {
accountId: account.accountId, accountId: account.accountId,
teamId: ctx.teamId || undefined, teamId: ctx.teamId || undefined,
peer: { peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group", kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? command.user_id : command.channel_id, id: isDirectMessage ? command.user_id : command.channel_id,
}, },
}); });
+1 -1
View File
@@ -163,7 +163,7 @@ export const registerTelegramHandlers = ({
channel: "telegram", channel: "telegram",
accountId, accountId,
peer: { peer: {
kind: params.isGroup ? "group" : "dm", kind: params.isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
parentPeer, parentPeer,
+1 -1
View File
@@ -168,7 +168,7 @@ export const buildTelegramMessageContext = async ({
channel: "telegram", channel: "telegram",
accountId: account.accountId, accountId: account.accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: peerId, id: peerId,
}, },
parentPeer, parentPeer,
+1 -1
View File
@@ -495,7 +495,7 @@ export const registerTelegramNativeCommands = ({
channel: "telegram", channel: "telegram",
accountId, accountId,
peer: { peer: {
kind: isGroup ? "group" : "dm", kind: isGroup ? "group" : "direct",
id: isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId), id: isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId),
}, },
parentPeer, parentPeer,
+1 -1
View File
@@ -453,7 +453,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
cfg, cfg,
channel: "telegram", channel: "telegram",
accountId: account.accountId, accountId: account.accountId,
peer: { kind: isGroup ? "group" : "dm", id: peerId }, peer: { kind: isGroup ? "group" : "direct", id: peerId },
parentPeer, parentPeer,
}); });
const sessionKey = route.sessionKey; const sessionKey = route.sessionKey;
@@ -164,7 +164,7 @@ describe("web auto-reply", () => {
agentId: "rich", agentId: "rich",
match: { match: {
channel: "whatsapp", channel: "whatsapp",
peer: { kind: "dm", id: "+1555" }, peer: { kind: "direct", id: "+1555" },
}, },
}, },
], ],
@@ -223,7 +223,7 @@ describe("web auto-reply", () => {
agentId: "rich", agentId: "rich",
match: { match: {
channel: "whatsapp", channel: "whatsapp",
peer: { kind: "dm", id: "+1555" }, peer: { kind: "direct", id: "+1555" },
}, },
}, },
], ],
+1 -1
View File
@@ -60,7 +60,7 @@ export async function maybeBroadcastMessage(params: {
channel: "whatsapp", channel: "whatsapp",
accountId: params.route.accountId, accountId: params.route.accountId,
peer: { peer: {
kind: params.msg.chatType === "group" ? "group" : "dm", kind: params.msg.chatType === "group" ? "group" : "direct",
id: params.peerId, id: params.peerId,
}, },
dmScope: params.cfg.session?.dmScope, dmScope: params.cfg.session?.dmScope,
+1 -1
View File
@@ -68,7 +68,7 @@ export function createWebOnMessageHandler(params: {
channel: "whatsapp", channel: "whatsapp",
accountId: msg.accountId, accountId: msg.accountId,
peer: { peer: {
kind: msg.chatType === "group" ? "group" : "dm", kind: msg.chatType === "group" ? "group" : "direct",
id: peerId, id: peerId,
}, },
}); });
-1
View File
@@ -13,7 +13,6 @@
"noEmitOnError": true, "noEmitOnError": true,
"outDir": "dist", "outDir": "dist",
"resolveJsonModule": true, "resolveJsonModule": true,
"rootDir": "src",
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
"target": "es2023", "target": "es2023",