totemheart 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +212 -0
- package/package.json +62 -0
- package/src/Totemheart.js +1363 -0
- package/src/behavior/AttentionFocus.js +69 -0
- package/src/behavior/ExpressionDebt.js +48 -0
- package/src/behavior/ExpressionDirectives.js +95 -0
- package/src/behavior/ExpressiveSuppression.js +45 -0
- package/src/behavior/IdleProcessing.js +64 -0
- package/src/behavior/LinguisticModulation.js +62 -0
- package/src/behavior/LogitBiasBuilder.js +31 -0
- package/src/behavior/RuminationChain.js +93 -0
- package/src/behavior/StyleMimicry.js +72 -0
- package/src/cognition/AmygdalaHijack.js +40 -0
- package/src/cognition/AppraisalAgreement.js +39 -0
- package/src/cognition/BayesianExpectation.js +59 -0
- package/src/cognition/CognitiveDissonance.js +71 -0
- package/src/cognition/ControllabilityEstimate.js +56 -0
- package/src/cognition/DecisionFatigue.js +44 -0
- package/src/cognition/DefenseMechanisms.js +32 -0
- package/src/cognition/EmotionalOntology.js +134 -0
- package/src/cognition/FuzzyNormativeCheck.js +60 -0
- package/src/cognition/Intuition.js +71 -0
- package/src/cognition/LifeEventCatalog.js +98 -0
- package/src/cognition/LoadScheduler.js +41 -0
- package/src/cognition/LogicEngine.js +69 -0
- package/src/cognition/NoveltyDetector.js +59 -0
- package/src/cognition/Reappraisal.js +34 -0
- package/src/cognition/RefractoryPeriod.js +38 -0
- package/src/cognition/RemConsolidation.js +79 -0
- package/src/cognition/SarcasmDetector.js +38 -0
- package/src/cognition/SemanticSimilarity.js +75 -0
- package/src/cognition/Sensitization.js +45 -0
- package/src/cognition/SituationalContext.js +48 -0
- package/src/cognition/TopicSatiation.js +54 -0
- package/src/cognition/VisualProsody.js +48 -0
- package/src/core/AffectEMA.js +26 -0
- package/src/core/CoreBeliefs.js +58 -0
- package/src/core/DecayEngine.js +56 -0
- package/src/core/EmotionSpace.js +146 -0
- package/src/core/HebbianPlasticity.js +59 -0
- package/src/core/HedonicAdaptation.js +62 -0
- package/src/core/Homeostasis.js +119 -0
- package/src/core/MicroEmotions.js +25 -0
- package/src/core/MoodTracker.js +53 -0
- package/src/core/Personality.js +84 -0
- package/src/core/PipelineResilience.js +24 -0
- package/src/core/TriggerSentinel.js +38 -0
- package/src/core/WornPathCache.js +57 -0
- package/src/economics/AnchoringBias.js +38 -0
- package/src/economics/ClassicalConditioning.js +59 -0
- package/src/economics/LossAversion.js +40 -0
- package/src/embodiment/HardwareInteroception.js +26 -0
- package/src/embodiment/InteroceptiveSignals.js +132 -0
- package/src/embodiment/SensoryOverload.js +45 -0
- package/src/index.js +14 -0
- package/src/integration/ContextAdapter.js +247 -0
- package/src/neurochemistry/ArousalKalmanFilter.js +39 -0
- package/src/neurochemistry/CircadianRhythm.js +29 -0
- package/src/neurochemistry/CortisolEngine.js +54 -0
- package/src/neurochemistry/DopaminergicEngine.js +42 -0
- package/src/providers/FunctionProvider.js +26 -0
- package/src/providers/HeuristicProvider.js +156 -0
- package/src/providers/LanguageProvider.js +13 -0
- package/src/providers/OllamaProvider.js +63 -0
- package/src/providers/TransformersProvider.js +154 -0
- package/src/social/Attachment.js +81 -0
- package/src/social/BystanderEffect.js +17 -0
- package/src/social/ChronicContagion.js +48 -0
- package/src/social/CounterfactualComparison.js +34 -0
- package/src/social/EgoConfidence.js +34 -0
- package/src/social/EgoProjection.js +20 -0
- package/src/social/EmotionalContagion.js +52 -0
- package/src/social/EpisodicMemory.js +266 -0
- package/src/social/FairnessMonitor.js +34 -0
- package/src/social/ForgettingCurve.js +28 -0
- package/src/social/GratitudeEngine.js +32 -0
- package/src/social/GuiltEngine.js +43 -0
- package/src/social/MonteCarloToM.js +49 -0
- package/src/social/ReputationEngine.js +45 -0
- package/src/social/SelfModel.js +50 -0
- package/src/social/StatusEnvy.js +34 -0
- package/src/social/TheoryOfMind.js +53 -0
- package/src/social/TribalCategorization.js +24 -0
- package/src/social/UncannyValleyDetector.js +59 -0
- package/src/text/EmotionalCorpus.js +70 -0
- package/src/text/EmotionalTextGenerator.js +56 -0
- package/src/text/ExplainabilityEngine.js +30 -0
- package/src/text/TemplateComposer.js +114 -0
- package/src/version.js +1 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real softmax attention weights over the tokens of the INPUT text (not a
|
|
3
|
+
* transformer's internal Q/K/V — Totemheart doesn't run a transformer, so
|
|
4
|
+
* there are no attention matrices inside it to manipulate). What's real and
|
|
5
|
+
* honest here: Attention(Q,K,V) = softmax(QKᵀ/√d_k)·V is, at its core, a
|
|
6
|
+
* softmax over per-token relevance scores producing a weighting that sums
|
|
7
|
+
* to 1 — that part is reproduced exactly, with "relevance score" computed
|
|
8
|
+
* from each token's emotional charge (the same lexicon HeuristicProvider
|
|
9
|
+
* uses) instead of learned Q/K vectors. High charge tokens get most of the
|
|
10
|
+
* weight, the same qualitative effect the request describes ("more than
|
|
11
|
+
* 80% of the weight on the most conflictive phrase") without pretending to
|
|
12
|
+
* reach into a model Totemheart doesn't run.
|
|
13
|
+
*/
|
|
14
|
+
function tokenize( text ) {
|
|
15
|
+
|
|
16
|
+
return ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
|
|
17
|
+
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class AttentionFocus {
|
|
21
|
+
|
|
22
|
+
constructor( { chargedWords = new Map(), habituationAlpha = 0.85 } = {} ) {
|
|
23
|
+
|
|
24
|
+
this.chargedWords = chargedWords // token -> charge score (0..1); unlisted tokens default to a low baseline
|
|
25
|
+
this.habituation = new Map() // token -> EMA of past attention weight (0..1)
|
|
26
|
+
this.habituationAlpha = habituationAlpha // EMA persistence: higher = slower to habituate, slower to recover
|
|
27
|
+
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Current habituation reading for a token, 0 if never attended to. */
|
|
31
|
+
getHabituation( token ) {
|
|
32
|
+
|
|
33
|
+
return this.habituation.get( token ) ?? 0
|
|
34
|
+
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Real softmax over per-token relevance, then a real EMA-based saturation:
|
|
39
|
+
* a token that has repeatedly drawn strong attention gets its pre-softmax
|
|
40
|
+
* score divided down before renormalizing, the same saturating shape
|
|
41
|
+
* HedonicAdaptation applies to a whole utterance's emotional fingerprint —
|
|
42
|
+
* here at token granularity instead, so a repeated trigger *word* stops
|
|
43
|
+
* dominating attention even inside a novel sentence. Returns [{ token,
|
|
44
|
+
* weight }] — weights still sum to 1 after the habituation-adjusted softmax.
|
|
45
|
+
*/
|
|
46
|
+
computeWeights( text, temperature = 0.3 ) {
|
|
47
|
+
|
|
48
|
+
const tokens = tokenize( text )
|
|
49
|
+
if ( !tokens.length ) return []
|
|
50
|
+
|
|
51
|
+
const scores = tokens.map( t => this.chargedWords.get( t ) ?? 0.05 )
|
|
52
|
+
const damped = scores.map( ( s, i ) => s / ( 1 + this.getHabituation( tokens[ i ] ) ) )
|
|
53
|
+
const scaled = damped.map( s => s / temperature )
|
|
54
|
+
const max = Math.max( ...scaled )
|
|
55
|
+
const exps = scaled.map( s => Math.exp( s - max ) )
|
|
56
|
+
const total = exps.reduce( ( a, b ) => a + b, 0 )
|
|
57
|
+
const weights = tokens.map( ( token, i ) => ( { token, weight: exps[ i ] / total } ) )
|
|
58
|
+
|
|
59
|
+
for ( const { token, weight } of weights ) {
|
|
60
|
+
|
|
61
|
+
this.habituation.set( token, this.habituationAlpha * this.getHabituation( token ) + ( 1 - this.habituationAlpha ) * weight )
|
|
62
|
+
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return weights
|
|
66
|
+
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
function clamp01( v ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Bystander silence and sensory-overload freezes exit processInput() before
|
|
9
|
+
* any text is generated, but the felt state at that moment doesn't stop
|
|
10
|
+
* existing just because it wasn't expressed. Nothing tracked that gap before
|
|
11
|
+
* this — the swallowed magnitude just vanished. This accumulates it as a
|
|
12
|
+
* real scalar (own design, no citation: not a reproduction of any named
|
|
13
|
+
* "affect suppression" model), decays slowly like CortisolEngine/Sensitization,
|
|
14
|
+
* and pays a fraction of it back into the next turn that actually produces
|
|
15
|
+
* output — a real "I've been holding this in" effect built from magnitudes
|
|
16
|
+
* Totemheart already computed, not an invented one.
|
|
17
|
+
*/
|
|
18
|
+
export class ExpressionDebt {
|
|
19
|
+
|
|
20
|
+
constructor() {
|
|
21
|
+
|
|
22
|
+
this.debt = 0
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Called at an early-exit point (no text produced) with the swallowed felt magnitude. */
|
|
27
|
+
accumulate( magnitude ) {
|
|
28
|
+
|
|
29
|
+
this.debt = clamp01( this.debt + Math.max( 0, magnitude ) * 0.5 )
|
|
30
|
+
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
decay( dt, lambda = 0.02 ) {
|
|
34
|
+
|
|
35
|
+
this.debt = Math.max( 0, this.debt - lambda * dt )
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Pays out `fraction` of the current debt and keeps the rest lingering (gradual catharsis, not a single dump). */
|
|
40
|
+
release( fraction = 0.5 ) {
|
|
41
|
+
|
|
42
|
+
const paid = this.debt * fraction
|
|
43
|
+
this.debt = this.debt - paid
|
|
44
|
+
return paid
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consolidates 4 requested "physiological output" mechanisms (facial Action
|
|
3
|
+
* Units, vocal prosody, body kinematics/posture, and instinctive action
|
|
4
|
+
* tendency) into ONE honest module: **directives for an external renderer**
|
|
5
|
+
* (an avatar rig, a TTS engine, a robot), not measurements Totemheart itself
|
|
6
|
+
* produces — this library has no camera, no speaker, no motors. Four related
|
|
7
|
+
* biometric *sensing* channels from the same request (pupil dilation, skin
|
|
8
|
+
* conductance/EDA, heart-rate variability, facial blood-flow/thermography)
|
|
9
|
+
* are deliberately NOT implemented here or anywhere else: those are things a
|
|
10
|
+
* human body is measured producing, not something any software — embodied
|
|
11
|
+
* or not — generates. Faking sensor readings with no sensor behind them
|
|
12
|
+
* would be exactly the kind of theater this project has avoided throughout.
|
|
13
|
+
* See CALIBRATION.md.
|
|
14
|
+
*/
|
|
15
|
+
function clamp01( v ) {
|
|
16
|
+
|
|
17
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
18
|
+
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function softmax( scores ) {
|
|
22
|
+
|
|
23
|
+
const values = Object.values( scores )
|
|
24
|
+
const max = Math.max( ...values )
|
|
25
|
+
const exps = Object.fromEntries( Object.entries( scores ).map( ( [ k, v ] ) => [ k, Math.exp( v - max ) ] ) )
|
|
26
|
+
const total = Object.values( exps ).reduce( ( a, b ) => a + b, 0 )
|
|
27
|
+
return Object.fromEntries( Object.entries( exps ).map( ( [ k, v ] ) => [ k, v / total ] ) )
|
|
28
|
+
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* FACS (Facial Action Coding System, Ekman & Friesen) prototype Action Units
|
|
33
|
+
* per emotion — the specific AU combinations for "basic" emotions are widely
|
|
34
|
+
* reproduced in the affective-computing literature; treat these as the
|
|
35
|
+
* commonly-cited prototypes, not a verified primary-source transcription.
|
|
36
|
+
*/
|
|
37
|
+
const FACS_PROTOTYPES = {
|
|
38
|
+
joy : [ 'AU6', 'AU12' ],
|
|
39
|
+
sadness : [ 'AU1', 'AU4', 'AU15' ],
|
|
40
|
+
fear : [ 'AU1', 'AU2', 'AU4', 'AU5', 'AU20', 'AU26' ],
|
|
41
|
+
anger : [ 'AU4', 'AU5', 'AU7', 'AU23' ],
|
|
42
|
+
surprise : [ 'AU1', 'AU2', 'AU5', 'AU26' ],
|
|
43
|
+
disgust : [ 'AU9', 'AU15', 'AU16' ],
|
|
44
|
+
neutral : [],
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class ExpressionDirectives {
|
|
48
|
+
|
|
49
|
+
/** Facial Action Units (item 25) with intensity 0-5, derived from the dominant emotion's blend weight. */
|
|
50
|
+
getFacialDirectives( dominantEmotion, intensityWeight = 1 ) {
|
|
51
|
+
|
|
52
|
+
const units = FACS_PROTOTYPES[ dominantEmotion ] ?? FACS_PROTOTYPES.neutral
|
|
53
|
+
const intensity = Math.round( clamp01( intensityWeight ) * 5 )
|
|
54
|
+
return units.map( au => ( { unit: au, intensity } ) )
|
|
55
|
+
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Vocal prosody targets (item 26) — pitch/rate/energy deltas for a TTS engine, not synthesized audio. */
|
|
59
|
+
getProsodyDirectives( { valence, arousal } ) {
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
pitchShift : arousal * 0.3, // fraction above/below baseline F0
|
|
63
|
+
rateShift : arousal * 0.2, // fraction faster/slower than baseline
|
|
64
|
+
energyLevel : clamp01( ( arousal + 1 ) / 2 ), // 0..1 loudness/intensity target
|
|
65
|
+
breathiness : valence < -0.3 ? clamp01( -valence * 0.4 ) : 0, // sadness/despair reads breathier
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Posture/kinematics descriptor (item 27) — classic approach/withdraw/freeze mapping, not joint coordinates. */
|
|
71
|
+
getPostureDirectives( { valence, arousal, dominance } ) {
|
|
72
|
+
|
|
73
|
+
let stance = 'neutral'
|
|
74
|
+
if ( arousal > 0.5 && valence < -0.3 && dominance < -0.2 ) stance = 'freeze'
|
|
75
|
+
else if ( valence < -0.2 ) stance = 'withdraw'
|
|
76
|
+
else if ( valence > 0.2 ) stance = 'approach'
|
|
77
|
+
|
|
78
|
+
return { stance, openness: clamp01( ( dominance + 1 ) / 2 ) } // low dominance -> closed/hunched posture target
|
|
79
|
+
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Action tendency (item 32) — real softmax over a small instinctive action set. */
|
|
83
|
+
getActionTendency( { valence, arousal, dominance } ) {
|
|
84
|
+
|
|
85
|
+
const scores = {
|
|
86
|
+
approach : valence * 2 + dominance,
|
|
87
|
+
withdraw : -valence * 1.5 - dominance * 0.5,
|
|
88
|
+
freeze : arousal * ( dominance < 0 ? 1.5 : 0.2 ) - Math.abs( valence ) * 0.3,
|
|
89
|
+
engage : dominance * 1.5 + arousal * 0.5,
|
|
90
|
+
}
|
|
91
|
+
return softmax( scores )
|
|
92
|
+
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
function sigmoid( x ) {
|
|
2
|
+
|
|
3
|
+
return 1 / ( 1 + Math.exp( -x ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Real LSTM-style gating (forget gate + output gate, both sigmoids) applied
|
|
9
|
+
* ONCE to produce an *expressed* vector distinct from the *internal* one —
|
|
10
|
+
* this is the actual psychological point of expressive suppression: the felt
|
|
11
|
+
* state doesn't change, only what gets shown does. `Totemheart.emotionSpace`
|
|
12
|
+
* is never touched by this; callers use the suppressed vector only for text
|
|
13
|
+
* generation / linguistic modulation. `suppressionDrive` (0..1) is supplied
|
|
14
|
+
* by the caller — this module has no opinion on when suppression should
|
|
15
|
+
* kick in, only how to apply it once told to. Real gating math; the mapping
|
|
16
|
+
* from "drive" to gate values is our own logistic curve, not a citation.
|
|
17
|
+
*/
|
|
18
|
+
export class ExpressiveSuppression {
|
|
19
|
+
|
|
20
|
+
computeGates( suppressionDrive ) {
|
|
21
|
+
|
|
22
|
+
const x = -4 * suppressionDrive + 2 // drive 0 -> gate≈0.88 (mostly open); drive 1 -> gate≈0.12 (mostly closed)
|
|
23
|
+
return { forgetGate: sigmoid( x ), outputGate: sigmoid( x ) }
|
|
24
|
+
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Returns the expressed (gated) vector — the internal vector passed in is read-only here. */
|
|
28
|
+
suppress( vector, suppressionDrive ) {
|
|
29
|
+
|
|
30
|
+
if ( suppressionDrive <= 0 ) return { ...vector }
|
|
31
|
+
|
|
32
|
+
const { forgetGate, outputGate } = this.computeGates( suppressionDrive )
|
|
33
|
+
const cellState = {
|
|
34
|
+
valence : forgetGate * vector.valence,
|
|
35
|
+
arousal : forgetGate * vector.arousal,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
valence : outputGate * Math.tanh( cellState.valence ),
|
|
40
|
+
arousal : outputGate * Math.tanh( cellState.arousal ),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs between interactions (call `totemheart.idle()` from a cron/timer, or
|
|
3
|
+
* manually). Re-samples a recent memory and lets it nudge the mood a little
|
|
4
|
+
* — a cheap analogue of rumination/dreaming — and lets the other ticking
|
|
5
|
+
* stats (homeostasis, fatigue) drain on their own schedule.
|
|
6
|
+
*/
|
|
7
|
+
function weightedPick( items, weightOf ) {
|
|
8
|
+
|
|
9
|
+
const weights = items.map( weightOf )
|
|
10
|
+
const total = weights.reduce( ( a, b ) => a + b, 0 )
|
|
11
|
+
if ( total <= 0 ) return items[ Math.floor( Math.random() * items.length ) ]
|
|
12
|
+
|
|
13
|
+
let roll = Math.random() * total
|
|
14
|
+
for ( let i = 0; i < items.length; i++ ) {
|
|
15
|
+
|
|
16
|
+
roll -= weights[ i ]
|
|
17
|
+
if ( roll <= 0 ) return items[ i ]
|
|
18
|
+
|
|
19
|
+
}
|
|
20
|
+
return items[ items.length - 1 ]
|
|
21
|
+
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class IdleProcessing {
|
|
25
|
+
|
|
26
|
+
async runIdleCycle( { episodicMemory, moodTracker, homeostasis, decisionFatigue, cortisolEngine = null }, dt = 1 ) {
|
|
27
|
+
|
|
28
|
+
// Unresolved (unhealed) memories resurface preferentially — the rumination
|
|
29
|
+
// isn't purely random, it keeps circling back to whatever hasn't been
|
|
30
|
+
// processed yet. Zeigarnik weighting: among the unresolved pool, the ones
|
|
31
|
+
// that have gone longest without resolution get picked more often, not a
|
|
32
|
+
// uniform draw — a thread interrupted an hour ago nags harder than one from
|
|
33
|
+
// thirty seconds ago.
|
|
34
|
+
const unresolved = episodicMemory.getUnresolvedMemories()
|
|
35
|
+
const pool = unresolved.length ? unresolved : episodicMemory.getInfluentialMemories( 10 )
|
|
36
|
+
|
|
37
|
+
if ( pool.length ) {
|
|
38
|
+
|
|
39
|
+
const memory = unresolved.length
|
|
40
|
+
? weightedPick( pool, m => episodicMemory.getZeigarnikPriority( m ) )
|
|
41
|
+
: pool[ Math.floor( Math.random() * pool.length ) ]
|
|
42
|
+
moodTracker.push( {
|
|
43
|
+
valence : ( memory.emotionalSignature?.valence ?? 0 ) * 0.2,
|
|
44
|
+
arousal : ( memory.emotionalSignature?.arousal ?? 0 ) * 0.2,
|
|
45
|
+
} )
|
|
46
|
+
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Ambient anxiety from too many open threads — real pressure, not per-memory.
|
|
50
|
+
if ( cortisolEngine && unresolved.length ) {
|
|
51
|
+
|
|
52
|
+
const pressure = episodicMemory.getZeigarnikPressure()
|
|
53
|
+
if ( pressure > 1.5 ) cortisolEngine.register( 0, true )
|
|
54
|
+
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
homeostasis.tick( dt * 0.5, { getSocialDecayRate: () => 0.004 } )
|
|
58
|
+
decisionFatigue.decay( dt * 2 )
|
|
59
|
+
|
|
60
|
+
return { sampledMemory: pool.length ? true : false, resurfacedUnresolved: unresolved.length > 0 }
|
|
61
|
+
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps the emotional vector to surface text properties. Returns metadata
|
|
3
|
+
* rather than silently rewriting the text, so a host app can choose which
|
|
4
|
+
* effects to actually apply (e.g. skip typo injection in a production UI).
|
|
5
|
+
*/
|
|
6
|
+
export class LinguisticModulation {
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `styleTarget` (optional, from StyleMimicry) is a real, attachment-weighted
|
|
10
|
+
* blend of this user's own average sentence length and the AI's base style.
|
|
11
|
+
* Only trims — never pads with invented content — and only when the AI is
|
|
12
|
+
* running noticeably longer than the target and Attachment made this user's
|
|
13
|
+
* style actually count for something.
|
|
14
|
+
*/
|
|
15
|
+
modulate( text, { vector, fatigueLevel = 0, styleTarget = null } ) {
|
|
16
|
+
|
|
17
|
+
const { valence, arousal } = vector
|
|
18
|
+
const styleTags = []
|
|
19
|
+
let delayMs = 0
|
|
20
|
+
let output = text
|
|
21
|
+
|
|
22
|
+
if ( arousal > 0.5 && valence < -0.2 ) {
|
|
23
|
+
|
|
24
|
+
styleTags.push( 'fragmented', 'fearful' )
|
|
25
|
+
output = output.replace( /\. /g, '... ' )
|
|
26
|
+
|
|
27
|
+
}
|
|
28
|
+
else if ( arousal < -0.2 && valence < -0.2 ) {
|
|
29
|
+
|
|
30
|
+
styleTags.push( 'passive', 'low-energy' )
|
|
31
|
+
delayMs = 1200 + Math.abs( valence ) * 1500
|
|
32
|
+
|
|
33
|
+
}
|
|
34
|
+
else if ( valence > 0.4 && arousal > 0.3 ) {
|
|
35
|
+
|
|
36
|
+
styleTags.push( 'upbeat' )
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if ( fatigueLevel > 0.7 ) styleTags.push( 'fatigued' )
|
|
41
|
+
|
|
42
|
+
if ( styleTarget && styleTarget.avgSentenceLength > 0 ) {
|
|
43
|
+
|
|
44
|
+
const sentences = output.split( /(?<=[.!?])\s+/ ).filter( s => s.trim().length > 0 )
|
|
45
|
+
const words = output.match( /\p{L}+/gu ) || []
|
|
46
|
+
const currentAvgSentenceLength = sentences.length ? words.length / sentences.length : words.length
|
|
47
|
+
|
|
48
|
+
if ( sentences.length > 1 && currentAvgSentenceLength > styleTarget.avgSentenceLength * 1.8 ) {
|
|
49
|
+
|
|
50
|
+
const keep = Math.max( 1, Math.round( sentences.length * ( styleTarget.avgSentenceLength / currentAvgSentenceLength ) ) )
|
|
51
|
+
output = sentences.slice( 0, keep ).join( ' ' )
|
|
52
|
+
styleTags.push( 'mimicry-trimmed' )
|
|
53
|
+
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { text: output, delayMs, styleTags }
|
|
59
|
+
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real logit-bias penalties — the actual mechanism OpenAI-compatible chat
|
|
3
|
+
* APIs expose as `logit_bias` (a map from token to an additive penalty
|
|
4
|
+
* subtracted from that token's logit before softmax, exactly the formula
|
|
5
|
+
* requested: P(x_i) = softmax((z_i − P_i)/T)). Two honest limits, stated
|
|
6
|
+
* plainly: (1) `logit_bias` needs numeric TOKEN IDs from the specific
|
|
7
|
+
* host model's own tokenizer — Totemheart has no access to that, so this
|
|
8
|
+
* produces a WORD-level bias map; converting words to that model's token
|
|
9
|
+
* IDs is the host's job, using their own tokenizer, before passing this to
|
|
10
|
+
* their API. (2) this only does anything for a host actually calling an
|
|
11
|
+
* API that supports `logit_bias` — it's inert metadata otherwise, same as
|
|
12
|
+
* `systemPrompt` is inert unless a host reads it.
|
|
13
|
+
*/
|
|
14
|
+
export const DEFAULT_CHARGED_WORDS = [
|
|
15
|
+
'idiota', 'estúpido', 'estupido', 'inútil', 'inutil', 'odio', 'basta',
|
|
16
|
+
'callate', 'cállate', 'nunca', 'jamás', 'jamas', 'terrible', 'horrible',
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
export class LogitBiasBuilder {
|
|
20
|
+
|
|
21
|
+
/** suppressionDrive 0..1 -> a real penalty map, scaled into the -100..100 range most logit_bias APIs use. */
|
|
22
|
+
build( suppressionDrive, chargedWords = DEFAULT_CHARGED_WORDS ) {
|
|
23
|
+
|
|
24
|
+
if ( suppressionDrive <= 0 ) return {}
|
|
25
|
+
|
|
26
|
+
const penalty = -Math.round( suppressionDrive * 100 )
|
|
27
|
+
return Object.fromEntries( chargedWords.map( word => [ word, penalty ] ) )
|
|
28
|
+
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real (small, discrete) Markov chain over 3 mood states {negative, neutral,
|
|
3
|
+
* positive} with an attractor well on `negative` when rumination is active:
|
|
4
|
+
* the transition matrix gives a high self-loop probability (p > 0.9) for
|
|
5
|
+
* staying in the negative state once there, versus a much lower self-loop
|
|
6
|
+
* for neutral/positive — a negative thought loop is "sticky" the way real
|
|
7
|
+
* rumination is, rather than a simple additive decay. Activated during
|
|
8
|
+
* `idle()` when the mood is already negative, giving IdleProcessing a
|
|
9
|
+
* genuine chance of *staying* stuck instead of drifting back to baseline.
|
|
10
|
+
*/
|
|
11
|
+
function pickState( probabilities ) {
|
|
12
|
+
|
|
13
|
+
const roll = Math.random()
|
|
14
|
+
let acc = 0
|
|
15
|
+
for ( const [ state, p ] of Object.entries( probabilities ) ) {
|
|
16
|
+
|
|
17
|
+
acc += p
|
|
18
|
+
if ( roll <= acc ) return state
|
|
19
|
+
|
|
20
|
+
}
|
|
21
|
+
return Object.keys( probabilities )[ 0 ]
|
|
22
|
+
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const TRANSITION_MATRIX = {
|
|
26
|
+
negative : { negative: 0.92, neutral: 0.07, positive: 0.01 },
|
|
27
|
+
neutral : { negative: 0.2, neutral: 0.6, positive: 0.2 },
|
|
28
|
+
positive : { negative: 0.05, neutral: 0.25, positive: 0.7 },
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class RuminationChain {
|
|
32
|
+
|
|
33
|
+
constructor() {
|
|
34
|
+
|
|
35
|
+
this.state = 'neutral'
|
|
36
|
+
this.negativeBias = 0
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Seed the chain's current state from a real mood valence reading. */
|
|
41
|
+
sync( moodValence ) {
|
|
42
|
+
|
|
43
|
+
this.state = moodValence < -0.2 ? 'negative' : moodValence > 0.2 ? 'positive' : 'neutral'
|
|
44
|
+
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Raises rumination proneness for a while — the "Echo" life-event area's real hook:
|
|
49
|
+
* an Echo-tagged event (e.g. discovering a partner's lie) doesn't just spike the mood
|
|
50
|
+
* once, it makes getting stuck in the negative attractor more likely for a while after.
|
|
51
|
+
* Reallocates real probability mass from {neutral, positive} into {negative} in every
|
|
52
|
+
* row of the transition matrix, proportional to `amount`, keeping each row a valid
|
|
53
|
+
* distribution (sums to 1) rather than just adding an unnormalized nudge.
|
|
54
|
+
*/
|
|
55
|
+
biasTowardNegative( amount ) {
|
|
56
|
+
|
|
57
|
+
this.negativeBias = Math.min( 1, this.negativeBias + Math.max( 0, amount ) )
|
|
58
|
+
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Exponential decay of the bias — same shape as CortisolEngine/Sensitization, own tuning. */
|
|
62
|
+
decayBias( dt, lambda = 0.05 ) {
|
|
63
|
+
|
|
64
|
+
this.negativeBias = Math.max( 0, this.negativeBias - lambda * dt )
|
|
65
|
+
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
#biasedRow( state ) {
|
|
69
|
+
|
|
70
|
+
const base = TRANSITION_MATRIX[ state ]
|
|
71
|
+
if ( this.negativeBias <= 0 ) return base
|
|
72
|
+
|
|
73
|
+
const negative = base.negative + this.negativeBias * ( 1 - base.negative )
|
|
74
|
+
const remainder = 1 - negative
|
|
75
|
+
const restSum = base.neutral + base.positive
|
|
76
|
+
const scale = restSum > 0 ? remainder / restSum : 0
|
|
77
|
+
|
|
78
|
+
return { negative, neutral: base.neutral * scale, positive: base.positive * scale }
|
|
79
|
+
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One Markov step. Returns the new state and a small valence/arousal nudge to apply if ruminating. */
|
|
83
|
+
step() {
|
|
84
|
+
|
|
85
|
+
this.state = pickState( this.#biasedRow( this.state ) )
|
|
86
|
+
|
|
87
|
+
if ( this.state === 'negative' ) return { state: this.state, spike: { valence: -0.05, arousal: 0.03 } }
|
|
88
|
+
if ( this.state === 'positive' ) return { state: this.state, spike: { valence: 0.03, arousal: 0.01 } }
|
|
89
|
+
return { state: this.state, spike: { valence: 0, arousal: 0 } }
|
|
90
|
+
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
function splitSentences( text ) {
|
|
2
|
+
|
|
3
|
+
return ( text || '' ).split( /(?<=[.!?])\s+/ ).filter( s => s.trim().length > 0 )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function splitWords( text ) {
|
|
8
|
+
|
|
9
|
+
return ( text || '' ).match( /\p{L}+/gu ) || []
|
|
10
|
+
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Real lexical statistics (average word length, average sentence length) —
|
|
15
|
+
* not a claim of matching syntax or vocabulary choice, just the two
|
|
16
|
+
* cheapest real, measurable style dimensions available without a parser.
|
|
17
|
+
* Own design, no citation.
|
|
18
|
+
*/
|
|
19
|
+
export class StyleMimicry {
|
|
20
|
+
|
|
21
|
+
constructor( { alpha = 0.7 } = {} ) {
|
|
22
|
+
|
|
23
|
+
this.alpha = alpha
|
|
24
|
+
this.history = new Map() // userId -> { avgWordLength, avgSentenceLength } EMA
|
|
25
|
+
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
measure( text ) {
|
|
29
|
+
|
|
30
|
+
const words = splitWords( text )
|
|
31
|
+
const sentences = splitSentences( text )
|
|
32
|
+
const avgWordLength = words.length ? words.reduce( ( s, w ) => s + w.length, 0 ) / words.length : 0
|
|
33
|
+
const avgSentenceLength = sentences.length ? words.length / sentences.length : words.length
|
|
34
|
+
|
|
35
|
+
return { avgWordLength, avgSentenceLength }
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
observe( userId, text ) {
|
|
40
|
+
|
|
41
|
+
const sample = this.measure( text )
|
|
42
|
+
const prior = this.history.get( userId )
|
|
43
|
+
|
|
44
|
+
this.history.set( userId, prior
|
|
45
|
+
? { avgWordLength: this.alpha * prior.avgWordLength + ( 1 - this.alpha ) * sample.avgWordLength, avgSentenceLength: this.alpha * prior.avgSentenceLength + ( 1 - this.alpha ) * sample.avgSentenceLength }
|
|
46
|
+
: sample,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
return sample
|
|
50
|
+
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
getUserStyle( userId ) {
|
|
54
|
+
|
|
55
|
+
return this.history.get( userId ) ?? { avgWordLength: 5, avgSentenceLength: 10 }
|
|
56
|
+
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Interpolates between the AI's own base style and this user's, weighted by real Attachment trust — a genuine chameleon effect, not applied indiscriminately to strangers. */
|
|
60
|
+
getBlendedTarget( userId, baseStyle, attachmentWeight ) {
|
|
61
|
+
|
|
62
|
+
const userStyle = this.getUserStyle( userId )
|
|
63
|
+
const w = Math.max( 0, Math.min( 1, attachmentWeight ) )
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
avgWordLength : w * userStyle.avgWordLength + ( 1 - w ) * baseStyle.avgWordLength,
|
|
67
|
+
avgSentenceLength : w * userStyle.avgSentenceLength + ( 1 - w ) * baseStyle.avgSentenceLength,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { EMOTION_COORDS, SURVIVAL_EMOTIONS } from '../core/EmotionSpace.js'
|
|
2
|
+
|
|
3
|
+
function intensity( vector, coords ) {
|
|
4
|
+
|
|
5
|
+
const d = Math.hypot( vector.valence - coords.valence, vector.arousal - coords.arousal )
|
|
6
|
+
return 1 / ( 1 + d )
|
|
7
|
+
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Pure interrupt module. When a survival emotion (fear/anger) crosses the
|
|
12
|
+
* threshold, this bypasses the normal pipeline entirely and forces an
|
|
13
|
+
* instinctive, non-analytical output.
|
|
14
|
+
*/
|
|
15
|
+
export class AmygdalaHijack {
|
|
16
|
+
|
|
17
|
+
check( emotionSpace, threshold = 0.95 ) {
|
|
18
|
+
|
|
19
|
+
for ( const emotion of SURVIVAL_EMOTIONS ) {
|
|
20
|
+
|
|
21
|
+
const level = intensity( emotionSpace.vector, EMOTION_COORDS[ emotion ] )
|
|
22
|
+
if ( level >= threshold ) return { active: true, emotion, intensity: level }
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
return { active: false }
|
|
26
|
+
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
emergencyOutput( { emotion } ) {
|
|
30
|
+
|
|
31
|
+
const outputs = {
|
|
32
|
+
fear : [ '...', 'No.', 'Necesito parar.' ],
|
|
33
|
+
anger : [ '¡Basta!', 'No.', '...' ],
|
|
34
|
+
}
|
|
35
|
+
const options = outputs[ emotion ] || [ '...' ]
|
|
36
|
+
return options[ Math.floor( Math.random() * options.length ) ]
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
function clamp01( v ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Each turn already produces several independent valence estimates that
|
|
9
|
+
* never get compared against each other before being fused into one number:
|
|
10
|
+
* the appraisal's own desirability, situational.joy minus situational.stress,
|
|
11
|
+
* a semantic-similarity hostility read (when an embedding backend is
|
|
12
|
+
* configured), and a detected life event's valence. Nothing today measures
|
|
13
|
+
* whether those signals actually agree — this does, with a real population
|
|
14
|
+
* variance over whichever of them are available this turn, no citation
|
|
15
|
+
* (this is a plain statistical spread, not a reproduction of any named
|
|
16
|
+
* confidence model). High variance across sources means the turn is
|
|
17
|
+
* genuinely ambiguous; that's real information about how confidently the
|
|
18
|
+
* projected emotion should be expressed, not noise to discard.
|
|
19
|
+
*/
|
|
20
|
+
export class AppraisalAgreement {
|
|
21
|
+
|
|
22
|
+
evaluate( estimates ) {
|
|
23
|
+
|
|
24
|
+
const values = estimates.filter( v => typeof v === 'number' && Number.isFinite( v ) )
|
|
25
|
+
if ( values.length < 2 ) return { agreement: 1, variance: 0, mean: values[ 0 ] ?? 0, n: values.length }
|
|
26
|
+
|
|
27
|
+
const mean = values.reduce( ( a, b ) => a + b, 0 ) / values.length
|
|
28
|
+
const variance = values.reduce( ( sum, v ) => sum + ( v - mean ) ** 2, 0 ) / values.length
|
|
29
|
+
|
|
30
|
+
// valence estimates live in [-1, 1], so max possible spread (all mass split
|
|
31
|
+
// between -1 and 1) bounds variance at 1 — sqrt(variance) is then already
|
|
32
|
+
// a 0..1 "disagreement" reading, and agreement is just its complement.
|
|
33
|
+
const agreement = clamp01( 1 - Math.sqrt( variance ) )
|
|
34
|
+
|
|
35
|
+
return { agreement, variance, mean, n: values.length }
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
}
|