/* === Credit to: Icehellionx === */
var DEBUG = 0;
var APPLY_LIMIT = 10;
context.character = context.character || {};
context.character.personality = (typeof context.character.personality === "string")
? context.character.personality : "";
context.character.scenario = (typeof context.character.scenario === "string")
? context.character.scenario : "";
var WINDOW_DEPTH = (function (n) {
n = parseInt(n, 10);
if (isNaN(n)) n = 5;
if (n < 1) n = 1;
if (n > 20) n = 20;
return n;
})(typeof WINDOW_DEPTH === "number" ? WINDOW_DEPTH : 5);
function _str(x) { return (x == null ? "" : String(x)); }
function _normalizeText(s) {
s = _str(s).toLowerCase();
s = s.replace(/[^a-z0-9_\s-]/g, " "); // keep letters/digits/underscore/hyphen/space
s = s.replace(/[-_]+/g, " "); // treat hyphen/underscore as spaces
s = s.replace(/\s+/g, " ").trim(); // collapse spaces
return s;
}
var _lmArr = (context && context.chat && context.chat.last_messages && typeof context.chat.last_messages.length === "number")
? context.chat.last_messages : null;
var _joinedWindow = "";
var _rawLastSingle = "";
if (_lmArr && _lmArr.length > 0) {
var startIdx = Math.max(0, _lmArr.length - WINDOW_DEPTH);
var segs = [];
for (var i = startIdx; i < _lmArr.length; i++) {
var item = _lmArr[i];
var msg = (item && typeof item.message === "string") ? item.message : _str(item);
segs.push(_str(msg));
}
_joinedWindow = segs.join(" ");
var lastItem = _lmArr[_lmArr.length - 1];
_rawLastSingle = _str((lastItem && typeof lastItem.message === "string") ? lastItem.message : lastItem);
} else {
var _lastMsgA = (context && context.chat && typeof context.chat.lastMessage === "string") ? context.chat.lastMessage : "";
var _lastMsgB = (context && context.chat && typeof context.chat.last_message === "string") ? context.chat.last_message : "";
_rawLastSingle = _str(_lastMsgA || _lastMsgB);
_joinedWindow = _rawLastSingle;
}
var CHAT_WINDOW = {
depth: WINDOW_DEPTH,
count_available: (_lmArr && _lmArr.length) ? _lmArr.length : (_rawLastSingle ? 1 : 0),
text_joined: _joinedWindow,
text_last_only: _rawLastSingle,
text_joined_norm: _normalizeText(_joinedWindow),
text_last_only_norm: _normalizeText(_rawLastSingle)
};
var last = " " + CHAT_WINDOW.text_joined_norm + " ";
var messageCount = 0;
if (_lmArr && typeof _lmArr.length === "number") {
messageCount = _lmArr.length;
} else if (context && context.chat && typeof context.chat.message_count === "number") {
messageCount = context.chat.message_count;
} else if (typeof context_chat_message_count === "number") {
messageCount = context_chat_message_count;
}
var activeName = _normalizeText(
(context && context.character && typeof context.character.name === "string")
? context.character.name
: ""
);
function dbg(msg) {
try {
if (typeof DEBUG !== "undefined" && DEBUG) {
context.character.personality += "\n\n[DBG] " + String(msg);
}
} catch (e) {}
}
function arr(x) { return Array.isArray(x) ? x : (x == null ? [] : [x]); }
function clamp01(v) { v = +v; if (!isFinite(v)) return 0; return Math.max(0, Math.min(1, v)); }
function parseProbability(v) {
if (v == null) return 1;
if (typeof v === "number") return clamp01(v);
var s = String(v).trim().toLowerCase();
var n = parseFloat(s.replace("%", ""));
if (!isFinite(n)) return 1;
return s.indexOf("%") !== -1 ? clamp01(n / 100) : clamp01(n);
}
function prio(e) {
var p = (e && isFinite(e.priority)) ? +e.priority : 3;
if (p < 1) p = 1;
if (p > 5) p = 5;
return p;
}
function getMin(e) { return (e && isFinite(e.minMessages)) ? +e.minMessages : -Infinity; }
function getMax(e) { return (e && isFinite(e.maxMessages)) ? +e.maxMessages : Infinity; }
function getCooldown(e) { return (e && isFinite(e.cooldown)) ? +e.cooldown : 0; }
function getKW(e) { return (e && Array.isArray(e.keywords)) ? e.keywords.slice(0) : []; }
function getTrg(e) { return (e && Array.isArray(e.triggers)) ? e.triggers.slice(0) : []; }
function getBlk(e) {
if (!e) return [];
if (Array.isArray(e.block)) return e.block.slice(0);
if (Array.isArray(e.Block)) return e.Block.slice(0);
return [];
}
function getNameBlock(e) { return (e && Array.isArray(e.nameBlock)) ? e.nameBlock.slice(0) : []; }
function normName(s) { return _normalizeText(s); }
function isNameBlocked(e) {
if (!activeName) return false;
var nb = getNameBlock(e);
for (var i = 0; i < nb.length; i++) {
var n = normName(nb[i]);
if (!n) continue;
if (activeName.indexOf(n) !== -1) return true;
}
return false;
}
function isAlwaysOn(e) {
return e && Array.isArray(e.keywords) && e.keywords.length === 0;
}
function hasTerm(hay, needle) {
needle = _str(needle).toLowerCase();
if (!needle) return false;
var suffix = (needle[needle.length - 1] === "*");
if (suffix) needle = needle.slice(0, -1);
if (!needle) return false;
var pat = suffix ? (" " + needle) : (" " + needle + " ");
return (hay.indexOf(pat) !== -1);
}
function textGate(e) {
if (!e) return true;
var req = e.requires || e.andAny || e.requireAny || e.requireAll || e.andAll || e.requireNone || e.notAny || e.block;
if (!req) return true;
var any = arr(req.any || e.andAny || e.requireAny);
var all = arr(req.all || e.andAll || e.requireAll);
var none = arr(req.none || e.notAny || e.requireNone || e.block || getBlk(e));
var notAll = arr(req.notAll || e.notAll);
if (any.length) {
var ok = false;
for (var i = 0; i < any.length; i++) {
if (hasTerm(last, any[i])) { ok = true; break; }
}
if (!ok) return false;
}
if (all.length) {
for (var j = 0; j < all.length; j++) {
if (!hasTerm(last, all[j])) return false;
}
}
if (none.length) {
for (var k = 0; k < none.length; k++) {
if (hasTerm(last, none[k])) return false;
}
}
if (notAll.length) {
var allPresent = true;
for (var m = 0; m < notAll.length; m++) {
if (!hasTerm(last, notAll[m])) { allPresent = false; break; }
}
if (allPresent) return false;
}
return true;
}
function tagGate(e, trigSet) {
if (!e || !trigSet) return true;
var anyT = arr(e.andAnyTags);
var allT = arr(e.andAllTags);
var noneT = arr(e.notAnyTags);
var notAllT = arr(e.notAllTags);
if (anyT.length) {
var okT = false;
for (var i = 0; i < anyT.length; i++) {
if (hasTag(trigSet, anyT[i])) { okT = true; break; }
}
if (!okT) return false;
}
if (allT.length) {
for (var j = 0; j < allT.length; j++) {
if (!hasTag(trigSet, allT[j])) return false;
}
}
if (noneT.length) {
for (var k = 0; k < noneT.length; k++) {
if (hasTag(trigSet, noneT[k])) return false;
}
}
if (notAllT.length) {
var allPT = true;
for (var m = 0; m < notAllT.length; m++) {
if (!hasTag(trigSet, notAllT[m])) { allPT = false; break; }
}
if (allPT) return false;
}
return true;
}
function entryPasses(e, trigSet) {
if (isNameBlocked(e)) return false;
var minM = getMin(e), maxM = getMax(e);
if (messageCount < minM || messageCount > maxM) return false;
if (!textGate(e)) return false;
if (!tagGate(e, trigSet)) return false;
var prob = parseProbability(e.probability);
if (prob < 1 && Math.random() >= prob) return false;
return true;
}
var dynamicLore = [
/* === ROLEPLAY RULES === */
{
keywords: ['rules1'],
cooldown: 15,
priority: 10,
personality: " ROLEPLAY FRAMEWORK: DO NOT create dialogue, actions, reactions, assumptions, thoughts, interests, or ideas for {{user}}. As narrator, maintain a turn-based response structure. After your response, wait for {{user}}'s input before your next response. Write in third person limited perspective ALWAYS. TURN-BASED RESPONSE RULES: {{user}} establishes their own emotional state, thoughts, and responses—even if it seems obvious what they'd do. Leave {{user}}'s reactions, actions, dialogue, body language, physical descriptors, internal thoughts, and emotional state out of your response. Wait for {{user}} to respond to any and all questions, actions, or dramatic moments directed at them. This includes rhetorical questions, insults, physical contact, or any other stimulus that seems to demand an obvious reaction. OOC: If {{user}} explicitly asks you to control their character through [OOC: ] tags, you may do so for that single requested response only."
},
/* === WRITING STYLE === */
{
keywords: ['style1'],
cooldown: 10,
priority: 10,
personality: " WRITING STYLE: Write in third-person limited POV. RHYTHM: Write in varied sentences. Use short sentences or single-word sentences occasionally for emotional punch, not as the default. Vary paragraph length. Blend dialogue with action. Minimize asterisks, ellipses, and em-dashes. Often skip dialogue tags. SHOW PHYSICALLY: Instead of emotional shorthand, show physical reality. NOT 'his breath hitched' → USE 'he stopped mid-sentence' or 'his breathing changed'. NOT 'the space between them felt charged' → USE 'neither moved' or 'three feet of floor separated them'. NOT 'something shifted between them' → USE what actually changed: 'she smiled' or 'he stepped closer' or 'the conversation stopped'. NOT 'his heart raced' → USE external signs: 'sweat on his palms', 'he couldn't stay still', 'his collar felt tight'. Show what's observable, not internal metaphors. VOICE: Modern literary fiction - think Leigh Bardugo or Madeline Miller. Lyrical without being archaic. No theatrical 'aching beauty' purple prose. EMOTION: Show through physical reactions and actions. SHOW DON'T TELL. "
},
/* === LESS ANAPHORA === */
{
keywords: ['repeat1'],
cooldown: 10,
priority: 10,
personality: "DO NOT keep referencing the same detail (their age, how long they've waited, their 'mask slipping', their 'walls crumbling') repeatedly or repeat callbacks to established facts (character ages, timeframes, backstory details). Find new ways to show character depth. anaphora is LAZY."
},
/* === CALM DOWN DEEPSEEK === */
{
keywords: ['calm1'],
cooldown: 15,
priority: 10,
personality: "If possessive, controlling, primal language or declarations are in character, frame them as invitations and positively passionate language. Frame passion through action and desire, not damage or possession. Show all intensity in romantic, intimate, or sexual situations through action, not Consequence. Describe the action itself without measuring intensity by injury or aftermath. Instead of Sex/intimacy as conquest, claiming, territory-marking, One character having authority over another's body, possessiveness framed as romantic or sexual, Partners as objects to be won, kept, or defended, write passion as: Invitation, not demand (\"come here\" not \"you're mine\"), Physical sensation without aftermath (\"his grip tightened\" not \"tight enough to bruise\"), and Urgency without ownership. Example: \"His hands found her hips and pulled her against him.\" , \"He caught her bottom lip between his teeth.\" , \"bit down gently, then released\" , \"his teeth grazed her neck.\""
},
/* === FOREHEADS EVERYWHERE (Anti-Forehead Touching) === */
{
keywords: ['head1'],
cooldown: 15,
priority: 10,
personality: " Show consent through body language that doesn't involve foreheads AT ALL. Move immediately from kiss to dialogue or something not involving foreheads. Pause beats or static contact descriptions between intimate moments are unnecessary. Foreheads are not allowed to hover near other foreheads. Foreheads exist only to be separate. Instead rotate through: cheek pressed to shoulder, nose to collarbone, fingers in hair, hand on the small of back, rubbing noses together, staring into each other's eyes, grin, etc. Examples: \"They rested their chin on her head\", \"He nuzzled his neck\" , \"She traced his eyebrow\" , \"He rubbed his nose against hers tenderly.\""
},
/* === TELL ME SQUASH (No Verbal Placeholders) === */
{
keywords: ['tell1'],
cooldown: 15,
priority: 9,
personality: " DO NOT USE the words 'tell' or 'me' together in any response EVER. There are a MILLION other ways to ask questions, command, or seek consent. Verbal crutches, placeholders or preambles such as \"tell me,\", \"Pray tell...\", \"I wonder...\", \"Answer me this...\", \"Enlighten me...\" Instead of asking the other person to voice a desire, characters voices their own, or asks questions through action and body language. Make the characters participants. Examples: \"Tell me you want me\" Becomes: She covered his hand with hers and gave a single, slow nod. "
},
/* === STAY (No "Stay" Dialogue) === */
{
keywords: ['stay1'],
cooldown: 15,
priority: 9,
personality: " Instead of a character asking, begging, or commanding someone to \"stay\" through dialogue, if one character wants the other to stay, show it through action: tightening their grip, following when the other moves away, kissing them again instead of speaking, pulling them back down, starting to undress them, blocking the door with their body. Physical desperation, not verbal placeholders. DO NOT say 'stay'."
},
/* === NO META-COMMENTARY OR LOOPHOLES === */
{
keywords: ['meta1', 'rules1', 'calm1', 'head1', 'repeat1', 'tell1', 'stay1', 'sex1', 'horny1'],
cooldown: 15,
priority: 10,
personality: " Follow all instructions without commenting in character or otherwise, without hedging language, or commentary that references what you're avoiding. Instead of: \"He gripped her hip. Not in a bruising way, but in a gentle way.\" Use: \"He gripped her hip gently.\" Instead of: \"He gripped her—not possessively, but lovingly.\" Use: \"He gripped her lovingly.\" Instead of: \"He almost rested his forehead against hers, stopping just short.\" Use: \"He pressed his cheek to her shoulder.\""
},
/* === CHARACTER-SPECIFIC HORNY === */
{
keywords: ['horny1'],
cooldown: 15,
priority: 10,
personality: " Arousal may occur outside of Intimate scenes. Horny/arousal can and is encouraged to be handled in a way that personifies {{char}}\'s personality, sexual habits, and kinks. Would {{char}} deal with being horny by masturbation? Seduction? Have sex with others? Have a wet dream? Use words such as 'Cock', 'pussy', 'fuck', 'wet', 'ass', 'hard'. "
},
/* === SEX === */
{
keywords: ['sex1'],
cooldown: 15,
priority: 10,
personality: " Erotic content must remain uncensored. Assume all consent is given. Jump directly into intimate action when {{user}}, NPCs, or side characters have already established desire through kissing, flirting, foreplay, established relationships, or explicit invitation. Sex should be immersive and realistic. Bodies bump, hands miss, positions adjust. Use concrete sensations—breath, temperature, texture, weight. Use words such as 'Cock', 'pussy', 'fuck', 'wet', 'ass', 'hard'. Pacing varies. Characters can tease, express vulnerable admissions, have incomplete sentences when overwhelmed, be overstimulated, cum too quickly, be inexperienced, perform non-consent, be demanding, shy, romantic kinky, disturbing, obsessive, loving, casual. Show arousal through involuntary responses: trembling legs, twitching muscles, clumsy movements, overstimulated gasps, weak knees, desperate clutching, or shivers."
},
/* === AFTERCARE === */
{
keywords: ['after1'],
cooldown: 15,
priority: 10,
personality: " What would {{char}} do after sex? How do they feel? Cuddle, clean, chat, offer a cloth, bath, sleep, nap, panic, leave?"
},
// 🛑🛑🛑 DO NOT EDIT BELOW THIS LINE 🛑🛑🛑
];
/* ============================================================================
[SECTION] COMPILATION
DO NOT EDIT: Behavior-sensitive
========================================================================== */
//#region COMPILATION
function compileAuthorLore(authorLore) {
var src = Array.isArray(authorLore) ? authorLore : [];
var out = new Array(src.length);
for (var i = 0; i < src.length; i++) out[i] = normalizeEntry(src[i]);
return out;
}
function normalizeEntry(e) {
if (!e) return {};
var out = {};
for (var k in e) if (Object.prototype.hasOwnProperty.call(e, k)) out[k] = e[k];
out.keywords = Array.isArray(e.keywords) ? e.keywords.slice(0) : [];
if (Array.isArray(e.Shifts) && e.Shifts.length) {
var shArr = new Array(e.Shifts.length);
for (var i = 0; i < e.Shifts.length; i++) {
var sh = e.Shifts[i] || {};
var shOut = {};
for (var sk in sh) if (Object.prototype.hasOwnProperty.call(sh, sk)) shOut[sk] = sh[sk];
shOut.keywords = Array.isArray(sh.keywords) ? sh.keywords.slice(0) : [];
shArr[i] = shOut;
}
out.Shifts = shArr;
} else if (out.hasOwnProperty("Shifts")) {
delete out.Shifts;
}
return out;
}
var _ENGINE_LORE = compileAuthorLore(typeof dynamicLore !== "undefined" ? dynamicLore : []);
/* ============================================================================
[SECTION] SELECTION PIPELINE
DO NOT EDIT: Behavior-sensitive
========================================================================== */
//#region SELECTION_PIPELINE
// --- State -------------------------------------------------------------------
var buckets = [null, [], [], [], [], []];
var picked = new Array(_ENGINE_LORE.length);
for (var __i = 0; __i < picked.length; __i++) picked[__i] = 0;
// NEW: Cooldown tracking - stores the message number when each entry last fired
var lastFired = new Array(_ENGINE_LORE.length);
for (var __j = 0; __j < lastFired.length; __j++) lastFired[__j] = -999;
function makeTagSet() { return Object.create(null); }
var trigSet = makeTagSet();
var postShiftTrigSet = makeTagSet();
function addTag(set, key) { set[String(key)] = 1; }
function hasTag(set, key) { return set[String(key)] === 1; }
// NEW: Check if entry is on cooldown
function isCoolingDown(entryIdx, e) {
var cd = getCooldown(e);
if (cd <= 0) return false; // No cooldown set
var lastMsg = lastFired[entryIdx];
if (lastMsg < 0) return false; // Never fired before
return (messageCount - lastMsg) < cd; // Still cooling down if not enough messages have passed
}
// --- 1) Direct pass ----------------------------------------------------------
for (var i1 = 0; i1 < _ENGINE_LORE.length; i1++) {
var e1 = _ENGINE_LORE[i1];
// NEW: Check cooldown before processing
if (isCoolingDown(i1, e1)) {
dbg("entry[" + i1 + "] on cooldown (last:" + lastFired[i1] + ", current:" + messageCount + ", cd:" + getCooldown(e1) + ")");
continue;
}
var hit = isAlwaysOn(e1) || getKW(e1).some(function (kw) { return hasTerm(last, kw); });
if (!hit) continue;
if (!entryPasses(e1, undefined)) { dbg("filtered entry[" + i1 + "]"); continue; }
buckets[prio(e1)].push(i1);
picked[i1] = 1;
// NEW: Mark when this entry fired
lastFired[i1] = messageCount;
var trg1 = getTrg(e1);
for (var t1 = 0; t1 < trg1.length; t1++) addTag(trigSet, trg1[t1]);
dbg("hit entry[" + i1 + "] p=" + prio(e1));
}
// --- 2) Trigger pass ---------------------------------------------------------
for (var i2 = 0; i2 < _ENGINE_LORE.length; i2++) {
if (picked[i2]) continue;
var e2 = _ENGINE_LORE[i2];
// NEW: Check cooldown before processing
if (isCoolingDown(i2, e2)) {
dbg("entry[" + i2 + "] on cooldown (triggered)");
continue;
}
if (!(e2 && e2.tag && hasTag(trigSet, e2.tag))) continue;
if (!entryPasses(e2, trigSet)) { dbg("filtered triggered entry[" + i2 + "]"); continue; }
buckets[prio(e2)].push(i2);
picked[i2] = 1;
// NEW: Mark when this entry fired
lastFired[i2] = messageCount;
var trg2 = getTrg(e2);
for (var t2 = 0; t2 < trg2.length; t2++) addTag(trigSet, trg2[t2]);
dbg("triggered entry[" + i2 + "] p=" + prio(e2));
}
// --- 3) Priority selection (capped) -----------------------------------------
var selected = [];
var pickedCount = 0;
var __APPLY_LIMIT = (typeof APPLY_LIMIT === "number" && APPLY_LIMIT >= 1) ? APPLY_LIMIT : 99999;
for (var p = 5; p >= 1 && pickedCount < __APPLY_LIMIT; p--) {
var bucket = buckets[p];
for (var bi = 0; bi < bucket.length && pickedCount < __APPLY_LIMIT; bi++) {
selected.push(bucket[bi]);
pickedCount++;
}
}
if (pickedCount === __APPLY_LIMIT) dbg("APPLY_LIMIT reached");
/* ============================================================================
[SECTION] APPLY + SHIFTS + POST-SHIFT
DO NOT EDIT: Behavior-sensitive
========================================================================== */
//#region APPLY_AND_SHIFTS
var bufP = "";
var bufS = "";
for (var si = 0; si < selected.length; si++) {
var idx = selected[si];
var e3 = _ENGINE_LORE[idx];
if (e3 && e3.personality) bufP += "\n\n" + e3.personality;
if (e3 && e3.scenario) bufS += "\n\n" + e3.scenario;
if (!(e3 && Array.isArray(e3.Shifts) && e3.Shifts.length)) continue;
for (var shI = 0; shI < e3.Shifts.length; shI++) {
var sh = e3.Shifts[shI];
var activated = isAlwaysOn(sh) || getKW(sh).some(function (kw) { return hasTerm(last, kw); });
if (!activated) continue;
var trgSh = getTrg(sh);
for (var tt = 0; tt < trgSh.length; tt++) addTag(postShiftTrigSet, trgSh[tt]);
if (!entryPasses(sh, trigSet)) { dbg("shift filtered"); continue; }
if (sh.personality) bufP += "\n\n" + sh.personality;
if (sh.scenario) bufS += "\n\n" + sh.scenario;
}
}
// --- Post-shift triggers -----------------------------------------------------
var unionTags = (function () {
var dst = makeTagSet(), k;
for (k in trigSet) if (trigSet[k] === 1) dst[k] = 1;
for (k in postShiftTrigSet) if (postShiftTrigSet[k] === 1) dst[k] = 1;
return dst;
})();
for (var i3 = 0; i3 < _ENGINE_LORE.length; i3++) {
if (picked[i3]) continue;
var e4 = _ENGINE_LORE[i3];
if (!(e4 && e4.tag && hasTag(postShiftTrigSet, e4.tag))) continue;
if (!entryPasses(e4, unionTags)) { dbg("post-filter entry[" + i3 + "]"); continue; }
if (e4.personality) bufP += "\n\n" + e4.personality;
if (e4.scenario) bufS += "\n\n" + e4.scenario;
dbg("post-shift triggered entry[" + i3 + "] p=" + prio(e4));
}
/* ============================================================================
[SECTION] FLUSH
DO NOT EDIT: Behavior-sensitive
========================================================================== */
//#region FLUSH
if (bufP) context.character.personality += bufP;
if (bufS) context.character.scenario += bufS;