-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-entry.js
More file actions
100 lines (88 loc) · 4.03 KB
/
Copy pathsession-entry.js
File metadata and controls
100 lines (88 loc) · 4.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
const require = createRequire(import.meta.url);
function resolveHomePath(value) {
const raw = String(value || "").trim();
if (raw === "~") return homedir();
if (raw.startsWith("~/")) return join(homedir(), raw.slice(2));
return raw;
}
function resolveOpenClawHome() {
return resolveHomePath(process.env.OPENCLAW_STATE_DIR || process.env.OPENCLAW_HOME || join(homedir(), ".openclaw"));
}
export function extractAgentId(sessionKey, ctx = {}) {
if (typeof ctx.agentId === "string" && ctx.agentId.trim()) return ctx.agentId.trim();
const match = String(sessionKey || "").match(/^agent:([^:]+):/);
return match ? match[1] : "main";
}
function resolveLegacySessionStorePath(cfg, agentId) {
const safeAgentId = String(agentId || "main").trim().toLowerCase() || "main";
const store = typeof cfg?.session?.store === "string" ? cfg.session.store.trim() : "";
if (store) return resolve(resolveHomePath(store.replaceAll("{agentId}", safeAgentId)));
return join(resolveOpenClawHome(), "agents", safeAgentId, "sessions", "sessions.json");
}
function readLegacySessionEntry(cfg, sessionKey, ctx) {
const storePath = resolveLegacySessionStorePath(cfg, extractAgentId(sessionKey, ctx));
if (!existsSync(storePath)) return null;
const store = JSON.parse(readFileSync(storePath, "utf8"));
const entry = store?.[sessionKey] ?? store?.sessions?.[sessionKey];
return entry && typeof entry === "object" ? entry : null;
}
async function loadDefaultRuntime() {
let runtimePath;
try {
runtimePath = require.resolve("openclaw/plugin-sdk/session-store-runtime");
} catch (error) {
const message = String(error?.message || error);
if (error?.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || (
error?.code === "MODULE_NOT_FOUND" && message.includes("openclaw/plugin-sdk/session-store-runtime")
)) return null;
throw error;
}
return await import(pathToFileURL(runtimePath).href);
}
export function createSessionEntryReader({ loadRuntime = loadDefaultRuntime, legacyReader = readLegacySessionEntry, logger = console } = {}) {
let runtimePromise;
const getRuntime = async () => {
if (!runtimePromise) runtimePromise = Promise.resolve().then(loadRuntime).then((runtime) => (
runtime && typeof runtime.getSessionEntry === "function" ? runtime : null
)).catch((error) => ({ error }));
return runtimePromise;
};
return {
async read({ cfg, sessionKey, ctx = {} }) {
if (ctx?.sessionEntry && typeof ctx.sessionEntry === "object") {
return { entry: ctx.sessionEntry, source: "hook" };
}
const runtime = await getRuntime();
if (runtime?.error) {
logger.error?.(`[topic-context] session runtime lookup unavailable: ${String(runtime.error)}`);
return { entry: null, source: "runtime-error" };
}
if (runtime) {
const agentId = extractAgentId(sessionKey, ctx);
const params = { sessionKey, agentId, env: process.env };
if (typeof cfg?.session?.store === "string" && typeof runtime.resolveStorePath === "function") {
params.storePath = runtime.resolveStorePath(cfg.session.store, { agentId, env: process.env });
}
try {
const entry = await runtime.getSessionEntry(params);
return { entry: entry && typeof entry === "object" ? entry : null, source: "canonical" };
} catch (error) {
logger.error?.(`[topic-context] canonical session entry lookup failed: ${String(error)}`);
return { entry: null, source: "canonical-error" };
}
}
try {
return { entry: legacyReader(cfg, sessionKey, ctx), source: "legacy" };
} catch (error) {
logger.error?.(`[topic-context] legacy session entry lookup failed: ${String(error)}`);
return { entry: null, source: "legacy-error" };
}
},
};
}
export const sessionEntryReader = createSessionEntryReader();