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
@@ -228,4 +228,18 @@ describe("getDmHistoryLimitFromSessionKey", () => {
} as OpenClawConfig;
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 userIdRaw = providerParts.slice(2).join(":");
const userId = stripThreadSuffix(userIdRaw);
if (kind !== "dm") {
// Accept both "direct" (new) and "dm" (legacy) for backward compat
if (kind !== "direct" && kind !== "dm") {
return undefined;
}
+5 -4
View File
@@ -190,15 +190,16 @@ function inferDeliveryFromSessionKey(agentSessionKey?: string): CronDelivery | n
}
// buildAgentPeerSessionKey encodes peers as:
// - dm:<peerId>
// - <channel>:dm:<peerId>
// - <channel>:<accountId>:dm:<peerId>
// - direct:<peerId>
// - <channel>:direct:<peerId>
// - <channel>:<accountId>:direct:<peerId>
// - <channel>:group:<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.
// NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved.
const markerIndex = parts.findIndex(
(part) => part === "dm" || part === "group" || part === "channel",
(part) => part === "direct" || part === "dm" || part === "group" || part === "channel",
);
if (markerIndex === -1) {
return null;
+1 -1
View File
@@ -454,7 +454,7 @@ describe("initSessionState channel reset overrides", () => {
session: {
store: storePath,
idleMinutes: 60,
resetByType: { dm: { mode: "idle", idleMinutes: 10 } },
resetByType: { direct: { mode: "idle", idleMinutes: 10 } },
resetByChannel: { discord: { mode: "idle", idleMinutes: 10080 } },
},
} as OpenClawConfig;
+9
View File
@@ -15,4 +15,13 @@ describe("normalizeChatType", () => {
expect(normalizeChatType("nope")).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();
if (!value) {
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 { PollInput } from "../../polls.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 { ChannelMessageActionName as ChannelMessageActionNameFromList } from "./message-action-names.js";
@@ -162,7 +162,7 @@ export type ChannelGroupContext = {
};
export type ChannelCapabilities = {
chatTypes: Array<NormalizedChatType | "thread">;
chatTypes: Array<ChatType | "thread">;
polls?: boolean;
reactions?: 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 () => {
await withEnvOverride(
{ 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"));
},
);
});
// Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
it.skipIf(process.platform === "win32")(
"STATE_DIR respects OPENCLAW_HOME when state override is unset",
async () => {
await withEnvOverride(
{ 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 () => {
await withEnvOverride(
{
OPENCLAW_HOME: "/custom/home",
OPENCLAW_CONFIG_PATH: undefined,
OPENCLAW_STATE_DIR: undefined,
},
async () => {
const { CONFIG_PATH } = await import("./config.js");
expect(CONFIG_PATH).toBe(path.resolve("/custom/home/.openclaw/openclaw.json"));
},
);
});
// Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
it.skipIf(process.platform === "win32")(
"CONFIG_PATH defaults to OPENCLAW_HOME/.openclaw/openclaw.json",
async () => {
await withEnvOverride(
{
OPENCLAW_HOME: "/custom/home",
OPENCLAW_CONFIG_PATH: undefined,
OPENCLAW_STATE_DIR: undefined,
},
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 () => {
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";
export type SessionResetMode = "daily" | "idle";
export type SessionResetType = "dm" | "group" | "thread";
export type SessionResetType = "direct" | "group" | "thread";
export type SessionResetPolicy = {
mode: SessionResetMode;
@@ -46,7 +46,7 @@ export function resolveSessionResetType(params: {
if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) {
return "group";
}
return "dm";
return "direct";
}
export function resolveThreadFlag(params: {
@@ -88,7 +88,13 @@ export function resolveSessionResetPolicy(params: {
}): SessionResetPolicy {
const sessionCfg = params.sessionCfg;
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 legacyIdleMinutes = params.resetOverride ? undefined : sessionCfg?.idleMinutes;
const mode =
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Skill } from "@mariozechner/pi-coding-agent";
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 { DeliveryContext } from "../../utils/delivery-context.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 SessionChatType = NormalizedChatType;
export type SessionChatType = ChatType;
export type SessionOrigin = {
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 { HumanDelayConfig, IdentityConfig } from "./types.base.js";
import type { GroupChatConfig } from "./types.messages.js";
@@ -74,7 +75,7 @@ export type AgentBinding = {
match: {
channel: string;
accountId?: string;
peer?: { kind: "dm" | "group" | "channel"; id: string };
peer?: { kind: ChatType; id: string };
guildId?: 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 TypingMode = "never" | "instant" | "thinking" | "message";
@@ -50,7 +50,7 @@ export type HumanDelayConfig = {
export type SessionSendPolicyAction = "allow" | "deny";
export type SessionSendPolicyMatch = {
channel?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
keyPrefix?: string;
};
export type SessionSendPolicyRule = {
@@ -71,6 +71,8 @@ export type SessionResetConfig = {
idleMinutes?: number;
};
export type SessionResetByTypeConfig = {
direct?: SessionResetConfig;
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm?: SessionResetConfig;
group?: 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";
export type MediaUnderstandingScopeMatch = {
channel?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
keyPrefix?: string;
};
+7 -1
View File
@@ -22,7 +22,13 @@ export const BindingsSchema = z
accountId: z.string().optional(),
peer: z
.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(),
})
.strict()
+7 -1
View File
@@ -378,7 +378,13 @@ export const MediaUnderstandingScopeSchema = z
.object({
channel: z.string().optional(),
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(),
keyPrefix: z.string().optional(),
})
+9 -1
View File
@@ -27,7 +27,13 @@ export const SessionSendPolicySchema = z
.object({
channel: z.string().optional(),
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(),
keyPrefix: z.string().optional(),
})
@@ -57,6 +63,8 @@ export const SessionSchema = z
reset: SessionResetConfigSchema.optional(),
resetByType: z
.object({
direct: SessionResetConfigSchema.optional(),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm: SessionResetConfigSchema.optional(),
group: SessionResetConfigSchema.optional(),
thread: SessionResetConfigSchema.optional(),
@@ -87,12 +87,12 @@ describe("discord processDiscordMessage inbound contract", () => {
guildInfo: null,
guildSlug: "",
channelConfig: null,
baseSessionKey: "agent:main:discord:dm:u1",
baseSessionKey: "agent:main:discord:direct:u1",
route: {
agentId: "main",
channel: "discord",
accountId: "default",
sessionKey: "agent:main:discord:dm:u1",
sessionKey: "agent:main:discord:direct:u1",
mainSessionKey: "agent:main:main",
// oxlint-disable-next-line typescript/no-explicit-any
} as any,
@@ -224,7 +224,7 @@ export async function preflightDiscordMessage(
accountId: params.accountId,
guildId: params.data.guild_id ?? undefined,
peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel",
kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? author.id : message.channelId,
},
// Pass parent peer for thread binding inheritance
+1 -1
View File
@@ -736,7 +736,7 @@ async function dispatchDiscordCommandInteraction(params: {
accountId,
guildId: interaction.guild?.id ?? undefined,
peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel",
kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? user.id : channelId,
},
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 { DeliveryContext } from "../utils/delivery-context.js";
@@ -19,7 +19,7 @@ export type GatewaySessionRow = {
subject?: string;
groupChannel?: string;
space?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
origin?: SessionEntry["origin"];
updatedAt: number | null;
sessionId?: string;
+1 -1
View File
@@ -387,7 +387,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
channel: "imessage",
accountId: accountInfo.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? String(chatId ?? "unknown") : normalizeIMessageHandle(sender),
},
});
+3 -3
View File
@@ -43,7 +43,7 @@ describe("resolveOutboundSessionRoute", () => {
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");
});
@@ -64,7 +64,7 @@ describe("resolveOutboundSessionRoute", () => {
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 () => {
@@ -88,7 +88,7 @@ describe("resolveOutboundSessionRoute", () => {
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");
});
+29 -30
View File
@@ -1,4 +1,5 @@
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 { OpenClawConfig } from "../../config/config.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 { parseDiscordTarget } from "../../discord/targets.js";
import { parseIMessageTarget, normalizeIMessageHandle } from "../../imessage/targets.js";
import {
buildAgentSessionKey,
type RoutePeer,
type RoutePeerKind,
} from "../../routing/resolve-route.js";
import { buildAgentSessionKey, type RoutePeer } from "../../routing/resolve-route.js";
import { resolveThreadSessionKeys } from "../../routing/session-key.js";
import {
resolveSignalPeerId,
@@ -94,10 +91,10 @@ function stripKindPrefix(raw: string): string {
function inferPeerKind(params: {
channel: ChannelId;
resolvedTarget?: ResolvedMessagingTarget;
}): RoutePeerKind {
}): ChatType {
const resolvedKind = params.resolvedTarget?.kind;
if (resolvedKind === "user") {
return "dm";
return "direct";
}
if (resolvedKind === "channel") {
return "channel";
@@ -112,7 +109,7 @@ function inferPeerKind(params: {
}
return "group";
}
return "dm";
return "direct";
}
function buildBaseSessionKey(params: {
@@ -205,7 +202,7 @@ async function resolveSlackSession(
return null;
}
const isDm = parsed.kind === "user";
let peerKind: RoutePeerKind = isDm ? "dm" : "channel";
let peerKind: ChatType = isDm ? "direct" : "channel";
if (!isDm && /^G/i.test(parsed.id)) {
// Slack mpim/group DMs share the G-prefix; detect to align session keys with inbound.
const channelType = await resolveSlackChannelType({
@@ -217,7 +214,7 @@ async function resolveSlackSession(
peerKind = "group";
}
if (channelType === "dm") {
peerKind = "dm";
peerKind = "direct";
}
}
const peer: RoutePeer = {
@@ -240,14 +237,14 @@ async function resolveSlackSession(
sessionKey: threadKeys.sessionKey,
baseSessionKey,
peer,
chatType: peerKind === "dm" ? "direct" : "channel",
chatType: peerKind === "direct" ? "direct" : "channel",
from:
peerKind === "dm"
peerKind === "direct"
? `slack:${parsed.id}`
: peerKind === "group"
? `slack:group:${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,
};
}
@@ -261,7 +258,7 @@ function resolveDiscordSession(
}
const isDm = parsed.kind === "user";
const peer: RoutePeer = {
kind: isDm ? "dm" : "channel",
kind: isDm ? "direct" : "channel",
id: parsed.id,
};
const baseSessionKey = buildBaseSessionKey({
@@ -312,7 +309,7 @@ function resolveTelegramSession(
params.resolvedTarget.kind !== "user");
const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : chatId;
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -342,7 +339,7 @@ function resolveWhatsAppSession(
}
const isGroup = isWhatsAppGroupJid(normalized);
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: normalized,
};
const baseSessionKey = buildBaseSessionKey({
@@ -409,7 +406,7 @@ function resolveSignalSession(
});
const peerId = sender ? resolveSignalPeerId(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({
cfg: params.cfg,
agentId: params.agentId,
@@ -436,7 +433,7 @@ function resolveIMessageSession(
if (!handle) {
return null;
}
const peer: RoutePeer = { kind: "dm", id: handle };
const peer: RoutePeer = { kind: "direct", id: handle };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -497,7 +494,7 @@ function resolveMatrixSession(
if (!rawId) {
return null;
}
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId };
const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -533,7 +530,7 @@ function resolveMSTeamsSession(
const conversationId = rawId.split(";")[0] ?? rawId;
const isChannel = !isUser && /@thread\.tacv2/i.test(conversationId);
const peer: RoutePeer = {
kind: isUser ? "dm" : isChannel ? "channel" : "group",
kind: isUser ? "direct" : isChannel ? "channel" : "group",
id: conversationId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -574,7 +571,7 @@ function resolveMattermostSession(
if (!rawId) {
return null;
}
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId };
const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -619,7 +616,7 @@ function resolveBlueBubblesSession(
return null;
}
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -680,7 +677,7 @@ function resolveZaloSession(
}
const isGroup = trimmed.toLowerCase().startsWith("group:");
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({
cfg: params.cfg,
agentId: params.agentId,
@@ -710,7 +707,7 @@ function resolveZalouserSession(
const isGroup = trimmed.toLowerCase().startsWith("group:");
const peerId = stripKindPrefix(trimmed);
// 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({
cfg: params.cfg,
agentId: params.agentId,
@@ -735,7 +732,7 @@ function resolveNostrSession(
if (!trimmed) {
return null;
}
const peer: RoutePeer = { kind: "dm", id: trimmed };
const peer: RoutePeer = { kind: "direct", id: trimmed };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -798,7 +795,7 @@ function resolveTlonSession(
peerId = normalizeTlonShip(trimmed);
}
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId };
const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -851,7 +848,7 @@ function resolveFeishuSession(
}
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: trimmed,
};
const baseSessionKey = buildBaseSessionKey({
@@ -893,10 +890,12 @@ function resolveFallbackSession(
channel: params.channel,
peer,
});
const chatType = peerKind === "dm" ? "direct" : peerKind === "channel" ? "channel" : "group";
const chatType = peerKind === "direct" ? "direct" : peerKind === "channel" ? "channel" : "group";
const from =
peerKind === "dm" ? `${params.channel}:${peerId}` : `${params.channel}:${peerKind}:${peerId}`;
const toPrefix = peerKind === "dm" ? "user" : "channel";
peerKind === "direct"
? `${params.channel}:${peerId}`
: `${params.channel}:${peerKind}:${peerId}`;
const toPrefix = peerKind === "direct" ? "user" : "channel";
return {
sessionKey: baseSessionKey,
baseSessionKey,
+2 -2
View File
@@ -154,7 +154,7 @@ export async function buildLineMessageContext(params: BuildLineMessageContextPar
channel: "line",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
});
@@ -328,7 +328,7 @@ export async function buildLinePostbackContext(params: {
channel: "line",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
});
+1 -1
View File
@@ -178,7 +178,7 @@ describe("applyMediaUnderstanding", () => {
Body: "<media:audio>",
MediaUrl: "https://example.com/note.ogg",
MediaType: "audio/ogg",
ChatType: "dm",
ChatType: "direct",
};
const cfg: OpenClawConfig = {
tools: {
+1 -1
View File
@@ -714,7 +714,7 @@ export class QmdMemoryManager implements MemorySearchManager {
const parts = normalized.split(":").filter(Boolean);
if (
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();
}
+3
View File
@@ -118,6 +118,9 @@ export { ToolPolicySchema } from "../config/zod-schema.agent-runtime.js";
export type { RuntimeEnv } from "../runtime.js";
export type { WizardPrompter } from "../wizard/prompts.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 type { ReplyPayload } from "../auto-reply/types.js";
export type { ChunkMode } from "../auto-reply/chunk.js";
+45 -19
View File
@@ -9,7 +9,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: null,
peer: { kind: "dm", id: "+15551234567" },
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.agentId).toBe("main");
expect(route.accountId).toBe("default");
@@ -25,9 +25,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
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", () => {
@@ -38,9 +38,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
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", () => {
@@ -56,9 +56,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "telegram",
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", () => {
@@ -74,9 +74,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "discord",
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", () => {
@@ -87,7 +87,7 @@ describe("resolveAgentRoute", () => {
match: {
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
},
},
{
@@ -100,7 +100,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("a");
expect(route.sessionKey).toBe("agent:a:main");
@@ -177,7 +177,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: undefined,
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(defaultRoute.agentId).toBe("defaultacct");
expect(defaultRoute.matchedBy).toBe("binding.account");
@@ -186,7 +186,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(otherRoute.agentId).toBe("main");
});
@@ -204,7 +204,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("any");
expect(route.matchedBy).toBe("binding.channel");
@@ -220,7 +220,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("home");
expect(route.sessionKey).toBe("agent:home:main");
@@ -235,9 +235,9 @@ test("dmScope=per-account-channel-peer isolates DM sessions per account, channel
cfg,
channel: "telegram",
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", () => {
@@ -248,9 +248,9 @@ test("dmScope=per-account-channel-peer uses default accountId when not provided"
cfg,
channel: "telegram",
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)", () => {
@@ -409,3 +409,29 @@ describe("parentPeer binding inheritance (thread support)", () => {
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 { resolveDefaultAgentId } from "../agents/agent-scope.js";
import { normalizeChatType } from "../channels/chat-type.js";
import { listBindings } from "./bindings.js";
import {
buildAgentMainSessionKey,
@@ -10,10 +12,11 @@ import {
sanitizeAgentId,
} 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 = {
kind: RoutePeerKind;
kind: ChatType;
id: string;
};
@@ -89,7 +92,7 @@ export function buildAgentSessionKey(params: {
mainKey: DEFAULT_MAIN_KEY,
channel,
accountId: params.accountId,
peerKind: peer?.kind ?? "dm",
peerKind: peer?.kind ?? "direct",
peerId: peer ? normalizeId(peer.id) || "unknown" : null,
dmScope: params.dmScope,
identityLinks: params.identityLinks,
@@ -137,7 +140,8 @@ function matchesPeer(
if (!m) {
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);
if (!kind || !id) {
return false;
+16
View File
@@ -23,3 +23,19 @@ describe("classifySessionKeyShape", () => {
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";
export {
@@ -140,14 +141,14 @@ export function buildAgentPeerSessionKey(params: {
mainKey?: string | undefined;
channel: string;
accountId?: string | null;
peerKind?: "dm" | "group" | "channel" | null;
peerKind?: ChatType | null;
peerId?: string | null;
identityLinks?: Record<string, string[]>;
/** DM session scope. */
dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
}): string {
const peerKind = params.peerKind ?? "dm";
if (peerKind === "dm") {
const peerKind = params.peerKind ?? "direct";
if (peerKind === "direct") {
const dmScope = params.dmScope ?? "main";
let peerId = (params.peerId ?? "").trim();
const linkedPeerId =
@@ -165,14 +166,14 @@ export function buildAgentPeerSessionKey(params: {
if (dmScope === "per-account-channel-peer" && peerId) {
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
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) {
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) {
return `agent:${normalizeAgentId(params.agentId)}:dm:${peerId}`;
return `agent:${normalizeAgentId(params.agentId)}:direct:${peerId}`;
}
return buildAgentMainSessionKey({
agentId: params.agentId,
@@ -414,7 +414,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig,
channel: "signal",
accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") },
peer: { kind: "direct", id: normalizeE164("+15550001111") },
});
const events = peekSystemEvents(route.sessionKey);
expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true);
@@ -470,7 +470,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig,
channel: "signal",
accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") },
peer: { kind: "direct", id: normalizeE164("+15550001111") },
});
const events = peekSystemEvents(route.sessionKey);
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",
accountId: deps.accountId,
peer: {
kind: entry.isGroup ? "group" : "dm",
kind: entry.isGroup ? "group" : "direct",
id: entry.isGroup ? (entry.groupId ?? "unknown") : entry.senderPeerId,
},
});
@@ -370,7 +370,7 @@ export function createSignalEventHandler(deps: SignalEventHandlerDeps) {
channel: "signal",
accountId: deps.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? (groupId ?? "unknown") : senderPeerId,
},
});
@@ -120,7 +120,7 @@ describe("monitorSlackProvider tool results", () => {
bindings: [
{
agentId: "rich",
match: { channel: "slack", peer: { kind: "dm", id: "U1" } },
match: { channel: "slack", peer: { kind: "direct", id: "U1" } },
},
],
messages: {
+1 -1
View File
@@ -188,7 +188,7 @@ export async function prepareSlackMessage(params: {
accountId: account.accountId,
teamId: ctx.teamId || undefined,
peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group",
kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? (message.user ?? "unknown") : message.channel,
},
});
+1 -1
View File
@@ -373,7 +373,7 @@ export function registerSlackMonitorSlashCommands(params: {
accountId: account.accountId,
teamId: ctx.teamId || undefined,
peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group",
kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? command.user_id : command.channel_id,
},
});
+1 -1
View File
@@ -163,7 +163,7 @@ export const registerTelegramHandlers = ({
channel: "telegram",
accountId,
peer: {
kind: params.isGroup ? "group" : "dm",
kind: params.isGroup ? "group" : "direct",
id: peerId,
},
parentPeer,
+1 -1
View File
@@ -168,7 +168,7 @@ export const buildTelegramMessageContext = async ({
channel: "telegram",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
parentPeer,
+1 -1
View File
@@ -495,7 +495,7 @@ export const registerTelegramNativeCommands = ({
channel: "telegram",
accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId),
},
parentPeer,
+1 -1
View File
@@ -453,7 +453,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
cfg,
channel: "telegram",
accountId: account.accountId,
peer: { kind: isGroup ? "group" : "dm", id: peerId },
peer: { kind: isGroup ? "group" : "direct", id: peerId },
parentPeer,
});
const sessionKey = route.sessionKey;
@@ -164,7 +164,7 @@ describe("web auto-reply", () => {
agentId: "rich",
match: {
channel: "whatsapp",
peer: { kind: "dm", id: "+1555" },
peer: { kind: "direct", id: "+1555" },
},
},
],
@@ -223,7 +223,7 @@ describe("web auto-reply", () => {
agentId: "rich",
match: {
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",
accountId: params.route.accountId,
peer: {
kind: params.msg.chatType === "group" ? "group" : "dm",
kind: params.msg.chatType === "group" ? "group" : "direct",
id: params.peerId,
},
dmScope: params.cfg.session?.dmScope,
+1 -1
View File
@@ -68,7 +68,7 @@ export function createWebOnMessageHandler(params: {
channel: "whatsapp",
accountId: msg.accountId,
peer: {
kind: msg.chatType === "group" ? "group" : "dm",
kind: msg.chatType === "group" ? "group" : "direct",
id: peerId,
},
});