UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

281 lines (278 loc) • 11.5 kB
import { l as normalizeOptionalString, m as readNonBlankString, o as normalizeLowercaseStringOrEmpty } from "../../string-coerce-CCIiB4H7.mjs"; import { s as isVitestRuntimeEnv } from "../../env-HehwidXj.mjs"; import { c as formatErrorStackWithMessage } from "../../error-coercion-hDrHOSGy.mjs"; import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs"; import { E as parseApiErrorPayload, _ as extractLeadingHttpStatus } from "../../redact-Mj7pppxC.mjs"; import { r as resolveStateDir } from "../../state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "../../utils-C8YECn2Q.mjs"; import "../../paths-DAcAg5aV.mjs"; import { t as createDeferredCore } from "../../deferred-D0La5CRk.mjs"; import { w as root } from "../../fs-safe-BbWvmdVn.mjs"; import { r as isIncognitoSessionKey } from "../../session-key-DW1jcHbM.mjs"; import { g as toAgentStoreSessionKey, j as parseAgentSessionKey } from "../../session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "../../paths-DvQ5AJvD.mjs"; import { a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "../../agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "../../subsystem-BHJiy01V.mjs"; import { c as resolveAgentIdByWorkspacePath } from "../../agent-scope-BwB8YH6y.mjs"; import { s as withFileLock } from "../../file-lock-D9Tpq9ra.mjs"; import "../../file-lock-B28znsON.mjs"; import { T as runWithGatewayIndependentRootWorkContinuation } from "../../gateway-work-admission-79pid1hQ.mjs"; import { f as prepareSystemAgentRunAdmission } from "../../admitted-run-context-D3Jvk_f_.mjs"; import { n as resolveAgentTimeoutMs } from "../../timeout-BEnEcjB4.mjs"; import { t as resolveHookConfig } from "../../policy-9WWlcycM.mjs"; import { a as resolveUserTimezone } from "../../date-time-ChxDjIEM.mjs"; import { t as SessionManager } from "../../session-manager-DuaaMI5O.mjs"; import "../../sessions-G45sHB31.mjs"; import { t as createMemoryWriteProvenanceObserver } from "../../memory-write-provenance-z3UaKwZY.mjs"; import { t as captureSessionMemoryTranscript } from "../../capture-BViUfNam.mjs"; import { r as isSessionAutoResetReason } from "../../session-auto-reset-zcLtCg1x.mjs"; import { n as runEmbeddedAgent } from "../../embedded-agent-DHYfZZ9G.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; //#region src/hooks/bundled/session-memory/handler.ts const log = createSubsystemLogger("hooks/session-memory"); const slugGeneratorLog = createSubsystemLogger("llm-slug-generator"); const PROVIDER_ERROR_PREFIX_RE = /^(?:provider\s+)?(?:api|llm|model|openai|anthropic|codex|gateway)\s+(?:request\s+)?(?:error|failed|failure)\b/i; const PROVIDER_ERROR_DETAIL_RE = /\b(?:insufficient[_ -]?quota|quota (?:exceeded|exhausted)|exceeded your current quota|payment required|insufficient credits|credit balance|insufficient[_ -]?(?:balance|funds)|rate[_ -]?limit(?:ed)?|too many requests|invalid[_ -]?api[_ -]?key|incorrect api key|authentication failed|oauth token refresh failed|missing (?:token|projectid|credentials)|google cloud credentials|re-?authenticate|unauthorized|forbidden|permission_error|billing hard limit|spend(?:ing)? limit)\b/i; function isErrorSlugPayload(e) { if (!e) return false; if (e.isError === true) return true; const t = e.text?.trim(); if (!t) return false; if (parseApiErrorPayload(t)) return true; const n = extractLeadingHttpStatus(t); if (n) { if ([ 401, 402, 403, 429 ].includes(n.code)) return true; if (n.code === 400 && (parseApiErrorPayload(n.rest) || PROVIDER_ERROR_PREFIX_RE.test(n.rest) || PROVIDER_ERROR_DETAIL_RE.test(n.rest))) return true; } return PROVIDER_ERROR_PREFIX_RE.test(t) || PROVIDER_ERROR_DETAIL_RE.test(t); } function formatLocalSessionTimestamp(e, t) { const n = new Intl.DateTimeFormat("en-US", { timeZone: t, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(e); const r = n.find((e) => e.type === "year")?.value; const i = n.find((e) => e.type === "month")?.value; const a = n.find((e) => e.type === "day")?.value; const o = n.find((e) => e.type === "hour")?.value; const s = n.find((e) => e.type === "minute")?.value; const c = n.find((e) => e.type === "second")?.value; return { date: `${r}-${i}-${a}`, time: `${o}:${s}:${c}`, timeSlug: `${o}${s}` }; } async function resolveAvailableMemoryFilename(e) { const t = `${e.dateStr}-${e.slug}`; let n = 1; while (true) { const r = n === 1 ? `${t}.md` : `${t}-${n}.md`; try { await fs.access(path.join(e.memoryDir, r)); n += 1; } catch (e) { if (e.code === "ENOENT") return r; throw e; } } } function resolveDisplaySessionKey(e) { if (!e.cfg || !e.workspaceDir) return e.sessionKey; const t = resolveAgentIdByWorkspacePath(e.cfg, e.workspaceDir); const n = parseAgentSessionKey(e.sessionKey); if (!t || !n || t === n.agentId) return e.sessionKey; return toAgentStoreSessionKey({ agentId: t, requestKey: n.rest }); } const pendingSessionMemoryWrites = /* @__PURE__ */ new Set(); function requireSessionMemoryAgentId(e) { const t = normalizeOptionalString(e.context?.agentId); if (!t) throw new Error("Session memory hook contract requires context.agentId"); return t; } async function flushSessionMemoryWritesForTest() { await Promise.allSettled(pendingSessionMemoryWrites); } async function saveSessionMemoryNow(e, t, n) { try { const r = e.context || {}; const i = r.cfg; const a = readNonBlankString(r.workspaceDir); const o = a || (i ? resolveAgentWorkspaceDir(i, t) : path.join(resolveStateDir(process.env, os.homedir), "workspace")); const s = resolveDisplaySessionKey({ cfg: i, workspaceDir: a, sessionKey: e.sessionKey }); const c = path.join(o, "memory"); await fs.mkdir(c, { recursive: true }); const l = new Date(e.timestamp); const u = resolveUserTimezone(i?.agents?.defaults?.userTimezone ?? process.env.TZ); const d = formatLocalSessionTimestamp(l, u); const f = d.date; const p = e.type === "command" ? r.previousSessionEntry || r.sessionEntry || {} : r.sessionEntry || {}; const m = normalizeOptionalString(p.sessionId); const h = resolveHookConfig(i, "session-memory"); let g = null; if (n.status === "unavailable") log.warn("Session transcript unavailable for memory capture", { sessionKey: e.sessionKey, error: n.reason }); if (m) { const e = !isVitestRuntimeEnv() && h?.llmSlug === true; if (n.status === "available" && n.content && i && e) try { const e = resolveAgentWorkspaceDir(i, t); const r = resolveAgentDir(i, t); const a = `slug-generator-${randomUUID()}`; const o = `agent:${t}:helper:incognito-${a}`; const s = `Based on this conversation, generate a short 1-2 word filename slug (lowercase, hyphen-separated, no file extension). Conversation summary: ${truncateUtf16Safe(n.content, 2e3)} Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design", "bug-fix"`; const c = i.agents?.defaults?.timeoutSeconds === void 0 ? 15e3 : resolveAgentTimeoutMs({ cfg: i }); const l = `slug-gen-${Date.now()}`; const u = prepareSystemAgentRunAdmission(i, l, t, "hooks.slug-generator"); try { const n = (await runEmbeddedAgent({ preparedRunAdmission: u, sessionId: a, sessionKey: o, sessionManager: SessionManager.inMemory(e), agentId: t, workspaceDir: e, agentDir: r, config: i, prompt: s, model: typeof h?.model === "string" ? h.model : void 0, timeoutMs: c, runId: l, disableTools: true, toolsAllow: [], disableTrajectory: true, cleanupBundleMcpOnRunEnd: true, authProfileFailurePolicy: "local" })).payloads?.[0]; const d = n?.text; if (d && !isErrorSlugPayload(n)) g = normalizeLowercaseStringOrEmpty(d).replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30).replace(/^-+|-+$/g, "") || null; } finally { u.close(); } } catch (e) { const t = e instanceof Error ? formatErrorStackWithMessage(e) : String(e); slugGeneratorLog.error(`Failed to generate slug: ${t}`); } } if (!g) g = d.timeSlug; const _ = d.time; const v = p.sessionId || "unknown"; const y = e.type === "session" ? `- **Reason**: ${r.reason || "unknown"}` : `- **Source**: ${r.commandSource || "unknown"}`; const b = [ `# Session: ${f} ${_} ${u}`, "", `- **Session Key**: ${s}`, `- **Session ID**: ${v}`, y, "" ]; if (n.status === "available" && n.content) b.push("## Conversation Summary", "", n.content, ""); else if (n.status === "unavailable") b.push("## Conversation Summary", "", `> Transcript content was unavailable: ${JSON.stringify(n.reason)}`, ""); const x = b.join("\n"); const S = await root(c); const C = createMemoryWriteProvenanceObserver({ mutationRoot: o, workspaceDir: o, resolveOriginClass: () => n.status === "available" ? n.originClass : "agent", sessionId: m, sessionKey: e.sessionKey, now: () => l.getTime() }); const w = await withFileLock(path.join(c, ".session-memory"), { retries: { retries: 1200, factor: 1, minTimeout: 25, maxTimeout: 25 }, stale: 3e4, staleRecovery: "remove-if-definitely-stale" }, async () => { const e = await resolveAvailableMemoryFilename({ memoryDir: c, dateStr: f, slug: g }); const t = path.join(c, e); await C.write({ absolutePath: t, contentBefore: "", contentAfter: x, commit: () => S.create(e, x, { encoding: "utf-8", atomic: true }) }); return t; }); const T = shortenHomePath(w); log.info(`Session context saved to ${T}`); } catch (e) { if (e instanceof Error) log.error("Failed to save session memory", { errorName: e.name, errorMessage: e.message, stack: e.stack }); else log.error("Failed to save session memory", { error: String(e) }); } } const saveSessionToMemory = async (e) => { const t = e.action === "new" || e.action === "reset"; const n = e.type === "session" && e.action === "auto-reset" && isSessionAutoResetReason(e.context.reason); if ((e.type !== "command" || !t) && !n) return; const r = e.context; const i = e.type === "command" ? r.previousSessionEntry ?? r.sessionEntry : r.sessionEntry; if (isIncognitoSessionKey(e.sessionKey) || i?.incognito === true) return; const a = requireSessionMemoryAgentId(e); const o = r.cfg; const s = createDeferredCore(); const captureAndSave = async () => { const t = r.previousSessionMemory ?? (i?.sessionId ? await captureSessionMemoryTranscript({ agentId: a, sessionId: i.sessionId, sessionKey: e.sessionKey, storePath: normalizeOptionalString(r.storePath) ?? resolveSessionStorePathCore(o?.session?.store, { agentId: a }) }, o) : { status: "available", content: null, originClass: "agent" }); s.resolve(); await saveSessionMemoryNow(e, a, t); }; const c = n ? captureAndSave() : runWithGatewayIndependentRootWorkContinuation(captureAndSave, "hooks:session-memory"); pendingSessionMemoryWrites.add(c); c.then(() => pendingSessionMemoryWrites.delete(c), (e) => { pendingSessionMemoryWrites.delete(c); s.reject(e); }); await s.promise; if (n) return c; }; //#endregion export { saveSessionToMemory as default, flushSessionMemoryWritesForTest };