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
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { I as IToolDefinition, a as IProviderAdapter, b as IContextStrategy, S as ShortTermMemoryRegistry } from './storage-CG3nTa6o.mjs';
|
|
2
|
+
import { I as ILogger } from './logger-DxvKliuk.mjs';
|
|
3
|
+
import { I as ISkill } from './skills-wc8S-OvC.mjs';
|
|
4
|
+
import { I as IRAGAdapter } from './rag-La_Bo-J8.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* MCP (Model Context Protocol) transport and configuration types for lemura.
|
|
8
|
+
*/
|
|
9
|
+
/** Supported MCP server transport modes */
|
|
10
|
+
type MCPTransportType = 'stdio' | 'http' | 'sse';
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for a single MCP server connection.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* // stdio server
|
|
16
|
+
* const config: MCPServerConfig = {
|
|
17
|
+
* name: 'my_server',
|
|
18
|
+
* transport: 'stdio',
|
|
19
|
+
* command: 'npx',
|
|
20
|
+
* args: ['@modelcontextprotocol/server-github'],
|
|
21
|
+
* env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! }
|
|
22
|
+
* };
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* // HTTP server
|
|
26
|
+
* const config: MCPServerConfig = {
|
|
27
|
+
* name: 'remote_tools',
|
|
28
|
+
* transport: 'http',
|
|
29
|
+
* url: 'http://localhost:3001'
|
|
30
|
+
* };
|
|
31
|
+
*/
|
|
32
|
+
interface MCPServerConfig {
|
|
33
|
+
/** Unique name for this server (used to namespace tools) */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Transport mechanism to communicate with the server */
|
|
36
|
+
transport: MCPTransportType;
|
|
37
|
+
/**
|
|
38
|
+
* For `stdio`: the executable to spawn (e.g. `'npx'`, `'python'`).
|
|
39
|
+
* For `http`/`sse`: leave undefined — use `url` instead.
|
|
40
|
+
*/
|
|
41
|
+
command?: string;
|
|
42
|
+
/**
|
|
43
|
+
* For `stdio`: additional arguments passed to the spawned command.
|
|
44
|
+
* @example ['@modelcontextprotocol/server-github']
|
|
45
|
+
*/
|
|
46
|
+
args?: string[];
|
|
47
|
+
/**
|
|
48
|
+
* For `http`/`sse`: base URL of the MCP server.
|
|
49
|
+
* @example 'http://localhost:3001'
|
|
50
|
+
*/
|
|
51
|
+
url?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Environment variables injected into the spawned process (stdio only).
|
|
54
|
+
* Runtime env variables can be referenced before passing, e.g.:
|
|
55
|
+
* `{ GITHUB_TOKEN: process.env.GITHUB_TOKEN! }`
|
|
56
|
+
*/
|
|
57
|
+
env?: Record<string, string>;
|
|
58
|
+
/**
|
|
59
|
+
* Per-call timeout in milliseconds. Defaults to `30_000`.
|
|
60
|
+
*/
|
|
61
|
+
timeoutMs?: number;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A tool definition as returned by an MCP server's `tools/list` response.
|
|
65
|
+
* @internal Used by `MCPClient`; developers interact with `IToolDefinition` instead.
|
|
66
|
+
*/
|
|
67
|
+
interface MCPToolDefinition {
|
|
68
|
+
/** Tool name as declared by the MCP server */
|
|
69
|
+
name: string;
|
|
70
|
+
/** Human-readable description of what the tool does */
|
|
71
|
+
description: string;
|
|
72
|
+
/** JSON Schema for the tool's input parameters */
|
|
73
|
+
inputSchema: Record<string, unknown>;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Raw JSON-RPC 2.0 request envelope sent to an MCP server.
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
interface MCPJsonRpcRequest {
|
|
80
|
+
jsonrpc: '2.0';
|
|
81
|
+
id: number | string;
|
|
82
|
+
method: string;
|
|
83
|
+
params?: Record<string, unknown>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Raw JSON-RPC 2.0 response envelope received from an MCP server.
|
|
87
|
+
* @internal
|
|
88
|
+
*/
|
|
89
|
+
interface MCPJsonRpcResponse {
|
|
90
|
+
jsonrpc: '2.0';
|
|
91
|
+
id: number | string;
|
|
92
|
+
result?: unknown;
|
|
93
|
+
error?: {
|
|
94
|
+
code: number;
|
|
95
|
+
message: string;
|
|
96
|
+
data?: unknown;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface ToolResponseEvaluation {
|
|
101
|
+
relevanceScore: number;
|
|
102
|
+
sizeClass: 'small' | 'medium' | 'large' | 'oversized';
|
|
103
|
+
shouldCompress: boolean;
|
|
104
|
+
suggestedMaxTokens: number;
|
|
105
|
+
answered: boolean;
|
|
106
|
+
answeredPartially: boolean;
|
|
107
|
+
errorDetected: boolean;
|
|
108
|
+
suggestedAction: 'continue' | 'retry' | 'retry_with_params' | 'skip' | 'escalate';
|
|
109
|
+
}
|
|
110
|
+
interface IToolResponseProcessor {
|
|
111
|
+
evaluate(response: string, tool: IToolDefinition, context: unknown): ToolResponseEvaluation;
|
|
112
|
+
compress(response: string, evaluation: ToolResponseEvaluation): string;
|
|
113
|
+
}
|
|
114
|
+
interface MediaConfig {
|
|
115
|
+
enableTools?: boolean;
|
|
116
|
+
toolPrefix?: string;
|
|
117
|
+
}
|
|
118
|
+
type ToolDecision = 'accept' | 'deny' | 'ask';
|
|
119
|
+
interface ToolFirewallRule {
|
|
120
|
+
/** Regex pattern matched against the tool name */
|
|
121
|
+
name?: string;
|
|
122
|
+
/** Regex pattern matched against the serialised arguments JSON */
|
|
123
|
+
arguments?: string;
|
|
124
|
+
/** Decision to apply when this rule matches */
|
|
125
|
+
decision: ToolDecision;
|
|
126
|
+
/** Human-readable reason surfaced to the agent when blocked */
|
|
127
|
+
reason?: string;
|
|
128
|
+
}
|
|
129
|
+
interface ToolFirewallConfig {
|
|
130
|
+
/** Decision applied when no rule matches. Defaults to 'ask'. */
|
|
131
|
+
defaultDecision?: ToolDecision;
|
|
132
|
+
/** Ordered list of firewall rules — first match wins */
|
|
133
|
+
rules?: ToolFirewallRule[];
|
|
134
|
+
/**
|
|
135
|
+
* Called when a tool hits the 'ask' decision.
|
|
136
|
+
* Return 'accept' or 'deny'. If omitted, 'ask' behaves like 'deny'.
|
|
137
|
+
*/
|
|
138
|
+
onAsk?: (toolName: string, argsJson: string) => Promise<'accept' | 'deny'> | 'accept' | 'deny';
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Execution budget constraints for tool calls within a session.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* toolExecutionBudget: {
|
|
145
|
+
* maxCallsPerSession: 50,
|
|
146
|
+
* maxCallsPerTool: { search_web: 10 },
|
|
147
|
+
* maxConcurrentCalls: 4,
|
|
148
|
+
* }
|
|
149
|
+
*/
|
|
150
|
+
interface ToolExecutionBudget {
|
|
151
|
+
/** Maximum total tool calls allowed for the entire session */
|
|
152
|
+
maxCallsPerSession?: number;
|
|
153
|
+
/** Maximum calls per named tool within the session */
|
|
154
|
+
maxCallsPerTool?: Record<string, number>;
|
|
155
|
+
/** Maximum simultaneous parallel tool executions (default: unlimited) */
|
|
156
|
+
maxConcurrentCalls?: number;
|
|
157
|
+
}
|
|
158
|
+
/** Configuration for a lemura Session */
|
|
159
|
+
interface SessionConfig {
|
|
160
|
+
/** The provider adapter to use */
|
|
161
|
+
adapter: IProviderAdapter;
|
|
162
|
+
/** Model string */
|
|
163
|
+
model: string;
|
|
164
|
+
/** Max context tokens */
|
|
165
|
+
maxTokens: number;
|
|
166
|
+
/** Max ReAct cycles */
|
|
167
|
+
maxIterations?: number;
|
|
168
|
+
/** Explicit tools */
|
|
169
|
+
tools?: IToolDefinition[];
|
|
170
|
+
/** Explicit skills */
|
|
171
|
+
skills?: ISkill[];
|
|
172
|
+
/** RAG adapter */
|
|
173
|
+
ragAdapter?: IRAGAdapter;
|
|
174
|
+
/** Context compression strategies */
|
|
175
|
+
compressionStrategies?: IContextStrategy[];
|
|
176
|
+
/** System prompt base */
|
|
177
|
+
systemPrompt?: string;
|
|
178
|
+
/** Logger */
|
|
179
|
+
logger?: ILogger;
|
|
180
|
+
/** Media bridge config */
|
|
181
|
+
media?: MediaConfig;
|
|
182
|
+
/** Tool firewall config */
|
|
183
|
+
toolFirewall?: ToolFirewallConfig;
|
|
184
|
+
/** Budget for tool responses before compression */
|
|
185
|
+
toolResponseTokenBudget?: number;
|
|
186
|
+
/** Processor for tool responses */
|
|
187
|
+
toolResponseProcessor?: IToolResponseProcessor;
|
|
188
|
+
/** Max single steps (tool calls) */
|
|
189
|
+
maxSteps?: number;
|
|
190
|
+
/** Enable tool continuation planning */
|
|
191
|
+
enableContinuationPlanning?: boolean;
|
|
192
|
+
continuationStrategy?: 'sequential' | 'parallel' | 'conditional';
|
|
193
|
+
/** Enable goal planning */
|
|
194
|
+
enableGoalPlanning?: boolean;
|
|
195
|
+
goalInjectionFrequency?: 'always' | 'every_N_turns' | 'on_compression';
|
|
196
|
+
goalInjectionPosition?: 'system_prompt' | 'pre_turn';
|
|
197
|
+
/** Skill budget */
|
|
198
|
+
skillTokenBudget?: number;
|
|
199
|
+
/** Callback for each turn in the session */
|
|
200
|
+
onTurn?: (turn: any) => void;
|
|
201
|
+
/** Short Term Memory Registry */
|
|
202
|
+
stmRegistry?: ShortTermMemoryRegistry;
|
|
203
|
+
/** Max tokens allowed for a single tool response */
|
|
204
|
+
maxTokensPerTool?: number;
|
|
205
|
+
/**
|
|
206
|
+
* Execution budget constraints: call quotas and concurrency cap.
|
|
207
|
+
* Enforced in the ReAct loop before each tool call.
|
|
208
|
+
*/
|
|
209
|
+
toolExecutionBudget?: ToolExecutionBudget;
|
|
210
|
+
/**
|
|
211
|
+
* When true, independent tool calls within a single assistant response are
|
|
212
|
+
* executed in parallel using `Promise.all`. Defaults to false (sequential).
|
|
213
|
+
*/
|
|
214
|
+
parallelToolCalls?: boolean;
|
|
215
|
+
/**
|
|
216
|
+
* Default timeout in ms for each tool execution.
|
|
217
|
+
* Passed to `ToolRegistry`. Defaults to 30 000.
|
|
218
|
+
*/
|
|
219
|
+
toolRegistryTimeoutMs?: number;
|
|
220
|
+
/** Callback for granular trace events (planning, budgets, tools, etc.) */
|
|
221
|
+
onTrace?: (event: TraceEvent) => void;
|
|
222
|
+
/**
|
|
223
|
+
* MCP (Model Context Protocol) server configurations.
|
|
224
|
+
* Each server is connected at session construction, its tools are discovered
|
|
225
|
+
* and registered alongside native tools — fully transparent to the ReAct loop.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* mcpServers: [
|
|
229
|
+
* { name: 'github', transport: 'stdio', command: 'npx', args: ['@modelcontextprotocol/server-github'] },
|
|
230
|
+
* { name: 'db_tools', transport: 'http', url: 'http://localhost:3001' }
|
|
231
|
+
* ]
|
|
232
|
+
*/
|
|
233
|
+
mcpServers?: MCPServerConfig[];
|
|
234
|
+
}
|
|
235
|
+
/** Rich trace event for observability */
|
|
236
|
+
interface TraceEvent {
|
|
237
|
+
sessionId?: string;
|
|
238
|
+
type: 'planning' | 'budget' | 'tool_call' | 'tool_result' | 'thinking' | 'system' | 'compression' | 'error';
|
|
239
|
+
name: string;
|
|
240
|
+
input?: any;
|
|
241
|
+
output?: any;
|
|
242
|
+
durationMs?: number;
|
|
243
|
+
startedAt?: number;
|
|
244
|
+
status?: 'running' | 'done' | 'error';
|
|
245
|
+
metadata?: Record<string, any>;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export type { IToolResponseProcessor as I, MCPServerConfig as M, SessionConfig as S, ToolResponseEvaluation as T, MCPToolDefinition as a, MCPJsonRpcRequest as b, MCPJsonRpcResponse as c, MCPTransportType as d, MediaConfig as e, ToolDecision as f, ToolExecutionBudget as g, ToolFirewallConfig as h, ToolFirewallRule as i, TraceEvent as j };
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { I as IToolDefinition, a as IProviderAdapter, b as IContextStrategy, S as ShortTermMemoryRegistry } from './storage-DBt_q0wO.js';
|
|
2
|
+
import { I as ILogger } from './logger-DxvKliuk.js';
|
|
3
|
+
import { I as ISkill } from './skills-wc8S-OvC.js';
|
|
4
|
+
import { I as IRAGAdapter } from './rag-La_Bo-J8.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* MCP (Model Context Protocol) transport and configuration types for lemura.
|
|
8
|
+
*/
|
|
9
|
+
/** Supported MCP server transport modes */
|
|
10
|
+
type MCPTransportType = 'stdio' | 'http' | 'sse';
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for a single MCP server connection.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* // stdio server
|
|
16
|
+
* const config: MCPServerConfig = {
|
|
17
|
+
* name: 'my_server',
|
|
18
|
+
* transport: 'stdio',
|
|
19
|
+
* command: 'npx',
|
|
20
|
+
* args: ['@modelcontextprotocol/server-github'],
|
|
21
|
+
* env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! }
|
|
22
|
+
* };
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* // HTTP server
|
|
26
|
+
* const config: MCPServerConfig = {
|
|
27
|
+
* name: 'remote_tools',
|
|
28
|
+
* transport: 'http',
|
|
29
|
+
* url: 'http://localhost:3001'
|
|
30
|
+
* };
|
|
31
|
+
*/
|
|
32
|
+
interface MCPServerConfig {
|
|
33
|
+
/** Unique name for this server (used to namespace tools) */
|
|
34
|
+
name: string;
|
|
35
|
+
/** Transport mechanism to communicate with the server */
|
|
36
|
+
transport: MCPTransportType;
|
|
37
|
+
/**
|
|
38
|
+
* For `stdio`: the executable to spawn (e.g. `'npx'`, `'python'`).
|
|
39
|
+
* For `http`/`sse`: leave undefined — use `url` instead.
|
|
40
|
+
*/
|
|
41
|
+
command?: string;
|
|
42
|
+
/**
|
|
43
|
+
* For `stdio`: additional arguments passed to the spawned command.
|
|
44
|
+
* @example ['@modelcontextprotocol/server-github']
|
|
45
|
+
*/
|
|
46
|
+
args?: string[];
|
|
47
|
+
/**
|
|
48
|
+
* For `http`/`sse`: base URL of the MCP server.
|
|
49
|
+
* @example 'http://localhost:3001'
|
|
50
|
+
*/
|
|
51
|
+
url?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Environment variables injected into the spawned process (stdio only).
|
|
54
|
+
* Runtime env variables can be referenced before passing, e.g.:
|
|
55
|
+
* `{ GITHUB_TOKEN: process.env.GITHUB_TOKEN! }`
|
|
56
|
+
*/
|
|
57
|
+
env?: Record<string, string>;
|
|
58
|
+
/**
|
|
59
|
+
* Per-call timeout in milliseconds. Defaults to `30_000`.
|
|
60
|
+
*/
|
|
61
|
+
timeoutMs?: number;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A tool definition as returned by an MCP server's `tools/list` response.
|
|
65
|
+
* @internal Used by `MCPClient`; developers interact with `IToolDefinition` instead.
|
|
66
|
+
*/
|
|
67
|
+
interface MCPToolDefinition {
|
|
68
|
+
/** Tool name as declared by the MCP server */
|
|
69
|
+
name: string;
|
|
70
|
+
/** Human-readable description of what the tool does */
|
|
71
|
+
description: string;
|
|
72
|
+
/** JSON Schema for the tool's input parameters */
|
|
73
|
+
inputSchema: Record<string, unknown>;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Raw JSON-RPC 2.0 request envelope sent to an MCP server.
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
interface MCPJsonRpcRequest {
|
|
80
|
+
jsonrpc: '2.0';
|
|
81
|
+
id: number | string;
|
|
82
|
+
method: string;
|
|
83
|
+
params?: Record<string, unknown>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Raw JSON-RPC 2.0 response envelope received from an MCP server.
|
|
87
|
+
* @internal
|
|
88
|
+
*/
|
|
89
|
+
interface MCPJsonRpcResponse {
|
|
90
|
+
jsonrpc: '2.0';
|
|
91
|
+
id: number | string;
|
|
92
|
+
result?: unknown;
|
|
93
|
+
error?: {
|
|
94
|
+
code: number;
|
|
95
|
+
message: string;
|
|
96
|
+
data?: unknown;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface ToolResponseEvaluation {
|
|
101
|
+
relevanceScore: number;
|
|
102
|
+
sizeClass: 'small' | 'medium' | 'large' | 'oversized';
|
|
103
|
+
shouldCompress: boolean;
|
|
104
|
+
suggestedMaxTokens: number;
|
|
105
|
+
answered: boolean;
|
|
106
|
+
answeredPartially: boolean;
|
|
107
|
+
errorDetected: boolean;
|
|
108
|
+
suggestedAction: 'continue' | 'retry' | 'retry_with_params' | 'skip' | 'escalate';
|
|
109
|
+
}
|
|
110
|
+
interface IToolResponseProcessor {
|
|
111
|
+
evaluate(response: string, tool: IToolDefinition, context: unknown): ToolResponseEvaluation;
|
|
112
|
+
compress(response: string, evaluation: ToolResponseEvaluation): string;
|
|
113
|
+
}
|
|
114
|
+
interface MediaConfig {
|
|
115
|
+
enableTools?: boolean;
|
|
116
|
+
toolPrefix?: string;
|
|
117
|
+
}
|
|
118
|
+
type ToolDecision = 'accept' | 'deny' | 'ask';
|
|
119
|
+
interface ToolFirewallRule {
|
|
120
|
+
/** Regex pattern matched against the tool name */
|
|
121
|
+
name?: string;
|
|
122
|
+
/** Regex pattern matched against the serialised arguments JSON */
|
|
123
|
+
arguments?: string;
|
|
124
|
+
/** Decision to apply when this rule matches */
|
|
125
|
+
decision: ToolDecision;
|
|
126
|
+
/** Human-readable reason surfaced to the agent when blocked */
|
|
127
|
+
reason?: string;
|
|
128
|
+
}
|
|
129
|
+
interface ToolFirewallConfig {
|
|
130
|
+
/** Decision applied when no rule matches. Defaults to 'ask'. */
|
|
131
|
+
defaultDecision?: ToolDecision;
|
|
132
|
+
/** Ordered list of firewall rules — first match wins */
|
|
133
|
+
rules?: ToolFirewallRule[];
|
|
134
|
+
/**
|
|
135
|
+
* Called when a tool hits the 'ask' decision.
|
|
136
|
+
* Return 'accept' or 'deny'. If omitted, 'ask' behaves like 'deny'.
|
|
137
|
+
*/
|
|
138
|
+
onAsk?: (toolName: string, argsJson: string) => Promise<'accept' | 'deny'> | 'accept' | 'deny';
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Execution budget constraints for tool calls within a session.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* toolExecutionBudget: {
|
|
145
|
+
* maxCallsPerSession: 50,
|
|
146
|
+
* maxCallsPerTool: { search_web: 10 },
|
|
147
|
+
* maxConcurrentCalls: 4,
|
|
148
|
+
* }
|
|
149
|
+
*/
|
|
150
|
+
interface ToolExecutionBudget {
|
|
151
|
+
/** Maximum total tool calls allowed for the entire session */
|
|
152
|
+
maxCallsPerSession?: number;
|
|
153
|
+
/** Maximum calls per named tool within the session */
|
|
154
|
+
maxCallsPerTool?: Record<string, number>;
|
|
155
|
+
/** Maximum simultaneous parallel tool executions (default: unlimited) */
|
|
156
|
+
maxConcurrentCalls?: number;
|
|
157
|
+
}
|
|
158
|
+
/** Configuration for a lemura Session */
|
|
159
|
+
interface SessionConfig {
|
|
160
|
+
/** The provider adapter to use */
|
|
161
|
+
adapter: IProviderAdapter;
|
|
162
|
+
/** Model string */
|
|
163
|
+
model: string;
|
|
164
|
+
/** Max context tokens */
|
|
165
|
+
maxTokens: number;
|
|
166
|
+
/** Max ReAct cycles */
|
|
167
|
+
maxIterations?: number;
|
|
168
|
+
/** Explicit tools */
|
|
169
|
+
tools?: IToolDefinition[];
|
|
170
|
+
/** Explicit skills */
|
|
171
|
+
skills?: ISkill[];
|
|
172
|
+
/** RAG adapter */
|
|
173
|
+
ragAdapter?: IRAGAdapter;
|
|
174
|
+
/** Context compression strategies */
|
|
175
|
+
compressionStrategies?: IContextStrategy[];
|
|
176
|
+
/** System prompt base */
|
|
177
|
+
systemPrompt?: string;
|
|
178
|
+
/** Logger */
|
|
179
|
+
logger?: ILogger;
|
|
180
|
+
/** Media bridge config */
|
|
181
|
+
media?: MediaConfig;
|
|
182
|
+
/** Tool firewall config */
|
|
183
|
+
toolFirewall?: ToolFirewallConfig;
|
|
184
|
+
/** Budget for tool responses before compression */
|
|
185
|
+
toolResponseTokenBudget?: number;
|
|
186
|
+
/** Processor for tool responses */
|
|
187
|
+
toolResponseProcessor?: IToolResponseProcessor;
|
|
188
|
+
/** Max single steps (tool calls) */
|
|
189
|
+
maxSteps?: number;
|
|
190
|
+
/** Enable tool continuation planning */
|
|
191
|
+
enableContinuationPlanning?: boolean;
|
|
192
|
+
continuationStrategy?: 'sequential' | 'parallel' | 'conditional';
|
|
193
|
+
/** Enable goal planning */
|
|
194
|
+
enableGoalPlanning?: boolean;
|
|
195
|
+
goalInjectionFrequency?: 'always' | 'every_N_turns' | 'on_compression';
|
|
196
|
+
goalInjectionPosition?: 'system_prompt' | 'pre_turn';
|
|
197
|
+
/** Skill budget */
|
|
198
|
+
skillTokenBudget?: number;
|
|
199
|
+
/** Callback for each turn in the session */
|
|
200
|
+
onTurn?: (turn: any) => void;
|
|
201
|
+
/** Short Term Memory Registry */
|
|
202
|
+
stmRegistry?: ShortTermMemoryRegistry;
|
|
203
|
+
/** Max tokens allowed for a single tool response */
|
|
204
|
+
maxTokensPerTool?: number;
|
|
205
|
+
/**
|
|
206
|
+
* Execution budget constraints: call quotas and concurrency cap.
|
|
207
|
+
* Enforced in the ReAct loop before each tool call.
|
|
208
|
+
*/
|
|
209
|
+
toolExecutionBudget?: ToolExecutionBudget;
|
|
210
|
+
/**
|
|
211
|
+
* When true, independent tool calls within a single assistant response are
|
|
212
|
+
* executed in parallel using `Promise.all`. Defaults to false (sequential).
|
|
213
|
+
*/
|
|
214
|
+
parallelToolCalls?: boolean;
|
|
215
|
+
/**
|
|
216
|
+
* Default timeout in ms for each tool execution.
|
|
217
|
+
* Passed to `ToolRegistry`. Defaults to 30 000.
|
|
218
|
+
*/
|
|
219
|
+
toolRegistryTimeoutMs?: number;
|
|
220
|
+
/** Callback for granular trace events (planning, budgets, tools, etc.) */
|
|
221
|
+
onTrace?: (event: TraceEvent) => void;
|
|
222
|
+
/**
|
|
223
|
+
* MCP (Model Context Protocol) server configurations.
|
|
224
|
+
* Each server is connected at session construction, its tools are discovered
|
|
225
|
+
* and registered alongside native tools — fully transparent to the ReAct loop.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* mcpServers: [
|
|
229
|
+
* { name: 'github', transport: 'stdio', command: 'npx', args: ['@modelcontextprotocol/server-github'] },
|
|
230
|
+
* { name: 'db_tools', transport: 'http', url: 'http://localhost:3001' }
|
|
231
|
+
* ]
|
|
232
|
+
*/
|
|
233
|
+
mcpServers?: MCPServerConfig[];
|
|
234
|
+
}
|
|
235
|
+
/** Rich trace event for observability */
|
|
236
|
+
interface TraceEvent {
|
|
237
|
+
sessionId?: string;
|
|
238
|
+
type: 'planning' | 'budget' | 'tool_call' | 'tool_result' | 'thinking' | 'system' | 'compression' | 'error';
|
|
239
|
+
name: string;
|
|
240
|
+
input?: any;
|
|
241
|
+
output?: any;
|
|
242
|
+
durationMs?: number;
|
|
243
|
+
startedAt?: number;
|
|
244
|
+
status?: 'running' | 'done' | 'error';
|
|
245
|
+
metadata?: Record<string, any>;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export type { IToolResponseProcessor as I, MCPServerConfig as M, SessionConfig as S, ToolResponseEvaluation as T, MCPToolDefinition as a, MCPJsonRpcRequest as b, MCPJsonRpcResponse as c, MCPTransportType as d, MediaConfig as e, ToolDecision as f, ToolExecutionBudget as g, ToolFirewallConfig as h, ToolFirewallRule as i, TraceEvent as j };
|
package/dist/context/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export { b as STMRegistryConfig, c as ShortTermMemoryRegistry } from '../storage-DMcliVVj.mjs';
|
|
1
|
+
import { b as IContextStrategy, C as ContextWindow, a as IProviderAdapter, m as IStorageAdapter } from '../storage-CG3nTa6o.mjs';
|
|
2
|
+
export { o as STMRegistryConfig, S as ShortTermMemoryRegistry } from '../storage-CG3nTa6o.mjs';
|
|
4
3
|
import '../rag-La_Bo-J8.mjs';
|
|
5
4
|
import '../logger-DxvKliuk.mjs';
|
|
6
5
|
|
package/dist/context/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export { b as STMRegistryConfig, c as ShortTermMemoryRegistry } from '../storage-BGu4Loao.js';
|
|
1
|
+
import { b as IContextStrategy, C as ContextWindow, a as IProviderAdapter, m as IStorageAdapter } from '../storage-DBt_q0wO.js';
|
|
2
|
+
export { o as STMRegistryConfig, S as ShortTermMemoryRegistry } from '../storage-DBt_q0wO.js';
|
|
4
3
|
import '../rag-La_Bo-J8.js';
|
|
5
4
|
import '../logger-DxvKliuk.js';
|
|
6
5
|
|
|
@@ -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/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,IAAM,0BAAA,GAAN,cAAyC,WAAA,CAAY;AAAA,EACxD,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,SAAS,kBAAkB,CAAA;AACjC,IAAA,IAAA,CAAK,IAAA,GAAO,4BAAA;AAAA,EAChB;AACJ,CAAA;;;ACzBO,IAAM,iBAAN,MAAqB;AAAA,EAChB,aAAiC,EAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO1C,iBAAiB,QAAA,EAAkC;AAC/C,IAAA,IAAA,CAAK,UAAA,CAAW,KAAK,QA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AO,EAAE,CAAA;AAAA,EAChC;AACJ;AC9FO,IAAM,yBAAN,MAAwD;AAAA,EACnD,KAAA,uBAAY,GAAA,EAAkE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtF,MAAM,IAAI,EAAA,EAAsC;AAC5C,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA,EAAG,OAAA;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,QAAQ,EAAA,EAAuF;AACjG,IAAA,OAAO,IAAA,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,iBAAAA,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.js","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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wB,OAAA,EAAc,QAAA,EAAqD;AACjG,IAAA,MAAM,UAAA,GAAa,MAAMA,iBAAAA,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.js","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"]}
|