export function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentRoute {
// 1. 过滤出匹配通道和账户的绑定
const bindings = listBindings(input.cfg).filter((binding) => {
if (!matchesChannel(binding.match, channel)) return false;
return matchesAccountId(binding.match?.accountId, accountId);
});
const choose = (agentId: string, matchedBy: ...) => {
const resolvedAgentId = pickFirstExistingAgentId(input.cfg, agentId);
const sessionKey = buildAgentSessionKey({ ... });
const mainSessionKey = buildAgentMainSessionKey({ ... });
return { agentId: resolvedAgentId, channel, accountId, sessionKey, mainSessionKey, matchedBy };
};
// 优先级 1:精确对等方匹配(最具体)
if (peer) {
const peerMatch = bindings.find((b) => matchesPeer(b.match, peer));
if (peerMatch) return choose(peerMatch.agentId, "binding.peer");
}
// 优先级 2:线程父对等方匹配(继承父消息的路由)
if (parentPeer?.id) {
const parentMatch = bindings.find((b) => matchesPeer(b.match, parentPeer));
if (parentMatch) return choose(parentMatch.agentId, "binding.peer.parent");
}
// 优先级 3:Guild 匹配(Discord 服务器级别)
if (guildId) {
const guildMatch = bindings.find((b) => matchesGuild(b.match, guildId));
if (guildMatch) return choose(guildMatch.agentId, "binding.guild");
}
// 优先级 4:Team 匹配(Slack 团队级别)
if (teamId) {
const teamMatch = bindings.find((b) => matchesTeam(b.match, teamId));
if (teamMatch) return choose(teamMatch.agentId, "binding.team");
}
// 优先级 5:账户匹配(排除带有更具体匹配条件的绑定)
const accountMatch = bindings.find((b) =>
b.match?.accountId?.trim() !== "*" && !b.match?.peer && !b.match?.guildId
);
if (accountMatch) return choose(accountMatch.agentId, "binding.account");
// 优先级 6:通道通配符匹配(accountId === "*")
const anyAccountMatch = bindings.find((b) =>
b.match?.accountId?.trim() === "*" && !b.match?.peer && !b.match?.guildId
);
if (anyAccountMatch) return choose(anyAccountMatch.agentId, "binding.channel");
// 优先级 7:默认 Agent
return choose(resolveDefaultAgentId(input.cfg), "default");
}