Skip to content

Module API Reference

Function signatures and hooks for built-in modules.

Creates and returns an engine instance.

Creates an isolated engine instance for testing.

Cognition Core — createCognitionCore(config?)

Section titled “Cognition Core — createCognitionCore(config?)”
FunctionSignatureDescription
getCognition(world, entityId) → CognitionStateGet entity’s cognition state
setBelief(world, entityId, belief) → voidSet a belief
getBelief(world, entityId, subject, key) → BeliefGet a specific belief
getBeliefValue(world, entityId, subject, key) → anyGet belief value directly
believes(world, entityId, subject, key, value) → booleanCheck if entity holds a belief
addMemory(world, entityId, memory) → voidRecord a memory
getMemories(world, entityId) → Memory[]Get all memories
getRecentMemories(world, entityId, count) → Memory[]Get N most recent memories
checkPerception(world, entityId, difficulty, stat?) → PerceptionResultRoll a perception check
selectIntent(world, entityId) → IntentOptionChoose an action from AI profile

Perception Filter — createPerceptionFilter(config?)

Section titled “Perception Filter — createPerceptionFilter(config?)”
FunctionSignatureDescription
getPerceptionLog(world, entityId) → PerceivedEvent[]Full perception history
getRecentPerceptions(world, entityId, count) → PerceivedEvent[]Recent perceptions
didPerceive(world, entityId, eventType) → booleanCheck if entity perceived event type
whoPerceived(world, eventType) → string[]List entities that perceived event

Progression Core — createProgressionCore(config)

Section titled “Progression Core — createProgressionCore(config)”
FunctionSignatureDescription
getCurrency(world, entityId, currency) → numberGet currency balance
addCurrency(world, entityId, currency, amount) → voidAdd currency
spendCurrency(world, entityId, currency, amount) → booleanSpend currency
isNodeUnlocked(world, entityId, nodeId) → booleanCheck if node is unlocked
canUnlock(world, entityId, nodeId) → booleanCheck if node can be unlocked
unlockNode(world, entityId, nodeId) → UnlockResultUnlock a progression node
getAvailableNodes(world, entityId) → TreeNode[]List unlockable nodes
getUnlockedNodes(world, entityId) → string[]List unlocked node IDs

Environment Core — createEnvironmentCore(config?)

Section titled “Environment Core — createEnvironmentCore(config?)”
FunctionSignatureDescription
getZoneProperty(world, zoneId, key) → numberGet dynamic zone property
setZoneProperty(world, zoneId, key, value) → voidSet zone property
modifyZoneProperty(world, zoneId, key, delta) → voidModify property by delta
processEnvironmentDecays(world) → voidProcess all decay timers

Narrative Authority — createNarrativeAuthority(config?)

Section titled “Narrative Authority — createNarrativeAuthority(config?)”
FunctionSignatureDescription
conceal(world, eventId, reason) → voidHide an event from presentation
distort(world, eventId, replacement) → voidReplace event in presentation
getContradictions(world) → Contradiction[]List recorded contradictions
reveal(world, contradictionId) → voidExpose a hidden truth

District Core — createDistrictCore(config)

Section titled “District Core — createDistrictCore(config)”
FunctionSignatureDescription
getDistrictForZone(world, zoneId) → string | undefinedFind which district a zone belongs to
getDistrictState(world, districtId) → DistrictMetrics | undefinedGet district aggregate metrics
getDistrictDefinition(world, districtId) → DistrictDefinition | undefinedGet district config
getAllDistrictIds(world) → string[]List all district IDs
getDistrictMetric(world, districtId, metric) → numberGet a specific metric value
modifyDistrictMetric(world, districtId, metric, delta) → voidModify a metric by delta (clamped 0-100)
isDistrictOnAlert(world, districtId) → booleanCheck if alertPressure > 30
getDistrictThreatLevel(world, districtId) → numberWeighted composite of all metrics

Belief Provenance — createBeliefProvenance()

Section titled “Belief Provenance — createBeliefProvenance()”
FunctionSignatureDescription
traceEntityBelief(world, entityId, subject, key) → BeliefTraceTrace an entity belief’s provenance
traceFactionBelief(world, factionId, subject, key) → BeliefTraceTrace a faction belief through rumor chain
traceSubject(world, subject) → BeliefTrace[]Find all beliefs about a subject
formatBeliefTrace(trace) → stringHuman-readable forensic narrative

Observer Presentation — createObserverPresentation(config?)

Section titled “Observer Presentation — createObserverPresentation(config?)”
FunctionSignatureDescription
presentForObserver(event, observerId, world, rules?) → ObserverPresentedEventPresent event from observer’s perspective
presentForAllObservers(event, world) → ObserverPresentedEvent[]One version per AI entity
getDivergences(world) → DivergenceRecord[]All recorded divergences
getEventDivergences(world, eventId) → DivergenceRecord[]Divergences for a specific event

Pure functions for structured social play. 4 compound verbs (social, rumor, diplomacy, sabotage) with 24 sub-actions, resolved deterministically.

FunctionSignatureDescription
getLeverageState(custom) → LeverageStateExtract leverage currencies from profile
adjustLeverage(custom, currency, delta) → customModify a single currency
applyLeverageDeltas(custom, deltas) → customApply multiple currency changes
canAfford(state, costs) → booleanCheck if player can pay action costs
isCooldownReady(custom, verb, subAction, tick, turns) → booleanCheck cooldown elapsed
setCooldown(custom, verb, subAction, tick) → customRecord cooldown timestamp
resolveSocialAction(subAction, targetId, factionId, state, rep, factionCog?, tick) → LeverageResolutionResolve social verb
resolveRumorAction(subAction, factionId, state, tick) → LeverageResolutionResolve rumor verb
resolveDiplomacyAction(subAction, factionId, state, rep, factionCog?, tick) → LeverageResolutionResolve diplomacy verb
resolveSabotageAction(subAction, targetId, factionId, state, tick) → LeverageResolutionResolve sabotage verb
tickLeverage(custom, reputations) → customPassive tick: heat decay, influence calc
computeLeverageGains(hints) → Record<string, number>Natural gains from game events
formatLeverageForDirector(state) → stringDirector-mode leverage display
formatLeverageStatus(state) → stringCompact one-line status

Aggregates world state into a strategic overview of districts, factions, and hotspots.

FunctionSignatureDescription
buildStrategicMap(world, rumors, pressures, reputation, actions?) → StrategicMapBuild complete strategic view
formatStrategicMapForDirector(map) → stringDirector-mode map display
formatStrategicMapForPlayer(map) → stringPlayer-facing map display

Deterministic scoring engine that evaluates all 24 leverage sub-actions against current state. Drives contextual suggestions and /status command.

FunctionSignatureDescription
recommendMoves(inputs: AdvisorInputs) → MoveRecommendationScore all actions, return top 3 + situation tag
scoreAction(category, subAction, targetFactionId, inputs) → ScoredMoveScore a single action
deriveSituation(inputs) → 'safe' | 'pressured' | 'crisis' | 'opportunity'Derive situation tag from state

Scoring formula: score = (urgency × 0.3 + feasibility × 0.3 + impact × 0.25 + (1 - risk) × 0.15) × 100

  • Urgency: Active pressure urgency, faction hostility, threat levels
  • Feasibility: Binary gate (can afford? cooldown ready?) then surplus ratio
  • Impact: Static table from resolution effect magnitudes, boosted by pressure relevance
  • Risk: Heat generation + alert escalation, scaled by current heat

Pure functions for category-level supply tracking per district. No module registration — import and call directly.

FunctionSignatureDescription
createDistrictEconomy(genre?, districtTags?) → DistrictEconomyInitialize with genre defaults + tag modifiers
tickDistrictEconomy(economy, commerce, stability, tick) → DistrictEconomyBaseline-seeking decay, stability modulation
applyEconomyShift(economy, shift) → DistrictEconomyAdjust single supply, clamp 0-100
deriveEconomyDescriptor(economy) → EconomyDescriptorIdentify scarcities, surpluses, overall tone
isBlackMarketCondition(economy) → booleanTrue when contraband > 30 or any supply < 20
getSupplyLevel(economy, category) → numberGet level for a single category
getScarcestSupply(economy) → SupplyCategory | undefinedLowest supply below baseline
getMostSurplusSupply(economy) → SupplyCategory | undefinedHighest supply above baseline
formatEconomyForDirector(districtId, districtName, economy, descriptor) → stringDetailed director view
formatEconomyForNarrator(descriptor) → stringCompact phrase (~10 tokens)
formatAllDistrictEconomiesForDirector(economies) → stringMarket overview of all districts

Material tracking, salvage computation, and inventory management. Pure functions, no module registration.

FunctionSignatureDescription
getMaterialInventory(custom) → MaterialInventoryRead materials.* from profile.custom
adjustMaterial(custom, category, delta) → customModify single material, clamp 0-50
applyMaterialDeltas(custom, deltas) → customApply multiple material changes
hasMaterials(custom) → booleanTrue if any material > 0
computeSalvageYield(item) → MaterialYield[]Pure yield lookup by slot × rarity
salvageItem(item, context?) → SalvageResultFull salvage: yields + byproducts + economy shifts
formatMaterialsForDirector(inventory) → stringDetailed multi-line view
formatMaterialsCompact(inventory) → stringOne-line status
formatSalvagePreview(item, result) → stringPreview salvage yields

Recipe lookup, crafting resolution, repair, and modification. Pure functions, genre-aware.

FunctionSignatureDescription
getAvailableRecipes(genre, playerTags?, districtTags?) → CraftingRecipe[]Filter recipes by genre + tags
getRecipeById(genre, recipeId) → CraftingRecipe | undefinedSingle recipe lookup
canCraft(recipe, materials, context?) → CraftCheckMaterial + context requirement check
resolveCraft(recipe, context) → CraftResultExecute craft: output item + side effects
resolveRepair(item, recipe, context) → RepairResultRestore item stats
resolveModify(item, recipe, context) → ModifyResultApply modification: stat deltas + provenance
computeQualityBonus(context) → numberProsperity/stability quality modifier
formatRecipeForDirector(recipe, materials) → stringSingle recipe with can-craft status
formatAvailableRecipesForDirector(recipes, materials) → stringAll recipes grouped by category

Context-sensitive item valuation. Pure functions, lookup-table driven.

FunctionSignatureDescription
computeItemValue(baseValue, supplyCategory, ctx) → ItemValueResultFull contextual valuation
computeScarcityMultiplier(supplyLevel) → number0.5-3.0 based on supply level
computeFactionAttitudeMultiplier(reputation) → number0.85-1.5 based on faction rep
computeProvenanceMultiplier(provenance?, heat?) → number1.0-2.0 based on item history
computeContrabandFactor(isContraband, blackMarketActive, reputation) → number0.0-1.0
computePressureModifier(pressureKinds, category) → number0.8-1.5 from active pressures
deriveTradeAdvice(modifiers, isContraband) → TradeAdvicesell-here/elsewhere/hold/risky/untradeable
formatValueBreakdownForDirector(result) → stringDetailed value breakdown
formatTradeAdviceForNarrator(result) → stringCompact narrator advice

Emergent opportunity generation and lifecycle. Pure functions, no module registration.

FunctionSignatureDescription
evaluateOpportunities(inputs: OpportunityInputs) → OpportunitySpawnResult | nullEvaluate and spawn a new opportunity
tickOpportunities(opps, currentTick) → OpportunityTickResultDecrement timers, expire overdue, escalate visibility
getAvailableOpportunities(opps) → OpportunityState[]Filter to available opportunities
getAcceptedOpportunities(opps) → OpportunityState[]Filter to accepted opportunities
getOpportunityById(opps, id) → OpportunityState | undefinedFind by ID
getOpportunitiesForNpc(opps, npcId) → OpportunityState[]Filter by source NPC
getOpportunitiesForFaction(opps, factionId) → OpportunityState[]Filter by source faction
makeOpportunity(overrides) → OpportunityStateCreate opportunity with defaults
formatOpportunityForDirector(opp) → stringDetailed single opportunity view
formatOpportunityListForDirector(opps) → stringMulti-opportunity director list
formatOpportunityForNarrator(opp) → stringCompact narrator context
formatOpportunityForDialogue(opp) → stringDialogue context for quest-giver NPCs

Opportunity Resolution — opportunity-resolution.ts

Section titled “Opportunity Resolution — opportunity-resolution.ts”

Compute fallout effects when opportunities resolve. Pure functions, deterministic.

FunctionSignatureDescription
computeOpportunityFallout(opp, resolutionType, ctx) → OpportunityFalloutCompute all fallout effects for a resolution
formatOpportunityFalloutForDirector(fallout) → stringDetailed fallout breakdown
formatOpportunityFalloutForNarrator(fallout) → stringCompact narrator summary

Resolution types: completed, failed, abandoned, betrayed, expired, declined

Fallout effects (14 variants): reputation, leverage, materials, economy-shift, rumor, obligation, spawn-pressure, spawn-opportunity, heat, alert, npc-relationship, companion-morale, milestone-tag, title-trigger

Simulation Inspector — createSimulationInspector()

Section titled “Simulation Inspector — createSimulationInspector()”
FunctionSignatureDescription
inspectEntity(world, entityId) → EntityInspectionFull entity cognitive state
inspectFaction(world, factionId) → FactionInspectionFaction beliefs and alert level
inspectZone(world, zoneId) → ZoneInspectionZone environment state
inspectDistrict(world, districtId) → DistrictInspectionDistrict aggregate metrics
inspectAllDistricts(world) → Record<string, DistrictInspection>All district inspections
createSnapshot(world) → SimulationSnapshotFull world snapshot
formatEntityInspection(inspection) → stringText format for entity
formatFactionInspection(inspection) → stringText format for faction
formatDistrictInspection(inspection) → stringText format for district