openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 11.4 kB
JavaScript
import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{l as trackAsyncWork,o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{D as withTimeout}from"./fs-safe-Bxzu1j4h.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{i as isValidBase64}from"./base64-BbBj85Rq.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{m as sessionEntryCommitGuardOptions,s as composeSessionSourceAssertion}from"./session-source-authority-Cun3s-rH.mjs";import{i as readSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{t as captureSessionActorStorageOwner}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import"./session-accessor-CY8UYP4m.mjs";import{a as SESSION_TITLE_SOURCE_MAX_CHARS,o as resolveSessionTitleSource}from"./session-actor-memory-owner-yGnpeolI.mjs";import{s as resolveStoredSessionKeyForAgentStore}from"./session-store-key-DZXBwthg.mjs";import{i as patchSessionEntryCore}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import{i as resolveSessionRuntimeOverrideForProvider}from"./session-runtime-compat-DGwJiPrH.mjs";import{o as withWorktreeSourceWait}from"./allocation-70UOBpud.mjs";import{t as createCrustaceanSlug}from"./session-slug-Bs6pqTOe.mjs";import{n as resolveExplicitSessionName,r as sessionTitleRequests,t as hasExplicitSessionName}from"./session-title-state-CV8qI-Qb.mjs";import{o as resolveUtilityModelSelectionForAgent}from"./utility-model-CDT0xFeg.mjs";import{t as runWithAsyncWorkResources}from"./async-work-resources-vg9S-hbA.mjs";import{t as readSessionTitleFieldsFromTranscriptAsync}from"./session-transcript-title-reader-CbM8gT-K.mjs";import{t as resolveSessionUtilityPrimary}from"./session-utility-route-D0lQy_Pa.mjs";import{AsyncLocalStorage}from"node:async_hooks";
//!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}}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?`
`:``}${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-`)}function isDashboardSessionTitleCandidate(e){const t=e.userMessage.trim();return Boolean(t&&isAutoTitleSessionKey(e.sessionKey))}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(`
`).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-CsEW1pop.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=resolveSessionUtilityPrimary(e.cfg,e.agentId,e.entry);if(!n){e.onFallback?.();return null}const r=resolveSessionRuntimeOverrideForProvider({provider:n.primaryProvider,entry:e.entry,cfg:e.cfg});const{preferredProfile:i,primaryModelRef:a}=n;const o=resolveUtilityModelSelectionForAgent({cfg:e.cfg,agentId:e.agentId,...n,modelPolicy:e.operatorAuthority?.modelPolicy});const s=`modelRef`in o?o.modelRef:void 0;const generateLabel=async()=>{try{const{generateConversationLabelWithFallback:n}=await import(`./conversation-label-generator-Cd_mCF8f.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}:{},...s?{utilityModelRef:s}:{},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 c=await generateLabel();if(!c&&e.retryAfter){await e.retryAfter;e.assertCurrent?.();e.abortSignal?.throwIfAborted();c=await generateLabel()}if(c)return c;if(e.utilityOnly)return null;e.onFallback?.();return createCrustaceanSlug()}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}}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})}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={...n,sessionId:e.sessionId};const o=sessionTitleRequests.get(a);if(o){const t=await(e.retryFailedJoin?o.catch(()=>false):o);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 i=>{const a=await readSessionEntryReadOnlyInWorker(n,assertMemoryCurrent);if(a?.sessionId!==e.sessionId||hasExplicitSessionName(a))return false;i();const o=await prepareTitleSkillCommands({cfg:e.cfg,agentId:e.agentId,entry:a,sessionKey:t,assertCurrent:assertMemoryCurrent});const s={agentId:e.agentId,sessionEntry:a,sessionId:e.sessionId,sessionKey:t,storePath:e.storePath};const c=(await readSessionTitleFieldsFromTranscriptAsync(s,{skillCommands:o})).firstUserMessage;assertMemoryCurrent();const l=c??``;const u=resolveSessionTitleSource(e.currentUserMessage??``,o);const d=resolveSessionTitleSource(a.pendingWorktree?.titleSource??``,o)??(!l||u&&u===l?resolveSessionTitleSource(e.userMessage,o):l);if(!d)return false;const generate=t=>generateDashboardSessionTitle({cfg:e.cfg,agentId:e.agentId,entry:e.entry??a,sourceText:d,operatorAuthority:e.operatorAuthority,...t?{abortSignal:t}:{},...e.retryAfter?{retryAfter:e.retryAfter}:{},onFallback:e.onFallback,...r?{assertCurrent:assertMemoryCurrent}:{}});const f=e.withSource;if(!f){e.commitGuard?.();return await finish(generate())}return await runWithAsyncWorkResources(async()=>{const t=AsyncLocalStorage.snapshot();const n=await f(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(a,run,e.onTitleStateChanged)}export{maybeGenerateSessionTitle as a,maybeGenerateDashboardSessionTitle as i,generateWorktreeSessionTitle as n,prepareDashboardSessionTitle as o,isDashboardSessionTitleCandidate as r,buildDashboardSessionTitleSource as t};