File size: 12,266 Bytes
fc93158 | 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | /**
* Session memory hook handler
*
* Saves session context to memory when /new or /reset command is triggered
* Creates a new dated memory file with LLM-generated slug
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
resolveAgentIdByWorkspacePath,
resolveAgentWorkspaceDir,
} from "../../../agents/agent-scope.js";
import type { OpenClawConfig } from "../../../config/config.js";
import { resolveStateDir } from "../../../config/paths.js";
import { writeFileWithinRoot } from "../../../infra/fs-safe.js";
import { createSubsystemLogger } from "../../../logging/subsystem.js";
import {
parseAgentSessionKey,
resolveAgentIdFromSessionKey,
toAgentStoreSessionKey,
} from "../../../routing/session-key.js";
import { hasInterSessionUserProvenance } from "../../../sessions/input-provenance.js";
import { resolveHookConfig } from "../../config.js";
import type { HookHandler } from "../../hooks.js";
import { generateSlugViaLLM } from "../../llm-slug-generator.js";
const log = createSubsystemLogger("hooks/session-memory");
function resolveDisplaySessionKey(params: {
cfg?: OpenClawConfig;
workspaceDir?: string;
sessionKey: string;
}): string {
if (!params.cfg || !params.workspaceDir) {
return params.sessionKey;
}
const workspaceAgentId = resolveAgentIdByWorkspacePath(params.cfg, params.workspaceDir);
const parsed = parseAgentSessionKey(params.sessionKey);
if (!workspaceAgentId || !parsed || workspaceAgentId === parsed.agentId) {
return params.sessionKey;
}
return toAgentStoreSessionKey({
agentId: workspaceAgentId,
requestKey: parsed.rest,
});
}
/**
* Read recent messages from session file for slug generation
*/
async function getRecentSessionContent(
sessionFilePath: string,
messageCount: number = 15,
): Promise<string | null> {
try {
const content = await fs.readFile(sessionFilePath, "utf-8");
const lines = content.trim().split("\n");
// Parse JSONL and extract user/assistant messages first
const allMessages: string[] = [];
for (const line of lines) {
try {
const entry = JSON.parse(line);
// Session files have entries with type="message" containing a nested message object
if (entry.type === "message" && entry.message) {
const msg = entry.message;
const role = msg.role;
if ((role === "user" || role === "assistant") && msg.content) {
if (role === "user" && hasInterSessionUserProvenance(msg)) {
continue;
}
// Extract text content
const text = Array.isArray(msg.content)
? // oxlint-disable-next-line typescript/no-explicit-any
msg.content.find((c: any) => c.type === "text")?.text
: msg.content;
if (text && !text.startsWith("/")) {
allMessages.push(`${role}: ${text}`);
}
}
}
} catch {
// Skip invalid JSON lines
}
}
// Then slice to get exactly messageCount messages
const recentMessages = allMessages.slice(-messageCount);
return recentMessages.join("\n");
} catch {
return null;
}
}
/**
* Try the active transcript first; if /new already rotated it,
* fallback to the latest .jsonl.reset.* sibling.
*/
async function getRecentSessionContentWithResetFallback(
sessionFilePath: string,
messageCount: number = 15,
): Promise<string | null> {
const primary = await getRecentSessionContent(sessionFilePath, messageCount);
if (primary) {
return primary;
}
try {
const dir = path.dirname(sessionFilePath);
const base = path.basename(sessionFilePath);
const resetPrefix = `${base}.reset.`;
const files = await fs.readdir(dir);
const resetCandidates = files.filter((name) => name.startsWith(resetPrefix)).toSorted();
if (resetCandidates.length === 0) {
return primary;
}
const latestResetPath = path.join(dir, resetCandidates[resetCandidates.length - 1]);
const fallback = await getRecentSessionContent(latestResetPath, messageCount);
if (fallback) {
log.debug("Loaded session content from reset fallback", {
sessionFilePath,
latestResetPath,
});
}
return fallback || primary;
} catch {
return primary;
}
}
function stripResetSuffix(fileName: string): string {
const resetIndex = fileName.indexOf(".reset.");
return resetIndex === -1 ? fileName : fileName.slice(0, resetIndex);
}
async function findPreviousSessionFile(params: {
sessionsDir: string;
currentSessionFile?: string;
sessionId?: string;
}): Promise<string | undefined> {
try {
const files = await fs.readdir(params.sessionsDir);
const fileSet = new Set(files);
const baseFromReset = params.currentSessionFile
? stripResetSuffix(path.basename(params.currentSessionFile))
: undefined;
if (baseFromReset && fileSet.has(baseFromReset)) {
return path.join(params.sessionsDir, baseFromReset);
}
const trimmedSessionId = params.sessionId?.trim();
if (trimmedSessionId) {
const canonicalFile = `${trimmedSessionId}.jsonl`;
if (fileSet.has(canonicalFile)) {
return path.join(params.sessionsDir, canonicalFile);
}
const topicVariants = files
.filter(
(name) =>
name.startsWith(`${trimmedSessionId}-topic-`) &&
name.endsWith(".jsonl") &&
!name.includes(".reset."),
)
.toSorted()
.toReversed();
if (topicVariants.length > 0) {
return path.join(params.sessionsDir, topicVariants[0]);
}
}
if (!params.currentSessionFile) {
return undefined;
}
const nonResetJsonl = files
.filter((name) => name.endsWith(".jsonl") && !name.includes(".reset."))
.toSorted()
.toReversed();
if (nonResetJsonl.length > 0) {
return path.join(params.sessionsDir, nonResetJsonl[0]);
}
} catch {
// Ignore directory read errors.
}
return undefined;
}
/**
* Save session context to memory when /new or /reset command is triggered
*/
const saveSessionToMemory: HookHandler = async (event) => {
// Only trigger on reset/new commands
const isResetCommand = event.action === "new" || event.action === "reset";
if (event.type !== "command" || !isResetCommand) {
return;
}
try {
log.debug("Hook triggered for reset/new command", { action: event.action });
const context = event.context || {};
const cfg = context.cfg as OpenClawConfig | undefined;
const contextWorkspaceDir =
typeof context.workspaceDir === "string" && context.workspaceDir.trim().length > 0
? context.workspaceDir
: undefined;
const agentId = resolveAgentIdFromSessionKey(event.sessionKey);
const workspaceDir =
contextWorkspaceDir ||
(cfg
? resolveAgentWorkspaceDir(cfg, agentId)
: path.join(resolveStateDir(process.env, os.homedir), "workspace"));
const displaySessionKey = resolveDisplaySessionKey({
cfg,
workspaceDir: contextWorkspaceDir,
sessionKey: event.sessionKey,
});
const memoryDir = path.join(workspaceDir, "memory");
await fs.mkdir(memoryDir, { recursive: true });
// Get today's date for filename
const now = new Date(event.timestamp);
const dateStr = now.toISOString().split("T")[0]; // YYYY-MM-DD
// Generate descriptive slug from session using LLM
// Prefer previousSessionEntry (old session before /new) over current (which may be empty)
const sessionEntry = (context.previousSessionEntry || context.sessionEntry || {}) as Record<
string,
unknown
>;
const currentSessionId = sessionEntry.sessionId as string;
let currentSessionFile = (sessionEntry.sessionFile as string) || undefined;
// If sessionFile is empty or looks like a new/reset file, try to find the previous session file.
if (!currentSessionFile || currentSessionFile.includes(".reset.")) {
const sessionsDirs = new Set<string>();
if (currentSessionFile) {
sessionsDirs.add(path.dirname(currentSessionFile));
}
sessionsDirs.add(path.join(workspaceDir, "sessions"));
for (const sessionsDir of sessionsDirs) {
const recoveredSessionFile = await findPreviousSessionFile({
sessionsDir,
currentSessionFile,
sessionId: currentSessionId,
});
if (!recoveredSessionFile) {
continue;
}
currentSessionFile = recoveredSessionFile;
log.debug("Found previous session file", { file: currentSessionFile });
break;
}
}
log.debug("Session context resolved", {
sessionId: currentSessionId,
sessionFile: currentSessionFile,
hasCfg: Boolean(cfg),
});
const sessionFile = currentSessionFile || undefined;
// Read message count from hook config (default: 15)
const hookConfig = resolveHookConfig(cfg, "session-memory");
const messageCount =
typeof hookConfig?.messages === "number" && hookConfig.messages > 0
? hookConfig.messages
: 15;
let slug: string | null = null;
let sessionContent: string | null = null;
if (sessionFile) {
// Get recent conversation content, with fallback to rotated reset transcript.
sessionContent = await getRecentSessionContentWithResetFallback(sessionFile, messageCount);
log.debug("Session content loaded", {
length: sessionContent?.length ?? 0,
messageCount,
});
// Avoid calling the model provider in unit tests; keep hooks fast and deterministic.
const isTestEnv =
process.env.OPENCLAW_TEST_FAST === "1" ||
process.env.VITEST === "true" ||
process.env.VITEST === "1" ||
process.env.NODE_ENV === "test";
const allowLlmSlug = !isTestEnv && hookConfig?.llmSlug !== false;
if (sessionContent && cfg && allowLlmSlug) {
log.debug("Calling generateSlugViaLLM...");
// Use LLM to generate a descriptive slug
slug = await generateSlugViaLLM({ sessionContent, cfg });
log.debug("Generated slug", { slug });
}
}
// If no slug, use timestamp
if (!slug) {
const timeSlug = now.toISOString().split("T")[1].split(".")[0].replace(/:/g, "");
slug = timeSlug.slice(0, 4); // HHMM
log.debug("Using fallback timestamp slug", { slug });
}
// Create filename with date and slug
const filename = `${dateStr}-${slug}.md`;
const memoryFilePath = path.join(memoryDir, filename);
log.debug("Memory file path resolved", {
filename,
path: memoryFilePath.replace(os.homedir(), "~"),
});
// Format time as HH:MM:SS UTC
const timeStr = now.toISOString().split("T")[1].split(".")[0];
// Extract context details
const sessionId = (sessionEntry.sessionId as string) || "unknown";
const source = (context.commandSource as string) || "unknown";
// Build Markdown entry
const entryParts = [
`# Session: ${dateStr} ${timeStr} UTC`,
"",
`- **Session Key**: ${displaySessionKey}`,
`- **Session ID**: ${sessionId}`,
`- **Source**: ${source}`,
"",
];
// Include conversation content if available
if (sessionContent) {
entryParts.push("## Conversation Summary", "", sessionContent, "");
}
const entry = entryParts.join("\n");
// Write under memory root with alias-safe file validation.
await writeFileWithinRoot({
rootDir: memoryDir,
relativePath: filename,
data: entry,
encoding: "utf-8",
});
log.debug("Memory file written successfully");
// Log completion (but don't send user-visible confirmation - it's internal housekeeping)
const relPath = memoryFilePath.replace(os.homedir(), "~");
log.info(`Session context saved to ${relPath}`);
} catch (err) {
if (err instanceof Error) {
log.error("Failed to save session memory", {
errorName: err.name,
errorMessage: err.message,
stack: err.stack,
});
} else {
log.error("Failed to save session memory", { error: String(err) });
}
}
};
export default saveSessionToMemory;
|