Files
openclaw/src/auto-reply/reply/session.ts

494 lines
18 KiB
TypeScript
Raw Normal View History

2026-01-04 05:47:21 +01:00
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { CURRENT_SESSION_VERSION, SessionManager } from "@mariozechner/pi-coding-agent";
import { resolveSessionAgentId } from "../../agents/agent-scope.js";
import { normalizeChatType } from "../../channels/chat-type.js";
import type { OpenClawConfig } from "../../config/config.js";
2026-01-04 05:47:21 +01:00
import {
DEFAULT_RESET_TRIGGERS,
deriveSessionMetaPatch,
evaluateSessionFreshness,
2026-01-04 05:47:21 +01:00
type GroupKeyResolution,
loadSessionStore,
feat: thread-bound subagents on Discord (#21805) * docs: thread-bound subagents plan * docs: add exact thread-bound subagent implementation touchpoints * Docs: prioritize auto thread-bound subagent flow * Docs: add ACP harness thread-binding extensions * Discord: add thread-bound session routing and auto-bind spawn flow * Subagents: add focus commands and ACP/session binding lifecycle hooks * Tests: cover thread bindings, focus commands, and ACP unbind hooks * Docs: add plugin-hook appendix for thread-bound subagents * Plugins: add subagent lifecycle hook events * Core: emit subagent lifecycle hooks and decouple Discord bindings * Discord: handle subagent bind lifecycle via plugin hooks * Subagents: unify completion finalizer and split registry modules * Add subagent lifecycle events module * Hooks: fix subagent ended context key * Discord: share thread bindings across ESM and Jiti * Subagents: add persistent sessions_spawn mode for thread-bound sessions * Subagents: clarify thread intro and persistent completion copy * test(subagents): stabilize sessions_spawn lifecycle cleanup assertions * Discord: add thread-bound session TTL with auto-unfocus * Subagents: fail session spawns when thread bind fails * Subagents: cover thread session failure cleanup paths * Session: add thread binding TTL config and /session ttl controls * Tests: align discord reaction expectations * Agent: persist sessionFile for keyed subagent sessions * Discord: normalize imports after conflict resolution * Sessions: centralize sessionFile resolve/persist helper * Discord: harden thread-bound subagent session routing * Rebase: resolve upstream/main conflicts * Subagents: move thread binding into hooks and split bindings modules * Docs: add channel-agnostic subagent routing hook plan * Agents: decouple subagent routing from Discord * Discord: refactor thread-bound subagent flows * Subagents: prevent duplicate end hooks and orphaned failed sessions * Refactor: split subagent command and provider phases * Subagents: honor hook delivery target overrides * Discord: add thread binding kill switches and refresh plan doc * Discord: fix thread bind channel resolution * Routing: centralize account id normalization * Discord: clean up thread bindings on startup failures * Discord: add startup cleanup regression tests * Docs: add long-term thread-bound subagent architecture * Docs: split session binding plan and dedupe thread-bound doc * Subagents: add channel-agnostic session binding routing * Subagents: stabilize announce completion routing tests * Subagents: cover multi-bound completion routing * Subagents: suppress lifecycle hooks on failed thread bind * tests: fix discord provider mock typing regressions * docs/protocol: sync slash command aliases and delete param models * fix: add changelog entry for Discord thread-bound subagents (#21805) (thanks @onutc) --------- Co-authored-by: Shadow <hi@shadowing.dev>
2026-02-21 16:14:55 +01:00
resolveAndPersistSessionFile,
resolveChannelResetConfig,
resolveThreadFlag,
resolveSessionResetPolicy,
resolveSessionResetType,
2026-01-04 05:47:21 +01:00
resolveGroupSessionKey,
resolveSessionFilePath,
2026-01-04 05:47:21 +01:00
resolveSessionKey,
2026-01-07 22:56:50 +00:00
resolveSessionTranscriptPath,
2026-01-04 05:47:21 +01:00
resolveStorePath,
type SessionEntry,
2026-01-04 07:05:04 +01:00
type SessionScope,
updateSessionStore,
2026-01-04 05:47:21 +01:00
} from "../../config/sessions.js";
import type { TtsAutoMode } from "../../config/types.tts.js";
import { archiveSessionTranscripts } from "../../gateway/session-utils.fs.js";
fix: unify session maintenance and cron run pruning (#13083) * fix: prune stale session entries, cap entry count, and rotate sessions.json The sessions.json file grows unbounded over time. Every heartbeat tick (default: 30m) triggers multiple full rewrites, and session keys from groups, threads, and DMs accumulate indefinitely with large embedded objects (skillsSnapshot, systemPromptReport). At >50MB the synchronous JSON parse blocks the event loop, causing Telegram webhook timeouts and effectively taking the bot down. Three mitigations, all running inside saveSessionStoreUnlocked() on every write: 1. Prune stale entries: remove entries with updatedAt older than 30 days (configurable via session.maintenance.pruneDays in openclaw.json) 2. Cap entry count: keep only the 500 most recently updated entries (configurable via session.maintenance.maxEntries). Entries without updatedAt are evicted first. 3. File rotation: if the existing sessions.json exceeds 10MB before a write, rename it to sessions.json.bak.{timestamp} and keep only the 3 most recent backups (configurable via session.maintenance.rotateBytes). All three thresholds are configurable under session.maintenance in openclaw.json with Zod validation. No env vars. Existing tests updated to use Date.now() instead of epoch-relative timestamps (1, 2, 3) that would be incorrectly pruned as stale. 27 new tests covering pruning, capping, rotation, and integration scenarios. * feat: auto-prune expired cron run sessions (#12289) Add TTL-based reaper for isolated cron run sessions that accumulate indefinitely in sessions.json. New config option: cron.sessionRetention: string | false (default: '24h') The reaper runs piggy-backed on the cron timer tick, self-throttled to sweep at most every 5 minutes. It removes session entries matching the pattern cron:<jobId>:run:<uuid> whose updatedAt + retention < now. Design follows the Kubernetes ttlSecondsAfterFinished pattern: - Sessions are persisted normally (observability/debugging) - A periodic reaper prunes expired entries - Configurable retention with sensible default - Set to false to disable pruning entirely Files changed: - src/config/types.cron.ts: Add sessionRetention to CronConfig - src/config/zod-schema.ts: Add Zod validation for sessionRetention - src/cron/session-reaper.ts: New reaper module (sweepCronRunSessions) - src/cron/session-reaper.test.ts: 12 tests covering all paths - src/cron/service/state.ts: Add cronConfig/sessionStorePath to deps - src/cron/service/timer.ts: Wire reaper into onTimer tick - src/gateway/server-cron.ts: Pass config and session store path to deps Closes #12289 * fix: sweep cron session stores per agent * docs: add changelog for session maintenance (#13083) (thanks @skyfallsin, @Glucksberg) * fix: add warn-only session maintenance mode * fix: warn-only maintenance defaults to active session * fix: deliver maintenance warnings to active session * docs: add session maintenance examples * fix: accept duration and size maintenance thresholds * refactor: share cron run session key check * fix: format issues and replace defaultRuntime.warn with console.warn --------- Co-authored-by: Pradeep Elankumaran <pradeepe@gmail.com> Co-authored-by: Glucksberg <markuscontasul@gmail.com> Co-authored-by: max <40643627+quotentiroler@users.noreply.github.com> Co-authored-by: quotentiroler <max.nussbaumer@maxhealth.tech>
2026-02-09 23:42:35 -05:00
import { deliverSessionMaintenanceWarning } from "../../infra/session-maintenance-warning.js";
import { createSubsystemLogger } from "../../logging/subsystem.js";
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
import { normalizeMainKey } from "../../routing/session-key.js";
import { normalizeSessionDeliveryFields } from "../../utils/delivery-context.js";
import { resolveCommandAuthorization } from "../command-auth.js";
import type { MsgContext, TemplateContext } from "../templating.js";
2026-01-17 04:04:05 +00:00
import { normalizeInboundTextNewlines } from "./inbound-text.js";
import { stripMentions, stripStructuralPrefixes } from "./mentions.js";
2026-01-04 05:47:21 +01:00
const log = createSubsystemLogger("session-init");
2026-01-04 05:47:21 +01:00
export type SessionInitResult = {
sessionCtx: TemplateContext;
sessionEntry: SessionEntry;
2026-01-17 01:31:39 +00:00
previousSessionEntry?: SessionEntry;
2026-01-04 05:47:21 +01:00
sessionStore: Record<string, SessionEntry>;
sessionKey: string;
sessionId: string;
isNewSession: boolean;
resetTriggered: boolean;
2026-01-04 05:47:21 +01:00
systemSent: boolean;
abortedLastRun: boolean;
storePath: string;
2026-01-04 07:05:04 +01:00
sessionScope: SessionScope;
2026-01-04 05:47:21 +01:00
groupResolution?: GroupKeyResolution;
isGroup: boolean;
bodyStripped?: string;
triggerBodyNormalized: string;
};
function forkSessionFromParent(params: {
parentEntry: SessionEntry;
agentId: string;
sessionsDir: string;
}): { sessionId: string; sessionFile: string } | null {
const parentSessionFile = resolveSessionFilePath(
params.parentEntry.sessionId,
params.parentEntry,
{ agentId: params.agentId, sessionsDir: params.sessionsDir },
);
if (!parentSessionFile || !fs.existsSync(parentSessionFile)) {
return null;
}
try {
const manager = SessionManager.open(parentSessionFile);
const leafId = manager.getLeafId();
if (leafId) {
const sessionFile = manager.createBranchedSession(leafId) ?? manager.getSessionFile();
const sessionId = manager.getSessionId();
if (sessionFile && sessionId) {
return { sessionId, sessionFile };
}
}
const sessionId = crypto.randomUUID();
const timestamp = new Date().toISOString();
const fileTimestamp = timestamp.replace(/[:.]/g, "-");
const sessionFile = path.join(manager.getSessionDir(), `${fileTimestamp}_${sessionId}.jsonl`);
const header = {
type: "session",
version: CURRENT_SESSION_VERSION,
id: sessionId,
timestamp,
cwd: manager.getCwd(),
parentSession: parentSessionFile,
};
fs.writeFileSync(sessionFile, `${JSON.stringify(header)}\n`, "utf-8");
return { sessionId, sessionFile };
} catch {
return null;
}
}
2026-01-04 05:47:21 +01:00
export async function initSessionState(params: {
ctx: MsgContext;
2026-01-30 03:15:10 +01:00
cfg: OpenClawConfig;
commandAuthorized: boolean;
2026-01-04 05:47:21 +01:00
}): Promise<SessionInitResult> {
const { ctx, cfg, commandAuthorized } = params;
// Native slash commands (Telegram/Discord/Slack) are delivered on a separate
// "slash session" key, but should mutate the target chat session.
const targetSessionKey =
ctx.CommandSource === "native" ? ctx.CommandTargetSessionKey?.trim() : undefined;
const sessionCtxForState =
targetSessionKey && targetSessionKey !== ctx.SessionKey
? { ...ctx, SessionKey: targetSessionKey }
: ctx;
2026-01-04 05:47:21 +01:00
const sessionCfg = cfg.session;
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
const agentId = resolveSessionAgentId({
sessionKey: sessionCtxForState.SessionKey,
config: cfg,
});
const groupResolution = resolveGroupSessionKey(sessionCtxForState) ?? undefined;
2026-01-04 05:47:21 +01:00
const resetTriggers = sessionCfg?.resetTriggers?.length
? sessionCfg.resetTriggers
: DEFAULT_RESET_TRIGGERS;
const sessionScope = sessionCfg?.scope ?? "per-sender";
const storePath = resolveStorePath(sessionCfg?.store, { agentId });
2026-01-04 05:47:21 +01:00
// CRITICAL: Skip cache to ensure fresh data when resolving session identity.
// Stale cache (especially with multiple gateway processes or on Windows where
// mtime granularity may miss rapid writes) can cause incorrect sessionId
// generation, leading to orphaned transcript files. See #17971.
const sessionStore: Record<string, SessionEntry> = loadSessionStore(storePath, {
skipCache: true,
});
2026-01-04 05:47:21 +01:00
let sessionKey: string | undefined;
let sessionEntry: SessionEntry;
2026-01-04 05:47:21 +01:00
let sessionId: string | undefined;
let isNewSession = false;
let bodyStripped: string | undefined;
let systemSent = false;
let abortedLastRun = false;
2026-01-17 01:31:39 +00:00
let resetTriggered = false;
2026-01-04 05:47:21 +01:00
let persistedThinking: string | undefined;
let persistedVerbose: string | undefined;
let persistedReasoning: string | undefined;
let persistedTtsAuto: TtsAutoMode | undefined;
2026-01-04 05:47:21 +01:00
let persistedModelOverride: string | undefined;
let persistedProviderOverride: string | undefined;
2026-01-17 04:04:05 +00:00
const normalizedChatType = normalizeChatType(ctx.ChatType);
2026-01-17 05:48:34 +00:00
const isGroup =
normalizedChatType != null && normalizedChatType !== "direct" ? true : Boolean(groupResolution);
2026-01-10 18:53:33 +01:00
// Prefer CommandBody/RawBody (clean message) for command detection; fall back
// to Body which may contain structural context (history, sender labels).
2026-01-17 04:04:05 +00:00
const commandSource = ctx.BodyForCommands ?? ctx.CommandBody ?? ctx.RawBody ?? ctx.Body ?? "";
// IMPORTANT: do NOT lowercase the entire command body.
// Users often pass case-sensitive arguments (e.g. filesystem paths on Linux).
// Command parsing downstream lowercases only the command token for matching.
const triggerBodyNormalized = stripStructuralPrefixes(commandSource).trim();
2026-01-04 05:47:21 +01:00
2026-01-10 18:53:33 +01:00
// Use CommandBody/RawBody for reset trigger matching (clean message without structural context).
const rawBody = commandSource;
2026-01-04 05:47:21 +01:00
const trimmedBody = rawBody.trim();
const resetAuthorized = resolveCommandAuthorization({
ctx,
cfg,
commandAuthorized,
}).isAuthorizedSender;
2026-01-04 05:47:21 +01:00
// Timestamp/message prefixes (e.g. "[Dec 4 17:35] ") are added by the
// web inbox before we get here. They prevented reset triggers like "/new"
// from matching, so strip structural wrappers when checking for resets.
const strippedForReset = isGroup
2026-01-08 22:57:08 +01:00
? stripMentions(triggerBodyNormalized, ctx, cfg, agentId)
2026-01-04 05:47:21 +01:00
: triggerBodyNormalized;
// Reset triggers are configured as lowercased commands (e.g. "/new"), but users may type
// "/NEW" etc. Match case-insensitively while keeping the original casing for any stripped body.
const trimmedBodyLower = trimmedBody.toLowerCase();
const strippedForResetLower = strippedForReset.toLowerCase();
2026-01-04 05:47:21 +01:00
for (const trigger of resetTriggers) {
if (!trigger) {
continue;
}
if (!resetAuthorized) {
break;
}
const triggerLower = trigger.toLowerCase();
if (trimmedBodyLower === triggerLower || strippedForResetLower === triggerLower) {
2026-01-04 05:47:21 +01:00
isNewSession = true;
bodyStripped = "";
2026-01-17 01:31:39 +00:00
resetTriggered = true;
2026-01-04 05:47:21 +01:00
break;
}
const triggerPrefixLower = `${triggerLower} `;
if (
trimmedBodyLower.startsWith(triggerPrefixLower) ||
strippedForResetLower.startsWith(triggerPrefixLower)
) {
2026-01-04 05:47:21 +01:00
isNewSession = true;
bodyStripped = strippedForReset.slice(trigger.length).trimStart();
2026-01-17 01:31:39 +00:00
resetTriggered = true;
2026-01-04 05:47:21 +01:00
break;
}
}
sessionKey = resolveSessionKey(sessionScope, sessionCtxForState, mainKey);
2026-01-04 05:47:21 +01:00
const entry = sessionStore[sessionKey];
2026-01-17 01:31:39 +00:00
const previousSessionEntry = resetTriggered && entry ? { ...entry } : undefined;
const now = Date.now();
const isThread = resolveThreadFlag({
sessionKey,
messageThreadId: ctx.MessageThreadId,
threadLabel: ctx.ThreadLabel,
threadStarterBody: ctx.ThreadStarterBody,
parentSessionKey: ctx.ParentSessionKey,
});
const resetType = resolveSessionResetType({ sessionKey, isGroup, isThread });
const channelReset = resolveChannelResetConfig({
sessionCfg,
channel:
groupResolution?.channel ??
(ctx.OriginatingChannel as string | undefined) ??
ctx.Surface ??
ctx.Provider,
});
const resetPolicy = resolveSessionResetPolicy({
sessionCfg,
resetType,
resetOverride: channelReset,
});
const freshEntry = entry
? evaluateSessionFreshness({ updatedAt: entry.updatedAt, now, policy: resetPolicy }).fresh
: false;
2026-01-04 05:47:21 +01:00
if (!isNewSession && freshEntry) {
2026-01-04 05:47:21 +01:00
sessionId = entry.sessionId;
systemSent = entry.systemSent ?? false;
abortedLastRun = entry.abortedLastRun ?? false;
persistedThinking = entry.thinkingLevel;
persistedVerbose = entry.verboseLevel;
persistedReasoning = entry.reasoningLevel;
persistedTtsAuto = entry.ttsAuto;
2026-01-04 05:47:21 +01:00
persistedModelOverride = entry.modelOverride;
persistedProviderOverride = entry.providerOverride;
} else {
sessionId = crypto.randomUUID();
isNewSession = true;
systemSent = false;
abortedLastRun = false;
// When a reset trigger (/new, /reset) starts a new session, carry over
// user-set behavior overrides (verbose, thinking, reasoning, ttsAuto)
// so the user doesn't have to re-enable them every time.
if (resetTriggered && entry) {
persistedThinking = entry.thinkingLevel;
persistedVerbose = entry.verboseLevel;
persistedReasoning = entry.reasoningLevel;
persistedTtsAuto = entry.ttsAuto;
persistedModelOverride = entry.modelOverride;
persistedProviderOverride = entry.providerOverride;
}
2026-01-04 05:47:21 +01:00
}
const baseEntry = !isNewSession && freshEntry ? entry : undefined;
// Track the originating channel/to for announce routing (subagent announce-back).
2026-01-17 07:59:53 +00:00
const lastChannelRaw = (ctx.OriginatingChannel as string | undefined) || baseEntry?.lastChannel;
const lastToRaw = ctx.OriginatingTo || ctx.To || baseEntry?.lastTo;
const lastAccountIdRaw = ctx.AccountId || baseEntry?.lastAccountId;
// Only fall back to persisted threadId for thread sessions. Non-thread
// sessions (e.g. DM without topics) must not inherit a stale threadId from a
// previous interaction that happened inside a topic/thread.
const lastThreadIdRaw = ctx.MessageThreadId || (isThread ? baseEntry?.lastThreadId : undefined);
const deliveryFields = normalizeSessionDeliveryFields({
deliveryContext: {
channel: lastChannelRaw,
to: lastToRaw,
accountId: lastAccountIdRaw,
threadId: lastThreadIdRaw,
},
});
const lastChannel = deliveryFields.lastChannel ?? lastChannelRaw;
const lastTo = deliveryFields.lastTo ?? lastToRaw;
const lastAccountId = deliveryFields.lastAccountId ?? lastAccountIdRaw;
const lastThreadId = deliveryFields.lastThreadId ?? lastThreadIdRaw;
2026-01-04 05:47:21 +01:00
sessionEntry = {
...baseEntry,
sessionId,
updatedAt: Date.now(),
systemSent,
abortedLastRun,
// Persist previously stored thinking/verbose levels when present.
thinkingLevel: persistedThinking ?? baseEntry?.thinkingLevel,
verboseLevel: persistedVerbose ?? baseEntry?.verboseLevel,
reasoningLevel: persistedReasoning ?? baseEntry?.reasoningLevel,
ttsAuto: persistedTtsAuto ?? baseEntry?.ttsAuto,
2026-01-09 02:21:17 +00:00
responseUsage: baseEntry?.responseUsage,
2026-01-04 05:47:21 +01:00
modelOverride: persistedModelOverride ?? baseEntry?.modelOverride,
providerOverride: persistedProviderOverride ?? baseEntry?.providerOverride,
sendPolicy: baseEntry?.sendPolicy,
queueMode: baseEntry?.queueMode,
queueDebounceMs: baseEntry?.queueDebounceMs,
queueCap: baseEntry?.queueCap,
queueDrop: baseEntry?.queueDrop,
displayName: baseEntry?.displayName,
chatType: baseEntry?.chatType,
channel: baseEntry?.channel,
2026-01-17 08:46:19 +00:00
groupId: baseEntry?.groupId,
2026-01-04 05:47:21 +01:00
subject: baseEntry?.subject,
2026-01-17 09:01:36 +00:00
groupChannel: baseEntry?.groupChannel,
2026-01-04 05:47:21 +01:00
space: baseEntry?.space,
deliveryContext: deliveryFields.deliveryContext,
// Track originating channel for subagent announce routing.
lastChannel,
lastTo,
lastAccountId,
lastThreadId,
2026-01-04 05:47:21 +01:00
};
const metaPatch = deriveSessionMetaPatch({
ctx: sessionCtxForState,
sessionKey,
existing: sessionEntry,
groupResolution,
});
if (metaPatch) {
sessionEntry = { ...sessionEntry, ...metaPatch };
}
if (!sessionEntry.chatType) {
2026-01-04 05:47:21 +01:00
sessionEntry.chatType = "direct";
}
const threadLabel = ctx.ThreadLabel?.trim();
if (threadLabel) {
sessionEntry.displayName = threadLabel;
}
const parentSessionKey = ctx.ParentSessionKey?.trim();
if (
isNewSession &&
parentSessionKey &&
parentSessionKey !== sessionKey &&
sessionStore[parentSessionKey]
) {
log.warn(
`forking from parent session: parentKey=${parentSessionKey} → sessionKey=${sessionKey} ` +
`parentTokens=${sessionStore[parentSessionKey].totalTokens ?? "?"}`,
);
const forked = forkSessionFromParent({
parentEntry: sessionStore[parentSessionKey],
agentId,
sessionsDir: path.dirname(storePath),
});
if (forked) {
sessionId = forked.sessionId;
sessionEntry.sessionId = forked.sessionId;
sessionEntry.sessionFile = forked.sessionFile;
log.warn(`forked session created: file=${forked.sessionFile}`);
}
}
feat: thread-bound subagents on Discord (#21805) * docs: thread-bound subagents plan * docs: add exact thread-bound subagent implementation touchpoints * Docs: prioritize auto thread-bound subagent flow * Docs: add ACP harness thread-binding extensions * Discord: add thread-bound session routing and auto-bind spawn flow * Subagents: add focus commands and ACP/session binding lifecycle hooks * Tests: cover thread bindings, focus commands, and ACP unbind hooks * Docs: add plugin-hook appendix for thread-bound subagents * Plugins: add subagent lifecycle hook events * Core: emit subagent lifecycle hooks and decouple Discord bindings * Discord: handle subagent bind lifecycle via plugin hooks * Subagents: unify completion finalizer and split registry modules * Add subagent lifecycle events module * Hooks: fix subagent ended context key * Discord: share thread bindings across ESM and Jiti * Subagents: add persistent sessions_spawn mode for thread-bound sessions * Subagents: clarify thread intro and persistent completion copy * test(subagents): stabilize sessions_spawn lifecycle cleanup assertions * Discord: add thread-bound session TTL with auto-unfocus * Subagents: fail session spawns when thread bind fails * Subagents: cover thread session failure cleanup paths * Session: add thread binding TTL config and /session ttl controls * Tests: align discord reaction expectations * Agent: persist sessionFile for keyed subagent sessions * Discord: normalize imports after conflict resolution * Sessions: centralize sessionFile resolve/persist helper * Discord: harden thread-bound subagent session routing * Rebase: resolve upstream/main conflicts * Subagents: move thread binding into hooks and split bindings modules * Docs: add channel-agnostic subagent routing hook plan * Agents: decouple subagent routing from Discord * Discord: refactor thread-bound subagent flows * Subagents: prevent duplicate end hooks and orphaned failed sessions * Refactor: split subagent command and provider phases * Subagents: honor hook delivery target overrides * Discord: add thread binding kill switches and refresh plan doc * Discord: fix thread bind channel resolution * Routing: centralize account id normalization * Discord: clean up thread bindings on startup failures * Discord: add startup cleanup regression tests * Docs: add long-term thread-bound subagent architecture * Docs: split session binding plan and dedupe thread-bound doc * Subagents: add channel-agnostic session binding routing * Subagents: stabilize announce completion routing tests * Subagents: cover multi-bound completion routing * Subagents: suppress lifecycle hooks on failed thread bind * tests: fix discord provider mock typing regressions * docs/protocol: sync slash command aliases and delete param models * fix: add changelog entry for Discord thread-bound subagents (#21805) (thanks @onutc) --------- Co-authored-by: Shadow <hi@shadowing.dev>
2026-02-21 16:14:55 +01:00
const fallbackSessionFile = !sessionEntry.sessionFile
? resolveSessionTranscriptPath(sessionEntry.sessionId, agentId, ctx.MessageThreadId)
: undefined;
const resolvedSessionFile = await resolveAndPersistSessionFile({
sessionId: sessionEntry.sessionId,
sessionKey,
sessionStore,
storePath,
sessionEntry,
agentId,
sessionsDir: path.dirname(storePath),
fallbackSessionFile,
activeSessionKey: sessionKey,
});
sessionEntry = resolvedSessionFile.sessionEntry;
if (isNewSession) {
sessionEntry.compactionCount = 0;
sessionEntry.memoryFlushCompactionCount = undefined;
sessionEntry.memoryFlushAt = undefined;
// Clear stale token metrics from previous session so /status doesn't
// display the old session's context usage after /new or /reset.
sessionEntry.totalTokens = undefined;
sessionEntry.inputTokens = undefined;
sessionEntry.outputTokens = undefined;
sessionEntry.contextTokens = undefined;
}
// Preserve per-session overrides while resetting compaction state on /new.
sessionStore[sessionKey] = { ...sessionStore[sessionKey], ...sessionEntry };
fix: unify session maintenance and cron run pruning (#13083) * fix: prune stale session entries, cap entry count, and rotate sessions.json The sessions.json file grows unbounded over time. Every heartbeat tick (default: 30m) triggers multiple full rewrites, and session keys from groups, threads, and DMs accumulate indefinitely with large embedded objects (skillsSnapshot, systemPromptReport). At >50MB the synchronous JSON parse blocks the event loop, causing Telegram webhook timeouts and effectively taking the bot down. Three mitigations, all running inside saveSessionStoreUnlocked() on every write: 1. Prune stale entries: remove entries with updatedAt older than 30 days (configurable via session.maintenance.pruneDays in openclaw.json) 2. Cap entry count: keep only the 500 most recently updated entries (configurable via session.maintenance.maxEntries). Entries without updatedAt are evicted first. 3. File rotation: if the existing sessions.json exceeds 10MB before a write, rename it to sessions.json.bak.{timestamp} and keep only the 3 most recent backups (configurable via session.maintenance.rotateBytes). All three thresholds are configurable under session.maintenance in openclaw.json with Zod validation. No env vars. Existing tests updated to use Date.now() instead of epoch-relative timestamps (1, 2, 3) that would be incorrectly pruned as stale. 27 new tests covering pruning, capping, rotation, and integration scenarios. * feat: auto-prune expired cron run sessions (#12289) Add TTL-based reaper for isolated cron run sessions that accumulate indefinitely in sessions.json. New config option: cron.sessionRetention: string | false (default: '24h') The reaper runs piggy-backed on the cron timer tick, self-throttled to sweep at most every 5 minutes. It removes session entries matching the pattern cron:<jobId>:run:<uuid> whose updatedAt + retention < now. Design follows the Kubernetes ttlSecondsAfterFinished pattern: - Sessions are persisted normally (observability/debugging) - A periodic reaper prunes expired entries - Configurable retention with sensible default - Set to false to disable pruning entirely Files changed: - src/config/types.cron.ts: Add sessionRetention to CronConfig - src/config/zod-schema.ts: Add Zod validation for sessionRetention - src/cron/session-reaper.ts: New reaper module (sweepCronRunSessions) - src/cron/session-reaper.test.ts: 12 tests covering all paths - src/cron/service/state.ts: Add cronConfig/sessionStorePath to deps - src/cron/service/timer.ts: Wire reaper into onTimer tick - src/gateway/server-cron.ts: Pass config and session store path to deps Closes #12289 * fix: sweep cron session stores per agent * docs: add changelog for session maintenance (#13083) (thanks @skyfallsin, @Glucksberg) * fix: add warn-only session maintenance mode * fix: warn-only maintenance defaults to active session * fix: deliver maintenance warnings to active session * docs: add session maintenance examples * fix: accept duration and size maintenance thresholds * refactor: share cron run session key check * fix: format issues and replace defaultRuntime.warn with console.warn --------- Co-authored-by: Pradeep Elankumaran <pradeepe@gmail.com> Co-authored-by: Glucksberg <markuscontasul@gmail.com> Co-authored-by: max <40643627+quotentiroler@users.noreply.github.com> Co-authored-by: quotentiroler <max.nussbaumer@maxhealth.tech>
2026-02-09 23:42:35 -05:00
await updateSessionStore(
storePath,
(store) => {
// Preserve per-session overrides while resetting compaction state on /new.
store[sessionKey] = { ...store[sessionKey], ...sessionEntry };
},
{
activeSessionKey: sessionKey,
onWarn: (warning) =>
deliverSessionMaintenanceWarning({
cfg,
sessionKey,
entry: sessionEntry,
warning,
}),
},
);
2026-01-04 05:47:21 +01:00
// Archive old transcript so it doesn't accumulate on disk (#14869).
if (previousSessionEntry?.sessionId) {
archiveSessionTranscripts({
sessionId: previousSessionEntry.sessionId,
storePath,
sessionFile: previousSessionEntry.sessionFile,
agentId,
reason: "reset",
});
}
2026-01-04 05:47:21 +01:00
const sessionCtx: TemplateContext = {
...ctx,
// Keep BodyStripped aligned with Body (best default for agent prompts).
// RawBody is reserved for command/directive parsing and may omit context.
BodyStripped: normalizeInboundTextNewlines(
bodyStripped ??
ctx.BodyForAgent ??
ctx.Body ??
ctx.CommandBody ??
ctx.RawBody ??
ctx.BodyForCommands ??
"",
),
2026-01-04 05:47:21 +01:00
SessionId: sessionId,
IsNewSession: isNewSession ? "true" : "false",
};
// Run session plugin hooks (fire-and-forget)
const hookRunner = getGlobalHookRunner();
if (hookRunner && isNewSession) {
const effectiveSessionId = sessionId ?? "";
// If replacing an existing session, fire session_end for the old one
if (previousSessionEntry?.sessionId && previousSessionEntry.sessionId !== effectiveSessionId) {
if (hookRunner.hasHooks("session_end")) {
void hookRunner
.runSessionEnd(
{
sessionId: previousSessionEntry.sessionId,
messageCount: 0,
},
{
sessionId: previousSessionEntry.sessionId,
agentId: resolveSessionAgentId({ sessionKey, config: cfg }),
},
)
.catch(() => {});
}
}
// Fire session_start for the new session
if (hookRunner.hasHooks("session_start")) {
void hookRunner
.runSessionStart(
{
sessionId: effectiveSessionId,
resumedFrom: previousSessionEntry?.sessionId,
},
{
sessionId: effectiveSessionId,
agentId: resolveSessionAgentId({ sessionKey, config: cfg }),
},
)
.catch(() => {});
}
}
2026-01-04 05:47:21 +01:00
return {
sessionCtx,
sessionEntry,
2026-01-17 01:31:39 +00:00
previousSessionEntry,
2026-01-04 05:47:21 +01:00
sessionStore,
sessionKey,
sessionId: sessionId ?? crypto.randomUUID(),
isNewSession,
resetTriggered,
2026-01-04 05:47:21 +01:00
systemSent,
abortedLastRun,
storePath,
sessionScope,
groupResolution,
isGroup,
bodyStripped,
triggerBodyNormalized,
};
}