UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

375 lines (374 loc) • 14.1 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { l as trackAsyncWork, o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { A as withTimeout } from "./fs-safe-BbWvmdVn.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { b as resolveNativeModelPrimary, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { i as isValidBase64 } from "./base64-CnKpkbff.mjs"; import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { f as sessionEntryCommitGuardOptions, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { a as SESSION_TITLE_SOURCE_MAX_CHARS, o as resolveSessionTitleSource } from "./session-actor-memory-owner-BkB9Vtu4.mjs"; import { s as resolveStoredSessionKeyForAgentStore } from "./session-store-key-CEwU3noi.mjs"; import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs"; import { i as resolveSessionRuntimeOverrideForProvider } from "./session-runtime-compat-C_CO9LR_.mjs"; import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs"; import { o as withWorktreeSourceWait } from "./allocation-DPkHxKtM.mjs"; import { t as createCrustaceanSlug } from "./session-slug-CTgJwlm2.mjs"; import { n as resolveExplicitSessionName, r as sessionTitleRequests, t as hasExplicitSessionName } from "./session-title-state-nyOIuOVp.mjs"; import { a as resolveUtilityModelRefForAgent } from "./utility-model-DHdotLLx.mjs"; import { t as runWithAsyncWorkResources } from "./async-work-resources-BF09U4aO.mjs"; import { t as readSessionTitleFieldsFromTranscriptAsync } from "./session-transcript-title-reader-BiVwCofT.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/gateway/dashboard-session-title.ts const DASHBOARD_SESSION_TITLE_MAX_CHARS = 60; const WORKTREE_SESSION_TITLE_WAIT_MS = 3e4; const DASHBOARD_SESSION_TITLE_PROMPT = "Generate a concise session title (3-6 words, max 60 characters) from the supplied source message. Use the language the message is written in, not the language of quoted literals, in sentence case: capitalize only the first word and words that language always capitalizes. No emoji. Return only the title."; function decodeTextAttachmentPrefix(e, t) { const n = e.mimeType?.trim().toLowerCase(); const r = e.content; if (!n?.startsWith("text/") || typeof r !== "string" || !r) return null; if (!isValidBase64(r)) return null; const i = Math.ceil((t * 3 + 3) / 3) * 4; const a = r.length > i; const o = a ? i : r.length; const s = r.slice(0, o); const c = Buffer.from(s, "base64"); try { return new TextDecoder("utf-8", { fatal: true }).decode(c, { stream: a }); } catch { return null; } } /** Builds the bounded model source shared by dashboard and worktree titles. */ function buildDashboardSessionTitleSource(e) { const t = e.message.trim(); const n = t.startsWith("/"); let r = n ? "" : t; for (const t of e.attachments ?? []) { const e = r ? 1 : 0; const n = SESSION_TITLE_SOURCE_MAX_CHARS - r.length - e; if (n <= 0) break; const i = decodeTextAttachmentPrefix(t, n)?.trim(); if (!i) continue; r += `${r ? "\n" : ""}${truncateUtf16Safe(i, n)}`; } if (!r && n) return truncateUtf16Safe(t, SESSION_TITLE_SOURCE_MAX_CHARS); return truncateUtf16Safe(r.trim(), SESSION_TITLE_SOURCE_MAX_CHARS); } function isAutoTitleSessionKey(e) { const t = parseAgentSessionKey(e)?.rest ?? ""; return t.startsWith("dashboard:") || t.startsWith("ios-") || t.startsWith("node-"); } /** True when this interactive chat key should receive an automatic topic title. */ function isDashboardSessionTitleCandidate(e) { const t = e.userMessage.trim(); return Boolean(t && isAutoTitleSessionKey(e.sessionKey)); } function resolveDashboardTitleAuthProfile(e) { const t = e.entry?.authProfileOverride?.trim(); if (t) return t; const n = resolveNativeModelPrimary(e.cfg, e.agentId)?.trim(); const r = n ? splitTrailingAuthProfile(n).profile : void 0; if (!r) return; return resolveSessionModelRef(e.cfg, void 0, e.agentId).provider === e.regularProvider ? r : void 0; } const TITLE_LEAD_IN = /^(?:(?:concise|short|suggested|proposed|final|correct|session|chat|conversation|kurzer|kürzester|passender|richtiger|vorgeschlagener)\s+)?(?:(?:sitzungs|session-?|chat-?)?(?:title|titel)|label)(?:\s+(?:for|für)\s[^:]*)?\s*:\s*/iu; function stripTitleLeadIn(e) { const t = e.replace(/\s+/g, " ").trim(); const n = t.replace(TITLE_LEAD_IN, ""); return { text: (/^\*\*([^*]+)\*\*$/u.exec(n)?.[1] ?? n).trim(), introduced: n !== t }; } const TITLE_QUOTE_PAIRS = { "\"": "\"", "'": "'", "`": "`", "„": "“", "“": "”", "«": "»", "»": "«", "‘": "’" }; function quotesExactly(e, t) { return Object.entries(TITLE_QUOTE_PAIRS).some(([n, r]) => e.includes(`${n}${t}${r}`)); } function normalizeDashboardSessionTitle(e) { const t = e.replace(/\r/g, "").split("\n").map((e) => stripTitleLeadIn(e)).filter(({ text: e }) => e && !e.startsWith("```")); const n = t.filter(({ text: e }) => !e.endsWith(":")); const [r] = n; const i = (n.find(({ introduced: e }) => e) ?? (r && r.text.length > DASHBOARD_SESSION_TITLE_MAX_CHARS ? n.slice(1).find(({ text: e }) => quotesExactly(r.text, e)) : void 0) ?? r ?? t[0])?.text; if (!i || i.endsWith(":")) return null; const a = truncateUtf16Safe(i, DASHBOARD_SESSION_TITLE_MAX_CHARS); const o = /["'`„“”«»‘’]/gu; const s = []; const c = /* @__PURE__ */ new Set(); for (const e of a.matchAll(o)) { const t = e[0]; const n = e.index; const r = s.at(-1); const i = a.slice(0, n); const o = a.slice(n + 1); if (/['’]/u.test(t) && /[\p{L}\p{M}\p{N}]$/u.test(i)) { if (/^[\p{L}\p{M}\p{N}]/u.test(o)) continue; if (o || /s$/iu.test(i)) { const e = /‘|(?<![\p{L}\p{M}\p{N}])['’]|['’](?![\p{L}\p{M}\p{N}])/u.exec(o); if (r?.close !== t || e?.[0] === t && !/^[\p{L}\p{M}\p{N}]/u.test(o.slice(e.index + 1))) continue; } } if (r?.close === t) { s.pop(); c.delete(r.index); if (/^[\s"'`„“”«»‘’]*$/u.test(a.slice(0, r.index) + a.slice(n + 1))) { c.add(r.index); c.add(n); } } else if (TITLE_QUOTE_PAIRS[t]) { s.push({ index: n, close: TITLE_QUOTE_PAIRS[t] }); c.add(n); } else if (/[”’]/u.test(t)) c.add(n); } const l = a.replace(o, (e, t) => c.has(t) ? "" : e).trim(); return /[^\s"'`„“”«»‘’]/u.test(l) ? l : null; } async function prepareTitleSkillCommands(e) { const { prepareSkillCommandsForWorkspace: t } = await import("./chat-commands-h6wTJmEk.mjs"); return await t({ cfg: e.cfg, agentId: e.agentId, workspaceDir: resolveAgentWorkspaceDir(e.cfg, e.agentId), sessionEntry: e.entry, sessionKey: e.sessionKey }, e.assertCurrent); } async function generateDashboardSessionTitle(e) { const t = e.sourceText; const n = resolveSessionModelRef(e.cfg, e.entry, e.agentId); const r = resolveSessionRuntimeOverrideForProvider({ provider: n.provider, entry: e.entry, cfg: e.cfg }); const i = resolveDashboardTitleAuthProfile({ cfg: e.cfg, agentId: e.agentId, entry: e.entry, regularProvider: n.provider }); const a = `${n.provider}/${n.model}${i ? `@${i}` : ""}`; const o = resolveUtilityModelRefForAgent({ cfg: e.cfg, agentId: e.agentId, primaryProvider: n.provider, primaryModelRef: a }); const generateLabel = async () => { try { const { generateConversationLabelWithFallback: n } = await import("./conversation-label-generator-B0Xgvf3o.mjs"); e.assertCurrent?.(); e.abortSignal?.throwIfAborted(); return await n({ userMessage: t, prompt: DASHBOARD_SESSION_TITLE_PROMPT, cfg: e.cfg, agentId: e.agentId, ...r ? { agentHarnessRuntimeOverride: r } : {}, ...o ? { utilityModelRef: o } : {}, regularModelRef: a, ...i ? { preferredProfile: i } : {}, normalizeLabel: normalizeDashboardSessionTitle, maxLength: DASHBOARD_SESSION_TITLE_MAX_CHARS, abortSignal: e.abortSignal, assertCurrent: e.assertCurrent, operatorAuthority: e.operatorAuthority, ...e.utilityOnly ? { utilityOnly: true } : {} }); } catch { e.assertCurrent?.(); e.abortSignal?.throwIfAborted(); } return null; }; let s = await generateLabel(); if (!s && e.retryAfter) { await e.retryAfter; e.assertCurrent?.(); e.abortSignal?.throwIfAborted(); s = await generateLabel(); } if (s) return s; if (e.utilityOnly) return null; e.onFallback?.(); return createCrustaceanSlug(); } /** Prepares a creation draft's title without creating or updating a session. */ async function prepareDashboardSessionTitle(e) { try { const t = resolveSessionTitleSource(e.userMessage) ?? resolveSessionTitleSource(e.userMessage, await prepareTitleSkillCommands({ cfg: e.cfg, agentId: e.agentId, assertCurrent: e.assertCurrent })); return t ? await generateDashboardSessionTitle({ ...e, sourceText: t, utilityOnly: true }) : null; } catch { e.assertCurrent?.(); e.abortSignal?.throwIfAborted(); return null; } } /** Worktree callers bound their own wait without cancelling another naming owner's request. */ async function generateWorktreeSessionTitle(e) { const t = { agentId: e.agentId, sessionKey: resolveStoredSessionKeyForAgentStore(e), storePath: e.storePath }; const { waitBudget: n, ...r } = e; const i = maybeGenerateSessionTitle(r); try { await withTimeout(i, WORKTREE_SESSION_TITLE_WAIT_MS, "worktree title generation"); } catch (t) { e.onError(t); } const readCurrent = async (n) => { e.commitGuard?.(); n?.(); const r = await readSessionEntryReadOnlyInWorker(t, () => { e.commitGuard?.(); n?.(); }); if (r?.sessionId !== e.sessionId) throw new Error("Session changed while naming its worktree; retry from the current session."); return resolveExplicitSessionName(r); }; return e.withSource ? await withWorktreeSourceWait(e.withSource, n, (e) => readCurrent(e.assertCurrent)) : readCurrent(); } async function maybeGenerateDashboardSessionTitle(e) { if (!isDashboardSessionTitleCandidate(e)) return false; return await maybeGenerateSessionTitle({ ...e, retryFailedJoin: true }); } /** Joins existing work; only the caller that persists a title returns true. */ async function maybeGenerateSessionTitle(e) { const t = resolveStoredSessionKeyForAgentStore(e); const n = { agentId: e.agentId, sessionKey: t, storePath: e.storePath }; const assertCurrent = () => e.commitGuard?.(); const r = captureSessionActorStorageOwner(n, { assertCurrent, authorize: assertCurrent }); if (r && !r.owner?.readSession(t, r.authority)?.entry) return false; const i = r?.owner?.captureSessionReadGuard(t); const assertMemoryCurrent = () => { i?.(); r?.binding?.actor.assertReadable(); r?.authority.assertCurrent(); }; const a = await readSessionEntryReadOnlyInWorker(n, assertMemoryCurrent); if (a?.sessionId !== e.sessionId || hasExplicitSessionName(a)) return false; const o = { cfg: e.cfg, agentId: e.agentId, entry: a, sessionKey: t, assertCurrent: assertMemoryCurrent }; const s = { ...n, sessionId: e.sessionId }; const c = sessionTitleRequests.get(s); if (c) { const t = await (e.retryFailedJoin ? c.catch(() => false) : c); assertMemoryCurrent(); return !t && e.retryFailedJoin ? await maybeGenerateSessionTitle({ ...e, retryFailedJoin: false }) : false; } const finish = async (t) => { const i = await t; if (!i) return false; const persist = async (t) => { const a = composeSessionSourceAssertion([ e.commitGuard, t, ...r ? [assertMemoryCurrent] : [] ]); if (t) a?.(); let o = false; await patchSessionEntryCore(n, (t) => { if (t.sessionId !== e.sessionId || hasExplicitSessionName(t)) return null; o = true; return { displayName: i }; }, { requireWriteSuccess: true, ...sessionEntryCommitGuardOptions(a) }); return o; }; return e.withSource ? await e.withSource((e) => persist(e.assertCurrent)) : await persist(); }; const run = async () => { const n = await prepareTitleSkillCommands(o); const i = { agentId: e.agentId, sessionEntry: a, sessionId: e.sessionId, sessionKey: t, storePath: e.storePath }; const s = (await readSessionTitleFieldsFromTranscriptAsync(i, { skillCommands: n })).firstUserMessage; assertMemoryCurrent(); const c = s ?? ""; const l = resolveSessionTitleSource(e.currentUserMessage ?? "", n); const u = resolveSessionTitleSource(a.pendingWorktree?.titleSource ?? "", n) ?? (!c || l && l === c ? resolveSessionTitleSource(e.userMessage, n) : c); if (!u) return false; const generate = (t) => generateDashboardSessionTitle({ cfg: e.cfg, agentId: e.agentId, entry: e.entry ?? a, sourceText: u, operatorAuthority: e.operatorAuthority, ...t ? { abortSignal: t } : {}, ...e.retryAfter ? { retryAfter: e.retryAfter } : {}, onFallback: e.onFallback, ...r ? { assertCurrent: assertMemoryCurrent } : {} }); const d = e.withSource; if (!d) { e.commitGuard?.(); return await finish(generate()); } return await runWithAsyncWorkResources(async () => { const t = AsyncLocalStorage.snapshot(); const n = await d((n) => { e.commitGuard?.(); n.assertCurrent(); const r = t(() => trackAsyncWork(() => generate(getAsyncWorkSignal()))); r.catch(() => void 0); return { completion: r }; }); return await finish(n.completion); }, { cancelOnError: true }); }; return await sessionTitleRequests.run(s, run, e.onTitleStateChanged); } //#endregion export { maybeGenerateSessionTitle as a, maybeGenerateDashboardSessionTitle as i, generateWorktreeSessionTitle as n, prepareDashboardSessionTitle as o, isDashboardSessionTitleCandidate as r, buildDashboardSessionTitleSource as t };