UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

677 lines (676 loc) • 25.2 kB
import { _ as resolveStateDir } from "./paths-ViKUYWUK.js"; import { m as normalizeE164 } from "./utils-CS0Ikux6.js"; import { c as normalizeAgentId, l as normalizeMainKey, r as buildAgentMainSessionKey, t as DEFAULT_AGENT_ID } from "./session-key-DAhnzjyr.js"; import { m as resolveDefaultAgentId, r as listAgentIds } from "./agent-scope-bjWqU22i.js"; import { s as loadConfig } from "./io-y3Az_Onx.js"; import { l as normalizeMessageChannel } from "./message-channel-BliByQBl.js"; import { A as resolveGroupSessionKey, l as updateSessionStore, n as loadSessionStore, r as normalizeStoreSessionKey } from "./store-C5UK26Ce.js"; import { i as resolveMainSessionKey } from "./main-session-ClbmrpGK.js"; import { a as resolveSessionTranscriptPath, i as resolveSessionFilePathOptions, l as resolveStorePath, n as resolveDefaultSessionStorePath, r as resolveSessionFilePath, t as resolveAgentsDirFromSessionStorePath } from "./paths-rhN9LKM_.js"; import { t as normalizeExplicitDiscordSessionKey } from "./session-key-api-Lk-KlhbQ.js"; import fs from "node:fs"; import path from "node:path"; import fs$1 from "node:fs/promises"; import { CURRENT_SESSION_VERSION, SessionManager } from "@mariozechner/pi-coding-agent"; //#region src/config/sessions/main-session.runtime.ts function resolveMainSessionKeyFromConfig() { return resolveMainSessionKey(loadConfig()); } const THREAD_SESSION_MARKERS = [":thread:", ":topic:"]; const GROUP_SESSION_MARKERS = [":group:", ":channel:"]; function isThreadSessionKey(sessionKey) { const normalized = (sessionKey ?? "").toLowerCase(); if (!normalized) return false; return THREAD_SESSION_MARKERS.some((marker) => normalized.includes(marker)); } function resolveSessionResetType(params) { if (params.isThread || isThreadSessionKey(params.sessionKey)) return "thread"; if (params.isGroup) return "group"; const normalized = (params.sessionKey ?? "").toLowerCase(); if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) return "group"; return "direct"; } function resolveThreadFlag(params) { if (params.messageThreadId != null) return true; if (params.threadLabel?.trim()) return true; if (params.threadStarterBody?.trim()) return true; if (params.parentSessionKey?.trim()) return true; return isThreadSessionKey(params.sessionKey); } function resolveDailyResetAtMs(now, atHour) { const normalizedAtHour = normalizeResetAtHour(atHour); const resetAt = new Date(now); resetAt.setHours(normalizedAtHour, 0, 0, 0); if (now < resetAt.getTime()) resetAt.setDate(resetAt.getDate() - 1); return resetAt.getTime(); } function resolveSessionResetPolicy(params) { const sessionCfg = params.sessionCfg; const baseReset = params.resetOverride ?? sessionCfg?.reset; const typeReset = params.resetOverride ? void 0 : sessionCfg?.resetByType?.[params.resetType] ?? (params.resetType === "direct" ? (sessionCfg?.resetByType)?.dm : void 0); const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType); const legacyIdleMinutes = params.resetOverride ? void 0 : sessionCfg?.idleMinutes; const mode = typeReset?.mode ?? baseReset?.mode ?? (!hasExplicitReset && legacyIdleMinutes != null ? "idle" : "daily"); const atHour = normalizeResetAtHour(typeReset?.atHour ?? baseReset?.atHour ?? 4); const idleMinutesRaw = typeReset?.idleMinutes ?? baseReset?.idleMinutes ?? legacyIdleMinutes; let idleMinutes; if (idleMinutesRaw != null) { const normalized = Math.floor(idleMinutesRaw); if (Number.isFinite(normalized)) idleMinutes = Math.max(normalized, 0); } else if (mode === "idle") idleMinutes = 0; return { mode, atHour, idleMinutes }; } function resolveChannelResetConfig(params) { const resetByChannel = params.sessionCfg?.resetByChannel; if (!resetByChannel) return; const normalized = normalizeMessageChannel(params.channel); const fallback = params.channel?.trim().toLowerCase(); const key = normalized ?? fallback; if (!key) return; return resetByChannel[key] ?? resetByChannel[key.toLowerCase()]; } function evaluateSessionFreshness(params) { const dailyResetAt = params.policy.mode === "daily" ? resolveDailyResetAtMs(params.now, params.policy.atHour) : void 0; const idleExpiresAt = params.policy.idleMinutes != null && params.policy.idleMinutes > 0 ? params.updatedAt + params.policy.idleMinutes * 6e4 : void 0; const staleDaily = dailyResetAt != null && params.updatedAt < dailyResetAt; const staleIdle = idleExpiresAt != null && params.now > idleExpiresAt; return { fresh: !(staleDaily || staleIdle), dailyResetAt, idleExpiresAt }; } function normalizeResetAtHour(value) { if (typeof value !== "number" || !Number.isFinite(value)) return 4; const normalized = Math.floor(value); if (!Number.isFinite(normalized)) return 4; if (normalized < 0) return 0; if (normalized > 23) return 23; return normalized; } //#endregion //#region src/config/sessions/explicit-session-key-normalization.ts const EXPLICIT_SESSION_KEY_NORMALIZERS = [{ provider: "discord", normalize: normalizeExplicitDiscordSessionKey, matches: ({ sessionKey, provider, surface, from }) => surface === "discord" || provider === "discord" || from.startsWith("discord:") || sessionKey.startsWith("discord:") || sessionKey.includes(":discord:") }]; function resolveExplicitSessionKeyNormalizer(sessionKey, ctx) { const normalizedProvider = ctx.Provider?.trim().toLowerCase(); const normalizedSurface = ctx.Surface?.trim().toLowerCase(); const normalizedFrom = (ctx.From ?? "").trim().toLowerCase(); return EXPLICIT_SESSION_KEY_NORMALIZERS.find((entry) => entry.matches({ sessionKey, provider: normalizedProvider, surface: normalizedSurface, from: normalizedFrom }))?.normalize; } function normalizeExplicitSessionKey(sessionKey, ctx) { const normalized = sessionKey.trim().toLowerCase(); const normalize = resolveExplicitSessionKeyNormalizer(normalized, ctx); return normalize ? normalize(normalized, ctx) : normalized; } //#endregion //#region src/config/sessions/session-key.ts function deriveSessionKey(scope, ctx) { if (scope === "global") return "global"; const resolvedGroup = resolveGroupSessionKey(ctx); if (resolvedGroup) return resolvedGroup.key; return (ctx.From ? normalizeE164(ctx.From) : "") || "unknown"; } /** * Resolve the session key with a canonical direct-chat bucket (default: "main"). * All non-group direct chats collapse to this bucket; groups stay isolated. */ function resolveSessionKey(scope, ctx, mainKey) { const explicit = ctx.SessionKey?.trim(); if (explicit) return normalizeExplicitSessionKey(explicit, ctx); const raw = deriveSessionKey(scope, ctx); if (scope === "global") return raw; const canonical = buildAgentMainSessionKey({ agentId: DEFAULT_AGENT_ID, mainKey: normalizeMainKey(mainKey) }); if (!(raw.includes(":group:") || raw.includes(":channel:"))) return canonical; return `agent:${DEFAULT_AGENT_ID}:${raw}`; } //#endregion //#region src/sessions/transcript-events.ts const SESSION_TRANSCRIPT_LISTENERS = /* @__PURE__ */ new Set(); function onSessionTranscriptUpdate(listener) { SESSION_TRANSCRIPT_LISTENERS.add(listener); return () => { SESSION_TRANSCRIPT_LISTENERS.delete(listener); }; } function emitSessionTranscriptUpdate(update) { const normalized = typeof update === "string" ? { sessionFile: update } : { sessionFile: update.sessionFile, sessionKey: update.sessionKey, message: update.message, messageId: update.messageId }; const trimmed = normalized.sessionFile.trim(); if (!trimmed) return; const nextUpdate = { sessionFile: trimmed, ...typeof normalized.sessionKey === "string" && normalized.sessionKey.trim() ? { sessionKey: normalized.sessionKey.trim() } : {}, ...normalized.message !== void 0 ? { message: normalized.message } : {}, ...typeof normalized.messageId === "string" && normalized.messageId.trim() ? { messageId: normalized.messageId.trim() } : {} }; for (const listener of SESSION_TRANSCRIPT_LISTENERS) try { listener(nextUpdate); } catch {} } //#endregion //#region src/config/sessions/delivery-info.ts /** * Extract deliveryContext and threadId from a sessionKey. * Supports both :thread: (most channels) and :topic: (Telegram). */ function parseSessionThreadInfo(sessionKey) { if (!sessionKey) return { baseSessionKey: void 0, threadId: void 0 }; const topicIndex = sessionKey.lastIndexOf(":topic:"); const threadIndex = sessionKey.lastIndexOf(":thread:"); const markerIndex = Math.max(topicIndex, threadIndex); const marker = topicIndex > threadIndex ? ":topic:" : ":thread:"; return { baseSessionKey: markerIndex === -1 ? sessionKey : sessionKey.slice(0, markerIndex), threadId: (markerIndex === -1 ? void 0 : sessionKey.slice(markerIndex + marker.length))?.trim() || void 0 }; } function extractDeliveryInfo(sessionKey) { const { baseSessionKey, threadId } = parseSessionThreadInfo(sessionKey); if (!sessionKey || !baseSessionKey) return { deliveryContext: void 0, threadId }; let deliveryContext; try { const store = loadSessionStore(resolveStorePath(loadConfig().session?.store)); let entry = store[sessionKey]; if (!entry?.deliveryContext && baseSessionKey !== sessionKey) entry = store[baseSessionKey]; if (entry?.deliveryContext) deliveryContext = { channel: entry.deliveryContext.channel, to: entry.deliveryContext.to, accountId: entry.deliveryContext.accountId }; } catch {} return { deliveryContext, threadId }; } //#endregion //#region src/config/sessions/session-file.ts async function resolveAndPersistSessionFile(params) { const { sessionId, sessionKey, sessionStore, storePath } = params; const baseEntry = params.sessionEntry ?? sessionStore[sessionKey] ?? { sessionId, updatedAt: Date.now() }; const fallbackSessionFile = params.fallbackSessionFile?.trim(); const sessionFile = resolveSessionFilePath(sessionId, !baseEntry.sessionFile && fallbackSessionFile ? { ...baseEntry, sessionFile: fallbackSessionFile } : baseEntry, { agentId: params.agentId, sessionsDir: params.sessionsDir }); const persistedEntry = { ...baseEntry, sessionId, updatedAt: Date.now(), sessionFile }; if (baseEntry.sessionId !== sessionId || baseEntry.sessionFile !== sessionFile) { sessionStore[sessionKey] = persistedEntry; await updateSessionStore(storePath, (store) => { store[sessionKey] = { ...store[sessionKey], ...persistedEntry }; }, params.activeSessionKey ? { activeSessionKey: params.activeSessionKey } : void 0); return { sessionFile, sessionEntry: persistedEntry }; } sessionStore[sessionKey] = persistedEntry; return { sessionFile, sessionEntry: persistedEntry }; } //#endregion //#region src/config/sessions/transcript.ts function stripQuery(value) { const noHash = value.split("#")[0] ?? value; return noHash.split("?")[0] ?? noHash; } function extractFileNameFromMediaUrl(value) { const trimmed = value.trim(); if (!trimmed) return null; const cleaned = stripQuery(trimmed); try { const parsed = new URL(cleaned); const base = path.basename(parsed.pathname); if (!base) return null; try { return decodeURIComponent(base); } catch { return base; } } catch { const base = path.basename(cleaned); if (!base || base === "/" || base === ".") return null; return base; } } function resolveMirroredTranscriptText(params) { const mediaUrls = params.mediaUrls?.filter((url) => url && url.trim()) ?? []; if (mediaUrls.length > 0) { const names = mediaUrls.map((url) => extractFileNameFromMediaUrl(url)).filter((name) => Boolean(name && name.trim())); if (names.length > 0) return names.join(", "); return "media"; } const trimmed = (params.text ?? "").trim(); return trimmed ? trimmed : null; } async function ensureSessionHeader(params) { if (fs.existsSync(params.sessionFile)) return; await fs.promises.mkdir(path.dirname(params.sessionFile), { recursive: true }); const header = { type: "session", version: CURRENT_SESSION_VERSION, id: params.sessionId, timestamp: (/* @__PURE__ */ new Date()).toISOString(), cwd: process.cwd() }; await fs.promises.writeFile(params.sessionFile, `${JSON.stringify(header)}\n`, { encoding: "utf-8", mode: 384 }); } async function resolveSessionTranscriptFile(params) { const sessionPathOpts = resolveSessionFilePathOptions({ agentId: params.agentId, storePath: params.storePath }); let sessionFile = resolveSessionFilePath(params.sessionId, params.sessionEntry, sessionPathOpts); let sessionEntry = params.sessionEntry; if (params.sessionStore && params.storePath) { const threadIdFromSessionKey = parseSessionThreadInfo(params.sessionKey).threadId; const fallbackSessionFile = !sessionEntry?.sessionFile ? resolveSessionTranscriptPath(params.sessionId, params.agentId, params.threadId ?? threadIdFromSessionKey) : void 0; const resolvedSessionFile = await resolveAndPersistSessionFile({ sessionId: params.sessionId, sessionKey: params.sessionKey, sessionStore: params.sessionStore, storePath: params.storePath, sessionEntry, agentId: sessionPathOpts?.agentId, sessionsDir: sessionPathOpts?.sessionsDir, fallbackSessionFile }); sessionFile = resolvedSessionFile.sessionFile; sessionEntry = resolvedSessionFile.sessionEntry; } return { sessionFile, sessionEntry }; } async function appendAssistantMessageToSessionTranscript(params) { const sessionKey = params.sessionKey.trim(); if (!sessionKey) return { ok: false, reason: "missing sessionKey" }; const mirrorText = resolveMirroredTranscriptText({ text: params.text, mediaUrls: params.mediaUrls }); if (!mirrorText) return { ok: false, reason: "empty text" }; const storePath = params.storePath ?? resolveDefaultSessionStorePath(params.agentId); const store = loadSessionStore(storePath, { skipCache: true }); const entry = store[normalizeStoreSessionKey(sessionKey)] ?? store[sessionKey]; if (!entry?.sessionId) return { ok: false, reason: `unknown sessionKey: ${sessionKey}` }; let sessionFile; try { sessionFile = (await resolveAndPersistSessionFile({ sessionId: entry.sessionId, sessionKey, sessionStore: store, storePath, sessionEntry: entry, agentId: params.agentId, sessionsDir: path.dirname(storePath) })).sessionFile; } catch (err) { return { ok: false, reason: err instanceof Error ? err.message : String(err) }; } await ensureSessionHeader({ sessionFile, sessionId: entry.sessionId }); const existingMessageId = params.idempotencyKey ? await transcriptHasIdempotencyKey(sessionFile, params.idempotencyKey) : void 0; if (existingMessageId) return { ok: true, sessionFile, messageId: existingMessageId }; const message = { role: "assistant", content: [{ type: "text", text: mirrorText }], api: "openai-responses", provider: "openclaw", model: "delivery-mirror", usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "stop", timestamp: Date.now(), ...params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {} }; const messageId = SessionManager.open(sessionFile).appendMessage(message); emitSessionTranscriptUpdate({ sessionFile, sessionKey, message, messageId }); return { ok: true, sessionFile, messageId }; } async function transcriptHasIdempotencyKey(transcriptPath, idempotencyKey) { try { const raw = await fs.promises.readFile(transcriptPath, "utf-8"); for (const line of raw.split(/\r?\n/)) { if (!line.trim()) continue; try { const parsed = JSON.parse(line); if (parsed.message?.idempotencyKey === idempotencyKey && typeof parsed.id === "string" && parsed.id) return parsed.id; } catch { continue; } } } catch { return; } } //#endregion //#region src/agents/session-dirs.ts function mapAgentSessionDirs(agentsDir, entries) { return entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(agentsDir, entry.name, "sessions")).toSorted((a, b) => a.localeCompare(b)); } async function resolveAgentSessionDirsFromAgentsDir(agentsDir) { let entries = []; try { entries = await fs$1.readdir(agentsDir, { withFileTypes: true }); } catch (err) { if (err.code === "ENOENT") return []; throw err; } return mapAgentSessionDirs(agentsDir, entries); } function resolveAgentSessionDirsFromAgentsDirSync(agentsDir) { let entries = []; try { entries = fs.readdirSync(agentsDir, { withFileTypes: true }); } catch (err) { if (err.code === "ENOENT") return []; throw err; } return mapAgentSessionDirs(agentsDir, entries); } async function resolveAgentSessionDirs(stateDir) { return await resolveAgentSessionDirsFromAgentsDir(path.join(stateDir, "agents")); } //#endregion //#region src/config/sessions/targets.ts const NON_FATAL_DISCOVERY_ERROR_CODES = new Set([ "EACCES", "ELOOP", "ENOENT", "ENOTDIR", "EPERM", "ESTALE" ]); function dedupeTargetsByStorePath(targets) { const deduped = /* @__PURE__ */ new Map(); for (const target of targets) if (!deduped.has(target.storePath)) deduped.set(target.storePath, target); return [...deduped.values()]; } function shouldSkipDiscoveryError(err) { const code = err?.code; return typeof code === "string" && NON_FATAL_DISCOVERY_ERROR_CODES.has(code); } function isWithinRoot(realPath, realRoot) { return realPath === realRoot || realPath.startsWith(`${realRoot}${path.sep}`); } function shouldSkipDiscoveredAgentDirName(dirName, agentId) { return agentId === "main" && dirName.trim().toLowerCase() !== "main"; } function resolveValidatedDiscoveredStorePathSync(params) { const storePath = path.join(params.sessionsDir, "sessions.json"); try { const stat = fs.lstatSync(storePath); if (stat.isSymbolicLink() || !stat.isFile()) return; const realStorePath = fs.realpathSync.native(storePath); return isWithinRoot(realStorePath, params.realAgentsRoot ?? fs.realpathSync.native(params.agentsRoot)) ? realStorePath : void 0; } catch (err) { if (shouldSkipDiscoveryError(err)) return; throw err; } } async function resolveValidatedDiscoveredStorePath(params) { const storePath = path.join(params.sessionsDir, "sessions.json"); try { const stat = await fs$1.lstat(storePath); if (stat.isSymbolicLink() || !stat.isFile()) return; const realStorePath = await fs$1.realpath(storePath); return isWithinRoot(realStorePath, params.realAgentsRoot ?? await fs$1.realpath(params.agentsRoot)) ? realStorePath : void 0; } catch (err) { if (shouldSkipDiscoveryError(err)) return; throw err; } } function resolveSessionStoreDiscoveryState(cfg, env) { const configuredTargets = resolveSessionStoreTargets(cfg, { allAgents: true }, { env }); const agentsRoots = /* @__PURE__ */ new Set(); for (const target of configuredTargets) { const agentsDir = resolveAgentsDirFromSessionStorePath(target.storePath); if (agentsDir) agentsRoots.add(agentsDir); } agentsRoots.add(path.join(resolveStateDir(env), "agents")); return { configuredTargets, agentsRoots: [...agentsRoots] }; } function toDiscoveredSessionStoreTarget(sessionsDir, storePath) { const dirName = path.basename(path.dirname(sessionsDir)); const agentId = normalizeAgentId(dirName); if (shouldSkipDiscoveredAgentDirName(dirName, agentId)) return; return { agentId, storePath }; } function resolveAllAgentSessionStoreTargetsSync(cfg, params = {}) { const { configuredTargets, agentsRoots } = resolveSessionStoreDiscoveryState(cfg, params.env ?? process.env); const realAgentsRoots = /* @__PURE__ */ new Map(); const getRealAgentsRoot = (agentsRoot) => { const cached = realAgentsRoots.get(agentsRoot); if (cached !== void 0) return cached; try { const realAgentsRoot = fs.realpathSync.native(agentsRoot); realAgentsRoots.set(agentsRoot, realAgentsRoot); return realAgentsRoot; } catch (err) { if (shouldSkipDiscoveryError(err)) return; throw err; } }; const validatedConfiguredTargets = configuredTargets.flatMap((target) => { const agentsRoot = resolveAgentsDirFromSessionStorePath(target.storePath); if (!agentsRoot) return [target]; const realAgentsRoot = getRealAgentsRoot(agentsRoot); if (!realAgentsRoot) return []; const validatedStorePath = resolveValidatedDiscoveredStorePathSync({ sessionsDir: path.dirname(target.storePath), agentsRoot, realAgentsRoot }); return validatedStorePath ? [{ ...target, storePath: validatedStorePath }] : []; }); const discoveredTargets = agentsRoots.flatMap((agentsDir) => { try { const realAgentsRoot = getRealAgentsRoot(agentsDir); if (!realAgentsRoot) return []; return resolveAgentSessionDirsFromAgentsDirSync(agentsDir).flatMap((sessionsDir) => { const validatedStorePath = resolveValidatedDiscoveredStorePathSync({ sessionsDir, agentsRoot: agentsDir, realAgentsRoot }); const target = validatedStorePath ? toDiscoveredSessionStoreTarget(sessionsDir, validatedStorePath) : void 0; return target ? [target] : []; }); } catch (err) { if (shouldSkipDiscoveryError(err)) return []; throw err; } }); return dedupeTargetsByStorePath([...validatedConfiguredTargets, ...discoveredTargets]); } async function resolveAllAgentSessionStoreTargets(cfg, params = {}) { const { configuredTargets, agentsRoots } = resolveSessionStoreDiscoveryState(cfg, params.env ?? process.env); const realAgentsRoots = /* @__PURE__ */ new Map(); const getRealAgentsRoot = async (agentsRoot) => { const cached = realAgentsRoots.get(agentsRoot); if (cached !== void 0) return cached; try { const realAgentsRoot = await fs$1.realpath(agentsRoot); realAgentsRoots.set(agentsRoot, realAgentsRoot); return realAgentsRoot; } catch (err) { if (shouldSkipDiscoveryError(err)) return; throw err; } }; const validatedConfiguredTargets = (await Promise.all(configuredTargets.map(async (target) => { const agentsRoot = resolveAgentsDirFromSessionStorePath(target.storePath); if (!agentsRoot) return target; const realAgentsRoot = await getRealAgentsRoot(agentsRoot); if (!realAgentsRoot) return; const validatedStorePath = await resolveValidatedDiscoveredStorePath({ sessionsDir: path.dirname(target.storePath), agentsRoot, realAgentsRoot }); return validatedStorePath ? { ...target, storePath: validatedStorePath } : void 0; }))).filter((target) => Boolean(target)); const discoveredTargets = (await Promise.all(agentsRoots.map(async (agentsDir) => { try { const realAgentsRoot = await getRealAgentsRoot(agentsDir); if (!realAgentsRoot) return []; const sessionsDirs = await resolveAgentSessionDirsFromAgentsDir(agentsDir); return (await Promise.all(sessionsDirs.map(async (sessionsDir) => { const validatedStorePath = await resolveValidatedDiscoveredStorePath({ sessionsDir, agentsRoot: agentsDir, realAgentsRoot }); return validatedStorePath ? toDiscoveredSessionStoreTarget(sessionsDir, validatedStorePath) : void 0; }))).filter((target) => Boolean(target)); } catch (err) { if (shouldSkipDiscoveryError(err)) return []; throw err; } }))).flat(); return dedupeTargetsByStorePath([...validatedConfiguredTargets, ...discoveredTargets]); } function resolveSessionStoreTargets(cfg, opts, params = {}) { const env = params.env ?? process.env; const defaultAgentId = resolveDefaultAgentId(cfg); const hasAgent = Boolean(opts.agent?.trim()); const allAgents = opts.allAgents === true; if (hasAgent && allAgents) throw new Error("--agent and --all-agents cannot be used together"); if (opts.store && (hasAgent || allAgents)) throw new Error("--store cannot be combined with --agent or --all-agents"); if (opts.store) return [{ agentId: defaultAgentId, storePath: resolveStorePath(opts.store, { agentId: defaultAgentId, env }) }]; if (allAgents) return dedupeTargetsByStorePath(listAgentIds(cfg).map((agentId) => ({ agentId, storePath: resolveStorePath(cfg.session?.store, { agentId, env }) }))); if (hasAgent) { const knownAgents = listAgentIds(cfg); const requested = normalizeAgentId(opts.agent ?? ""); if (!knownAgents.includes(requested)) throw new Error(`Unknown agent id "${opts.agent}". Use "openclaw agents list" to see configured agents.`); return [{ agentId: requested, storePath: resolveStorePath(cfg.session?.store, { agentId: requested, env }) }]; } return [{ agentId: defaultAgentId, storePath: resolveStorePath(cfg.session?.store, { agentId: defaultAgentId, env }) }]; } //#endregion export { resolveSessionResetPolicy as _, appendAssistantMessageToSessionTranscript as a, resolveMainSessionKeyFromConfig as b, resolveAndPersistSessionFile as c, emitSessionTranscriptUpdate as d, onSessionTranscriptUpdate as f, resolveChannelResetConfig as g, evaluateSessionFreshness as h, resolveAgentSessionDirs as i, extractDeliveryInfo as l, resolveSessionKey as m, resolveAllAgentSessionStoreTargetsSync as n, resolveMirroredTranscriptText as o, deriveSessionKey as p, resolveSessionStoreTargets as r, resolveSessionTranscriptFile as s, resolveAllAgentSessionStoreTargets as t, parseSessionThreadInfo as u, resolveSessionResetType as v, resolveThreadFlag as y };