sillytavern-utils-lib 1.0.65 → 1.0.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- "use strict";var Et=Object.defineProperty;var Rt=(m,i,o)=>i in m?Et(m,i,{enumerable:!0,configurable:!0,writable:!0,value:o}):m[i]=o;var A=(m,i,o)=>Rt(m,typeof i!="symbol"?i+"":i,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./config.cjs"),St=require("./tokenizer.cjs"),gt=require("../../../regex/engine.js"),dt=require("../../../../world-info.js"),a=require("../../../../../script.js"),_t=require("../../../../power-user.js"),ht=require("../../../../group-chats.js");class Ot{constructor(i){A(this,"messages",[]);A(this,"tokenizer");A(this,"maxContext");A(this,"currentTokenCount",0);this.tokenizer=new St.Tokenizer,this.maxContext=i}getTokenCount(i){var o,g;return i.content?((g=(o=i.source)==null?void 0:o.extra)==null?void 0:g.token_count)??this.tokenizer.encode(i.content).length:0}canFit(i){return this.currentTokenCount+this.getTokenCount(i)<=this.maxContext}add(i){if(!i.content)return!0;const o=this.getTokenCount(i);return this.currentTokenCount+o>this.maxContext?!1:(this.messages.push(i),this.currentTokenCount+=o,!0)}addFront(i){if(!i.content)return!0;const o=this.getTokenCount(i);return this.currentTokenCount+o>this.maxContext?!1:(this.messages.unshift(i),this.currentTokenCount+=o,!0)}addMany(i){const o=i.filter(u=>u.content),g=o.map(u=>this.getTokenCount(u)),U=g.reduce((u,P)=>u+P,0);if(this.currentTokenCount+U<=this.maxContext)return this.messages.push(...o),this.currentTokenCount+=U,!0;let b=0;const f=[];for(let u=o.length-1;u>=0;u--){const P=o[u],v=g[u];if(this.currentTokenCount+b+v<=this.maxContext)f.unshift(P),b+=v;else break}return f.length>0&&(this.messages.push(...f),this.currentTokenCount+=b),f.length===o.length}insert(i,o){if(!o.content)return!0;const g=this.getTokenCount(o);return this.currentTokenCount+g>this.maxContext?!1:(this.messages.splice(i,0,o),this.currentTokenCount+=g,!0)}getMessages(){return this.messages}}async function At(m,{targetCharacterId:i,presetName:o,instructName:g,contextName:U,syspromptName:b,maxContext:f,includeNames:u,ignoreCharacterFields:P,ignoreAuthorNote:v,ignoreWorldInfo:Q,messageIndexesBetween:k}={}){var Z,tt,et,ot,nt,st,rt,it,at,pt,ct,lt,ut,mt;if(!["textgenerationwebui","openai"].includes(m))throw new Error("Unsupported API");const n=SillyTavern.getContext();let{description:$,personality:q,persona:J,scenario:z,mesExamples:Pt,system:y,jailbreak:yt}=P?{description:"",personality:"",persona:"",scenario:"",mesExamples:"",system:"",jailbreak:""}:n.getCharacterCardFields({chid:i});const E=m==="textgenerationwebui"?(Z=n.getPresetManager("instruct"))==null?void 0:Z.getCompletionPresetByName(g):void 0,H=!!(E!=null&&E.enabled);let x=s.st_parseMesExamples(Pt,H);function xt(){var e,l;if(typeof f=="number")return f;if(!f||f==="active"||!o)return s.st_getMaxContextSize();if(typeof f=="number")return f;let t;if(m==="textgenerationwebui"){const r=(e=n.getPresetManager("textgenerationwebui"))==null?void 0:e.getCompletionPresetByName(o);t=r==null?void 0:r.max_length}else{const r=(l=n.getPresetManager("openai"))==null?void 0:l.getCompletionPresetByName(o);t=r==null?void 0:r.openai_max_context}return typeof t=="number"?t:s.st_getMaxContextSize()}let M=[];const W=xt();if(W<=0)return{result:[],warnings:M};const c=new Ot(W),Mt=n.ToolManager.isToolCallingSupported(),K=(k==null?void 0:k.start)??0,L=k!=null&&k.end?k.end+1:void 0;let w=K===-1&&L===0?[]:n.chat.slice(K,L).filter(t=>{var e;return!t.is_system||Mt&&Array.isArray((e=t.extra)==null?void 0:e.tool_invocations)});w=await Promise.all(w.map(async(t,e)=>{var j,D;let l=t.mes,r=t.is_user?gt.regex_placement.USER_INPUT:gt.regex_placement.AI_OUTPUT,p={isPrompt:!0,depth:w.length-e-1},d=s.st_getRegexedString(l,r,p);return d=await s.st_appendFileContent(t,d),(j=t==null?void 0:t.extra)!=null&&j.append_title&&((D=t==null?void 0:t.extra)!=null&&D.title)&&(d=`${d}
1
+ "use strict";var Re=Object.defineProperty;var Se=(u,r,s)=>r in u?Re(u,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[r]=s;var O=(u,r,s)=>Se(u,typeof r!="symbol"?r+"":r,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./config.cjs"),Ie=require("./tokenizer.cjs"),A=require("./prompt-message-utils.cjs"),Oe=require("./prompt-slice-utils.cjs"),ge=require("../../../regex/engine.js"),de=require("../../../../world-info.js"),a=require("../../../../../script.js"),_e=require("../../../../power-user.js"),he=require("../../../../group-chats.js");class Ae{constructor(r){O(this,"messages",[]);O(this,"tokenizer");O(this,"maxContext");O(this,"currentTokenCount",0);this.tokenizer=new Ie.Tokenizer,this.maxContext=r}getTokenCount(r){var l,g;const s=A.getMessageText(r);return s?((g=(l=r.source)==null?void 0:l.extra)==null?void 0:g.token_count)??this.tokenizer.encode(s).length:0}canFit(r){return this.currentTokenCount+this.getTokenCount(r)<=this.maxContext}add(r){const s=A.sanitizePromptMessage(r);if(!s)return!0;r=s;const l=this.getTokenCount(r);return this.currentTokenCount+l>this.maxContext?!1:(this.messages.push(r),this.currentTokenCount+=l,!0)}addFront(r){const s=A.sanitizePromptMessage(r);if(!s)return!0;r=s;const l=this.getTokenCount(r);return this.currentTokenCount+l>this.maxContext?!1:(this.messages.unshift(r),this.currentTokenCount+=l,!0)}addMany(r){const s=A.sanitizePromptMessages(r),l=s.map(d=>this.getTokenCount(d)),g=l.reduce((d,x)=>d+x,0);if(this.currentTokenCount+g<=this.maxContext)return this.messages.push(...s),this.currentTokenCount+=g,!0;let b=0;const f=[];for(let d=s.length-1;d>=0;d--){const x=s[d],v=l[d];if(this.currentTokenCount+b+v<=this.maxContext)f.unshift(x),b+=v;else break}return f.length>0&&(this.messages.push(...f),this.currentTokenCount+=b),f.length===s.length}insert(r,s){const l=A.sanitizePromptMessage(s);if(!l)return!0;s=l;const g=this.getTokenCount(s);return this.currentTokenCount+g>this.maxContext?!1:(this.messages.splice(r,0,s),this.currentTokenCount+=g,!0)}getMessages(){return this.messages}}async function Be(u,{targetCharacterId:r,presetName:s,instructName:l,contextName:g,syspromptName:b,maxContext:f,includeNames:d,ignoreCharacterFields:x,ignoreAuthorNote:v,ignoreWorldInfo:Q,messageIndexesBetween:Pe}={}){var Z,ee,te,se,oe,ne,re,ie,ae,pe,ce,me,le,ue;if(!["textgenerationwebui","openai"].includes(u))throw new Error("Unsupported API");const o=SillyTavern.getContext();let{description:q,personality:F,persona:J,scenario:$,mesExamples:xe,system:y,jailbreak:ye}=x?{description:"",personality:"",persona:"",scenario:"",mesExamples:"",system:"",jailbreak:""}:o.getCharacterCardFields({chid:r});const E=u==="textgenerationwebui"?(Z=o.getPresetManager("instruct"))==null?void 0:Z.getCompletionPresetByName(l):void 0,H=!!(E!=null&&E.enabled);let M=n.st_parseMesExamples(xe,H);function Me(){var t,m;if(typeof f=="number")return f;if(!f||f==="active"||!s)return n.st_getMaxContextSize();if(typeof f=="number")return f;let e;if(u==="textgenerationwebui"){const i=(t=o.getPresetManager("textgenerationwebui"))==null?void 0:t.getCompletionPresetByName(s);e=i==null?void 0:i.max_length}else{const i=(m=o.getPresetManager("openai"))==null?void 0:m.getCompletionPresetByName(s);e=i==null?void 0:i.openai_max_context}return typeof e=="number"?e:n.st_getMaxContextSize()}let w=[];const W=Me();if(W<=0)return{result:[],warnings:w};const c=new Ae(W),we=o.ToolManager.isToolCallingSupported(),{startIndex:K,endIndex:L}=Oe.getMessageSliceBounds(Pe);let k=K===-1&&L===0?[]:o.chat.slice(K,L).filter(e=>{var t;return!e.is_system||we&&Array.isArray((t=e.extra)==null?void 0:t.tool_invocations)});k=await Promise.all(k.map(async(e,t)=>{var N,j;let m=e.mes,i=e.is_user?ge.regex_placement.USER_INPUT:ge.regex_placement.AI_OUTPUT,p={isPrompt:!0,depth:k.length-t-1},_=n.st_getRegexedString(m,i,p);return _=await n.st_appendFileContent(e,_),(N=e==null?void 0:e.extra)!=null&&N.append_title&&((j=e==null?void 0:e.extra)!=null&&j.title)&&(_=`${_}
2
2
 
3
- ${t.extra.title}`),{...t,mes:d,index:e}}));const Ct=w.map(t=>dt.world_info_include_names?`${t.name}: ${t.mes}`:t.mes).reverse(),{worldInfoString:Ut,worldInfoBefore:I,worldInfoAfter:N,worldInfoExamples:Tt,worldInfoDepth:kt,anBefore:V,anAfter:X}=Q?{worldInfoString:"",worldInfoBefore:"",worldInfoAfter:"",worldInfoExamples:[],worldInfoDepth:[],anBefore:[],anAfter:[]}:await n.getWorldInfoPrompt(Ct,W,!1);for(const t of Tt){const e=t.content;if(e.length===0)continue;const l=s.st_baseChatReplace(e,a.name1,a.name2),r=s.st_parseMesExamples(l,H);t.position===dt.wi_anchor_position.before?x.unshift(...r):x.push(...r)}function Y(){const t=[];for(let e=w.length-1;e>=0;e--){const l=w[e],r=l.name==="System"&&!l.is_user?"system":l.is_user?"user":"assistant";t.unshift({role:r,content:u&&r!="system"?`${l.name}: ${l.mes}`:l.mes,source:l})}c.addMany(t)}if(m==="textgenerationwebui"){const t=[...x];x&&(x=s.st_formatInstructModeExamples(x,a.name1,a.name2));const e=(tt=n.getPresetManager("sysprompt"))==null?void 0:tt.getCompletionPresetByName(b);e&&(y=n.powerUserSettings.prefer_character_prompt&&y?y:s.st_baseChatReplace(e.content,a.name1,a.name2),y=H?s.st_formatInstructModeSystemPrompt(n.substituteParams(y,a.name1,a.name2,e.content),E):y);const l={description:$,personality:q,persona:n.powerUserSettings.persona_description_position==_t.persona_description_positions.IN_PROMPT?J:"",scenario:z,system:y,char:a.name2,user:a.name1,wiBefore:I,wiAfter:N,loreBefore:I,loreAfter:N,mesExamples:x.join(""),mesExamplesRaw:t.join("")},r=(et=n.getPresetManager("context"))==null?void 0:et.getCompletionPresetByName(U);let p=s.st_renderStoryString(l,{customInstructSettings:E,customStoryString:r==null?void 0:r.story_string});p&&c.add({role:"system",content:p,ignoreInstruct:!0}),Y()}else{let t=function(h){const T=_.find(G=>G.identifier===h);if(T)return T;const ft=p.prompts.find(G=>G.identifier===h);if(ft)return ft},e=s.st_setOpenAIMessages(w),l=s.st_setOpenAIMessageExamples(x);async function r(){let[h,T]=await s.st_prepareOpenAIMessages({name2:a.name2,charDescription:$,charPersonality:q,Scenario:z,worldInfoBefore:I,worldInfoAfter:N,extensionPrompts:n.extensionPrompts,bias:"",type:"normal",quietPrompt:void 0,quietImage:void 0,cyclePrompt:"",systemPromptOverride:y,jailbreakPromptOverride:yt,personaDescription:J,messages:e,messageExamples:l},!1);c.addMany(h)}if(!o)return M.push("No preset name provided. Using default preset."),await r(),{result:c.getMessages(),warnings:M};const p=(ot=n.getPresetManager("openai"))==null?void 0:ot.getCompletionPresetByName(o);if(!p)return console.warn(`Preset not found: ${o}. Using current preset.`),M.push(`Preset not found: ${o}. Using current preset.`),r(),{result:c.getMessages(),warnings:M};let d=(nt=p.prompt_order)==null?void 0:nt.find(h=>h.character_id===a.this_chid);if(!d&&p.prompt_order&&p.prompt_order.length>0&&(d=p.prompt_order[p.prompt_order.length-1]),!d)return console.warn(`No prompt order found for preset: ${o}. Using current preset.`),M.push(`No prompt order found for preset: ${o}. Using current preset.`),r(),{result:c.getMessages(),warnings:M};const j=z&&p.scenario_format?n.substituteParams(p.scenario_format):"",D=q&&p.personality_format?n.substituteParams(p.personality_format):"",bt=n.substituteParams(p.group_nudge_prompt),vt=p.impersonation_prompt?n.substituteParams(p.impersonation_prompt):"",_=[];Q||_.push({role:"system",content:s.st_formatWorldInfo(I,{wiFormat:p.wi_format}),identifier:"worldInfoBefore"},{role:"system",content:s.st_formatWorldInfo(N,{wiFormat:p.wi_format}),identifier:"worldInfoAfter"}),P||_.push({role:"system",content:$,identifier:"charDescription"},{role:"system",content:D,identifier:"charPersonality"},{role:"system",content:j,identifier:"scenario"}),_.push({role:"system",content:vt,identifier:"impersonate"},{role:"system",content:bt,identifier:"groupNudge"});const R=n.extensionPrompts["1_memory"];R&&R.value&&_.push({role:s.st_getPromptRole(R.role),content:R.value,identifier:"summary",position:s.st_getPromptPosition(R.position)});const S=n.extensionPrompts["2_floating_prompt"];!v&&S&&S.value&&_.push({role:s.st_getPromptRole(S.role),content:S.value,identifier:"authorsNote",position:s.st_getPromptPosition(S.position)});const B=n.extensionPrompts["3_vectors"];B&&B.value&&_.push({role:"system",content:B.value,identifier:"vectorsMemory",position:s.st_getPromptPosition(B.position)});const O=n.extensionPrompts["4_vectors_data_bank"];O&&O.value&&_.push({role:s.st_getPromptRole(O.role),content:O.value,identifier:"vectorsDataBank",position:s.st_getPromptPosition(O.position)});const F=n.extensionPrompts.chromadb;F&&F.value&&_.push({role:"system",content:F.value,identifier:"smartContext",position:s.st_getPromptPosition(F.position)}),!P&&n.powerUserSettings.persona_description&&n.powerUserSettings.persona_description_position===_t.persona_description_positions.IN_PROMPT&&_.push({role:"system",content:n.powerUserSettings.persona_description,identifier:"personaDescription"}),d.order.forEach(h=>{if(!h.enabled)return;const T=t(h.identifier);if(T&&T.content){c.add({role:T.role??"system",content:n.substituteParams(T.content)});return}h.identifier==="chatHistory"&&Y()})}const wt=["1_memory","2_floating_prompt","3_vectors","4_vectors_data_bank","chromadb","PERSONA_DESCRIPTION","QUIET_PROMPT","DEPTH_PROMPT"];for(const t in n.extensionPrompts)if(Object.hasOwn(n.extensionPrompts,t)){const e=n.extensionPrompts[t];if(wt.includes(t)||!n.extensionPrompts[t].value||![a.extension_prompt_types.BEFORE_PROMPT,a.extension_prompt_types.IN_PROMPT].includes(e.position)||typeof e.filter=="function"&&!await e.filter())continue;const r={role:s.st_getPromptRole(e.role)??"system",content:e.value};if(e.position===a.extension_prompt_types.BEFORE_PROMPT)c.insert(e.depth,r);else if(e.position===a.extension_prompt_types.IN_PROMPT){const p=c.getMessages();c.insert(p.length-e.depth,r)}}for(const t of kt){const e=c.getMessages();c.insert(e.length-t.depth,{role:s.st_getPromptRole(t.role),content:t.entries.join(`
4
- `)})}if(!P){const t=s.st_getGroupDepthPrompts(ht.selected_group,Number(a.this_chid));if(ht.selected_group&&Array.isArray(t)&&t.length>0)t.filter(e=>e.text).forEach((e,l)=>{const r=c.getMessages();c.insert(r.length-e.depth,{role:e.role,content:e.text})});else{const e=s.st_baseChatReplace((pt=(at=(it=(rt=(st=n.characters[a.this_chid])==null?void 0:st.data)==null?void 0:rt.extensions)==null?void 0:it.depth_prompt)==null?void 0:at.prompt)==null?void 0:pt.trim(),a.name1,a.name2)||"";if(e){const l=a.depth_prompt_depth_default,r=((mt=(ut=(lt=(ct=n.characters[a.this_chid])==null?void 0:ct.data)==null?void 0:lt.extensions)==null?void 0:ut.depth_prompt)==null?void 0:mt.role)??a.depth_prompt_role_default,p=c.getMessages();c.insert(p.length-l,{role:s.st_getPromptRole(r),content:e})}}}let C=-1;if(!v){const t=s.st_getAuthorNote();if(t.prompt){t.prompt=s.st_baseChatReplace(t.prompt,a.name1,a.name2);const e={role:s.st_getPromptRole(t.role),content:t.prompt};switch(t.position){case a.extension_prompt_types.IN_PROMPT:c.insert(1,e),C=1;break;case a.extension_prompt_types.IN_CHAT:C=c.getMessages().length-t.depth,c.insert(C,e);break;case a.extension_prompt_types.BEFORE_PROMPT:c.addFront(e),C=0;break}}}return C>=0&&(V.length>0&&(c.insert(C,{role:"system",content:V.join(`
3
+ ${e.extra.title}`),{...e,mes:_,index:t}}));const Ce=k.map(e=>de.world_info_include_names?`${e.name}: ${e.mes}`:e.mes).reverse(),{worldInfoString:Ue,worldInfoBefore:B,worldInfoAfter:U,worldInfoExamples:Te,worldInfoDepth:ke,anBefore:V,anAfter:X}=Q?{worldInfoString:"",worldInfoBefore:"",worldInfoAfter:"",worldInfoExamples:[],worldInfoDepth:[],anBefore:[],anAfter:[]}:await o.getWorldInfoPrompt(Ce,W,!1);for(const e of Te){const t=e.content;if(t.length===0)continue;const m=n.st_baseChatReplace(t,a.name1,a.name2),i=n.st_parseMesExamples(m,H);e.position===de.wi_anchor_position.before?M.unshift(...i):M.push(...i)}function Y(){const e=[];for(let t=k.length-1;t>=0;t--){const m=k[t],i=m.name==="System"&&!m.is_user?"system":m.is_user?"user":"assistant";e.unshift({role:i,content:d&&i!="system"?`${m.name}: ${m.mes}`:m.mes,source:m})}c.addMany(e)}if(u==="textgenerationwebui"){const e=[...M];M&&(M=n.st_formatInstructModeExamples(M,a.name1,a.name2));const t=(ee=o.getPresetManager("sysprompt"))==null?void 0:ee.getCompletionPresetByName(b);t&&(y=o.powerUserSettings.prefer_character_prompt&&y?y:n.st_baseChatReplace(t.content,a.name1,a.name2),y=H?n.st_formatInstructModeSystemPrompt(o.substituteParams(y,a.name1,a.name2,t.content),E):y);const m={description:q,personality:F,persona:o.powerUserSettings.persona_description_position==_e.persona_description_positions.IN_PROMPT?J:"",scenario:$,system:y,char:a.name2,user:a.name1,wiBefore:B,wiAfter:U,loreBefore:B,loreAfter:U,mesExamples:M.join(""),mesExamplesRaw:e.join("")},i=(te=o.getPresetManager("context"))==null?void 0:te.getCompletionPresetByName(g);let p=n.st_renderStoryString(m,{customInstructSettings:E,customStoryString:i==null?void 0:i.story_string});p&&c.add({role:"system",content:p,ignoreInstruct:!0}),Y()}else{let e=function(P){const T=h.find(G=>G.identifier===P);if(T)return T;const fe=p.prompts.find(G=>G.identifier===P);if(fe)return fe},t=n.st_setOpenAIMessages(k),m=n.st_setOpenAIMessageExamples(M);async function i(){let[P,T]=await n.st_prepareOpenAIMessages({name2:a.name2,charDescription:q,charPersonality:F,Scenario:$,worldInfoBefore:B,worldInfoAfter:U,extensionPrompts:o.extensionPrompts,bias:"",type:"normal",quietPrompt:void 0,quietImage:void 0,cyclePrompt:"",systemPromptOverride:y,jailbreakPromptOverride:ye,personaDescription:J,messages:t,messageExamples:m},!1);c.addMany(P)}if(!s)return w.push("No preset name provided. Using default preset."),await i(),{result:c.getMessages(),warnings:w};const p=(se=o.getPresetManager("openai"))==null?void 0:se.getCompletionPresetByName(s);if(!p)return console.warn(`Preset not found: ${s}. Using current preset.`),w.push(`Preset not found: ${s}. Using current preset.`),i(),{result:c.getMessages(),warnings:w};let _=(oe=p.prompt_order)==null?void 0:oe.find(P=>P.character_id===a.this_chid);if(!_&&p.prompt_order&&p.prompt_order.length>0&&(_=p.prompt_order[p.prompt_order.length-1]),!_)return console.warn(`No prompt order found for preset: ${s}. Using current preset.`),w.push(`No prompt order found for preset: ${s}. Using current preset.`),i(),{result:c.getMessages(),warnings:w};const N=$&&p.scenario_format?o.substituteParams(p.scenario_format):"",j=F&&p.personality_format?o.substituteParams(p.personality_format):"",ve=o.substituteParams(p.group_nudge_prompt),Ee=p.impersonation_prompt?o.substituteParams(p.impersonation_prompt):"",h=[];Q||h.push({role:"system",content:n.st_formatWorldInfo(B,{wiFormat:p.wi_format}),identifier:"worldInfoBefore"},{role:"system",content:n.st_formatWorldInfo(U,{wiFormat:p.wi_format}),identifier:"worldInfoAfter"}),x||h.push({role:"system",content:q,identifier:"charDescription"},{role:"system",content:j,identifier:"charPersonality"},{role:"system",content:N,identifier:"scenario"}),h.push({role:"system",content:Ee,identifier:"impersonate"},{role:"system",content:ve,identifier:"groupNudge"});const R=o.extensionPrompts["1_memory"];R&&R.value&&h.push({role:n.st_getPromptRole(R.role),content:R.value,identifier:"summary",position:n.st_getPromptPosition(R.position)});const S=o.extensionPrompts["2_floating_prompt"];!v&&S&&S.value&&h.push({role:n.st_getPromptRole(S.role),content:S.value,identifier:"authorsNote",position:n.st_getPromptPosition(S.position)});const z=o.extensionPrompts["3_vectors"];z&&z.value&&h.push({role:"system",content:z.value,identifier:"vectorsMemory",position:n.st_getPromptPosition(z.position)});const I=o.extensionPrompts["4_vectors_data_bank"];I&&I.value&&h.push({role:n.st_getPromptRole(I.role),content:I.value,identifier:"vectorsDataBank",position:n.st_getPromptPosition(I.position)});const D=o.extensionPrompts.chromadb;D&&D.value&&h.push({role:"system",content:D.value,identifier:"smartContext",position:n.st_getPromptPosition(D.position)}),!x&&o.powerUserSettings.persona_description&&o.powerUserSettings.persona_description_position===_e.persona_description_positions.IN_PROMPT&&h.push({role:"system",content:o.powerUserSettings.persona_description,identifier:"personaDescription"}),_.order.forEach(P=>{if(!P.enabled)return;const T=e(P.identifier);if(T&&T.content){c.add({role:T.role??"system",content:o.substituteParams(T.content)});return}P.identifier==="chatHistory"&&Y()})}const be=["1_memory","2_floating_prompt","3_vectors","4_vectors_data_bank","chromadb","PERSONA_DESCRIPTION","QUIET_PROMPT","DEPTH_PROMPT"];for(const e in o.extensionPrompts)if(Object.hasOwn(o.extensionPrompts,e)){const t=o.extensionPrompts[e];if(be.includes(e)||!o.extensionPrompts[e].value||![a.extension_prompt_types.BEFORE_PROMPT,a.extension_prompt_types.IN_PROMPT].includes(t.position)||typeof t.filter=="function"&&!await t.filter())continue;const i={role:n.st_getPromptRole(t.role)??"system",content:t.value};if(t.position===a.extension_prompt_types.BEFORE_PROMPT)c.insert(t.depth,i);else if(t.position===a.extension_prompt_types.IN_PROMPT){const p=c.getMessages();c.insert(p.length-t.depth,i)}}for(const e of ke){const t=c.getMessages();c.insert(t.length-e.depth,{role:n.st_getPromptRole(e.role),content:e.entries.join(`
4
+ `)})}if(!x){const e=n.st_getGroupDepthPrompts(he.selected_group,Number(a.this_chid));if(he.selected_group&&Array.isArray(e)&&e.length>0)e.filter(t=>t.text).forEach((t,m)=>{const i=c.getMessages();c.insert(i.length-t.depth,{role:t.role,content:t.text})});else{const t=n.st_baseChatReplace((pe=(ae=(ie=(re=(ne=o.characters[a.this_chid])==null?void 0:ne.data)==null?void 0:re.extensions)==null?void 0:ie.depth_prompt)==null?void 0:ae.prompt)==null?void 0:pe.trim(),a.name1,a.name2)||"";if(t){const m=a.depth_prompt_depth_default,i=((ue=(le=(me=(ce=o.characters[a.this_chid])==null?void 0:ce.data)==null?void 0:me.extensions)==null?void 0:le.depth_prompt)==null?void 0:ue.role)??a.depth_prompt_role_default,p=c.getMessages();c.insert(p.length-m,{role:n.st_getPromptRole(i),content:t})}}}let C=-1;if(!v){const e=n.st_getAuthorNote();if(e.prompt){e.prompt=n.st_baseChatReplace(e.prompt,a.name1,a.name2);const t={role:n.st_getPromptRole(e.role),content:e.prompt};switch(e.position){case a.extension_prompt_types.IN_PROMPT:c.insert(1,t),C=1;break;case a.extension_prompt_types.IN_CHAT:C=c.getMessages().length-e.depth,c.insert(C,t);break;case a.extension_prompt_types.BEFORE_PROMPT:c.addFront(t),C=0;break}}}return C>=0&&(V.length>0&&(c.insert(C,{role:"system",content:V.join(`
5
5
  `)}),C++),X.length>0&&c.insert(C+1,{role:"system",content:X.join(`
6
- `)})),{result:c.getMessages(),warnings:M}}exports.buildPrompt=At;
6
+ `)})),{result:c.getMessages(),warnings:w}}exports.buildPrompt=Be;
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-builder.d.ts","sourceRoot":"","sources":["../src/prompt-builder.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAMtE,MAAM,WAAW,OAAQ,SAAQ,qBAAqB;IACpD,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;IAC1C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;OAEG;IACH,qBAAqB,CAAC,EAAE;QACtB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;CACH;AAmGD;;;;;;GAMG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,MAAM,EACX,EACE,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,aAAa,EACb,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,qBAAqB,GACtB,GAAE,kBAAuB,GACzB,OAAO,CAAC;IAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAsgBrD"}
1
+ {"version":3,"file":"prompt-builder.d.ts","sourceRoot":"","sources":["../src/prompt-builder.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAQtE,MAAM,WAAW,OAAQ,SAAQ,qBAAqB;IACpD,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;IAC1C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;OAEG;IACH,qBAAqB,CAAC,EAAE;QACtB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;CACH;AA0GD;;;;;;GAMG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,MAAM,EACX,EACE,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,aAAa,EACb,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,qBAAqB,GACtB,GAAE,kBAAuB,GACzB,OAAO,CAAC;IAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAqgBrD"}
@@ -1,80 +1,89 @@
1
- var It = Object.defineProperty;
2
- var Dt = (l, s, o) => s in l ? It(l, s, { enumerable: !0, configurable: !0, writable: !0, value: o }) : l[s] = o;
3
- var U = (l, s, o) => Dt(l, typeof s != "symbol" ? s + "" : s, o);
4
- import { st_parseMesExamples as xt, st_getRegexedString as Bt, st_appendFileContent as Ft, st_baseChatReplace as q, st_formatInstructModeExamples as $t, st_formatInstructModeSystemPrompt as jt, st_renderStoryString as zt, st_setOpenAIMessages as Ht, st_setOpenAIMessageExamples as qt, st_formatWorldInfo as Mt, st_getPromptPosition as I, st_getPromptRole as w, st_getGroupDepthPrompts as Wt, st_getAuthorNote as Gt, st_getMaxContextSize as X, st_prepareOpenAIMessages as Qt } from "./config.js";
5
- import { Tokenizer as Jt } from "./tokenizer.js";
6
- import { regex_placement as Tt } from "../../../regex/engine.js";
7
- import { world_info_include_names as Kt, wi_anchor_position as Lt } from "../../../../world-info.js";
8
- import { name1 as b, name2 as T, this_chid as W, extension_prompt_types as v, depth_prompt_role_default as Vt, depth_prompt_depth_default as Xt } from "../../../../../script.js";
9
- import { persona_description_positions as Ct } from "../../../../power-user.js";
10
- import { selected_group as kt } from "../../../../group-chats.js";
11
- class Yt {
12
- constructor(s) {
13
- U(this, "messages", []);
14
- U(this, "tokenizer");
15
- U(this, "maxContext");
16
- U(this, "currentTokenCount", 0);
17
- this.tokenizer = new Jt(), this.maxContext = s;
1
+ var Ue = Object.defineProperty;
2
+ var De = (m, n, o) => n in m ? Ue(m, n, { enumerable: !0, configurable: !0, writable: !0, value: o }) : m[n] = o;
3
+ var B = (m, n, o) => De(m, typeof n != "symbol" ? n + "" : n, o);
4
+ import { st_parseMesExamples as ye, st_getRegexedString as ze, st_appendFileContent as Fe, st_baseChatReplace as H, st_formatInstructModeExamples as $e, st_formatInstructModeSystemPrompt as je, st_renderStoryString as He, st_setOpenAIMessages as qe, st_setOpenAIMessageExamples as We, st_formatWorldInfo as Me, st_getPromptPosition as N, st_getPromptRole as k, st_getGroupDepthPrompts as Ge, st_getAuthorNote as Qe, st_getMaxContextSize as V, st_prepareOpenAIMessages as Je } from "./config.js";
5
+ import { Tokenizer as Ke } from "./tokenizer.js";
6
+ import { getMessageText as Le, sanitizePromptMessage as X, sanitizePromptMessages as Ve } from "./prompt-message-utils.js";
7
+ import { getMessageSliceBounds as Xe } from "./prompt-slice-utils.js";
8
+ import { regex_placement as we } from "../../../regex/engine.js";
9
+ import { world_info_include_names as Ye, wi_anchor_position as Ze } from "../../../../world-info.js";
10
+ import { name1 as b, name2 as T, this_chid as q, extension_prompt_types as v, depth_prompt_role_default as et, depth_prompt_depth_default as tt } from "../../../../../script.js";
11
+ import { persona_description_positions as Te } from "../../../../power-user.js";
12
+ import { selected_group as Ce } from "../../../../group-chats.js";
13
+ class ot {
14
+ constructor(n) {
15
+ B(this, "messages", []);
16
+ B(this, "tokenizer");
17
+ B(this, "maxContext");
18
+ B(this, "currentTokenCount", 0);
19
+ this.tokenizer = new Ke(), this.maxContext = n;
18
20
  }
19
- getTokenCount(s) {
20
- var o, m;
21
- return s.content ? ((m = (o = s.source) == null ? void 0 : o.extra) == null ? void 0 : m.token_count) ?? this.tokenizer.encode(s.content).length : 0;
21
+ getTokenCount(n) {
22
+ var c, u;
23
+ const o = Le(n);
24
+ return o ? ((u = (c = n.source) == null ? void 0 : c.extra) == null ? void 0 : u.token_count) ?? this.tokenizer.encode(o).length : 0;
22
25
  }
23
- canFit(s) {
24
- return this.currentTokenCount + this.getTokenCount(s) <= this.maxContext;
26
+ canFit(n) {
27
+ return this.currentTokenCount + this.getTokenCount(n) <= this.maxContext;
25
28
  }
26
- add(s) {
27
- if (!s.content) return !0;
28
- const o = this.getTokenCount(s);
29
- return this.currentTokenCount + o > this.maxContext ? !1 : (this.messages.push(s), this.currentTokenCount += o, !0);
29
+ add(n) {
30
+ const o = X(n);
31
+ if (!o) return !0;
32
+ n = o;
33
+ const c = this.getTokenCount(n);
34
+ return this.currentTokenCount + c > this.maxContext ? !1 : (this.messages.push(n), this.currentTokenCount += c, !0);
30
35
  }
31
- addFront(s) {
32
- if (!s.content) return !0;
33
- const o = this.getTokenCount(s);
34
- return this.currentTokenCount + o > this.maxContext ? !1 : (this.messages.unshift(s), this.currentTokenCount += o, !0);
36
+ addFront(n) {
37
+ const o = X(n);
38
+ if (!o) return !0;
39
+ n = o;
40
+ const c = this.getTokenCount(n);
41
+ return this.currentTokenCount + c > this.maxContext ? !1 : (this.messages.unshift(n), this.currentTokenCount += c, !0);
35
42
  }
36
- addMany(s) {
37
- const o = s.filter((c) => c.content), m = o.map((c) => this.getTokenCount(c)), D = m.reduce((c, h) => c + h, 0);
38
- if (this.currentTokenCount + D <= this.maxContext)
39
- return this.messages.push(...o), this.currentTokenCount += D, !0;
43
+ addMany(n) {
44
+ const o = Ve(n), c = o.map((f) => this.getTokenCount(f)), u = c.reduce((f, _) => f + _, 0);
45
+ if (this.currentTokenCount + u <= this.maxContext)
46
+ return this.messages.push(...o), this.currentTokenCount += u, !0;
40
47
  let E = 0;
41
- const u = [];
42
- for (let c = o.length - 1; c >= 0; c--) {
43
- const h = o[c], O = m[c];
44
- if (this.currentTokenCount + E + O <= this.maxContext)
45
- u.unshift(h), E += O;
48
+ const l = [];
49
+ for (let f = o.length - 1; f >= 0; f--) {
50
+ const _ = o[f], I = c[f];
51
+ if (this.currentTokenCount + E + I <= this.maxContext)
52
+ l.unshift(_), E += I;
46
53
  else
47
54
  break;
48
55
  }
49
- return u.length > 0 && (this.messages.push(...u), this.currentTokenCount += E), u.length === o.length;
56
+ return l.length > 0 && (this.messages.push(...l), this.currentTokenCount += E), l.length === o.length;
50
57
  }
51
- insert(s, o) {
52
- if (!o.content) return !0;
53
- const m = this.getTokenCount(o);
54
- return this.currentTokenCount + m > this.maxContext ? !1 : (this.messages.splice(s, 0, o), this.currentTokenCount += m, !0);
58
+ insert(n, o) {
59
+ const c = X(o);
60
+ if (!c) return !0;
61
+ o = c;
62
+ const u = this.getTokenCount(o);
63
+ return this.currentTokenCount + u > this.maxContext ? !1 : (this.messages.splice(n, 0, o), this.currentTokenCount += u, !0);
55
64
  }
56
65
  getMessages() {
57
66
  return this.messages;
58
67
  }
59
68
  }
60
- async function ce(l, {
61
- targetCharacterId: s,
69
+ async function gt(m, {
70
+ targetCharacterId: n,
62
71
  presetName: o,
63
- instructName: m,
64
- contextName: D,
72
+ instructName: c,
73
+ contextName: u,
65
74
  syspromptName: E,
66
- maxContext: u,
67
- includeNames: c,
68
- ignoreCharacterFields: h,
69
- ignoreAuthorNote: O,
75
+ maxContext: l,
76
+ includeNames: f,
77
+ ignoreCharacterFields: _,
78
+ ignoreAuthorNote: I,
70
79
  ignoreWorldInfo: Y,
71
- messageIndexesBetween: C
80
+ messageIndexesBetween: ke
72
81
  } = {}) {
73
- var st, it, at, pt, ct, lt, ut, mt, ft, dt, gt, ht, _t, Pt;
74
- if (!["textgenerationwebui", "openai"].includes(l))
82
+ var re, ie, ae, pe, ce, me, le, ue, fe, de, ge, he, _e, Pe;
83
+ if (!["textgenerationwebui", "openai"].includes(m))
75
84
  throw new Error("Unsupported API");
76
- const n = SillyTavern.getContext();
77
- let { description: G, personality: Q, persona: Z, scenario: J, mesExamples: wt, system: _, jailbreak: bt } = h ? {
85
+ const s = SillyTavern.getContext();
86
+ let { description: W, personality: G, persona: Z, scenario: Q, mesExamples: be, system: P, jailbreak: ve } = _ ? {
78
87
  description: "",
79
88
  personality: "",
80
89
  persona: "",
@@ -82,54 +91,54 @@ async function ce(l, {
82
91
  mesExamples: "",
83
92
  system: "",
84
93
  jailbreak: ""
85
- } : n.getCharacterCardFields({
86
- chid: s
94
+ } : s.getCharacterCardFields({
95
+ chid: n
87
96
  });
88
- const S = l === "textgenerationwebui" ? (st = n.getPresetManager("instruct")) == null ? void 0 : st.getCompletionPresetByName(m) : void 0, K = !!(S != null && S.enabled);
89
- let P = xt(wt, K);
90
- function vt() {
91
- var e, p;
92
- if (typeof u == "number")
93
- return u;
94
- if (!u)
95
- return X();
96
- if (u === "active" || !o)
97
- return X();
98
- if (typeof u == "number")
99
- return u;
100
- let t;
101
- if (l === "textgenerationwebui") {
102
- const r = (e = n.getPresetManager("textgenerationwebui")) == null ? void 0 : e.getCompletionPresetByName(o);
103
- t = r == null ? void 0 : r.max_length;
97
+ const S = m === "textgenerationwebui" ? (re = s.getPresetManager("instruct")) == null ? void 0 : re.getCompletionPresetByName(c) : void 0, J = !!(S != null && S.enabled);
98
+ let x = ye(be, J);
99
+ function Ee() {
100
+ var t, p;
101
+ if (typeof l == "number")
102
+ return l;
103
+ if (!l)
104
+ return V();
105
+ if (l === "active" || !o)
106
+ return V();
107
+ if (typeof l == "number")
108
+ return l;
109
+ let e;
110
+ if (m === "textgenerationwebui") {
111
+ const r = (t = s.getPresetManager("textgenerationwebui")) == null ? void 0 : t.getCompletionPresetByName(o);
112
+ e = r == null ? void 0 : r.max_length;
104
113
  } else {
105
- const r = (p = n.getPresetManager("openai")) == null ? void 0 : p.getCompletionPresetByName(o);
106
- t = r == null ? void 0 : r.openai_max_context;
114
+ const r = (p = s.getPresetManager("openai")) == null ? void 0 : p.getCompletionPresetByName(o);
115
+ e = r == null ? void 0 : r.openai_max_context;
107
116
  }
108
- return typeof t == "number" ? t : X();
117
+ return typeof e == "number" ? e : V();
109
118
  }
110
119
  let y = [];
111
- const L = vt();
112
- if (L <= 0)
120
+ const K = Ee();
121
+ if (K <= 0)
113
122
  return { result: [], warnings: y };
114
- const a = new Yt(L), Et = n.ToolManager.isToolCallingSupported(), tt = (C == null ? void 0 : C.start) ?? 0, et = C != null && C.end ? C.end + 1 : void 0;
115
- let k = tt === -1 && et === 0 ? [] : n.chat.slice(tt, et).filter((t) => {
116
- var e;
117
- return !t.is_system || Et && Array.isArray((e = t.extra) == null ? void 0 : e.tool_invocations);
123
+ const a = new ot(K), Ie = s.ToolManager.isToolCallingSupported(), { startIndex: ee, endIndex: te } = Xe(ke);
124
+ let C = ee === -1 && te === 0 ? [] : s.chat.slice(ee, te).filter((e) => {
125
+ var t;
126
+ return !e.is_system || Ie && Array.isArray((t = e.extra) == null ? void 0 : t.tool_invocations);
118
127
  });
119
- k = await Promise.all(
120
- k.map(async (t, e) => {
121
- var $, j;
122
- let p = t.mes, r = t.is_user ? Tt.USER_INPUT : Tt.AI_OUTPUT, i = { isPrompt: !0, depth: k.length - e - 1 }, f = Bt(p, r, i);
123
- return f = await Ft(t, f), ($ = t == null ? void 0 : t.extra) != null && $.append_title && ((j = t == null ? void 0 : t.extra) != null && j.title) && (f = `${f}
128
+ C = await Promise.all(
129
+ C.map(async (e, t) => {
130
+ var z, F;
131
+ let p = e.mes, r = e.is_user ? we.USER_INPUT : we.AI_OUTPUT, i = { isPrompt: !0, depth: C.length - t - 1 }, d = ze(p, r, i);
132
+ return d = await Fe(e, d), (z = e == null ? void 0 : e.extra) != null && z.append_title && ((F = e == null ? void 0 : e.extra) != null && F.title) && (d = `${d}
124
133
 
125
- ${t.extra.title}`), {
126
- ...t,
127
- mes: f,
128
- index: e
134
+ ${e.extra.title}`), {
135
+ ...e,
136
+ mes: d,
137
+ index: t
129
138
  };
130
139
  })
131
140
  );
132
- const Ot = k.map((t) => Kt ? `${t.name}: ${t.mes}` : t.mes).reverse(), { worldInfoString: Zt, worldInfoBefore: B, worldInfoAfter: F, worldInfoExamples: St, worldInfoDepth: At, anBefore: ot, anAfter: nt } = Y ? {
141
+ const Se = C.map((e) => Ye ? `${e.name}: ${e.mes}` : e.mes).reverse(), { worldInfoString: st, worldInfoBefore: U, worldInfoAfter: D, worldInfoExamples: Oe, worldInfoDepth: Ae, anBefore: oe, anAfter: se } = Y ? {
133
142
  worldInfoString: "",
134
143
  worldInfoBefore: "",
135
144
  worldInfoAfter: "",
@@ -137,169 +146,169 @@ ${t.extra.title}`), {
137
146
  worldInfoDepth: [],
138
147
  anBefore: [],
139
148
  anAfter: []
140
- } : await n.getWorldInfoPrompt(Ot, L, !1);
141
- for (const t of St) {
142
- const e = t.content;
143
- if (e.length === 0)
149
+ } : await s.getWorldInfoPrompt(Se, K, !1);
150
+ for (const e of Oe) {
151
+ const t = e.content;
152
+ if (t.length === 0)
144
153
  continue;
145
- const p = q(e, b, T), r = xt(p, K);
146
- t.position === Lt.before ? P.unshift(...r) : P.push(...r);
154
+ const p = H(t, b, T), r = ye(p, J);
155
+ e.position === Ze.before ? x.unshift(...r) : x.push(...r);
147
156
  }
148
- function rt() {
149
- const t = [];
150
- for (let e = k.length - 1; e >= 0; e--) {
151
- const p = k[e], r = p.name === "System" && !p.is_user ? "system" : p.is_user ? "user" : "assistant";
152
- t.unshift({
157
+ function ne() {
158
+ const e = [];
159
+ for (let t = C.length - 1; t >= 0; t--) {
160
+ const p = C[t], r = p.name === "System" && !p.is_user ? "system" : p.is_user ? "user" : "assistant";
161
+ e.unshift({
153
162
  role: r,
154
- content: c && r != "system" ? `${p.name}: ${p.mes}` : p.mes,
163
+ content: f && r != "system" ? `${p.name}: ${p.mes}` : p.mes,
155
164
  source: p
156
165
  });
157
166
  }
158
- a.addMany(t);
167
+ a.addMany(e);
159
168
  }
160
- if (l === "textgenerationwebui") {
161
- const t = [...P];
162
- P && (P = $t(P, b, T));
163
- const e = (it = n.getPresetManager("sysprompt")) == null ? void 0 : it.getCompletionPresetByName(E);
164
- e && (_ = n.powerUserSettings.prefer_character_prompt && _ ? _ : q(e.content, b, T), _ = K ? jt(
165
- n.substituteParams(_, b, T, e.content),
169
+ if (m === "textgenerationwebui") {
170
+ const e = [...x];
171
+ x && (x = $e(x, b, T));
172
+ const t = (ie = s.getPresetManager("sysprompt")) == null ? void 0 : ie.getCompletionPresetByName(E);
173
+ t && (P = s.powerUserSettings.prefer_character_prompt && P ? P : H(t.content, b, T), P = J ? je(
174
+ s.substituteParams(P, b, T, t.content),
166
175
  S
167
- ) : _);
176
+ ) : P);
168
177
  const p = {
169
- description: G,
170
- personality: Q,
171
- persona: n.powerUserSettings.persona_description_position == Ct.IN_PROMPT ? Z : "",
172
- scenario: J,
173
- system: _,
178
+ description: W,
179
+ personality: G,
180
+ persona: s.powerUserSettings.persona_description_position == Te.IN_PROMPT ? Z : "",
181
+ scenario: Q,
182
+ system: P,
174
183
  char: T,
175
184
  user: b,
176
- wiBefore: B,
177
- wiAfter: F,
178
- loreBefore: B,
179
- loreAfter: F,
180
- mesExamples: P.join(""),
181
- mesExamplesRaw: t.join("")
182
- }, r = (at = n.getPresetManager("context")) == null ? void 0 : at.getCompletionPresetByName(D);
183
- let i = zt(p, {
185
+ wiBefore: U,
186
+ wiAfter: D,
187
+ loreBefore: U,
188
+ loreAfter: D,
189
+ mesExamples: x.join(""),
190
+ mesExamplesRaw: e.join("")
191
+ }, r = (ae = s.getPresetManager("context")) == null ? void 0 : ae.getCompletionPresetByName(u);
192
+ let i = He(p, {
184
193
  customInstructSettings: S,
185
194
  customStoryString: r == null ? void 0 : r.story_string
186
195
  });
187
- i && a.add({ role: "system", content: i, ignoreInstruct: !0 }), rt();
196
+ i && a.add({ role: "system", content: i, ignoreInstruct: !0 }), ne();
188
197
  } else {
189
- let t = function(g) {
190
- const M = d.find((V) => V.identifier === g);
191
- if (M)
192
- return M;
193
- const yt = i.prompts.find((V) => V.identifier === g);
194
- if (yt)
195
- return yt;
196
- }, e = Ht(k), p = qt(P);
198
+ let e = function(h) {
199
+ const w = g.find((L) => L.identifier === h);
200
+ if (w)
201
+ return w;
202
+ const xe = i.prompts.find((L) => L.identifier === h);
203
+ if (xe)
204
+ return xe;
205
+ }, t = qe(C), p = We(x);
197
206
  async function r() {
198
- let [g, M] = await Qt(
207
+ let [h, w] = await Je(
199
208
  {
200
209
  name2: T,
201
- charDescription: G,
202
- charPersonality: Q,
203
- Scenario: J,
204
- worldInfoBefore: B,
205
- worldInfoAfter: F,
206
- extensionPrompts: n.extensionPrompts,
210
+ charDescription: W,
211
+ charPersonality: G,
212
+ Scenario: Q,
213
+ worldInfoBefore: U,
214
+ worldInfoAfter: D,
215
+ extensionPrompts: s.extensionPrompts,
207
216
  bias: "",
208
217
  type: "normal",
209
218
  quietPrompt: void 0,
210
219
  quietImage: void 0,
211
220
  cyclePrompt: "",
212
- systemPromptOverride: _,
213
- jailbreakPromptOverride: bt,
221
+ systemPromptOverride: P,
222
+ jailbreakPromptOverride: ve,
214
223
  personaDescription: Z,
215
- messages: e,
224
+ messages: t,
216
225
  messageExamples: p
217
226
  },
218
227
  !1
219
228
  );
220
- a.addMany(g);
229
+ a.addMany(h);
221
230
  }
222
231
  if (!o)
223
232
  return y.push("No preset name provided. Using default preset."), await r(), { result: a.getMessages(), warnings: y };
224
- const i = (pt = n.getPresetManager("openai")) == null ? void 0 : pt.getCompletionPresetByName(o);
233
+ const i = (pe = s.getPresetManager("openai")) == null ? void 0 : pe.getCompletionPresetByName(o);
225
234
  if (!i)
226
235
  return console.warn(`Preset not found: ${o}. Using current preset.`), y.push(`Preset not found: ${o}. Using current preset.`), r(), { result: a.getMessages(), warnings: y };
227
- let f = (ct = i.prompt_order) == null ? void 0 : ct.find((g) => g.character_id === W);
228
- if (!f && i.prompt_order && i.prompt_order.length > 0 && (f = i.prompt_order[i.prompt_order.length - 1]), !f)
236
+ let d = (ce = i.prompt_order) == null ? void 0 : ce.find((h) => h.character_id === q);
237
+ if (!d && i.prompt_order && i.prompt_order.length > 0 && (d = i.prompt_order[i.prompt_order.length - 1]), !d)
229
238
  return console.warn(`No prompt order found for preset: ${o}. Using current preset.`), y.push(`No prompt order found for preset: ${o}. Using current preset.`), r(), { result: a.getMessages(), warnings: y };
230
- const $ = J && i.scenario_format ? n.substituteParams(i.scenario_format) : "", j = Q && i.personality_format ? n.substituteParams(i.personality_format) : "", Nt = n.substituteParams(i.group_nudge_prompt), Ut = i.impersonation_prompt ? n.substituteParams(i.impersonation_prompt) : "", d = [];
231
- Y || d.push(
239
+ const z = Q && i.scenario_format ? s.substituteParams(i.scenario_format) : "", F = G && i.personality_format ? s.substituteParams(i.personality_format) : "", Be = s.substituteParams(i.group_nudge_prompt), Ne = i.impersonation_prompt ? s.substituteParams(i.impersonation_prompt) : "", g = [];
240
+ Y || g.push(
232
241
  {
233
242
  role: "system",
234
- content: Mt(B, { wiFormat: i.wi_format }),
243
+ content: Me(U, { wiFormat: i.wi_format }),
235
244
  identifier: "worldInfoBefore"
236
245
  },
237
246
  {
238
247
  role: "system",
239
- content: Mt(F, { wiFormat: i.wi_format }),
248
+ content: Me(D, { wiFormat: i.wi_format }),
240
249
  identifier: "worldInfoAfter"
241
250
  }
242
- ), h || d.push(
243
- { role: "system", content: G, identifier: "charDescription" },
244
- { role: "system", content: j, identifier: "charPersonality" },
245
- { role: "system", content: $, identifier: "scenario" }
246
- ), d.push(
247
- { role: "system", content: Ut, identifier: "impersonate" },
248
- { role: "system", content: Nt, identifier: "groupNudge" }
251
+ ), _ || g.push(
252
+ { role: "system", content: W, identifier: "charDescription" },
253
+ { role: "system", content: F, identifier: "charPersonality" },
254
+ { role: "system", content: z, identifier: "scenario" }
255
+ ), g.push(
256
+ { role: "system", content: Ne, identifier: "impersonate" },
257
+ { role: "system", content: Be, identifier: "groupNudge" }
249
258
  );
250
- const A = n.extensionPrompts["1_memory"];
251
- A && A.value && d.push({
252
- role: w(A.role),
253
- content: A.value,
259
+ const O = s.extensionPrompts["1_memory"];
260
+ O && O.value && g.push({
261
+ role: k(O.role),
262
+ content: O.value,
254
263
  identifier: "summary",
255
- position: I(A.position)
264
+ position: N(O.position)
256
265
  });
257
- const R = n.extensionPrompts["2_floating_prompt"];
258
- !O && R && R.value && d.push({
259
- role: w(R.role),
260
- content: R.value,
266
+ const A = s.extensionPrompts["2_floating_prompt"];
267
+ !I && A && A.value && g.push({
268
+ role: k(A.role),
269
+ content: A.value,
261
270
  identifier: "authorsNote",
262
- position: I(R.position)
271
+ position: N(A.position)
263
272
  });
264
- const z = n.extensionPrompts["3_vectors"];
265
- z && z.value && d.push({
273
+ const $ = s.extensionPrompts["3_vectors"];
274
+ $ && $.value && g.push({
266
275
  role: "system",
267
- content: z.value,
276
+ content: $.value,
268
277
  identifier: "vectorsMemory",
269
- position: I(z.position)
278
+ position: N($.position)
270
279
  });
271
- const N = n.extensionPrompts["4_vectors_data_bank"];
272
- N && N.value && d.push({
273
- role: w(N.role),
274
- content: N.value,
280
+ const R = s.extensionPrompts["4_vectors_data_bank"];
281
+ R && R.value && g.push({
282
+ role: k(R.role),
283
+ content: R.value,
275
284
  identifier: "vectorsDataBank",
276
- position: I(N.position)
285
+ position: N(R.position)
277
286
  });
278
- const H = n.extensionPrompts.chromadb;
279
- H && H.value && d.push({
287
+ const j = s.extensionPrompts.chromadb;
288
+ j && j.value && g.push({
280
289
  role: "system",
281
- content: H.value,
290
+ content: j.value,
282
291
  identifier: "smartContext",
283
- position: I(H.position)
284
- }), !h && n.powerUserSettings.persona_description && n.powerUserSettings.persona_description_position === Ct.IN_PROMPT && d.push({
292
+ position: N(j.position)
293
+ }), !_ && s.powerUserSettings.persona_description && s.powerUserSettings.persona_description_position === Te.IN_PROMPT && g.push({
285
294
  role: "system",
286
- content: n.powerUserSettings.persona_description,
295
+ content: s.powerUserSettings.persona_description,
287
296
  identifier: "personaDescription"
288
- }), f.order.forEach((g) => {
289
- if (!g.enabled)
297
+ }), d.order.forEach((h) => {
298
+ if (!h.enabled)
290
299
  return;
291
- const M = t(g.identifier);
292
- if (M && M.content) {
300
+ const w = e(h.identifier);
301
+ if (w && w.content) {
293
302
  a.add({
294
- role: M.role ?? "system",
295
- content: n.substituteParams(M.content)
303
+ role: w.role ?? "system",
304
+ content: s.substituteParams(w.content)
296
305
  });
297
306
  return;
298
307
  }
299
- g.identifier === "chatHistory" && rt();
308
+ h.identifier === "chatHistory" && ne();
300
309
  });
301
310
  }
302
- const Rt = [
311
+ const Re = [
303
312
  "1_memory",
304
313
  "2_floating_prompt",
305
314
  "3_vectors",
@@ -309,74 +318,74 @@ ${t.extra.title}`), {
309
318
  "QUIET_PROMPT",
310
319
  "DEPTH_PROMPT"
311
320
  ];
312
- for (const t in n.extensionPrompts)
313
- if (Object.hasOwn(n.extensionPrompts, t)) {
314
- const e = n.extensionPrompts[t];
315
- if (Rt.includes(t) || !n.extensionPrompts[t].value || ![v.BEFORE_PROMPT, v.IN_PROMPT].includes(e.position) || typeof e.filter == "function" && !await e.filter()) continue;
321
+ for (const e in s.extensionPrompts)
322
+ if (Object.hasOwn(s.extensionPrompts, e)) {
323
+ const t = s.extensionPrompts[e];
324
+ if (Re.includes(e) || !s.extensionPrompts[e].value || ![v.BEFORE_PROMPT, v.IN_PROMPT].includes(t.position) || typeof t.filter == "function" && !await t.filter()) continue;
316
325
  const r = {
317
- role: w(e.role) ?? "system",
318
- content: e.value
326
+ role: k(t.role) ?? "system",
327
+ content: t.value
319
328
  };
320
- if (e.position === v.BEFORE_PROMPT)
321
- a.insert(e.depth, r);
322
- else if (e.position === v.IN_PROMPT) {
329
+ if (t.position === v.BEFORE_PROMPT)
330
+ a.insert(t.depth, r);
331
+ else if (t.position === v.IN_PROMPT) {
323
332
  const i = a.getMessages();
324
- a.insert(i.length - e.depth, r);
333
+ a.insert(i.length - t.depth, r);
325
334
  }
326
335
  }
327
- for (const t of At) {
328
- const e = a.getMessages();
329
- a.insert(e.length - t.depth, {
330
- role: w(t.role),
331
- content: t.entries.join(`
336
+ for (const e of Ae) {
337
+ const t = a.getMessages();
338
+ a.insert(t.length - e.depth, {
339
+ role: k(e.role),
340
+ content: e.entries.join(`
332
341
  `)
333
342
  });
334
343
  }
335
- if (!h) {
336
- const t = Wt(kt, Number(W));
337
- if (kt && Array.isArray(t) && t.length > 0)
338
- t.filter((e) => e.text).forEach((e, p) => {
344
+ if (!_) {
345
+ const e = Ge(Ce, Number(q));
346
+ if (Ce && Array.isArray(e) && e.length > 0)
347
+ e.filter((t) => t.text).forEach((t, p) => {
339
348
  const r = a.getMessages();
340
- a.insert(r.length - e.depth, { role: e.role, content: e.text });
349
+ a.insert(r.length - t.depth, { role: t.role, content: t.text });
341
350
  });
342
351
  else {
343
- const e = q(
344
- (dt = (ft = (mt = (ut = (lt = n.characters[W]) == null ? void 0 : lt.data) == null ? void 0 : ut.extensions) == null ? void 0 : mt.depth_prompt) == null ? void 0 : ft.prompt) == null ? void 0 : dt.trim(),
352
+ const t = H(
353
+ (de = (fe = (ue = (le = (me = s.characters[q]) == null ? void 0 : me.data) == null ? void 0 : le.extensions) == null ? void 0 : ue.depth_prompt) == null ? void 0 : fe.prompt) == null ? void 0 : de.trim(),
345
354
  b,
346
355
  T
347
356
  ) || "";
348
- if (e) {
349
- const p = Xt, r = ((Pt = (_t = (ht = (gt = n.characters[W]) == null ? void 0 : gt.data) == null ? void 0 : ht.extensions) == null ? void 0 : _t.depth_prompt) == null ? void 0 : Pt.role) ?? Vt, i = a.getMessages();
357
+ if (t) {
358
+ const p = tt, r = ((Pe = (_e = (he = (ge = s.characters[q]) == null ? void 0 : ge.data) == null ? void 0 : he.extensions) == null ? void 0 : _e.depth_prompt) == null ? void 0 : Pe.role) ?? et, i = a.getMessages();
350
359
  a.insert(i.length - p, {
351
- role: w(r),
352
- content: e
360
+ role: k(r),
361
+ content: t
353
362
  });
354
363
  }
355
364
  }
356
365
  }
357
- let x = -1;
358
- if (!O) {
359
- const t = Gt();
360
- if (t.prompt) {
361
- t.prompt = q(t.prompt, b, T);
362
- const e = { role: w(t.role), content: t.prompt };
363
- switch (t.position) {
366
+ let M = -1;
367
+ if (!I) {
368
+ const e = Qe();
369
+ if (e.prompt) {
370
+ e.prompt = H(e.prompt, b, T);
371
+ const t = { role: k(e.role), content: e.prompt };
372
+ switch (e.position) {
364
373
  case v.IN_PROMPT:
365
- a.insert(1, e), x = 1;
374
+ a.insert(1, t), M = 1;
366
375
  break;
367
376
  case v.IN_CHAT:
368
- x = a.getMessages().length - t.depth, a.insert(x, e);
377
+ M = a.getMessages().length - e.depth, a.insert(M, t);
369
378
  break;
370
379
  case v.BEFORE_PROMPT:
371
- a.addFront(e), x = 0;
380
+ a.addFront(t), M = 0;
372
381
  break;
373
382
  }
374
383
  }
375
384
  }
376
- return x >= 0 && (ot.length > 0 && (a.insert(x, { role: "system", content: ot.join(`
377
- `) }), x++), nt.length > 0 && a.insert(x + 1, { role: "system", content: nt.join(`
385
+ return M >= 0 && (oe.length > 0 && (a.insert(M, { role: "system", content: oe.join(`
386
+ `) }), M++), se.length > 0 && a.insert(M + 1, { role: "system", content: se.join(`
378
387
  `) })), { result: a.getMessages(), warnings: y };
379
388
  }
380
389
  export {
381
- ce as buildPrompt
390
+ gt as buildPrompt
382
391
  };
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function r(e){return typeof e=="string"&&e.trim().length>0}function o(e){const t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.map(n=>n.type==="text"?n.text:"").filter(r).join(`
2
+ `):""}function s(e){const t=e.content;if(typeof t=="string")return r(t)?e:null;if(Array.isArray(t)){const n=t.filter(i=>i.type!=="text"||r(i.text));return n.length>0?{...e,content:n}:null}return null}function u(e){return e.map(t=>s(t)).filter(t=>t!==null)}exports.getMessageText=o;exports.sanitizePromptMessage=s;exports.sanitizePromptMessages=u;
@@ -0,0 +1,6 @@
1
+ import { ChatCompletionMessage } from './types/index.js';
2
+
3
+ export declare function getMessageText(message: ChatCompletionMessage): string;
4
+ export declare function sanitizePromptMessage<T extends ChatCompletionMessage>(message: T): T | null;
5
+ export declare function sanitizePromptMessages<T extends ChatCompletionMessage>(messages: T[]): T[];
6
+ //# sourceMappingURL=prompt-message-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-message-utils.d.ts","sourceRoot":"","sources":["../src/prompt-message-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAYzD,wBAAgB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,MAAM,CAerE;AAED,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,qBAAqB,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAa3F;AAED,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,qBAAqB,EAAE,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAI1F"}
@@ -0,0 +1,26 @@
1
+ function r(n) {
2
+ return typeof n == "string" && n.trim().length > 0;
3
+ }
4
+ function s(n) {
5
+ const t = n.content;
6
+ return typeof t == "string" ? t : Array.isArray(t) ? t.map((e) => e.type === "text" ? e.text : "").filter(r).join(`
7
+ `) : "";
8
+ }
9
+ function o(n) {
10
+ const t = n.content;
11
+ if (typeof t == "string")
12
+ return r(t) ? n : null;
13
+ if (Array.isArray(t)) {
14
+ const e = t.filter((i) => i.type !== "text" || r(i.text));
15
+ return e.length > 0 ? { ...n, content: e } : null;
16
+ }
17
+ return null;
18
+ }
19
+ function u(n) {
20
+ return n.map((t) => o(t)).filter((t) => t !== null);
21
+ }
22
+ export {
23
+ s as getMessageText,
24
+ o as sanitizePromptMessage,
25
+ u as sanitizePromptMessages
26
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function i(o){return{startIndex:(o==null?void 0:o.start)??0,endIndex:(o==null?void 0:o.end)===void 0?void 0:o.end+1}}exports.getMessageSliceBounds=i;
@@ -0,0 +1,7 @@
1
+ import { BuildPromptOptions } from './prompt-builder.js';
2
+
3
+ export declare function getMessageSliceBounds(messageIndexesBetween?: BuildPromptOptions['messageIndexesBetween']): {
4
+ startIndex: number;
5
+ endIndex: number | undefined;
6
+ };
7
+ //# sourceMappingURL=prompt-slice-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-slice-utils.d.ts","sourceRoot":"","sources":["../src/prompt-slice-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE9D,wBAAgB,qBAAqB,CAAC,qBAAqB,CAAC,EAAE,kBAAkB,CAAC,uBAAuB,CAAC,GAAG;IAC1G,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;CAC9B,CAKA"}
@@ -0,0 +1,9 @@
1
+ function r(o) {
2
+ return {
3
+ startIndex: (o == null ? void 0 : o.start) ?? 0,
4
+ endIndex: (o == null ? void 0 : o.end) === void 0 ? void 0 : o.end + 1
5
+ };
6
+ }
7
+ export {
8
+ r as getMessageSliceBounds
9
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sillytavern-utils-lib",
3
- "version": "1.0.65",
3
+ "version": "1.0.67",
4
4
  "description": "Utility library for SillyTavern",
5
5
  "type": "module",
6
6
  "exports": {