Skip to content

Commit 7b71d56

Browse files
authored
perf(gateway): reuse session catalog entry snapshots per request (#114358)
* perf(gateway): reuse session catalog entry snapshots * chore(gateway): satisfy knip and typed-test lanes for catalog snapshot
1 parent 2714c60 commit 7b71d56

9 files changed

Lines changed: 352 additions & 154 deletions

File tree

‎extensions/anthropic/session-catalog-runtime.ts‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
import {
2-
listAgentIds,
32
resolveAllowedModelRef,
43
resolveDefaultAgentId,
54
resolveDefaultModelForAgent,
65
} from "openclaw/plugin-sdk/agent-runtime";
76
import { resolveEffectiveAgentRuntime } from "openclaw/plugin-sdk/command-auth-native";
87
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
98
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
9+
import {
10+
listSessionCatalogEntries,
11+
type SessionCatalogEntrySnapshot,
12+
} from "openclaw/plugin-sdk/session-catalog";
1013
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1114
import { CLAUDE_CLI_BACKEND_ID, CLAUDE_CLI_ROUTE_PROBE_MODEL_IDS } from "./cli-constants.js";
1215
import { adoptedSourceKey, CLAUDE_LOCAL_SESSION_HOST_ID } from "./session-catalog-adoption.js";
@@ -47,17 +50,17 @@ function boundClaudeSource(
4750
: undefined;
4851
}
4952

50-
export function listBoundClaudeSessions(api: OpenClawPluginApi): Map<string, string> {
53+
export function listBoundClaudeSessions(
54+
api: OpenClawPluginApi,
55+
sessionEntries?: SessionCatalogEntrySnapshot,
56+
): Map<string, string> {
5157
const config = currentClaudeSessionCatalogConfig(api);
52-
const defaultAgentId = resolveDefaultAgentId(config);
53-
const agentIds = [
54-
defaultAgentId,
55-
...listAgentIds(config).filter((agentId) => agentId !== defaultAgentId),
56-
];
5758
const bound = new Map<string, string>();
58-
for (const { sessionKey, entry } of agentIds.flatMap((agentId) =>
59-
api.runtime.agent.session.listSessionEntries({ agentId, readOnly: true }),
60-
)) {
59+
for (const { sessionKey, entry } of listSessionCatalogEntries({
60+
config,
61+
runtime: api.runtime,
62+
sessionEntries,
63+
})) {
6164
const source = boundClaudeSource(api.id, entry);
6265
if (source) {
6366
bound.set(adoptedSourceKey(source.hostId, source.threadId), sessionKey);

‎extensions/anthropic/session-catalog.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,9 +1596,9 @@ export function registerClaudeSessionCatalog(api: OpenClawPluginApi): void {
15961596
label: "Claude Code",
15971597
resolveCreateSession: ({ agentId }) => resolveClaudeCatalogCreateSession(api, agentId),
15981598
list: async (query) => {
1599-
const adopted = listBoundClaudeSessions(api);
1599+
const adopted = listBoundClaudeSessions(api, query.sessionEntries);
16001600
const localCliAvailable = catalogTerminal.isClaudeCliAvailable();
1601-
const { onHost, ...gatewayQuery } = query;
1601+
const { onHost, sessionEntries: _sessionEntries, ...gatewayQuery } = query;
16021602
const mapHost = (host: ClaudeSessionCatalogHost) =>
16031603
toGenericClaudeHost(host, adopted, localCliAvailable);
16041604
const result = await listClaudeSessionCatalog({

‎extensions/codex/src/session-catalog-node-adoption.ts‎

Lines changed: 36 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
44
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
55
import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";
66
import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
7+
import {
8+
listSessionCatalogEntries,
9+
type SessionCatalogEntrySnapshot,
10+
} from "openclaw/plugin-sdk/session-catalog";
711
import { resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
812
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
913
import type { CodexThread } from "./app-server/protocol.js";
@@ -137,41 +141,41 @@ export function listNodeAdoptedSessionEntries(params: {
137141
config?: OpenClawConfig;
138142
runtime: PluginRuntime;
139143
includeInitializing?: boolean;
144+
sessionEntries?: SessionCatalogEntrySnapshot;
140145
}): Map<string, AdoptedSessionEntry> {
141146
const adopted = new Map<string, AdoptedSessionEntry>();
142-
for (const agentId of listSupervisionAgentIds(params.config ?? {})) {
143-
for (const { entry, sessionKey } of params.runtime.agent.session.listSessionEntries({
144-
agentId,
145-
readOnly: true,
146-
})) {
147-
const marker = readNodeSessionMarker(entry);
148-
const sessionId = entry.sessionId?.trim();
149-
if (
150-
!marker ||
151-
(marker.initializing === true && params.includeInitializing !== true) ||
152-
entry.initializationPending === true ||
153-
entry.agentHarnessId !== "codex" ||
154-
entry.modelSelectionLocked !== true ||
155-
!sessionId ||
156-
adoptionSessionKeyRest(sessionKey) !==
157-
nodeAdoptionSessionKey(marker.sourceHostId, marker.sourceThreadId) ||
158-
marker.sourceHostId !== `node:${marker.nodeId}`
159-
) {
160-
continue;
161-
}
162-
const sourceKey = adoptedSourceKey(marker.sourceHostId, marker.sourceThreadId);
163-
if (adopted.has(sourceKey)) {
164-
throw new Error(
165-
`multiple OpenClaw sessions adopt Codex thread ${marker.sourceThreadId} on ${marker.sourceHostId}`,
166-
);
167-
}
168-
adopted.set(sourceKey, {
169-
key: sessionKey,
170-
sessionId,
171-
agentId,
172-
...(marker.initializing === true ? { initializing: true } : {}),
173-
});
147+
for (const { agentId, entry, sessionKey } of listSessionCatalogEntries({
148+
config: params.config ?? {},
149+
runtime: params.runtime,
150+
sessionEntries: params.sessionEntries,
151+
})) {
152+
const marker = readNodeSessionMarker(entry);
153+
const sessionId = entry.sessionId?.trim();
154+
if (
155+
!marker ||
156+
(marker.initializing === true && params.includeInitializing !== true) ||
157+
entry.initializationPending === true ||
158+
entry.agentHarnessId !== "codex" ||
159+
entry.modelSelectionLocked !== true ||
160+
!sessionId ||
161+
adoptionSessionKeyRest(sessionKey) !==
162+
nodeAdoptionSessionKey(marker.sourceHostId, marker.sourceThreadId) ||
163+
marker.sourceHostId !== `node:${marker.nodeId}`
164+
) {
165+
continue;
166+
}
167+
const sourceKey = adoptedSourceKey(marker.sourceHostId, marker.sourceThreadId);
168+
if (adopted.has(sourceKey)) {
169+
throw new Error(
170+
`multiple OpenClaw sessions adopt Codex thread ${marker.sourceThreadId} on ${marker.sourceHostId}`,
171+
);
174172
}
173+
adopted.set(sourceKey, {
174+
key: sessionKey,
175+
sessionId,
176+
agentId,
177+
...(marker.initializing === true ? { initializing: true } : {}),
178+
});
175179
}
176180
return adopted;
177181
}

‎extensions/codex/src/session-catalog.ts‎

Lines changed: 47 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import type {
77
OpenClawPluginNodeInvokePolicy,
88
} from "openclaw/plugin-sdk/plugin-entry";
99
import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";
10-
import type {
11-
SessionCatalogHost,
12-
SessionCatalogProvider,
10+
import {
11+
listSessionCatalogEntries,
12+
type SessionCatalogEntrySnapshot,
13+
type SessionCatalogHost,
14+
type SessionCatalogProvider,
1315
} from "openclaw/plugin-sdk/session-catalog";
1416
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1517
import { CODEX_CONTROL_METHODS } from "./app-server/capabilities.js";
@@ -372,6 +374,7 @@ async function listGatewayHost(params: {
372374
control: CodexSessionCatalogControl;
373375
query: CodexSessionCatalogParams;
374376
runtime: PluginRuntime;
377+
sessionEntries?: SessionCatalogEntrySnapshot;
375378
}): Promise<CodexSessionCatalogHost> {
376379
try {
377380
const page = parseCatalogPage(
@@ -387,6 +390,7 @@ async function listGatewayHost(params: {
387390
bindingStore: params.bindingStore,
388391
config: params.config,
389392
runtime: params.runtime,
393+
sessionEntries: params.sessionEntries,
390394
});
391395
return {
392396
hostId: CODEX_LOCAL_SESSION_HOST_ID,
@@ -419,6 +423,7 @@ async function listCodexSessionCatalog(params: {
419423
control: CodexSessionCatalogControl;
420424
query?: CodexSessionCatalogParams;
421425
onHost?: (host: CodexSessionCatalogHost) => void;
426+
sessionEntries?: SessionCatalogEntrySnapshot;
422427
}): Promise<CodexSessionCatalogResult> {
423428
const query = readGatewayParams(params.query);
424429
const requestedHostIds = query.hostIds ? new Set(query.hostIds) : undefined;
@@ -431,6 +436,7 @@ async function listCodexSessionCatalog(params: {
431436
control: params.control,
432437
query,
433438
runtime: params.runtime,
439+
sessionEntries: params.sessionEntries,
434440
}),
435441
]
436442
: [];
@@ -470,6 +476,7 @@ async function listCodexSessionCatalog(params: {
470476
const adoptedNodeSessions = listNodeAdoptedSessionEntries({
471477
config: params.config,
472478
runtime: params.runtime,
479+
sessionEntries: params.sessionEntries,
473480
});
474481
const nodeHosts = nodes.toSorted(compareNodeLabels).map(async (node) => {
475482
const host = await listPairedNode({
@@ -672,44 +679,44 @@ async function listAdoptedSessionEntries(params: {
672679
bindingStore: CodexAppServerBindingStore;
673680
config?: OpenClawConfig;
674681
runtime: PluginRuntime;
682+
sessionEntries?: SessionCatalogEntrySnapshot;
675683
}): Promise<Map<string, AdoptedSessionEntry>> {
676684
const adopted = new Map<string, AdoptedSessionEntry>();
677-
for (const agentId of listSupervisionAgentIds(params.config ?? {})) {
678-
for (const { entry, sessionKey } of params.runtime.agent.session.listSessionEntries({
679-
agentId,
680-
readOnly: true,
681-
})) {
682-
const sessionKeyRest = adoptionSessionKeyRest(sessionKey);
683-
if (
684-
!sessionKeyRest.startsWith(CODEX_SUPERVISION_SESSION_KEY_PREFIX) ||
685-
entry.initializationPending === true ||
686-
entry.agentHarnessId !== "codex" ||
687-
entry.modelSelectionLocked !== true
688-
) {
689-
continue;
690-
}
691-
const sessionId = entry.sessionId?.trim();
692-
if (!sessionId) {
693-
continue;
694-
}
695-
const binding = await params.bindingStore.read(
696-
sessionBindingIdentity({ sessionId, sessionKey, config: params.config }),
697-
);
698-
const sourceThreadId = binding?.supervisionSourceThreadId?.trim();
699-
const boundThreadId = binding?.threadId.trim();
700-
if (
701-
binding?.connectionScope !== "supervision" ||
702-
!sourceThreadId ||
703-
!boundThreadId ||
704-
sessionKeyRest !== adoptionSessionKey(sourceThreadId)
705-
) {
706-
continue;
707-
}
708-
if (adopted.has(sourceThreadId)) {
709-
throw new Error(`multiple OpenClaw sessions adopt Codex thread ${sourceThreadId}`);
710-
}
711-
adopted.set(sourceThreadId, { key: sessionKey, sessionId, agentId, boundThreadId });
685+
for (const { agentId, entry, sessionKey } of listSessionCatalogEntries({
686+
config: params.config ?? {},
687+
runtime: params.runtime,
688+
sessionEntries: params.sessionEntries,
689+
})) {
690+
const sessionKeyRest = adoptionSessionKeyRest(sessionKey);
691+
if (
692+
!sessionKeyRest.startsWith(CODEX_SUPERVISION_SESSION_KEY_PREFIX) ||
693+
entry.initializationPending === true ||
694+
entry.agentHarnessId !== "codex" ||
695+
entry.modelSelectionLocked !== true
696+
) {
697+
continue;
698+
}
699+
const sessionId = entry.sessionId?.trim();
700+
if (!sessionId) {
701+
continue;
702+
}
703+
const binding = await params.bindingStore.read(
704+
sessionBindingIdentity({ sessionId, sessionKey, config: params.config }),
705+
);
706+
const sourceThreadId = binding?.supervisionSourceThreadId?.trim();
707+
const boundThreadId = binding?.threadId.trim();
708+
if (
709+
binding?.connectionScope !== "supervision" ||
710+
!sourceThreadId ||
711+
!boundThreadId ||
712+
sessionKeyRest !== adoptionSessionKey(sourceThreadId)
713+
) {
714+
continue;
715+
}
716+
if (adopted.has(sourceThreadId)) {
717+
throw new Error(`multiple OpenClaw sessions adopt Codex thread ${sourceThreadId}`);
712718
}
719+
adopted.set(sourceThreadId, { key: sessionKey, sessionId, agentId, boundThreadId });
713720
}
714721
return adopted;
715722
}
@@ -1266,7 +1273,7 @@ function registerCodexSessionCatalog(params: {
12661273
),
12671274
list: async (query) => {
12681275
const localTerminalAvailable = resolveLocalCodexTerminalExecutable() !== undefined;
1269-
const { onHost, ...gatewayQuery } = query;
1276+
const { onHost, sessionEntries, ...gatewayQuery } = query;
12701277
const mapHost = (host: CodexSessionCatalogHost) =>
12711278
toGenericCatalogHost(host, localTerminalAvailable);
12721279
return (
@@ -1276,6 +1283,7 @@ function registerCodexSessionCatalog(params: {
12761283
runtime: params.api.runtime,
12771284
control: params.control,
12781285
query: gatewayQuery,
1286+
sessionEntries,
12791287
...(onHost ? { onHost: (host) => onHost(mapHost(host)) } : {}),
12801288
})
12811289
).hosts.map(mapHost);
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import type {
2+
SessionCatalogHost,
3+
SessionCatalogSession,
4+
} from "../../../packages/gateway-protocol/src/index.js";
5+
import type { SessionEntry } from "../../config/sessions.js";
6+
import {
7+
listSessionEntriesReadOnly,
8+
type SessionEntrySummary,
9+
} from "../../config/sessions/session-accessor.js";
10+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
11+
import type { SessionCatalogEntrySnapshot } from "../../plugins/session-catalog.js";
12+
import { normalizeAgentId, resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
13+
import { resolveStoredSessionKeyForAgentStore } from "../session-store-key.js";
14+
import { projectSessionActor } from "../session-utils-row.js";
15+
16+
type SessionCatalogRequestEntrySnapshot = {
17+
sessionEntries: SessionCatalogEntrySnapshot;
18+
projectHostCreatedActors: (host: SessionCatalogHost) => SessionCatalogHost;
19+
};
20+
21+
export function createSessionCatalogRequestEntrySnapshot(params: {
22+
cfg: OpenClawConfig;
23+
fallbackAgentId: string;
24+
}): SessionCatalogRequestEntrySnapshot {
25+
const entriesByAgentId = new Map<string, readonly SessionEntrySummary[]>();
26+
const entryIndexByAgentId = new Map<string, ReadonlyMap<string, SessionEntry>>();
27+
const actorBySessionKey = new Map<string, SessionCatalogSession["createdActor"]>();
28+
29+
const entriesForAgent = (rawAgentId: string): readonly SessionEntrySummary[] => {
30+
const agentId = normalizeAgentId(rawAgentId);
31+
if (!entriesByAgentId.has(agentId)) {
32+
entriesByAgentId.set(agentId, listSessionEntriesReadOnly({ agentId }));
33+
}
34+
return entriesByAgentId.get(agentId) ?? [];
35+
};
36+
37+
const entryIndexForAgent = (agentId: string): ReadonlyMap<string, SessionEntry> => {
38+
const normalizedAgentId = normalizeAgentId(agentId);
39+
const cached = entryIndexByAgentId.get(normalizedAgentId);
40+
if (cached) {
41+
return cached;
42+
}
43+
const index = new Map(
44+
entriesForAgent(normalizedAgentId).map(({ sessionKey, entry }) => [sessionKey, entry]),
45+
);
46+
entryIndexByAgentId.set(normalizedAgentId, index);
47+
return index;
48+
};
49+
50+
const createdActorForSession = (sessionKey: string): SessionCatalogSession["createdActor"] => {
51+
if (actorBySessionKey.has(sessionKey)) {
52+
return actorBySessionKey.get(sessionKey);
53+
}
54+
const agentId = resolveAgentIdFromSessionKey(sessionKey, params.fallbackAgentId);
55+
const index = entryIndexForAgent(agentId);
56+
const canonicalKey = resolveStoredSessionKeyForAgentStore({
57+
cfg: params.cfg,
58+
agentId,
59+
sessionKey,
60+
});
61+
const candidates = new Set([sessionKey, canonicalKey]);
62+
let freshest: SessionEntry | undefined;
63+
for (const key of candidates) {
64+
const entry = index.get(key);
65+
if (entry && (!freshest || (entry.updatedAt ?? 0) > (freshest.updatedAt ?? 0))) {
66+
freshest = entry;
67+
}
68+
}
69+
const actor = projectSessionActor(freshest?.createdActor);
70+
actorBySessionKey.set(sessionKey, actor);
71+
return actor;
72+
};
73+
74+
return {
75+
sessionEntries: { entriesForAgent },
76+
projectHostCreatedActors: (host) => ({
77+
...host,
78+
sessions: host.sessions.map(({ createdActor: _providerCreatedActor, ...session }) => {
79+
const createdActor = session.sessionKey
80+
? createdActorForSession(session.sessionKey)
81+
: undefined;
82+
return createdActor ? { ...session, createdActor } : session;
83+
}),
84+
}),
85+
};
86+
}

0 commit comments

Comments
 (0)