perf(routing): cache normalized agent-id lookups

This commit is contained in:
Peter Steinberger
2026-03-02 20:18:53 +00:00
parent 2937fe0351
commit 3de7768b11

View File

@@ -111,21 +111,53 @@ function listAgents(cfg: OpenClawConfig) {
return Array.isArray(agents) ? agents : []; return Array.isArray(agents) ? agents : [];
} }
type AgentLookupCache = {
agentsRef: OpenClawConfig["agents"] | undefined;
byNormalizedId: Map<string, string>;
fallbackDefaultAgentId: string;
};
const agentLookupCacheByCfg = new WeakMap<OpenClawConfig, AgentLookupCache>();
function resolveAgentLookupCache(cfg: OpenClawConfig): AgentLookupCache {
const agentsRef = cfg.agents;
const existing = agentLookupCacheByCfg.get(cfg);
if (existing && existing.agentsRef === agentsRef) {
return existing;
}
const byNormalizedId = new Map<string, string>();
for (const agent of listAgents(cfg)) {
const rawId = agent.id?.trim();
if (!rawId) {
continue;
}
byNormalizedId.set(normalizeAgentId(rawId), sanitizeAgentId(rawId));
}
const next: AgentLookupCache = {
agentsRef,
byNormalizedId,
fallbackDefaultAgentId: sanitizeAgentId(resolveDefaultAgentId(cfg)),
};
agentLookupCacheByCfg.set(cfg, next);
return next;
}
function pickFirstExistingAgentId(cfg: OpenClawConfig, agentId: string): string { function pickFirstExistingAgentId(cfg: OpenClawConfig, agentId: string): string {
const lookup = resolveAgentLookupCache(cfg);
const trimmed = (agentId ?? "").trim(); const trimmed = (agentId ?? "").trim();
if (!trimmed) { if (!trimmed) {
return sanitizeAgentId(resolveDefaultAgentId(cfg)); return lookup.fallbackDefaultAgentId;
} }
const normalized = normalizeAgentId(trimmed); const normalized = normalizeAgentId(trimmed);
const agents = listAgents(cfg); if (lookup.byNormalizedId.size === 0) {
if (agents.length === 0) {
return sanitizeAgentId(trimmed); return sanitizeAgentId(trimmed);
} }
const match = agents.find((agent) => normalizeAgentId(agent.id) === normalized); const resolved = lookup.byNormalizedId.get(normalized);
if (match?.id?.trim()) { if (resolved) {
return sanitizeAgentId(match.id.trim()); return resolved;
} }
return sanitizeAgentId(resolveDefaultAgentId(cfg)); return lookup.fallbackDefaultAgentId;
} }
function matchesChannel( function matchesChannel(