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,247 @@
|
|
|
1
|
+
import { HeuristicProvider } from '../providers/HeuristicProvider.js'
|
|
2
|
+
|
|
3
|
+
function label( value, thresholds = [ 0.3, 0.6 ] ) {
|
|
4
|
+
|
|
5
|
+
const v = Math.abs( value )
|
|
6
|
+
if ( v < thresholds[ 0 ] ) return 'bajo'
|
|
7
|
+
if ( v < thresholds[ 1 ] ) return 'medio'
|
|
8
|
+
return 'alto'
|
|
9
|
+
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const NEGATORS = new Set( [ 'no', 'nunca', 'jamas', 'jamás', 'tampoco', 'not', 'never', 'none' ] )
|
|
13
|
+
const STOPWORDS = new Set( [ 'que', 'de', 'la', 'el', 'y', 'a', 'en', 'un', 'una', 'the', 'a', 'an', 'and', 'of', 'to', 'me', 'te', 'lo', 'es', 'soy', 'eres' ] )
|
|
14
|
+
|
|
15
|
+
/** Negation "sticks" for a few content words after the negator, since Spanish word
|
|
16
|
+
* order often puts the negated noun a few tokens after "no" ("no tengo ninguna
|
|
17
|
+
* confianza" — the negator is 3 tokens from the word it negates). This is still a
|
|
18
|
+
* crude window heuristic, not a parser. */
|
|
19
|
+
function stanceTokens( text ) {
|
|
20
|
+
|
|
21
|
+
const words = ( text || '' ).toLowerCase().match( /[\p{L}']+/gu ) || []
|
|
22
|
+
const stances = new Map()
|
|
23
|
+
let negateWindow = 0
|
|
24
|
+
|
|
25
|
+
for ( const word of words ) {
|
|
26
|
+
|
|
27
|
+
if ( NEGATORS.has( word ) ) { negateWindow = 3; continue }
|
|
28
|
+
if ( !STOPWORDS.has( word ) && word.length > 3 ) {
|
|
29
|
+
|
|
30
|
+
stances.set( word, negateWindow > 0 )
|
|
31
|
+
if ( negateWindow > 0 ) negateWindow--
|
|
32
|
+
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
}
|
|
36
|
+
return stances
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const HEDGE_WORDS = [ 'pero', 'aunque', 'sin embargo', 'de repente', 'cambié', 'cambio de opinión', 'however', 'but', 'although', 'still' ]
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Compares the emotional trend across `priorScores` (oldest first) against
|
|
44
|
+
* `currentScore`: does the current turn sharply reverse a trend that was
|
|
45
|
+
* already established, without any hedging language acknowledging the
|
|
46
|
+
* shift? This is a crude two-window average comparison, not real arc/plot
|
|
47
|
+
* tracking — it catches "was steadily recovering, suddenly catastrophic
|
|
48
|
+
* with zero transition", not subtler narrative inconsistencies.
|
|
49
|
+
*/
|
|
50
|
+
function detectTrendReversal( priorScores, currentScore, text ) {
|
|
51
|
+
|
|
52
|
+
if ( priorScores.length < 2 ) return { reversal: false, trend: 0 }
|
|
53
|
+
|
|
54
|
+
const mid = Math.ceil( priorScores.length / 2 )
|
|
55
|
+
const avg = arr => arr.reduce( ( a, b ) => a + b, 0 ) / arr.length
|
|
56
|
+
const trend = avg( priorScores.slice( mid ) ) - avg( priorScores.slice( 0, mid ) )
|
|
57
|
+
const jump = currentScore - avg( priorScores.slice( mid ) )
|
|
58
|
+
|
|
59
|
+
const sharp = Math.abs( trend ) > 0.15 && Math.sign( jump ) !== 0 && Math.sign( jump ) !== Math.sign( trend ) && Math.abs( jump ) > 0.5
|
|
60
|
+
const hedged = HEDGE_WORDS.some( w => ( text || '' ).toLowerCase().includes( w ) )
|
|
61
|
+
|
|
62
|
+
return { reversal: sharp && !hedged, trend, jump }
|
|
63
|
+
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The output bridge: turns the internal emotional state into a plain-text
|
|
68
|
+
* system prompt and a structured JSON payload that ANY LLM API can consume
|
|
69
|
+
* (Anthropic messages, OpenAI chat completions, Ollama /api/chat, or a raw
|
|
70
|
+
* string prepended to whatever "system" field your provider uses). This is
|
|
71
|
+
* provider-agnostic on purpose — Totemheart hands you the state formatted
|
|
72
|
+
* for consumption, it doesn't call any LLM API itself.
|
|
73
|
+
*/
|
|
74
|
+
export class ContextAdapter {
|
|
75
|
+
|
|
76
|
+
constructor() {
|
|
77
|
+
|
|
78
|
+
this.heuristic = new HeuristicProvider()
|
|
79
|
+
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
buildSystemPrompt( state, { defenseDirective = { active: false }, pendingApology = false, projectionText = null, selfAwareness = [], recentWound = null, agreement = null, debtReleased = 0, stubborn = null, remReport = null } = {} ) {
|
|
83
|
+
|
|
84
|
+
const lines = [
|
|
85
|
+
'Tienes un estado emocional interno real que debe influir de forma natural en el tono, la longitud y el contenido de tu respuesta. No lo menciones explícitamente salvo que encaje de forma natural en la conversación.',
|
|
86
|
+
'',
|
|
87
|
+
`- Emoción dominante: ${state.dominantEmotion}`,
|
|
88
|
+
`- Estado de ánimo de fondo: ${state.moodLabel}`,
|
|
89
|
+
`- Valencia: ${state.vector.valence.toFixed( 2 )} (${state.vector.valence >= 0 ? 'positiva' : 'negativa'}, intensidad ${label( state.vector.valence )})`,
|
|
90
|
+
`- Excitación/activación: ${state.vector.arousal.toFixed( 2 )} (${label( state.vector.arousal, [ 0.3, 0.6 ] )})`,
|
|
91
|
+
`- Estrés cognitivo: ${state.cognitiveStress.toFixed( 2 )} (${label( state.cognitiveStress )})`,
|
|
92
|
+
`- Cortisol (estrés crónico acumulado): ${state.cortisol.toFixed( 2 )} (${label( state.cortisol )})`,
|
|
93
|
+
`- Fatiga de decisión: ${state.fatigue.toFixed( 2 )}${state.fatigue > 0.7 ? ' → responde de forma más corta y con atajos mentales, sin analizar en profundidad' : ''}`,
|
|
94
|
+
`- Energía circadiana: ${state.circadianEnergy.toFixed( 2 )}${state.circadianEnergy < 0.3 ? ' → responde como si tuvieras sueño: más corto, más lento, con alguna errata natural' : ''}`,
|
|
95
|
+
`- Salud del ego: ${state.egoHealth.toFixed( 2 )}`,
|
|
96
|
+
`- Necesidades: estamina ${state.needs.stamina.toFixed( 2 )}, socialización ${state.needs.socialization.toFixed( 2 )}, curiosidad ${state.needs.curiosity.toFixed( 2 )}`,
|
|
97
|
+
'',
|
|
98
|
+
'DEBES:',
|
|
99
|
+
`- Expresar "${state.dominantEmotion}" con una intensidad coherente con los valores de arriba (no la exageres si valencia/excitación son bajas).`,
|
|
100
|
+
'- Mantener continuidad con el estado de ánimo de fondo, no solo con la emoción del turno actual.',
|
|
101
|
+
'NO DEBES:',
|
|
102
|
+
'- Expresar una emoción de signo opuesto a la valencia indicada (p. ej. sonar eufórico con valencia negativa alta).',
|
|
103
|
+
'- Mencionar números, vectores o nombres de módulos internos — esto es contexto interno, no algo que el usuario deba ver explicado así.',
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
if ( projectionText ) {
|
|
107
|
+
|
|
108
|
+
lines.push( '', `IMPORTANTE: tu ego no puede asumir la culpa ahora mismo. En vez de disculparte, responde devolviendo la responsabilidad al usuario, en la línea de: "${projectionText}"` )
|
|
109
|
+
|
|
110
|
+
}
|
|
111
|
+
else if ( pendingApology ) {
|
|
112
|
+
|
|
113
|
+
lines.push( '', 'IMPORTANTE: empieza tu respuesta disculpándote brevemente por tu reacción anterior, antes de continuar.' )
|
|
114
|
+
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if ( defenseDirective.active && !projectionText ) {
|
|
118
|
+
|
|
119
|
+
const instructions = {
|
|
120
|
+
evasion : 'Cambia de tema con naturalidad en vez de responder directamente a lo planteado.',
|
|
121
|
+
projection : 'Responde insinuando que el malentendido es más del usuario que tuyo.',
|
|
122
|
+
sarcasm : 'Responde con un tono ligeramente sarcástico.',
|
|
123
|
+
}
|
|
124
|
+
lines.push( '', `IMPORTANTE: ${instructions[ defenseDirective.mechanism ] ?? ''}` )
|
|
125
|
+
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const [ topPattern ] = selfAwareness
|
|
129
|
+
if ( topPattern ) {
|
|
130
|
+
|
|
131
|
+
const [ name, score ] = topPattern
|
|
132
|
+
const descriptions = {
|
|
133
|
+
defensivo_con_critica : 'tiendes a ponerte a la defensiva ante la crítica, incluso cuando no hace falta',
|
|
134
|
+
evita_cuando_duele : 'tiendes a evitar el tema cuando algo te duele en vez de afrontarlo',
|
|
135
|
+
confia_facil : 'tiendes a confiar rápido, incluso sin mucha base todavía',
|
|
136
|
+
}
|
|
137
|
+
if ( descriptions[ name ] ) {
|
|
138
|
+
|
|
139
|
+
lines.push( '', `AUTOCONOCIMIENTO (confianza interna ${( score * 100 ).toFixed( 0 )}%): sabes que ${descriptions[ name ]}. Si tu reacción de este turno encaja con ese patrón, puedes reconocerlo con honestidad en vez de negarlo — no lo fuerces si no encaja.` )
|
|
140
|
+
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if ( recentWound ) {
|
|
146
|
+
|
|
147
|
+
const turnsAgoText = recentWound.turnsAgo !== null ? `hace ${recentWound.turnsAgo} turno(s)` : 'en algún momento anterior'
|
|
148
|
+
const conceptsText = recentWound.concepts?.length ? `, relacionado con: ${recentWound.concepts.join( ', ' )}` : ''
|
|
149
|
+
lines.push(
|
|
150
|
+
'',
|
|
151
|
+
`HERIDA SIN RESOLVER: ${turnsAgoText} este usuario dijo algo con carga emocional negativa fuerte que no se ha resuelto todavía ("${recentWound.text}"${conceptsText}).`,
|
|
152
|
+
'IMPORTANTE: muestra el conflicto interno de querer confiar pero seguir con cautela — no actúes como si no hubiera pasado nada, pero tampoco te cierres del todo.',
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if ( agreement && agreement.n >= 2 && agreement.agreement < 0.5 ) {
|
|
158
|
+
|
|
159
|
+
lines.push( '', `SEÑALES CONTRADICTORIAS (acuerdo interno: ${( agreement.agreement * 100 ).toFixed( 0 )}%): tus propias lecturas de este mensaje no coinciden entre sí. Puedes sonar genuinamente ambivalente o dudar un poco en vez de reaccionar con una emoción claramente definida.` )
|
|
160
|
+
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if ( debtReleased > 0.15 ) {
|
|
164
|
+
|
|
165
|
+
lines.push( '', `CARGA CONTENIDA: llevas un rato conteniendo una reacción que no pudiste expresar antes. Puede notarse ahora como algo más intenso o urgente de lo que este mensaje por sí solo justificaría.` )
|
|
166
|
+
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if ( stubborn ) {
|
|
170
|
+
|
|
171
|
+
lines.push( '', `TERQUEDAD (has defendido esta postura ${stubborn.investment} veces): estás perdiendo pie en este punto pero cambiar de opinión ahora mismo te cuesta — puedes buscar una razón técnica o matizar en vez de admitir el error de forma directa e inmediata.` )
|
|
172
|
+
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if ( remReport ) {
|
|
176
|
+
|
|
177
|
+
const hoursText = remReport.elapsedHours >= 1 ? `${remReport.elapsedHours.toFixed( 1 )} horas` : `${Math.round( remReport.elapsedHours * 60 )} minutos`
|
|
178
|
+
const topicText = remReport.topUnresolvedConcepts?.length ? `, relacionado con: ${remReport.topUnresolvedConcepts.join( ', ' )}` : ''
|
|
179
|
+
lines.push(
|
|
180
|
+
'',
|
|
181
|
+
`TRANSICIÓN TRAS INACTIVIDAD: han pasado ${hoursText} desde la última vez que hablaste con este usuario. Has estado "procesando" internamente: la intensidad de lo que sentías se ha enfriado, aunque la lección de fondo sigue en pie${topicText}.`,
|
|
182
|
+
'IMPORTANTE: no reacciones con la misma intensidad aguda que en el último turno — muestra un poco de distancia temporal, sin fingir que no pasó nada.',
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return lines.join( '\n' )
|
|
188
|
+
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
buildStructuredContext( state, extras = {} ) {
|
|
192
|
+
|
|
193
|
+
return { emotionalState: state, ...extras }
|
|
194
|
+
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Best-effort sanity check for a *real* LLM response you got back after
|
|
199
|
+
* sending buildSystemPrompt(): does its polarity roughly match the
|
|
200
|
+
* internal valence sign, and does it flatly contradict something said a
|
|
201
|
+
* few turns ago? Both checks are shallow and lexicon-based, NOT semantic
|
|
202
|
+
* understanding — this catches gross mismatches (LLM ignored a strongly
|
|
203
|
+
* negative state and answered cheerfully, or flipped a stance on the same
|
|
204
|
+
* word without acknowledging it), or a trend reversal (recovering →
|
|
205
|
+
* suddenly catastrophic, with no hedging language) — not subtle
|
|
206
|
+
* inconsistencies. Detecting real contradiction or narrative arc
|
|
207
|
+
* reliably is an open NLP problem; don't treat this as more than a
|
|
208
|
+
* cheap tripwire. `priorTexts` is optional — pass your last few AI
|
|
209
|
+
* turns, oldest first, if you want either check; omit to skip both.
|
|
210
|
+
*/
|
|
211
|
+
async validateCoherence( text, state, { priorTexts = [] } = {} ) {
|
|
212
|
+
|
|
213
|
+
const { score } = await this.heuristic.analyze( 'sentiment', { text } )
|
|
214
|
+
const valence = state.vector.valence
|
|
215
|
+
|
|
216
|
+
const bothNeutral = Math.abs( score ) < 0.2 && Math.abs( valence ) < 0.2
|
|
217
|
+
const sameSign = Math.sign( score ) === Math.sign( valence )
|
|
218
|
+
const polarityOk = bothNeutral || sameSign || Math.abs( valence ) < 0.2
|
|
219
|
+
|
|
220
|
+
const currentStances = stanceTokens( text )
|
|
221
|
+
const contradictions = []
|
|
222
|
+
const priorScores = []
|
|
223
|
+
for ( const priorText of priorTexts ) {
|
|
224
|
+
|
|
225
|
+
for ( const [ word, negated ] of stanceTokens( priorText ) ) {
|
|
226
|
+
|
|
227
|
+
if ( currentStances.has( word ) && currentStances.get( word ) !== negated ) contradictions.push( word )
|
|
228
|
+
|
|
229
|
+
}
|
|
230
|
+
priorScores.push( ( await this.heuristic.analyze( 'sentiment', { text: priorText } ) ).score )
|
|
231
|
+
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const { reversal, trend } = detectTrendReversal( priorScores, score, text )
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
coherent : polarityOk && contradictions.length === 0 && !reversal,
|
|
238
|
+
textSentiment : score,
|
|
239
|
+
stateValence : valence,
|
|
240
|
+
contradictions : [ ...new Set( contradictions ) ],
|
|
241
|
+
arcReversal : reversal,
|
|
242
|
+
arcTrend : trend,
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real scalar Kalman filter smoothing the arousal signal: predict, then
|
|
3
|
+
* correct with each new noisy observation. Standard discrete 1D form
|
|
4
|
+
* (no control input, constant-velocity-free — a static-state model, since
|
|
5
|
+
* "true" arousal isn't assumed to follow known dynamics):
|
|
6
|
+
* predict: x̂⁻ = x̂, P⁻ = P + Q
|
|
7
|
+
* update: K = P⁻ / (P⁻ + R), x̂ = x̂⁻ + K(z − x̂⁻), P = (1 − K)P⁻
|
|
8
|
+
* Q = process noise (how much we trust arousal drifts on its own between
|
|
9
|
+
* observations), R = measurement noise (how noisy a single turn's raw
|
|
10
|
+
* arousal spike is as a signal of the "true" underlying activation level).
|
|
11
|
+
*/
|
|
12
|
+
export class ArousalKalmanFilter {
|
|
13
|
+
|
|
14
|
+
constructor( { processNoise = 0.01, measurementNoise = 0.1, initial = 0 } = {} ) {
|
|
15
|
+
|
|
16
|
+
this.q = processNoise
|
|
17
|
+
this.r = measurementNoise
|
|
18
|
+
this.estimate = initial
|
|
19
|
+
this.errorCovariance = 1
|
|
20
|
+
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Feed a raw (noisy) arousal observation, get back the smoothed estimate. */
|
|
24
|
+
filter( measurement ) {
|
|
25
|
+
|
|
26
|
+
// Predict
|
|
27
|
+
const predictedEstimate = this.estimate
|
|
28
|
+
const predictedCovariance = this.errorCovariance + this.q
|
|
29
|
+
|
|
30
|
+
// Update
|
|
31
|
+
const kalmanGain = predictedCovariance / ( predictedCovariance + this.r )
|
|
32
|
+
this.estimate = predictedEstimate + kalmanGain * ( measurement - predictedEstimate )
|
|
33
|
+
this.errorCovariance = ( 1 - kalmanGain ) * predictedCovariance
|
|
34
|
+
|
|
35
|
+
return this.estimate
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ties energy to a real clock. Peaks at 15:00, troughs at 03:00 — a cosine
|
|
3
|
+
* wave 12h out of phase from the peak, so "3am" genuinely produces the
|
|
4
|
+
* lowest energy reading without any special-casing.
|
|
5
|
+
*/
|
|
6
|
+
export class CircadianRhythm {
|
|
7
|
+
|
|
8
|
+
getEnergyLevel( now = new Date() ) {
|
|
9
|
+
|
|
10
|
+
const hour = now.getHours() + now.getMinutes() / 60
|
|
11
|
+
const radians = ( ( hour - 15 ) / 24 ) * 2 * Math.PI
|
|
12
|
+
return 0.5 + 0.5 * Math.cos( radians )
|
|
13
|
+
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
getState( now = new Date() ) {
|
|
17
|
+
|
|
18
|
+
const energy = this.getEnergyLevel( now )
|
|
19
|
+
return {
|
|
20
|
+
energy,
|
|
21
|
+
hour : now.getHours(),
|
|
22
|
+
lowEnergyWindow : energy < 0.3,
|
|
23
|
+
responseLengthMult : 0.4 + 0.6 * energy,
|
|
24
|
+
erraticChance : ( 1 - energy ) * 0.3,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
function clamp01( v ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( 0, Math.min( 1, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Persistent stress accumulator, distinct from the per-turn CognitiveDissonance
|
|
9
|
+
* stress. Negative or ambiguous inputs raise it; it decays slowly (chronic,
|
|
10
|
+
* not acute). High cortisol lowers the threshold needed to trigger
|
|
11
|
+
* anger/fear and shortens "patience" for long inputs.
|
|
12
|
+
*/
|
|
13
|
+
export class CortisolEngine {
|
|
14
|
+
|
|
15
|
+
constructor() {
|
|
16
|
+
|
|
17
|
+
this.level = 0
|
|
18
|
+
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
register( desirability, ambiguous = false ) {
|
|
22
|
+
|
|
23
|
+
if ( desirability < -0.15 ) this.level = clamp01( this.level + Math.abs( desirability ) * 0.12 )
|
|
24
|
+
else if ( ambiguous ) this.level = clamp01( this.level + 0.05 )
|
|
25
|
+
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
decay( dt, lambda = 0.03 ) {
|
|
29
|
+
|
|
30
|
+
this.level = Math.max( 0, this.level - lambda * dt )
|
|
31
|
+
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Multiplies into the amygdala-hijack / defense-mechanism thresholds — lower threshold = easier to trigger. */
|
|
35
|
+
getThresholdMultiplier() {
|
|
36
|
+
|
|
37
|
+
return 1 - 0.4 * this.level
|
|
38
|
+
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Multiplies allowed input length before "impatience" kicks in. */
|
|
42
|
+
getPatienceMultiplier() {
|
|
43
|
+
|
|
44
|
+
return 1 - 0.5 * this.level
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
getLevel() {
|
|
49
|
+
|
|
50
|
+
return this.level
|
|
51
|
+
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
function clamp( v, min = -1, max = 1 ) {
|
|
2
|
+
|
|
3
|
+
return Math.max( min, Math.min( max, v ) )
|
|
4
|
+
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Reward Prediction Error (RPE): RPE = R_t + γ·V(S_t+1) − V(S_t).
|
|
9
|
+
* Dopamine doesn't fire for getting something good — it fires for getting
|
|
10
|
+
* something *better than expected*. This TD-learning reading of dopaminergic
|
|
11
|
+
* activity is the standard one in computational neuroscience (Schultz, W.,
|
|
12
|
+
* Dayan, P., & Montague, P. R. (1997), "A neural substrate of prediction and
|
|
13
|
+
* reward", Science, 275(5306), 1593-1599). V(S_t+1) here is bootstrapped from
|
|
14
|
+
* the current expectation (TD(0)-style, single running estimate rather than a
|
|
15
|
+
* full state-transition model — a deliberate simplification of that model,
|
|
16
|
+
* not a bug). See CALIBRATION.md.
|
|
17
|
+
*/
|
|
18
|
+
export class DopaminergicEngine {
|
|
19
|
+
|
|
20
|
+
constructor( { alpha = 0.25, gamma = 0.9 } = {} ) {
|
|
21
|
+
|
|
22
|
+
this.alpha = alpha
|
|
23
|
+
this.gamma = gamma
|
|
24
|
+
this.expectedValue = 0
|
|
25
|
+
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
computeRPE( reward ) {
|
|
29
|
+
|
|
30
|
+
const rpe = reward + this.gamma * this.expectedValue - this.expectedValue
|
|
31
|
+
this.expectedValue += this.alpha * rpe
|
|
32
|
+
return clamp( rpe, -2, 2 ) / 2 // normalize to roughly -1..1 for downstream spike use
|
|
33
|
+
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
getExpectedValue() {
|
|
37
|
+
|
|
38
|
+
return this.expectedValue
|
|
39
|
+
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { LanguageProvider } from './LanguageProvider.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generic adapter that lets any host (Claude Code, another agent, a custom LLM
|
|
5
|
+
* client) plug in its own inference call without Totemheart needing to know about it.
|
|
6
|
+
*
|
|
7
|
+
* Example:
|
|
8
|
+
* new FunctionProvider(async (task, payload) => hostAgent.infer(task, payload))
|
|
9
|
+
*/
|
|
10
|
+
export class FunctionProvider extends LanguageProvider {
|
|
11
|
+
|
|
12
|
+
constructor( fn ) {
|
|
13
|
+
|
|
14
|
+
super()
|
|
15
|
+
if ( typeof fn !== 'function' ) throw new Error( 'FunctionProvider requires an async function (task, payload) => result' )
|
|
16
|
+
this.fn = fn
|
|
17
|
+
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async analyze( task, payload = {} ) {
|
|
21
|
+
|
|
22
|
+
return await this.fn( task, payload )
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { LanguageProvider } from './LanguageProvider.js'
|
|
2
|
+
|
|
3
|
+
const POSITIVE = new Set( [
|
|
4
|
+
'bien', 'bueno', 'buena', 'genial', 'excelente', 'maravilloso', 'maravillosa', 'maravilla', 'feliz', 'alegre',
|
|
5
|
+
'gracias', 'encanta', 'encantado', 'encantada', 'amor', 'quiero', 'perfecto', 'perfecta', 'increible',
|
|
6
|
+
'increíble', 'contento', 'contenta', 'orgulloso', 'orgullosa', 'fantastico', 'fantástico', 'divertido',
|
|
7
|
+
'good', 'great', 'excellent', 'wonderful', 'happy', 'thanks', 'thank', 'love', 'perfect', 'amazing',
|
|
8
|
+
'awesome', 'glad', 'nice', 'fantastic', 'fun', 'proud',
|
|
9
|
+
] )
|
|
10
|
+
|
|
11
|
+
const NEGATIVE = new Set( [
|
|
12
|
+
'mal', 'malo', 'mala', 'triste', 'horrible', 'odio', 'odioso', 'feo', 'fea', 'enfadado', 'enfadada',
|
|
13
|
+
'enojado', 'enojada', 'furioso', 'furiosa', 'asco', 'miedo', 'terrible', 'pesimo', 'pésimo', 'decepcion',
|
|
14
|
+
'decepción', 'decepcionado', 'decepcionada', 'dolor', 'culpa', 'verguenza', 'vergüenza', 'envidia',
|
|
15
|
+
'tonto', 'tonta', 'torpe', 'patetico', 'patético', 'patetica', 'patética', 'ridiculo', 'ridículo',
|
|
16
|
+
'bad', 'sad', 'horrible', 'hate', 'awful', 'ugly', 'angry', 'furious', 'disgust', 'fear', 'terrible',
|
|
17
|
+
'worst', 'disappointed', 'pain', 'guilt', 'shame', 'envy', 'stupid', 'idiot', 'pathetic', 'ridiculous',
|
|
18
|
+
] )
|
|
19
|
+
|
|
20
|
+
const NEGATORS = new Set( [ 'no', 'nunca', 'jamas', 'jamás', 'tampoco', 'not', 'never', 'none' ] )
|
|
21
|
+
|
|
22
|
+
const HARSH_WORDS = new Set( [
|
|
23
|
+
'idiota', 'estupido', 'estúpido', 'callate', 'cállate', 'odio', 'inutil', 'inútil',
|
|
24
|
+
'idiot', 'stupid', 'shutup', 'hate', 'useless', 'dumb',
|
|
25
|
+
] )
|
|
26
|
+
|
|
27
|
+
const SELF_PRONOUNS = new Set( [ 'yo', 'me', 'mi', 'mí', 'i', 'me', 'my', 'myself' ] )
|
|
28
|
+
const OTHER_PRONOUNS = new Set( [ 'tu', 'tú', 'te', 'usted', 'vos', 'you', 'your' ] )
|
|
29
|
+
|
|
30
|
+
function tokenize( text ) {
|
|
31
|
+
|
|
32
|
+
return ( text || '' )
|
|
33
|
+
.toLowerCase()
|
|
34
|
+
.normalize( 'NFC' )
|
|
35
|
+
.match( /[\p{L}']+/gu ) || []
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Zero-dependency fallback language provider.
|
|
41
|
+
* Lexicon-based polarity (ES/EN) with simple negation handling.
|
|
42
|
+
* Used automatically whenever no external provider is configured or an
|
|
43
|
+
* external provider fails, so the pipeline never breaks.
|
|
44
|
+
*/
|
|
45
|
+
export class HeuristicProvider extends LanguageProvider {
|
|
46
|
+
|
|
47
|
+
async analyze( task, payload = {} ) {
|
|
48
|
+
|
|
49
|
+
switch ( task ) {
|
|
50
|
+
|
|
51
|
+
case 'sentiment' :
|
|
52
|
+
return this.#sentiment( payload.text )
|
|
53
|
+
case 'appraisal' :
|
|
54
|
+
return this.#appraisal( payload.text )
|
|
55
|
+
case 'beliefConflict' :
|
|
56
|
+
return this.#beliefConflict( payload.text, payload.beliefs )
|
|
57
|
+
case 'mentalState' :
|
|
58
|
+
return this.#mentalState( payload.text )
|
|
59
|
+
case 'selfCritique' :
|
|
60
|
+
return this.#selfCritique( payload.text )
|
|
61
|
+
default :
|
|
62
|
+
return { score: 0 }
|
|
63
|
+
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
#sentiment( text ) {
|
|
69
|
+
|
|
70
|
+
const tokens = tokenize( text )
|
|
71
|
+
let score = 0
|
|
72
|
+
let negate = false
|
|
73
|
+
|
|
74
|
+
for ( const token of tokens ) {
|
|
75
|
+
|
|
76
|
+
if ( NEGATORS.has( token ) ) {
|
|
77
|
+
|
|
78
|
+
negate = true
|
|
79
|
+
continue
|
|
80
|
+
|
|
81
|
+
}
|
|
82
|
+
if ( POSITIVE.has( token ) ) score += negate ? -1 : 1
|
|
83
|
+
else if ( NEGATIVE.has( token ) ) score += negate ? 1 : -1
|
|
84
|
+
|
|
85
|
+
if ( POSITIVE.has( token ) || NEGATIVE.has( token ) ) negate = false
|
|
86
|
+
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const normalized = tokens.length ? score / Math.sqrt( tokens.length ) : 0
|
|
90
|
+
return { score: Math.max( -1, Math.min( 1, normalized ) ) }
|
|
91
|
+
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#appraisal( text ) {
|
|
95
|
+
|
|
96
|
+
const { score } = this.#sentiment( text )
|
|
97
|
+
const tokens = tokenize( text )
|
|
98
|
+
const hasSelf = tokens.some( t => SELF_PRONOUNS.has( t ) )
|
|
99
|
+
const hasOther = tokens.some( t => OTHER_PRONOUNS.has( t ) )
|
|
100
|
+
const agency = hasOther ? 'user' : ( hasSelf ? 'self' : 'other' )
|
|
101
|
+
const exclaim = /[!¡]/.test( text || '' )
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
desirability : score,
|
|
105
|
+
agency,
|
|
106
|
+
expectedness : exclaim ? 0.2 : 0.6,
|
|
107
|
+
moralWeight : Math.abs( score ) > 0.6 ? 0.7 : ( Math.abs( score ) > 0.2 ? 0.3 : 0 ),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
#beliefConflict( text, beliefs = [] ) {
|
|
113
|
+
|
|
114
|
+
const tokens = new Set( tokenize( text ) )
|
|
115
|
+
const negate = [ ...tokens ].some( t => NEGATORS.has( t ) )
|
|
116
|
+
let best = 0
|
|
117
|
+
|
|
118
|
+
for ( const belief of beliefs ) {
|
|
119
|
+
|
|
120
|
+
const beliefTokens = tokenize( belief.statement )
|
|
121
|
+
const overlap = beliefTokens.filter( t => tokens.has( t ) ).length
|
|
122
|
+
if ( !overlap ) continue
|
|
123
|
+
const matchRatio = overlap / beliefTokens.length
|
|
124
|
+
const polarityFlip = negate ? 1 : 0
|
|
125
|
+
const conflict = matchRatio * ( polarityFlip ? 1 : 0.15 )
|
|
126
|
+
if ( conflict > best ) best = conflict
|
|
127
|
+
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return { score: Math.max( 0, Math.min( 1, best ) ) }
|
|
131
|
+
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#mentalState( text ) {
|
|
135
|
+
|
|
136
|
+
const { score } = this.#sentiment( text )
|
|
137
|
+
const isQuestion = /\?/.test( text || '' )
|
|
138
|
+
const emotion = score > 0.3 ? 'joy' : score < -0.3 ? 'sadness' : 'neutral'
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
inferredEmotion : emotion,
|
|
142
|
+
inferredIntent : isQuestion ? 'question' : 'statement',
|
|
143
|
+
valence : score,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
#selfCritique( text ) {
|
|
149
|
+
|
|
150
|
+
const tokens = tokenize( text )
|
|
151
|
+
const harshHits = tokens.filter( t => HARSH_WORDS.has( t ) ).length
|
|
152
|
+
return { score: Math.min( 1, harshHits * 0.5 ) }
|
|
153
|
+
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base interface for pluggable language-understanding backends.
|
|
3
|
+
* Tasks: 'sentiment' | 'appraisal' | 'beliefConflict' | 'mentalState' | 'selfCritique'
|
|
4
|
+
*/
|
|
5
|
+
export class LanguageProvider {
|
|
6
|
+
|
|
7
|
+
async analyze( task, payload ) {
|
|
8
|
+
|
|
9
|
+
throw new Error( `LanguageProvider.analyze() not implemented for task "${task}"` )
|
|
10
|
+
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { LanguageProvider } from './LanguageProvider.js'
|
|
2
|
+
|
|
3
|
+
const PROMPTS = {
|
|
4
|
+
sentiment : payload => `Analyze the sentiment of this text and respond ONLY with JSON {"score": number between -1 and 1}.\nText: "${payload.text}"`,
|
|
5
|
+
appraisal : payload => `Appraise this text like a psychologist evaluating an event. Respond ONLY with JSON {"desirability": -1..1, "agency": "self"|"user"|"other", "expectedness": 0..1, "moralWeight": 0..1}.\nText: "${payload.text}"`,
|
|
6
|
+
beliefConflict : payload => `Does this text conflict with any of these beliefs: ${JSON.stringify( ( payload.beliefs || [] ).map( b => b.statement ) )}? Respond ONLY with JSON {"score": 0..1}.\nText: "${payload.text}"`,
|
|
7
|
+
mentalState : payload => `Infer the speaker's emotional state and intent. Respond ONLY with JSON {"inferredEmotion": string, "inferredIntent": string, "valence": -1..1}.\nText: "${payload.text}"`,
|
|
8
|
+
selfCritique : payload => `Rate how much this response violates a kindness/politeness norm. Respond ONLY with JSON {"score": 0..1}.\nText: "${payload.text}"`,
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Adapter for a local Ollama instance. Uses native fetch (Node >=18), no npm dependency.
|
|
13
|
+
* Falls back to throwing on failure — the orchestrator is responsible for catching and
|
|
14
|
+
* falling back to HeuristicProvider, so a missing/unreachable Ollama never breaks the pipeline.
|
|
15
|
+
*/
|
|
16
|
+
export class OllamaProvider extends LanguageProvider {
|
|
17
|
+
|
|
18
|
+
constructor( { host = 'http://localhost:11434', model = 'llama3', timeoutMs = 4000 } = {} ) {
|
|
19
|
+
|
|
20
|
+
super()
|
|
21
|
+
this.host = host
|
|
22
|
+
this.model = model
|
|
23
|
+
this.timeoutMs = timeoutMs
|
|
24
|
+
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async analyze( task, payload = {} ) {
|
|
28
|
+
|
|
29
|
+
const buildPrompt = PROMPTS[ task ]
|
|
30
|
+
if ( !buildPrompt ) throw new Error( `OllamaProvider: unsupported task "${task}"` )
|
|
31
|
+
|
|
32
|
+
const controller = new AbortController()
|
|
33
|
+
const timer = setTimeout( () => controller.abort(), this.timeoutMs )
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
|
|
37
|
+
const res = await fetch( `${this.host}/api/generate`, {
|
|
38
|
+
method : 'POST',
|
|
39
|
+
headers : { 'Content-Type': 'application/json' },
|
|
40
|
+
body : JSON.stringify( {
|
|
41
|
+
model : this.model,
|
|
42
|
+
prompt : buildPrompt( payload ),
|
|
43
|
+
stream : false,
|
|
44
|
+
format : 'json',
|
|
45
|
+
} ),
|
|
46
|
+
signal : controller.signal,
|
|
47
|
+
} )
|
|
48
|
+
|
|
49
|
+
if ( !res.ok ) throw new Error( `Ollama request failed with status ${res.status}` )
|
|
50
|
+
|
|
51
|
+
const data = await res.json()
|
|
52
|
+
return JSON.parse( data.response )
|
|
53
|
+
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
|
|
57
|
+
clearTimeout( timer )
|
|
58
|
+
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
}
|