1096 lines
46 KiB
TypeScript
1096 lines
46 KiB
TypeScript
// The world-sim engine: pure, testable, no I/O. It (1) builds the LLM prompt from a
|
|
// preset + state, (2) parses and strictly validates the LLM's TurnResult JSON
|
|
// (defensively — never throws), (3) applies the delta atomically to a GameState,
|
|
// and (4) builds the advisor brainstorm prompt. The network call itself lives in
|
|
// llm.ts (injectable) and is invoked by runTurn.
|
|
import type {
|
|
EventOutcome,
|
|
EventType,
|
|
GameState,
|
|
Nation,
|
|
NationStats,
|
|
Preset,
|
|
RelationStatus,
|
|
RoundItem,
|
|
StatKey,
|
|
} from '../shared/types';
|
|
import { EVENT_TYPES, RELATION_STATUSES } from '../shared/types';
|
|
import {
|
|
addDays,
|
|
clampStat,
|
|
isDateLike,
|
|
makeEvent,
|
|
nationForPrompt,
|
|
type NationOp,
|
|
type TurnEventSpec,
|
|
type TurnResult,
|
|
} from '../shared/protocol';
|
|
import {
|
|
DEFAULT_MAX_TOKENS,
|
|
type ChatMessage,
|
|
type LlmClient,
|
|
type ToolDefinition,
|
|
type ToolExecutor,
|
|
type WireMessage,
|
|
} from './llm';
|
|
import { ADVISOR_MARKER } from './stub';
|
|
|
|
const VALID_EVENT_TYPES = new Set<string>(EVENT_TYPES);
|
|
const VALID_RELATIONS = new Set<string>(RELATION_STATUSES);
|
|
const VALID_OUTCOMES = new Set<string>(['success', 'failure', 'partial', 'neutral']);
|
|
const VALID_STATS = new Set<string>(['military', 'economy', 'stability', 'population']);
|
|
|
|
// --- The LLM's getNeighbours tool (v0.21, #16 P2: contiguous region transfers) ---
|
|
|
|
/**
|
|
* The single tool the turn loop exposes to the model: the precomputed region
|
|
* adjacency manifest (public/region-adjacency.json, via the resolver injected
|
|
* into runTurn). Given a set of region keys it returns the union of their
|
|
* bordering keys (the queried keys themselves excluded, sorted for
|
|
* determinism) — so the model can verify that a territory transfer is
|
|
* *contiguous* (a nation gains a region it already abuts) before committing
|
|
* it, instead of moving whole countries at a whim.
|
|
*/
|
|
export const GET_NEIGHBOURS_TOOL: ToolDefinition = {
|
|
type: 'function',
|
|
function: {
|
|
name: 'getNeighbours',
|
|
description:
|
|
'List the region keys that share a land border with any of the given region keys. ' +
|
|
'Pass a nation\'s territory keys (or a single region key) to see which regions are ' +
|
|
'contiguous to it. Use it before transferring territory: a nation can realistically ' +
|
|
'only gain regions that border its existing territory.',
|
|
parameters: {
|
|
type: 'object',
|
|
properties: {
|
|
regionKeys: {
|
|
type: 'array',
|
|
items: { type: 'string' },
|
|
description: 'One or more region keys to query (e.g. a gaining nation\'s territory).',
|
|
},
|
|
},
|
|
required: ['regionKeys'],
|
|
additionalProperties: false,
|
|
},
|
|
},
|
|
};
|
|
|
|
/**
|
|
* Build the tool executor for the turn loop. Never throws: unknown tool
|
|
* names, malformed arguments, and unknown region keys all degrade to a safe
|
|
* response (an error object or an empty list) that the model can recover from.
|
|
*/
|
|
export function makeNeighboursExecutor(
|
|
getNeighbours: (keys: string[]) => string[],
|
|
validRegionKeys?: ReadonlySet<string>,
|
|
): ToolExecutor {
|
|
return (name, args) => {
|
|
if (name !== GET_NEIGHBOURS_TOOL.function.name) {
|
|
return JSON.stringify({ error: `unknown tool: ${name}` });
|
|
}
|
|
const raw = Array.isArray(args.regionKeys) ? args.regionKeys : [];
|
|
const keys = raw.filter((k): k is string => typeof k === 'string' && k.length > 0);
|
|
const valid = validRegionKeys ? keys.filter((k) => validRegionKeys.has(k)) : keys;
|
|
if (valid.length === 0) return JSON.stringify({ neighbours: [] });
|
|
return JSON.stringify({ neighbours: getNeighbours(valid) });
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The player's frontier: region keys owned by *other* nations that share a
|
|
* land border with the player's territory (deduped, sorted — stable order for
|
|
* the deterministic stub). Computed server-side from the adjacency manifest so
|
|
* both the LLM (the `frontier` field of the user prompt) and the stub (which
|
|
* cannot call tools) see the same candidates. Empty when there is no
|
|
* adjacency data or no controllable border (e.g. the UK in 1939).
|
|
*/
|
|
export function playerFrontier(
|
|
state: GameState,
|
|
getNeighbours: (keys: string[]) => string[],
|
|
): string[] {
|
|
const player = state.nations[state.playerNationId];
|
|
if (!player || player.territory.length === 0) return [];
|
|
const playerKeys = new Set(player.territory);
|
|
const candidates = new Set<string>();
|
|
for (const key of getNeighbours(player.territory)) {
|
|
if (!playerKeys.has(key)) candidates.add(key);
|
|
}
|
|
if (candidates.size === 0) return [];
|
|
const frontier: string[] = [];
|
|
for (const n of Object.values(state.nations)) {
|
|
if (n.id === state.playerNationId) continue;
|
|
for (const key of n.territory) {
|
|
if (candidates.has(key)) {
|
|
candidates.delete(key);
|
|
frontier.push(key);
|
|
}
|
|
}
|
|
}
|
|
return frontier.sort();
|
|
}
|
|
|
|
// --- Prompt building ----------------------------------------------------------
|
|
|
|
/**
|
|
* The LLM system prompt: world context + rules + a strict JSON contract.
|
|
* When `withNeighboursTool` is set (the turn runs with the getNeighbours tool
|
|
* available) the contract gains the contiguity rules for territory transfers
|
|
* (v0.21, #16 P2): the model may only move regions across a shared border, and
|
|
* may verify borders with the tool before answering. The contract also
|
|
* documents the `nationOps` proposal queue (v0.23, #16 P4a) — rename plus the
|
|
* split/merge shapes applied on player confirm (v0.24, #16 P4b).
|
|
*/
|
|
export function buildSystemPrompt(preset: Preset, withNeighboursTool = false): string {
|
|
const rules = preset.simulationRules
|
|
.map((r) => `- ${r}`)
|
|
.join('\n');
|
|
const respondLine = withNeighboursTool
|
|
? 'You have a getNeighbours tool: given region keys it returns the region keys that border them. You may call it (a few times) to verify land borders before deciding territory transfers. Once done, respond with ONLY a valid JSON object of exactly this shape. No prose, no commentary, no markdown fences, no trailing commas:'
|
|
: 'Respond with ONLY a valid JSON object of exactly this shape. No prose, no commentary, no markdown fences, no trailing commas:';
|
|
// (v0.22, #16 P3) No man's land: a region can be left unowned after a war or
|
|
// cataclysm (the model narrates the cause in "events" and lists the key in
|
|
// "unowned"); unowned regions can later be re-claimed with an ordinary gain.
|
|
// The model sees the current no-man's-land keys in the user payload's
|
|
// "unowned" field and in the "regions" reference table.
|
|
const noMansLandRule =
|
|
'- A region key has at most one owner at all times — never assign a key to two nations. After a war or cataclysm a region may be left unowned ("no man\'s land"): list its key in "unowned" and narrate the cause in "events"; it stays unowned (grey on the map) until a nation re-claims it with a "gain". The "unowned" field of the user message lists the regions currently in no man\'s land.';
|
|
const territoryRules = withNeighboursTool
|
|
? [
|
|
'- Territory changes must be contiguous: a nation may only GAIN region keys that share a land border with a region it already owns (verify with getNeighbours) and may only LOSE region keys it currently owns.',
|
|
'- The "frontier" field of the user message lists region keys owned by other nations that border the player\'s territory — the natural targets of a player-led conquest this turn.',
|
|
noMansLandRule,
|
|
]
|
|
: [
|
|
'- Only change borders when war or a decisive political shift justifies it.',
|
|
noMansLandRule,
|
|
];
|
|
return [
|
|
`WORLD: ${preset.title} — ${preset.startDate}`,
|
|
preset.worldBackground,
|
|
'',
|
|
'SIMULATION RULES',
|
|
rules,
|
|
'',
|
|
'You are the world simulator. You advance the shared world state for ALL nations given the current state and the player\'s move.',
|
|
respondLine,
|
|
'{',
|
|
' "date": "YYYY-MM-DD (a few days after the current date)",',
|
|
' "events": [',
|
|
' {"nation":"<nationId>","type":"<military|diplomatic|economic|political|social|disaster|scientific|cultural>","title":"short headline","text":"1-3 sentences of narrative","outcome":"<success|failure|partial|neutral>"}',
|
|
' ],',
|
|
' "stateChanges": [{"nation":"<nationId>","stat":"<military|economy|stability|population>","op":"<set|add>","value":<0-100>}],',
|
|
' "relations": [{"a":"<nationId>","b":"<nationId>","set":"<ally|neutral|rival|hostile|war>"}],',
|
|
' "territoryChanges": [{"nation":"<nationId>","gain":["<region key>"],"lose":["<region key>"]}],',
|
|
' "unowned": ["<region key>"],',
|
|
' "nationOps": [',
|
|
' {"kind":"rename","nationRef":"<nation id or name>","to":"<new name>"},',
|
|
' {"kind":"split","nationRef":"<nation id or name>","parts":[{"name":"<new name>","territory":["<region key>"]}]}',
|
|
' {"kind":"merge","nationRefs":["<id>","<id>"],"survivingRef":"<id of the surviving nation>","into":"<new name>"}',
|
|
' ],',
|
|
'}',
|
|
'',
|
|
'HARD CONSTRAINTS',
|
|
'- Use only nation ids and region keys that exist in the provided state.',
|
|
'- A region key identifies one sub-region; the "regions" table in the user message maps each key to "<region name> (<parent country ISO_A3>)". Use those keys in territoryChanges and unowned.',
|
|
'- List in "unowned" only region keys that a nation currently owns, and narrate each release in "events".',
|
|
'- Nation-management ops ("nationOps") are PROPOSALS: they only take effect if the player confirms them afterwards. Propose at most 1-2 per turn, only when the narrative justifies it, and narrate each one in "events".',
|
|
'- Rename: add {"kind":"rename","nationRef":"<nation id or name>","to":"<new name>"} for a revolution, regime change or reunification that changes a nation\'s name.',
|
|
'- Split: add {"kind":"split","nationRef":"<nation id or name>","parts":[{"name":"<new name>","territory":["<region key>"]}, ...]} when a state breaks up (dissolution, secession). Use at least 2 parts and assign each of the nation\'s region keys to at most one part — any key you leave unassigned goes to the first part.',
|
|
'- Merge: add {"kind":"merge","nationRefs":["<id or name>","<id or name>"],"survivingRef":"<id or name of the surviving nation>","into":"<new name>"} when states reunify or one is absorbed. Use at least 2 input nations and "survivingRef" must name one of them — the survivor keeps its id and its stats.',
|
|
'- Prefer 1-4 events per turn; keep each text 1-3 sentences.',
|
|
'- Keep your internal reasoning brief (a few sentences) and go straight to the JSON result; do not over-deliberate or re-derive facts already present in the state.',
|
|
'- Keep every stat value between 0 and 100.',
|
|
...territoryRules,
|
|
'- If a field is not relevant this turn, set it to an empty array.',
|
|
].join('\n');
|
|
}
|
|
|
|
/**
|
|
* The user message: a compact JSON snapshot of the world plus the player's
|
|
* queued round (`items`) — the free-text actions and diplomatic messages to be
|
|
* simulated this period. `playerActions` is an LLM-friendly rendering of each
|
|
* item; the raw `pending` list is also emitted so the deterministic stub (and any
|
|
* other consumer) can read the exact items. The framing instruction tells the
|
|
* model to simulate the combined consequences of the whole batch (or to let the
|
|
* world advance on its own when the batch is empty) and return one TurnResult.
|
|
*/
|
|
export function buildUserPrompt(
|
|
state: GameState,
|
|
items: RoundItem[],
|
|
regionReference?: Record<string, string>,
|
|
/**
|
|
* The player's frontier: region keys owned by other nations that border the
|
|
* player's territory (v0.21, #16 P2). Emitted verbatim (even when empty) so
|
|
* the model — and the deterministic stub, which reads it — see the same
|
|
* contiguous targets. Omitted entirely when undefined (no adjacency data).
|
|
*/
|
|
frontier?: string[],
|
|
/**
|
|
* (v0.22, #16 P3) Region keys that are currently "no man's land" (released
|
|
* mid-game — `state.unowned`). Emitted verbatim (even when empty) so the
|
|
* model knows which unowned regions exist and can be re-claimed this turn.
|
|
* Omitted entirely when undefined.
|
|
*/
|
|
noMansLand?: string[],
|
|
): string {
|
|
const player = state.nations[state.playerNationId];
|
|
const playerName = player?.name ?? state.playerNationId;
|
|
const playerActions = items.map((i) =>
|
|
i.kind === 'action' ? i.text : { to: i.to ?? '', message: i.text },
|
|
);
|
|
const roundInstruction =
|
|
items.length > 0
|
|
? `This period the player (${playerName}) takes the following actions and sends the following diplomatic messages: ${JSON.stringify(
|
|
playerActions,
|
|
)}. Simulate the combined consequences across all nations and advance the world by one period. Return a single TurnResult.`
|
|
: 'The player takes no action this period; let the world advance on its own momentum. Return a single TurnResult.';
|
|
|
|
const payload: Record<string, unknown> = {
|
|
state: {
|
|
turn: state.turn,
|
|
date: state.date,
|
|
playerNationId: state.playerNationId,
|
|
nations: Object.fromEntries(
|
|
Object.entries(state.nations).map(([id, n]) => [id, nationForPrompt(n)]),
|
|
),
|
|
recentEvents: state.events.slice(-5).map((e) => ({
|
|
turn: e.turn,
|
|
date: e.date,
|
|
nation: e.nation,
|
|
type: e.type,
|
|
title: e.title,
|
|
text: e.text,
|
|
outcome: e.outcome,
|
|
})),
|
|
},
|
|
playerActions,
|
|
pending: items,
|
|
roundInstruction,
|
|
};
|
|
if (regionReference) payload.regions = regionReference;
|
|
if (frontier !== undefined) payload.frontier = frontier;
|
|
if (noMansLand !== undefined) payload.unowned = noMansLand;
|
|
return JSON.stringify(payload, null, 2);
|
|
}
|
|
|
|
// --- Defensive parsing --------------------------------------------------------
|
|
|
|
function stripFence(text: string): string {
|
|
let t = text.trim();
|
|
const lead = t.match(/^```[a-zA-Z]*\s*\n?/);
|
|
if (lead) t = t.slice(lead[0].length);
|
|
const tail = t.match(/\n?\s*```\s*$/);
|
|
if (tail) t = t.slice(0, t.length - tail[0].length);
|
|
return t.trim();
|
|
}
|
|
|
|
/** Extract the first balanced `{ ... }` substring (string-aware). */
|
|
function extractBalancedObject(text: string): string | null {
|
|
const start = text.indexOf('{');
|
|
if (start === -1) return null;
|
|
let depth = 0;
|
|
let inStr = false;
|
|
let esc = false;
|
|
for (let i = start; i < text.length; i++) {
|
|
const c = text[i];
|
|
if (inStr) {
|
|
if (esc) esc = false;
|
|
else if (c === '\\') esc = true;
|
|
else if (c === '"') inStr = false;
|
|
continue;
|
|
}
|
|
if (c === '"') inStr = true;
|
|
else if (c === '{') depth++;
|
|
else if (c === '}' && --depth === 0) return text.slice(start, i + 1);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Parse raw LLM output into a validated TurnResult, or null if unusable. Strips
|
|
* code fences, extracts the first balanced object, JSON.parse, then validates.
|
|
*/
|
|
export function parseTurnResult(raw: string): TurnResult | null {
|
|
const cleaned = stripFence(raw);
|
|
const jsonText = extractBalancedObject(cleaned);
|
|
if (!jsonText) return null;
|
|
let obj: unknown;
|
|
try {
|
|
obj = JSON.parse(jsonText);
|
|
} catch {
|
|
return null;
|
|
}
|
|
return validateTurnResult(obj);
|
|
}
|
|
|
|
function str(s: unknown, max = 0): string | null {
|
|
if (typeof s !== 'string') return null;
|
|
const t = s.trim();
|
|
if (!t) return null;
|
|
return max ? t.slice(0, max) : t;
|
|
}
|
|
|
|
/**
|
|
* Validate a raw (LLM) `nationOps` array into safe {@link NationOp} values
|
|
* (v0.23, #16 P4a). Defensive like the rest of the parser: entries with an
|
|
* unknown `kind` or missing/empty required fields are dropped, never throw.
|
|
* Rename: non-empty `nationRef` + `to` (each capped at 200 chars — resolution
|
|
* of `nationRef` to a concrete nation happens later, at confirm time). Split:
|
|
* non-empty `nationRef` + at least one part with a name. Merge: non-empty
|
|
* `nationRefs` (capped at 20) + `survivingRef` + `into`.
|
|
*/
|
|
export function validateNationOps(raw: unknown): NationOp[] {
|
|
if (!Array.isArray(raw)) return [];
|
|
const out: NationOp[] = [];
|
|
for (const e of raw) {
|
|
if (!e || typeof e !== 'object') continue;
|
|
const o = e as Record<string, unknown>;
|
|
if (o.kind === 'rename') {
|
|
const nationRef = str(o.nationRef, 200);
|
|
const to = str(o.to, 200);
|
|
if (nationRef && to) out.push({ kind: 'rename', nationRef, to });
|
|
} else if (o.kind === 'split') {
|
|
const nationRef = str(o.nationRef, 200);
|
|
const parts = (Array.isArray(o.parts) ? o.parts : [])
|
|
.filter((p): p is Record<string, unknown> => !!p && typeof p === 'object')
|
|
.map((p) => {
|
|
const name = str(p.name, 200);
|
|
const territory = Array.isArray(p.territory)
|
|
? p.territory.filter((k): k is string => typeof k === 'string' && k.trim() !== '')
|
|
: [];
|
|
return { name, territory };
|
|
})
|
|
.filter((p): p is { name: string; territory: string[] } => p.name !== null);
|
|
if (nationRef && parts.length > 0) out.push({ kind: 'split', nationRef, parts });
|
|
} else if (o.kind === 'merge') {
|
|
const nationRefs = (Array.isArray(o.nationRefs) ? o.nationRefs : [])
|
|
.map((x) => (typeof x === 'string' ? x.trim().slice(0, 200) : ''))
|
|
.filter((x) => x !== '')
|
|
.slice(0, 20);
|
|
const survivingRef = str(o.survivingRef, 200);
|
|
const into = str(o.into, 200);
|
|
if (nationRefs.length > 0 && survivingRef && into) {
|
|
out.push({ kind: 'merge', nationRefs, survivingRef, into });
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Validate and normalize an arbitrary parsed object into a safe TurnResult.
|
|
* Ignores unknown/invalid entries; clamps numeric stats to 0-100. Returns null
|
|
* only when the input is not even a plain object.
|
|
*/
|
|
export function validateTurnResult(input: unknown): TurnResult | null {
|
|
if (typeof input !== 'object' || input === null || Array.isArray(input)) return null;
|
|
const o = input as Record<string, unknown>;
|
|
const result: TurnResult = {
|
|
date: typeof o.date === 'string' ? o.date : '',
|
|
events: [],
|
|
stateChanges: [],
|
|
relations: [],
|
|
territoryChanges: [],
|
|
unowned: [],
|
|
nationOps: [],
|
|
};
|
|
|
|
if (Array.isArray(o.events)) {
|
|
for (const e of o.events) {
|
|
if (!e || typeof e !== 'object') continue;
|
|
const ev = e as Record<string, unknown>;
|
|
const nation = str(ev.nation);
|
|
const title = str(ev.title, 200);
|
|
const text = str(ev.text, 1200);
|
|
if (!nation || !title || !text) continue;
|
|
const type = VALID_EVENT_TYPES.has(String(ev.type))
|
|
? (ev.type as EventType)
|
|
: 'political';
|
|
const outcome = VALID_OUTCOMES.has(String(ev.outcome))
|
|
? (ev.outcome as EventOutcome)
|
|
: 'neutral';
|
|
result.events.push({ nation, type, title, text, outcome });
|
|
}
|
|
}
|
|
|
|
if (Array.isArray(o.stateChanges)) {
|
|
for (const c of o.stateChanges) {
|
|
if (!c || typeof c !== 'object') continue;
|
|
const cc = c as Record<string, unknown>;
|
|
const nation = str(cc.nation);
|
|
const stat = str(cc.stat);
|
|
if (!nation || !stat || !VALID_STATS.has(stat)) continue;
|
|
if (typeof cc.value !== 'number' || !Number.isFinite(cc.value)) continue;
|
|
if (cc.op === 'add') {
|
|
result.stateChanges.push({
|
|
nation,
|
|
stat: stat as StatKey,
|
|
op: 'add',
|
|
value: cc.value,
|
|
});
|
|
} else if (cc.op === 'set') {
|
|
result.stateChanges.push({
|
|
nation,
|
|
stat: stat as StatKey,
|
|
op: 'set',
|
|
value: clampStat(cc.value),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (Array.isArray(o.relations)) {
|
|
for (const r of o.relations) {
|
|
if (!r || typeof r !== 'object') continue;
|
|
const rr = r as Record<string, unknown>;
|
|
const a = str(rr.a);
|
|
const b = str(rr.b);
|
|
if (!a || !b || a === b) continue;
|
|
if (!VALID_RELATIONS.has(String(rr.set))) continue;
|
|
result.relations.push({ a, b, set: rr.set as RelationStatus });
|
|
}
|
|
}
|
|
|
|
if (Array.isArray(o.territoryChanges)) {
|
|
for (const t of o.territoryChanges) {
|
|
if (!t || typeof t !== 'object') continue;
|
|
const tt = t as Record<string, unknown>;
|
|
const nation = str(tt.nation);
|
|
if (!nation) continue;
|
|
const gain = Array.isArray(tt.gain)
|
|
? tt.gain.filter((x): x is string => typeof x === 'string')
|
|
: [];
|
|
const lose = Array.isArray(tt.lose)
|
|
? tt.lose.filter((x): x is string => typeof x === 'string')
|
|
: [];
|
|
if (gain.length === 0 && lose.length === 0) continue;
|
|
result.territoryChanges.push({ nation, gain, lose });
|
|
}
|
|
}
|
|
|
|
// (v0.22, #16 P3) Keys released to "no man's land": deduped, non-empty
|
|
// strings only (applied later by applyTurnResult against validKeys).
|
|
if (Array.isArray(o.unowned)) {
|
|
for (const k of o.unowned) {
|
|
const s = typeof k === 'string' ? k.trim() : '';
|
|
if (s && !result.unowned.includes(s)) result.unowned.push(s);
|
|
}
|
|
}
|
|
|
|
// (v0.23, #16 P4a) Nation-management ops the LLM proposes this turn. These
|
|
// are NOT applied by the turn — applyTurnResult appends them to the pending
|
|
// list for the player to confirm/reject.
|
|
result.nationOps = validateNationOps(o.nationOps);
|
|
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* A turn is "meaningful" if it produced at least an event, a stat change, a
|
|
* no-man's-land release (v0.22 #16 P3: a release is a real world change even
|
|
* when the model under-narrates it), or a nation-op proposal (v0.23 #16 P4a:
|
|
* a proposal is a real pending-world change the player will resolve, so it
|
|
* must survive the retry/nudge path instead of being replaced by the generic
|
|
* "unclear" result).
|
|
*/
|
|
export function isMeaningful(result: TurnResult): boolean {
|
|
return (
|
|
result.events.length > 0 ||
|
|
result.stateChanges.length > 0 ||
|
|
result.unowned.length > 0 ||
|
|
result.nationOps.length > 0
|
|
);
|
|
}
|
|
|
|
// --- Applying the delta -------------------------------------------------------
|
|
|
|
function genericUnclearEvent(state: GameState): TurnEventSpec {
|
|
return {
|
|
nation: state.playerNationId,
|
|
type: 'political',
|
|
title: 'The turn was unclear',
|
|
text: 'The simulation could not resolve a clear outcome this turn; the world drifts forward on its own momentum.',
|
|
outcome: 'neutral',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Apply a TurnResult to a GameState immutably: advance the date/turn, append
|
|
* events, apply stat changes (clamped), symmetric relations, and territory
|
|
* moves (including no-man's-land releases, v0.22 #16 P3). It also appends any
|
|
* proposed nation-ops to the pending list (v0.23 #16 P4a) without applying
|
|
* them — see the doc comment on `pendingNationOps` for why that list
|
|
* deliberately survives across turns.
|
|
*/
|
|
export function applyTurnResult(state: GameState, result: TurnResult, validKeys?: ReadonlySet<string>): GameState {
|
|
const next: GameState = JSON.parse(JSON.stringify(state));
|
|
next.version = (state.version ?? 0) + 1; // every mutation is a new revision
|
|
const actingTurn = state.turn; // this action resolves the current turn
|
|
next.turn = state.turn + 1; // then we advance to the next turn to play
|
|
next.date = isDateLike(result.date) ? result.date : addDays(state.date, 2);
|
|
// Committing a turn consumes the whole queued round — reset it for the next.
|
|
next.pending = [];
|
|
for (const ev of result.events) {
|
|
next.events.push(makeEvent(ev, actingTurn, next.date));
|
|
}
|
|
for (const c of result.stateChanges) {
|
|
const n = next.nations[c.nation];
|
|
if (!n) continue;
|
|
n.stats[c.stat] = c.op === 'set' ? clampStat(c.value) : clampStat(n.stats[c.stat] + c.value);
|
|
}
|
|
for (const r of result.relations) {
|
|
const a = next.nations[r.a];
|
|
const b = next.nations[r.b];
|
|
if (!a || !b) continue;
|
|
a.relations[r.b] = r.set;
|
|
b.relations[r.a] = r.set;
|
|
}
|
|
// --- Territory (v0.21, #16 P2: at most one owner per key;
|
|
// v0.22, #16 P3: a key may also be released to "no man's land") ---
|
|
//
|
|
// Two kinds of change, applied in this order:
|
|
//
|
|
// (1) RELEASES (`result.unowned`, v0.22 #16 P3): each key that a nation
|
|
// CURRENTLY owns (exactly one owner) is removed from that owner, left
|
|
// ownerless, and added to `GameState.unowned` — the client renders it
|
|
// as the distinct no-man's-land grey. A key with zero owners (a preset
|
|
// never assigned it) is never released: doing so would fabricate a
|
|
// visible no-man's-land out of an ordinary unowned region. A key with
|
|
// two or more owners (pre-existing corruption) is never touched, and
|
|
// a key already in `unowned` is a no-op (it is already unowned).
|
|
//
|
|
// (2) CLAIMS (`gain` entries), resolved against the ownership AFTER the
|
|
// releases (snapshot-first):
|
|
// - a key with exactly one owner that is not the gainer → a TRANSFER:
|
|
// removed from the old owner, granted to the gainer (v0.21 rules);
|
|
// - a key with NO owner → a RE-CLAIM: granted to the (sole) gainer and
|
|
// removed from `GameState.unowned` (it leaves no man's land);
|
|
// - a double claim (two or more distinct gainers) is rejected — the
|
|
// key stays as it is; a self-gain is a no-op; a pre-existing double
|
|
// ownership is never touched.
|
|
//
|
|
// Invariants after the turn: no key sits in two or more territories; a
|
|
// released key sits in none; `GameState.unowned` holds exactly the
|
|
// zero-owner keys that were released mid-game (not the preset-unassigned
|
|
// ones). "lose" entries remain deliberate no-ops: releasing is the
|
|
// `unowned` list's job, and a lone loss without a release would just
|
|
// orphan a key silently.
|
|
const valid = (k: string) => !validKeys || validKeys.has(k);
|
|
const unowned = new Set(state.unowned ?? []);
|
|
|
|
// (1) Releases: establish the new no-man's-land set before any claim.
|
|
for (const key of new Set(result.unowned)) {
|
|
if (!valid(key) || unowned.has(key)) continue;
|
|
const owners = Object.values(next.nations)
|
|
.filter((n) => n.territory.includes(key))
|
|
.map((n) => n.id);
|
|
if (owners.length !== 1) continue; // 0 owners (never assigned) or 2+ (corrupt): no-op
|
|
unowned.add(key);
|
|
next.nations[owners[0]].territory = next.nations[owners[0]].territory.filter((k) => k !== key);
|
|
}
|
|
|
|
// (2) Claims against the post-release ownership snapshot.
|
|
const ownerOf = new Map<string, string>(); // key -> sole owner id, or '' (2+ owners; 0 = absent)
|
|
for (const n of Object.values(next.nations)) {
|
|
for (const key of n.territory) {
|
|
if (!valid(key)) continue;
|
|
const cur = ownerOf.get(key);
|
|
if (cur === undefined) ownerOf.set(key, n.id);
|
|
else if (cur !== '') ownerOf.set(key, '');
|
|
}
|
|
}
|
|
// Claim pairs, deduped: one (key, gainer) per pair even if the model emits
|
|
// duplicate entries; two DIFFERENT gainers for one key is a double claim.
|
|
const claimPairs = new Set<string>();
|
|
for (const t of result.territoryChanges) {
|
|
if (!next.nations[t.nation]) continue;
|
|
for (const key of new Set(t.gain)) {
|
|
if (!valid(key)) continue;
|
|
claimPairs.add(`${key}\u0000${t.nation}`);
|
|
}
|
|
}
|
|
const claimants = new Map<string, Set<string>>(); // key -> distinct gainers
|
|
for (const pair of claimPairs) {
|
|
const idx = pair.indexOf('\u0000');
|
|
const key = pair.slice(0, idx);
|
|
const gainer = pair.slice(idx + 1);
|
|
let set = claimants.get(key);
|
|
if (set === undefined) {
|
|
set = new Set();
|
|
claimants.set(key, set);
|
|
}
|
|
set.add(gainer);
|
|
}
|
|
for (const [key, claiming] of claimants) {
|
|
if (claiming.size !== 1) continue; // double claim: the key stays as it was
|
|
const gainer = [...claiming][0];
|
|
const owner = ownerOf.get(key); // undefined: no owner; '': 2+ owners (corrupt)
|
|
if (owner === '') continue; // pre-existing double ownership: never touched
|
|
if (owner !== undefined && owner === gainer) continue; // self-gain: no-op
|
|
for (const n of Object.values(next.nations)) {
|
|
const i = n.territory.indexOf(key);
|
|
if (i !== -1) n.territory.splice(i, 1);
|
|
}
|
|
next.nations[gainer].territory.push(key);
|
|
unowned.delete(key); // re-claimed: the key leaves no man's land
|
|
}
|
|
|
|
next.unowned = [...unowned];
|
|
// (v0.23, #16 P4a) Nation-op proposals are NOT applied by the turn — they
|
|
// are appended to the pending list, which (unlike `pending`) SURVIVES
|
|
// across turns until the player confirms or rejects each one. `next` is a
|
|
// deep clone of `state`, so `next.pendingNationOps` is a copy of whatever
|
|
// the state already held (or undefined for a legacy row) — start from that
|
|
// and append the new proposals, defaulting a missing field to `[]`.
|
|
next.pendingNationOps = [...(next.pendingNationOps ?? []), ...result.nationOps];
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* Immutably queue one item onto a round: append it to `pending` and return a new
|
|
* state. This never advances the turn or the date — that only happens when a
|
|
* round is committed via runTurn. Bumps `version` (a new revision, so stale SSE
|
|
* snapshots can never clobber it client-side). Exported so the append-without-
|
|
* advance behavior is unit-testable, and reused by the /action and /diplomacy
|
|
* routes.
|
|
*/
|
|
export function queueRoundItem(state: GameState, item: RoundItem): GameState {
|
|
const next: GameState = JSON.parse(JSON.stringify(state));
|
|
next.version = (state.version ?? 0) + 1;
|
|
next.pending.push(item);
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* Immutably remove one item from the pending round by index and return a new
|
|
* state (bumping `version`). Returns `null` when the index is missing or not a
|
|
* valid, in-bounds integer position, so the route can answer 400 without
|
|
* mutating anything. Reused by the server's /queue/remove route.
|
|
*/
|
|
export function removeRoundItem(state: GameState, index: number | undefined): GameState | null {
|
|
if (index === undefined || !Number.isInteger(index) || index < 0 || index >= state.pending.length) {
|
|
return null;
|
|
}
|
|
const next: GameState = JSON.parse(JSON.stringify(state));
|
|
next.version = (state.version ?? 0) + 1;
|
|
next.pending.splice(index, 1);
|
|
return next;
|
|
}
|
|
|
|
// --- Nation-management ops (v0.23, #16 P4a: the hybrid "LLM proposes,
|
|
// player confirms" model) ----------------------------------------------------
|
|
//
|
|
// A NationOp proposed by a turn lands in `GameState.pendingNationOps` (see
|
|
// applyTurnResult) and waits there across turns. These functions resolve the
|
|
// player's decision on one pending proposal, by index. Like removeRoundItem
|
|
// they are pure: clone the state, mutate the clone, bump `version` once,
|
|
// return the new state — and return `null` for a bad index so the route can
|
|
// answer 400 without mutating anything.
|
|
|
|
/** True when `index` is a valid, in-bounds integer position in the pending list. */
|
|
function validPendingOpIndex(state: GameState, index: number): boolean {
|
|
const len = state.pendingNationOps?.length ?? 0;
|
|
return Number.isInteger(index) && index >= 0 && index < len;
|
|
}
|
|
|
|
/**
|
|
* Resolve a nation reference (the `nationRef` of a NationOp — the LLM may
|
|
* write either the nation's stable `id` or its human-readable `name`) to a
|
|
* concrete nation id: an exact id match wins, then a unique case-insensitive
|
|
* name match. Returns `null` when the reference is empty, unknown, or
|
|
* ambiguous (two or more nations share that name) — every caller treats
|
|
* `null` as "no-op" and nothing here ever throws.
|
|
*/
|
|
export function resolveNationRef(state: GameState, ref: string): string | null {
|
|
const r = (ref ?? '').trim();
|
|
if (!r) return null;
|
|
if (state.nations[r]) return r; // exact id first
|
|
const matches = Object.values(state.nations).filter(
|
|
(n) => n.name.trim().toLowerCase() === r.toLowerCase(),
|
|
);
|
|
return matches.length === 1 ? matches[0].id : null;
|
|
}
|
|
|
|
/**
|
|
* Generate a fresh, unused nation id for a newly created nation (split
|
|
* parts, v0.24 #16 P4b): the first free of `n1`, `n2`, ... The caller adds
|
|
* each id it creates to `taken` as it goes, so ids stay unique within an
|
|
* op and are never reused from a removed nation.
|
|
*/
|
|
export function freshNationId(taken: ReadonlySet<string>): string {
|
|
for (let i = 1; ; i++) {
|
|
const id = `n${i}`;
|
|
if (!taken.has(id)) return id;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The baseline stats a freshly created nation starts with (split parts,
|
|
* v0.24 #16 P4b) — a neutral middle-of-the-scale profile, deliberately NOT
|
|
* a copy of the parent's stats (a small rump state is not the parent's
|
|
* military power).
|
|
*/
|
|
export const NEW_NATION_STATS: NationStats = {
|
|
military: 50,
|
|
economy: 50,
|
|
stability: 50,
|
|
population: 50,
|
|
};
|
|
|
|
/**
|
|
* Defensive cleanup after nations are removed (merge, v0.24 #16 P4b): drop
|
|
* the removed nations' ids from every remaining nation's `relations` map so
|
|
* no key dangles. (The client already degrades gracefully on a missing
|
|
* target, but consistent data is cleaner.)
|
|
*/
|
|
function dropRelationsTo(state: GameState, removedIds: ReadonlySet<string>): void {
|
|
for (const n of Object.values(state.nations)) {
|
|
for (const id of removedIds) {
|
|
if (id in n.relations) delete n.relations[id];
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Apply one NationOp to a state, MUTATING the passed object in place (the
|
|
* caller passes a clone — confirmNationOp does) and NOT bumping `version`
|
|
* (the route-level functions do that once per decision). It never throws:
|
|
* any unresolvable reference or malformed op is a silent no-op (the op is
|
|
* still removed by confirmNationOp — the world simply doesn't change).
|
|
*
|
|
* - **rename** (v0.23, #16 P4a): changes only `Nation.name` — the id, its
|
|
* territory, its relations (keyed by id), and the player pointer all stay
|
|
* valid, so nothing downstream breaks; a player-supplied `edits.name`
|
|
* overrides the proposed `to` (an empty edit falls back to the proposal's
|
|
* own name).
|
|
*
|
|
* - **split** (v0.24, #16 P4b): the `nationRef` must resolve and there must
|
|
* be at least two named parts, else no-op. Parts are processed in order;
|
|
* each receives the region keys of its `territory` that (a) the parent
|
|
* owns and (b) no earlier part claimed — the first part to name a key
|
|
* wins. Keys of the parent's territory that no part claimed go to part 0
|
|
* (in the parent's `territory` order), so the parent's territory is fully
|
|
* partitioned — no key is lost or ever held twice. Each part gets a
|
|
* FRESH id (`freshNationId`) and the baseline `NEW_NATION_STATS` (not a
|
|
* copy of the parent's), plus a copy of the parent's relations; the
|
|
* parent is then removed. If the parent was the player's nation,
|
|
* `playerNationId` moves to the chosen part (`edits.playerPart`, clamped
|
|
* into range, default 0); `edits.name` renames that same chosen part.
|
|
*
|
|
* - **merge** (v0.24, #16 P4b): every input ref plus the survivor ref must
|
|
* resolve, at least two inputs must resolve to DISTINCT nations, and the
|
|
* survivor must be one of them — else no-op. The survivor keeps its id,
|
|
* keeps its own stats, gains the union of all inputs' territories
|
|
* (survivor's keys first, then each other input's unclaimed keys in its
|
|
* own order), and gains a union of the inputs' relations (on a third
|
|
* party the survivor's own view wins, else the first input's). The other
|
|
* inputs are removed (their ids dropped from everyone else's relations
|
|
* maps), and if the player led a removed input, `playerNationId` moves to
|
|
* the survivor. The merged name is `edits.name` (if non-empty), else
|
|
* `op.into`, else the survivor's current name.
|
|
*/
|
|
export function applyNationOp(
|
|
state: GameState,
|
|
op: NationOp,
|
|
edits?: { name?: string; playerPart?: number },
|
|
): void {
|
|
if (op.kind === 'rename') {
|
|
const id = resolveNationRef(state, op.nationRef);
|
|
if (id === null) return; // invalid/ambiguous ref: no-op
|
|
const n = state.nations[id];
|
|
if (!n) return;
|
|
const name = (edits?.name ?? '').trim() || op.to.trim();
|
|
if (name) n.name = name;
|
|
return;
|
|
}
|
|
|
|
if (op.kind === 'split') {
|
|
const id = resolveNationRef(state, op.nationRef);
|
|
if (id === null || op.parts.length < 2) return; // invalid ref / not enough parts: no-op
|
|
const parent = state.nations[id];
|
|
if (!parent) return;
|
|
const taken = new Set(Object.keys(state.nations));
|
|
const created: string[] = [];
|
|
const claimed = new Set<string>();
|
|
for (const part of op.parts) {
|
|
const newId = freshNationId(taken);
|
|
taken.add(newId);
|
|
const keys = (part.territory ?? [])
|
|
.filter((k) => parent.territory.includes(k) && !claimed.has(k));
|
|
for (const k of keys) claimed.add(k);
|
|
const partNation: Nation = {
|
|
id: newId,
|
|
type: parent.type, // a part keeps the parent's form of state
|
|
name: part.name,
|
|
stats: { ...NEW_NATION_STATS },
|
|
territory: keys,
|
|
relations: { ...parent.relations },
|
|
};
|
|
state.nations[newId] = partNation;
|
|
created.push(newId);
|
|
}
|
|
// Keys the parent owned but no part claimed go to part 0 (in the
|
|
// parent's territory order) — nothing is lost or duplicated.
|
|
for (const k of parent.territory) {
|
|
if (!claimed.has(k)) state.nations[created[0]].territory.push(k);
|
|
}
|
|
// The player chooses which part is its successor (edits.playerPart,
|
|
// clamped into range; default 0) — only relevant when the parent was
|
|
// the player's nation; the same part also gets a player-edited name.
|
|
const partIdx =
|
|
Math.min(Math.max(edits?.playerPart ?? 0, 0), created.length - 1);
|
|
if (state.playerNationId === id) state.playerNationId = created[partIdx];
|
|
const editedName = (edits?.name ?? '').trim();
|
|
if (editedName) state.nations[created[partIdx]].name = editedName;
|
|
delete state.nations[id];
|
|
dropRelationsTo(state, new Set([id]));
|
|
return;
|
|
}
|
|
|
|
// merge
|
|
const resolved: string[] = [];
|
|
for (const ref of op.nationRefs) {
|
|
const rid = resolveNationRef(state, ref);
|
|
if (rid === null) return; // any unresolvable input: no-op
|
|
resolved.push(rid);
|
|
}
|
|
const inputIds = new Set(resolved);
|
|
const survivorId = resolveNationRef(state, op.survivingRef);
|
|
if (survivorId === null || !inputIds.has(survivorId) || inputIds.size < 2) return;
|
|
const survivor = state.nations[survivorId];
|
|
if (!survivor) return;
|
|
// Territory: the union of all inputs — the survivor's keys first (stable
|
|
// order), then each other input's unclaimed keys in its own order.
|
|
const territory = [...survivor.territory];
|
|
const seen = new Set(territory);
|
|
for (const rid of resolved) {
|
|
for (const k of state.nations[rid].territory) {
|
|
if (!seen.has(k)) {
|
|
seen.add(k);
|
|
territory.push(k);
|
|
}
|
|
}
|
|
}
|
|
// Relations: the union of all inputs' relations; the first input to name a
|
|
// third party sets it, then the survivor's own view overwrites per key.
|
|
const relations: Record<string, RelationStatus> = {};
|
|
for (const rid of resolved) {
|
|
for (const [other, status] of Object.entries(state.nations[rid].relations)) {
|
|
if (other === survivorId) continue; // never relate to oneself
|
|
if (!(other in relations)) relations[other] = status;
|
|
}
|
|
}
|
|
for (const [other, status] of Object.entries(survivor.relations)) {
|
|
if (other !== survivorId) relations[other] = status;
|
|
}
|
|
const removed = new Set<string>();
|
|
for (const rid of inputIds) {
|
|
if (rid === survivorId) continue;
|
|
delete state.nations[rid];
|
|
removed.add(rid);
|
|
}
|
|
if (state.playerNationId !== survivorId && removed.has(state.playerNationId)) {
|
|
state.playerNationId = survivorId;
|
|
}
|
|
const name = (edits?.name ?? '').trim() || op.into.trim() || survivor.name;
|
|
if (name) survivor.name = name;
|
|
survivor.territory = territory;
|
|
survivor.relations = relations;
|
|
dropRelationsTo(state, removed);
|
|
}
|
|
|
|
/**
|
|
* Confirm a pending nation-op proposal by index: apply it (a rename takes
|
|
* effect, optionally with a player-edited name; a split partitions the
|
|
* nation's territory into the new parts, the player picking which part is
|
|
* its successor via `edits.playerPart`; a merge folds the inputs into the
|
|
* survivor, optionally renamed via `edits.name`) and remove it from
|
|
* `pendingNationOps`, bumping `version`. Returns `null` for an invalid
|
|
* index, so the route answers 400 without mutating. Reused by the
|
|
* /nation-op/confirm route.
|
|
*/
|
|
export function confirmNationOp(
|
|
state: GameState,
|
|
index: number,
|
|
edits?: { name?: string; playerPart?: number },
|
|
): GameState | null {
|
|
if (!validPendingOpIndex(state, index)) return null;
|
|
const next: GameState = JSON.parse(JSON.stringify(state));
|
|
next.version = (state.version ?? 0) + 1;
|
|
const op = next.pendingNationOps[index];
|
|
applyNationOp(next, op, edits);
|
|
next.pendingNationOps.splice(index, 1);
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* Reject (drop) a pending nation-op proposal by index without applying it,
|
|
* bumping `version`. Returns `null` for an invalid index, so the route
|
|
* answers 400 without mutating. Reused by the /nation-op/reject route.
|
|
*/
|
|
export function rejectNationOp(state: GameState, index: number): GameState | null {
|
|
if (!validPendingOpIndex(state, index)) return null;
|
|
const next: GameState = JSON.parse(JSON.stringify(state));
|
|
next.version = (state.version ?? 0) + 1;
|
|
next.pendingNationOps.splice(index, 1);
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* Run one turn end-to-end against the (injectable) LLM: build prompts, parse/
|
|
* validate, retry once with a nudge if the result is empty/invalid, and — if
|
|
* it is still invalid — emit a generic "unclear" event and advance. The
|
|
* committed state has `pending` cleared. Never throws on bad model output;
|
|
* only the underlying transport/network can throw.
|
|
*
|
|
* When `getNeighbours` is provided AND the LLM client implements
|
|
* `chatWithTools` (v0.21, #16 P2), the turn runs the bounded function-
|
|
* calling loop with the getNeighbours tool (the model may verify land
|
|
* borders before committing a territory transfer) and the user prompt gains
|
|
* the player's `frontier` field. Otherwise it falls back to a plain chat()
|
|
* call — same as before the tool existed.
|
|
*/
|
|
export async function runTurn(opts: {
|
|
llm: LlmClient;
|
|
preset: Preset;
|
|
state: GameState;
|
|
items: RoundItem[];
|
|
/** Region reference table (key -> "name (parent)") to include in the user prompt. */
|
|
regionReference?: Record<string, string>;
|
|
/** Set of valid region keys; territory changes with other keys are ignored. */
|
|
validRegionKeys?: ReadonlySet<string>;
|
|
/**
|
|
* Region adjacency resolver (keys -> bordering keys, from the precomputed
|
|
* manifest). Its presence (together with the client's chatWithTools)
|
|
* switches the turn onto the getNeighbours tool path.
|
|
*/
|
|
getNeighbours?: (keys: string[]) => string[];
|
|
}): Promise<{ state: GameState; result: TurnResult }> {
|
|
const { llm, preset, state, items, regionReference, validRegionKeys, getNeighbours } = opts;
|
|
const chatWithTools = llm.chatWithTools;
|
|
const useTools = getNeighbours !== undefined && chatWithTools !== undefined;
|
|
const system = buildSystemPrompt(preset, useTools);
|
|
const frontier = getNeighbours ? playerFrontier(state, getNeighbours) : undefined;
|
|
// (v0.22, #16 P3) the model always sees the current no-man's-land keys (empty
|
|
// list on a fresh game) so it knows which unowned regions can be re-claimed.
|
|
const user = buildUserPrompt(state, items, regionReference, frontier, state.unowned ?? []);
|
|
const nudge =
|
|
'Your previous output was invalid. Respond with ONLY the JSON object described above for this batch — no prose, no fences.';
|
|
|
|
/**
|
|
* One model call with the standard turn sampling: the bounded
|
|
* function-calling loop when available, else a plain chat(). The nudge
|
|
* re-send below always starts a FRESH history (no tool context carried
|
|
* over).
|
|
*/
|
|
const call = async (history: WireMessage[]): Promise<string> => {
|
|
if (useTools) {
|
|
return await chatWithTools(
|
|
history,
|
|
[GET_NEIGHBOURS_TOOL],
|
|
makeNeighboursExecutor(getNeighbours, validRegionKeys),
|
|
{ temperature: 0.4, maxTokens: DEFAULT_MAX_TOKENS },
|
|
);
|
|
}
|
|
return llm.chat(history as ChatMessage[], { temperature: 0.4, maxTokens: DEFAULT_MAX_TOKENS });
|
|
};
|
|
|
|
let result = parseTurnResult(await call([
|
|
{ role: 'system', content: system },
|
|
{ role: 'user', content: user },
|
|
]));
|
|
|
|
if (result === null || !isMeaningful(result)) {
|
|
result = parseTurnResult(await call([
|
|
{ role: 'system', content: system },
|
|
{ role: 'user', content: user },
|
|
{ role: 'assistant', content: '' },
|
|
{ role: 'user', content: nudge },
|
|
]));
|
|
}
|
|
|
|
if (result === null || !isMeaningful(result)) {
|
|
result = {
|
|
date: addDays(state.date, 2),
|
|
events: [genericUnclearEvent(state)],
|
|
stateChanges: [],
|
|
relations: [],
|
|
territoryChanges: [],
|
|
unowned: [],
|
|
nationOps: [],
|
|
};
|
|
}
|
|
|
|
return { state: applyTurnResult(state, result, validRegionKeys), result };
|
|
}
|
|
|
|
// --- Advisor (brainstorm) -----------------------------------------------------
|
|
|
|
export function buildAdvisorPrompt(
|
|
state: GameState,
|
|
prompt?: string,
|
|
): { system: string; user: string } {
|
|
const player = state.nations[state.playerNationId];
|
|
const system = [
|
|
`${ADVISOR_MARKER} You are a trusted strategic advisor to ${player?.name ?? 'the player'} (${state.playerNationId}).`,
|
|
'Given the current world state, brainstorm 3-5 concrete, in-character action ideas the player could take this turn.',
|
|
'Respond with ONLY a JSON array of 3-5 short strings. No object, no markdown fences, no prose.',
|
|
].join('\n');
|
|
const user = JSON.stringify({
|
|
player: player ? nationForPrompt(player) : null,
|
|
date: state.date,
|
|
turn: state.turn,
|
|
prompt: prompt ?? null,
|
|
});
|
|
return { system, user };
|
|
}
|
|
|
|
/** Parse advisor output (a JSON array of strings) into a clean suggestion list. */
|
|
export function parseAdvisor(raw: string): string[] {
|
|
const t = stripFence(raw);
|
|
const a = t.indexOf('[');
|
|
const b = t.lastIndexOf(']');
|
|
if (a !== -1 && b > a) {
|
|
try {
|
|
const arr = JSON.parse(t.slice(a, b + 1));
|
|
if (Array.isArray(arr)) {
|
|
const out = arr
|
|
.map((x) =>
|
|
typeof x === 'string'
|
|
? x
|
|
: x && typeof x === 'object'
|
|
? String((x as Record<string, unknown>).title ?? (x as Record<string, unknown>).text ?? '')
|
|
: '',
|
|
)
|
|
.map((s) => s.trim())
|
|
.filter((s) => s.length > 2);
|
|
if (out.length) return out.slice(0, 5);
|
|
}
|
|
} catch {
|
|
/* fall through to line-splitting */
|
|
}
|
|
}
|
|
return t
|
|
.split(/\n+/)
|
|
.map((l) => l.replace(/^[-*\d.)\s]+/, '').trim())
|
|
.filter((l) => l.length > 3)
|
|
.slice(0, 5);
|
|
}
|
|
|
|
/** Ask the LLM for 3-5 action ideas; degrades to a canned line if the model fails. */
|
|
export async function askAdvisor(
|
|
llm: LlmClient,
|
|
state: GameState,
|
|
prompt?: string,
|
|
): Promise<string[]> {
|
|
const { system, user } = buildAdvisorPrompt(state, prompt);
|
|
const raw = await llm.chat([
|
|
{ role: 'system', content: system },
|
|
{ role: 'user', content: user },
|
|
], { temperature: 0.7, maxTokens: DEFAULT_MAX_TOKENS });
|
|
const out = parseAdvisor(raw);
|
|
return out.length
|
|
? out
|
|
: ['The council is divided; no clear course of action is advisable this turn.'];
|
|
}
|