lemura 1.0.0 → 1.2.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/CHANGELOG.md +38 -0
- package/README.md +14 -2
- package/dist/adapters/index.d.mts +2 -3
- package/dist/adapters/index.d.ts +2 -3
- package/dist/adapters/index.js +5 -5
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/index.mjs +5 -5
- package/dist/adapters/index.mjs.map +1 -1
- package/dist/agent-D6uhF-CZ.d.mts +248 -0
- package/dist/agent-DxRd93wl.d.ts +248 -0
- package/dist/context/index.d.mts +2 -3
- package/dist/context/index.d.ts +2 -3
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs.map +1 -1
- package/dist/index.d.mts +257 -9
- package/dist/index.d.ts +257 -9
- package/dist/index.js +1599 -217
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1592 -218
- package/dist/index.mjs.map +1 -1
- package/dist/{adapters-BnG0LEYD.d.mts → storage-CG3nTa6o.d.mts} +127 -2
- package/dist/{adapters-BSkhv5ac.d.ts → storage-DBt_q0wO.d.ts} +127 -2
- package/dist/tools/index.d.mts +125 -5
- package/dist/tools/index.d.ts +125 -5
- package/dist/tools/index.js +278 -7
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/index.mjs +277 -8
- package/dist/tools/index.mjs.map +1 -1
- package/dist/types/index.d.mts +18 -69
- package/dist/types/index.d.ts +18 -69
- package/dist/types/index.js +21 -0
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs +19 -1
- package/dist/types/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/storage-BGu4Loao.d.ts +0 -121
- package/dist/storage-DMcliVVj.d.mts +0 -121
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/errors.ts","../../src/context/ContextManager.ts","../../src/context/SandwichCompressionStrategy.ts","../../src/context/HistoryCompressionStrategy.ts","../../src/context/ShortTermMemoryRegistry.ts","../../src/context/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CAAK,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,GAAA,CAAI,EAAA,EAAwB,OAAA,EAAc,QAAA,EAAqD;AACjG,IAAA,MAAM,UAAA,GAAa,MAAMA,UAAAA,EAAW;AACpC,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAA,EAAY,QAAA,KAAa,MAAA,GAAY,EAAE,OAAA,EAAS,QAAA,EAAS,GAAI,EAAE,OAAA,EAAS,CAAA;AACvF,IAAA,OAAO,UAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,OAAO,EAAA,EAA2B;AACpC,IAAA,IAAA,CAAK,KAAA,CAAM,OAAO,EAAE,CAAA;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,WAAA,GAAgC;AAClC,IAAA,OAAO,IAAA;AAAA,EACX;AACJ","file":"index.mjs","sourcesContent":["/**\n * Base class for all custom errors thrown by lemura.\n *\n * @example\n * throw new LemuraError('Something went wrong', 'UNKNOWN_ERROR');\n */\nexport class LemuraError extends Error {\n /**\n * @param message - The error message\n * @param code - The error code for programmatic handling\n * @param problem - A clear description of the problem for the end user\n * @param hints - A list of suggestions to resolve the issue\n */\n constructor(\n message: string,\n public readonly code: string,\n public readonly problem?: string,\n public readonly hints: string[] = []\n ) {\n super(message);\n this.name = 'LemuraError';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Error thrown when context exceeds max tokens and cannot be compressed further */\nexport class LemuraContextOverflowError extends LemuraError {\n constructor(message: string) {\n super(message, 'CONTEXT_OVERFLOW');\n this.name = 'LemuraContextOverflowError';\n }\n}\n\n/** Error thrown when a requested tool is not found in the registry */\nexport class LemuraToolNotFoundError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_NOT_FOUND');\n this.name = 'LemuraToolNotFoundError';\n }\n}\n\n/** Error thrown when an adapter encounters an API or formatting issue */\nexport class LemuraAdapterError extends LemuraError {\n constructor(\n message: string,\n code = 'ADAPTER_ERROR',\n public cause?: any,\n problem?: string,\n hints: string[] = []\n ) {\n super(message, code, problem, hints);\n this.name = 'LemuraAdapterError';\n }\n}\n\n/** Error thrown when a skill cannot be parsed or injected */\nexport class LemuraSkillInjectionError extends LemuraError {\n constructor(message: string) {\n super(message, 'SKILL_INJECTION_FAILED');\n this.name = 'LemuraSkillInjectionError';\n }\n}\n\n/** Error thrown when the ReAct loop exceeds the configured max iterations */\nexport class LemuraMaxIterationsError extends LemuraError {\n constructor(message: string) {\n super(message, 'MAX_ITERATIONS_EXCEEDED');\n this.name = 'LemuraMaxIterationsError';\n }\n}\n\n/** Error thrown when tool parameters fail JSON schema validation */\nexport class LemuraToolValidationError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_VALIDATION_FAILED');\n this.name = 'LemuraToolValidationError';\n }\n}\n\n/** Error thrown when a tool execute function exceeds its timeout */\nexport class LemuraToolTimeoutError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_TIMEOUT');\n this.name = 'LemuraToolTimeoutError';\n }\n}\n","import { ContextWindow, IContextStrategy, LemuraContextOverflowError } from '../types/index.js';\n\n/**\n * Orchestrates a stack of IContextStrategy implementations to keep the\n * token count within the maxTokens limit.\n */\nexport class ContextManager {\n private strategies: IContextStrategy[] = [];\n\n /**\n * Registers a new compression or pre-turn strategy and sorts the stack by priority.\n *\n * @param strategy - The strategy implementation to register\n */\n registerStrategy(strategy: IContextStrategy): void {\n this.strategies.push(strategy);\n this.strategies.sort((a, b) => a.priority - b.priority);\n }\n\n /**\n * Applies all registered strategies that return true for `shouldApply()`\n * until the context token count is safely below the maximum budget.\n *\n * @param context - The context window to prepare\n * @param safetyMargin - Modifier applied to maxTokens (default: 0.95 -> 95%)\n * @returns A new ContextWindow object potentially compressed\n * @throws {LemuraContextOverflowError} If the context is still over maxTokens after all strategies\n */\n async prepare(context: ContextWindow, safetyMargin = 0.95): Promise<ContextWindow> {\n let currentCtx = { ...context, turns: [...context.turns] };\n const targetTokenCount = currentCtx.maxTokens * safetyMargin;\n\n for (const strategy of this.strategies) {\n // If we are below the limit and it's not a pre-turn non-reducing strategy, skip it.\n // E.g., SummaryInjectionStrategy might still want to run.\n // But purely compression ones drop out early in our base architecture if they choose in `shouldApply`.\n if (strategy.shouldApply(currentCtx)) {\n currentCtx = await strategy.apply(currentCtx);\n }\n }\n\n if (currentCtx.tokenCount > currentCtx.maxTokens) {\n throw new LemuraContextOverflowError(\n `Context overflowed: ${currentCtx.tokenCount} tokens > ${currentCtx.maxTokens}`\n );\n }\n\n return currentCtx;\n }\n}\n","import { ContextWindow, IContextStrategy, IProviderAdapter, Turn } from '../types/index.js';\n\nexport interface SandwichCompressionConfig {\n preserveFirst: number;\n preserveLast: number;\n triggerThreshold: number; // e.g. 0.8\n}\n\n/**\n * Sandwich compression preserves the beginning and end of the conversation,\n * replacing the middle with a generated summary.\n */\nexport class SandwichCompressionStrategy implements IContextStrategy {\n readonly name = 'sandwich_compression';\n readonly priority = 20;\n\n constructor(\n private adapter: IProviderAdapter,\n private config: SandwichCompressionConfig\n ) { }\n\n shouldApply(ctx: ContextWindow): boolean {\n return (\n ctx.tokenCount >= ctx.maxTokens * this.config.triggerThreshold &&\n ctx.turns.length > this.config.preserveFirst + this.config.preserveLast\n );\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n const { preserveFirst, preserveLast } = this.config;\n\n const head = ctx.turns.slice(0, preserveFirst);\n const tail = ctx.turns.slice(ctx.turns.length - preserveLast);\n const middle = ctx.turns.slice(preserveFirst, ctx.turns.length - preserveLast);\n\n const middleText = middle.map(t => `${t.role}: ${JSON.stringify(t.content)}`).join('\\n');\n\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `Summarize the following conversation history briefly:\\n${middleText}`\n }]\n });\n\n const summaryStr = summaryResponse.content;\n\n const newCompressionSummary = ctx.compressionSummary\n ? `${ctx.compressionSummary}\\n${summaryStr}`\n : summaryStr;\n\n const summaryTurn: Turn = {\n role: 'system',\n content: `[COMPRESSED HISTORY SUMMARY]\\n${newCompressionSummary}`,\n tokenCount: this.adapter.estimateTokens(newCompressionSummary),\n turnIndex: -1,\n compressed: true,\n };\n\n const newTurns = [...head, summaryTurn, ...tail];\n const newTokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) +\n this.adapter.estimateTokens(ctx.systemPrompt) +\n this.adapter.estimateTokens(ctx.scratchpad);\n\n return {\n ...ctx,\n turns: newTurns,\n tokenCount: newTokenCount,\n compressionSummary: newCompressionSummary,\n };\n }\n\n /**\n * Applies sandwich compression specifically to a Short Term Memory item's content.\n * Implements a 3-layer pipeline: Pre-Layer (encoding), Core Layer (dense summary), Post-Layer (refinement cues).\n * \n * @param content - The heavy text content to compress\n * @param instructions - Guiding instructions for the core layer summary\n * @returns The three-layer sandwich result\n */\n async compressMemoryItem(content: string, instructions: string = 'Extract the key information'): Promise<{\n preLayer: string;\n coreLayer: string;\n postLayer: string;\n }> {\n // Pre-Layer: Chunking and initial encoding\n // Here we do a naive encoding representation to signify the pre-processed chunks\n const estimatedChunks = Math.max(1, Math.ceil(this.adapter.estimateTokens(content) / 2000));\n const preLayer = `[PRE-LAYER ENCODED: ${estimatedChunks} internal chunks]`;\n\n // Core Layer: Dense summary sandwich with instructions\n // We sandwich the content between the instructions to guide extraction\n // If content is extremely large, we might trim it here, but ideally the provider streaming handles it.\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `### INSTRUCTIONS ###\\n${instructions}\\n\\n### CONTENT ###\\n${content}\\n\\n### INSTRUCTIONS ###\\n${instructions}`\n }]\n });\n const coreLayer = summaryResponse.content;\n\n // Post-Layer: Decoding/Refinement hooks\n // Indicates that the LLM can use tools to drill down into specific chunks\n const postLayer = `[POST-LAYER DECODING: Use \\`refine_layer\\` or \\`read_chunk\\` tools to expand specific sections]`;\n\n return { preLayer, coreLayer, postLayer };\n }\n}\n","import { ContextWindow, IContextStrategy, IProviderAdapter, Turn } from '../types/index.js';\n\n/**\n * ScratchpadStrategy manages the thinking process separate from the turn history.\n * It is primarily a marker/pre-turn strategy that ensures scratchpad gets tokenized properly\n * but is not compressed.\n */\nexport class ScratchpadStrategy implements IContextStrategy {\n readonly name = 'scratchpad_strategy';\n readonly priority = 10;\n\n shouldApply(ctx: ContextWindow): boolean {\n // Only apply if there's actual scratchpad content to track\n return ctx.scratchpad.length > 0;\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n // Basic implementation: we don't compress the scratchpad, we just ensure its tokens are counted\n return ctx;\n }\n}\n\nexport interface HistoryCompressionConfig {\n windowSize: number;\n triggerAtPercent: number; // e.g. 0.8\n}\n\n/**\n * Operates on a rolling window of the oldest N turns and summarizes them.\n */\nexport class HistoryCompressionStrategy implements IContextStrategy {\n readonly name = 'history_compression';\n readonly priority = 30;\n\n constructor(\n private adapter: IProviderAdapter,\n private config: HistoryCompressionConfig\n ) { }\n\n shouldApply(ctx: ContextWindow): boolean {\n const triggerTokens = ctx.maxTokens * this.config.triggerAtPercent;\n // Apply if we are over the trigger threshold and have at least enough turns\n // Ignore system prompts and already compressed turns\n const uncompressedTurns = ctx.turns.filter(t => t.role !== 'system' && !t.compressed);\n return ctx.tokenCount >= triggerTokens && uncompressedTurns.length > this.config.windowSize;\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n // Find the oldest N uncompressed turns that aren't the system prompt\n const uncompressedIndices = ctx.turns\n .map((t, i) => ({ t, i }))\n .filter(({ t }) => t.role !== 'system' && !t.compressed)\n .slice(0, this.config.windowSize);\n\n const targetTurns = uncompressedIndices.map(u => u.t);\n const middleText = targetTurns.map(t => `${t.role}: ${JSON.stringify(t.content)}`).join('\\n');\n\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `Summarize the oldest part of this conversation:\\n${middleText}`\n }]\n });\n\n const summaryStr = summaryResponse.content;\n const newCompressionSummary = ctx.compressionSummary\n ? `${ctx.compressionSummary}\\n${summaryStr}`\n : summaryStr;\n\n // Filter out the summarized turns\n const indicesToRemove = new Set(uncompressedIndices.map(u => u.i));\n const newTurns = ctx.turns.filter((_, i) => !indicesToRemove.has(i));\n\n const TokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) +\n this.adapter.estimateTokens(ctx.systemPrompt) +\n this.adapter.estimateTokens(ctx.scratchpad);\n\n return {\n ...ctx,\n turns: newTurns,\n tokenCount: TokenCount,\n compressionSummary: newCompressionSummary,\n };\n }\n}\n","import { IStorageAdapter, STMItem } from '../types/index.js';\nimport { randomUUID } from 'crypto';\n\nexport interface STMRegistryConfig {\n /**\n * The storage backend to use for Short Term Memory items.\n */\n storage: IStorageAdapter;\n\n /**\n * The maximum number of tokens allowed for a 'text' type STM item.\n * If an item exceeds this, it may be rejected or truncated.\n * Default: 100000\n */\n maxTextTokens?: number;\n}\n\n/**\n * Registry for Short Term Memory (STM).\n * Manages the storage and retrieval of large context variables like long texts or blobs.\n * Generates '[STM:uuid]' references to be used within the ReAct agent context.\n */\nexport class ShortTermMemoryRegistry {\n private storage: IStorageAdapter;\n private maxTextTokens: number;\n\n constructor(config: STMRegistryConfig) {\n this.storage = config.storage;\n this.maxTextTokens = config.maxTextTokens ?? 100000;\n }\n\n /**\n * Registers a new memory item and returns its reference string.\n * \n * @param content - The raw content to store\n * @param type - The type of content ('text' or 'blob')\n * @param metadata - Optional metadata (e.g. sandwich layers, original filename)\n * @param estimateTokens - Optional function to estimate token count for 'text' type\n * @returns A reference string formatted as '[STM:uuid]'\n * @throws {Error} if a text item exceeds the maxTextTokens limit\n */\n async register(\n content: any,\n type: 'text' | 'blob',\n metadata?: Record<string, unknown>,\n estimateTokens?: (text: string) => number\n ): Promise<string> {\n if (type === 'text') {\n const tokenCount = estimateTokens ? estimateTokens(content) : Math.ceil(String(content).length / 4);\n if (tokenCount > this.maxTextTokens) {\n throw new Error(`Text content exceeds max tokens limit of ${this.maxTextTokens} (estimated ${tokenCount})`);\n }\n }\n\n const id = randomUUID();\n const item: STMItem = {\n id,\n content,\n type,\n ...(metadata !== undefined ? { metadata } : {})\n };\n\n await this.storage.set(id, item);\n return `[STM:${id}]`;\n }\n\n /**\n * Updates an existing STM item's content or metadata.\n * \n * @param id - The UUID of the item to update\n * @param updates - Partial updates to apply (content or metadata)\n */\n async update(id: string, updates: { content?: any; metadata?: Record<string, unknown> }): Promise<void> {\n const item = await this.storage.get(id);\n if (!item) throw new Error(`STM item not found for update: ${id}`);\n\n const updatedItem: STMItem = {\n ...item,\n ...(updates.content !== undefined ? { content: updates.content } : {}),\n ...(updates.metadata !== undefined ? { metadata: { ...item.metadata, ...updates.metadata } } : {})\n };\n\n await this.storage.set(id, updatedItem);\n }\n\n\n /**\n * Retrieves an STM item by its full reference string (e.g., '[STM:uuid]').\n * \n * @param ref - The full reference string\n * @returns The STMItem or undefined if not found\n */\n async getByRef(ref: string): Promise<STMItem | undefined> {\n const match = ref.match(/^\\[STM:(.+)\\]$/);\n if (!match || !match[1]) return undefined;\n return this.storage.get(match[1]);\n }\n\n /**\n * Deletes an STM item by its ID.\n * \n * @param id - The UUID of the item to delete\n */\n async delete(id: string): Promise<void> {\n await this.storage.delete(id);\n }\n}\n","import { IStorageAdapter } from '../types/index.js';\nimport { randomUUID } from 'crypto';\n\n/**\n * An in-memory implementation of IStorageAdapter for holding Short Term Memory.\n * Ideal for testing or single-process lightweight usage.\n *\n * @example\n * const storage = new InMemoryStorageAdapter();\n * const id = await storage.set(undefined, 'my content', { type: 'text' });\n * const retrieved = await storage.get(id);\n */\nexport class InMemoryStorageAdapter implements IStorageAdapter {\n private store = new Map<string, { content: any; metadata?: Record<string, unknown> }>();\n\n /**\n * Retrieves stored content by ID.\n *\n * @param id - The identifier of the stored item\n * @returns The stored content or undefined if not found\n */\n async get(id: string): Promise<any | undefined> {\n return this.store.get(id)?.content;\n }\n\n /**\n * Returns the full item including metadata.\n *\n * @param id - The identifier of the stored item\n * @returns The complete item with content and metadata\n * @internal\n */\n async getFull(id: string): Promise<{ content: any; metadata?: Record<string, unknown> } | undefined> {\n return this.store.get(id);\n }\n\n /**\n * Stores content, generating an ID if none is provided.\n *\n * @param id - Optional provided ID. If omitted, a UUID is generated.\n * @param content - The content to store\n * @param metadata - Optional metadata\n * @returns The ID under which the content is stored\n */\n async set(id: string | undefined, content: any, metadata?: Record<string, unknown>): Promise<string> {\n const resolvedId = id ?? randomUUID();\n this.store.set(resolvedId, metadata !== undefined ? { content, metadata } : { content });\n return resolvedId;\n }\n\n /**\n * Deletes the content for the given ID.\n *\n * @param id - The identifier of the item to delete\n */\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n /**\n * Synchronous health check, always true for in-memory.\n *\n * @returns true\n */\n async healthCheck(): Promise<boolean> {\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/errors.ts","../../src/context/ContextManager.ts","../../src/context/SandwichCompressionStrategy.ts","../../src/context/HistoryCompressionStrategy.ts","../../src/context/ShortTermMemoryRegistry.ts","../../src/context/InMemoryStorageAdapter.ts"],"names":["randomUUID"],"mappings":";;;AAMO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YACI,OAAA,EACgB,IAAA,EACA,OAAA,EACA,KAAA,GAAkB,EAAC,EACrC;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAJG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EACpD;AACJ,CAAA;AAGO,I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CAAA;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,WAAA,GAAgC;AAClC,IAAA,OAAO,IAAA;AAAA,EACX;AACJ","file":"index.mjs","sourcesContent":["/**\n * Base class for all custom errors thrown by lemura.\n *\n * @example\n * throw new LemuraError('Something went wrong', 'UNKNOWN_ERROR');\n */\nexport class LemuraError extends Error {\n /**\n * @param message - The error message\n * @param code - The error code for programmatic handling\n * @param problem - A clear description of the problem for the end user\n * @param hints - A list of suggestions to resolve the issue\n */\n constructor(\n message: string,\n public readonly code: string,\n public readonly problem?: string,\n public readonly hints: string[] = []\n ) {\n super(message);\n this.name = 'LemuraError';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Error thrown when context exceeds max tokens and cannot be compressed further */\nexport class LemuraContextOverflowError extends LemuraError {\n constructor(message: string) {\n super(message, 'CONTEXT_OVERFLOW');\n this.name = 'LemuraContextOverflowError';\n }\n}\n\n/** Error thrown when a requested tool is not found in the registry */\nexport class LemuraToolNotFoundError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_NOT_FOUND');\n this.name = 'LemuraToolNotFoundError';\n }\n}\n\n/** Error thrown when an adapter encounters an API or formatting issue */\nexport class LemuraAdapterError extends LemuraError {\n constructor(\n message: string,\n code = 'ADAPTER_ERROR',\n public cause?: any,\n problem?: string,\n hints: string[] = []\n ) {\n super(message, code, problem, hints);\n this.name = 'LemuraAdapterError';\n }\n}\n\n/** Error thrown when a skill cannot be parsed or injected */\nexport class LemuraSkillInjectionError extends LemuraError {\n constructor(message: string) {\n super(message, 'SKILL_INJECTION_FAILED');\n this.name = 'LemuraSkillInjectionError';\n }\n}\n\n/** Error thrown when the ReAct loop exceeds the configured max iterations */\nexport class LemuraMaxIterationsError extends LemuraError {\n constructor(message: string) {\n super(message, 'MAX_ITERATIONS_EXCEEDED');\n this.name = 'LemuraMaxIterationsError';\n }\n}\n\n/** Error thrown when tool parameters fail JSON schema validation */\nexport class LemuraToolValidationError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_VALIDATION_FAILED');\n this.name = 'LemuraToolValidationError';\n }\n}\n\n/** Error thrown when a tool execute function exceeds its timeout */\nexport class LemuraToolTimeoutError extends LemuraError {\n constructor(message: string) {\n super(message, 'TOOL_TIMEOUT');\n this.name = 'LemuraToolTimeoutError';\n }\n}\n\n/** Base error thrown for any MCP server communication failure */\nexport class LemuraMCPError extends LemuraError {\n constructor(message: string, code = 'MCP_ERROR', problem?: string, hints: string[] = []) {\n super(message, code, problem, hints);\n this.name = 'LemuraMCPError';\n }\n}\n\n/** Error thrown when an MCP server cannot be connected to (spawn failure, network error, init failure) */\nexport class LemuraMCPConnectionError extends LemuraMCPError {\n constructor(message: string, problem?: string, hints: string[] = []) {\n super(message, 'MCP_CONNECTION_FAILED', problem, hints);\n this.name = 'LemuraMCPConnectionError';\n }\n}\n\n/** Error thrown when a call to an MCP server tool exceeds the configured timeout */\nexport class LemuraMCPTimeoutError extends LemuraMCPError {\n constructor(message: string) {\n super(message, 'MCP_TOOL_TIMEOUT');\n this.name = 'LemuraMCPTimeoutError';\n }\n}\n","import { ContextWindow, IContextStrategy, LemuraContextOverflowError } from '../types/index.js';\n\n/**\n * Orchestrates a stack of IContextStrategy implementations to keep the\n * token count within the maxTokens limit.\n */\nexport class ContextManager {\n private strategies: IContextStrategy[] = [];\n\n /**\n * Registers a new compression or pre-turn strategy and sorts the stack by priority.\n *\n * @param strategy - The strategy implementation to register\n */\n registerStrategy(strategy: IContextStrategy): void {\n this.strategies.push(strategy);\n this.strategies.sort((a, b) => a.priority - b.priority);\n }\n\n /**\n * Applies all registered strategies that return true for `shouldApply()`\n * until the context token count is safely below the maximum budget.\n *\n * @param context - The context window to prepare\n * @param safetyMargin - Modifier applied to maxTokens (default: 0.95 -> 95%)\n * @returns A new ContextWindow object potentially compressed\n * @throws {LemuraContextOverflowError} If the context is still over maxTokens after all strategies\n */\n async prepare(context: ContextWindow, safetyMargin = 0.95): Promise<ContextWindow> {\n let currentCtx = { ...context, turns: [...context.turns] };\n const targetTokenCount = currentCtx.maxTokens * safetyMargin;\n\n for (const strategy of this.strategies) {\n // If we are below the limit and it's not a pre-turn non-reducing strategy, skip it.\n // E.g., SummaryInjectionStrategy might still want to run.\n // But purely compression ones drop out early in our base architecture if they choose in `shouldApply`.\n if (strategy.shouldApply(currentCtx)) {\n currentCtx = await strategy.apply(currentCtx);\n }\n }\n\n if (currentCtx.tokenCount > currentCtx.maxTokens) {\n throw new LemuraContextOverflowError(\n `Context overflowed: ${currentCtx.tokenCount} tokens > ${currentCtx.maxTokens}`\n );\n }\n\n return currentCtx;\n }\n}\n","import { ContextWindow, IContextStrategy, IProviderAdapter, Turn } from '../types/index.js';\n\nexport interface SandwichCompressionConfig {\n preserveFirst: number;\n preserveLast: number;\n triggerThreshold: number; // e.g. 0.8\n}\n\n/**\n * Sandwich compression preserves the beginning and end of the conversation,\n * replacing the middle with a generated summary.\n */\nexport class SandwichCompressionStrategy implements IContextStrategy {\n readonly name = 'sandwich_compression';\n readonly priority = 20;\n\n constructor(\n private adapter: IProviderAdapter,\n private config: SandwichCompressionConfig\n ) { }\n\n shouldApply(ctx: ContextWindow): boolean {\n return (\n ctx.tokenCount >= ctx.maxTokens * this.config.triggerThreshold &&\n ctx.turns.length > this.config.preserveFirst + this.config.preserveLast\n );\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n const { preserveFirst, preserveLast } = this.config;\n\n const head = ctx.turns.slice(0, preserveFirst);\n const tail = ctx.turns.slice(ctx.turns.length - preserveLast);\n const middle = ctx.turns.slice(preserveFirst, ctx.turns.length - preserveLast);\n\n const middleText = middle.map(t => `${t.role}: ${JSON.stringify(t.content)}`).join('\\n');\n\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `Summarize the following conversation history briefly:\\n${middleText}`\n }]\n });\n\n const summaryStr = summaryResponse.content;\n\n const newCompressionSummary = ctx.compressionSummary\n ? `${ctx.compressionSummary}\\n${summaryStr}`\n : summaryStr;\n\n const summaryTurn: Turn = {\n role: 'system',\n content: `[COMPRESSED HISTORY SUMMARY]\\n${newCompressionSummary}`,\n tokenCount: this.adapter.estimateTokens(newCompressionSummary),\n turnIndex: -1,\n compressed: true,\n };\n\n const newTurns = [...head, summaryTurn, ...tail];\n const newTokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) +\n this.adapter.estimateTokens(ctx.systemPrompt) +\n this.adapter.estimateTokens(ctx.scratchpad);\n\n return {\n ...ctx,\n turns: newTurns,\n tokenCount: newTokenCount,\n compressionSummary: newCompressionSummary,\n };\n }\n\n /**\n * Applies sandwich compression specifically to a Short Term Memory item's content.\n * Implements a 3-layer pipeline: Pre-Layer (encoding), Core Layer (dense summary), Post-Layer (refinement cues).\n * \n * @param content - The heavy text content to compress\n * @param instructions - Guiding instructions for the core layer summary\n * @returns The three-layer sandwich result\n */\n async compressMemoryItem(content: string, instructions: string = 'Extract the key information'): Promise<{\n preLayer: string;\n coreLayer: string;\n postLayer: string;\n }> {\n // Pre-Layer: Chunking and initial encoding\n // Here we do a naive encoding representation to signify the pre-processed chunks\n const estimatedChunks = Math.max(1, Math.ceil(this.adapter.estimateTokens(content) / 2000));\n const preLayer = `[PRE-LAYER ENCODED: ${estimatedChunks} internal chunks]`;\n\n // Core Layer: Dense summary sandwich with instructions\n // We sandwich the content between the instructions to guide extraction\n // If content is extremely large, we might trim it here, but ideally the provider streaming handles it.\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `### INSTRUCTIONS ###\\n${instructions}\\n\\n### CONTENT ###\\n${content}\\n\\n### INSTRUCTIONS ###\\n${instructions}`\n }]\n });\n const coreLayer = summaryResponse.content;\n\n // Post-Layer: Decoding/Refinement hooks\n // Indicates that the LLM can use tools to drill down into specific chunks\n const postLayer = `[POST-LAYER DECODING: Use \\`refine_layer\\` or \\`read_chunk\\` tools to expand specific sections]`;\n\n return { preLayer, coreLayer, postLayer };\n }\n}\n","import { ContextWindow, IContextStrategy, IProviderAdapter, Turn } from '../types/index.js';\n\n/**\n * ScratchpadStrategy manages the thinking process separate from the turn history.\n * It is primarily a marker/pre-turn strategy that ensures scratchpad gets tokenized properly\n * but is not compressed.\n */\nexport class ScratchpadStrategy implements IContextStrategy {\n readonly name = 'scratchpad_strategy';\n readonly priority = 10;\n\n shouldApply(ctx: ContextWindow): boolean {\n // Only apply if there's actual scratchpad content to track\n return ctx.scratchpad.length > 0;\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n // Basic implementation: we don't compress the scratchpad, we just ensure its tokens are counted\n return ctx;\n }\n}\n\nexport interface HistoryCompressionConfig {\n windowSize: number;\n triggerAtPercent: number; // e.g. 0.8\n}\n\n/**\n * Operates on a rolling window of the oldest N turns and summarizes them.\n */\nexport class HistoryCompressionStrategy implements IContextStrategy {\n readonly name = 'history_compression';\n readonly priority = 30;\n\n constructor(\n private adapter: IProviderAdapter,\n private config: HistoryCompressionConfig\n ) { }\n\n shouldApply(ctx: ContextWindow): boolean {\n const triggerTokens = ctx.maxTokens * this.config.triggerAtPercent;\n // Apply if we are over the trigger threshold and have at least enough turns\n // Ignore system prompts and already compressed turns\n const uncompressedTurns = ctx.turns.filter(t => t.role !== 'system' && !t.compressed);\n return ctx.tokenCount >= triggerTokens && uncompressedTurns.length > this.config.windowSize;\n }\n\n async apply(ctx: ContextWindow): Promise<ContextWindow> {\n // Find the oldest N uncompressed turns that aren't the system prompt\n const uncompressedIndices = ctx.turns\n .map((t, i) => ({ t, i }))\n .filter(({ t }) => t.role !== 'system' && !t.compressed)\n .slice(0, this.config.windowSize);\n\n const targetTurns = uncompressedIndices.map(u => u.t);\n const middleText = targetTurns.map(t => `${t.role}: ${JSON.stringify(t.content)}`).join('\\n');\n\n const summaryResponse = await this.adapter.complete({\n model: '',\n messages: [{\n role: 'user',\n content: `Summarize the oldest part of this conversation:\\n${middleText}`\n }]\n });\n\n const summaryStr = summaryResponse.content;\n const newCompressionSummary = ctx.compressionSummary\n ? `${ctx.compressionSummary}\\n${summaryStr}`\n : summaryStr;\n\n // Filter out the summarized turns\n const indicesToRemove = new Set(uncompressedIndices.map(u => u.i));\n const newTurns = ctx.turns.filter((_, i) => !indicesToRemove.has(i));\n\n const TokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) +\n this.adapter.estimateTokens(ctx.systemPrompt) +\n this.adapter.estimateTokens(ctx.scratchpad);\n\n return {\n ...ctx,\n turns: newTurns,\n tokenCount: TokenCount,\n compressionSummary: newCompressionSummary,\n };\n }\n}\n","import { IStorageAdapter, STMItem } from '../types/index.js';\nimport { randomUUID } from 'crypto';\n\nexport interface STMRegistryConfig {\n /**\n * The storage backend to use for Short Term Memory items.\n */\n storage: IStorageAdapter;\n\n /**\n * The maximum number of tokens allowed for a 'text' type STM item.\n * If an item exceeds this, it may be rejected or truncated.\n * Default: 100000\n */\n maxTextTokens?: number;\n}\n\n/**\n * Registry for Short Term Memory (STM).\n * Manages the storage and retrieval of large context variables like long texts or blobs.\n * Generates '[STM:uuid]' references to be used within the ReAct agent context.\n */\nexport class ShortTermMemoryRegistry {\n private storage: IStorageAdapter;\n private maxTextTokens: number;\n\n constructor(config: STMRegistryConfig) {\n this.storage = config.storage;\n this.maxTextTokens = config.maxTextTokens ?? 100000;\n }\n\n /**\n * Registers a new memory item and returns its reference string.\n * \n * @param content - The raw content to store\n * @param type - The type of content ('text' or 'blob')\n * @param metadata - Optional metadata (e.g. sandwich layers, original filename)\n * @param estimateTokens - Optional function to estimate token count for 'text' type\n * @returns A reference string formatted as '[STM:uuid]'\n * @throws {Error} if a text item exceeds the maxTextTokens limit\n */\n async register(\n content: any,\n type: 'text' | 'blob',\n metadata?: Record<string, unknown>,\n estimateTokens?: (text: string) => number\n ): Promise<string> {\n if (type === 'text') {\n const tokenCount = estimateTokens ? estimateTokens(content) : Math.ceil(String(content).length / 4);\n if (tokenCount > this.maxTextTokens) {\n throw new Error(`Text content exceeds max tokens limit of ${this.maxTextTokens} (estimated ${tokenCount})`);\n }\n }\n\n const id = randomUUID();\n const item: STMItem = {\n id,\n content,\n type,\n ...(metadata !== undefined ? { metadata } : {})\n };\n\n await this.storage.set(id, item);\n return `[STM:${id}]`;\n }\n\n /**\n * Updates an existing STM item's content or metadata.\n * \n * @param id - The UUID of the item to update\n * @param updates - Partial updates to apply (content or metadata)\n */\n async update(id: string, updates: { content?: any; metadata?: Record<string, unknown> }): Promise<void> {\n const item = await this.storage.get(id);\n if (!item) throw new Error(`STM item not found for update: ${id}`);\n\n const updatedItem: STMItem = {\n ...item,\n ...(updates.content !== undefined ? { content: updates.content } : {}),\n ...(updates.metadata !== undefined ? { metadata: { ...item.metadata, ...updates.metadata } } : {})\n };\n\n await this.storage.set(id, updatedItem);\n }\n\n\n /**\n * Retrieves an STM item by its full reference string (e.g., '[STM:uuid]').\n * \n * @param ref - The full reference string\n * @returns The STMItem or undefined if not found\n */\n async getByRef(ref: string): Promise<STMItem | undefined> {\n const match = ref.match(/^\\[STM:(.+)\\]$/);\n if (!match || !match[1]) return undefined;\n return this.storage.get(match[1]);\n }\n\n /**\n * Deletes an STM item by its ID.\n * \n * @param id - The UUID of the item to delete\n */\n async delete(id: string): Promise<void> {\n await this.storage.delete(id);\n }\n}\n","import { IStorageAdapter } from '../types/index.js';\nimport { randomUUID } from 'crypto';\n\n/**\n * An in-memory implementation of IStorageAdapter for holding Short Term Memory.\n * Ideal for testing or single-process lightweight usage.\n *\n * @example\n * const storage = new InMemoryStorageAdapter();\n * const id = await storage.set(undefined, 'my content', { type: 'text' });\n * const retrieved = await storage.get(id);\n */\nexport class InMemoryStorageAdapter implements IStorageAdapter {\n private store = new Map<string, { content: any; metadata?: Record<string, unknown> }>();\n\n /**\n * Retrieves stored content by ID.\n *\n * @param id - The identifier of the stored item\n * @returns The stored content or undefined if not found\n */\n async get(id: string): Promise<any | undefined> {\n return this.store.get(id)?.content;\n }\n\n /**\n * Returns the full item including metadata.\n *\n * @param id - The identifier of the stored item\n * @returns The complete item with content and metadata\n * @internal\n */\n async getFull(id: string): Promise<{ content: any; metadata?: Record<string, unknown> } | undefined> {\n return this.store.get(id);\n }\n\n /**\n * Stores content, generating an ID if none is provided.\n *\n * @param id - Optional provided ID. If omitted, a UUID is generated.\n * @param content - The content to store\n * @param metadata - Optional metadata\n * @returns The ID under which the content is stored\n */\n async set(id: string | undefined, content: any, metadata?: Record<string, unknown>): Promise<string> {\n const resolvedId = id ?? randomUUID();\n this.store.set(resolvedId, metadata !== undefined ? { content, metadata } : { content });\n return resolvedId;\n }\n\n /**\n * Deletes the content for the given ID.\n *\n * @param id - The identifier of the item to delete\n */\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n /**\n * Synchronous health check, always true for in-memory.\n *\n * @returns true\n */\n async healthCheck(): Promise<boolean> {\n return true;\n }\n}\n"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,19 +1,51 @@
|
|
|
1
|
-
import { C as ContextWindow,
|
|
2
|
-
export {
|
|
3
|
-
import { SessionConfig, IToolResponseProcessor, ToolResponseEvaluation } from './
|
|
4
|
-
export {
|
|
5
|
-
export {
|
|
1
|
+
import { a as IProviderAdapter, T as TranscriptionRequest, c as TranscriptionResponse, d as SynthesisRequest, A as AudioChunk, V as VisionRequest, e as VisionResponse, f as ImageGenRequest, g as ImageGenResponse, M as ModelInfo, C as ContextWindow, h as Turn, i as ContentBlock, I as IToolDefinition } from './storage-CG3nTa6o.mjs';
|
|
2
|
+
export { j as CompletionChunk, k as CompletionRequest, l as CompletionResponse, b as IContextStrategy, m as IStorageAdapter, N as NormalizedMessage, n as STMItem, o as STMRegistryConfig, S as ShortTermMemoryRegistry, p as TokenUsage, q as ToolCall, r as ToolContext, s as ToolResult } from './storage-CG3nTa6o.mjs';
|
|
3
|
+
import { S as SessionConfig, I as IToolResponseProcessor, T as ToolResponseEvaluation, M as MCPServerConfig, a as MCPToolDefinition } from './agent-D6uhF-CZ.mjs';
|
|
4
|
+
export { b as MCPJsonRpcRequest, c as MCPJsonRpcResponse, d as MCPTransportType, e as MediaConfig, f as ToolDecision, g as ToolExecutionBudget, h as ToolFirewallConfig, i as ToolFirewallRule, j as TraceEvent } from './agent-D6uhF-CZ.mjs';
|
|
5
|
+
export { LemuraAdapterError, LemuraContextOverflowError, LemuraError, LemuraMCPConnectionError, LemuraMCPError, LemuraMCPTimeoutError, LemuraMaxIterationsError, LemuraSkillInjectionError, LemuraToolNotFoundError, LemuraToolTimeoutError, LemuraToolValidationError } from './types/index.mjs';
|
|
6
|
+
import { I as ILogger } from './logger-DxvKliuk.mjs';
|
|
7
|
+
export { L as LogLevel, a as LogMetadata, S as Severity } from './logger-DxvKliuk.mjs';
|
|
6
8
|
export { I as IRAGAdapter, R as RAGDocument, a as RAGIngestOptions, b as RAGIngestRequest, c as RAGIngestResponse, d as RAGQueryRequest, e as RAGQueryResponse, f as RAGResult } from './rag-La_Bo-J8.mjs';
|
|
7
9
|
export { I as ISkill } from './skills-wc8S-OvC.mjs';
|
|
8
|
-
import { I as IToolDefinition } from './storage-DMcliVVj.mjs';
|
|
9
|
-
export { a as IStorageAdapter, S as STMItem, b as STMRegistryConfig, c as ShortTermMemoryRegistry, T as ToolContext } from './storage-DMcliVVj.mjs';
|
|
10
10
|
export { OpenAICompatibleAdapter, OpenAICompatibleAdapterConfig, RetryConfig } from './adapters/index.mjs';
|
|
11
11
|
export { ContextManager, HistoryCompressionConfig, HistoryCompressionStrategy, InMemoryStorageAdapter, SandwichCompressionConfig, SandwichCompressionStrategy, ScratchpadStrategy } from './context/index.mjs';
|
|
12
|
-
export { ToolRegistry } from './tools/index.mjs';
|
|
12
|
+
export { SchemaValidationError, ToolFirewallResult, ToolRegistry, ToolRegistryOptions, evaluateToolFirewall, validateJsonSchema } from './tools/index.mjs';
|
|
13
13
|
export { SkillInjector } from './skills/index.mjs';
|
|
14
14
|
export { InMemoryRAGAdapter } from './rag/index.mjs';
|
|
15
15
|
export { DefaultLogger } from './logger/index.mjs';
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* MediaBridge provides a single, app-friendly entry point for audio/vision/image features.
|
|
19
|
+
*/
|
|
20
|
+
declare class MediaBridge {
|
|
21
|
+
private adapter;
|
|
22
|
+
constructor(adapter: IProviderAdapter);
|
|
23
|
+
transcribe(request: TranscriptionRequest): Promise<TranscriptionResponse>;
|
|
24
|
+
synthesize(request: SynthesisRequest): AsyncIterable<AudioChunk>;
|
|
25
|
+
synthesizeToArray(request: SynthesisRequest): Promise<AudioChunk[]>;
|
|
26
|
+
describeImage(request: VisionRequest): Promise<VisionResponse>;
|
|
27
|
+
generateImage(request: ImageGenRequest): Promise<ImageGenResponse>;
|
|
28
|
+
getModelInfo(): ModelInfo;
|
|
29
|
+
supportsVision(): boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Core entry point for lemura agent sessions.
|
|
34
|
+
*
|
|
35
|
+
* `SessionManager` owns the full ReAct loop lifecycle:
|
|
36
|
+
* - Context window management and compression
|
|
37
|
+
* - Skill injection
|
|
38
|
+
* - Tool firewall + schema validation + timeout enforcement
|
|
39
|
+
* - Parallel tool execution (opt-in via `parallelToolCalls`)
|
|
40
|
+
* - maxSteps guard → forced graceful conclusion
|
|
41
|
+
* - Tool response compression (via `toolResponseProcessor`)
|
|
42
|
+
* - Goal injection (via `enableGoalPlanning`)
|
|
43
|
+
* - Streaming output (`stream()`)
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* const session = new SessionManager({ adapter, model: 'gpt-4o', maxTokens: 16_000 });
|
|
47
|
+
* const answer = await session.run('What is the capital of France?');
|
|
48
|
+
*/
|
|
17
49
|
declare class SessionManager {
|
|
18
50
|
private contextManager;
|
|
19
51
|
private toolRegistry;
|
|
@@ -23,10 +55,97 @@ declare class SessionManager {
|
|
|
23
55
|
private config;
|
|
24
56
|
private iterations;
|
|
25
57
|
private logger;
|
|
58
|
+
private media;
|
|
59
|
+
private stepCounter;
|
|
60
|
+
private toolResponseProcessor;
|
|
61
|
+
private goalInjector;
|
|
62
|
+
private continuationPlanner;
|
|
63
|
+
private mcpRegistry;
|
|
64
|
+
/** Resolves when all MCP servers are connected; used by run() and stream() */
|
|
65
|
+
private mcpReady;
|
|
66
|
+
private totalToolCallCount;
|
|
67
|
+
private perToolCallCount;
|
|
68
|
+
private totalTokens;
|
|
26
69
|
constructor(config: SessionConfig);
|
|
70
|
+
private emitTrace;
|
|
71
|
+
/**
|
|
72
|
+
* Returns a shallow copy of the current context window.
|
|
73
|
+
*/
|
|
27
74
|
getContext(): ContextWindow;
|
|
75
|
+
/**
|
|
76
|
+
* Returns the current conversation history.
|
|
77
|
+
*/
|
|
28
78
|
getHistory(): Turn[];
|
|
79
|
+
/**
|
|
80
|
+
* Returns the `MediaBridge` for direct ASR / TTS / Vision / Image-gen calls.
|
|
81
|
+
*/
|
|
82
|
+
getMedia(): MediaBridge;
|
|
83
|
+
/**
|
|
84
|
+
* Connects all configured MCP servers and registers their bridged tools.
|
|
85
|
+
* Called from the constructor as a fire-and-start async task; `run()` and
|
|
86
|
+
* `stream()` await `this.mcpReady` before executing.
|
|
87
|
+
*/
|
|
88
|
+
private _initMCP;
|
|
89
|
+
/** Builds the system prompt, injecting skills and goal if configured. */
|
|
90
|
+
private buildSystemPrompt;
|
|
91
|
+
/** Builds the messages array for the provider from the current context */
|
|
92
|
+
private buildMessages;
|
|
93
|
+
/** Checks the tool execution budget and throws descriptively if exceeded */
|
|
94
|
+
private checkExecutionBudget;
|
|
95
|
+
/** Records a tool call in budget counters */
|
|
96
|
+
private recordToolCall;
|
|
97
|
+
/**
|
|
98
|
+
* Processes a firewall decision for a tool call.
|
|
99
|
+
* Returns true to proceed, false to block.
|
|
100
|
+
*/
|
|
101
|
+
private passesFirewall;
|
|
102
|
+
/**
|
|
103
|
+
* Executes a single parsed tool call and returns the serialised result string.
|
|
104
|
+
*/
|
|
105
|
+
private executeSingleToolCall;
|
|
106
|
+
/**
|
|
107
|
+
* Runs the full ReAct loop for a user message and returns the final assistant response.
|
|
108
|
+
*
|
|
109
|
+
* @param userMessage - The user's message (string or multimodal content blocks)
|
|
110
|
+
* @returns The assistant's final response string
|
|
111
|
+
* @throws {LemuraMaxIterationsError} When the loop exceeds `maxIterations`
|
|
112
|
+
*/
|
|
29
113
|
run(userMessage: string | ContentBlock[]): Promise<string>;
|
|
114
|
+
/**
|
|
115
|
+
* Runs the ReAct loop and streams the final assistant response token-by-token.
|
|
116
|
+
*
|
|
117
|
+
* Tool calls within the loop are still executed synchronously (they must complete
|
|
118
|
+
* before streaming the conclusion). Only the final LLM text output is streamed.
|
|
119
|
+
*
|
|
120
|
+
* @param userMessage - The user's message (string or multimodal content blocks)
|
|
121
|
+
* @returns An `AsyncIterable<string>` of delta tokens from the final response
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* for await (const token of session.stream('Tell me a story')) {
|
|
125
|
+
* process.stdout.write(token);
|
|
126
|
+
* }
|
|
127
|
+
*/
|
|
128
|
+
stream(userMessage: string | ContentBlock[]): AsyncIterable<string>;
|
|
129
|
+
/**
|
|
130
|
+
* Resets the session: clears conversation history, resets iteration counters,
|
|
131
|
+
* and resets tool execution budgets. The adapter, config, and tools are retained.
|
|
132
|
+
*/
|
|
133
|
+
reset(): void;
|
|
134
|
+
/**
|
|
135
|
+
* Closes the session and disconnects all MCP servers.
|
|
136
|
+
*
|
|
137
|
+
* Call this when you are done with the session and have registered MCP servers,
|
|
138
|
+
* to ensure child processes are terminated and HTTP connections are released.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* const session = new SessionManager({ ..., mcpServers: [...] });
|
|
142
|
+
* try {
|
|
143
|
+
* await session.run('Hello');
|
|
144
|
+
* } finally {
|
|
145
|
+
* await session.close();
|
|
146
|
+
* }
|
|
147
|
+
*/
|
|
148
|
+
close(): Promise<void>;
|
|
30
149
|
}
|
|
31
150
|
|
|
32
151
|
/**
|
|
@@ -51,6 +170,7 @@ declare class GoalInjector {
|
|
|
51
170
|
private goal;
|
|
52
171
|
constructor(goal: Goal);
|
|
53
172
|
injectInto(prompt: string): string;
|
|
173
|
+
getGoal(): Goal;
|
|
54
174
|
}
|
|
55
175
|
|
|
56
176
|
interface ContinuationStep {
|
|
@@ -88,4 +208,132 @@ declare class FinalResponseFormatter {
|
|
|
88
208
|
static validateStructure(response: string): boolean;
|
|
89
209
|
}
|
|
90
210
|
|
|
91
|
-
|
|
211
|
+
/**
|
|
212
|
+
* Low-level MCP server client.
|
|
213
|
+
*
|
|
214
|
+
* Supports two transports:
|
|
215
|
+
* - **stdio** — spawns a child process and communicates over stdin/stdout via newline-delimited JSON-RPC 2.0
|
|
216
|
+
* - **http** — sends JSON-RPC 2.0 `POST` requests using native `fetch` (Node >= 18 required)
|
|
217
|
+
*
|
|
218
|
+
* Lifecycle:
|
|
219
|
+
* 1. `connect()` — initialize the server and fetch its tool list
|
|
220
|
+
* 2. `callTool()` — invoke a tool by name
|
|
221
|
+
* 3. `disconnect()` — terminate the connection / child process
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* const client = new MCPClient('github', {
|
|
225
|
+
* name: 'github',
|
|
226
|
+
* transport: 'stdio',
|
|
227
|
+
* command: 'npx',
|
|
228
|
+
* args: ['@modelcontextprotocol/server-github'],
|
|
229
|
+
* env: { GITHUB_TOKEN: '...' }
|
|
230
|
+
* }, logger);
|
|
231
|
+
*
|
|
232
|
+
* await client.connect();
|
|
233
|
+
* const result = await client.callTool('create_issue', { title: 'bug' });
|
|
234
|
+
* await client.disconnect();
|
|
235
|
+
*/
|
|
236
|
+
declare class MCPClient {
|
|
237
|
+
private readonly config;
|
|
238
|
+
private readonly logger;
|
|
239
|
+
private readonly _serverName;
|
|
240
|
+
private readonly timeoutMs;
|
|
241
|
+
private _tools;
|
|
242
|
+
private _connected;
|
|
243
|
+
private process;
|
|
244
|
+
private pendingCallbacks;
|
|
245
|
+
private requestId;
|
|
246
|
+
private stdioBuffer;
|
|
247
|
+
constructor(name: string, config: MCPServerConfig, logger: ILogger);
|
|
248
|
+
get serverName(): string;
|
|
249
|
+
get tools(): MCPToolDefinition[];
|
|
250
|
+
get isConnected(): boolean;
|
|
251
|
+
/**
|
|
252
|
+
* Connects to the MCP server: sends `initialize` + `notifications/initialized`,
|
|
253
|
+
* then fetches the tool list via `tools/list`.
|
|
254
|
+
*/
|
|
255
|
+
connect(): Promise<void>;
|
|
256
|
+
/**
|
|
257
|
+
* Calls a tool on this MCP server.
|
|
258
|
+
*
|
|
259
|
+
* @param toolName - The tool name as declared by the server
|
|
260
|
+
* @param args - Tool arguments (must match the tool's inputSchema)
|
|
261
|
+
* @returns The serialised result from the server
|
|
262
|
+
*/
|
|
263
|
+
callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
|
|
264
|
+
/**
|
|
265
|
+
* Disconnects from the MCP server.
|
|
266
|
+
* For stdio: sends the `exit` notification then terminates the process.
|
|
267
|
+
*/
|
|
268
|
+
disconnect(): Promise<void>;
|
|
269
|
+
private _connectStdio;
|
|
270
|
+
/** Parses newline-delimited JSON messages from the stdio buffer */
|
|
271
|
+
private _flushStdioBuffer;
|
|
272
|
+
private _nextId;
|
|
273
|
+
/** Sends a JSON-RPC request and returns the response, honouring the configured timeout. */
|
|
274
|
+
private _rpc;
|
|
275
|
+
private _rpcStdio;
|
|
276
|
+
private _rpcHttp;
|
|
277
|
+
/** Sends `initialize` then `notifications/initialized` per MCP spec */
|
|
278
|
+
private _initialize;
|
|
279
|
+
/** Fetches and caches the tool list from the server */
|
|
280
|
+
private _discoverTools;
|
|
281
|
+
private _assertNoError;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Manages the full lifecycle of multiple MCP server connections and routes
|
|
286
|
+
* tool calls to the correct server.
|
|
287
|
+
*
|
|
288
|
+
* Typical usage is handled automatically by `SessionManager` when `mcpServers`
|
|
289
|
+
* is set in `SessionConfig`. You can also use it standalone for advanced scenarios.
|
|
290
|
+
*
|
|
291
|
+
* @example
|
|
292
|
+
* const registry = new MCPClientRegistry(logger);
|
|
293
|
+
* await registry.register('github', { transport: 'stdio', command: 'npx', args: ['...'] });
|
|
294
|
+
* const tools = await registry.discoverTools(); // IToolDefinition[] ready for ToolRegistry
|
|
295
|
+
*/
|
|
296
|
+
declare class MCPClientRegistry {
|
|
297
|
+
private readonly clients;
|
|
298
|
+
/** toolName → serverName */
|
|
299
|
+
private readonly toolRouter;
|
|
300
|
+
private readonly logger;
|
|
301
|
+
constructor(logger: ILogger);
|
|
302
|
+
/**
|
|
303
|
+
* Creates an `MCPClient` for the given config, connects to the server, and
|
|
304
|
+
* registers the server by name.
|
|
305
|
+
*
|
|
306
|
+
* @throws {LemuraMCPConnectionError} if connection / initialization fails
|
|
307
|
+
*/
|
|
308
|
+
register(name: string, config: MCPServerConfig): Promise<void>;
|
|
309
|
+
/**
|
|
310
|
+
* Collects tools from all connected MCP servers and returns them as
|
|
311
|
+
* `IToolDefinition` adapters ready to be registered in `ToolRegistry`.
|
|
312
|
+
*
|
|
313
|
+
* Tool names are **not** namespaced — if two servers expose a tool with the
|
|
314
|
+
* same name, the last-registered server wins and a warning is emitted.
|
|
315
|
+
*/
|
|
316
|
+
discoverTools(): Promise<IToolDefinition[]>;
|
|
317
|
+
/**
|
|
318
|
+
* Calls a tool on the correct MCP server.
|
|
319
|
+
*
|
|
320
|
+
* @param toolName - The tool name as registered via `discoverTools()`
|
|
321
|
+
* @param args - Parsed arguments object
|
|
322
|
+
* @throws {LemuraMCPConnectionError} if no server is registered for `toolName`
|
|
323
|
+
*/
|
|
324
|
+
callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
|
|
325
|
+
/**
|
|
326
|
+
* Disconnects all registered MCP servers gracefully.
|
|
327
|
+
* Called automatically by `SessionManager.close()`.
|
|
328
|
+
*/
|
|
329
|
+
disconnectAll(): Promise<void>;
|
|
330
|
+
/** Returns the names of all currently registered servers */
|
|
331
|
+
getRegisteredServers(): string[];
|
|
332
|
+
/**
|
|
333
|
+
* Bridges an `MCPToolDefinition` from the protocol into an `IToolDefinition`
|
|
334
|
+
* that the existing `ToolRegistry` can execute.
|
|
335
|
+
*/
|
|
336
|
+
private _bridge;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export { AudioChunk, ContentBlock, ContextWindow, type ContinuationPlan, ContinuationPlanner, type ContinuationStep, FinalResponseFormatter, type Goal, GoalInjector, ILogger, IProviderAdapter, IToolDefinition, IToolResponseProcessor, ImageGenRequest, ImageGenResponse, MCPClient, MCPClientRegistry, MCPServerConfig, MCPToolDefinition, MediaBridge, ModelInfo, SessionConfig, SessionManager, StepCounter, SynthesisRequest, ToolResponseEvaluation, ToolResponseProcessor, TranscriptionRequest, TranscriptionResponse, Turn, VisionRequest, VisionResponse };
|