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/dist/index.d.ts CHANGED
@@ -1,19 +1,51 @@
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';
1
+ import { a as IProviderAdapter, T as TranscriptionRequest, c as TranscriptionResponse, d as SynthesisRequest, A as AudioChunk, V as VisionRequest, e as VisionResponse, f as ImageGenRequest, g as ImageGenResponse, M as ModelInfo, C as ContextWindow, h as Turn, i as ContentBlock, I as IToolDefinition } from './storage-DBt_q0wO.js';
2
+ export { j as CompletionChunk, k as CompletionRequest, l as CompletionResponse, b as IContextStrategy, m as IStorageAdapter, N as NormalizedMessage, n as STMItem, o as STMRegistryConfig, S as ShortTermMemoryRegistry, p as TokenUsage, q as ToolCall, r as ToolContext, s as ToolResult } from './storage-DBt_q0wO.js';
3
+ import { S as SessionConfig, I as IToolResponseProcessor, T as ToolResponseEvaluation, M as MCPServerConfig, a as MCPToolDefinition } from './agent-DxRd93wl.js';
4
+ export { b as MCPJsonRpcRequest, c as MCPJsonRpcResponse, d as MCPTransportType, e as MediaConfig, f as ToolDecision, g as ToolExecutionBudget, h as ToolFirewallConfig, i as ToolFirewallRule, j as TraceEvent } from './agent-DxRd93wl.js';
5
+ export { LemuraAdapterError, LemuraContextOverflowError, LemuraError, LemuraMCPConnectionError, LemuraMCPError, LemuraMCPTimeoutError, LemuraMaxIterationsError, LemuraSkillInjectionError, LemuraToolNotFoundError, LemuraToolTimeoutError, LemuraToolValidationError } from './types/index.js';
6
+ import { I as ILogger } from './logger-DxvKliuk.js';
7
+ export { L as LogLevel, a as LogMetadata, S as Severity } from './logger-DxvKliuk.js';
6
8
  export { I as IRAGAdapter, R as RAGDocument, a as RAGIngestOptions, b as RAGIngestRequest, c as RAGIngestResponse, d as RAGQueryRequest, e as RAGQueryResponse, f as RAGResult } from './rag-La_Bo-J8.js';
7
9
  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
10
  export { OpenAICompatibleAdapter, OpenAICompatibleAdapterConfig, RetryConfig } from './adapters/index.js';
11
11
  export { ContextManager, HistoryCompressionConfig, HistoryCompressionStrategy, InMemoryStorageAdapter, SandwichCompressionConfig, SandwichCompressionStrategy, ScratchpadStrategy } from './context/index.js';
12
- export { ToolRegistry } from './tools/index.js';
12
+ export { SchemaValidationError, ToolFirewallResult, ToolRegistry, ToolRegistryOptions, evaluateToolFirewall, validateJsonSchema } from './tools/index.js';
13
13
  export { SkillInjector } from './skills/index.js';
14
14
  export { InMemoryRAGAdapter } from './rag/index.js';
15
15
  export { DefaultLogger } from './logger/index.js';
16
16
 
17
+ /**
18
+ * MediaBridge provides a single, app-friendly entry point for audio/vision/image features.
19
+ */
20
+ declare class MediaBridge {
21
+ private adapter;
22
+ constructor(adapter: IProviderAdapter);
23
+ transcribe(request: TranscriptionRequest): Promise<TranscriptionResponse>;
24
+ synthesize(request: SynthesisRequest): AsyncIterable<AudioChunk>;
25
+ synthesizeToArray(request: SynthesisRequest): Promise<AudioChunk[]>;
26
+ describeImage(request: VisionRequest): Promise<VisionResponse>;
27
+ generateImage(request: ImageGenRequest): Promise<ImageGenResponse>;
28
+ getModelInfo(): ModelInfo;
29
+ supportsVision(): boolean;
30
+ }
31
+
32
+ /**
33
+ * Core entry point for lemura agent sessions.
34
+ *
35
+ * `SessionManager` owns the full ReAct loop lifecycle:
36
+ * - Context window management and compression
37
+ * - Skill injection
38
+ * - Tool firewall + schema validation + timeout enforcement
39
+ * - Parallel tool execution (opt-in via `parallelToolCalls`)
40
+ * - maxSteps guard → forced graceful conclusion
41
+ * - Tool response compression (via `toolResponseProcessor`)
42
+ * - Goal injection (via `enableGoalPlanning`)
43
+ * - Streaming output (`stream()`)
44
+ *
45
+ * @example
46
+ * const session = new SessionManager({ adapter, model: 'gpt-4o', maxTokens: 16_000 });
47
+ * const answer = await session.run('What is the capital of France?');
48
+ */
17
49
  declare class SessionManager {
18
50
  private contextManager;
19
51
  private toolRegistry;
@@ -23,10 +55,97 @@ declare class SessionManager {
23
55
  private config;
24
56
  private iterations;
25
57
  private logger;
58
+ private media;
59
+ private stepCounter;
60
+ private toolResponseProcessor;
61
+ private goalInjector;
62
+ private continuationPlanner;
63
+ private mcpRegistry;
64
+ /** Resolves when all MCP servers are connected; used by run() and stream() */
65
+ private mcpReady;
66
+ private totalToolCallCount;
67
+ private perToolCallCount;
68
+ private totalTokens;
26
69
  constructor(config: SessionConfig);
70
+ private emitTrace;
71
+ /**
72
+ * Returns a shallow copy of the current context window.
73
+ */
27
74
  getContext(): ContextWindow;
75
+ /**
76
+ * Returns the current conversation history.
77
+ */
28
78
  getHistory(): Turn[];
79
+ /**
80
+ * Returns the `MediaBridge` for direct ASR / TTS / Vision / Image-gen calls.
81
+ */
82
+ getMedia(): MediaBridge;
83
+ /**
84
+ * Connects all configured MCP servers and registers their bridged tools.
85
+ * Called from the constructor as a fire-and-start async task; `run()` and
86
+ * `stream()` await `this.mcpReady` before executing.
87
+ */
88
+ private _initMCP;
89
+ /** Builds the system prompt, injecting skills and goal if configured. */
90
+ private buildSystemPrompt;
91
+ /** Builds the messages array for the provider from the current context */
92
+ private buildMessages;
93
+ /** Checks the tool execution budget and throws descriptively if exceeded */
94
+ private checkExecutionBudget;
95
+ /** Records a tool call in budget counters */
96
+ private recordToolCall;
97
+ /**
98
+ * Processes a firewall decision for a tool call.
99
+ * Returns true to proceed, false to block.
100
+ */
101
+ private passesFirewall;
102
+ /**
103
+ * Executes a single parsed tool call and returns the serialised result string.
104
+ */
105
+ private executeSingleToolCall;
106
+ /**
107
+ * Runs the full ReAct loop for a user message and returns the final assistant response.
108
+ *
109
+ * @param userMessage - The user's message (string or multimodal content blocks)
110
+ * @returns The assistant's final response string
111
+ * @throws {LemuraMaxIterationsError} When the loop exceeds `maxIterations`
112
+ */
29
113
  run(userMessage: string | ContentBlock[]): Promise<string>;
114
+ /**
115
+ * Runs the ReAct loop and streams the final assistant response token-by-token.
116
+ *
117
+ * Tool calls within the loop are still executed synchronously (they must complete
118
+ * before streaming the conclusion). Only the final LLM text output is streamed.
119
+ *
120
+ * @param userMessage - The user's message (string or multimodal content blocks)
121
+ * @returns An `AsyncIterable<string>` of delta tokens from the final response
122
+ *
123
+ * @example
124
+ * for await (const token of session.stream('Tell me a story')) {
125
+ * process.stdout.write(token);
126
+ * }
127
+ */
128
+ stream(userMessage: string | ContentBlock[]): AsyncIterable<string>;
129
+ /**
130
+ * Resets the session: clears conversation history, resets iteration counters,
131
+ * and resets tool execution budgets. The adapter, config, and tools are retained.
132
+ */
133
+ reset(): void;
134
+ /**
135
+ * Closes the session and disconnects all MCP servers.
136
+ *
137
+ * Call this when you are done with the session and have registered MCP servers,
138
+ * to ensure child processes are terminated and HTTP connections are released.
139
+ *
140
+ * @example
141
+ * const session = new SessionManager({ ..., mcpServers: [...] });
142
+ * try {
143
+ * await session.run('Hello');
144
+ * } finally {
145
+ * await session.close();
146
+ * }
147
+ */
148
+ close(): Promise<void>;
30
149
  }
31
150
 
32
151
  /**
@@ -51,6 +170,7 @@ declare class GoalInjector {
51
170
  private goal;
52
171
  constructor(goal: Goal);
53
172
  injectInto(prompt: string): string;
173
+ getGoal(): Goal;
54
174
  }
55
175
 
56
176
  interface ContinuationStep {
@@ -88,4 +208,132 @@ declare class FinalResponseFormatter {
88
208
  static validateStructure(response: string): boolean;
89
209
  }
90
210
 
91
- export { ContentBlock, ContextWindow, type ContinuationPlan, ContinuationPlanner, type ContinuationStep, FinalResponseFormatter, type Goal, GoalInjector, IToolDefinition, IToolResponseProcessor, SessionConfig, SessionManager, StepCounter, ToolResponseEvaluation, ToolResponseProcessor, Turn };
211
+ /**
212
+ * Low-level MCP server client.
213
+ *
214
+ * Supports two transports:
215
+ * - **stdio** — spawns a child process and communicates over stdin/stdout via newline-delimited JSON-RPC 2.0
216
+ * - **http** — sends JSON-RPC 2.0 `POST` requests using native `fetch` (Node >= 18 required)
217
+ *
218
+ * Lifecycle:
219
+ * 1. `connect()` — initialize the server and fetch its tool list
220
+ * 2. `callTool()` — invoke a tool by name
221
+ * 3. `disconnect()` — terminate the connection / child process
222
+ *
223
+ * @example
224
+ * const client = new MCPClient('github', {
225
+ * name: 'github',
226
+ * transport: 'stdio',
227
+ * command: 'npx',
228
+ * args: ['@modelcontextprotocol/server-github'],
229
+ * env: { GITHUB_TOKEN: '...' }
230
+ * }, logger);
231
+ *
232
+ * await client.connect();
233
+ * const result = await client.callTool('create_issue', { title: 'bug' });
234
+ * await client.disconnect();
235
+ */
236
+ declare class MCPClient {
237
+ private readonly config;
238
+ private readonly logger;
239
+ private readonly _serverName;
240
+ private readonly timeoutMs;
241
+ private _tools;
242
+ private _connected;
243
+ private process;
244
+ private pendingCallbacks;
245
+ private requestId;
246
+ private stdioBuffer;
247
+ constructor(name: string, config: MCPServerConfig, logger: ILogger);
248
+ get serverName(): string;
249
+ get tools(): MCPToolDefinition[];
250
+ get isConnected(): boolean;
251
+ /**
252
+ * Connects to the MCP server: sends `initialize` + `notifications/initialized`,
253
+ * then fetches the tool list via `tools/list`.
254
+ */
255
+ connect(): Promise<void>;
256
+ /**
257
+ * Calls a tool on this MCP server.
258
+ *
259
+ * @param toolName - The tool name as declared by the server
260
+ * @param args - Tool arguments (must match the tool's inputSchema)
261
+ * @returns The serialised result from the server
262
+ */
263
+ callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
264
+ /**
265
+ * Disconnects from the MCP server.
266
+ * For stdio: sends the `exit` notification then terminates the process.
267
+ */
268
+ disconnect(): Promise<void>;
269
+ private _connectStdio;
270
+ /** Parses newline-delimited JSON messages from the stdio buffer */
271
+ private _flushStdioBuffer;
272
+ private _nextId;
273
+ /** Sends a JSON-RPC request and returns the response, honouring the configured timeout. */
274
+ private _rpc;
275
+ private _rpcStdio;
276
+ private _rpcHttp;
277
+ /** Sends `initialize` then `notifications/initialized` per MCP spec */
278
+ private _initialize;
279
+ /** Fetches and caches the tool list from the server */
280
+ private _discoverTools;
281
+ private _assertNoError;
282
+ }
283
+
284
+ /**
285
+ * Manages the full lifecycle of multiple MCP server connections and routes
286
+ * tool calls to the correct server.
287
+ *
288
+ * Typical usage is handled automatically by `SessionManager` when `mcpServers`
289
+ * is set in `SessionConfig`. You can also use it standalone for advanced scenarios.
290
+ *
291
+ * @example
292
+ * const registry = new MCPClientRegistry(logger);
293
+ * await registry.register('github', { transport: 'stdio', command: 'npx', args: ['...'] });
294
+ * const tools = await registry.discoverTools(); // IToolDefinition[] ready for ToolRegistry
295
+ */
296
+ declare class MCPClientRegistry {
297
+ private readonly clients;
298
+ /** toolName → serverName */
299
+ private readonly toolRouter;
300
+ private readonly logger;
301
+ constructor(logger: ILogger);
302
+ /**
303
+ * Creates an `MCPClient` for the given config, connects to the server, and
304
+ * registers the server by name.
305
+ *
306
+ * @throws {LemuraMCPConnectionError} if connection / initialization fails
307
+ */
308
+ register(name: string, config: MCPServerConfig): Promise<void>;
309
+ /**
310
+ * Collects tools from all connected MCP servers and returns them as
311
+ * `IToolDefinition` adapters ready to be registered in `ToolRegistry`.
312
+ *
313
+ * Tool names are **not** namespaced — if two servers expose a tool with the
314
+ * same name, the last-registered server wins and a warning is emitted.
315
+ */
316
+ discoverTools(): Promise<IToolDefinition[]>;
317
+ /**
318
+ * Calls a tool on the correct MCP server.
319
+ *
320
+ * @param toolName - The tool name as registered via `discoverTools()`
321
+ * @param args - Parsed arguments object
322
+ * @throws {LemuraMCPConnectionError} if no server is registered for `toolName`
323
+ */
324
+ callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
325
+ /**
326
+ * Disconnects all registered MCP servers gracefully.
327
+ * Called automatically by `SessionManager.close()`.
328
+ */
329
+ disconnectAll(): Promise<void>;
330
+ /** Returns the names of all currently registered servers */
331
+ getRegisteredServers(): string[];
332
+ /**
333
+ * Bridges an `MCPToolDefinition` from the protocol into an `IToolDefinition`
334
+ * that the existing `ToolRegistry` can execute.
335
+ */
336
+ private _bridge;
337
+ }
338
+
339
+ export { AudioChunk, ContentBlock, ContextWindow, type ContinuationPlan, ContinuationPlanner, type ContinuationStep, FinalResponseFormatter, type Goal, GoalInjector, ILogger, IProviderAdapter, IToolDefinition, IToolResponseProcessor, ImageGenRequest, ImageGenResponse, MCPClient, MCPClientRegistry, MCPServerConfig, MCPToolDefinition, MediaBridge, ModelInfo, SessionConfig, SessionManager, StepCounter, SynthesisRequest, ToolResponseEvaluation, ToolResponseProcessor, TranscriptionRequest, TranscriptionResponse, Turn, VisionRequest, VisionResponse };