@charivo/llm 0.9.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +8 -5
- package/dist/index.mjs.map +1 -1
- package/dist/remote/index.js +37 -37
- package/dist/remote/index.js.map +1 -1
- package/dist/remote/index.mjs +38 -38
- package/dist/remote/index.mjs.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -210,9 +210,14 @@ write path it takes over.
|
|
|
210
210
|
resolves with the latest response text. It aborts neither an in-flight
|
|
211
211
|
request nor an already-running handler, and it does not govern history
|
|
212
212
|
writes.
|
|
213
|
+
- `signal` — an `AbortSignal` forwarded to the client as `LLMCallOptions.signal`
|
|
214
|
+
on every `call`/`callWithTools` request the call makes, tool rounds
|
|
215
|
+
included. Distinct from `isCancelled`: this is what aborts the in-flight
|
|
216
|
+
request itself, rather than gating new work between steps.
|
|
213
217
|
|
|
214
|
-
`Charivo.userSay(text)` always passes
|
|
215
|
-
|
|
218
|
+
`Charivo.userSay(text)` always passes `callerOwnsHistory`, `isCancelled`, and
|
|
219
|
+
`signal` — see the latest-wins turn contract in the
|
|
220
|
+
[core README](../core/README.md#charivo).
|
|
216
221
|
|
|
217
222
|
Direct, manager-only use is otherwise unchanged: omit the options and
|
|
218
223
|
`generateResponse(...)` stays self-contained, appending the user message,
|
|
@@ -228,4 +233,7 @@ removes its own message and restores its own evictions only when nothing else
|
|
|
228
233
|
has written since; hold your own bound; and neither emit events nor call back
|
|
229
234
|
into `Charivo`. Honor `callerOwnsHistory` by suppressing every history write
|
|
230
235
|
for that call, and `isCancelled` by starting no new tool work and dropping
|
|
231
|
-
every further projected emission once it returns `true`.
|
|
236
|
+
every further projected emission once it returns `true`. Forward `signal` to
|
|
237
|
+
your client's calls if you want real request cancellation — the built-in
|
|
238
|
+
manager passes it through as `LLMCallOptions.signal`, but the option is
|
|
239
|
+
otherwise a no-op unless a manager forwards it.
|
package/dist/index.js
CHANGED
|
@@ -329,8 +329,9 @@ var LLMManager = class {
|
|
|
329
329
|
try {
|
|
330
330
|
const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(
|
|
331
331
|
apiMessages,
|
|
332
|
-
options.isCancelled ?? (() => false)
|
|
333
|
-
|
|
332
|
+
options.isCancelled ?? (() => false),
|
|
333
|
+
options.signal
|
|
334
|
+
) : await this.llmClient.call(apiMessages, { signal: options.signal });
|
|
334
335
|
if (!callerOwnsHistory) {
|
|
335
336
|
const responseMessage = ResponseMessageBuilder.create(
|
|
336
337
|
assistantMessage,
|
|
@@ -361,11 +362,11 @@ var LLMManager = class {
|
|
|
361
362
|
* no further tool call and issues no further request; it returns the latest
|
|
362
363
|
* text the model produced.
|
|
363
364
|
*/
|
|
364
|
-
async runToolLoop(apiMessages, isCancelled) {
|
|
365
|
+
async runToolLoop(apiMessages, isCancelled, signal) {
|
|
365
366
|
const callWithTools = this.llmClient.callWithTools.bind(this.llmClient);
|
|
366
367
|
const definitions = this.getRegisteredTools();
|
|
367
368
|
const working = this.buildToolLoopMessages(apiMessages);
|
|
368
|
-
let response = await callWithTools(working, definitions);
|
|
369
|
+
let response = await callWithTools(working, definitions, { signal });
|
|
369
370
|
for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {
|
|
370
371
|
const toolCalls = response.toolCalls ?? [];
|
|
371
372
|
if (toolCalls.length === 0) {
|
|
@@ -394,7 +395,9 @@ var LLMManager = class {
|
|
|
394
395
|
return response.content;
|
|
395
396
|
}
|
|
396
397
|
const isFinalRound = round === MAX_TOOL_ROUNDS - 1;
|
|
397
|
-
response = await callWithTools(working, isFinalRound ? [] : definitions
|
|
398
|
+
response = await callWithTools(working, isFinalRound ? [] : definitions, {
|
|
399
|
+
signal
|
|
400
|
+
});
|
|
398
401
|
}
|
|
399
402
|
return response.content;
|
|
400
403
|
}
|
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,IAAc,CAAA;AAEnB,IAAA,IAAI,OAAA,CAAQ,UAAU,KAAA,EAAO;A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MAC1C,IAAA,CAAK;AAAA,KACP;AACA,IAAA,OAAO,gBAAA,CAAiB,uBAAA,CAAwB,YAAA,EAAc,QAAQ,CAAA;AAAA,EACxE;AAAA,EAEQ,oBAAA,GAAkC;AACxC,IAAA,MAAM,eAAA,GAAkB,KAAK,cAAA,CAAe,SAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AAEA,IAAA,IAAI,eAAA,CAAgB,CAAC,CAAA,EAAG,IAAA,KAAS,WAAA,EAAa;AAC5C,MAAA,OAAO,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF,CAAA;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACqB;AACrB,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,OAAO,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACjE;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.js","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private writeCount = 0;\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n this.writeCount += 1;\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n const removed = this.history.pop();\n\n if (removed !== undefined) {\n this.writeCount += 1;\n }\n\n return removed;\n }\n\n /**\n * Remove the entry that *is* the given object and report whether it was\n * found. Reference identity, not id: overlapping turns can carry duplicate\n * ids, so an id lookup can drop another turn's message.\n */\n remove(message: Message): boolean {\n const index = this.history.indexOf(message);\n\n if (index === -1) {\n return false;\n }\n\n this.history.splice(index, 1);\n this.writeCount += 1;\n return true;\n }\n\n /** Reference-identity membership check, matching remove(). */\n contains(message: Message): boolean {\n return this.history.includes(message);\n }\n\n /** Put previously evicted entries back at the head, in their original order. */\n restoreToHead(messages: Message[]): void {\n if (messages.length === 0) {\n return;\n }\n\n this.history.unshift(...messages);\n this.writeCount += 1;\n }\n\n clear(): void {\n this.history = [];\n this.writeCount += 1;\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n /** Monotonic counter of the write attempts this store has taken. */\n getWriteCount(): number {\n return this.writeCount;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n this.writeCount += 1;\n }\n }\n\n /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order. pruneBatchSize is deliberately ignored:\n * the batch encodes a user/assistant pairing that a single caller-owned\n * append does not have, so batching would evict a message too many.\n */\n pruneToBound(): Message[] {\n if (\n this.maxMessages === undefined ||\n this.history.length <= this.maxMessages\n ) {\n return [];\n }\n\n const evicted = this.history.splice(\n 0,\n this.history.length - this.maxMessages,\n );\n this.writeCount += 1;\n return evicted;\n }\n\n /** Drop the leading character messages and report them in their original order. */\n removeLeadingCharacterMessages(): Message[] {\n let count = 0;\n // Stop before the last entry: the newest message is never a stranded reply.\n while (\n count < this.history.length - 1 &&\n this.history[count].type === \"character\"\n ) {\n count += 1;\n }\n\n if (count === 0) {\n return [];\n }\n\n const removed = this.history.splice(0, count);\n this.writeCount += 1;\n return removed;\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type GenerateResponseOptions,\n type HistoryRollback,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\n/**\n * Internal loop signal: a superseded turn skips the handler entirely, so there\n * is no tool turn to append and the round has to stop.\n */\ntype ToolCallOutcome = { executed: true; output: string } | { executed: false };\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Ensure the message is present in the history and return an undo handle.\n * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)\n * write both the user message and the reply through here, so the transcript\n * they present and the transcript the next prompt is built from are the\n * same one.\n */\n addToHistory(message: Message): HistoryRollback {\n // Only user messages are validated: the reply commit has never been, so\n // an empty model response is still stored exactly as produced.\n if (message.type === \"user\") {\n try {\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n }\n\n if (this.historyManager.contains(message)) {\n return () => {};\n }\n\n this.historyManager.add(message, { prune: false });\n const evicted = this.historyManager.pruneToBound();\n if (evicted.length > 0) {\n // Pruning a user message can strand its reply at the head. Only an\n // eviction-bearing prune drops it, so a deliberately character-first\n // history - a reply committed after clearHistory() - survives.\n evicted.push(...this.historyManager.removeLeadingCharacterMessages());\n }\n const writeCount = this.historyManager.getWriteCount();\n\n let spent = false;\n return () => {\n if (spent) {\n return;\n }\n spent = true;\n\n // Restore only what this call evicted, and only when nothing else has\n // written since: a clearHistory() plus re-append can leave the array\n // looking untouched while the app deliberately discarded everything.\n const untouched = this.historyManager.getWriteCount() === writeCount;\n this.historyManager.remove(message);\n\n if (untouched) {\n this.historyManager.restoreToHead(evicted);\n }\n };\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(\n message: Message,\n options: GenerateResponseOptions = {},\n ): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // The caller placed the message itself and commits the reply itself, so\n // this call writes nothing - not even a rollback on failure.\n const callerOwnsHistory = options.callerOwnsHistory === true;\n\n // Defer pruning until the assistant message is appended. On failure we\n // only remove this call's own user message, so older history must remain\n // intact during the API call.\n if (!callerOwnsHistory) {\n this.historyManager.add(message, { prune: false });\n }\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(\n apiMessages,\n options.isCancelled ?? (() => false),\n )\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n if (!callerOwnsHistory) {\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n }\n\n return assistantMessage;\n } catch (error) {\n // Remove this call's own message by identity: an overlapping turn may\n // have appended after it, and duplicate ids make a lookup ambiguous.\n if (!callerOwnsHistory) {\n this.historyManager.remove(message);\n }\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text, the\n * round cap is reached, or the turn is superseded. A superseded turn starts\n * no further tool call and issues no further request; it returns the latest\n * text the model produced.\n */\n private async runToolLoop(\n apiMessages: LLMApiMessage[],\n isCancelled: () => boolean,\n ): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n // An earlier handler in this same round can supersede the turn, and so\n // can a listener of the tool:call this executes - which is why the\n // outcome, not this check alone, decides whether the round continues.\n if (isCancelled()) {\n return response.content;\n }\n\n const outcome = await this.executeToolCall(toolCall, isCancelled);\n if (!outcome.executed) {\n return response.content;\n }\n\n working.push({\n role: \"tool\",\n content: outcome.output,\n toolCallId: toolCall.id,\n });\n }\n\n if (isCancelled()) {\n return response.content;\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n *\n * Returns \"not executed\" when the turn is superseded before the handler\n * starts: there is no tool turn to push, so the caller stops the round.\n */\n private async executeToolCall(\n toolCall: LLMToolCall,\n isCancelled: () => boolean,\n ): Promise<ToolCallOutcome> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n // Emission is synchronous, so a tool:call listener runs - and can start a\n // new turn - before the handler this event announces.\n if (isCancelled()) {\n return { executed: false };\n }\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return {\n executed: true,\n output: JSON.stringify(createToolFailureOutput(failure)),\n };\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(\n toolCall.name,\n outcome.snapshot,\n toolCall.id,\n isCancelled,\n );\n\n return { executed: true, output: outcome.serialized };\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter, and a superseded turn projects\n * nothing further - its avatar state would land on top of the live turn's.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n isCancelled: () => boolean,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n // Checked per projector, which is also the check for the projector that\n // just returned: any of them can supersede the turn.\n if (isCancelled()) {\n return;\n }\n\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n // Listeners run synchronously, so an earlier emission from this\n // same projector can supersede the turn mid-projection.\n if (isCancelled()) {\n return;\n }\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n // A projector that superseded the turn and then threw belongs to a\n // stale turn: it reports no error either.\n if (isCancelled()) {\n return;\n }\n\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
|
|
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,CAA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,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.js","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private writeCount = 0;\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n this.writeCount += 1;\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n const removed = this.history.pop();\n\n if (removed !== undefined) {\n this.writeCount += 1;\n }\n\n return removed;\n }\n\n /**\n * Remove the entry that *is* the given object and report whether it was\n * found. Reference identity, not id: overlapping turns can carry duplicate\n * ids, so an id lookup can drop another turn's message.\n */\n remove(message: Message): boolean {\n const index = this.history.indexOf(message);\n\n if (index === -1) {\n return false;\n }\n\n this.history.splice(index, 1);\n this.writeCount += 1;\n return true;\n }\n\n /** Reference-identity membership check, matching remove(). */\n contains(message: Message): boolean {\n return this.history.includes(message);\n }\n\n /** Put previously evicted entries back at the head, in their original order. */\n restoreToHead(messages: Message[]): void {\n if (messages.length === 0) {\n return;\n }\n\n this.history.unshift(...messages);\n this.writeCount += 1;\n }\n\n clear(): void {\n this.history = [];\n this.writeCount += 1;\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n /** Monotonic counter of the write attempts this store has taken. */\n getWriteCount(): number {\n return this.writeCount;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n this.writeCount += 1;\n }\n }\n\n /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order. pruneBatchSize is deliberately ignored:\n * the batch encodes a user/assistant pairing that a single caller-owned\n * append does not have, so batching would evict a message too many.\n */\n pruneToBound(): Message[] {\n if (\n this.maxMessages === undefined ||\n this.history.length <= this.maxMessages\n ) {\n return [];\n }\n\n const evicted = this.history.splice(\n 0,\n this.history.length - this.maxMessages,\n );\n this.writeCount += 1;\n return evicted;\n }\n\n /** Drop the leading character messages and report them in their original order. */\n removeLeadingCharacterMessages(): Message[] {\n let count = 0;\n // Stop before the last entry: the newest message is never a stranded reply.\n while (\n count < this.history.length - 1 &&\n this.history[count].type === \"character\"\n ) {\n count += 1;\n }\n\n if (count === 0) {\n return [];\n }\n\n const removed = this.history.splice(0, count);\n this.writeCount += 1;\n return removed;\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type GenerateResponseOptions,\n type HistoryRollback,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\n/**\n * Internal loop signal: a superseded turn skips the handler entirely, so there\n * is no tool turn to append and the round has to stop.\n */\ntype ToolCallOutcome = { executed: true; output: string } | { executed: false };\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Ensure the message is present in the history and return an undo handle.\n * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)\n * write both the user message and the reply through here, so the transcript\n * they present and the transcript the next prompt is built from are the\n * same one.\n */\n addToHistory(message: Message): HistoryRollback {\n // Only user messages are validated: the reply commit has never been, so\n // an empty model response is still stored exactly as produced.\n if (message.type === \"user\") {\n try {\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n }\n\n if (this.historyManager.contains(message)) {\n return () => {};\n }\n\n this.historyManager.add(message, { prune: false });\n const evicted = this.historyManager.pruneToBound();\n if (evicted.length > 0) {\n // Pruning a user message can strand its reply at the head. Only an\n // eviction-bearing prune drops it, so a deliberately character-first\n // history - a reply committed after clearHistory() - survives.\n evicted.push(...this.historyManager.removeLeadingCharacterMessages());\n }\n const writeCount = this.historyManager.getWriteCount();\n\n let spent = false;\n return () => {\n if (spent) {\n return;\n }\n spent = true;\n\n // Restore only what this call evicted, and only when nothing else has\n // written since: a clearHistory() plus re-append can leave the array\n // looking untouched while the app deliberately discarded everything.\n const untouched = this.historyManager.getWriteCount() === writeCount;\n this.historyManager.remove(message);\n\n if (untouched) {\n this.historyManager.restoreToHead(evicted);\n }\n };\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(\n message: Message,\n options: GenerateResponseOptions = {},\n ): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // The caller placed the message itself and commits the reply itself, so\n // this call writes nothing - not even a rollback on failure.\n const callerOwnsHistory = options.callerOwnsHistory === true;\n\n // Defer pruning until the assistant message is appended. On failure we\n // only remove this call's own user message, so older history must remain\n // intact during the API call.\n if (!callerOwnsHistory) {\n this.historyManager.add(message, { prune: false });\n }\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(\n apiMessages,\n options.isCancelled ?? (() => false),\n 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"]}
|
package/dist/index.mjs
CHANGED
|
@@ -327,8 +327,9 @@ var LLMManager = class {
|
|
|
327
327
|
try {
|
|
328
328
|
const assistantMessage = this.shouldUseToolLoop() ? await this.runToolLoop(
|
|
329
329
|
apiMessages,
|
|
330
|
-
options.isCancelled ?? (() => false)
|
|
331
|
-
|
|
330
|
+
options.isCancelled ?? (() => false),
|
|
331
|
+
options.signal
|
|
332
|
+
) : await this.llmClient.call(apiMessages, { signal: options.signal });
|
|
332
333
|
if (!callerOwnsHistory) {
|
|
333
334
|
const responseMessage = ResponseMessageBuilder.create(
|
|
334
335
|
assistantMessage,
|
|
@@ -359,11 +360,11 @@ var LLMManager = class {
|
|
|
359
360
|
* no further tool call and issues no further request; it returns the latest
|
|
360
361
|
* text the model produced.
|
|
361
362
|
*/
|
|
362
|
-
async runToolLoop(apiMessages, isCancelled) {
|
|
363
|
+
async runToolLoop(apiMessages, isCancelled, signal) {
|
|
363
364
|
const callWithTools = this.llmClient.callWithTools.bind(this.llmClient);
|
|
364
365
|
const definitions = this.getRegisteredTools();
|
|
365
366
|
const working = this.buildToolLoopMessages(apiMessages);
|
|
366
|
-
let response = await callWithTools(working, definitions);
|
|
367
|
+
let response = await callWithTools(working, definitions, { signal });
|
|
367
368
|
for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {
|
|
368
369
|
const toolCalls = response.toolCalls ?? [];
|
|
369
370
|
if (toolCalls.length === 0) {
|
|
@@ -392,7 +393,9 @@ var LLMManager = class {
|
|
|
392
393
|
return response.content;
|
|
393
394
|
}
|
|
394
395
|
const isFinalRound = round === MAX_TOOL_ROUNDS - 1;
|
|
395
|
-
response = await callWithTools(working, isFinalRound ? [] : definitions
|
|
396
|
+
response = await callWithTools(working, isFinalRound ? [] : definitions, {
|
|
397
|
+
signal
|
|
398
|
+
});
|
|
396
399
|
}
|
|
397
400
|
return response.content;
|
|
398
401
|
}
|
package/dist/index.mjs.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":[],"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,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AmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.mjs","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private writeCount = 0;\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n this.writeCount += 1;\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n const removed = this.history.pop();\n\n if (removed !== undefined) {\n this.writeCount += 1;\n }\n\n return removed;\n }\n\n /**\n * Remove the entry that *is* the given object and report whether it was\n * found. Reference identity, not id: overlapping turns can carry duplicate\n * ids, so an id lookup can drop another turn's message.\n */\n remove(message: Message): boolean {\n const index = this.history.indexOf(message);\n\n if (index === -1) {\n return false;\n }\n\n this.history.splice(index, 1);\n this.writeCount += 1;\n return true;\n }\n\n /** Reference-identity membership check, matching remove(). */\n contains(message: Message): boolean {\n return this.history.includes(message);\n }\n\n /** Put previously evicted entries back at the head, in their original order. */\n restoreToHead(messages: Message[]): void {\n if (messages.length === 0) {\n return;\n }\n\n this.history.unshift(...messages);\n this.writeCount += 1;\n }\n\n clear(): void {\n this.history = [];\n this.writeCount += 1;\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n /** Monotonic counter of the write attempts this store has taken. */\n getWriteCount(): number {\n return this.writeCount;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n this.writeCount += 1;\n }\n }\n\n /**\n * Prune in one step, down to the exact bound, and report what was\n * evicted in its original order. pruneBatchSize is deliberately ignored:\n * the batch encodes a user/assistant pairing that a single caller-owned\n * append does not have, so batching would evict a message too many.\n */\n pruneToBound(): Message[] {\n if (\n this.maxMessages === undefined ||\n this.history.length <= this.maxMessages\n ) {\n return [];\n }\n\n const evicted = this.history.splice(\n 0,\n this.history.length - this.maxMessages,\n );\n this.writeCount += 1;\n return evicted;\n }\n\n /** Drop the leading character messages and report them in their original order. */\n removeLeadingCharacterMessages(): Message[] {\n let count = 0;\n // Stop before the last entry: the newest message is never a stranded reply.\n while (\n count < this.history.length - 1 &&\n this.history[count].type === \"character\"\n ) {\n count += 1;\n }\n\n if (count === 0) {\n return [];\n }\n\n const removed = this.history.splice(0, count);\n this.writeCount += 1;\n return removed;\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Converted message shape. The role is a literal union so the result is also\n * assignable to the tool-calling `LLMMessage` union without casts.\n */\nexport interface LLMApiMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(messages: Message[]): LLMApiMessage[] {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): LLMApiMessage[] {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n assertToolResultObject,\n createToolFailureOutput,\n createToolRegistry,\n snapshotToolResult,\n toCharivoError,\n validateToolArguments,\n withToolTimeout,\n type CharivoEventEmitter,\n type GenerateResponseOptions,\n type HistoryRollback,\n type LLMManagerWithTools,\n type LLMMessage,\n type LLMToolCall,\n type ToolDefinition,\n type ToolRegistration,\n type ToolResultProjector,\n type ToolResultSnapshot,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter, type LLMApiMessage } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\nconst DEFAULT_TOOL_TIMEOUT_MS = 10_000;\n/** Tool rounds actually executed before the reply is forced to finish. */\nconst MAX_TOOL_ROUNDS = 3;\n\n/**\n * Internal loop signal: a superseded turn skips the handler entirely, so there\n * is no tool turn to append and the round has to stop.\n */\ntype ToolCallOutcome = { executed: true; output: string } | { executed: false };\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n tools?: ToolRegistration[];\n resultProjectors?: ToolResultProjector[];\n /** Appended to the character system prompt, tools path only. */\n toolInstructions?: string;\n defaultToolTimeoutMs?: number;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private readonly toolRegistry = createToolRegistry();\n private readonly resultProjectors: ToolResultProjector[];\n private readonly defaultToolTimeoutMs: number;\n private character: Character | null = null;\n private eventEmitter?: CharivoEventEmitter;\n private toolInstructions: string | null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n this.resultProjectors = options.resultProjectors ?? [];\n this.defaultToolTimeoutMs =\n options.defaultToolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;\n this.toolInstructions = options.toolInstructions ?? null;\n\n for (const tool of options.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n setEventEmitter(eventEmitter: CharivoEventEmitter): void {\n this.eventEmitter = eventEmitter;\n }\n\n registerTool(tool: ToolRegistration): void {\n this.toolRegistry.register(tool);\n }\n\n unregisterTool(name: string): void {\n this.toolRegistry.unregister(name);\n }\n\n getRegisteredTools(): ToolDefinition[] {\n return this.toolRegistry.getDefinitions();\n }\n\n /**\n * Set the tool instructions appended to the system prompt.\n * Pass null to clear them.\n */\n setToolInstructions(instructions: string | null): void {\n this.toolInstructions = instructions;\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Ensure the message is present in the history and return an undo handle.\n * Callers that own the turn (see GenerateResponseOptions.callerOwnsHistory)\n * write both the user message and the reply through here, so the transcript\n * they present and the transcript the next prompt is built from are the\n * same one.\n */\n addToHistory(message: Message): HistoryRollback {\n // Only user messages are validated: the reply commit has never been, so\n // an empty model response is still stored exactly as produced.\n if (message.type === \"user\") {\n try {\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n }\n\n if (this.historyManager.contains(message)) {\n return () => {};\n }\n\n this.historyManager.add(message, { prune: false });\n const evicted = this.historyManager.pruneToBound();\n if (evicted.length > 0) {\n // Pruning a user message can strand its reply at the head. Only an\n // eviction-bearing prune drops it, so a deliberately character-first\n // history - a reply committed after clearHistory() - survives.\n evicted.push(...this.historyManager.removeLeadingCharacterMessages());\n }\n const writeCount = this.historyManager.getWriteCount();\n\n let spent = false;\n return () => {\n if (spent) {\n return;\n }\n spent = true;\n\n // Restore only what this call evicted, and only when nothing else has\n // written since: a clearHistory() plus re-append can leave the array\n // looking untouched while the app deliberately discarded everything.\n const untouched = this.historyManager.getWriteCount() === writeCount;\n this.historyManager.remove(message);\n\n if (untouched) {\n this.historyManager.restoreToHead(evicted);\n }\n };\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(\n message: Message,\n options: GenerateResponseOptions = {},\n ): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // The caller placed the message itself and commits the reply itself, so\n // this call writes nothing - not even a rollback on failure.\n const callerOwnsHistory = options.callerOwnsHistory === true;\n\n // Defer pruning until the assistant message is appended. On failure we\n // only remove this call's own user message, so older history must remain\n // intact during the API call.\n if (!callerOwnsHistory) {\n this.historyManager.add(message, { prune: false });\n }\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = this.shouldUseToolLoop()\n ? await this.runToolLoop(\n apiMessages,\n options.isCancelled ?? (() => false),\n )\n : await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history.\n // Only the final assistant text is persisted: tool-call and tool-result\n // turns stay inside the loop so the stored history remains a plain\n // user/character transcript that other modalities can reuse.\n if (!callerOwnsHistory) {\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n }\n\n return assistantMessage;\n } catch (error) {\n // Remove this call's own message by identity: an overlapping turn may\n // have appended after it, and duplicate ids make a lookup ambiguous.\n if (!callerOwnsHistory) {\n this.historyManager.remove(message);\n }\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Tools engage only when both sides opt in: at least one registered tool and\n * a client that implements the optional tool-calling variant.\n */\n private shouldUseToolLoop(): boolean {\n return (\n this.toolRegistry.size() > 0 &&\n typeof this.llmClient.callWithTools === \"function\"\n );\n }\n\n /**\n * Run the tool-calling conversation until the model answers with text, the\n * round cap is reached, or the turn is superseded. A superseded turn starts\n * no further tool call and issues no further request; it returns the latest\n * text the model produced.\n */\n private async runToolLoop(\n apiMessages: LLMApiMessage[],\n isCancelled: () => boolean,\n ): Promise<string> {\n // Guarded by shouldUseToolLoop(): callWithTools exists on this path\n const callWithTools = this.llmClient.callWithTools!.bind(this.llmClient);\n const definitions = this.getRegisteredTools();\n const working = this.buildToolLoopMessages(apiMessages);\n\n let response = await callWithTools(working, definitions);\n\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const toolCalls = response.toolCalls ?? [];\n if (toolCalls.length === 0) {\n return response.content;\n }\n\n working.push({\n role: \"assistant\",\n content: response.content,\n toolCalls,\n });\n\n for (const toolCall of toolCalls) {\n // An earlier handler in this same round can supersede the turn, and so\n // can a listener of the tool:call this executes - which is why the\n // outcome, not this check alone, decides whether the round continues.\n if (isCancelled()) {\n return response.content;\n }\n\n const outcome = await this.executeToolCall(toolCall, isCancelled);\n if (!outcome.executed) {\n return response.content;\n }\n\n working.push({\n role: \"tool\",\n content: outcome.output,\n toolCallId: toolCall.id,\n });\n }\n\n if (isCancelled()) {\n return response.content;\n }\n\n // Terminal call offers no tools so the reply is text, not an unexecuted tool request.\n const isFinalRound = round === MAX_TOOL_ROUNDS - 1;\n response = await callWithTools(working, isFinalRound ? [] : definitions);\n }\n\n // Round cap reached: return the model's text instead of executing more tools\n return response.content;\n }\n\n /**\n * Seed the tool conversation, appending the tool instructions to the system\n * prompt. generateResponse validates the character first, so the tools path\n * always starts with a system message.\n */\n private buildToolLoopMessages(apiMessages: LLMApiMessage[]): LLMMessage[] {\n const messages: LLMMessage[] = [...apiMessages];\n const systemMessage = messages[0];\n\n if (this.toolInstructions && systemMessage.role === \"system\") {\n messages[0] = {\n role: \"system\",\n content: `${systemMessage.content}\\n\\n${this.toolInstructions}`,\n };\n }\n\n return messages;\n }\n\n /**\n * Execute one tool call and return the serialized output for its tool turn.\n * Every failure - unknown tool, invalid arguments, handler throw/timeout,\n * non-object result, unserializable output - becomes a failure output so the\n * reply always continues.\n *\n * Returns \"not executed\" when the turn is superseded before the handler\n * starts: there is no tool turn to push, so the caller stops the round.\n */\n private async executeToolCall(\n toolCall: LLMToolCall,\n isCancelled: () => boolean,\n ): Promise<ToolCallOutcome> {\n let outcome: ToolResultSnapshot;\n\n this.eventEmitter?.emit(\"tool:call\", {\n name: toolCall.name,\n args: toolCall.arguments,\n callId: toolCall.id,\n });\n\n // Emission is synchronous, so a tool:call listener runs - and can start a\n // new turn - before the handler this event announces.\n if (isCancelled()) {\n return { executed: false };\n }\n\n try {\n const tool = this.toolRegistry.get(toolCall.name);\n if (!tool) {\n throw new Error(`No LLM tool registered for \"${toolCall.name}\"`);\n }\n\n validateToolArguments(tool.definition, toolCall.arguments, \"LLM tool\");\n\n const result = await withToolTimeout(\n tool.handler(toolCall.arguments, {\n character: this.character,\n callId: toolCall.id,\n }),\n tool.timeoutMs ?? this.defaultToolTimeoutMs,\n tool.definition.name,\n \"LLM tool\",\n );\n\n assertToolResultObject(result, tool.definition.name, \"LLM tool\");\n\n // Serialize inside the failure boundary: outputs that cannot be\n // represented as JSON (bigint values, circular references, a `toJSON()`\n // yielding a non-object) degrade to a failure output instead of aborting\n // the reply.\n outcome = snapshotToolResult(result, tool.definition.name, \"LLM tool\");\n } catch (error) {\n const failure = toError(error);\n this.eventEmitter?.emit(\"tool:error\", {\n name: toolCall.name,\n error: failure,\n callId: toolCall.id,\n });\n return {\n executed: true,\n output: JSON.stringify(createToolFailureOutput(failure)),\n };\n }\n\n // The event and the projectors both receive the snapshot — the same value\n // the model's tool turn carries — so a tool result means one thing no\n // matter which modality executed it.\n this.eventEmitter?.emit(\"tool:result\", {\n name: toolCall.name,\n output: outcome.snapshot,\n callId: toolCall.id,\n });\n this.projectToolResult(\n toolCall.name,\n outcome.snapshot,\n toolCall.id,\n isCancelled,\n );\n\n return { executed: true, output: outcome.serialized };\n }\n\n /**\n * Turn a successful tool result into avatar-style events. Projection is\n * skipped entirely without an event emitter, and a superseded turn projects\n * nothing further - its avatar state would land on top of the live turn's.\n */\n private projectToolResult(\n name: string,\n output: Record<string, unknown>,\n callId: string,\n isCancelled: () => boolean,\n ): void {\n const eventEmitter = this.eventEmitter;\n if (!eventEmitter) {\n return;\n }\n\n for (const projector of this.resultProjectors) {\n // Checked per projector, which is also the check for the projector that\n // just returned: any of them can supersede the turn.\n if (isCancelled()) {\n return;\n }\n\n try {\n projector({\n name,\n output,\n callId,\n emit: (event, payload) => {\n // Listeners run synchronously, so an earlier emission from this\n // same projector can supersede the turn mid-projection.\n if (isCancelled()) {\n return;\n }\n eventEmitter.emit(event, payload);\n },\n });\n } catch (error) {\n // A projector that superseded the turn and then threw belongs to a\n // stale turn: it reports no error either.\n if (isCancelled()) {\n return;\n }\n\n eventEmitter.emit(\"llm:error\", {\n error: new Error(\n `LLM result projector failed for tool \"${name}\": ${toError(error).message}`,\n ),\n });\n }\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(messages: Message[]): LLMApiMessage[] {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManagerWithTools {\n return new LLMManager(llmClient, options);\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
|
|
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,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,I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AAM;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"]}
|
package/dist/remote/index.js
CHANGED
|
@@ -3,14 +3,17 @@
|
|
|
3
3
|
var core = require('@charivo/core');
|
|
4
4
|
|
|
5
5
|
// src/remote/index.ts
|
|
6
|
-
var REQUEST_TIMEOUT_MS = 3e4;
|
|
7
6
|
var RemoteLLMClient = class {
|
|
8
7
|
apiEndpoint;
|
|
9
8
|
constructor(config = {}) {
|
|
10
9
|
this.apiEndpoint = config.apiEndpoint || "/api/chat";
|
|
11
10
|
}
|
|
12
|
-
async call(messages) {
|
|
13
|
-
const data = await postChatRequest(
|
|
11
|
+
async call(messages, options) {
|
|
12
|
+
const data = await postChatRequest(
|
|
13
|
+
this.apiEndpoint,
|
|
14
|
+
{ messages },
|
|
15
|
+
options?.signal
|
|
16
|
+
);
|
|
14
17
|
if (!data.success) {
|
|
15
18
|
throw new core.CharivoProviderError(
|
|
16
19
|
data.error || "Failed to generate response"
|
|
@@ -22,8 +25,12 @@ var RemoteLLMClient = class {
|
|
|
22
25
|
* Tools are sent as-is, including an empty array: the server is expected to
|
|
23
26
|
* treat an empty list as no tools for that turn.
|
|
24
27
|
*/
|
|
25
|
-
async callWithTools(messages, tools) {
|
|
26
|
-
const data = await postChatRequest(
|
|
28
|
+
async callWithTools(messages, tools, options) {
|
|
29
|
+
const data = await postChatRequest(
|
|
30
|
+
this.apiEndpoint,
|
|
31
|
+
{ messages, tools },
|
|
32
|
+
options?.signal
|
|
33
|
+
);
|
|
27
34
|
if (!isPlainObject(data)) {
|
|
28
35
|
throw new core.CharivoProviderError("Malformed response body");
|
|
29
36
|
}
|
|
@@ -47,8 +54,8 @@ var RemoteLLMClient = class {
|
|
|
47
54
|
function createRemoteLLMClient(config) {
|
|
48
55
|
return new RemoteLLMClient(config);
|
|
49
56
|
}
|
|
50
|
-
async function postChatRequest(apiEndpoint, body) {
|
|
51
|
-
|
|
57
|
+
async function postChatRequest(apiEndpoint, body, signal) {
|
|
58
|
+
return core.fetchWithTimeout(
|
|
52
59
|
apiEndpoint,
|
|
53
60
|
{
|
|
54
61
|
method: "POST",
|
|
@@ -57,15 +64,30 @@ async function postChatRequest(apiEndpoint, body) {
|
|
|
57
64
|
},
|
|
58
65
|
body: JSON.stringify(body)
|
|
59
66
|
},
|
|
60
|
-
|
|
67
|
+
{
|
|
68
|
+
timeoutMessage: `LLM request timed out after ${core.DEFAULT_FETCH_TIMEOUT_MS}ms`,
|
|
69
|
+
failureMessage: "LLM request failed",
|
|
70
|
+
signal
|
|
71
|
+
},
|
|
72
|
+
// Consume the body while cancellation is still wired up, so an abort
|
|
73
|
+
// during a slow/streaming response body still cancels the request.
|
|
74
|
+
async (response) => {
|
|
75
|
+
if (!response.ok) {
|
|
76
|
+
let errorData = { error: "Unknown error" };
|
|
77
|
+
try {
|
|
78
|
+
errorData = await response.json();
|
|
79
|
+
} catch (parseError) {
|
|
80
|
+
if (!(parseError instanceof SyntaxError)) {
|
|
81
|
+
throw parseError;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
throw new core.CharivoProviderError(
|
|
85
|
+
`API call failed: ${errorData.error || response.statusText}`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
return response.json();
|
|
89
|
+
}
|
|
61
90
|
);
|
|
62
|
-
if (!response.ok) {
|
|
63
|
-
const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
64
|
-
throw new core.CharivoProviderError(
|
|
65
|
-
`API call failed: ${errorData.error || response.statusText}`
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
return response.json();
|
|
69
91
|
}
|
|
70
92
|
function parseToolCalls(value) {
|
|
71
93
|
if (value === void 0) {
|
|
@@ -106,28 +128,6 @@ function parseToolCall(value) {
|
|
|
106
128
|
function isPlainObject(value) {
|
|
107
129
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
108
130
|
}
|
|
109
|
-
async function fetchWithTimeout(input, init, timeoutMessage) {
|
|
110
|
-
const controller = new AbortController();
|
|
111
|
-
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
112
|
-
try {
|
|
113
|
-
return await fetch(input, {
|
|
114
|
-
...init,
|
|
115
|
-
signal: controller.signal
|
|
116
|
-
});
|
|
117
|
-
} catch (error) {
|
|
118
|
-
if (isAbortError(error)) {
|
|
119
|
-
throw new core.CharivoTimeoutError(timeoutMessage, { cause: error });
|
|
120
|
-
}
|
|
121
|
-
throw new core.CharivoTransportError("LLM request failed", {
|
|
122
|
-
cause: error instanceof Error ? error : void 0
|
|
123
|
-
});
|
|
124
|
-
} finally {
|
|
125
|
-
clearTimeout(timeoutId);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
function isAbortError(error) {
|
|
129
|
-
return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
|
|
130
|
-
}
|
|
131
131
|
|
|
132
132
|
exports.createRemoteLLMClient = createRemoteLLMClient;
|
|
133
133
|
//# sourceMappingURL=index.js.map
|
package/dist/remote/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/remote/index.ts"],"names":["CharivoProviderError","
|
|
1
|
+
{"version":3,"sources":["../../src/remote/index.ts"],"names":["CharivoProviderError","fetchWithTimeout","DEFAULT_FETCH_TIMEOUT_MS"],"mappings":";;;;;AA2BA,IAAM,kBAAN,MAA2C;AAAA,EACjC,WAAA;AAAA,EAER,WAAA,CAAY,MAAA,GAA0B,EAAC,EAAG;AACxC,IAAA,IAAA,CAAK,WAAA,GAAc,OAAO,WAAA,IAAe,WAAA;AAAA,EAC3C;AAAA,EAEA,MAAM,IAAA,CACJ,QAAA,EACA,OAAA,EACiB;AACjB,IAAA,MAAM,OAAO,MAAM,eAAA;AAAA,MACjB,IAAA,CAAK,WAAA;AAAA,MACL,EAAE,QAAA,EAAS;AAAA,MACX,OAAA,EAAS;AAAA,KACX;AAEA,IAAA,IAAI,CAAC,KAAK,OAAA,EAAS;AACjB,MAAA,MAAM,IAAIA,yBAAA;AAAA,QACR,KAAK,KAAA,IAAS;AAAA,OAChB;AAAA,IACF;AAEA,IAAA,OAAO,KAAK,OAAA,IAAW,EAAA;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EACA,OAAA,EAC0B;AAC1B,IAAA,MAAM,OAAO,MAAM,eAAA;AAAA,MACjB,IAAA,CAAK,WAAA;AAAA,MACL,EAAE,UAAU,KAAA,EAAM;AAAA,MAClB,OAAA,EAAS;AAAA,KACX;AAIA,IAAA,IAAI,CAAC,aAAA,CAAc,IAAe,CAAA,EAAG;AACnC,MAAA,MAAM,IAAIA,0BAAqB,yBAAyB,CAAA;AAAA,IAC1D;AAGA,IAAA,IAAI,IAAA,CAAK,YAAY,IAAA,EAAM;AACzB,MAAA,MAAM,IAAIA,yBAAA;AAAA,QACR,KAAK,KAAA,IAAS;AAAA,OAChB;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AA,EAAW,IAAA,EAAK;AACrC;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E","file":"index.js","sourcesContent":["import {\n CharivoProviderError,\n DEFAULT_FETCH_TIMEOUT_MS,\n fetchWithTimeout,\n type LLMCallOptions,\n type LLMClient,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\n\nexport interface RemoteLLMConfig {\n apiEndpoint?: string;\n}\n\n/** Server reply as received; each field is validated where it is read. */\ninterface RemoteLLMResponseBody {\n success?: boolean;\n error?: string;\n message?: string;\n toolCalls?: unknown;\n}\n\n/**\n * Remote LLM Client - stateless client that calls the server API\n */\nclass RemoteLLMClient implements LLMClient {\n private apiEndpoint: string;\n\n constructor(config: RemoteLLMConfig = {}) {\n this.apiEndpoint = config.apiEndpoint || \"/api/chat\";\n }\n\n async call(\n messages: Array<{ role: string; content: string }>,\n options?: LLMCallOptions,\n ): Promise<string> {\n const data = await postChatRequest(\n this.apiEndpoint,\n { messages },\n options?.signal,\n );\n\n if (!data.success) {\n throw new CharivoProviderError(\n data.error || \"Failed to generate response\",\n );\n }\n\n return data.message || \"\";\n }\n\n /**\n * Tools are sent as-is, including an empty array: the server is expected to\n * treat an empty list as no tools for that turn.\n */\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n options?: LLMCallOptions,\n ): Promise<LLMToolResponse> {\n const data = await postChatRequest(\n this.apiEndpoint,\n { messages, tools },\n options?.signal,\n );\n\n // Cast through `unknown` so the guard doesn't narrow `data`'s declared shape\n // away to a bare index signature - the fields below still need their types.\n if (!isPlainObject(data as unknown)) {\n throw new CharivoProviderError(\"Malformed response body\");\n }\n\n // `!== true` keeps the missing/false error path and rejects non-boolean flags.\n if (data.success !== true) {\n throw new CharivoProviderError(\n data.error || \"Failed to generate response\",\n );\n }\n\n if (typeof data.message !== \"string\") {\n throw new CharivoProviderError(\n 'LLM response field \"message\" must be a string',\n );\n }\n\n const toolCalls = parseToolCalls(data.toolCalls);\n\n return {\n content: data.message,\n ...(toolCalls ? { toolCalls } : {}),\n };\n }\n}\n\nexport function createRemoteLLMClient(config?: RemoteLLMConfig): LLMClient {\n return new RemoteLLMClient(config);\n}\n\nasync function postChatRequest(\n apiEndpoint: string,\n body: unknown,\n signal?: AbortSignal,\n): Promise<RemoteLLMResponseBody> {\n return fetchWithTimeout(\n apiEndpoint,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n {\n timeoutMessage: `LLM request timed out after ${DEFAULT_FETCH_TIMEOUT_MS}ms`,\n failureMessage: \"LLM request failed\",\n signal,\n },\n // Consume the body while cancellation is still wired up, so an abort\n // during a slow/streaming response body still cancels the request.\n async (response) => {\n if (!response.ok) {\n let errorData: { error?: string } = { error: \"Unknown error\" };\n try {\n errorData = await response.json();\n } catch (parseError) {\n // Only a malformed/non-JSON error body falls back to the default\n // message. Anything else (e.g. an abort or timeout mid-read)\n // propagates as-is so fetchWithTimeout classifies it, instead of\n // masking it behind a generic provider error.\n if (!(parseError instanceof SyntaxError)) {\n throw parseError;\n }\n }\n throw new CharivoProviderError(\n `API call failed: ${errorData.error || response.statusText}`,\n );\n }\n\n return response.json() as Promise<RemoteLLMResponseBody>;\n },\n );\n}\n\nfunction parseToolCalls(value: unknown): LLMToolCall[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value)) {\n throw new CharivoProviderError(\n 'LLM response field \"toolCalls\" must be an array',\n );\n }\n\n if (value.length === 0) {\n return undefined;\n }\n\n return value.map(parseToolCall);\n}\n\nfunction parseToolCall(value: unknown): LLMToolCall {\n if (!isPlainObject(value)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const { id, name, arguments: args } = value;\n\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"name\"`,\n );\n }\n\n if (!isPlainObject(args)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"arguments\" that are not a JSON object`,\n );\n }\n\n return { id, name, arguments: args };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
package/dist/remote/index.mjs
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
import { CharivoProviderError,
|
|
1
|
+
import { CharivoProviderError, fetchWithTimeout, DEFAULT_FETCH_TIMEOUT_MS } from '@charivo/core';
|
|
2
2
|
|
|
3
3
|
// src/remote/index.ts
|
|
4
|
-
var REQUEST_TIMEOUT_MS = 3e4;
|
|
5
4
|
var RemoteLLMClient = class {
|
|
6
5
|
apiEndpoint;
|
|
7
6
|
constructor(config = {}) {
|
|
8
7
|
this.apiEndpoint = config.apiEndpoint || "/api/chat";
|
|
9
8
|
}
|
|
10
|
-
async call(messages) {
|
|
11
|
-
const data = await postChatRequest(
|
|
9
|
+
async call(messages, options) {
|
|
10
|
+
const data = await postChatRequest(
|
|
11
|
+
this.apiEndpoint,
|
|
12
|
+
{ messages },
|
|
13
|
+
options?.signal
|
|
14
|
+
);
|
|
12
15
|
if (!data.success) {
|
|
13
16
|
throw new CharivoProviderError(
|
|
14
17
|
data.error || "Failed to generate response"
|
|
@@ -20,8 +23,12 @@ var RemoteLLMClient = class {
|
|
|
20
23
|
* Tools are sent as-is, including an empty array: the server is expected to
|
|
21
24
|
* treat an empty list as no tools for that turn.
|
|
22
25
|
*/
|
|
23
|
-
async callWithTools(messages, tools) {
|
|
24
|
-
const data = await postChatRequest(
|
|
26
|
+
async callWithTools(messages, tools, options) {
|
|
27
|
+
const data = await postChatRequest(
|
|
28
|
+
this.apiEndpoint,
|
|
29
|
+
{ messages, tools },
|
|
30
|
+
options?.signal
|
|
31
|
+
);
|
|
25
32
|
if (!isPlainObject(data)) {
|
|
26
33
|
throw new CharivoProviderError("Malformed response body");
|
|
27
34
|
}
|
|
@@ -45,8 +52,8 @@ var RemoteLLMClient = class {
|
|
|
45
52
|
function createRemoteLLMClient(config) {
|
|
46
53
|
return new RemoteLLMClient(config);
|
|
47
54
|
}
|
|
48
|
-
async function postChatRequest(apiEndpoint, body) {
|
|
49
|
-
|
|
55
|
+
async function postChatRequest(apiEndpoint, body, signal) {
|
|
56
|
+
return fetchWithTimeout(
|
|
50
57
|
apiEndpoint,
|
|
51
58
|
{
|
|
52
59
|
method: "POST",
|
|
@@ -55,15 +62,30 @@ async function postChatRequest(apiEndpoint, body) {
|
|
|
55
62
|
},
|
|
56
63
|
body: JSON.stringify(body)
|
|
57
64
|
},
|
|
58
|
-
|
|
65
|
+
{
|
|
66
|
+
timeoutMessage: `LLM request timed out after ${DEFAULT_FETCH_TIMEOUT_MS}ms`,
|
|
67
|
+
failureMessage: "LLM request failed",
|
|
68
|
+
signal
|
|
69
|
+
},
|
|
70
|
+
// Consume the body while cancellation is still wired up, so an abort
|
|
71
|
+
// during a slow/streaming response body still cancels the request.
|
|
72
|
+
async (response) => {
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
let errorData = { error: "Unknown error" };
|
|
75
|
+
try {
|
|
76
|
+
errorData = await response.json();
|
|
77
|
+
} catch (parseError) {
|
|
78
|
+
if (!(parseError instanceof SyntaxError)) {
|
|
79
|
+
throw parseError;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
throw new CharivoProviderError(
|
|
83
|
+
`API call failed: ${errorData.error || response.statusText}`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
return response.json();
|
|
87
|
+
}
|
|
59
88
|
);
|
|
60
|
-
if (!response.ok) {
|
|
61
|
-
const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
62
|
-
throw new CharivoProviderError(
|
|
63
|
-
`API call failed: ${errorData.error || response.statusText}`
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
return response.json();
|
|
67
89
|
}
|
|
68
90
|
function parseToolCalls(value) {
|
|
69
91
|
if (value === void 0) {
|
|
@@ -104,28 +126,6 @@ function parseToolCall(value) {
|
|
|
104
126
|
function isPlainObject(value) {
|
|
105
127
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
106
128
|
}
|
|
107
|
-
async function fetchWithTimeout(input, init, timeoutMessage) {
|
|
108
|
-
const controller = new AbortController();
|
|
109
|
-
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
110
|
-
try {
|
|
111
|
-
return await fetch(input, {
|
|
112
|
-
...init,
|
|
113
|
-
signal: controller.signal
|
|
114
|
-
});
|
|
115
|
-
} catch (error) {
|
|
116
|
-
if (isAbortError(error)) {
|
|
117
|
-
throw new CharivoTimeoutError(timeoutMessage, { cause: error });
|
|
118
|
-
}
|
|
119
|
-
throw new CharivoTransportError("LLM request failed", {
|
|
120
|
-
cause: error instanceof Error ? error : void 0
|
|
121
|
-
});
|
|
122
|
-
} finally {
|
|
123
|
-
clearTimeout(timeoutId);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
function isAbortError(error) {
|
|
127
|
-
return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
|
|
128
|
-
}
|
|
129
129
|
|
|
130
130
|
export { createRemoteLLMClient };
|
|
131
131
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/remote/index.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../../src/remote/index.ts"],"names":[],"mappings":";;;AA2BA,IAAM,kBAAN,MAA2C;AAAA,EACjC,WAAA;AAAA,EAER,WAAA,CAAY,MAAA,GAA0B,EAAC,EAAG;AACxC,IAAA,IAAA,CAAK,WAAA,GAAc,OAAO,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WAAW,CAAA,EAAG;AACtB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA,CAAM,IAAI,aAAa,CAAA;AAChC;AAEA,SAAS,cAAc,KAAA,EAA6B;AAClD,EAAA,IAAI,CAAC,aAAA,CAAc,KAAK,CAAA,EAAG;AACzB,IAAA,MAAM,IAAI,qBAAqB,iCAAiC,CAAA;AAAA,EAClE;AAEA,EAAA,MAAM,EAAE,EAAA,EAAI,IAAA,EAAM,SAAA,EAAW,MAAK,GAAI,KAAA;AAEtC,EAAA,IAAI,OAAO,EAAA,KAAO,QAAA,IAAY,EAAA,CAAG,WAAW,CAAA,EAAG;AAC7C,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,CAAK,WAAW,CAAA,EAAG;AACjD,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR,kBAAkB,EAAE,CAAA,sCAAA;AAAA,KACtB;AAAA,EACF;AAEA,EAAA,IAAI,CAAC,aAAA,CAAc,IAAI,CAAA,EAAG;AACxB,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR,kBAAkB,IAAI,CAAA,4CAAA;AAAA,KACxB;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,SAAA,EAAW,IAAA,EAAK;AACrC;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E","file":"index.mjs","sourcesContent":["import {\n CharivoProviderError,\n DEFAULT_FETCH_TIMEOUT_MS,\n fetchWithTimeout,\n type LLMCallOptions,\n type LLMClient,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\n\nexport interface RemoteLLMConfig {\n apiEndpoint?: string;\n}\n\n/** Server reply as received; each field is validated where it is read. */\ninterface RemoteLLMResponseBody {\n success?: boolean;\n error?: string;\n message?: string;\n toolCalls?: unknown;\n}\n\n/**\n * Remote LLM Client - stateless client that calls the server API\n */\nclass RemoteLLMClient implements LLMClient {\n private apiEndpoint: string;\n\n constructor(config: RemoteLLMConfig = {}) {\n this.apiEndpoint = config.apiEndpoint || \"/api/chat\";\n }\n\n async call(\n messages: Array<{ role: string; content: string }>,\n options?: LLMCallOptions,\n ): Promise<string> {\n const data = await postChatRequest(\n this.apiEndpoint,\n { messages },\n options?.signal,\n );\n\n if (!data.success) {\n throw new CharivoProviderError(\n data.error || \"Failed to generate response\",\n );\n }\n\n return data.message || \"\";\n }\n\n /**\n * Tools are sent as-is, including an empty array: the server is expected to\n * treat an empty list as no tools for that turn.\n */\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n options?: LLMCallOptions,\n ): Promise<LLMToolResponse> {\n const data = await postChatRequest(\n this.apiEndpoint,\n { messages, tools },\n options?.signal,\n );\n\n // Cast through `unknown` so the guard doesn't narrow `data`'s declared shape\n // away to a bare index signature - the fields below still need their types.\n if (!isPlainObject(data as unknown)) {\n throw new CharivoProviderError(\"Malformed response body\");\n }\n\n // `!== true` keeps the missing/false error path and rejects non-boolean flags.\n if (data.success !== true) {\n throw new CharivoProviderError(\n data.error || \"Failed to generate response\",\n );\n }\n\n if (typeof data.message !== \"string\") {\n throw new CharivoProviderError(\n 'LLM response field \"message\" must be a string',\n );\n }\n\n const toolCalls = parseToolCalls(data.toolCalls);\n\n return {\n content: data.message,\n ...(toolCalls ? { toolCalls } : {}),\n };\n }\n}\n\nexport function createRemoteLLMClient(config?: RemoteLLMConfig): LLMClient {\n return new RemoteLLMClient(config);\n}\n\nasync function postChatRequest(\n apiEndpoint: string,\n body: unknown,\n signal?: AbortSignal,\n): Promise<RemoteLLMResponseBody> {\n return fetchWithTimeout(\n apiEndpoint,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n {\n timeoutMessage: `LLM request timed out after ${DEFAULT_FETCH_TIMEOUT_MS}ms`,\n failureMessage: \"LLM request failed\",\n signal,\n },\n // Consume the body while cancellation is still wired up, so an abort\n // during a slow/streaming response body still cancels the request.\n async (response) => {\n if (!response.ok) {\n let errorData: { error?: string } = { error: \"Unknown error\" };\n try {\n errorData = await response.json();\n } catch (parseError) {\n // Only a malformed/non-JSON error body falls back to the default\n // message. Anything else (e.g. an abort or timeout mid-read)\n // propagates as-is so fetchWithTimeout classifies it, instead of\n // masking it behind a generic provider error.\n if (!(parseError instanceof SyntaxError)) {\n throw parseError;\n }\n }\n throw new CharivoProviderError(\n `API call failed: ${errorData.error || response.statusText}`,\n );\n }\n\n return response.json() as Promise<RemoteLLMResponseBody>;\n },\n );\n}\n\nfunction parseToolCalls(value: unknown): LLMToolCall[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value)) {\n throw new CharivoProviderError(\n 'LLM response field \"toolCalls\" must be an array',\n );\n }\n\n if (value.length === 0) {\n return undefined;\n }\n\n return value.map(parseToolCall);\n}\n\nfunction parseToolCall(value: unknown): LLMToolCall {\n if (!isPlainObject(value)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const { id, name, arguments: args } = value;\n\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"name\"`,\n );\n }\n\n if (!isPlainObject(args)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"arguments\" that are not a JSON object`,\n );\n }\n\n return { id, name, arguments: args };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@charivo/llm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "LLM manager and browser adapters for Charivo",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"openai": "^4.47.1",
|
|
37
|
-
"@charivo/core": "^0.
|
|
37
|
+
"@charivo/core": "^0.27.0"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"tsup": "^8.5.0",
|