@charivo/core 0.0.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zeikar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,291 @@
1
+ # @charivo/core
2
+
3
+ Core types, interfaces, and event bus for the Charivo framework.
4
+
5
+ ## Features
6
+
7
+ - 🎯 **Core Types** - Shared types for messages, characters, and configuration
8
+ - 🔌 **Interface Definitions** - Standard interfaces for LLM, TTS, and Renderer
9
+ - 📡 **Event Bus** - Type-safe event system for component communication
10
+ - 🎨 **Extensible** - Build custom clients, players, and providers
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add @charivo/core
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ### Basic Setup
21
+
22
+ ```typescript
23
+ import { Charivo } from "@charivo/core";
24
+ import { createLLMManager } from "@charivo/llm-core";
25
+ import { createTTSManager } from "@charivo/tts-core";
26
+ import { createRenderManager } from "@charivo/render-core";
27
+ import { OpenAILLMClient } from "@charivo/llm-client-openai";
28
+ import { OpenAITTSPlayer } from "@charivo/tts-player-openai";
29
+ import { Live2DRenderer } from "@charivo/render-live2d";
30
+
31
+ // Initialize Charivo
32
+ const charivo = new Charivo();
33
+
34
+ // Setup LLM
35
+ const llmClient = new OpenAILLMClient({ apiKey: "your-api-key" });
36
+ const llmManager = createLLMManager(llmClient);
37
+ charivo.attachLLM(llmManager);
38
+
39
+ // Setup TTS
40
+ const ttsPlayer = new OpenAITTSPlayer({ apiKey: "your-api-key" });
41
+ const ttsManager = createTTSManager(ttsPlayer);
42
+ charivo.attachTTS(ttsManager);
43
+
44
+ // Disable TTS (optional)
45
+ // charivo.detachTTS();
46
+
47
+ // Setup Renderer
48
+ const renderer = new Live2DRenderer({ canvas });
49
+ await renderer.initialize();
50
+ await renderer.loadModel("/live2d/model.model3.json");
51
+ const renderManager = createRenderManager(renderer);
52
+ charivo.attachRenderer(renderManager);
53
+
54
+ // Set character
55
+ charivo.setCharacter({
56
+ id: "hiyori",
57
+ name: "Hiyori",
58
+ personality: "Cheerful and helpful AI assistant"
59
+ });
60
+
61
+ // Start chatting
62
+ await charivo.userSay("Hello!");
63
+ ```
64
+
65
+ ### API Reference
66
+
67
+ #### Charivo Methods
68
+
69
+ - `attachLLM(manager: LLMManager): void` - Attach an LLM manager for conversation
70
+ - `attachTTS(manager: TTSManager): void` - Attach a TTS manager for voice synthesis
71
+ - `detachTTS(): void` - Detach the TTS manager to disable voice synthesis
72
+ - `attachRenderer(manager: RenderManager): void` - Attach a renderer for visual output
73
+ - `setCharacter(character: Character): void` - Set the character configuration
74
+ - `userSay(message: string): Promise<void>` - Send a user message and get a response
75
+
76
+ ### Event Bus
77
+
78
+ ```typescript
79
+ import { EventBus } from "@charivo/core";
80
+
81
+ const eventBus = new EventBus();
82
+
83
+ // Subscribe to events
84
+ eventBus.on("tts:audio:start", (data) => {
85
+ console.log("TTS started", data.audioElement);
86
+ });
87
+
88
+ eventBus.on("tts:audio:end", () => {
89
+ console.log("TTS ended");
90
+ });
91
+
92
+ // Emit events
93
+ eventBus.emit("tts:audio:start", { audioElement });
94
+ eventBus.emit("tts:audio:end", {});
95
+ ```
96
+
97
+ ## Core Types
98
+
99
+ ### Character
100
+
101
+ ```typescript
102
+ interface Character {
103
+ id: string;
104
+ name: string;
105
+ personality: string;
106
+ traits?: string[];
107
+ background?: string;
108
+ instructions?: string[];
109
+ }
110
+ ```
111
+
112
+ ### Message
113
+
114
+ ```typescript
115
+ interface Message {
116
+ id: string;
117
+ content: string;
118
+ timestamp: Date;
119
+ type: "user" | "character" | "system";
120
+ }
121
+ ```
122
+
123
+ ### MotionType
124
+
125
+ ```typescript
126
+ type MotionType = "greeting" | "happy" | "thinking" | "talk";
127
+ ```
128
+
129
+ ## Core Interfaces
130
+
131
+ ### LLMManager
132
+
133
+ ```typescript
134
+ interface LLMManager {
135
+ setCharacter(character: Character): void;
136
+ getCharacter(): Character | null;
137
+ clearHistory(): void;
138
+ getHistory(): Message[];
139
+ generateResponse(message: Message): Promise<string>;
140
+ }
141
+ ```
142
+
143
+ ### TTSManager
144
+
145
+ ```typescript
146
+ interface TTSManager {
147
+ speak(text: string, options?: TTSOptions): Promise<void>;
148
+ stop(): Promise<void>;
149
+ setVoice(voice: string): void;
150
+ isSupported(): boolean;
151
+ setEventEmitter?(eventEmitter: {
152
+ emit: (event: string, data: any) => void;
153
+ }): void;
154
+ }
155
+ ```
156
+
157
+ ### RenderManager
158
+
159
+ ```typescript
160
+ interface RenderManager {
161
+ initialize(): Promise<void>;
162
+ render(message: Message, character?: Character): Promise<void>;
163
+ setCharacter(character: Character): void;
164
+ destroy(): Promise<void>;
165
+ loadModel?(modelPath: string): Promise<void>;
166
+ setMessageCallback?(callback: MessageCallback): void;
167
+ }
168
+ ```
169
+
170
+ ### Renderer
171
+
172
+ ```typescript
173
+ interface Renderer {
174
+ initialize(): Promise<void>;
175
+ render(message: Message, character?: Character): Promise<void>;
176
+ destroy(): Promise<void>;
177
+ loadModel?(modelPath: string): Promise<void>;
178
+ playMotion?(motionType: MotionType): void;
179
+ animateExpression?(motionType: MotionType): void;
180
+ setRealtimeLipSync?(enabled: boolean): void;
181
+ updateRealtimeLipSyncRms?(rms: number): void;
182
+ }
183
+ ```
184
+
185
+ ## Architecture
186
+
187
+ The Charivo framework follows a modular architecture:
188
+
189
+ ```
190
+ Charivo (orchestrator)
191
+ ├─ LLMManager (stateful)
192
+ │ └─ LLMClient (stateless)
193
+ │
194
+ ├─ TTSManager (stateful)
195
+ │ └─ TTSPlayer (stateless)
196
+ │
197
+ └─ RenderManager (stateful)
198
+ └─ Renderer (stateless)
199
+ ```
200
+
201
+ ### Manager Pattern
202
+
203
+ - **Managers**: Stateful components that handle business logic, state management, and coordination
204
+ - **Clients/Players/Renderers**: Stateless components that handle pure operations (API calls, audio playback, rendering)
205
+
206
+ This separation allows:
207
+ - Easy testing (mock the stateless components)
208
+ - Flexibility (swap implementations without changing business logic)
209
+ - Reusability (use clients independently or with managers)
210
+
211
+ ## Creating Custom Implementations
212
+
213
+ ### Custom LLM Client
214
+
215
+ ```typescript
216
+ import { LLMClient } from "@charivo/core";
217
+
218
+ class MyLLMClient implements LLMClient {
219
+ async call(messages: Array<{role: string, content: string}>): Promise<string> {
220
+ // Call your LLM API
221
+ return "Response from my LLM";
222
+ }
223
+ }
224
+ ```
225
+
226
+ ### Custom TTS Player
227
+
228
+ ```typescript
229
+ import { TTSPlayer, TTSOptions } from "@charivo/core";
230
+
231
+ class MyTTSPlayer implements TTSPlayer {
232
+ async speak(text: string, options?: TTSOptions): Promise<void> {
233
+ // Play audio
234
+ }
235
+
236
+ async stop(): Promise<void> {
237
+ // Stop playback
238
+ }
239
+
240
+ setVoice(voice: string): void {
241
+ // Set voice
242
+ }
243
+
244
+ isSupported(): boolean {
245
+ return true;
246
+ }
247
+ }
248
+ ```
249
+
250
+ ### Custom Renderer
251
+
252
+ ```typescript
253
+ import { Renderer, Message, Character, MotionType } from "@charivo/core";
254
+
255
+ class MyRenderer implements Renderer {
256
+ async initialize(): Promise<void> {
257
+ // Setup renderer
258
+ }
259
+
260
+ async render(message: Message, character?: Character): Promise<void> {
261
+ // Render the message
262
+ }
263
+
264
+ async destroy(): Promise<void> {
265
+ // Cleanup
266
+ }
267
+
268
+ // Optional methods
269
+ playMotion?(motionType: MotionType): void {
270
+ // Play motion
271
+ }
272
+ }
273
+ ```
274
+
275
+ ## Events
276
+
277
+ ### TTS Events
278
+
279
+ - `tts:audio:start` - Emitted when TTS starts playing
280
+ ```typescript
281
+ { audioElement: HTMLAudioElement }
282
+ ```
283
+
284
+ - `tts:audio:end` - Emitted when TTS stops playing
285
+ ```typescript
286
+ {}
287
+ ```
288
+
289
+ ## License
290
+
291
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,338 @@
1
+ 'use strict';
2
+
3
+ // src/bus.ts
4
+ var EventBus = class {
5
+ listeners = /* @__PURE__ */ new Map();
6
+ on(event, listener) {
7
+ if (!this.listeners.has(event)) {
8
+ this.listeners.set(event, []);
9
+ }
10
+ this.listeners.get(event).push(listener);
11
+ }
12
+ emit(event, data) {
13
+ const eventListeners = this.listeners.get(event);
14
+ if (eventListeners) {
15
+ eventListeners.forEach((listener) => listener(data));
16
+ }
17
+ }
18
+ off(event, listener) {
19
+ const eventListeners = this.listeners.get(event);
20
+ if (eventListeners) {
21
+ const index = eventListeners.indexOf(listener);
22
+ if (index > -1) {
23
+ eventListeners.splice(index, 1);
24
+ }
25
+ }
26
+ }
27
+ clear() {
28
+ this.listeners.clear();
29
+ }
30
+ };
31
+
32
+ // src/types.ts
33
+ var Emotion = /* @__PURE__ */ ((Emotion2) => {
34
+ Emotion2["NEUTRAL"] = "neutral";
35
+ Emotion2["HAPPY"] = "happy";
36
+ Emotion2["SAD"] = "sad";
37
+ Emotion2["ANGRY"] = "angry";
38
+ Emotion2["SURPRISED"] = "surprised";
39
+ Emotion2["THINKING"] = "thinking";
40
+ Emotion2["EXCITED"] = "excited";
41
+ Emotion2["SHY"] = "shy";
42
+ return Emotion2;
43
+ })(Emotion || {});
44
+
45
+ // src/emotion-parser.ts
46
+ var EMOTION_TAG_REGEX = /\[([a-zA-Z]+)\]/g;
47
+ var EMOTION_KEYWORD_MAP = {
48
+ // Neutral
49
+ neutral: "neutral" /* NEUTRAL */,
50
+ normal: "neutral" /* NEUTRAL */,
51
+ calm: "neutral" /* NEUTRAL */,
52
+ // Happy
53
+ happy: "happy" /* HAPPY */,
54
+ joy: "happy" /* HAPPY */,
55
+ joyful: "happy" /* HAPPY */,
56
+ cheerful: "happy" /* HAPPY */,
57
+ smile: "happy" /* HAPPY */,
58
+ // Sad
59
+ sad: "sad" /* SAD */,
60
+ unhappy: "sad" /* SAD */,
61
+ depressed: "sad" /* SAD */,
62
+ down: "sad" /* SAD */,
63
+ cry: "sad" /* SAD */,
64
+ // Angry
65
+ angry: "angry" /* ANGRY */,
66
+ mad: "angry" /* ANGRY */,
67
+ furious: "angry" /* ANGRY */,
68
+ annoyed: "angry" /* ANGRY */,
69
+ // Surprised
70
+ surprised: "surprised" /* SURPRISED */,
71
+ shock: "surprised" /* SURPRISED */,
72
+ shocked: "surprised" /* SURPRISED */,
73
+ amazed: "surprised" /* SURPRISED */,
74
+ wow: "surprised" /* SURPRISED */,
75
+ // Thinking
76
+ thinking: "thinking" /* THINKING */,
77
+ wonder: "thinking" /* THINKING */,
78
+ curious: "thinking" /* THINKING */,
79
+ hmm: "thinking" /* THINKING */,
80
+ // Excited
81
+ excited: "excited" /* EXCITED */,
82
+ energetic: "excited" /* EXCITED */,
83
+ hyper: "excited" /* EXCITED */,
84
+ enthusiastic: "excited" /* EXCITED */,
85
+ // Shy
86
+ shy: "shy" /* SHY */,
87
+ embarrassed: "shy" /* SHY */,
88
+ blush: "shy" /* SHY */,
89
+ timid: "shy" /* SHY */
90
+ };
91
+ function parseEmotion(text) {
92
+ let detectedEmotion;
93
+ let cleanedText = text;
94
+ const matches = Array.from(text.matchAll(EMOTION_TAG_REGEX));
95
+ for (const match of matches) {
96
+ const keyword = match[1].toLowerCase();
97
+ const emotion = EMOTION_KEYWORD_MAP[keyword];
98
+ if (emotion) {
99
+ detectedEmotion = emotion;
100
+ } else {
101
+ console.warn(`\u26A0\uFE0F [Emotion] Unknown keyword: [${match[1]}]`);
102
+ }
103
+ cleanedText = cleanedText.replace(match[0], "");
104
+ }
105
+ cleanedText = cleanedText.replace(/\s+/g, " ").trim();
106
+ if (detectedEmotion) {
107
+ console.log(`\u{1F3AD} [Emotion] ${detectedEmotion} \u2192 "${cleanedText}"`);
108
+ }
109
+ return {
110
+ text: cleanedText,
111
+ emotion: detectedEmotion
112
+ };
113
+ }
114
+ function hasEmotionTag(text) {
115
+ return EMOTION_TAG_REGEX.test(text);
116
+ }
117
+ function getSupportedEmotionKeywords() {
118
+ return Object.keys(EMOTION_KEYWORD_MAP);
119
+ }
120
+
121
+ // src/index.ts
122
+ var Charivo = class {
123
+ eventBus;
124
+ llmManager;
125
+ renderManager;
126
+ ttsManager;
127
+ character;
128
+ constructor() {
129
+ this.eventBus = new EventBus();
130
+ }
131
+ /**
132
+ * Attach a render manager to handle character visualization.
133
+ * Automatically connects the event bus and sets the current character if available.
134
+ */
135
+ attachRenderer(renderManager) {
136
+ console.log(
137
+ "\u{1F3AD} Charivo: Attaching render manager",
138
+ renderManager.constructor.name
139
+ );
140
+ this.renderManager = renderManager;
141
+ this.connectRenderManagerEventBus(renderManager);
142
+ if (this.character) {
143
+ renderManager.setCharacter(this.character);
144
+ }
145
+ }
146
+ /**
147
+ * Connects the render manager to the event bus for bidirectional communication.
148
+ */
149
+ connectRenderManagerEventBus(renderManager) {
150
+ if ("setEventBus" in renderManager && typeof renderManager.setEventBus === "function") {
151
+ console.log(
152
+ "\u{1F517} Charivo: \u2705 Render manager supports event bus - connecting"
153
+ );
154
+ renderManager.setEventBus({
155
+ on: (event, callback) => {
156
+ console.log(
157
+ `\u{1F517} Charivo: Render manager subscribing to event: ${event}`
158
+ );
159
+ this.eventBus.on(event, callback);
160
+ },
161
+ emit: (event, data) => {
162
+ console.log(
163
+ `\u{1F517} Charivo: Render manager emitting event: ${event}`,
164
+ data
165
+ );
166
+ this.eventBus.emit(event, data);
167
+ }
168
+ });
169
+ console.log("\u{1F517} Charivo: Event bus connection completed");
170
+ } else {
171
+ console.warn(
172
+ "\u26A0\uFE0F Charivo: Render manager doesn't support event bus connection",
173
+ {
174
+ hasSetEventBus: "setEventBus" in renderManager,
175
+ setEventBusType: typeof renderManager.setEventBus
176
+ }
177
+ );
178
+ }
179
+ }
180
+ /**
181
+ * Attach an LLM manager to handle conversation generation.
182
+ * Automatically sets the current character if available.
183
+ */
184
+ attachLLM(manager) {
185
+ this.llmManager = manager;
186
+ if (this.character) {
187
+ manager.setCharacter(this.character);
188
+ }
189
+ }
190
+ /**
191
+ * Attach a TTS manager to handle voice synthesis.
192
+ * Automatically connects the event emitter for audio events.
193
+ */
194
+ attachTTS(manager) {
195
+ console.log("\u{1F50A} Charivo: Attaching TTS manager", manager.constructor.name);
196
+ this.ttsManager = manager;
197
+ this.connectTTSManagerEventEmitter(manager);
198
+ }
199
+ /**
200
+ * Detach the TTS manager to disable voice synthesis.
201
+ */
202
+ detachTTS() {
203
+ console.log("\u{1F507} Charivo: Detaching TTS manager");
204
+ this.ttsManager = void 0;
205
+ }
206
+ /**
207
+ * Connects the TTS manager to the event bus for audio event emission.
208
+ */
209
+ connectTTSManagerEventEmitter(manager) {
210
+ if (manager.setEventEmitter) {
211
+ console.log(
212
+ "\u{1F517} Charivo: \u2705 TTS manager supports event emitter - connecting"
213
+ );
214
+ manager.setEventEmitter({
215
+ emit: (event, data) => {
216
+ console.log(`\u{1F3B5} Charivo: \u2705 TTS EMITTING EVENT: ${event}`, data);
217
+ this.eventBus.emit(event, data);
218
+ console.log(`\u{1F3B5} Charivo: \u2705 Event ${event} emitted to event bus`);
219
+ }
220
+ });
221
+ console.log("\u{1F517} Charivo: TTS Manager connection completed");
222
+ } else {
223
+ console.warn("\u26A0\uFE0F Charivo: TTS manager doesn't support event emitter", {
224
+ managerType: manager.constructor.name
225
+ });
226
+ }
227
+ }
228
+ /**
229
+ * Set the character for this Charivo instance.
230
+ * Automatically propagates to all attached managers (LLM, Renderer).
231
+ */
232
+ setCharacter(character) {
233
+ this.character = character;
234
+ if (this.llmManager) {
235
+ this.llmManager.setCharacter(character);
236
+ }
237
+ if (this.renderManager) {
238
+ this.renderManager.setCharacter(character);
239
+ }
240
+ }
241
+ /**
242
+ * Process a user message and generate a character response.
243
+ * Orchestrates the full conversation flow: rendering, LLM generation, and TTS playback.
244
+ */
245
+ async userSay(content) {
246
+ const userMessage = {
247
+ id: Date.now().toString(),
248
+ content,
249
+ timestamp: /* @__PURE__ */ new Date(),
250
+ type: "user"
251
+ };
252
+ this.eventBus.emit("message:sent", { message: userMessage });
253
+ if (this.renderManager) {
254
+ await this.renderManager.render(userMessage);
255
+ }
256
+ if (this.llmManager && this.character) {
257
+ const response = await this.llmManager.generateResponse(userMessage);
258
+ const parsed = parseEmotion(response);
259
+ const characterMessage = {
260
+ id: Date.now().toString() + "_response",
261
+ content: parsed.text,
262
+ // Use cleaned text without emotion tags
263
+ timestamp: /* @__PURE__ */ new Date(),
264
+ characterId: this.character.id,
265
+ type: "character",
266
+ emotion: parsed.emotion
267
+ // Add parsed emotion
268
+ };
269
+ this.eventBus.emit("message:received", { message: characterMessage });
270
+ this.eventBus.emit("character:speak", {
271
+ character: this.character,
272
+ message: parsed.text
273
+ });
274
+ if (this.renderManager) {
275
+ await this.renderManager.render(characterMessage, this.character);
276
+ }
277
+ if (this.ttsManager) {
278
+ try {
279
+ this.eventBus.emit("tts:start", {
280
+ text: parsed.text,
281
+ characterId: this.character.id
282
+ });
283
+ const ttsOptions = this.character.voice ? {
284
+ rate: this.character.voice.rate,
285
+ pitch: this.character.voice.pitch,
286
+ volume: this.character.voice.volume,
287
+ voice: this.character.voice.voiceId
288
+ } : void 0;
289
+ await this.ttsManager.speak(parsed.text, ttsOptions);
290
+ this.eventBus.emit("tts:end", { characterId: this.character.id });
291
+ } catch (error) {
292
+ this.eventBus.emit("tts:error", { error });
293
+ }
294
+ }
295
+ }
296
+ }
297
+ /**
298
+ * Clear the conversation history from the LLM manager.
299
+ */
300
+ clearHistory() {
301
+ if (this.llmManager) {
302
+ this.llmManager.clearHistory();
303
+ }
304
+ }
305
+ /**
306
+ * Get the conversation history from the LLM manager.
307
+ */
308
+ getHistory() {
309
+ return this.llmManager ? this.llmManager.getHistory() : [];
310
+ }
311
+ /**
312
+ * Get the currently configured character.
313
+ */
314
+ getCurrentCharacter() {
315
+ return this.character ?? null;
316
+ }
317
+ /**
318
+ * Subscribe to events from the event bus.
319
+ */
320
+ on(event, listener) {
321
+ this.eventBus.on(event, listener);
322
+ }
323
+ /**
324
+ * Emit events to the event bus.
325
+ */
326
+ emit(event, data) {
327
+ this.eventBus.emit(event, data);
328
+ }
329
+ };
330
+
331
+ exports.Charivo = Charivo;
332
+ exports.Emotion = Emotion;
333
+ exports.EventBus = EventBus;
334
+ exports.getSupportedEmotionKeywords = getSupportedEmotionKeywords;
335
+ exports.hasEmotionTag = hasEmotionTag;
336
+ exports.parseEmotion = parseEmotion;
337
+ //# sourceMappingURL=index.cjs.map
338
+ //# sourceMappingURL=index.cjs.map