@charivo/llm 0.8.2 → 0.9.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/README.md CHANGED
@@ -166,9 +166,66 @@ modalities can reuse.
166
166
 
167
167
  - `setCharacter(character)`
168
168
  - `getCharacter()`
169
- - `generateResponse(message)`
169
+ - `addToHistory(message)`
170
+ - `generateResponse(message, options?)`
170
171
  - `getHistory()`
171
172
  - `clearHistory()`
172
173
  - `setEventEmitter(eventEmitter)` — wired automatically by `Charivo.attachLLM(...)`
173
174
  - `registerTool(tool)` / `unregisterTool(name)` / `getRegisteredTools()`
174
175
  - `setToolInstructions(instructions | null)`
176
+
177
+ ### Caller-Owned History
178
+
179
+ `addToHistory(message)` ensures `message` is present in the manager's history
180
+ and returns a `HistoryRollback` (from `@charivo/core`) — a zero-argument,
181
+ idempotent undo handle. It is synchronous, and it appends only when that exact
182
+ object is not already present (reference identity, not id), then prunes to the
183
+ configured bound. That prune repairs orphans: when it actually evicts
184
+ something it also drops leading character messages, so an eviction never
185
+ leaves history starting with a reply whose user message is gone, while a
186
+ deliberately character-first history — a seeded greeting, or a reply committed
187
+ after `clearHistory()` — is preserved.
188
+
189
+ The returned handle removes its message if it is still present and restores
190
+ what *that* call evicted, but only while nothing else has written to history
191
+ since; a call that appended nothing returns an inert handle, so it can neither
192
+ delete the message nor invalidate an earlier handle. A message the manager
193
+ cannot store is rejected with a typed `CharivoStateError`: a `type: "user"`
194
+ message needs non-empty string content, while a `type: "character"` message is
195
+ stored as produced, empty content included — each rule matching the existing
196
+ write path it takes over.
197
+
198
+ `generateResponse(message, options?)` accepts `GenerateResponseOptions`:
199
+
200
+ - `callerOwnsHistory` — the caller has already placed the message via
201
+ `addToHistory` and commits the reply itself, so the call performs **no**
202
+ history writes: no append, no reply commit, no rollback on failure.
203
+ Character and message validation and prompt building are unchanged, and the
204
+ prompt still comes from history, which already holds the message.
205
+ - `isCancelled` — reports that the call has been superseded. It is consulted
206
+ before each further tool call, between a call's `tool:call` emission and its
207
+ handler, before each follow-up request, and on every projected emission,
208
+ including repeated emissions from inside one projector. Once it returns
209
+ `true` the call starts nothing further and projects nothing further, then
210
+ resolves with the latest response text. It aborts neither an in-flight
211
+ request nor an already-running handler, and it does not govern history
212
+ writes.
213
+
214
+ `Charivo.userSay(text)` always passes both — see the latest-wins turn contract
215
+ in the [core README](../core/README.md#charivo).
216
+
217
+ Direct, manager-only use is otherwise unchanged: omit the options and
218
+ `generateResponse(...)` stays self-contained, appending the user message,
219
+ committing the reply, pruning the completed pair as before, and rolling back
220
+ on failure — that rollback now works by reference identity, so overlapping
221
+ direct calls no longer roll back each other's messages.
222
+
223
+ **Migrating a custom `LLMManager`:** `addToHistory(message)` is now a required
224
+ member. Implement it synchronously; reject what you cannot store with a typed
225
+ state error; append only when the exact object is absent; return an inert
226
+ handle when you appended nothing, and otherwise an idempotent handle that
227
+ removes its own message and restores its own evictions only when nothing else
228
+ has written since; hold your own bound; and neither emit events nor call back
229
+ into `Charivo`. Honor `callerOwnsHistory` by suppressing every history write
230
+ for that call, and `isCancelled` by starting no new tool work and dropping
231
+ every further projected emission once it returns `true`.
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ var core = require('@charivo/core');
7
7
  // src/message-history-manager.ts
8
8
  var MessageHistoryManager = class {
9
9
  history = [];
10
+ writeCount = 0;
10
11
  maxMessages;
11
12
  pruneBatchSize;
12
13
  constructor(options = {}) {
@@ -21,15 +22,47 @@ var MessageHistoryManager = class {
21
22
  }
22
23
  add(message, options = {}) {
23
24
  this.history.push(message);
25
+ this.writeCount += 1;
24
26
  if (options.prune !== false) {
25
27
  this.pruneToMax();
26
28
  }
27
29
  }
28
30
  removeLast() {
29
- return this.history.pop();
31
+ const removed = this.history.pop();
32
+ if (removed !== void 0) {
33
+ this.writeCount += 1;
34
+ }
35
+ return removed;
36
+ }
37
+ /**
38
+ * Remove the entry that *is* the given object and report whether it was
39
+ * found. Reference identity, not id: overlapping turns can carry duplicate
40
+ * ids, so an id lookup can drop another turn's message.
41
+ */
42
+ remove(message) {
43
+ const index = this.history.indexOf(message);
44
+ if (index === -1) {
45
+ return false;
46
+ }
47
+ this.history.splice(index, 1);
48
+ this.writeCount += 1;
49
+ return true;
50
+ }
51
+ /** Reference-identity membership check, matching remove(). */
52
+ contains(message) {
53
+ return this.history.includes(message);
54
+ }
55
+ /** Put previously evicted entries back at the head, in their original order. */
56
+ restoreToHead(messages) {
57
+ if (messages.length === 0) {
58
+ return;
59
+ }
60
+ this.history.unshift(...messages);
61
+ this.writeCount += 1;
30
62
  }
31
63
  clear() {
32
64
  this.history = [];
65
+ this.writeCount += 1;
33
66
  }
34
67
  getAll() {
35
68
  return [...this.history];
@@ -46,6 +79,10 @@ var MessageHistoryManager = class {
46
79
  size() {
47
80
  return this.history.length;
48
81
  }
82
+ /** Monotonic counter of the write attempts this store has taken. */
83
+ getWriteCount() {
84
+ return this.writeCount;
85
+ }
49
86
  pruneToMax() {
50
87
  if (this.maxMessages === void 0) {
51
88
  return;
@@ -57,8 +94,39 @@ var MessageHistoryManager = class {
57
94
  this.history.length
58
95
  );
59
96
  this.history.splice(0, removeCount);
97
+ this.writeCount += 1;
60
98
  }
61
99
  }
100
+ /**
101
+ * Prune in one step, down to the exact bound, and report what was
102
+ * evicted in its original order. pruneBatchSize is deliberately ignored:
103
+ * the batch encodes a user/assistant pairing that a single caller-owned
104
+ * append does not have, so batching would evict a message too many.
105
+ */
106
+ pruneToBound() {
107
+ if (this.maxMessages === void 0 || this.history.length <= this.maxMessages) {
108
+ return [];
109
+ }
110
+ const evicted = this.history.splice(
111
+ 0,
112
+ this.history.length - this.maxMessages
113
+ );
114
+ this.writeCount += 1;
115
+ return evicted;
116
+ }
117
+ /** Drop the leading character messages and report them in their original order. */
118
+ removeLeadingCharacterMessages() {
119
+ let count = 0;
120
+ while (count < this.history.length - 1 && this.history[count].type === "character") {
121
+ count += 1;
122
+ }
123
+ if (count === 0) {
124
+ return [];
125
+ }
126
+ const removed = this.history.splice(0, count);
127
+ this.writeCount += 1;
128
+ return removed;
129
+ }
62
130
  };
63
131
 
64
132
  // src/character-prompt-builder.ts
@@ -204,31 +272,79 @@ var LLMManager = class {
204
272
  getHistory() {
205
273
  return this.historyManager.getAll();
206
274
  }
275
+ /**
276
+ * Ensure the message is present in the history and return an undo handle.
277
+ * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)
278
+ * write both the user message and the reply through here, so the transcript
279
+ * they present and the transcript the next prompt is built from are the
280
+ * same one.
281
+ */
282
+ addToHistory(message) {
283
+ if (message.type === "user") {
284
+ try {
285
+ LLMValidators.validateMessage(message);
286
+ } catch (error) {
287
+ throw core.toCharivoError("state", error);
288
+ }
289
+ }
290
+ if (this.historyManager.contains(message)) {
291
+ return () => {
292
+ };
293
+ }
294
+ this.historyManager.add(message, { prune: false });
295
+ const evicted = this.historyManager.pruneToBound();
296
+ if (evicted.length > 0) {
297
+ evicted.push(...this.historyManager.removeLeadingCharacterMessages());
298
+ }
299
+ const writeCount = this.historyManager.getWriteCount();
300
+ let spent = false;
301
+ return () => {
302
+ if (spent) {
303
+ return;
304
+ }
305
+ spent = true;
306
+ const untouched = this.historyManager.getWriteCount() === writeCount;
307
+ this.historyManager.remove(message);
308
+ if (untouched) {
309
+ this.historyManager.restoreToHead(evicted);
310
+ }
311
+ };
312
+ }
207
313
  /**
208
314
  * Generate a response to a message
209
315
  */
210
- async generateResponse(message) {
316
+ async generateResponse(message, options = {}) {
211
317
  try {
212
318
  LLMValidators.validateCharacterSet(this.character);
213
319
  LLMValidators.validateMessage(message);
214
320
  } catch (error) {
215
321
  throw core.toCharivoError("state", error);
216
322
  }
217
- this.historyManager.add(message, { prune: false });
323
+ const callerOwnsHistory = options.callerOwnsHistory === true;
324
+ if (!callerOwnsHistory) {
325
+ this.historyManager.add(message, { prune: false });
326
+ }
218
327
  const historyMessages = this.getHistoryForApiCall();
219
328
  const apiMessages = this.prepareApiMessages(historyMessages);
220
329
  try {
221
- const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(apiMessages) : await this.llmClient.call(apiMessages);
222
- const responseMessage = ResponseMessageBuilder.create(
223
- assistantMessage,
224
- this.character.id
225
- // character is guaranteed non-null after validateCharacterSet
226
- );
227
- this.historyManager.add(responseMessage, { prune: false });
228
- this.historyManager.pruneToMax();
330
+ const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(
331
+ apiMessages,
332
+ options.isCancelled ?? (() => false)
333
+ ) : await this.llmClient.call(apiMessages);
334
+ if (!callerOwnsHistory) {
335
+ const responseMessage = ResponseMessageBuilder.create(
336
+ assistantMessage,
337
+ this.character.id
338
+ // character is guaranteed non-null after validateCharacterSet
339
+ );
340
+ this.historyManager.add(responseMessage, { prune: false });
341
+ this.historyManager.pruneToMax();
342
+ }
229
343
  return assistantMessage;
230
344
  } catch (error) {
231
- this.historyManager.removeLast();
345
+ if (!callerOwnsHistory) {
346
+ this.historyManager.remove(message);
347
+ }
232
348
  throw core.toCharivoError("provider", error);
233
349
  }
234
350
  }
@@ -240,10 +356,12 @@ var LLMManager = class {
240
356
  return this.toolRegistry.size() > 0 && typeof this.llmClient.callWithTools === "function";
241
357
  }
242
358
  /**
243
- * Run the tool-calling conversation until the model answers with text or the
244
- * round cap is reached.
359
+ * Run the tool-calling conversation until the model answers with text, the
360
+ * round cap is reached, or the turn is superseded. A superseded turn starts
361
+ * no further tool call and issues no further request; it returns the latest
362
+ * text the model produced.
245
363
  */
246
- async runToolLoop(apiMessages) {
364
+ async runToolLoop(apiMessages, isCancelled) {
247
365
  const callWithTools = this.llmClient.callWithTools.bind(this.llmClient);
248
366
  const definitions = this.getRegisteredTools();
249
367
  const working = this.buildToolLoopMessages(apiMessages);
@@ -259,12 +377,22 @@ var LLMManager = class {
259
377
  toolCalls
260
378
  });
261
379
  for (const toolCall of toolCalls) {
380
+ if (isCancelled()) {
381
+ return response.content;
382
+ }
383
+ const outcome = await this.executeToolCall(toolCall, isCancelled);
384
+ if (!outcome.executed) {
385
+ return response.content;
386
+ }
262
387
  working.push({
263
388
  role: "tool",
264
- content: await this.executeToolCall(toolCall),
389
+ content: outcome.output,
265
390
  toolCallId: toolCall.id
266
391
  });
267
392
  }
393
+ if (isCancelled()) {
394
+ return response.content;
395
+ }
268
396
  const isFinalRound = round === MAX_TOOL_ROUNDS - 1;
269
397
  response = await callWithTools(working, isFinalRound ? [] : definitions);
270
398
  }
@@ -293,14 +421,20 @@ ${this.toolInstructions}`
293
421
  * Every failure - unknown tool, invalid arguments, handler throw/timeout,
294
422
  * non-object result, unserializable output - becomes a failure output so the
295
423
  * reply always continues.
424
+ *
425
+ * Returns "not executed" when the turn is superseded before the handler
426
+ * starts: there is no tool turn to push, so the caller stops the round.
296
427
  */
297
- async executeToolCall(toolCall) {
428
+ async executeToolCall(toolCall, isCancelled) {
298
429
  let outcome;
299
430
  this.eventEmitter?.emit("tool:call", {
300
431
  name: toolCall.name,
301
432
  args: toolCall.arguments,
302
433
  callId: toolCall.id
303
434
  });
435
+ if (isCancelled()) {
436
+ return { executed: false };
437
+ }
304
438
  try {
305
439
  const tool = this.toolRegistry.get(toolCall.name);
306
440
  if (!tool) {
@@ -325,36 +459,54 @@ ${this.toolInstructions}`
325
459
  error: failure,
326
460
  callId: toolCall.id
327
461
  });
328
- return JSON.stringify(core.createToolFailureOutput(failure));
462
+ return {
463
+ executed: true,
464
+ output: JSON.stringify(core.createToolFailureOutput(failure))
465
+ };
329
466
  }
330
467
  this.eventEmitter?.emit("tool:result", {
331
468
  name: toolCall.name,
332
469
  output: outcome.snapshot,
333
470
  callId: toolCall.id
334
471
  });
335
- this.projectToolResult(toolCall.name, outcome.snapshot, toolCall.id);
336
- return outcome.serialized;
472
+ this.projectToolResult(
473
+ toolCall.name,
474
+ outcome.snapshot,
475
+ toolCall.id,
476
+ isCancelled
477
+ );
478
+ return { executed: true, output: outcome.serialized };
337
479
  }
338
480
  /**
339
481
  * Turn a successful tool result into avatar-style events. Projection is
340
- * skipped entirely without an event emitter.
482
+ * skipped entirely without an event emitter, and a superseded turn projects
483
+ * nothing further - its avatar state would land on top of the live turn's.
341
484
  */
342
- projectToolResult(name, output, callId) {
485
+ projectToolResult(name, output, callId, isCancelled) {
343
486
  const eventEmitter = this.eventEmitter;
344
487
  if (!eventEmitter) {
345
488
  return;
346
489
  }
347
490
  for (const projector of this.resultProjectors) {
491
+ if (isCancelled()) {
492
+ return;
493
+ }
348
494
  try {
349
495
  projector({
350
496
  name,
351
497
  output,
352
498
  callId,
353
499
  emit: (event, payload) => {
500
+ if (isCancelled()) {
501
+ return;
502
+ }
354
503
  eventEmitter.emit(event, payload);
355
504
  }
356
505
  });
357
506
  } catch (error) {
507
+ if (isCancelled()) {
508
+ return;
509
+ }
358
510
  eventEmitter.emit("llm:error", {
359
511
  error: new Error(
360
512
  `LLM result projector failed for tool "${name}": ${toError(error).message}`
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/message-history-manager.ts","../src/character-prompt-builder.ts","../src/message-converter.ts","../src/validators.ts","../src/response-message-builder.ts","../src/llm-manager.ts"],"names":["createToolRegistry","toCharivoError","validateToolArguments","withToolTimeout","assertToolResultObject","snapshotToolResult","createToolFailureOutput"],"mappings":";;;;;;;AAkBO,IAAM,wBAAN,MAA4B;AAAA,EACzB,UAAqB,EAAC;AAAA,EACb,WAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAwC,EAAC,EAAG;AACtD,IAAA,IACE,OAAA,CAAQ,WAAA,KAAgB,MAAA,IACxB,OAAA,CAAQ,gBAAgB,IAAA,KACvB,CAAC,MAAA,CAAO,SAAA,CAAU,OAAA,CAAQ,WAAW,CAAA,IAAK,OAAA,CAAQ,eAAe,CAAA,CAAA,EAClE;AACA,MAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,IACtE;AAEA,IAAA,IACE,OAAA,CAAQ,cAAA,KAAmB,MAAA,KAC1B,CAAC,MAAA,CAAO,SAAA,CA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AAA,CAAuB,iBAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AACA,IAAA,OAAO,gBAAA,CAAiB,uBAAA,CAAwB,YAAA,EAAc,QAAQ,CAAA;AAAA,EACxE;AAAA,EAEQ,oBAAA,GAAkC;AACxC,IAAA,MAAM,eAAA,GAAkB,KAAK,cAAA,CAAe,SAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AAEA,IAAA,IAAI,eAAA,CAAgB,CAAC,CAAA,EAAG,IAAA,KAAS,WAAA,EAAa;AAC5C,MAAA,OAAO,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF,CAAA;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACqB;AACrB,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,OAAO,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACjE;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.js","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n return this.history.pop();\n }\n\n clear(): void {\n this.history = [];\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n }\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(message: Message): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // Defer pruning until the assistant message is appended. On failure we\n // only removeLast() the in-flight user message, so older history must\n // remain intact during the API call.\n this.historyManager.add(message, { prune: false });\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(apiMessages)\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n\n return assistantMessage;\n } catch (error) {\n // On error, remove the last message from the history\n this.historyManager.removeLast();\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text or the\n * round cap is reached.\n */\n private async runToolLoop(apiMessages: LLMApiMessage[]): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n working.push({\n role: \"tool\",\n content: await this.executeToolCall(toolCall),\n toolCallId: toolCall.id,\n });\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n */\n private async executeToolCall(toolCall: LLMToolCall): Promise<string> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return JSON.stringify(createToolFailureOutput(failure));\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(toolCall.name, outcome.snapshot, toolCall.id);\n\n return outcome.serialized;\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
1
+ {"version":3,"sources":["../src/message-history-manager.ts","../src/character-prompt-builder.ts","../src/message-converter.ts","../src/validators.ts","../src/response-message-builder.ts","../src/llm-manager.ts"],"names":["createToolRegistry","toCharivoError","validateToolArguments","withToolTimeout","assertToolResultObject","snapshotToolResult","createToolFailureOutput"],"mappings":";;;;;;;AAkBO,IAAM,wBAAN,MAA4B;AAAA,EACzB,UAAqB,EAAC;AAAA,EACtB,UAAA,GAAa,CAAA;AAAA,EACJ,WAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CA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;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF,CAAA;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACqB;AACrB,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,OAAO,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACjE;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.js","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private writeCount = 0;\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n this.writeCount += 1;\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n const removed = this.history.pop();\n\n if (removed !== undefined) {\n this.writeCount += 1;\n }\n\n return removed;\n }\n\n /**\n * Remove the entry that *is* the given object and report whether it was\n * found. Reference identity, not id: overlapping turns can carry duplicate\n * ids, so an id lookup can drop another turn's message.\n */\n remove(message: Message): boolean {\n const index = this.history.indexOf(message);\n\n if (index === -1) {\n return false;\n }\n\n this.history.splice(index, 1);\n this.writeCount += 1;\n return true;\n }\n\n /** Reference-identity membership check, matching remove(). */\n contains(message: Message): boolean {\n return this.history.includes(message);\n }\n\n /** Put previously evicted entries back at the head, in their original order. */\n restoreToHead(messages: Message[]): void {\n if (messages.length === 0) {\n return;\n }\n\n this.history.unshift(...messages);\n this.writeCount += 1;\n }\n\n clear(): void {\n this.history = [];\n this.writeCount += 1;\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n /** Monotonic counter of the write attempts this store has taken. */\n getWriteCount(): number {\n return this.writeCount;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n this.writeCount += 1;\n }\n }\n\n /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order. pruneBatchSize is deliberately ignored:\n * the batch encodes a user/assistant pairing that a single caller-owned\n * append does not have, so batching would evict a message too many.\n */\n pruneToBound(): Message[] {\n if (\n this.maxMessages === undefined ||\n this.history.length <= this.maxMessages\n ) {\n return [];\n }\n\n const evicted = this.history.splice(\n 0,\n this.history.length - this.maxMessages,\n );\n this.writeCount += 1;\n return evicted;\n }\n\n /** Drop the leading character messages and report them in their original order. */\n removeLeadingCharacterMessages(): Message[] {\n let count = 0;\n // Stop before the last entry: the newest message is never a stranded reply.\n while (\n count < this.history.length - 1 &&\n this.history[count].type === \"character\"\n ) {\n count += 1;\n }\n\n if (count === 0) {\n return [];\n }\n\n const removed = this.history.splice(0, count);\n this.writeCount += 1;\n return removed;\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type GenerateResponseOptions,\n type HistoryRollback,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\n/**\n * Internal loop signal: a superseded turn skips the handler entirely, so there\n * is no tool turn to append and the round has to stop.\n */\ntype ToolCallOutcome = { executed: true; output: string } | { executed: false };\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Ensure the message is present in the history and return an undo handle.\n * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)\n * write both the user message and the reply through here, so the transcript\n * they present and the transcript the next prompt is built from are the\n * same one.\n */\n addToHistory(message: Message): HistoryRollback {\n // Only user messages are validated: the reply commit has never been, so\n // an empty model response is still stored exactly as produced.\n if (message.type === \"user\") {\n try {\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n }\n\n if (this.historyManager.contains(message)) {\n return () => {};\n }\n\n this.historyManager.add(message, { prune: false });\n const evicted = this.historyManager.pruneToBound();\n if (evicted.length > 0) {\n // Pruning a user message can strand its reply at the head. Only an\n // eviction-bearing prune drops it, so a deliberately character-first\n // history - a reply committed after clearHistory() - survives.\n evicted.push(...this.historyManager.removeLeadingCharacterMessages());\n }\n const writeCount = this.historyManager.getWriteCount();\n\n let spent = false;\n return () => {\n if (spent) {\n return;\n }\n spent = true;\n\n // Restore only what this call evicted, and only when nothing else has\n // written since: a clearHistory() plus re-append can leave the array\n // looking untouched while the app deliberately discarded everything.\n const untouched = this.historyManager.getWriteCount() === writeCount;\n this.historyManager.remove(message);\n\n if (untouched) {\n this.historyManager.restoreToHead(evicted);\n }\n };\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(\n message: Message,\n options: GenerateResponseOptions = {},\n ): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // The caller placed the message itself and commits the reply itself, so\n // this call writes nothing - not even a rollback on failure.\n const callerOwnsHistory = options.callerOwnsHistory === true;\n\n // Defer pruning until the assistant message is appended. On failure we\n // only remove this call's own user message, so older history must remain\n // intact during the API call.\n if (!callerOwnsHistory) {\n this.historyManager.add(message, { prune: false });\n }\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(\n apiMessages,\n options.isCancelled ?? (() => false),\n )\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n if (!callerOwnsHistory) {\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n }\n\n return assistantMessage;\n } catch (error) {\n // Remove this call's own message by identity: an overlapping turn may\n // have appended after it, and duplicate ids make a lookup ambiguous.\n if (!callerOwnsHistory) {\n this.historyManager.remove(message);\n }\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text, the\n * round cap is reached, or the turn is superseded. A superseded turn starts\n * no further tool call and issues no further request; it returns the latest\n * text the model produced.\n */\n private async runToolLoop(\n apiMessages: LLMApiMessage[],\n isCancelled: () => boolean,\n ): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n // An earlier handler in this same round can supersede the turn, and so\n // can a listener of the tool:call this executes - which is why the\n // outcome, not this check alone, decides whether the round continues.\n if (isCancelled()) {\n return response.content;\n }\n\n const outcome = await this.executeToolCall(toolCall, isCancelled);\n if (!outcome.executed) {\n return response.content;\n }\n\n working.push({\n role: \"tool\",\n content: outcome.output,\n toolCallId: toolCall.id,\n });\n }\n\n if (isCancelled()) {\n return response.content;\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n *\n * Returns \"not executed\" when the turn is superseded before the handler\n * starts: there is no tool turn to push, so the caller stops the round.\n */\n private async executeToolCall(\n toolCall: LLMToolCall,\n isCancelled: () => boolean,\n ): Promise<ToolCallOutcome> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n // Emission is synchronous, so a tool:call listener runs - and can start a\n // new turn - before the handler this event announces.\n if (isCancelled()) {\n return { executed: false };\n }\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return {\n executed: true,\n output: JSON.stringify(createToolFailureOutput(failure)),\n };\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(\n toolCall.name,\n outcome.snapshot,\n toolCall.id,\n isCancelled,\n );\n\n return { executed: true, output: outcome.serialized };\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter, and a superseded turn projects\n * nothing further - its avatar state would land on top of the live turn's.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n isCancelled: () => boolean,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n // Checked per projector, which is also the check for the projector that\n // just returned: any of them can supersede the turn.\n if (isCancelled()) {\n return;\n }\n\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n // Listeners run synchronously, so an earlier emission from this\n // same projector can supersede the turn mid-projection.\n if (isCancelled()) {\n return;\n }\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n // A projector that superseded the turn and then threw belongs to a\n // stale turn: it reports no error either.\n if (isCancelled()) {\n return;\n }\n\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
package/dist/index.mjs CHANGED
@@ -5,6 +5,7 @@ import { createToolRegistry, toCharivoError, validateToolArguments, withToolTime
5
5
  // src/message-history-manager.ts
6
6
  var MessageHistoryManager = class {
7
7
  history = [];
8
+ writeCount = 0;
8
9
  maxMessages;
9
10
  pruneBatchSize;
10
11
  constructor(options = {}) {
@@ -19,15 +20,47 @@ var MessageHistoryManager = class {
19
20
  }
20
21
  add(message, options = {}) {
21
22
  this.history.push(message);
23
+ this.writeCount += 1;
22
24
  if (options.prune !== false) {
23
25
  this.pruneToMax();
24
26
  }
25
27
  }
26
28
  removeLast() {
27
- return this.history.pop();
29
+ const removed = this.history.pop();
30
+ if (removed !== void 0) {
31
+ this.writeCount += 1;
32
+ }
33
+ return removed;
34
+ }
35
+ /**
36
+ * Remove the entry that *is* the given object and report whether it was
37
+ * found. Reference identity, not id: overlapping turns can carry duplicate
38
+ * ids, so an id lookup can drop another turn's message.
39
+ */
40
+ remove(message) {
41
+ const index = this.history.indexOf(message);
42
+ if (index === -1) {
43
+ return false;
44
+ }
45
+ this.history.splice(index, 1);
46
+ this.writeCount += 1;
47
+ return true;
48
+ }
49
+ /** Reference-identity membership check, matching remove(). */
50
+ contains(message) {
51
+ return this.history.includes(message);
52
+ }
53
+ /** Put previously evicted entries back at the head, in their original order. */
54
+ restoreToHead(messages) {
55
+ if (messages.length === 0) {
56
+ return;
57
+ }
58
+ this.history.unshift(...messages);
59
+ this.writeCount += 1;
28
60
  }
29
61
  clear() {
30
62
  this.history = [];
63
+ this.writeCount += 1;
31
64
  }
32
65
  getAll() {
33
66
  return [...this.history];
@@ -44,6 +77,10 @@ var MessageHistoryManager = class {
44
77
  size() {
45
78
  return this.history.length;
46
79
  }
80
+ /** Monotonic counter of the write attempts this store has taken. */
81
+ getWriteCount() {
82
+ return this.writeCount;
83
+ }
47
84
  pruneToMax() {
48
85
  if (this.maxMessages === void 0) {
49
86
  return;
@@ -55,8 +92,39 @@ var MessageHistoryManager = class {
55
92
  this.history.length
56
93
  );
57
94
  this.history.splice(0, removeCount);
95
+ this.writeCount += 1;
58
96
  }
59
97
  }
98
+ /**
99
+ * Prune in one step, down to the exact bound, and report what was
100
+ * evicted in its original order. pruneBatchSize is deliberately ignored:
101
+ * the batch encodes a user/assistant pairing that a single caller-owned
102
+ * append does not have, so batching would evict a message too many.
103
+ */
104
+ pruneToBound() {
105
+ if (this.maxMessages === void 0 || this.history.length <= this.maxMessages) {
106
+ return [];
107
+ }
108
+ const evicted = this.history.splice(
109
+ 0,
110
+ this.history.length - this.maxMessages
111
+ );
112
+ this.writeCount += 1;
113
+ return evicted;
114
+ }
115
+ /** Drop the leading character messages and report them in their original order. */
116
+ removeLeadingCharacterMessages() {
117
+ let count = 0;
118
+ while (count < this.history.length - 1 && this.history[count].type === "character") {
119
+ count += 1;
120
+ }
121
+ if (count === 0) {
122
+ return [];
123
+ }
124
+ const removed = this.history.splice(0, count);
125
+ this.writeCount += 1;
126
+ return removed;
127
+ }
60
128
  };
61
129
 
62
130
  // src/character-prompt-builder.ts
@@ -202,31 +270,79 @@ var LLMManager = class {
202
270
  getHistory() {
203
271
  return this.historyManager.getAll();
204
272
  }
273
+ /**
274
+ * Ensure the message is present in the history and return an undo handle.
275
+ * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)
276
+ * write both the user message and the reply through here, so the transcript
277
+ * they present and the transcript the next prompt is built from are the
278
+ * same one.
279
+ */
280
+ addToHistory(message) {
281
+ if (message.type === "user") {
282
+ try {
283
+ LLMValidators.validateMessage(message);
284
+ } catch (error) {
285
+ throw toCharivoError("state", error);
286
+ }
287
+ }
288
+ if (this.historyManager.contains(message)) {
289
+ return () => {
290
+ };
291
+ }
292
+ this.historyManager.add(message, { prune: false });
293
+ const evicted = this.historyManager.pruneToBound();
294
+ if (evicted.length > 0) {
295
+ evicted.push(...this.historyManager.removeLeadingCharacterMessages());
296
+ }
297
+ const writeCount = this.historyManager.getWriteCount();
298
+ let spent = false;
299
+ return () => {
300
+ if (spent) {
301
+ return;
302
+ }
303
+ spent = true;
304
+ const untouched = this.historyManager.getWriteCount() === writeCount;
305
+ this.historyManager.remove(message);
306
+ if (untouched) {
307
+ this.historyManager.restoreToHead(evicted);
308
+ }
309
+ };
310
+ }
205
311
  /**
206
312
  * Generate a response to a message
207
313
  */
208
- async generateResponse(message) {
314
+ async generateResponse(message, options = {}) {
209
315
  try {
210
316
  LLMValidators.validateCharacterSet(this.character);
211
317
  LLMValidators.validateMessage(message);
212
318
  } catch (error) {
213
319
  throw toCharivoError("state", error);
214
320
  }
215
- this.historyManager.add(message, { prune: false });
321
+ const callerOwnsHistory = options.callerOwnsHistory === true;
322
+ if (!callerOwnsHistory) {
323
+ this.historyManager.add(message, { prune: false });
324
+ }
216
325
  const historyMessages = this.getHistoryForApiCall();
217
326
  const apiMessages = this.prepareApiMessages(historyMessages);
218
327
  try {
219
- const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(apiMessages) : await this.llmClient.call(apiMessages);
220
- const responseMessage = ResponseMessageBuilder.create(
221
- assistantMessage,
222
- this.character.id
223
- // character is guaranteed non-null after validateCharacterSet
224
- );
225
- this.historyManager.add(responseMessage, { prune: false });
226
- this.historyManager.pruneToMax();
328
+ const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(
329
+ apiMessages,
330
+ options.isCancelled ?? (() => false)
331
+ ) : await this.llmClient.call(apiMessages);
332
+ if (!callerOwnsHistory) {
333
+ const responseMessage = ResponseMessageBuilder.create(
334
+ assistantMessage,
335
+ this.character.id
336
+ // character is guaranteed non-null after validateCharacterSet
337
+ );
338
+ this.historyManager.add(responseMessage, { prune: false });
339
+ this.historyManager.pruneToMax();
340
+ }
227
341
  return assistantMessage;
228
342
  } catch (error) {
229
- this.historyManager.removeLast();
343
+ if (!callerOwnsHistory) {
344
+ this.historyManager.remove(message);
345
+ }
230
346
  throw toCharivoError("provider", error);
231
347
  }
232
348
  }
@@ -238,10 +354,12 @@ var LLMManager = class {
238
354
  return this.toolRegistry.size() > 0 && typeof this.llmClient.callWithTools === "function";
239
355
  }
240
356
  /**
241
- * Run the tool-calling conversation until the model answers with text or the
242
- * round cap is reached.
357
+ * Run the tool-calling conversation until the model answers with text, the
358
+ * round cap is reached, or the turn is superseded. A superseded turn starts
359
+ * no further tool call and issues no further request; it returns the latest
360
+ * text the model produced.
243
361
  */
244
- async runToolLoop(apiMessages) {
362
+ async runToolLoop(apiMessages, isCancelled) {
245
363
  const callWithTools = this.llmClient.callWithTools.bind(this.llmClient);
246
364
  const definitions = this.getRegisteredTools();
247
365
  const working = this.buildToolLoopMessages(apiMessages);
@@ -257,12 +375,22 @@ var LLMManager = class {
257
375
  toolCalls
258
376
  });
259
377
  for (const toolCall of toolCalls) {
378
+ if (isCancelled()) {
379
+ return response.content;
380
+ }
381
+ const outcome = await this.executeToolCall(toolCall, isCancelled);
382
+ if (!outcome.executed) {
383
+ return response.content;
384
+ }
260
385
  working.push({
261
386
  role: "tool",
262
- content: await this.executeToolCall(toolCall),
387
+ content: outcome.output,
263
388
  toolCallId: toolCall.id
264
389
  });
265
390
  }
391
+ if (isCancelled()) {
392
+ return response.content;
393
+ }
266
394
  const isFinalRound = round === MAX_TOOL_ROUNDS - 1;
267
395
  response = await callWithTools(working, isFinalRound ? [] : definitions);
268
396
  }
@@ -291,14 +419,20 @@ ${this.toolInstructions}`
291
419
  * Every failure - unknown tool, invalid arguments, handler throw/timeout,
292
420
  * non-object result, unserializable output - becomes a failure output so the
293
421
  * reply always continues.
422
+ *
423
+ * Returns "not executed" when the turn is superseded before the handler
424
+ * starts: there is no tool turn to push, so the caller stops the round.
294
425
  */
295
- async executeToolCall(toolCall) {
426
+ async executeToolCall(toolCall, isCancelled) {
296
427
  let outcome;
297
428
  this.eventEmitter?.emit("tool:call", {
298
429
  name: toolCall.name,
299
430
  args: toolCall.arguments,
300
431
  callId: toolCall.id
301
432
  });
433
+ if (isCancelled()) {
434
+ return { executed: false };
435
+ }
302
436
  try {
303
437
  const tool = this.toolRegistry.get(toolCall.name);
304
438
  if (!tool) {
@@ -323,36 +457,54 @@ ${this.toolInstructions}`
323
457
  error: failure,
324
458
  callId: toolCall.id
325
459
  });
326
- return JSON.stringify(createToolFailureOutput(failure));
460
+ return {
461
+ executed: true,
462
+ output: JSON.stringify(createToolFailureOutput(failure))
463
+ };
327
464
  }
328
465
  this.eventEmitter?.emit("tool:result", {
329
466
  name: toolCall.name,
330
467
  output: outcome.snapshot,
331
468
  callId: toolCall.id
332
469
  });
333
- this.projectToolResult(toolCall.name, outcome.snapshot, toolCall.id);
334
- return outcome.serialized;
470
+ this.projectToolResult(
471
+ toolCall.name,
472
+ outcome.snapshot,
473
+ toolCall.id,
474
+ isCancelled
475
+ );
476
+ return { executed: true, output: outcome.serialized };
335
477
  }
336
478
  /**
337
479
  * Turn a successful tool result into avatar-style events. Projection is
338
- * skipped entirely without an event emitter.
480
+ * skipped entirely without an event emitter, and a superseded turn projects
481
+ * nothing further - its avatar state would land on top of the live turn's.
339
482
  */
340
- projectToolResult(name, output, callId) {
483
+ projectToolResult(name, output, callId, isCancelled) {
341
484
  const eventEmitter = this.eventEmitter;
342
485
  if (!eventEmitter) {
343
486
  return;
344
487
  }
345
488
  for (const projector of this.resultProjectors) {
489
+ if (isCancelled()) {
490
+ return;
491
+ }
346
492
  try {
347
493
  projector({
348
494
  name,
349
495
  output,
350
496
  callId,
351
497
  emit: (event, payload) => {
498
+ if (isCancelled()) {
499
+ return;
500
+ }
352
501
  eventEmitter.emit(event, payload);
353
502
  }
354
503
  });
355
504
  } catch (error) {
505
+ if (isCancelled()) {
506
+ return;
507
+ }
356
508
  eventEmitter.emit("llm:error", {
357
509
  error: new Error(
358
510
  `LLM result projector failed for tool "${name}": ${toError(error).message}`
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/message-history-manager.ts","../src/character-prompt-builder.ts","../src/message-converter.ts","../src/validators.ts","../src/response-message-builder.ts","../src/llm-manager.ts"],"names":[],"mappings":";;;;;AAkBO,IAAM,wBAAN,MAA4B;AAAA,EACzB,UAAqB,EAAC;AAAA,EACb,WAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAwC,EAAC,EAAG;AACtD,IAAA,IACE,OAAA,CAAQ,WAAA,KAAgB,MAAA,IACxB,OAAA,CAAQ,gBAAgB,IAAA,KACvB,CAAC,MAAA,CAAO,SAAA,CA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AAkB,CAAA;AAC3B","file":"index.mjs","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n return this.history.pop();\n }\n\n clear(): void {\n this.history = [];\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n }\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(message: Message): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // Defer pruning until the assistant message is appended. On failure we\n // only removeLast() the in-flight user message, so older history must\n // remain intact during the API call.\n this.historyManager.add(message, { prune: false });\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(apiMessages)\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n\n return assistantMessage;\n } catch (error) {\n // On error, remove the last message from the history\n this.historyManager.removeLast();\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text or the\n * round cap is reached.\n */\n private async runToolLoop(apiMessages: LLMApiMessage[]): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n working.push({\n role: \"tool\",\n content: await this.executeToolCall(toolCall),\n toolCallId: toolCall.id,\n });\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n */\n private async executeToolCall(toolCall: LLMToolCall): Promise<string> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return JSON.stringify(createToolFailureOutput(failure));\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(toolCall.name, outcome.snapshot, toolCall.id);\n\n return outcome.serialized;\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
1
+ {"version":3,"sources":["../src/message-history-manager.ts","../src/character-prompt-builder.ts","../src/message-converter.ts","../src/validators.ts","../src/response-message-builder.ts","../src/llm-manager.ts"],"names":[],"mappings":";;;;;AAkBO,IAAM,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IAAI,eAAA,CAAgB,CAAC,CAAA,EAAG,IAAA,KAAS,WAAA,EAAa;AAC5C,MAAA,OAAO,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF,CAAA;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACqB;AACrB,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,OAAO,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACjE;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.mjs","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private writeCount = 0;\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n this.writeCount += 1;\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n const removed = this.history.pop();\n\n if (removed !== undefined) {\n this.writeCount += 1;\n }\n\n return removed;\n }\n\n /**\n * Remove the entry that *is* the given object and report whether it was\n * found. Reference identity, not id: overlapping turns can carry duplicate\n * ids, so an id lookup can drop another turn's message.\n */\n remove(message: Message): boolean {\n const index = this.history.indexOf(message);\n\n if (index === -1) {\n return false;\n }\n\n this.history.splice(index, 1);\n this.writeCount += 1;\n return true;\n }\n\n /** Reference-identity membership check, matching remove(). */\n contains(message: Message): boolean {\n return this.history.includes(message);\n }\n\n /** Put previously evicted entries back at the head, in their original order. */\n restoreToHead(messages: Message[]): void {\n if (messages.length === 0) {\n return;\n }\n\n this.history.unshift(...messages);\n this.writeCount += 1;\n }\n\n clear(): void {\n this.history = [];\n this.writeCount += 1;\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n /** Monotonic counter of the write attempts this store has taken. */\n getWriteCount(): number {\n return this.writeCount;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n this.writeCount += 1;\n }\n }\n\n /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order. pruneBatchSize is deliberately ignored:\n * the batch encodes a user/assistant pairing that a single caller-owned\n * append does not have, so batching would evict a message too many.\n */\n pruneToBound(): Message[] {\n if (\n this.maxMessages === undefined ||\n this.history.length <= this.maxMessages\n ) {\n return [];\n }\n\n const evicted = this.history.splice(\n 0,\n this.history.length - this.maxMessages,\n );\n this.writeCount += 1;\n return evicted;\n }\n\n /** Drop the leading character messages and report them in their original order. */\n removeLeadingCharacterMessages(): Message[] {\n let count = 0;\n // Stop before the last entry: the newest message is never a stranded reply.\n while (\n count < this.history.length - 1 &&\n this.history[count].type === \"character\"\n ) {\n count += 1;\n }\n\n if (count === 0) {\n return [];\n }\n\n const removed = this.history.splice(0, count);\n this.writeCount += 1;\n return removed;\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type GenerateResponseOptions,\n type HistoryRollback,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\n/**\n * Internal loop signal: a superseded turn skips the handler entirely, so there\n * is no tool turn to append and the round has to stop.\n */\ntype ToolCallOutcome = { executed: true; output: string } | { executed: false };\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Ensure the message is present in the history and return an undo handle.\n * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)\n * write both the user message and the reply through here, so the transcript\n * they present and the transcript the next prompt is built from are the\n * same one.\n */\n addToHistory(message: Message): HistoryRollback {\n // Only user messages are validated: the reply commit has never been, so\n // an empty model response is still stored exactly as produced.\n if (message.type === \"user\") {\n try {\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n }\n\n if (this.historyManager.contains(message)) {\n return () => {};\n }\n\n this.historyManager.add(message, { prune: false });\n const evicted = this.historyManager.pruneToBound();\n if (evicted.length > 0) {\n // Pruning a user message can strand its reply at the head. Only an\n // eviction-bearing prune drops it, so a deliberately character-first\n // history - a reply committed after clearHistory() - survives.\n evicted.push(...this.historyManager.removeLeadingCharacterMessages());\n }\n const writeCount = this.historyManager.getWriteCount();\n\n let spent = false;\n return () => {\n if (spent) {\n return;\n }\n spent = true;\n\n // Restore only what this call evicted, and only when nothing else has\n // written since: a clearHistory() plus re-append can leave the array\n // looking untouched while the app deliberately discarded everything.\n const untouched = this.historyManager.getWriteCount() === writeCount;\n this.historyManager.remove(message);\n\n if (untouched) {\n this.historyManager.restoreToHead(evicted);\n }\n };\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(\n message: Message,\n options: GenerateResponseOptions = {},\n ): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // The caller placed the message itself and commits the reply itself, so\n // this call writes nothing - not even a rollback on failure.\n const callerOwnsHistory = options.callerOwnsHistory === true;\n\n // Defer pruning until the assistant message is appended. On failure we\n // only remove this call's own user message, so older history must remain\n // intact during the API call.\n if (!callerOwnsHistory) {\n this.historyManager.add(message, { prune: false });\n }\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(\n apiMessages,\n options.isCancelled ?? (() => false),\n )\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n if (!callerOwnsHistory) {\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n }\n\n return assistantMessage;\n } catch (error) {\n // Remove this call's own message by identity: an overlapping turn may\n // have appended after it, and duplicate ids make a lookup ambiguous.\n if (!callerOwnsHistory) {\n this.historyManager.remove(message);\n }\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text, the\n * round cap is reached, or the turn is superseded. A superseded turn starts\n * no further tool call and issues no further request; it returns the latest\n * text the model produced.\n */\n private async runToolLoop(\n apiMessages: LLMApiMessage[],\n isCancelled: () => boolean,\n ): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n // An earlier handler in this same round can supersede the turn, and so\n // can a listener of the tool:call this executes - which is why the\n // outcome, not this check alone, decides whether the round continues.\n if (isCancelled()) {\n return response.content;\n }\n\n const outcome = await this.executeToolCall(toolCall, isCancelled);\n if (!outcome.executed) {\n return response.content;\n }\n\n working.push({\n role: \"tool\",\n content: outcome.output,\n toolCallId: toolCall.id,\n });\n }\n\n if (isCancelled()) {\n return response.content;\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n *\n * Returns \"not executed\" when the turn is superseded before the handler\n * starts: there is no tool turn to push, so the caller stops the round.\n */\n private async executeToolCall(\n toolCall: LLMToolCall,\n isCancelled: () => boolean,\n ): Promise<ToolCallOutcome> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n // Emission is synchronous, so a tool:call listener runs - and can start a\n // new turn - before the handler this event announces.\n if (isCancelled()) {\n return { executed: false };\n }\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return {\n executed: true,\n output: JSON.stringify(createToolFailureOutput(failure)),\n };\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(\n toolCall.name,\n outcome.snapshot,\n toolCall.id,\n isCancelled,\n );\n\n return { executed: true, output: outcome.serialized };\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter, and a superseded turn projects\n * nothing further - its avatar state would land on top of the live turn's.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n isCancelled: () => boolean,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n // Checked per projector, which is also the check for the projector that\n // just returned: any of them can supersede the turn.\n if (isCancelled()) {\n return;\n }\n\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n // Listeners run synchronously, so an earlier emission from this\n // same projector can supersede the turn mid-projection.\n if (isCancelled()) {\n return;\n }\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n // A projector that superseded the turn and then threw belongs to a\n // stale turn: it reports no error either.\n if (isCancelled()) {\n return;\n }\n\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@charivo/llm",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "LLM manager and browser adapters for Charivo",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "openai": "^4.47.1",
37
- "@charivo/core": "^0.22.0"
37
+ "@charivo/core": "^0.24.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "tsup": "^8.5.0",