Files
tiny-worlds/server/variants.mjs
T

72 lines
3.7 KiB
JavaScript

// server/variants.mjs -- variant literature: parse, pick, resolve.
//
// A player turn may be variant literature: several complete candidate
// turns in one <variants> block (one <variant> each), each carrying
// its own substrate verbs. The loop picks one at random on reception
// -- genuine chaos over curation, by GM ruling -- and only the picked
// variant ever renders on a model-facing surface; the unpicked rest
// survive in the session log alone (she must not remember roads not
// taken; the housekeeper must not file fiction-that-never-was).
//
// Parsing is strict: a malformed block refuses loud BEFORE anything
// is appended -- nothing applies, nothing drifts. Every variants
// message in a log is therefore well-formed, and the resolution map
// below can treat violations as context invariants (thrown, like
// pairing violations).
import { randomInt } from 'node:crypto';
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
const ANY_TAG = /<\/?variants?>/; // matches <variant>, <variants>, and both closers
/** The parsed candidates of one variants block.
* @typedef {{ variants: string[] }} Variants */
/** @param {?string} text @returns {?Variants} null = no variants syntax at all (a plain turn); throws on malformed */
export function parseVariants(text) {
const t = String(text ?? '');
if (!ANY_TAG.test(t)) return null;
const blocks = [...t.matchAll(/<variants>([\s\S]*?)<\/variants>/g)];
if (!blocks.length) throw new Error('<variant> blocks must live inside one <variants> block');
if (blocks.length > 1) throw new Error('more than one <variants> block in one turn');
const outside = t.replace(blocks[0][0], '').trim();
if (outside) throw new Error(`prose outside the <variants> block ("${outside.slice(0, 60)}${outside.length > 60 ? '...' : ''}") -- a turn is one shape`);
const variants = blocks[0][1].match(/<variant>([\s\S]*?)<\/variant>/g) ?? [];
const texts = variants.map((v) => v.replace(/^<variant>/, '').replace(/<\/variant>$/, '').trim());
if (!texts.length) throw new Error('no <variant> block inside <variants>');
if (texts.some((v) => !v)) throw new Error('an empty <variant> block');
if (texts.some((v) => ANY_TAG.test(v))) throw new Error('variants syntax nested inside a <variant> block');
return { variants: texts };
}
// the dice: uniform, server-side, unwatchable by the model
/** @param {number} count @returns {number} */
export const pickVariant = (count) => randomInt(count);
// The effective-content map: what each assistant message "really
// said" on any model-facing surface. A message followed by its pick
// note renders the chosen variant; a message still mid-turn (a tool
// call carrying draft variants) renders the block stripped -- the
// candidates are her live draft until a pick resolves them.
/** @param {LogEvent[]} lines @returns {Map<number, string>} */
export function effectiveContents(lines) {
const eff = new Map();
for (let i = 0; i < lines.length; i++) {
const e = lines[i];
if (e.t !== 'msg' || e.m?.role !== 'assistant' || typeof e.m.content !== 'string') continue;
if (!ANY_TAG.test(e.m.content)) continue;
const next = lines[i + 1];
if (next?.t === 'note' && next.kind === 'pick') {
const v = parseVariants(e.m.content);
if (!v) throw new Error('context invariant violated: a pick note follows a non-variants message');
if (!Number.isInteger(next.chosen) || next.chosen < 0 || next.chosen >= v.variants.length) {
throw new Error(`context invariant violated: the pick note chooses #${next.chosen} of ${v.variants.length}`);
}
eff.set(i, v.variants[next.chosen]);
} else {
eff.set(i, e.m.content.replace(/<variants>[\s\S]*?<\/variants>/g, '').trim());
}
}
return eff;
}