Files
Kokorone/apps/api/src/emotion/emotion.service.ts
T
Jeffery d82b834e47 feat: 完成 I 群組 — 生活作息與離線生活
- ScheduleService:I-1 平日/週末/假期時段表(可為角色寫入高中生預設作息)、
  I-3 時間感知(Asia/Taipei 當地時間,不受伺服器時區影響)、剛醒/睡前偵測
- constants.ts:I-2 時段狀態 → 回應可用度對照(FREE/SEMI_BUSY/BUSY/SLEEP →
  NORMAL/BRIEF/DELAYED/NO_REPLY),沒有作息表的角色一律視為 NORMAL(相容既有角色)
- ScheduleExceptionService:I-4 三種破例(深夜還陪你聊/上課偷回訊息/為你調整行程),
  各自獨立冷卻期,觸發時記入關係帳本
- ScheduleEmotionBaselineService:I-5 作息驅動情緒基線(社團剛結束的疲憊、假日偏高心情),
  只在本輪沒有明確情緒訊號時介入,串接進 EmotionService.processInput 的新增選項
- OfflineEventService:I-6 離線事件生成,依「今天已發生的固定行程」挑選對應模板,
  一天只生成一次,寫入低權重情節記憶
- DialogueService 整合以上機制:離線事件生成 → 情緒基線標記 → 累積親密度 →
  作息可用度判定 → 不符合則嘗試破例 → 依可用度決定回覆內容
- 修正真實 bug:G-5 角色建立流程誤用 source=OFFLINE_GENERATED 標記背景故事,
  與 I-6「今天是否已生成離線事件」的判斷共用同一標記,已改為 SOURCE_EXTRACTION
- ChatView.tsx 補上 NO_REPLY/context 為 null 的防呆(作息可用度整合後的必要調整)
- scripts/smoke/I.mjs:以獨立測試角色(避免污染種子角色的排程狀態)驗證全部六項

npm run restart && npm run smoke -- I 皆通過(I-V),A~H 群組冒煙測試無回歸。
2026-08-13 14:08:24 +08:00

156 lines
5.8 KiB
TypeScript

import { Injectable } from "@nestjs/common";
import type { EmotionTag, EmotionState } from "@kokorone/shared";
import { PrismaService } from "../prisma/prisma.service.js";
import { RuleBasedEmotionTagger } from "./emotion-tagger.js";
import { nextEmotionState, type TransitionContext } from "./emotion-state-machine.js";
import { toResponseStyle, type ResponseStyle } from "./response-style.js";
import { getArchetypeParams } from "../personality/archetype-params.js";
// D-2 時間衰減:預設半衰期 2 小時,實際速度由角色參數(G 群組)覆寫。
const DEFAULT_HALF_LIFE_MS = 2 * 60 * 60 * 1000;
// 低於此值視為「沒有明顯情緒」,dominantState 回報平靜。
const DOMINANT_EPSILON = 5;
// 標記強度低於此值視為刺激太弱,不足以真正觸發情緒轉移(高情緒觸發閾值的原型因此「難觸發」)。
const MIN_TRIGGER_INTENSITY = 0.25;
interface Dimensions {
calm: number;
joy: number;
sad: number;
alert: number;
shy: number;
grumpy: number;
}
const NON_CALM_TAGS: Exclude<EmotionTag, "CALM">[] = ["JOY", "SAD", "ALERT", "SHY", "GRUMPY"];
function fieldFor(tag: Exclude<EmotionTag, "CALM">): "joy" | "sad" | "alert" | "shy" | "grumpy" {
return tag.toLowerCase() as "joy" | "sad" | "alert" | "shy" | "grumpy";
}
function dominantState(dims: Dimensions): EmotionTag {
let best: EmotionTag = "CALM";
let bestValue = DOMINANT_EPSILON;
for (const tag of NON_CALM_TAGS) {
const value = dims[fieldFor(tag)];
if (value > bestValue) {
best = tag;
bestValue = value;
}
}
return best;
}
function decayDimensions(dims: Dimensions, elapsedMs: number, halfLifeMs: number): Dimensions {
const factor = elapsedMs > 0 ? Math.pow(0.5, elapsedMs / halfLifeMs) : 1;
const joy = dims.joy * factor;
const sad = dims.sad * factor;
const alert = dims.alert * factor;
const shy = dims.shy * factor;
const grumpy = dims.grumpy * factor;
const calm = Math.max(0, Math.min(100, 100 - (joy + sad + alert + shy + grumpy)));
return { calm, joy, sad, alert, shy, grumpy };
}
export interface ProcessInputOptions extends TransitionContext {
triggerThreshold?: number;
halfLifeMs?: number;
now?: Date;
// I-5:本輪對話沒有明確情緒訊號時,套用作息驅動的基線情緒(不覆蓋文字本身觸發的訊號)。
baselineSignal?: { tag: EmotionTag; intensity: number };
}
function toDomain(characterId: string, dims: Dimensions, updatedAt: Date): EmotionState {
return {
characterId,
calm: dims.calm,
joy: dims.joy,
sad: dims.sad,
alert: dims.alert,
shy: dims.shy,
grumpy: dims.grumpy,
updatedAt: updatedAt.toISOString(),
};
}
@Injectable()
export class EmotionService {
constructor(
private readonly prisma: PrismaService,
private readonly tagger: RuleBasedEmotionTagger,
) {}
async getState(characterId: string, now: Date = new Date()): Promise<EmotionState> {
const { dims, updatedAt } = await this.decayedDimensions(characterId, now);
await this.persist(characterId, dims, now);
return toDomain(characterId, dims, now);
}
async getResponseStyle(characterId: string, now: Date = new Date()): Promise<ResponseStyle> {
const state = await this.getState(characterId, now);
return toResponseStyle(dominantState(state));
}
async processInput(
characterId: string,
text: string,
options: ProcessInputOptions = {},
): Promise<{ state: EmotionState; style: ResponseStyle }> {
const now = options.now ?? new Date();
const { dims: decayed } = await this.decayedDimensions(characterId, now, options.halfLifeMs);
const currentDominant = dominantState(decayed);
// G-1:情緒觸發閾值預設由角色性格原型決定,呼叫端仍可明確覆寫。
const character = await this.prisma.client.character.findUniqueOrThrow({ where: { id: characterId } });
const archetypeParams = getArchetypeParams(character.personalityArchetype);
const triggerThreshold = options.triggerThreshold ?? archetypeParams.emotionTriggerThreshold;
const rawSignal = this.tagger.tag({ text, triggerThreshold });
// 情緒觸發閾值除了縮放強度,也要能讓「難觸發」原型對弱刺激完全不觸發(而不只是觸發得比較小力)。
let signal = rawSignal.intensity < MIN_TRIGGER_INTENSITY ? { tag: "CALM" as const, intensity: 0 } : rawSignal;
if (signal.tag === "CALM" && options.baselineSignal) {
signal = options.baselineSignal;
}
const next = nextEmotionState(currentDominant, signal, options);
let updated: Dimensions;
if (next === currentDominant) {
updated = decayed;
} else if (next === "CALM") {
updated = { calm: 100, joy: 0, sad: 0, alert: 0, shy: 0, grumpy: 0 };
} else {
const intensityValue = Math.max(20, signal.intensity * 100);
updated = { calm: Math.max(0, 100 - intensityValue), joy: 0, sad: 0, alert: 0, shy: 0, grumpy: 0 };
updated[fieldFor(next)] = intensityValue;
}
await this.persist(characterId, updated, now);
return { state: toDomain(characterId, updated, now), style: toResponseStyle(next) };
}
private async decayedDimensions(
characterId: string,
now: Date,
halfLifeMs = DEFAULT_HALF_LIFE_MS,
): Promise<{ dims: Dimensions; updatedAt: Date }> {
const row = await this.prisma.client.emotionState.upsert({
where: { characterId },
update: {},
create: { characterId },
});
const elapsedMs = now.getTime() - row.updatedAt.getTime();
const dims = decayDimensions(row, elapsedMs, halfLifeMs);
return { dims, updatedAt: row.updatedAt };
}
private async persist(characterId: string, dims: Dimensions, now: Date): Promise<void> {
await this.prisma.client.emotionState.update({
where: { characterId },
data: { ...dims, updatedAt: now },
});
}
}
export { dominantState };