lemura 1.0.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -0
  3. package/README.md +143 -0
  4. package/dist/adapters/index.d.mts +45 -0
  5. package/dist/adapters/index.d.ts +45 -0
  6. package/dist/adapters/index.js +371 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/index.mjs +369 -0
  9. package/dist/adapters/index.mjs.map +1 -0
  10. package/dist/adapters-BSkhv5ac.d.ts +208 -0
  11. package/dist/adapters-BnG0LEYD.d.mts +208 -0
  12. package/dist/context/index.d.mts +143 -0
  13. package/dist/context/index.d.ts +143 -0
  14. package/dist/context/index.js +321 -0
  15. package/dist/context/index.js.map +1 -0
  16. package/dist/context/index.mjs +314 -0
  17. package/dist/context/index.mjs.map +1 -0
  18. package/dist/index.d.mts +91 -0
  19. package/dist/index.d.ts +91 -0
  20. package/dist/index.js +1375 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/index.mjs +1348 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/logger/index.d.mts +19 -0
  25. package/dist/logger/index.d.ts +19 -0
  26. package/dist/logger/index.js +67 -0
  27. package/dist/logger/index.js.map +1 -0
  28. package/dist/logger/index.mjs +65 -0
  29. package/dist/logger/index.mjs.map +1 -0
  30. package/dist/logger-DxvKliuk.d.mts +37 -0
  31. package/dist/logger-DxvKliuk.d.ts +37 -0
  32. package/dist/rag/index.d.mts +10 -0
  33. package/dist/rag/index.d.ts +10 -0
  34. package/dist/rag/index.js +43 -0
  35. package/dist/rag/index.js.map +1 -0
  36. package/dist/rag/index.mjs +41 -0
  37. package/dist/rag/index.mjs.map +1 -0
  38. package/dist/rag-La_Bo-J8.d.mts +45 -0
  39. package/dist/rag-La_Bo-J8.d.ts +45 -0
  40. package/dist/skills/index.d.mts +15 -0
  41. package/dist/skills/index.d.ts +15 -0
  42. package/dist/skills/index.js +40 -0
  43. package/dist/skills/index.js.map +1 -0
  44. package/dist/skills/index.mjs +38 -0
  45. package/dist/skills/index.mjs.map +1 -0
  46. package/dist/skills-wc8S-OvC.d.mts +14 -0
  47. package/dist/skills-wc8S-OvC.d.ts +14 -0
  48. package/dist/storage-BGu4Loao.d.ts +121 -0
  49. package/dist/storage-DMcliVVj.d.mts +121 -0
  50. package/dist/tools/index.d.mts +17 -0
  51. package/dist/tools/index.d.ts +17 -0
  52. package/dist/tools/index.js +72 -0
  53. package/dist/tools/index.js.map +1 -0
  54. package/dist/tools/index.mjs +70 -0
  55. package/dist/tools/index.mjs.map +1 -0
  56. package/dist/types/index.d.mts +118 -0
  57. package/dist/types/index.d.ts +118 -0
  58. package/dist/types/index.js +84 -0
  59. package/dist/types/index.js.map +1 -0
  60. package/dist/types/index.mjs +74 -0
  61. package/dist/types/index.mjs.map +1 -0
  62. package/package.json +79 -0
@@ -0,0 +1,314 @@
1
+ import { randomUUID } from 'crypto';
2
+
3
+ // src/types/errors.ts
4
+ var LemuraError = class extends Error {
5
+ /**
6
+ * @param message - The error message
7
+ * @param code - The error code for programmatic handling
8
+ * @param problem - A clear description of the problem for the end user
9
+ * @param hints - A list of suggestions to resolve the issue
10
+ */
11
+ constructor(message, code, problem, hints = []) {
12
+ super(message);
13
+ this.code = code;
14
+ this.problem = problem;
15
+ this.hints = hints;
16
+ this.name = "LemuraError";
17
+ Object.setPrototypeOf(this, new.target.prototype);
18
+ }
19
+ };
20
+ var LemuraContextOverflowError = class extends LemuraError {
21
+ constructor(message) {
22
+ super(message, "CONTEXT_OVERFLOW");
23
+ this.name = "LemuraContextOverflowError";
24
+ }
25
+ };
26
+
27
+ // src/context/ContextManager.ts
28
+ var ContextManager = class {
29
+ strategies = [];
30
+ /**
31
+ * Registers a new compression or pre-turn strategy and sorts the stack by priority.
32
+ *
33
+ * @param strategy - The strategy implementation to register
34
+ */
35
+ registerStrategy(strategy) {
36
+ this.strategies.push(strategy);
37
+ this.strategies.sort((a, b) => a.priority - b.priority);
38
+ }
39
+ /**
40
+ * Applies all registered strategies that return true for `shouldApply()`
41
+ * until the context token count is safely below the maximum budget.
42
+ *
43
+ * @param context - The context window to prepare
44
+ * @param safetyMargin - Modifier applied to maxTokens (default: 0.95 -> 95%)
45
+ * @returns A new ContextWindow object potentially compressed
46
+ * @throws {LemuraContextOverflowError} If the context is still over maxTokens after all strategies
47
+ */
48
+ async prepare(context, safetyMargin = 0.95) {
49
+ let currentCtx = { ...context, turns: [...context.turns] };
50
+ currentCtx.maxTokens * safetyMargin;
51
+ for (const strategy of this.strategies) {
52
+ if (strategy.shouldApply(currentCtx)) {
53
+ currentCtx = await strategy.apply(currentCtx);
54
+ }
55
+ }
56
+ if (currentCtx.tokenCount > currentCtx.maxTokens) {
57
+ throw new LemuraContextOverflowError(
58
+ `Context overflowed: ${currentCtx.tokenCount} tokens > ${currentCtx.maxTokens}`
59
+ );
60
+ }
61
+ return currentCtx;
62
+ }
63
+ };
64
+
65
+ // src/context/SandwichCompressionStrategy.ts
66
+ var SandwichCompressionStrategy = class {
67
+ constructor(adapter, config) {
68
+ this.adapter = adapter;
69
+ this.config = config;
70
+ }
71
+ name = "sandwich_compression";
72
+ priority = 20;
73
+ shouldApply(ctx) {
74
+ return ctx.tokenCount >= ctx.maxTokens * this.config.triggerThreshold && ctx.turns.length > this.config.preserveFirst + this.config.preserveLast;
75
+ }
76
+ async apply(ctx) {
77
+ const { preserveFirst, preserveLast } = this.config;
78
+ const head = ctx.turns.slice(0, preserveFirst);
79
+ const tail = ctx.turns.slice(ctx.turns.length - preserveLast);
80
+ const middle = ctx.turns.slice(preserveFirst, ctx.turns.length - preserveLast);
81
+ const middleText = middle.map((t) => `${t.role}: ${JSON.stringify(t.content)}`).join("\n");
82
+ const summaryResponse = await this.adapter.complete({
83
+ model: "",
84
+ messages: [{
85
+ role: "user",
86
+ content: `Summarize the following conversation history briefly:
87
+ ${middleText}`
88
+ }]
89
+ });
90
+ const summaryStr = summaryResponse.content;
91
+ const newCompressionSummary = ctx.compressionSummary ? `${ctx.compressionSummary}
92
+ ${summaryStr}` : summaryStr;
93
+ const summaryTurn = {
94
+ role: "system",
95
+ content: `[COMPRESSED HISTORY SUMMARY]
96
+ ${newCompressionSummary}`,
97
+ tokenCount: this.adapter.estimateTokens(newCompressionSummary),
98
+ turnIndex: -1,
99
+ compressed: true
100
+ };
101
+ const newTurns = [...head, summaryTurn, ...tail];
102
+ const newTokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) + this.adapter.estimateTokens(ctx.systemPrompt) + this.adapter.estimateTokens(ctx.scratchpad);
103
+ return {
104
+ ...ctx,
105
+ turns: newTurns,
106
+ tokenCount: newTokenCount,
107
+ compressionSummary: newCompressionSummary
108
+ };
109
+ }
110
+ /**
111
+ * Applies sandwich compression specifically to a Short Term Memory item's content.
112
+ * Implements a 3-layer pipeline: Pre-Layer (encoding), Core Layer (dense summary), Post-Layer (refinement cues).
113
+ *
114
+ * @param content - The heavy text content to compress
115
+ * @param instructions - Guiding instructions for the core layer summary
116
+ * @returns The three-layer sandwich result
117
+ */
118
+ async compressMemoryItem(content, instructions = "Extract the key information") {
119
+ const estimatedChunks = Math.max(1, Math.ceil(this.adapter.estimateTokens(content) / 2e3));
120
+ const preLayer = `[PRE-LAYER ENCODED: ${estimatedChunks} internal chunks]`;
121
+ const summaryResponse = await this.adapter.complete({
122
+ model: "",
123
+ messages: [{
124
+ role: "user",
125
+ content: `### INSTRUCTIONS ###
126
+ ${instructions}
127
+
128
+ ### CONTENT ###
129
+ ${content}
130
+
131
+ ### INSTRUCTIONS ###
132
+ ${instructions}`
133
+ }]
134
+ });
135
+ const coreLayer = summaryResponse.content;
136
+ const postLayer = `[POST-LAYER DECODING: Use \`refine_layer\` or \`read_chunk\` tools to expand specific sections]`;
137
+ return { preLayer, coreLayer, postLayer };
138
+ }
139
+ };
140
+
141
+ // src/context/HistoryCompressionStrategy.ts
142
+ var ScratchpadStrategy = class {
143
+ name = "scratchpad_strategy";
144
+ priority = 10;
145
+ shouldApply(ctx) {
146
+ return ctx.scratchpad.length > 0;
147
+ }
148
+ async apply(ctx) {
149
+ return ctx;
150
+ }
151
+ };
152
+ var HistoryCompressionStrategy = class {
153
+ constructor(adapter, config) {
154
+ this.adapter = adapter;
155
+ this.config = config;
156
+ }
157
+ name = "history_compression";
158
+ priority = 30;
159
+ shouldApply(ctx) {
160
+ const triggerTokens = ctx.maxTokens * this.config.triggerAtPercent;
161
+ const uncompressedTurns = ctx.turns.filter((t) => t.role !== "system" && !t.compressed);
162
+ return ctx.tokenCount >= triggerTokens && uncompressedTurns.length > this.config.windowSize;
163
+ }
164
+ async apply(ctx) {
165
+ const uncompressedIndices = ctx.turns.map((t, i) => ({ t, i })).filter(({ t }) => t.role !== "system" && !t.compressed).slice(0, this.config.windowSize);
166
+ const targetTurns = uncompressedIndices.map((u) => u.t);
167
+ const middleText = targetTurns.map((t) => `${t.role}: ${JSON.stringify(t.content)}`).join("\n");
168
+ const summaryResponse = await this.adapter.complete({
169
+ model: "",
170
+ messages: [{
171
+ role: "user",
172
+ content: `Summarize the oldest part of this conversation:
173
+ ${middleText}`
174
+ }]
175
+ });
176
+ const summaryStr = summaryResponse.content;
177
+ const newCompressionSummary = ctx.compressionSummary ? `${ctx.compressionSummary}
178
+ ${summaryStr}` : summaryStr;
179
+ const indicesToRemove = new Set(uncompressedIndices.map((u) => u.i));
180
+ const newTurns = ctx.turns.filter((_, i) => !indicesToRemove.has(i));
181
+ const TokenCount = newTurns.reduce((sum, t) => sum + t.tokenCount, 0) + this.adapter.estimateTokens(ctx.systemPrompt) + this.adapter.estimateTokens(ctx.scratchpad);
182
+ return {
183
+ ...ctx,
184
+ turns: newTurns,
185
+ tokenCount: TokenCount,
186
+ compressionSummary: newCompressionSummary
187
+ };
188
+ }
189
+ };
190
+ var ShortTermMemoryRegistry = class {
191
+ storage;
192
+ maxTextTokens;
193
+ constructor(config) {
194
+ this.storage = config.storage;
195
+ this.maxTextTokens = config.maxTextTokens ?? 1e5;
196
+ }
197
+ /**
198
+ * Registers a new memory item and returns its reference string.
199
+ *
200
+ * @param content - The raw content to store
201
+ * @param type - The type of content ('text' or 'blob')
202
+ * @param metadata - Optional metadata (e.g. sandwich layers, original filename)
203
+ * @param estimateTokens - Optional function to estimate token count for 'text' type
204
+ * @returns A reference string formatted as '[STM:uuid]'
205
+ * @throws {Error} if a text item exceeds the maxTextTokens limit
206
+ */
207
+ async register(content, type, metadata, estimateTokens) {
208
+ if (type === "text") {
209
+ const tokenCount = estimateTokens ? estimateTokens(content) : Math.ceil(String(content).length / 4);
210
+ if (tokenCount > this.maxTextTokens) {
211
+ throw new Error(`Text content exceeds max tokens limit of ${this.maxTextTokens} (estimated ${tokenCount})`);
212
+ }
213
+ }
214
+ const id = randomUUID();
215
+ const item = {
216
+ id,
217
+ content,
218
+ type,
219
+ ...metadata !== void 0 ? { metadata } : {}
220
+ };
221
+ await this.storage.set(id, item);
222
+ return `[STM:${id}]`;
223
+ }
224
+ /**
225
+ * Updates an existing STM item's content or metadata.
226
+ *
227
+ * @param id - The UUID of the item to update
228
+ * @param updates - Partial updates to apply (content or metadata)
229
+ */
230
+ async update(id, updates) {
231
+ const item = await this.storage.get(id);
232
+ if (!item) throw new Error(`STM item not found for update: ${id}`);
233
+ const updatedItem = {
234
+ ...item,
235
+ ...updates.content !== void 0 ? { content: updates.content } : {},
236
+ ...updates.metadata !== void 0 ? { metadata: { ...item.metadata, ...updates.metadata } } : {}
237
+ };
238
+ await this.storage.set(id, updatedItem);
239
+ }
240
+ /**
241
+ * Retrieves an STM item by its full reference string (e.g., '[STM:uuid]').
242
+ *
243
+ * @param ref - The full reference string
244
+ * @returns The STMItem or undefined if not found
245
+ */
246
+ async getByRef(ref) {
247
+ const match = ref.match(/^\[STM:(.+)\]$/);
248
+ if (!match || !match[1]) return void 0;
249
+ return this.storage.get(match[1]);
250
+ }
251
+ /**
252
+ * Deletes an STM item by its ID.
253
+ *
254
+ * @param id - The UUID of the item to delete
255
+ */
256
+ async delete(id) {
257
+ await this.storage.delete(id);
258
+ }
259
+ };
260
+ var InMemoryStorageAdapter = class {
261
+ store = /* @__PURE__ */ new Map();
262
+ /**
263
+ * Retrieves stored content by ID.
264
+ *
265
+ * @param id - The identifier of the stored item
266
+ * @returns The stored content or undefined if not found
267
+ */
268
+ async get(id) {
269
+ return this.store.get(id)?.content;
270
+ }
271
+ /**
272
+ * Returns the full item including metadata.
273
+ *
274
+ * @param id - The identifier of the stored item
275
+ * @returns The complete item with content and metadata
276
+ * @internal
277
+ */
278
+ async getFull(id) {
279
+ return this.store.get(id);
280
+ }
281
+ /**
282
+ * Stores content, generating an ID if none is provided.
283
+ *
284
+ * @param id - Optional provided ID. If omitted, a UUID is generated.
285
+ * @param content - The content to store
286
+ * @param metadata - Optional metadata
287
+ * @returns The ID under which the content is stored
288
+ */
289
+ async set(id, content, metadata) {
290
+ const resolvedId = id ?? randomUUID();
291
+ this.store.set(resolvedId, metadata !== void 0 ? { content, metadata } : { content });
292
+ return resolvedId;
293
+ }
294
+ /**
295
+ * Deletes the content for the given ID.
296
+ *
297
+ * @param id - The identifier of the item to delete
298
+ */
299
+ async delete(id) {
300
+ this.store.delete(id);
301
+ }
302
+ /**
303
+ * Synchronous health check, always true for in-memory.
304
+ *
305
+ * @returns true
306
+ */
307
+ async healthCheck() {
308
+ return true;
309
+ }
310
+ };
311
+
312
+ export { ContextManager, HistoryCompressionStrategy, InMemoryStorageAdapter, SandwichCompressionStrategy, ScratchpadStrategy, ShortTermMemoryRegistry };
313
+ //# sourceMappingURL=index.mjs.map
314
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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/InMemoryStorageAdapter.ts"],"names":["randomUUID"],"mappings":";;;AAMO,IAAM,WAA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A;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"]}
@@ -0,0 +1,91 @@
1
+ import { C as ContextWindow, T as Turn, a as ContentBlock } from './adapters-BnG0LEYD.mjs';
2
+ export { A as AudioChunk, b as CompletionChunk, c as CompletionRequest, d as CompletionResponse, I as IContextStrategy, e as IProviderAdapter, f as ImageGenRequest, g as ImageGenResponse, M as ModelInfo, N as NormalizedMessage, S as SynthesisRequest, h as TokenUsage, i as ToolCall, j as ToolResult, k as TranscriptionRequest, l as TranscriptionResponse, V as VisionRequest, m as VisionResponse } from './adapters-BnG0LEYD.mjs';
3
+ import { SessionConfig, IToolResponseProcessor, ToolResponseEvaluation } from './types/index.mjs';
4
+ export { LemuraAdapterError, LemuraContextOverflowError, LemuraError, LemuraMaxIterationsError, LemuraSkillInjectionError, LemuraToolNotFoundError, LemuraToolTimeoutError, LemuraToolValidationError } from './types/index.mjs';
5
+ export { I as ILogger, L as LogLevel, a as LogMetadata, S as Severity } from './logger-DxvKliuk.mjs';
6
+ 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
+ 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
+ export { OpenAICompatibleAdapter, OpenAICompatibleAdapterConfig, RetryConfig } from './adapters/index.mjs';
11
+ export { ContextManager, HistoryCompressionConfig, HistoryCompressionStrategy, InMemoryStorageAdapter, SandwichCompressionConfig, SandwichCompressionStrategy, ScratchpadStrategy } from './context/index.mjs';
12
+ export { ToolRegistry } from './tools/index.mjs';
13
+ export { SkillInjector } from './skills/index.mjs';
14
+ export { InMemoryRAGAdapter } from './rag/index.mjs';
15
+ export { DefaultLogger } from './logger/index.mjs';
16
+
17
+ declare class SessionManager {
18
+ private contextManager;
19
+ private toolRegistry;
20
+ private skillInjector;
21
+ private context;
22
+ private adapter;
23
+ private config;
24
+ private iterations;
25
+ private logger;
26
+ constructor(config: SessionConfig);
27
+ getContext(): ContextWindow;
28
+ getHistory(): Turn[];
29
+ run(userMessage: string | ContentBlock[]): Promise<string>;
30
+ }
31
+
32
+ /**
33
+ * Advanced Execution: ToolResponseProcessor handles compression
34
+ * and evaluation of tool outputs, flagging errors, mapping tool size classes
35
+ * and compressing large responses to save token bandwidth.
36
+ */
37
+ declare class ToolResponseProcessor implements IToolResponseProcessor {
38
+ evaluate(response: string, tool: IToolDefinition, context: unknown): ToolResponseEvaluation;
39
+ compress(response: string, evaluation: ToolResponseEvaluation): string;
40
+ }
41
+
42
+ interface Goal {
43
+ id: string;
44
+ statement: string;
45
+ decomposition: string[];
46
+ successCriteria: string[];
47
+ injectionFrequency: 'always' | 'every_N_turns' | 'on_compression';
48
+ injectionPosition: 'system_prompt' | 'pre_turn';
49
+ }
50
+ declare class GoalInjector {
51
+ private goal;
52
+ constructor(goal: Goal);
53
+ injectInto(prompt: string): string;
54
+ }
55
+
56
+ interface ContinuationStep {
57
+ stepId: string;
58
+ toolName: string;
59
+ description: string;
60
+ dependsOn: string[];
61
+ status: 'pending' | 'running' | 'done' | 'failed' | 'skipped';
62
+ outputKey?: string;
63
+ inputMapping?: Record<string, string>;
64
+ }
65
+ interface ContinuationPlan {
66
+ steps: ContinuationStep[];
67
+ currentStepIndex: number;
68
+ strategy: 'sequential' | 'parallel' | 'conditional';
69
+ }
70
+ declare class ContinuationPlanner {
71
+ private plan;
72
+ constructor(plan: ContinuationPlan);
73
+ getPlanStatusString(): string;
74
+ }
75
+
76
+ declare class StepCounter {
77
+ private maxSteps;
78
+ private toolCallCount;
79
+ constructor(maxSteps?: number);
80
+ increment(count?: number): void;
81
+ get count(): number;
82
+ isMaxReached(): boolean;
83
+ getForcedConclusionPrompt(): string;
84
+ }
85
+
86
+ declare class FinalResponseFormatter {
87
+ static getRequiredStructure(): string;
88
+ static validateStructure(response: string): boolean;
89
+ }
90
+
91
+ export { ContentBlock, ContextWindow, type ContinuationPlan, ContinuationPlanner, type ContinuationStep, FinalResponseFormatter, type Goal, GoalInjector, IToolDefinition, IToolResponseProcessor, SessionConfig, SessionManager, StepCounter, ToolResponseEvaluation, ToolResponseProcessor, Turn };
@@ -0,0 +1,91 @@
1
+ import { C as ContextWindow, T as Turn, a as ContentBlock } from './adapters-BSkhv5ac.js';
2
+ export { A as AudioChunk, b as CompletionChunk, c as CompletionRequest, d as CompletionResponse, I as IContextStrategy, e as IProviderAdapter, f as ImageGenRequest, g as ImageGenResponse, M as ModelInfo, N as NormalizedMessage, S as SynthesisRequest, h as TokenUsage, i as ToolCall, j as ToolResult, k as TranscriptionRequest, l as TranscriptionResponse, V as VisionRequest, m as VisionResponse } from './adapters-BSkhv5ac.js';
3
+ import { SessionConfig, IToolResponseProcessor, ToolResponseEvaluation } from './types/index.js';
4
+ export { LemuraAdapterError, LemuraContextOverflowError, LemuraError, LemuraMaxIterationsError, LemuraSkillInjectionError, LemuraToolNotFoundError, LemuraToolTimeoutError, LemuraToolValidationError } from './types/index.js';
5
+ export { I as ILogger, L as LogLevel, a as LogMetadata, S as Severity } from './logger-DxvKliuk.js';
6
+ 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.js';
7
+ export { I as ISkill } from './skills-wc8S-OvC.js';
8
+ import { I as IToolDefinition } from './storage-BGu4Loao.js';
9
+ export { a as IStorageAdapter, S as STMItem, b as STMRegistryConfig, c as ShortTermMemoryRegistry, T as ToolContext } from './storage-BGu4Loao.js';
10
+ export { OpenAICompatibleAdapter, OpenAICompatibleAdapterConfig, RetryConfig } from './adapters/index.js';
11
+ export { ContextManager, HistoryCompressionConfig, HistoryCompressionStrategy, InMemoryStorageAdapter, SandwichCompressionConfig, SandwichCompressionStrategy, ScratchpadStrategy } from './context/index.js';
12
+ export { ToolRegistry } from './tools/index.js';
13
+ export { SkillInjector } from './skills/index.js';
14
+ export { InMemoryRAGAdapter } from './rag/index.js';
15
+ export { DefaultLogger } from './logger/index.js';
16
+
17
+ declare class SessionManager {
18
+ private contextManager;
19
+ private toolRegistry;
20
+ private skillInjector;
21
+ private context;
22
+ private adapter;
23
+ private config;
24
+ private iterations;
25
+ private logger;
26
+ constructor(config: SessionConfig);
27
+ getContext(): ContextWindow;
28
+ getHistory(): Turn[];
29
+ run(userMessage: string | ContentBlock[]): Promise<string>;
30
+ }
31
+
32
+ /**
33
+ * Advanced Execution: ToolResponseProcessor handles compression
34
+ * and evaluation of tool outputs, flagging errors, mapping tool size classes
35
+ * and compressing large responses to save token bandwidth.
36
+ */
37
+ declare class ToolResponseProcessor implements IToolResponseProcessor {
38
+ evaluate(response: string, tool: IToolDefinition, context: unknown): ToolResponseEvaluation;
39
+ compress(response: string, evaluation: ToolResponseEvaluation): string;
40
+ }
41
+
42
+ interface Goal {
43
+ id: string;
44
+ statement: string;
45
+ decomposition: string[];
46
+ successCriteria: string[];
47
+ injectionFrequency: 'always' | 'every_N_turns' | 'on_compression';
48
+ injectionPosition: 'system_prompt' | 'pre_turn';
49
+ }
50
+ declare class GoalInjector {
51
+ private goal;
52
+ constructor(goal: Goal);
53
+ injectInto(prompt: string): string;
54
+ }
55
+
56
+ interface ContinuationStep {
57
+ stepId: string;
58
+ toolName: string;
59
+ description: string;
60
+ dependsOn: string[];
61
+ status: 'pending' | 'running' | 'done' | 'failed' | 'skipped';
62
+ outputKey?: string;
63
+ inputMapping?: Record<string, string>;
64
+ }
65
+ interface ContinuationPlan {
66
+ steps: ContinuationStep[];
67
+ currentStepIndex: number;
68
+ strategy: 'sequential' | 'parallel' | 'conditional';
69
+ }
70
+ declare class ContinuationPlanner {
71
+ private plan;
72
+ constructor(plan: ContinuationPlan);
73
+ getPlanStatusString(): string;
74
+ }
75
+
76
+ declare class StepCounter {
77
+ private maxSteps;
78
+ private toolCallCount;
79
+ constructor(maxSteps?: number);
80
+ increment(count?: number): void;
81
+ get count(): number;
82
+ isMaxReached(): boolean;
83
+ getForcedConclusionPrompt(): string;
84
+ }
85
+
86
+ declare class FinalResponseFormatter {
87
+ static getRequiredStructure(): string;
88
+ static validateStructure(response: string): boolean;
89
+ }
90
+
91
+ export { ContentBlock, ContextWindow, type ContinuationPlan, ContinuationPlanner, type ContinuationStep, FinalResponseFormatter, type Goal, GoalInjector, IToolDefinition, IToolResponseProcessor, SessionConfig, SessionManager, StepCounter, ToolResponseEvaluation, ToolResponseProcessor, Turn };