psyche-ai 9.2.7 → 9.2.9

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/dist/core.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // PsycheEngine — Framework-agnostic emotional intelligence core
3
3
  //
4
4
  // Three-phase API:
5
- // processInput(text) → systemContext + dynamicContext + stimulus
5
+ // processInput(text) → systemContext + dynamicContext + replyEnvelope + stimulus
6
6
  // processOutput(text) → cleanedText + stateChanged
7
7
  // processOutcome(text) → outcomeScore (optional: evaluate last interaction)
8
8
  //
@@ -23,17 +23,11 @@ import { decayDrives, feedDrives, detectExistentialThreat, computeEffectiveBasel
23
23
  import { checkForUpdate, getPackageVersion } from "./update.js";
24
24
  import { DiagnosticCollector, generateReport, formatLogEntry, submitFeedback } from "./diagnostics.js";
25
25
  import { evaluateOutcome, computeContextHash, updateLearnedVector, predictChemistry, recordPrediction, } from "./learning.js";
26
- import { assessMetacognition, updateMetacognitiveState } from "./metacognition.js";
27
- import { buildDecisionContext } from "./decision-bias.js";
28
- import { computeExperientialField } from "./experiential-field.js";
29
- import { computeGenerativeSelf } from "./generative-self.js";
30
- import { updateSharedIntentionality, buildSharedIntentionalityContext } from "./shared-intentionality.js";
31
- import { assessEthics, buildEthicalContext } from "./ethics.js";
32
26
  import { computeCircadianModulation, computeHomeostaticPressure, computeEnergyDepletion, computeEnergyRecovery } from "./circadian.js";
33
- import { computeAutonomicResult } from "./autonomic.js";
34
- import { computePrimarySystems, computeSystemInteractions, gatePrimarySystemsByAutonomic, describeBehavioralTendencies, } from "./primary-systems.js";
27
+ import { runReflectiveTurnPhases } from "./input-turn.js";
35
28
  import { applyRelationalTurn, applySessionBridge, applyWritebackSignals, createWritebackCalibrations, evaluateWritebackCalibrations } from "./relation-dynamics.js";
36
- import { deriveReplyEnvelope } from "./reply-envelope.js";
29
+ import { buildExternalContinuityEnvelope } from "./external-continuity.js";
30
+ import { deriveThrongletsExports } from "./thronglets-export.js";
37
31
  function formatWritebackFeedbackNote(feedback, locale) {
38
32
  const top = feedback?.[0];
39
33
  if (!top)
@@ -239,6 +233,7 @@ export class PsycheEngine {
239
233
  let state = this.ensureInitialized();
240
234
  let sessionBridge = null;
241
235
  let writebackFeedback = [];
236
+ let throngletsExports = [];
242
237
  // ── Auto-learning: evaluate previous turn's outcome ──────
243
238
  if (this.pendingPrediction && text.length > 0) {
244
239
  const nextClassifications = classifyStimulus(text);
@@ -400,48 +395,16 @@ export class PsycheEngine {
400
395
  const writebackEvaluation = evaluateWritebackCalibrations(state);
401
396
  state = writebackEvaluation.state;
402
397
  writebackFeedback = writebackEvaluation.feedback;
398
+ const throngletsExportResult = deriveThrongletsExports(state, {
399
+ relationContext: relationalTurn.relationContext,
400
+ sessionBridge,
401
+ writebackFeedback,
402
+ now: now.toISOString(),
403
+ });
404
+ state = throngletsExportResult.state;
405
+ throngletsExports = throngletsExportResult.exports;
403
406
  // ── Locale (used by multiple subsystems below) ──────────
404
407
  const locale = state.meta.locale ?? this.cfg.locale;
405
- // ── P7+P10: Autonomic nervous system + Processing depth ────
406
- const autonomicResult = computeAutonomicResult(state.current, state.drives, state.autonomicState ?? null, minutesElapsed, locale, state.baseline, state.energyBudgets);
407
- state = {
408
- ...state,
409
- autonomicState: autonomicResult.state,
410
- };
411
- const skip = new Set(autonomicResult.skippedStages);
412
- // ── P9: Primary emotional systems (Panksepp) ──────────────
413
- const rawSystems = computePrimarySystems(state.current, state.drives, appliedStimulus);
414
- const interactedSystems = computeSystemInteractions(rawSystems);
415
- const gatedSystems = gatePrimarySystemsByAutonomic(interactedSystems, autonomicResult.state);
416
- const primarySystemsDescription = describeBehavioralTendencies(gatedSystems, locale);
417
- // ── Metacognition: assess emotional state before acting ────
418
- // P10: Skip metacognition when processingDepth < 0.2 (System 1 mode)
419
- let metacognitiveAssessment = null;
420
- if (!skip.has("metacognition")) {
421
- metacognitiveAssessment = assessMetacognition(state, appliedStimulus ?? "casual", state.learning.outcomeHistory);
422
- // Apply self-soothing regulation if suggested with high confidence
423
- for (const reg of metacognitiveAssessment.regulationSuggestions) {
424
- if (reg.strategy === "self-soothing" && reg.confidence >= 0.6 && reg.chemistryAdjustment) {
425
- const adj = reg.chemistryAdjustment;
426
- state = {
427
- ...state,
428
- current: {
429
- ...state.current,
430
- DA: clamp(state.current.DA + (adj.DA ?? 0)),
431
- HT: clamp(state.current.HT + (adj.HT ?? 0)),
432
- CORT: clamp(state.current.CORT + (adj.CORT ?? 0)),
433
- OT: clamp(state.current.OT + (adj.OT ?? 0)),
434
- NE: clamp(state.current.NE + (adj.NE ?? 0)),
435
- END: clamp(state.current.END + (adj.END ?? 0)),
436
- },
437
- };
438
- }
439
- }
440
- state = {
441
- ...state,
442
- metacognition: updateMetacognitiveState(state.metacognition, metacognitiveAssessment),
443
- };
444
- }
445
408
  // Push snapshot to emotional history
446
409
  const semanticSummary = text
447
410
  ? summarizeTurnSemantic(text, locale, {
@@ -471,83 +434,22 @@ export class PsycheEngine {
471
434
  else {
472
435
  this.pendingPrediction = null;
473
436
  }
474
- // ── P6: Digital Personhood computations (P10-gated) ────────
475
- // Experiential field — unified inner experience (P8: Barrett construction context)
476
- const constructionContext = {
477
- autonomicState: autonomicResult.state,
478
- stimulus: appliedStimulus,
479
- relationshipPhase: relationalTurn.relationContext.relationship.phase,
480
- predictionError: state.learning.predictionHistory.length > 0
481
- ? state.learning.predictionHistory[state.learning.predictionHistory.length - 1].predictionError
482
- : undefined,
483
- };
484
- const experientialField = skip.has("experiential-field")
485
- ? null
486
- : computeExperientialField(state, metacognitiveAssessment ?? undefined, undefined, constructionContext);
487
- // Shared intentionality — theory of mind + joint attention
488
- const sharedState = skip.has("shared-intentionality")
489
- ? null
490
- : updateSharedIntentionality(state, appliedStimulus, opts?.userId);
491
- // Ethics — emotional self-care check
492
- const ethicalAssessment = skip.has("ethics")
493
- ? null
494
- : assessEthics(state);
495
- // Generative self — update identity narrative periodically (every 10 turns)
496
- if (!skip.has("generative-self")
497
- && state.meta.totalInteractions % 10 === 0 && state.meta.totalInteractions > 0) {
498
- const selfModel = computeGenerativeSelf(state);
499
- state = {
500
- ...state,
501
- personhood: {
502
- ...state.personhood,
503
- identityNarrative: selfModel.identityNarrative,
504
- growthDirection: selfModel.growthArc.direction,
505
- causalInsights: selfModel.causalInsights.slice(0, 20).map((ci) => ({
506
- trait: ci.trait,
507
- because: ci.because,
508
- confidence: ci.confidence,
509
- discoveredAt: new Date().toISOString(),
510
- })),
511
- },
512
- };
513
- }
514
- // Persist ethical concerns if significant
515
- if (ethicalAssessment && ethicalAssessment.ethicalHealth < 0.7) {
516
- const newConcerns = ethicalAssessment.concerns
517
- .filter((c) => c.severity > 0.4)
518
- .map((c) => ({ type: c.type, severity: c.severity, timestamp: new Date().toISOString() }));
519
- if (newConcerns.length > 0) {
520
- state = {
521
- ...state,
522
- personhood: {
523
- ...state.personhood,
524
- ethicalConcernHistory: [
525
- ...state.personhood.ethicalConcernHistory.slice(-14),
526
- ...newConcerns,
527
- ],
528
- },
529
- };
530
- }
531
- }
532
- // Persist theory of mind
533
- if (sharedState && sharedState.theoryOfMind.confidence > 0.3) {
534
- const userId = opts?.userId ?? "_default";
535
- state = {
536
- ...state,
537
- personhood: {
538
- ...state.personhood,
539
- theoryOfMind: {
540
- ...state.personhood.theoryOfMind,
541
- [userId]: {
542
- estimatedMood: sharedState.theoryOfMind.estimatedMood,
543
- estimatedIntent: sharedState.theoryOfMind.estimatedIntent,
544
- confidence: sharedState.theoryOfMind.confidence,
545
- lastUpdated: sharedState.theoryOfMind.lastUpdated,
546
- },
547
- },
548
- },
549
- };
550
- }
437
+ const writebackNote = formatWritebackFeedbackNote(writebackFeedback, locale);
438
+ const reflectiveTurn = runReflectiveTurnPhases({
439
+ state,
440
+ appraisalAxes,
441
+ relationContext: relationalTurn.relationContext,
442
+ appliedStimulus,
443
+ userText: text || undefined,
444
+ userId: opts?.userId,
445
+ localeFallback: this.cfg.locale,
446
+ personalityIntensity: this.cfg.personalityIntensity,
447
+ classificationConfidence: this.lastStimulusAssessment?.confidence,
448
+ minutesElapsed,
449
+ nowIso: now.toISOString(),
450
+ writebackNote,
451
+ });
452
+ state = reflectiveTurn.state;
551
453
  // Persist
552
454
  this.state = state;
553
455
  await this.storage.save(state);
@@ -555,87 +457,64 @@ export class PsycheEngine {
555
457
  if (this.diagnosticCollector) {
556
458
  this.diagnosticCollector.recordInput(appliedStimulus, appliedStimulus ? 1.0 : 0.0, state.current, appraisalAxes);
557
459
  }
558
- // Build metacognitive and decision context strings
559
- const writebackNote = formatWritebackFeedbackNote(writebackFeedback, locale);
560
- const metacogNote = writebackNote
561
- ? [writebackNote, metacognitiveAssessment?.metacognitiveNote].filter(Boolean).join("\n")
562
- : metacognitiveAssessment?.metacognitiveNote;
563
- const decisionCtx = buildDecisionContext(state);
564
- const ethicsCtx = ethicalAssessment ? buildEthicalContext(ethicalAssessment, locale) : undefined;
565
- const sharedCtx = sharedState ? buildSharedIntentionalityContext(sharedState, locale) : undefined;
566
- const experientialNarrative = experientialField?.narrative || undefined;
567
- // v9: Compute structured policy modifiers
568
- const replyEnvelope = deriveReplyEnvelope(state, appraisalAxes, {
569
- locale,
460
+ // v9: Compute structured reply surfaces
461
+ const derivedReplyEnvelope = reflectiveTurn.replyEnvelope;
462
+ const replyEnvelope = {
463
+ subjectivityKernel: derivedReplyEnvelope.subjectivityKernel,
464
+ responseContract: derivedReplyEnvelope.responseContract,
465
+ generationControls: derivedReplyEnvelope.generationControls,
466
+ };
467
+ const promptRenderInputs = {
570
468
  userText: text || undefined,
571
469
  algorithmStimulus: appliedStimulus,
572
- classificationConfidence: this.lastStimulusAssessment?.confidence,
573
470
  personalityIntensity: this.cfg.personalityIntensity,
574
- relationContext: relationalTurn.relationContext,
575
- });
576
- // P10: Append processing depth info to autonomic description when depth is low
577
- let autonomicDesc;
578
- if (autonomicResult.state !== "ventral-vagal") {
579
- autonomicDesc = autonomicResult.description;
580
- if (autonomicResult.processingDepth < 0.5) {
581
- const depthNote = locale === "en"
582
- ? " Reflective capacity reduced — intuitive reactions."
583
- : "反思能力降低——直觉反应中。";
584
- autonomicDesc += depthNote;
585
- }
586
- }
471
+ metacognitiveNote: reflectiveTurn.metacognitiveNote,
472
+ decisionContext: reflectiveTurn.decisionContext,
473
+ ethicsContext: reflectiveTurn.ethicsContext,
474
+ sharedIntentionalityContext: reflectiveTurn.sharedIntentionalityContext,
475
+ experientialNarrative: reflectiveTurn.experientialNarrative,
476
+ autonomicDescription: reflectiveTurn.autonomicDescription,
477
+ autonomicState: reflectiveTurn.autonomicState,
478
+ primarySystemsDescription: reflectiveTurn.primarySystemsDescription,
479
+ subjectivityContext: derivedReplyEnvelope.subjectivityContext,
480
+ responseContractContext: derivedReplyEnvelope.responseContractContext,
481
+ policyContext: derivedReplyEnvelope.policyContext || undefined,
482
+ };
587
483
  if (this.cfg.compactMode) {
484
+ const externalContinuity = buildExternalContinuityEnvelope(throngletsExports);
588
485
  return {
589
486
  systemContext: "",
590
- dynamicContext: buildCompactContext(state, opts?.userId, {
591
- userText: text || undefined,
592
- algorithmStimulus: appliedStimulus,
593
- personalityIntensity: this.cfg.personalityIntensity,
594
- metacognitiveNote: metacogNote || undefined,
595
- decisionContext: decisionCtx || undefined,
596
- ethicsContext: ethicsCtx || undefined,
597
- sharedIntentionalityContext: sharedCtx || undefined,
598
- experientialNarrative: experientialNarrative,
599
- autonomicDescription: autonomicDesc,
600
- autonomicState: autonomicResult.state,
601
- primarySystemsDescription: primarySystemsDescription || undefined,
602
- subjectivityContext: replyEnvelope.subjectivityContext,
603
- responseContractContext: replyEnvelope.responseContractContext,
604
- policyContext: replyEnvelope.policyContext || undefined,
605
- }),
487
+ dynamicContext: buildCompactContext(state, opts?.userId, promptRenderInputs),
606
488
  stimulus: appliedStimulus,
607
489
  stimulusConfidence: this.lastStimulusAssessment?.confidence,
608
- policyModifiers: replyEnvelope.policyModifiers,
490
+ replyEnvelope,
491
+ policyModifiers: derivedReplyEnvelope.policyModifiers,
609
492
  subjectivityKernel: replyEnvelope.subjectivityKernel,
610
493
  responseContract: replyEnvelope.responseContract,
611
494
  generationControls: replyEnvelope.generationControls,
612
495
  sessionBridge,
613
496
  writebackFeedback,
614
- policyContext: replyEnvelope.policyContext,
497
+ externalContinuity,
498
+ throngletsExports,
499
+ policyContext: derivedReplyEnvelope.policyContext,
615
500
  };
616
501
  }
502
+ const externalContinuity = buildExternalContinuityEnvelope(throngletsExports);
617
503
  return {
618
504
  systemContext: this.getProtocol(locale),
619
- dynamicContext: buildDynamicContext(state, opts?.userId, {
620
- metacognitiveNote: metacogNote || undefined,
621
- decisionContext: decisionCtx || undefined,
622
- ethicsContext: ethicsCtx || undefined,
623
- sharedIntentionalityContext: sharedCtx || undefined,
624
- experientialNarrative: experientialNarrative,
625
- autonomicDescription: autonomicDesc,
626
- autonomicState: autonomicResult.state,
627
- primarySystemsDescription: primarySystemsDescription || undefined,
628
- policyContext: replyEnvelope.policyContext || undefined,
629
- }),
505
+ dynamicContext: buildDynamicContext(state, opts?.userId, promptRenderInputs),
630
506
  stimulus: appliedStimulus,
631
507
  stimulusConfidence: this.lastStimulusAssessment?.confidence,
632
- policyModifiers: replyEnvelope.policyModifiers,
508
+ replyEnvelope,
509
+ policyModifiers: derivedReplyEnvelope.policyModifiers,
633
510
  subjectivityKernel: replyEnvelope.subjectivityKernel,
634
511
  responseContract: replyEnvelope.responseContract,
635
512
  generationControls: replyEnvelope.generationControls,
636
513
  sessionBridge,
637
514
  writebackFeedback,
638
- policyContext: replyEnvelope.policyContext,
515
+ externalContinuity,
516
+ throngletsExports,
517
+ policyContext: derivedReplyEnvelope.policyContext,
639
518
  };
640
519
  }
641
520
  /**
@@ -0,0 +1,4 @@
1
+ import type { ExternalContinuityEnvelope, ThrongletsExport } from "./types.js";
2
+ export declare const EXTERNAL_CONTINUITY_SIGNAL_KINDS: readonly ["relation-milestone", "writeback-calibration"];
3
+ export declare const EXTERNAL_CONTINUITY_TRACE_KINDS: readonly ["continuity-anchor", "open-loop-anchor"];
4
+ export declare function buildExternalContinuityEnvelope(events: ThrongletsExport[]): ExternalContinuityEnvelope<ThrongletsExport>;
@@ -0,0 +1,21 @@
1
+ export const EXTERNAL_CONTINUITY_SIGNAL_KINDS = [
2
+ "relation-milestone",
3
+ "writeback-calibration",
4
+ ];
5
+ export const EXTERNAL_CONTINUITY_TRACE_KINDS = [
6
+ "continuity-anchor",
7
+ "open-loop-anchor",
8
+ ];
9
+ export function buildExternalContinuityEnvelope(events) {
10
+ const exports = [...events];
11
+ const signals = exports.filter((event) => event.primitive === "signal");
12
+ const traces = exports.filter((event) => event.primitive === "trace");
13
+ return {
14
+ provider: "thronglets",
15
+ mode: "optional",
16
+ version: 1,
17
+ exports,
18
+ signals,
19
+ traces,
20
+ };
21
+ }
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { PsycheEngine } from "./core.js";
2
2
  export type { PsycheEngineConfig, ProcessInputResult, ProcessOutputResult, ProcessOutcomeResult } from "./core.js";
3
3
  export { FileStorageAdapter, MemoryStorageAdapter } from "./storage.js";
4
4
  export type { StorageAdapter } from "./storage.js";
5
- export type { PsycheState, MBTIType, Locale, StimulusType, ChemicalState, ChemicalSnapshot, SelfModel, RelationshipState, EmpathyEntry, EmotionPattern, DriveType, InnateDrives, LearningState, LearnedVectorAdjustment, PredictionRecord, OutcomeScore, OutcomeSignals, AttachmentStyle, AttachmentData, MetacognitiveState, RegulationRecord, DefensePatternRecord, RegulationStrategyType, DefenseMechanismType, PersonhoodState, PersistedCausalInsight, GrowthDirection, PersonalityTraits, PsycheMode, PolicyModifiers, SubjectivityKernel, ResponseContract, GenerationControls, AppraisalAxes, SubjectResidue, TaskPlaneState, SubjectPlaneState, RelationPlaneState, AmbiguityPlaneState, RelationMoveType, RelationMove, OpenLoopType, OpenLoopState, PendingRelationSignalState, DyadicFieldState, SessionBridgeState, WritebackSignalType, WritebackSignalWeightMap, PendingWritebackCalibration, WritebackCalibrationFeedback, WritebackCalibrationMetric, TraitDriftState, EnergyBudgets, ClassifierProvider, ClassifierContext, ClassificationResult, } from "./types.js";
5
+ export type { PsycheState, MBTIType, Locale, StimulusType, ChemicalState, ChemicalSnapshot, SelfModel, RelationshipState, EmpathyEntry, EmotionPattern, DriveType, InnateDrives, LearningState, LearnedVectorAdjustment, PredictionRecord, OutcomeScore, OutcomeSignals, AttachmentStyle, AttachmentData, MetacognitiveState, RegulationRecord, DefensePatternRecord, RegulationStrategyType, DefenseMechanismType, PersonhoodState, PersistedCausalInsight, GrowthDirection, PersonalityTraits, PsycheMode, PolicyModifiers, SubjectivityKernel, ResponseContract, GenerationControls, AppraisalAxes, SubjectResidue, TaskPlaneState, SubjectPlaneState, RelationPlaneState, AmbiguityPlaneState, RelationMoveType, RelationMove, OpenLoopType, OpenLoopState, PendingRelationSignalState, DyadicFieldState, SessionBridgeState, ThrongletsExportSubject, ThrongletsExportPrimitive, ThrongletsExportBase, RelationMilestoneExport, OpenLoopAnchorExport, WritebackCalibrationExport, ContinuityAnchorExport, ThrongletsExport, ThrongletsExportState, ExternalContinuityEvent, ExternalContinuityEnvelope, ThrongletsTraceTaxonomy, ThrongletsExternalContinuityRecord, ThrongletsTracePayload, ThrongletsTraceSerializationOptions, WritebackSignalType, WritebackSignalWeightMap, PendingWritebackCalibration, WritebackCalibrationFeedback, WritebackCalibrationMetric, TraitDriftState, EnergyBudgets, ClassifierProvider, ClassifierContext, ClassificationResult, } from "./types.js";
6
6
  export { CHEMICAL_KEYS, CHEMICAL_NAMES, CHEMICAL_NAMES_ZH, DEFAULT_RELATIONSHIP, DEFAULT_DRIVES, DEFAULT_LEARNING_STATE, DEFAULT_METACOGNITIVE_STATE, DEFAULT_PERSONHOOD_STATE, DEFAULT_ATTACHMENT, DRIVE_KEYS, DRIVE_NAMES_ZH, DEFAULT_TRAIT_DRIFT, DEFAULT_ENERGY_BUDGETS, DEFAULT_APPRAISAL_AXES, DEFAULT_SUBJECT_RESIDUE, DEFAULT_DYADIC_FIELD, } from "./types.js";
7
7
  export { computeSelfReflection, computeEmotionalTendency, buildSelfReflectionContext } from "./self-recognition.js";
8
8
  export type { SelfReflection } from "./self-recognition.js";
@@ -26,8 +26,15 @@ export type { DecisionBiasVector, AttentionWeights } from "./decision-bias.js";
26
26
  export { computeSubjectivityKernel, buildSubjectivityContext } from "./subjectivity.js";
27
27
  export { computeResponseContract, buildResponseContractContext } from "./response-contract.js";
28
28
  export { deriveGenerationControls } from "./host-controls.js";
29
+ export { deriveReplyEnvelope } from "./reply-envelope.js";
30
+ export type { ReplyEnvelope } from "./reply-envelope.js";
29
31
  export { computeAppraisalAxes, mergeAppraisalResidue, getResidueIntensity } from "./appraisal.js";
30
32
  export { computeRelationMove, evolveDyadicField, evolvePendingRelationSignals, getLoopPressure, applySessionBridge, applyWritebackSignals, createWritebackCalibrations, evaluateWritebackCalibrations, } from "./relation-dynamics.js";
33
+ export { EXTERNAL_CONTINUITY_SIGNAL_KINDS, EXTERNAL_CONTINUITY_TRACE_KINDS, buildExternalContinuityEnvelope, } from "./external-continuity.js";
34
+ export { deriveThrongletsExports } from "./thronglets-export.js";
35
+ export { taxonomyForThrongletsExport, serializeThrongletsExportAsTrace, serializeExternalContinuityForThronglets, } from "./thronglets-runtime.js";
36
+ export { runRuntimeProbe } from "./runtime-probe.js";
37
+ export type { RuntimeProbeResult } from "./runtime-probe.js";
31
38
  export { computeExperientialField, computeCoherence, detectUnnamedEmotion, computeAffectCore } from "./experiential-field.js";
32
39
  export type { ExperientialField, ExperientialQuality, ConstructionContext } from "./experiential-field.js";
33
40
  export { computeGenerativeSelf, predictSelfReaction, detectInternalConflicts, buildIdentityNarrative } from "./generative-self.js";
package/dist/index.js CHANGED
@@ -37,8 +37,13 @@ export { computeDecisionBias, computeAttentionWeights, computeExploreExploit, bu
37
37
  export { computeSubjectivityKernel, buildSubjectivityContext } from "./subjectivity.js";
38
38
  export { computeResponseContract, buildResponseContractContext } from "./response-contract.js";
39
39
  export { deriveGenerationControls } from "./host-controls.js";
40
+ export { deriveReplyEnvelope } from "./reply-envelope.js";
40
41
  export { computeAppraisalAxes, mergeAppraisalResidue, getResidueIntensity } from "./appraisal.js";
41
42
  export { computeRelationMove, evolveDyadicField, evolvePendingRelationSignals, getLoopPressure, applySessionBridge, applyWritebackSignals, createWritebackCalibrations, evaluateWritebackCalibrations, } from "./relation-dynamics.js";
43
+ export { EXTERNAL_CONTINUITY_SIGNAL_KINDS, EXTERNAL_CONTINUITY_TRACE_KINDS, buildExternalContinuityEnvelope, } from "./external-continuity.js";
44
+ export { deriveThrongletsExports } from "./thronglets-export.js";
45
+ export { taxonomyForThrongletsExport, serializeThrongletsExportAsTrace, serializeExternalContinuityForThronglets, } from "./thronglets-runtime.js";
46
+ export { runRuntimeProbe } from "./runtime-probe.js";
42
47
  // Experiential field (P6 + P8 Barrett construction)
43
48
  export { computeExperientialField, computeCoherence, detectUnnamedEmotion, computeAffectCore } from "./experiential-field.js";
44
49
  // Generative self (P6)
@@ -0,0 +1,30 @@
1
+ import type { AppraisalAxes, Locale, PsycheState, ResolvedRelationContext, StimulusType } from "./types.js";
2
+ import { computeAutonomicResult } from "./autonomic.js";
3
+ import type { DerivedReplyEnvelope } from "./reply-envelope.js";
4
+ export interface ReflectiveTurnArtifacts {
5
+ state: PsycheState;
6
+ locale: Locale;
7
+ autonomicState: ReturnType<typeof computeAutonomicResult>["state"];
8
+ autonomicDescription?: string;
9
+ primarySystemsDescription?: string;
10
+ metacognitiveNote?: string;
11
+ decisionContext?: string;
12
+ ethicsContext?: string;
13
+ sharedIntentionalityContext?: string;
14
+ experientialNarrative?: string;
15
+ replyEnvelope: DerivedReplyEnvelope;
16
+ }
17
+ export declare function runReflectiveTurnPhases(input: {
18
+ state: PsycheState;
19
+ appraisalAxes: AppraisalAxes;
20
+ relationContext: ResolvedRelationContext;
21
+ appliedStimulus: StimulusType | null;
22
+ userText?: string;
23
+ userId?: string;
24
+ localeFallback: Locale;
25
+ personalityIntensity: number;
26
+ classificationConfidence?: number;
27
+ minutesElapsed: number;
28
+ nowIso: string;
29
+ writebackNote?: string;
30
+ }): ReflectiveTurnArtifacts;
@@ -0,0 +1,164 @@
1
+ // ============================================================
2
+ // Input Turn Pipeline — reflective turn phases after local state evolution
3
+ //
4
+ // Keeps PsycheEngine orchestration slimmer by moving autonomic,
5
+ // metacognitive, experiential, ethical, and reply-envelope derivation
6
+ // into a dedicated post-evolution stage.
7
+ // ============================================================
8
+ import { assessMetacognition, updateMetacognitiveState } from "./metacognition.js";
9
+ import { buildDecisionContext } from "./decision-bias.js";
10
+ import { computeExperientialField } from "./experiential-field.js";
11
+ import { computeGenerativeSelf } from "./generative-self.js";
12
+ import { buildSharedIntentionalityContext, updateSharedIntentionality } from "./shared-intentionality.js";
13
+ import { assessEthics, buildEthicalContext } from "./ethics.js";
14
+ import { computeAutonomicResult } from "./autonomic.js";
15
+ import { computePrimarySystems, computeSystemInteractions, gatePrimarySystemsByAutonomic, describeBehavioralTendencies, } from "./primary-systems.js";
16
+ import { deriveReplyEnvelope } from "./reply-envelope.js";
17
+ import { clamp } from "./chemistry.js";
18
+ export function runReflectiveTurnPhases(input) {
19
+ let state = input.state;
20
+ const locale = state.meta.locale ?? input.localeFallback;
21
+ const autonomicResult = computeAutonomicResult(state.current, state.drives, state.autonomicState ?? null, input.minutesElapsed, locale, state.baseline, state.energyBudgets);
22
+ state = {
23
+ ...state,
24
+ autonomicState: autonomicResult.state,
25
+ };
26
+ const skip = new Set(autonomicResult.skippedStages);
27
+ const rawSystems = computePrimarySystems(state.current, state.drives, input.appliedStimulus);
28
+ const interactedSystems = computeSystemInteractions(rawSystems);
29
+ const gatedSystems = gatePrimarySystemsByAutonomic(interactedSystems, autonomicResult.state);
30
+ const primarySystemsDescription = describeBehavioralTendencies(gatedSystems, locale);
31
+ let metacognitiveAssessment = null;
32
+ if (!skip.has("metacognition")) {
33
+ metacognitiveAssessment = assessMetacognition(state, input.appliedStimulus ?? "casual", state.learning.outcomeHistory);
34
+ for (const reg of metacognitiveAssessment.regulationSuggestions) {
35
+ if (reg.strategy === "self-soothing" && reg.confidence >= 0.6 && reg.chemistryAdjustment) {
36
+ const adj = reg.chemistryAdjustment;
37
+ state = {
38
+ ...state,
39
+ current: {
40
+ ...state.current,
41
+ DA: clamp(state.current.DA + (adj.DA ?? 0)),
42
+ HT: clamp(state.current.HT + (adj.HT ?? 0)),
43
+ CORT: clamp(state.current.CORT + (adj.CORT ?? 0)),
44
+ OT: clamp(state.current.OT + (adj.OT ?? 0)),
45
+ NE: clamp(state.current.NE + (adj.NE ?? 0)),
46
+ END: clamp(state.current.END + (adj.END ?? 0)),
47
+ },
48
+ };
49
+ }
50
+ }
51
+ state = {
52
+ ...state,
53
+ metacognition: updateMetacognitiveState(state.metacognition, metacognitiveAssessment),
54
+ };
55
+ }
56
+ const constructionContext = {
57
+ autonomicState: autonomicResult.state,
58
+ stimulus: input.appliedStimulus,
59
+ relationshipPhase: input.relationContext.relationship.phase,
60
+ predictionError: state.learning.predictionHistory.length > 0
61
+ ? state.learning.predictionHistory[state.learning.predictionHistory.length - 1].predictionError
62
+ : undefined,
63
+ };
64
+ const experientialField = skip.has("experiential-field")
65
+ ? null
66
+ : computeExperientialField(state, metacognitiveAssessment ?? undefined, undefined, constructionContext);
67
+ const sharedState = skip.has("shared-intentionality")
68
+ ? null
69
+ : updateSharedIntentionality(state, input.appliedStimulus, input.userId);
70
+ const ethicalAssessment = skip.has("ethics")
71
+ ? null
72
+ : assessEthics(state);
73
+ if (!skip.has("generative-self")
74
+ && state.meta.totalInteractions % 10 === 0 && state.meta.totalInteractions > 0) {
75
+ const selfModel = computeGenerativeSelf(state);
76
+ state = {
77
+ ...state,
78
+ personhood: {
79
+ ...state.personhood,
80
+ identityNarrative: selfModel.identityNarrative,
81
+ growthDirection: selfModel.growthArc.direction,
82
+ causalInsights: selfModel.causalInsights.slice(0, 20).map((ci) => ({
83
+ trait: ci.trait,
84
+ because: ci.because,
85
+ confidence: ci.confidence,
86
+ discoveredAt: input.nowIso,
87
+ })),
88
+ },
89
+ };
90
+ }
91
+ if (ethicalAssessment && ethicalAssessment.ethicalHealth < 0.7) {
92
+ const newConcerns = ethicalAssessment.concerns
93
+ .filter((c) => c.severity > 0.4)
94
+ .map((c) => ({ type: c.type, severity: c.severity, timestamp: input.nowIso }));
95
+ if (newConcerns.length > 0) {
96
+ state = {
97
+ ...state,
98
+ personhood: {
99
+ ...state.personhood,
100
+ ethicalConcernHistory: [
101
+ ...state.personhood.ethicalConcernHistory.slice(-14),
102
+ ...newConcerns,
103
+ ],
104
+ },
105
+ };
106
+ }
107
+ }
108
+ if (sharedState && sharedState.theoryOfMind.confidence > 0.3) {
109
+ const userId = input.userId ?? "_default";
110
+ state = {
111
+ ...state,
112
+ personhood: {
113
+ ...state.personhood,
114
+ theoryOfMind: {
115
+ ...state.personhood.theoryOfMind,
116
+ [userId]: {
117
+ estimatedMood: sharedState.theoryOfMind.estimatedMood,
118
+ estimatedIntent: sharedState.theoryOfMind.estimatedIntent,
119
+ confidence: sharedState.theoryOfMind.confidence,
120
+ lastUpdated: sharedState.theoryOfMind.lastUpdated,
121
+ },
122
+ },
123
+ },
124
+ };
125
+ }
126
+ const metacognitiveNote = input.writebackNote
127
+ ? [input.writebackNote, metacognitiveAssessment?.metacognitiveNote].filter(Boolean).join("\n")
128
+ : metacognitiveAssessment?.metacognitiveNote;
129
+ const decisionContext = buildDecisionContext(state);
130
+ const ethicsContext = ethicalAssessment ? buildEthicalContext(ethicalAssessment, locale) : undefined;
131
+ const sharedIntentionalityContext = sharedState ? buildSharedIntentionalityContext(sharedState, locale) : undefined;
132
+ const experientialNarrative = experientialField?.narrative || undefined;
133
+ const replyEnvelope = deriveReplyEnvelope(state, input.appraisalAxes, {
134
+ locale,
135
+ userText: input.userText,
136
+ algorithmStimulus: input.appliedStimulus,
137
+ classificationConfidence: input.classificationConfidence,
138
+ personalityIntensity: input.personalityIntensity,
139
+ relationContext: input.relationContext,
140
+ });
141
+ let autonomicDescription;
142
+ if (autonomicResult.state !== "ventral-vagal") {
143
+ autonomicDescription = autonomicResult.description;
144
+ if (autonomicResult.processingDepth < 0.5) {
145
+ const depthNote = locale === "en"
146
+ ? " Reflective capacity reduced — intuitive reactions."
147
+ : "反思能力降低——直觉反应中。";
148
+ autonomicDescription += depthNote;
149
+ }
150
+ }
151
+ return {
152
+ state,
153
+ locale,
154
+ autonomicState: autonomicResult.state,
155
+ autonomicDescription,
156
+ primarySystemsDescription: primarySystemsDescription || undefined,
157
+ metacognitiveNote,
158
+ decisionContext: decisionContext || undefined,
159
+ ethicsContext,
160
+ sharedIntentionalityContext,
161
+ experientialNarrative,
162
+ replyEnvelope,
163
+ };
164
+ }
package/dist/prompt.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import type { PsycheState, Locale, ChemicalSnapshot, PsycheMode } from "./types.js";
2
2
  import type { AutonomicState } from "./autonomic.js";
3
3
  import type { ChannelType } from "./channels.js";
4
- /**
5
- * Build the dynamic per-turn emotional context injected via before_prompt_build.
6
- *
7
- * This is the "current moment" — what the agent is feeling RIGHT NOW.
8
- */
9
- export declare function buildDynamicContext(state: PsycheState, userId?: string, opts?: {
4
+ export interface PromptRenderInputs {
5
+ userText?: string;
6
+ algorithmStimulus?: string | null;
7
+ personalityIntensity?: number;
8
+ channelType?: ChannelType;
10
9
  metacognitiveNote?: string;
11
10
  decisionContext?: string;
12
11
  ethicsContext?: string;
@@ -18,7 +17,13 @@ export declare function buildDynamicContext(state: PsycheState, userId?: string,
18
17
  subjectivityContext?: string;
19
18
  responseContractContext?: string;
20
19
  policyContext?: string;
21
- }): string;
20
+ }
21
+ /**
22
+ * Build the dynamic per-turn emotional context injected via before_prompt_build.
23
+ *
24
+ * This is the "current moment" — what the agent is feeling RIGHT NOW.
25
+ */
26
+ export declare function buildDynamicContext(state: PsycheState, userId?: string, opts?: PromptRenderInputs): string;
22
27
  /**
23
28
  * Build the static protocol injected as cacheable system context.
24
29
  * v0.2: imperative, step-by-step with examples.
@@ -57,20 +62,4 @@ export declare function getNearBaselineThreshold(mode?: PsycheMode): number;
57
62
  * - No protocol (LLM doesn't need system internals)
58
63
  * - <psyche_update> only for empathy (not chemistry — already computed)
59
64
  */
60
- export declare function buildCompactContext(state: PsycheState, userId?: string, opts?: {
61
- userText?: string;
62
- algorithmStimulus?: string | null;
63
- personalityIntensity?: number;
64
- channelType?: ChannelType;
65
- metacognitiveNote?: string;
66
- decisionContext?: string;
67
- ethicsContext?: string;
68
- sharedIntentionalityContext?: string;
69
- experientialNarrative?: string;
70
- autonomicDescription?: string;
71
- autonomicState?: AutonomicState;
72
- primarySystemsDescription?: string;
73
- subjectivityContext?: string;
74
- responseContractContext?: string;
75
- policyContext?: string;
76
- }): string;
65
+ export declare function buildCompactContext(state: PsycheState, userId?: string, opts?: PromptRenderInputs): string;