@charivo/llm 0.10.5 → 0.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,22 +9,17 @@ var MessageHistoryManager = class {
9
9
  history = [];
10
10
  writeCount = 0;
11
11
  maxMessages;
12
- pruneBatchSize;
13
12
  constructor(options = {}) {
14
13
  if (options.maxMessages !== void 0 && options.maxMessages !== null && (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)) {
15
14
  throw new TypeError("maxMessages must be a positive integer or null");
16
15
  }
17
- if (options.pruneBatchSize !== void 0 && (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)) {
18
- throw new TypeError("pruneBatchSize must be a positive integer");
19
- }
20
16
  this.maxMessages = options.maxMessages === null ? void 0 : options.maxMessages;
21
- this.pruneBatchSize = options.pruneBatchSize ?? 1;
22
17
  }
23
18
  add(message, options = {}) {
24
19
  this.history.push(message);
25
20
  this.writeCount += 1;
26
21
  if (options.prune !== false) {
27
- this.pruneToMax();
22
+ this.pruneToBound();
28
23
  }
29
24
  }
30
25
  removeLast() {
@@ -83,25 +78,9 @@ var MessageHistoryManager = class {
83
78
  getWriteCount() {
84
79
  return this.writeCount;
85
80
  }
86
- pruneToMax() {
87
- if (this.maxMessages === void 0) {
88
- return;
89
- }
90
- while (this.history.length > this.maxMessages) {
91
- const excess = this.history.length - this.maxMessages;
92
- const removeCount = Math.min(
93
- Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,
94
- this.history.length
95
- );
96
- this.history.splice(0, removeCount);
97
- this.writeCount += 1;
98
- }
99
- }
100
81
  /**
101
82
  * 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.
83
+ * evicted in its original order.
105
84
  */
106
85
  pruneToBound() {
107
86
  if (this.maxMessages === void 0 || this.history.length <= this.maxMessages) {
@@ -207,8 +186,7 @@ var LLMManager = class {
207
186
  this.llmClient = llmClient;
208
187
  this.maxHistoryMessages = resolveMaxHistoryMessages(options);
209
188
  this.historyManager = new MessageHistoryManager({
210
- maxMessages: this.maxHistoryMessages,
211
- pruneBatchSize: 2
189
+ maxMessages: this.maxHistoryMessages
212
190
  });
213
191
  this.resultProjectors = options.resultProjectors ?? [];
214
192
  this.defaultToolTimeoutMs = options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;
@@ -272,6 +250,22 @@ var LLMManager = class {
272
250
  getHistory() {
273
251
  return this.historyManager.getAll();
274
252
  }
253
+ /**
254
+ * Trim to the bound and report everything removed, in its original order.
255
+ *
256
+ * Pruning is exact rather than turn-sized: overlapping turns leave the
257
+ * excess odd, and rounding up to a whole turn evicts the pending turn's
258
+ * user message as well, stranding the reply it is about to commit. Turns
259
+ * still leave together on the sequential path, where a committed pair
260
+ * always makes the excess even.
261
+ */
262
+ pruneWithoutStrandingReplies() {
263
+ const evicted = this.historyManager.pruneToBound();
264
+ if (evicted.length > 0) {
265
+ evicted.push(...this.historyManager.removeLeadingCharacterMessages());
266
+ }
267
+ return evicted;
268
+ }
275
269
  /**
276
270
  * Ensure the message is present in the history and return an undo handle.
277
271
  * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)
@@ -292,10 +286,7 @@ var LLMManager = class {
292
286
  };
293
287
  }
294
288
  this.historyManager.add(message, { prune: false });
295
- const evicted = this.historyManager.pruneToBound();
296
- if (evicted.length > 0) {
297
- evicted.push(...this.historyManager.removeLeadingCharacterMessages());
298
- }
289
+ const evicted = this.pruneWithoutStrandingReplies();
299
290
  const writeCount = this.historyManager.getWriteCount();
300
291
  let spent = false;
301
292
  return () => {
@@ -339,7 +330,7 @@ var LLMManager = class {
339
330
  // character is guaranteed non-null after validateCharacterSet
340
331
  );
341
332
  this.historyManager.add(responseMessage, { prune: false });
342
- this.historyManager.pruneToMax();
333
+ this.pruneWithoutStrandingReplies();
343
334
  }
344
335
  return assistantMessage;
345
336
  } catch (error) {
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,EACtB,UAAA,GAAa,CAAA;AAAA,EACJ,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,CAAU,OAAA,CAAQ,cAAc,CAAA,IAAK,OAAA,CAAQ,cAAA,IAAkB,CAAA,CAAA,EACxE;AACA,MAAA,MAAM,IAAI,UAAU,2CAA2C,CAAA;AAAA,IACjE;AAEA,IAAA,IAAA,CAAK,WAAA,GACH,OAAA,CAAQ,WAAA,KAAgB,IAAA,GAAO,SAAY,OAAA,CAAQ,WAAA;AACrD,IAAA,IAAA,CAAK,cAAA,GAAiB,QAAQ,cAAA,IAAkB,CAAA;AAAA,EAClD;AAAA,EAEA,GAAA,CAAI,OAAA,EAAkB,OAAA,GAA6B,EAAC,EAAS;AAC3D,IAAA,IAAA,CAAK,OAAA,CAAQ,KAAK,OAAO,CAAA;AACzB,IAAA,IAAA,CAAK,UAAA,IAA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ent":["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 options.signal,\n )\n : await this.llmClient.call(apiMessages, { signal: options.signal });\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 signal?: AbortSignal,\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, { signal });\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 signal,\n });\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"]}
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":";;;;;;;AAiBO,IAAM,wBAAN,MAA4B;AAAA,EACzB,UAAqB,EAAC;AAAA,EACtB,UAAA,GAAa,CAAA;AAAA,EACJ,WAAA;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,IAAA,CAAK,WAAA,GACH,OAAA,CAAQ,WAAA,KAAgB,IAAA,GAAO,SAAY,OAAA,CAAQ,WAAA;AAAA,EACvD;AAAA,EAEA,GAAA,CAAI,OAAA,EAAkB,OAAA,GAA6B,EAAC,EAAS;AAC3D,IAAA,IAAA,CAAK,OAAA,CAAQ,KAAK,OAAO,CAAA;AACzB,IAAA,IAAA,CAAK,UAAA,IA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B,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}\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\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 this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\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.pruneToBound();\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 /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order.\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 });\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 * Trim to the bound and report everything removed, in its original order.\n *\n * Pruning is exact rather than turn-sized: overlapping turns leave the\n * excess odd, and rounding up to a whole turn evicts the pending turn's\n * user message as well, stranding the reply it is about to commit. Turns\n * still leave together on the sequential path, where a committed pair\n * always makes the excess even.\n */\n private pruneWithoutStrandingReplies(): Message[] {\n const evicted = this.historyManager.pruneToBound();\n\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\n return evicted;\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.pruneWithoutStrandingReplies();\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 options.signal,\n )\n : await this.llmClient.call(apiMessages, { signal: options.signal });\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.pruneWithoutStrandingReplies();\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 signal?: AbortSignal,\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, { signal });\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 signal,\n });\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
@@ -7,22 +7,17 @@ var MessageHistoryManager = class {
7
7
  history = [];
8
8
  writeCount = 0;
9
9
  maxMessages;
10
- pruneBatchSize;
11
10
  constructor(options = {}) {
12
11
  if (options.maxMessages !== void 0 && options.maxMessages !== null && (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)) {
13
12
  throw new TypeError("maxMessages must be a positive integer or null");
14
13
  }
15
- if (options.pruneBatchSize !== void 0 && (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)) {
16
- throw new TypeError("pruneBatchSize must be a positive integer");
17
- }
18
14
  this.maxMessages = options.maxMessages === null ? void 0 : options.maxMessages;
19
- this.pruneBatchSize = options.pruneBatchSize ?? 1;
20
15
  }
21
16
  add(message, options = {}) {
22
17
  this.history.push(message);
23
18
  this.writeCount += 1;
24
19
  if (options.prune !== false) {
25
- this.pruneToMax();
20
+ this.pruneToBound();
26
21
  }
27
22
  }
28
23
  removeLast() {
@@ -81,25 +76,9 @@ var MessageHistoryManager = class {
81
76
  getWriteCount() {
82
77
  return this.writeCount;
83
78
  }
84
- pruneToMax() {
85
- if (this.maxMessages === void 0) {
86
- return;
87
- }
88
- while (this.history.length > this.maxMessages) {
89
- const excess = this.history.length - this.maxMessages;
90
- const removeCount = Math.min(
91
- Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,
92
- this.history.length
93
- );
94
- this.history.splice(0, removeCount);
95
- this.writeCount += 1;
96
- }
97
- }
98
79
  /**
99
80
  * 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.
81
+ * evicted in its original order.
103
82
  */
104
83
  pruneToBound() {
105
84
  if (this.maxMessages === void 0 || this.history.length <= this.maxMessages) {
@@ -205,8 +184,7 @@ var LLMManager = class {
205
184
  this.llmClient = llmClient;
206
185
  this.maxHistoryMessages = resolveMaxHistoryMessages(options);
207
186
  this.historyManager = new MessageHistoryManager({
208
- maxMessages: this.maxHistoryMessages,
209
- pruneBatchSize: 2
187
+ maxMessages: this.maxHistoryMessages
210
188
  });
211
189
  this.resultProjectors = options.resultProjectors ?? [];
212
190
  this.defaultToolTimeoutMs = options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;
@@ -270,6 +248,22 @@ var LLMManager = class {
270
248
  getHistory() {
271
249
  return this.historyManager.getAll();
272
250
  }
251
+ /**
252
+ * Trim to the bound and report everything removed, in its original order.
253
+ *
254
+ * Pruning is exact rather than turn-sized: overlapping turns leave the
255
+ * excess odd, and rounding up to a whole turn evicts the pending turn's
256
+ * user message as well, stranding the reply it is about to commit. Turns
257
+ * still leave together on the sequential path, where a committed pair
258
+ * always makes the excess even.
259
+ */
260
+ pruneWithoutStrandingReplies() {
261
+ const evicted = this.historyManager.pruneToBound();
262
+ if (evicted.length > 0) {
263
+ evicted.push(...this.historyManager.removeLeadingCharacterMessages());
264
+ }
265
+ return evicted;
266
+ }
273
267
  /**
274
268
  * Ensure the message is present in the history and return an undo handle.
275
269
  * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)
@@ -290,10 +284,7 @@ var LLMManager = class {
290
284
  };
291
285
  }
292
286
  this.historyManager.add(message, { prune: false });
293
- const evicted = this.historyManager.pruneToBound();
294
- if (evicted.length > 0) {
295
- evicted.push(...this.historyManager.removeLeadingCharacterMessages());
296
- }
287
+ const evicted = this.pruneWithoutStrandingReplies();
297
288
  const writeCount = this.historyManager.getWriteCount();
298
289
  let spent = false;
299
290
  return () => {
@@ -337,7 +328,7 @@ var LLMManager = class {
337
328
  // character is guaranteed non-null after validateCharacterSet
338
329
  );
339
330
  this.historyManager.add(responseMessage, { prune: false });
340
- this.historyManager.pruneToMax();
331
+ this.pruneWithoutStrandingReplies();
341
332
  }
342
333
  return assistantMessage;
343
334
  } catch (error) {
@@ -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,EACtB,UAAA,GAAa,CAAA;AAAA,EACJ,WAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAwC,EAAC,EAAG;AACtD,IAAA,IACE,OAAA,CAAQ,WAAA,KAAgB,MAAA,IACxB,OAAA,CAAQ,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AAM,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 options.signal,\n )\n : await this.llmClient.call(apiMessages, { signal: options.signal });\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 signal?: AbortSignal,\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, { signal });\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 signal,\n });\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"]}
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":";;;;;AAiBO,IAAM,wBAAN,MAA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AAA,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}\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\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 this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\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.pruneToBound();\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 /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order.\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 });\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 * Trim to the bound and report everything removed, in its original order.\n *\n * Pruning is exact rather than turn-sized: overlapping turns leave the\n * excess odd, and rounding up to a whole turn evicts the pending turn's\n * user message as well, stranding the reply it is about to commit. Turns\n * still leave together on the sequential path, where a committed pair\n * always makes the excess even.\n */\n private pruneWithoutStrandingReplies(): Message[] {\n const evicted = this.historyManager.pruneToBound();\n\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\n return evicted;\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.pruneWithoutStrandingReplies();\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 options.signal,\n )\n : await this.llmClient.call(apiMessages, { signal: options.signal });\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.pruneWithoutStrandingReplies();\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 signal?: AbortSignal,\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, { signal });\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 signal,\n });\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.10.5",
3
+ "version": "0.10.6",
4
4
  "description": "LLM manager and browser adapters for Charivo",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",