@radaros/core 0.3.5 → 0.3.7

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 (60) hide show
  1. package/dist/index.d.ts +1711 -0
  2. package/dist/index.js +6341 -0
  3. package/package.json +6 -2
  4. package/src/a2a/a2a-remote-agent.ts +0 -270
  5. package/src/a2a/types.ts +0 -142
  6. package/src/agent/agent.ts +0 -417
  7. package/src/agent/llm-loop.ts +0 -290
  8. package/src/agent/run-context.ts +0 -35
  9. package/src/agent/types.ts +0 -89
  10. package/src/events/event-bus.ts +0 -45
  11. package/src/events/types.ts +0 -16
  12. package/src/guardrails/types.ts +0 -5
  13. package/src/hooks/types.ts +0 -6
  14. package/src/index.ts +0 -157
  15. package/src/knowledge/knowledge-base.ts +0 -146
  16. package/src/logger/logger.ts +0 -249
  17. package/src/mcp/mcp-client.ts +0 -264
  18. package/src/memory/memory.ts +0 -87
  19. package/src/memory/types.ts +0 -13
  20. package/src/memory/user-memory.ts +0 -211
  21. package/src/models/provider.ts +0 -22
  22. package/src/models/providers/anthropic.ts +0 -360
  23. package/src/models/providers/google.ts +0 -386
  24. package/src/models/providers/ollama.ts +0 -211
  25. package/src/models/providers/openai.ts +0 -345
  26. package/src/models/providers/vertex.ts +0 -427
  27. package/src/models/registry.ts +0 -107
  28. package/src/models/types.ts +0 -124
  29. package/src/session/session-manager.ts +0 -75
  30. package/src/session/types.ts +0 -10
  31. package/src/storage/driver.ts +0 -10
  32. package/src/storage/in-memory.ts +0 -44
  33. package/src/storage/mongodb.ts +0 -70
  34. package/src/storage/postgres.ts +0 -81
  35. package/src/storage/sqlite.ts +0 -81
  36. package/src/team/modes.ts +0 -1
  37. package/src/team/team.ts +0 -323
  38. package/src/team/types.ts +0 -26
  39. package/src/toolkits/base.ts +0 -15
  40. package/src/toolkits/duckduckgo.ts +0 -256
  41. package/src/toolkits/gmail.ts +0 -226
  42. package/src/toolkits/hackernews.ts +0 -121
  43. package/src/toolkits/websearch.ts +0 -158
  44. package/src/toolkits/whatsapp.ts +0 -209
  45. package/src/tools/define-tool.ts +0 -22
  46. package/src/tools/tool-executor.ts +0 -221
  47. package/src/tools/types.ts +0 -36
  48. package/src/utils/retry.ts +0 -56
  49. package/src/vector/base.ts +0 -44
  50. package/src/vector/embeddings/google.ts +0 -64
  51. package/src/vector/embeddings/openai.ts +0 -66
  52. package/src/vector/in-memory.ts +0 -115
  53. package/src/vector/mongodb.ts +0 -241
  54. package/src/vector/pgvector.ts +0 -169
  55. package/src/vector/qdrant.ts +0 -203
  56. package/src/vector/types.ts +0 -55
  57. package/src/workflow/step-runner.ts +0 -303
  58. package/src/workflow/types.ts +0 -55
  59. package/src/workflow/workflow.ts +0 -68
  60. package/tsconfig.json +0 -8
@@ -0,0 +1,1711 @@
1
+ import * as zod from 'zod';
2
+ import { z } from 'zod';
3
+
4
+ type MessageRole = "system" | "user" | "assistant" | "tool";
5
+ interface TextPart {
6
+ type: "text";
7
+ text: string;
8
+ }
9
+ interface ImagePart {
10
+ type: "image";
11
+ /** Base64-encoded image data OR a URL. */
12
+ data: string;
13
+ mimeType?: "image/png" | "image/jpeg" | "image/gif" | "image/webp";
14
+ }
15
+ interface AudioPart {
16
+ type: "audio";
17
+ /** Base64-encoded audio data. */
18
+ data: string;
19
+ mimeType?: "audio/mp3" | "audio/wav" | "audio/ogg" | "audio/webm";
20
+ }
21
+ interface FilePart {
22
+ type: "file";
23
+ /** Base64-encoded file data OR a URL. */
24
+ data: string;
25
+ mimeType: string;
26
+ filename?: string;
27
+ }
28
+ type ContentPart = TextPart | ImagePart | AudioPart | FilePart;
29
+ /** Convenience: plain string, or an array of multi-modal content parts. */
30
+ type MessageContent = string | ContentPart[];
31
+ interface ChatMessage {
32
+ role: MessageRole;
33
+ content: MessageContent | null;
34
+ toolCalls?: ToolCall[];
35
+ toolCallId?: string;
36
+ name?: string;
37
+ }
38
+ interface ToolCall {
39
+ id: string;
40
+ name: string;
41
+ arguments: Record<string, unknown>;
42
+ }
43
+ interface ToolDefinition {
44
+ name: string;
45
+ description: string;
46
+ parameters: Record<string, unknown>;
47
+ }
48
+ interface TokenUsage {
49
+ promptTokens: number;
50
+ completionTokens: number;
51
+ totalTokens: number;
52
+ reasoningTokens?: number;
53
+ }
54
+ interface ModelResponse {
55
+ message: ChatMessage;
56
+ usage: TokenUsage;
57
+ finishReason: "stop" | "tool_calls" | "length" | "content_filter";
58
+ raw: unknown;
59
+ }
60
+ type StreamChunk = {
61
+ type: "text";
62
+ text: string;
63
+ } | {
64
+ type: "thinking";
65
+ text: string;
66
+ } | {
67
+ type: "tool_call_start";
68
+ toolCall: {
69
+ id: string;
70
+ name: string;
71
+ };
72
+ } | {
73
+ type: "tool_call_delta";
74
+ toolCallId: string;
75
+ argumentsDelta: string;
76
+ } | {
77
+ type: "tool_call_end";
78
+ toolCallId: string;
79
+ } | {
80
+ type: "finish";
81
+ finishReason: string;
82
+ usage?: TokenUsage;
83
+ };
84
+ interface ReasoningConfig {
85
+ enabled: boolean;
86
+ /** Reasoning effort for OpenAI o-series models. */
87
+ effort?: "low" | "medium" | "high";
88
+ /** Token budget for thinking (Anthropic / Gemini). */
89
+ budgetTokens?: number;
90
+ }
91
+ interface ModelConfig {
92
+ temperature?: number;
93
+ maxTokens?: number;
94
+ topP?: number;
95
+ stop?: string[];
96
+ responseFormat?: "text" | "json" | {
97
+ type: "json_schema";
98
+ schema: Record<string, unknown>;
99
+ name?: string;
100
+ };
101
+ /** Per-request API key override. When provided, the provider uses this key instead of the one set at construction. */
102
+ apiKey?: string;
103
+ /** Enable extended thinking / reasoning. */
104
+ reasoning?: ReasoningConfig;
105
+ }
106
+ /** Extract the text content from a MessageContent value. */
107
+ declare function getTextContent(content: MessageContent | null): string;
108
+ /** Check if content has multi-modal parts. */
109
+ declare function isMultiModal(content: MessageContent | null): content is ContentPart[];
110
+
111
+ interface ModelProvider {
112
+ readonly providerId: string;
113
+ readonly modelId: string;
114
+ generate(messages: ChatMessage[], options?: ModelConfig & {
115
+ tools?: ToolDefinition[];
116
+ }): Promise<ModelResponse>;
117
+ stream(messages: ChatMessage[], options?: ModelConfig & {
118
+ tools?: ToolDefinition[];
119
+ }): AsyncGenerator<StreamChunk>;
120
+ }
121
+
122
+ declare class RunContext {
123
+ readonly runId: string;
124
+ readonly sessionId: string;
125
+ readonly userId?: string;
126
+ readonly metadata: Record<string, unknown>;
127
+ readonly eventBus: EventBus;
128
+ sessionState: Record<string, unknown>;
129
+ constructor(opts: {
130
+ sessionId: string;
131
+ userId?: string;
132
+ metadata?: Record<string, unknown>;
133
+ eventBus: EventBus;
134
+ sessionState?: Record<string, unknown>;
135
+ runId?: string;
136
+ });
137
+ getState<T>(key: string): T | undefined;
138
+ setState(key: string, value: unknown): void;
139
+ }
140
+
141
+ interface Artifact {
142
+ type: string;
143
+ data: unknown;
144
+ mimeType?: string;
145
+ }
146
+ interface ToolResult {
147
+ content: string;
148
+ artifacts?: Artifact[];
149
+ }
150
+ interface ToolCacheConfig {
151
+ /** Time-to-live in milliseconds. Cached results expire after this duration. */
152
+ ttl: number;
153
+ }
154
+ interface ToolDef {
155
+ name: string;
156
+ description: string;
157
+ parameters: z.ZodObject<any>;
158
+ execute: (args: Record<string, unknown>, ctx: RunContext) => Promise<string | ToolResult>;
159
+ /** Raw JSON Schema to send to the LLM, bypassing Zod-to-JSON conversion (used by MCP tools). */
160
+ rawJsonSchema?: Record<string, unknown>;
161
+ /** Enable result caching for this tool. */
162
+ cache?: ToolCacheConfig;
163
+ }
164
+ interface ToolCallResult {
165
+ toolCallId: string;
166
+ toolName: string;
167
+ result: string | ToolResult;
168
+ error?: string;
169
+ }
170
+
171
+ interface StorageDriver {
172
+ get<T>(namespace: string, key: string): Promise<T | null>;
173
+ set<T>(namespace: string, key: string, value: T): Promise<void>;
174
+ delete(namespace: string, key: string): Promise<void>;
175
+ list<T>(namespace: string, prefix?: string): Promise<Array<{
176
+ key: string;
177
+ value: T;
178
+ }>>;
179
+ close(): Promise<void>;
180
+ }
181
+
182
+ interface MemoryConfig {
183
+ storage?: StorageDriver;
184
+ /** LLM used to generate conversation summaries from overflow messages. */
185
+ model?: ModelProvider;
186
+ /** Maximum number of summaries kept per session (oldest dropped first). Default 20. */
187
+ maxSummaries?: number;
188
+ }
189
+ interface MemoryEntry {
190
+ key: string;
191
+ summary: string;
192
+ createdAt: Date;
193
+ }
194
+
195
+ /**
196
+ * Long-term conversation memory.
197
+ *
198
+ * Memory stores LLM-generated summaries of past conversation segments.
199
+ * It does NOT store raw messages — that's Session's job.
200
+ *
201
+ * Flow: Session overflows → Agent passes overflow to Memory.summarize() →
202
+ * Memory generates an LLM summary and persists it.
203
+ * On the next run, Memory.getContextString() provides past summaries as context.
204
+ */
205
+ declare class Memory {
206
+ private storage;
207
+ private model?;
208
+ private maxSummaries;
209
+ private initPromise;
210
+ constructor(config?: MemoryConfig);
211
+ private ensureInitialized;
212
+ /**
213
+ * Summarize overflow messages and store the summary.
214
+ * Uses the configured LLM model; falls back to basic concatenation if no model.
215
+ */
216
+ summarize(sessionId: string, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
217
+ /** Get all stored summaries for a session. */
218
+ getSummaries(sessionId: string): Promise<string[]>;
219
+ /** Get summaries formatted as a context string for injection into the system prompt. */
220
+ getContextString(sessionId: string): Promise<string>;
221
+ /** Clear all summaries for a session. */
222
+ clear(sessionId: string): Promise<void>;
223
+ }
224
+
225
+ type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
226
+ interface LoggerConfig {
227
+ level?: LogLevel;
228
+ color?: boolean;
229
+ prefix?: string;
230
+ }
231
+ declare class Logger {
232
+ private level;
233
+ private color;
234
+ private prefix;
235
+ constructor(config?: LoggerConfig);
236
+ private c;
237
+ private shouldLog;
238
+ private tag;
239
+ private timestamp;
240
+ private log;
241
+ private formatValue;
242
+ debug(msg: string, data?: Record<string, unknown>): void;
243
+ info(msg: string, data?: Record<string, unknown>): void;
244
+ warn(msg: string, data?: Record<string, unknown>): void;
245
+ error(msg: string, data?: Record<string, unknown>): void;
246
+ private readonly boxWidth;
247
+ private pipe;
248
+ private printBoxLine;
249
+ agentStart(agentName: string, input: string): void;
250
+ toolCall(toolName: string, args: Record<string, unknown>): void;
251
+ toolResult(toolName: string, result: string): void;
252
+ thinking(content: string): void;
253
+ agentEnd(agentName: string, output: string, usage: {
254
+ promptTokens: number;
255
+ completionTokens: number;
256
+ totalTokens: number;
257
+ reasoningTokens?: number;
258
+ }, durationMs: number): void;
259
+ separator(): void;
260
+ private formatDuration;
261
+ }
262
+
263
+ interface UserMemoryConfig {
264
+ storage?: StorageDriver;
265
+ /** LLM used for auto-extraction of facts from conversations. */
266
+ model?: ModelProvider;
267
+ /** Maximum number of facts stored per user (default 100). */
268
+ maxFacts?: number;
269
+ /** Whether auto-extraction is enabled (default true). */
270
+ enabled?: boolean;
271
+ }
272
+ interface UserFact {
273
+ id: string;
274
+ fact: string;
275
+ createdAt: Date;
276
+ source: "auto" | "manual";
277
+ }
278
+ declare class UserMemory {
279
+ private storage;
280
+ private model?;
281
+ private maxFacts;
282
+ private enabled;
283
+ private initPromise;
284
+ constructor(config?: UserMemoryConfig);
285
+ private ensureInitialized;
286
+ getFacts(userId: string): Promise<UserFact[]>;
287
+ addFacts(userId: string, facts: string[], source?: "auto" | "manual"): Promise<void>;
288
+ removeFact(userId: string, factId: string): Promise<void>;
289
+ clear(userId: string): Promise<void>;
290
+ getContextString(userId: string): Promise<string>;
291
+ asTool(config?: {
292
+ name?: string;
293
+ description?: string;
294
+ }): ToolDef;
295
+ extractAndStore(userId: string, messages: ChatMessage[], fallbackModel?: ModelProvider): Promise<void>;
296
+ private extractJsonArray;
297
+ }
298
+
299
+ interface RetryConfig {
300
+ maxRetries: number;
301
+ initialDelayMs: number;
302
+ maxDelayMs: number;
303
+ retryableErrors?: (error: unknown) => boolean;
304
+ }
305
+ declare function withRetry<T>(fn: () => Promise<T>, config?: Partial<RetryConfig>): Promise<T>;
306
+
307
+ interface AgentConfig {
308
+ name: string;
309
+ model: ModelProvider;
310
+ tools?: ToolDef[];
311
+ instructions?: string | ((ctx: RunContext) => string);
312
+ memory?: Memory;
313
+ storage?: StorageDriver;
314
+ sessionId?: string;
315
+ userId?: string;
316
+ addHistoryToMessages?: boolean;
317
+ numHistoryRuns?: number;
318
+ maxToolRoundtrips?: number;
319
+ temperature?: number;
320
+ structuredOutput?: z.ZodSchema;
321
+ hooks?: AgentHooks;
322
+ guardrails?: {
323
+ input?: InputGuardrail[];
324
+ output?: OutputGuardrail[];
325
+ };
326
+ eventBus?: EventBus;
327
+ /** Logging level. Set to "debug" for tool call details, "info" for summaries, "silent" to disable. Default: "silent". */
328
+ logLevel?: LogLevel;
329
+ /** Enable extended thinking / reasoning for the model. */
330
+ reasoning?: ReasoningConfig;
331
+ /** User-scoped memory for cross-session personalization. */
332
+ userMemory?: UserMemory;
333
+ /** Retry configuration for transient LLM API failures (429, 5xx, network errors). */
334
+ retry?: Partial<RetryConfig>;
335
+ /** Maximum context window tokens. History is auto-trimmed to fit. */
336
+ maxContextTokens?: number;
337
+ }
338
+ interface RunOpts {
339
+ sessionId?: string;
340
+ userId?: string;
341
+ metadata?: Record<string, unknown>;
342
+ /** Per-request API key override passed to the model provider. */
343
+ apiKey?: string;
344
+ }
345
+ interface RunOutput {
346
+ text: string;
347
+ toolCalls: ToolCallResult[];
348
+ usage: TokenUsage;
349
+ /** Parsed structured output if structuredOutput schema is set. */
350
+ structured?: unknown;
351
+ /** Model's internal reasoning / thinking content (when reasoning is enabled). */
352
+ thinking?: string;
353
+ durationMs?: number;
354
+ }
355
+ interface AgentHooks {
356
+ beforeRun?: (ctx: RunContext) => Promise<void>;
357
+ afterRun?: (ctx: RunContext, output: RunOutput) => Promise<void>;
358
+ onToolCall?: (ctx: RunContext, toolName: string, args: unknown) => Promise<void>;
359
+ onError?: (ctx: RunContext, error: Error) => Promise<void>;
360
+ }
361
+ type GuardrailResult = {
362
+ pass: true;
363
+ } | {
364
+ pass: false;
365
+ reason: string;
366
+ };
367
+ interface InputGuardrail {
368
+ name: string;
369
+ validate: (input: MessageContent, ctx: RunContext) => Promise<GuardrailResult>;
370
+ }
371
+ interface OutputGuardrail {
372
+ name: string;
373
+ validate: (output: RunOutput, ctx: RunContext) => Promise<GuardrailResult>;
374
+ }
375
+
376
+ type AgentEventMap = {
377
+ "run.start": {
378
+ runId: string;
379
+ agentName: string;
380
+ input: string;
381
+ };
382
+ "run.complete": {
383
+ runId: string;
384
+ output: RunOutput;
385
+ };
386
+ "run.error": {
387
+ runId: string;
388
+ error: Error;
389
+ };
390
+ "run.stream.chunk": {
391
+ runId: string;
392
+ chunk: string;
393
+ };
394
+ "tool.call": {
395
+ runId: string;
396
+ toolName: string;
397
+ args: unknown;
398
+ };
399
+ "tool.result": {
400
+ runId: string;
401
+ toolName: string;
402
+ result: unknown;
403
+ };
404
+ "team.delegate": {
405
+ runId: string;
406
+ memberId: string;
407
+ task: string;
408
+ };
409
+ "workflow.step": {
410
+ runId: string;
411
+ stepName: string;
412
+ status: "start" | "done" | "error";
413
+ };
414
+ "voice.connected": {
415
+ agentName: string;
416
+ };
417
+ "voice.audio": {
418
+ agentName: string;
419
+ data: Buffer;
420
+ };
421
+ "voice.transcript": {
422
+ agentName: string;
423
+ text: string;
424
+ role: "user" | "assistant";
425
+ };
426
+ "voice.tool.call": {
427
+ agentName: string;
428
+ toolName: string;
429
+ args: unknown;
430
+ };
431
+ "voice.tool.result": {
432
+ agentName: string;
433
+ toolName: string;
434
+ result: string;
435
+ };
436
+ "voice.error": {
437
+ agentName: string;
438
+ error: Error;
439
+ };
440
+ "voice.disconnected": {
441
+ agentName: string;
442
+ };
443
+ };
444
+
445
+ type EventKey = keyof AgentEventMap;
446
+ declare class EventBus {
447
+ private emitter;
448
+ constructor();
449
+ on<K extends EventKey>(event: K, handler: (data: AgentEventMap[K]) => void): this;
450
+ once<K extends EventKey>(event: K, handler: (data: AgentEventMap[K]) => void): this;
451
+ off<K extends EventKey>(event: K, handler: (data: AgentEventMap[K]) => void): this;
452
+ emit<K extends EventKey>(event: K, data: AgentEventMap[K]): boolean;
453
+ removeAllListeners(event?: EventKey): this;
454
+ }
455
+
456
+ declare class Agent {
457
+ readonly name: string;
458
+ readonly eventBus: EventBus;
459
+ readonly instructions?: string | ((ctx: RunContext) => string);
460
+ private config;
461
+ private sessionManager;
462
+ private llmLoop;
463
+ private logger;
464
+ private storageInitPromise;
465
+ get tools(): ToolDef[];
466
+ get modelId(): string;
467
+ get providerId(): string;
468
+ get hasStructuredOutput(): boolean;
469
+ get structuredOutputSchema(): zod.ZodSchema | undefined;
470
+ constructor(config: AgentConfig);
471
+ run(input: MessageContent, opts?: RunOpts): Promise<RunOutput>;
472
+ stream(input: MessageContent, opts?: RunOpts): AsyncGenerator<StreamChunk>;
473
+ private buildMessages;
474
+ private estimateTokens;
475
+ private trimHistoryByTokens;
476
+ }
477
+
478
+ declare class ToolExecutor {
479
+ private tools;
480
+ private concurrency;
481
+ private cache;
482
+ private cachedDefs;
483
+ constructor(tools: ToolDef[], concurrency?: number);
484
+ clearCache(): void;
485
+ private getCacheKey;
486
+ private getCached;
487
+ private setCache;
488
+ executeAll(toolCalls: ToolCall[], ctx: RunContext): Promise<ToolCallResult[]>;
489
+ private executeSingle;
490
+ getToolDefinitions(): Array<{
491
+ name: string;
492
+ description: string;
493
+ parameters: Record<string, unknown>;
494
+ }>;
495
+ private buildToolDefinitions;
496
+ }
497
+
498
+ declare class LLMLoop {
499
+ private provider;
500
+ private toolExecutor;
501
+ private maxToolRoundtrips;
502
+ private temperature?;
503
+ private maxTokens?;
504
+ private structuredOutput?;
505
+ private logger?;
506
+ private reasoning?;
507
+ private retry?;
508
+ constructor(provider: ModelProvider, toolExecutor: ToolExecutor | null, options: {
509
+ maxToolRoundtrips: number;
510
+ temperature?: number;
511
+ maxTokens?: number;
512
+ structuredOutput?: z.ZodSchema;
513
+ logger?: Logger;
514
+ reasoning?: ReasoningConfig;
515
+ retry?: Partial<RetryConfig>;
516
+ });
517
+ run(messages: ChatMessage[], ctx: RunContext, apiKey?: string): Promise<RunOutput>;
518
+ stream(messages: ChatMessage[], ctx: RunContext, apiKey?: string): AsyncGenerator<StreamChunk>;
519
+ private extractJson;
520
+ private zodToJsonSchema;
521
+ }
522
+
523
+ declare enum TeamMode {
524
+ Coordinate = "coordinate",
525
+ Route = "route",
526
+ Broadcast = "broadcast",
527
+ Collaborate = "collaborate"
528
+ }
529
+ interface TeamConfig {
530
+ name: string;
531
+ mode: TeamMode;
532
+ model: ModelProvider;
533
+ members: Agent[];
534
+ instructions?: string;
535
+ sessionState?: Record<string, unknown>;
536
+ storage?: StorageDriver;
537
+ maxRounds?: number;
538
+ eventBus?: EventBus;
539
+ }
540
+
541
+ declare class Team {
542
+ readonly name: string;
543
+ readonly eventBus: EventBus;
544
+ private config;
545
+ constructor(config: TeamConfig);
546
+ run(input: string, opts?: RunOpts): Promise<RunOutput>;
547
+ stream(input: string, opts?: RunOpts): AsyncGenerator<StreamChunk>;
548
+ private runCoordinateMode;
549
+ private runRouteMode;
550
+ private runBroadcastMode;
551
+ private runCollaborateMode;
552
+ private buildMemberDescriptions;
553
+ private buildCoordinatorPrompt;
554
+ private buildSynthesisPrompt;
555
+ private parseDelegationPlan;
556
+ private findMember;
557
+ }
558
+
559
+ type StepDef<TState> = AgentStep<TState> | FunctionStep<TState> | ConditionStep<TState> | ParallelStep<TState>;
560
+ interface AgentStep<TState> {
561
+ name: string;
562
+ agent: Agent;
563
+ inputFrom?: (state: TState) => string;
564
+ }
565
+ interface FunctionStep<TState> {
566
+ name: string;
567
+ run: (state: TState, ctx: RunContext) => Promise<Partial<TState>>;
568
+ }
569
+ interface ConditionStep<TState> {
570
+ name: string;
571
+ condition: (state: TState) => boolean;
572
+ steps: StepDef<TState>[];
573
+ }
574
+ interface ParallelStep<TState> {
575
+ name: string;
576
+ parallel: StepDef<TState>[];
577
+ }
578
+ interface WorkflowConfig<TState extends Record<string, unknown> = Record<string, unknown>> {
579
+ name: string;
580
+ initialState: TState;
581
+ steps: StepDef<TState>[];
582
+ storage?: StorageDriver;
583
+ retryPolicy?: {
584
+ maxRetries: number;
585
+ backoffMs: number;
586
+ };
587
+ eventBus?: EventBus;
588
+ }
589
+ interface WorkflowResult<TState> {
590
+ state: TState;
591
+ stepResults: StepResult[];
592
+ }
593
+ interface StepResult {
594
+ stepName: string;
595
+ status: "done" | "error" | "skipped";
596
+ error?: string;
597
+ durationMs: number;
598
+ }
599
+
600
+ declare class Workflow<TState extends Record<string, unknown> = Record<string, unknown>> {
601
+ readonly name: string;
602
+ readonly eventBus: EventBus;
603
+ private config;
604
+ private stepRunner;
605
+ constructor(config: WorkflowConfig<TState>);
606
+ run(opts?: {
607
+ sessionId?: string;
608
+ userId?: string;
609
+ }): Promise<WorkflowResult<TState>>;
610
+ }
611
+
612
+ type ProviderFactory = (modelId: string, config?: Record<string, unknown>) => ModelProvider;
613
+ declare class ModelRegistry {
614
+ private factories;
615
+ register(providerId: string, factory: ProviderFactory): void;
616
+ resolve(providerId: string, modelId: string, config?: Record<string, unknown>): ModelProvider;
617
+ has(providerId: string): boolean;
618
+ }
619
+ declare const registry: ModelRegistry;
620
+ declare function openai(modelId: string, config?: {
621
+ apiKey?: string;
622
+ baseURL?: string;
623
+ }): ModelProvider;
624
+ declare function anthropic(modelId: string, config?: {
625
+ apiKey?: string;
626
+ }): ModelProvider;
627
+ declare function google(modelId: string, config?: {
628
+ apiKey?: string;
629
+ }): ModelProvider;
630
+ declare function ollama(modelId: string, config?: {
631
+ host?: string;
632
+ }): ModelProvider;
633
+ declare function vertex(modelId: string, config?: {
634
+ project?: string;
635
+ location?: string;
636
+ credentials?: string;
637
+ }): ModelProvider;
638
+
639
+ interface OpenAIConfig {
640
+ apiKey?: string;
641
+ baseURL?: string;
642
+ }
643
+ declare class OpenAIProvider implements ModelProvider {
644
+ readonly providerId = "openai";
645
+ readonly modelId: string;
646
+ private client;
647
+ private OpenAICtor;
648
+ private baseURL?;
649
+ private clientCache;
650
+ constructor(modelId: string, config?: OpenAIConfig);
651
+ private getClient;
652
+ generate(messages: ChatMessage[], options?: ModelConfig & {
653
+ tools?: ToolDefinition[];
654
+ }): Promise<ModelResponse>;
655
+ stream(messages: ChatMessage[], options?: ModelConfig & {
656
+ tools?: ToolDefinition[];
657
+ }): AsyncGenerator<StreamChunk>;
658
+ private applyResponseFormat;
659
+ private toOpenAIMessages;
660
+ private partToOpenAI;
661
+ private toOpenAITools;
662
+ private normalizeResponse;
663
+ }
664
+
665
+ interface AnthropicConfig {
666
+ apiKey?: string;
667
+ }
668
+ declare class AnthropicProvider implements ModelProvider {
669
+ readonly providerId = "anthropic";
670
+ readonly modelId: string;
671
+ private client;
672
+ private AnthropicCtor;
673
+ private clientCache;
674
+ constructor(modelId: string, config?: AnthropicConfig);
675
+ private getClient;
676
+ generate(messages: ChatMessage[], options?: ModelConfig & {
677
+ tools?: ToolDefinition[];
678
+ }): Promise<ModelResponse>;
679
+ stream(messages: ChatMessage[], options?: ModelConfig & {
680
+ tools?: ToolDefinition[];
681
+ }): AsyncGenerator<StreamChunk>;
682
+ private toAnthropicMessages;
683
+ private partToAnthropic;
684
+ private toAnthropicTools;
685
+ private normalizeResponse;
686
+ }
687
+
688
+ interface GoogleConfig {
689
+ apiKey?: string;
690
+ }
691
+ declare class GoogleProvider implements ModelProvider {
692
+ readonly providerId = "google";
693
+ readonly modelId: string;
694
+ private ai;
695
+ private GoogleGenAICtor;
696
+ private clientCache;
697
+ constructor(modelId: string, config?: GoogleConfig);
698
+ private getClient;
699
+ generate(messages: ChatMessage[], options?: ModelConfig & {
700
+ tools?: ToolDefinition[];
701
+ }): Promise<ModelResponse>;
702
+ stream(messages: ChatMessage[], options?: ModelConfig & {
703
+ tools?: ToolDefinition[];
704
+ }): AsyncGenerator<StreamChunk>;
705
+ private toGoogleMessages;
706
+ private partToGoogle;
707
+ private toGoogleTools;
708
+ private cleanJsonSchema;
709
+ private normalizeResponse;
710
+ }
711
+
712
+ interface OllamaConfig {
713
+ host?: string;
714
+ }
715
+ declare class OllamaProvider implements ModelProvider {
716
+ readonly providerId = "ollama";
717
+ readonly modelId: string;
718
+ private client;
719
+ constructor(modelId: string, config?: OllamaConfig);
720
+ generate(messages: ChatMessage[], options?: ModelConfig & {
721
+ tools?: ToolDefinition[];
722
+ }): Promise<ModelResponse>;
723
+ stream(messages: ChatMessage[], options?: ModelConfig & {
724
+ tools?: ToolDefinition[];
725
+ }): AsyncGenerator<StreamChunk>;
726
+ private toOllamaMessages;
727
+ private toOllamaTools;
728
+ private normalizeResponse;
729
+ }
730
+
731
+ interface VertexAIConfig {
732
+ project?: string;
733
+ location?: string;
734
+ /** Service account key JSON string or path (optional — uses ADC by default). */
735
+ credentials?: string;
736
+ }
737
+ /**
738
+ * Vertex AI provider using Google's @google/genai SDK in Vertex mode.
739
+ *
740
+ * Authentication (in order of precedence):
741
+ * 1. Explicit `project` + `location` in config
742
+ * 2. GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION env vars
743
+ * 3. Application Default Credentials (gcloud auth)
744
+ */
745
+ declare class VertexAIProvider implements ModelProvider {
746
+ readonly providerId = "vertex";
747
+ readonly modelId: string;
748
+ private ai;
749
+ private GoogleGenAICtor;
750
+ private project;
751
+ private location;
752
+ constructor(modelId: string, config?: VertexAIConfig);
753
+ private getClient;
754
+ generate(messages: ChatMessage[], options?: ModelConfig & {
755
+ tools?: ToolDefinition[];
756
+ }): Promise<ModelResponse>;
757
+ stream(messages: ChatMessage[], options?: ModelConfig & {
758
+ tools?: ToolDefinition[];
759
+ }): AsyncGenerator<StreamChunk>;
760
+ private toGoogleMessages;
761
+ private partToGoogle;
762
+ private toGoogleTools;
763
+ private cleanJsonSchema;
764
+ private normalizeResponse;
765
+ }
766
+
767
+ declare function defineTool<T extends z.ZodObject<any>>(config: {
768
+ name: string;
769
+ description: string;
770
+ parameters: T;
771
+ execute: (args: z.infer<T>, ctx: RunContext) => Promise<string | ToolResult>;
772
+ cache?: ToolCacheConfig;
773
+ }): ToolDef;
774
+
775
+ declare class InMemoryStorage implements StorageDriver {
776
+ private store;
777
+ private makeKey;
778
+ get<T>(namespace: string, key: string): Promise<T | null>;
779
+ set<T>(namespace: string, key: string, value: T): Promise<void>;
780
+ delete(namespace: string, key: string): Promise<void>;
781
+ list<T>(namespace: string, prefix?: string): Promise<Array<{
782
+ key: string;
783
+ value: T;
784
+ }>>;
785
+ close(): Promise<void>;
786
+ }
787
+
788
+ declare class SqliteStorage implements StorageDriver {
789
+ private db;
790
+ constructor(dbPath: string);
791
+ get<T>(namespace: string, key: string): Promise<T | null>;
792
+ set<T>(namespace: string, key: string, value: T): Promise<void>;
793
+ delete(namespace: string, key: string): Promise<void>;
794
+ list<T>(namespace: string, prefix?: string): Promise<Array<{
795
+ key: string;
796
+ value: T;
797
+ }>>;
798
+ close(): Promise<void>;
799
+ }
800
+
801
+ declare class PostgresStorage implements StorageDriver {
802
+ private pool;
803
+ constructor(connectionString: string);
804
+ initialize(): Promise<void>;
805
+ get<T>(namespace: string, key: string): Promise<T | null>;
806
+ set<T>(namespace: string, key: string, value: T): Promise<void>;
807
+ delete(namespace: string, key: string): Promise<void>;
808
+ list<T>(namespace: string, prefix?: string): Promise<Array<{
809
+ key: string;
810
+ value: T;
811
+ }>>;
812
+ close(): Promise<void>;
813
+ }
814
+
815
+ declare class MongoDBStorage implements StorageDriver {
816
+ private uri;
817
+ private dbName;
818
+ private collectionName;
819
+ private client;
820
+ private db;
821
+ private collection;
822
+ constructor(uri: string, dbName?: string, collectionName?: string);
823
+ initialize(): Promise<void>;
824
+ get<T>(namespace: string, key: string): Promise<T | null>;
825
+ set<T>(namespace: string, key: string, value: T): Promise<void>;
826
+ delete(namespace: string, key: string): Promise<void>;
827
+ list<T>(namespace: string, prefix?: string): Promise<Array<{
828
+ key: string;
829
+ value: T;
830
+ }>>;
831
+ close(): Promise<void>;
832
+ }
833
+
834
+ interface VectorDocument {
835
+ id: string;
836
+ content: string;
837
+ embedding?: number[];
838
+ metadata?: Record<string, unknown>;
839
+ }
840
+ interface VectorSearchResult {
841
+ id: string;
842
+ content: string;
843
+ score: number;
844
+ metadata?: Record<string, unknown>;
845
+ }
846
+ interface VectorSearchOptions {
847
+ topK?: number;
848
+ filter?: Record<string, unknown>;
849
+ minScore?: number;
850
+ }
851
+ interface EmbeddingProvider {
852
+ readonly dimensions: number;
853
+ embed(text: string): Promise<number[]>;
854
+ embedBatch(texts: string[]): Promise<number[][]>;
855
+ }
856
+ interface VectorStore {
857
+ /** Initialize collections/indexes. Call once before use. */
858
+ initialize(): Promise<void>;
859
+ /** Upsert a single document (embedding computed if not provided). */
860
+ upsert(collection: string, doc: VectorDocument): Promise<void>;
861
+ /** Upsert multiple documents in batch. */
862
+ upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
863
+ /** Similarity search by vector or text query. */
864
+ search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
865
+ /** Delete a document by ID. */
866
+ delete(collection: string, id: string): Promise<void>;
867
+ /** Get a document by ID. */
868
+ get(collection: string, id: string): Promise<VectorDocument | null>;
869
+ /** Drop an entire collection. */
870
+ dropCollection(collection: string): Promise<void>;
871
+ /** Close connections. */
872
+ close(): Promise<void>;
873
+ }
874
+
875
+ declare abstract class BaseVectorStore implements VectorStore {
876
+ protected embedder?: EmbeddingProvider | undefined;
877
+ constructor(embedder?: EmbeddingProvider | undefined);
878
+ protected ensureEmbedding(doc: VectorDocument): Promise<number[]>;
879
+ protected ensureQueryVector(query: number[] | string): Promise<number[]>;
880
+ abstract initialize(): Promise<void>;
881
+ abstract upsert(collection: string, doc: VectorDocument): Promise<void>;
882
+ abstract upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
883
+ abstract search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
884
+ abstract delete(collection: string, id: string): Promise<void>;
885
+ abstract get(collection: string, id: string): Promise<VectorDocument | null>;
886
+ abstract dropCollection(collection: string): Promise<void>;
887
+ abstract close(): Promise<void>;
888
+ }
889
+
890
+ declare class InMemoryVectorStore extends BaseVectorStore {
891
+ private collections;
892
+ constructor(embedder?: EmbeddingProvider);
893
+ initialize(): Promise<void>;
894
+ private getCol;
895
+ upsert(collection: string, doc: VectorDocument): Promise<void>;
896
+ upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
897
+ search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
898
+ private cosineSimilarity;
899
+ delete(collection: string, id: string): Promise<void>;
900
+ get(collection: string, id: string): Promise<VectorDocument | null>;
901
+ dropCollection(collection: string): Promise<void>;
902
+ close(): Promise<void>;
903
+ }
904
+
905
+ interface PgVectorConfig {
906
+ connectionString: string;
907
+ dimensions?: number;
908
+ }
909
+ declare class PgVectorStore extends BaseVectorStore {
910
+ private pool;
911
+ private dimensions;
912
+ private initializedCollections;
913
+ constructor(config: PgVectorConfig, embedder?: EmbeddingProvider);
914
+ initialize(): Promise<void>;
915
+ private ensureCollection;
916
+ private sanitize;
917
+ private toSql;
918
+ upsert(collection: string, doc: VectorDocument): Promise<void>;
919
+ upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
920
+ search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
921
+ delete(collection: string, id: string): Promise<void>;
922
+ get(collection: string, id: string): Promise<VectorDocument | null>;
923
+ dropCollection(collection: string): Promise<void>;
924
+ close(): Promise<void>;
925
+ }
926
+
927
+ interface QdrantConfig {
928
+ url?: string;
929
+ apiKey?: string;
930
+ dimensions?: number;
931
+ checkCompatibility?: boolean;
932
+ }
933
+ declare class QdrantVectorStore extends BaseVectorStore {
934
+ private client;
935
+ private dimensions;
936
+ private initializedCollections;
937
+ constructor(config?: QdrantConfig, embedder?: EmbeddingProvider);
938
+ initialize(): Promise<void>;
939
+ private ensureCollection;
940
+ upsert(collection: string, doc: VectorDocument): Promise<void>;
941
+ upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
942
+ search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
943
+ delete(collection: string, id: string): Promise<void>;
944
+ get(collection: string, id: string): Promise<VectorDocument | null>;
945
+ dropCollection(collection: string): Promise<void>;
946
+ close(): Promise<void>;
947
+ }
948
+
949
+ interface MongoDBVectorConfig {
950
+ uri: string;
951
+ dbName?: string;
952
+ /** Atlas Search index name (must be pre-created for $vectorSearch). Defaults to "vector_index". */
953
+ indexName?: string;
954
+ }
955
+ declare class MongoDBVectorStore extends BaseVectorStore {
956
+ private client;
957
+ private db;
958
+ private indexName;
959
+ private dbName;
960
+ private useAtlas;
961
+ constructor(config: MongoDBVectorConfig, embedder?: EmbeddingProvider);
962
+ initialize(): Promise<void>;
963
+ private col;
964
+ upsert(collection: string, doc: VectorDocument): Promise<void>;
965
+ upsertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
966
+ search(collection: string, query: number[] | string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
967
+ private atlasSearch;
968
+ private localSearch;
969
+ private buildFilter;
970
+ delete(collection: string, id: string): Promise<void>;
971
+ get(collection: string, id: string): Promise<VectorDocument | null>;
972
+ dropCollection(collection: string): Promise<void>;
973
+ close(): Promise<void>;
974
+ }
975
+
976
+ interface OpenAIEmbeddingConfig {
977
+ apiKey?: string;
978
+ baseURL?: string;
979
+ model?: string;
980
+ dimensions?: number;
981
+ }
982
+ declare class OpenAIEmbedding implements EmbeddingProvider {
983
+ readonly dimensions: number;
984
+ private client;
985
+ private model;
986
+ constructor(config?: OpenAIEmbeddingConfig);
987
+ embed(text: string): Promise<number[]>;
988
+ embedBatch(texts: string[]): Promise<number[][]>;
989
+ }
990
+
991
+ interface GoogleEmbeddingConfig {
992
+ apiKey?: string;
993
+ model?: string;
994
+ dimensions?: number;
995
+ }
996
+ declare class GoogleEmbedding implements EmbeddingProvider {
997
+ readonly dimensions: number;
998
+ private ai;
999
+ private model;
1000
+ constructor(config?: GoogleEmbeddingConfig);
1001
+ embed(text: string): Promise<number[]>;
1002
+ embedBatch(texts: string[]): Promise<number[][]>;
1003
+ }
1004
+
1005
+ type SearchMode = "vector" | "keyword" | "hybrid";
1006
+ interface HybridSearchConfig {
1007
+ /** Weight for vector (semantic) results in RRF. Default 1.0. */
1008
+ vectorWeight?: number;
1009
+ /** Weight for keyword (BM25) results in RRF. Default 1.0. */
1010
+ keywordWeight?: number;
1011
+ /** RRF constant k. Higher = less rank-sensitive. Default 60. */
1012
+ rrfK?: number;
1013
+ }
1014
+ interface KnowledgeBaseConfig {
1015
+ /** Display name used in tool description auto-generation. */
1016
+ name: string;
1017
+ /** The underlying vector store (any backend). */
1018
+ vectorStore: VectorStore;
1019
+ /** Collection/index name inside the vector store. */
1020
+ collection?: string;
1021
+ /**
1022
+ * Default search mode.
1023
+ * - `"vector"` — pure semantic (embedding) search (default, backward-compatible)
1024
+ * - `"keyword"` — pure BM25 keyword search
1025
+ * - `"hybrid"` — combines vector + keyword via Reciprocal Rank Fusion
1026
+ */
1027
+ searchMode?: SearchMode;
1028
+ /** Fine-tune hybrid search behavior. */
1029
+ hybridConfig?: HybridSearchConfig;
1030
+ }
1031
+ interface KnowledgeBaseToolConfig {
1032
+ /** Tool name exposed to the LLM. Defaults to `search_<collection>`. */
1033
+ toolName?: string;
1034
+ /** Custom tool description. A sensible default is generated from the KB name. */
1035
+ description?: string;
1036
+ /** Number of results to return per search. Default 5. */
1037
+ topK?: number;
1038
+ /** Minimum similarity score to include. */
1039
+ minScore?: number;
1040
+ /** Metadata filter applied to every search. */
1041
+ filter?: Record<string, unknown>;
1042
+ /** Override the search mode for this tool. Inherits from KB config if not set. */
1043
+ searchMode?: SearchMode;
1044
+ /** Custom formatter for search results. Defaults to numbered list with scores. */
1045
+ formatResults?: (results: VectorSearchResult[]) => string;
1046
+ }
1047
+ declare class KnowledgeBase {
1048
+ readonly name: string;
1049
+ readonly collection: string;
1050
+ private store;
1051
+ private initialized;
1052
+ private bm25;
1053
+ private defaultSearchMode;
1054
+ private hybridConfig;
1055
+ constructor(config: KnowledgeBaseConfig);
1056
+ initialize(): Promise<void>;
1057
+ add(doc: VectorDocument): Promise<void>;
1058
+ addDocuments(docs: VectorDocument[]): Promise<void>;
1059
+ search(query: string, options?: VectorSearchOptions & {
1060
+ searchMode?: SearchMode;
1061
+ }): Promise<VectorSearchResult[]>;
1062
+ get(id: string): Promise<VectorDocument | null>;
1063
+ delete(id: string): Promise<void>;
1064
+ clear(): Promise<void>;
1065
+ close(): Promise<void>;
1066
+ /**
1067
+ * Returns a ToolDef that an Agent can use to search this knowledge base.
1068
+ * Plug the result directly into `Agent({ tools: [kb.asTool()] })`.
1069
+ */
1070
+ asTool(config?: KnowledgeBaseToolConfig): ToolDef;
1071
+ private keywordSearch;
1072
+ private hybridSearch;
1073
+ private ensureInit;
1074
+ }
1075
+
1076
+ /**
1077
+ * Lightweight BM25 (Okapi BM25) implementation for keyword search.
1078
+ * Maintains an in-memory inverted index for fast full-text scoring.
1079
+ */
1080
+ interface BM25Document {
1081
+ id: string;
1082
+ content: string;
1083
+ metadata?: Record<string, unknown>;
1084
+ }
1085
+ interface BM25Result {
1086
+ id: string;
1087
+ content: string;
1088
+ score: number;
1089
+ metadata?: Record<string, unknown>;
1090
+ }
1091
+ declare class BM25Index {
1092
+ private docs;
1093
+ private docFreqs;
1094
+ private avgDocLength;
1095
+ /** BM25 free parameter: term frequency saturation. */
1096
+ private k1;
1097
+ /** BM25 free parameter: document length normalization. */
1098
+ private b;
1099
+ constructor(opts?: {
1100
+ k1?: number;
1101
+ b?: number;
1102
+ });
1103
+ get size(): number;
1104
+ add(doc: BM25Document): void;
1105
+ addBatch(docs: BM25Document[]): void;
1106
+ remove(id: string): void;
1107
+ clear(): void;
1108
+ search(query: string, opts?: {
1109
+ topK?: number;
1110
+ minScore?: number;
1111
+ filter?: Record<string, unknown>;
1112
+ }): BM25Result[];
1113
+ private recomputeAvgLength;
1114
+ }
1115
+
1116
+ /**
1117
+ * Reciprocal Rank Fusion (RRF) — merges ranked result lists from different
1118
+ * retrieval methods into a single fused ranking.
1119
+ *
1120
+ * RRF score for document d = sum over all lists L of: 1 / (k + rank_L(d))
1121
+ * where k is a constant (default 60) that mitigates the impact of high
1122
+ * rankings by outlier systems.
1123
+ *
1124
+ * Reference: Cormack, Clarke & Buettcher (2009)
1125
+ */
1126
+ interface RankedItem {
1127
+ id: string;
1128
+ content: string;
1129
+ score: number;
1130
+ metadata?: Record<string, unknown>;
1131
+ }
1132
+ interface RRFOptions {
1133
+ /** Fusion constant. Higher values dampen the effect of rank differences. Default 60. */
1134
+ k?: number;
1135
+ /** Maximum results to return. */
1136
+ topK?: number;
1137
+ /** Minimum fused score to include. */
1138
+ minScore?: number;
1139
+ /** Weight per ranked list. Defaults to equal weighting (1.0 each). */
1140
+ weights?: number[];
1141
+ }
1142
+ declare function reciprocalRankFusion(rankedLists: RankedItem[][], options?: RRFOptions): RankedItem[];
1143
+
1144
+ interface Session {
1145
+ sessionId: string;
1146
+ userId?: string;
1147
+ messages: ChatMessage[];
1148
+ state: Record<string, unknown>;
1149
+ createdAt: Date;
1150
+ updatedAt: Date;
1151
+ }
1152
+
1153
+ interface SessionManagerConfig {
1154
+ /** Maximum messages kept in session history. Oldest are trimmed first. Default: unlimited. */
1155
+ maxMessages?: number;
1156
+ }
1157
+ interface AppendResult {
1158
+ /** Messages that were trimmed from the session because maxMessages was exceeded. */
1159
+ overflow: ChatMessage[];
1160
+ }
1161
+ declare class SessionManager {
1162
+ private storage;
1163
+ private maxMessages?;
1164
+ constructor(storage: StorageDriver, config?: SessionManagerConfig);
1165
+ getOrCreate(sessionId: string, userId?: string): Promise<Session>;
1166
+ appendMessage(sessionId: string, msg: ChatMessage): Promise<AppendResult>;
1167
+ appendMessages(sessionId: string, msgs: ChatMessage[]): Promise<AppendResult>;
1168
+ getHistory(sessionId: string, limit?: number): Promise<ChatMessage[]>;
1169
+ updateState(sessionId: string, patch: Record<string, unknown>): Promise<void>;
1170
+ getState(sessionId: string): Promise<Record<string, unknown>>;
1171
+ deleteSession(sessionId: string): Promise<void>;
1172
+ }
1173
+
1174
+ interface MCPToolProviderConfig {
1175
+ name: string;
1176
+ transport: "stdio" | "http";
1177
+ /** For stdio transport: command to spawn */
1178
+ command?: string;
1179
+ /** For stdio transport: args for the command */
1180
+ args?: string[];
1181
+ /** For stdio transport: environment variables */
1182
+ env?: Record<string, string>;
1183
+ /** For http transport: server URL */
1184
+ url?: string;
1185
+ /** For http transport: custom headers */
1186
+ headers?: Record<string, string>;
1187
+ }
1188
+ /**
1189
+ * Connects to an MCP (Model Context Protocol) server and exposes its tools
1190
+ * as native RadarOS ToolDef[] that any Agent can use.
1191
+ *
1192
+ * Supports stdio and HTTP (Streamable HTTP) transports.
1193
+ * Requires: npm install @modelcontextprotocol/sdk
1194
+ */
1195
+ declare class MCPToolProvider {
1196
+ readonly name: string;
1197
+ private config;
1198
+ private client;
1199
+ private transportInstance;
1200
+ private tools;
1201
+ private connected;
1202
+ constructor(config: MCPToolProviderConfig);
1203
+ connect(): Promise<void>;
1204
+ private discoverTools;
1205
+ private jsonSchemaToZod;
1206
+ /**
1207
+ * Returns tools from this MCP server as RadarOS ToolDef[].
1208
+ * Optionally filter by tool names to reduce token usage.
1209
+ *
1210
+ * @param filter - Tool names to include (without the server name prefix).
1211
+ * If omitted, returns all tools.
1212
+ *
1213
+ * @example
1214
+ * // All tools
1215
+ * await mcp.getTools()
1216
+ *
1217
+ * // Only specific tools (pass the original MCP tool names, not prefixed)
1218
+ * await mcp.getTools({ include: ["get_latest_release", "search_repositories"] })
1219
+ *
1220
+ * // Exclude specific tools
1221
+ * await mcp.getTools({ exclude: ["push_files", "create_repository"] })
1222
+ */
1223
+ getTools(filter?: {
1224
+ include?: string[];
1225
+ exclude?: string[];
1226
+ }): Promise<ToolDef[]>;
1227
+ /** Refresh the tool list from the MCP server. */
1228
+ refresh(): Promise<void>;
1229
+ /** Disconnect from the MCP server. */
1230
+ close(): Promise<void>;
1231
+ }
1232
+
1233
+ /**
1234
+ * A2A (Agent-to-Agent) Protocol types.
1235
+ * Based on the A2A specification v0.2.
1236
+ * https://google.github.io/A2A/specification/
1237
+ */
1238
+ interface A2ATextPart {
1239
+ kind: "text";
1240
+ text: string;
1241
+ }
1242
+ interface A2AFilePart {
1243
+ kind: "file";
1244
+ file: {
1245
+ name?: string;
1246
+ mimeType?: string;
1247
+ bytes?: string;
1248
+ uri?: string;
1249
+ };
1250
+ }
1251
+ interface A2ADataPart {
1252
+ kind: "data";
1253
+ data: Record<string, unknown>;
1254
+ }
1255
+ type A2APart = A2ATextPart | A2AFilePart | A2ADataPart;
1256
+ interface A2AMessage {
1257
+ role: "user" | "agent";
1258
+ parts: A2APart[];
1259
+ messageId?: string;
1260
+ taskId?: string;
1261
+ referenceTaskIds?: string[];
1262
+ metadata?: Record<string, unknown>;
1263
+ }
1264
+ type A2ATaskState = "submitted" | "working" | "input-required" | "completed" | "failed" | "canceled";
1265
+ interface A2AArtifact {
1266
+ artifactId: string;
1267
+ name?: string;
1268
+ description?: string;
1269
+ parts: A2APart[];
1270
+ metadata?: Record<string, unknown>;
1271
+ }
1272
+ interface A2ATask {
1273
+ id: string;
1274
+ sessionId?: string;
1275
+ status: {
1276
+ state: A2ATaskState;
1277
+ message?: A2AMessage;
1278
+ timestamp?: string;
1279
+ };
1280
+ artifacts?: A2AArtifact[];
1281
+ history?: A2AMessage[];
1282
+ metadata?: Record<string, unknown>;
1283
+ }
1284
+ interface A2ASkill {
1285
+ id: string;
1286
+ name: string;
1287
+ description?: string;
1288
+ tags?: string[];
1289
+ examples?: string[];
1290
+ }
1291
+ interface A2AAgentCard {
1292
+ name: string;
1293
+ description?: string;
1294
+ url: string;
1295
+ version?: string;
1296
+ provider?: {
1297
+ organization: string;
1298
+ url?: string;
1299
+ };
1300
+ capabilities?: {
1301
+ streaming?: boolean;
1302
+ pushNotifications?: boolean;
1303
+ stateTransitionHistory?: boolean;
1304
+ };
1305
+ authentication?: {
1306
+ schemes?: string[];
1307
+ credentials?: string;
1308
+ };
1309
+ skills?: A2ASkill[];
1310
+ defaultInputModes?: string[];
1311
+ defaultOutputModes?: string[];
1312
+ supportedInputModes?: string[];
1313
+ supportedOutputModes?: string[];
1314
+ }
1315
+ interface A2AJsonRpcRequest {
1316
+ jsonrpc: "2.0";
1317
+ id: string | number;
1318
+ method: string;
1319
+ params?: Record<string, unknown>;
1320
+ }
1321
+ interface A2AJsonRpcResponse {
1322
+ jsonrpc: "2.0";
1323
+ id: string | number;
1324
+ result?: unknown;
1325
+ error?: {
1326
+ code: number;
1327
+ message: string;
1328
+ data?: unknown;
1329
+ };
1330
+ }
1331
+ interface A2ASendParams {
1332
+ message: A2AMessage;
1333
+ configuration?: {
1334
+ acceptedOutputModes?: string[];
1335
+ blocking?: boolean;
1336
+ };
1337
+ metadata?: Record<string, unknown>;
1338
+ }
1339
+ interface A2ATaskQueryParams {
1340
+ id: string;
1341
+ historyLength?: number;
1342
+ }
1343
+
1344
+ interface A2ARemoteAgentConfig {
1345
+ url: string;
1346
+ /** Custom headers for every request (e.g. auth tokens). */
1347
+ headers?: Record<string, string>;
1348
+ /** Override the discovered name. */
1349
+ name?: string;
1350
+ /** Request timeout in ms (default 60000). */
1351
+ timeoutMs?: number;
1352
+ }
1353
+ /**
1354
+ * A2ARemoteAgent wraps a remote A2A-compliant agent.
1355
+ * It can be used as a tool, a Team member, or called directly.
1356
+ */
1357
+ declare class A2ARemoteAgent {
1358
+ readonly url: string;
1359
+ name: string;
1360
+ instructions: string;
1361
+ skills: Array<{
1362
+ id: string;
1363
+ name: string;
1364
+ description?: string;
1365
+ }>;
1366
+ private headers;
1367
+ private timeoutMs;
1368
+ private card;
1369
+ private rpcId;
1370
+ get tools(): ToolDef[];
1371
+ get modelId(): string;
1372
+ get providerId(): string;
1373
+ get hasStructuredOutput(): boolean;
1374
+ constructor(config: A2ARemoteAgentConfig);
1375
+ /**
1376
+ * Fetch the Agent Card from /.well-known/agent.json and populate metadata.
1377
+ */
1378
+ discover(): Promise<A2AAgentCard>;
1379
+ /**
1380
+ * Synchronous run: sends message/send and returns RunOutput.
1381
+ */
1382
+ run(input: string, opts?: RunOpts): Promise<RunOutput>;
1383
+ /**
1384
+ * Streaming run: sends message/stream and yields StreamChunks from SSE.
1385
+ */
1386
+ stream(input: string, opts?: RunOpts): AsyncGenerator<StreamChunk>;
1387
+ /**
1388
+ * Wrap this remote agent as a ToolDef so it can be used by an orchestrator agent.
1389
+ */
1390
+ asTool(): ToolDef;
1391
+ getAgentCard(): A2AAgentCard | null;
1392
+ private partsToText;
1393
+ }
1394
+
1395
+ type AudioFormat = "pcm16" | "g711_ulaw" | "g711_alaw";
1396
+ interface TurnDetectionConfig {
1397
+ /** Server-side VAD type. */
1398
+ type: "server_vad";
1399
+ /** Activation threshold (0-1). Lower = more sensitive. */
1400
+ threshold?: number;
1401
+ /** Duration of speech (ms) required to open the turn. */
1402
+ prefixPaddingMs?: number;
1403
+ /** Duration of silence (ms) required to close the turn. */
1404
+ silenceDurationMs?: number;
1405
+ }
1406
+ interface RealtimeSessionConfig {
1407
+ instructions?: string;
1408
+ voice?: string;
1409
+ tools?: ToolDefinition[];
1410
+ inputAudioFormat?: AudioFormat;
1411
+ outputAudioFormat?: AudioFormat;
1412
+ turnDetection?: TurnDetectionConfig | null;
1413
+ temperature?: number;
1414
+ maxResponseOutputTokens?: number | "inf";
1415
+ apiKey?: string;
1416
+ }
1417
+ interface RealtimeToolCall {
1418
+ id: string;
1419
+ name: string;
1420
+ arguments: string;
1421
+ }
1422
+ type RealtimeEventMap = {
1423
+ audio: {
1424
+ data: Buffer;
1425
+ mimeType?: string;
1426
+ };
1427
+ text: {
1428
+ text: string;
1429
+ };
1430
+ transcript: {
1431
+ text: string;
1432
+ role: "user" | "assistant";
1433
+ };
1434
+ tool_call: RealtimeToolCall;
1435
+ interrupted: {};
1436
+ error: {
1437
+ error: Error;
1438
+ };
1439
+ connected: {};
1440
+ disconnected: {};
1441
+ };
1442
+ type RealtimeEvent = keyof RealtimeEventMap;
1443
+ interface RealtimeConnection {
1444
+ sendAudio(data: Buffer): void;
1445
+ sendText(text: string): void;
1446
+ sendToolResult(callId: string, result: string): void;
1447
+ interrupt(): void;
1448
+ close(): Promise<void>;
1449
+ on<K extends RealtimeEvent>(event: K, handler: (data: RealtimeEventMap[K]) => void): void;
1450
+ off<K extends RealtimeEvent>(event: K, handler: (data: RealtimeEventMap[K]) => void): void;
1451
+ }
1452
+ interface RealtimeProvider {
1453
+ readonly providerId: string;
1454
+ readonly modelId: string;
1455
+ connect(config: RealtimeSessionConfig): Promise<RealtimeConnection>;
1456
+ }
1457
+ interface VoiceAgentConfig {
1458
+ name: string;
1459
+ provider: RealtimeProvider;
1460
+ instructions?: string;
1461
+ tools?: ToolDef[];
1462
+ voice?: string;
1463
+ turnDetection?: TurnDetectionConfig | null;
1464
+ inputAudioFormat?: AudioFormat;
1465
+ outputAudioFormat?: AudioFormat;
1466
+ temperature?: number;
1467
+ maxResponseOutputTokens?: number | "inf";
1468
+ eventBus?: EventBus;
1469
+ logLevel?: LogLevel;
1470
+ /** User-scoped memory — persists facts about a user across sessions. */
1471
+ userMemory?: UserMemory;
1472
+ /** LLM model used for auto-extracting user facts from transcripts (required if userMemory is set). */
1473
+ model?: ModelProvider;
1474
+ /** Default session ID (can be overridden per connect()). */
1475
+ sessionId?: string;
1476
+ /** Default user ID (can be overridden per connect()). */
1477
+ userId?: string;
1478
+ }
1479
+ type VoiceSessionEventMap = RealtimeEventMap & {
1480
+ tool_call_start: {
1481
+ name: string;
1482
+ args: unknown;
1483
+ };
1484
+ tool_result: {
1485
+ name: string;
1486
+ result: string;
1487
+ };
1488
+ };
1489
+ type VoiceSessionEvent = keyof VoiceSessionEventMap;
1490
+ interface VoiceSession {
1491
+ sendAudio(data: Buffer): void;
1492
+ sendText(text: string): void;
1493
+ interrupt(): void;
1494
+ close(): Promise<void>;
1495
+ on<K extends VoiceSessionEvent>(event: K, handler: (data: VoiceSessionEventMap[K]) => void): void;
1496
+ off<K extends VoiceSessionEvent>(event: K, handler: (data: VoiceSessionEventMap[K]) => void): void;
1497
+ }
1498
+
1499
+ declare class VoiceAgent {
1500
+ readonly name: string;
1501
+ private config;
1502
+ private eventBus;
1503
+ private logger;
1504
+ private toolExecutor;
1505
+ constructor(config: VoiceAgentConfig);
1506
+ connect(opts?: {
1507
+ apiKey?: string;
1508
+ sessionId?: string;
1509
+ userId?: string;
1510
+ }): Promise<VoiceSession>;
1511
+ /**
1512
+ * Consolidate transcript deltas into full messages.
1513
+ * Voice transcripts arrive as many small chunks (one per word/syllable).
1514
+ * Consecutive entries with the same role are merged into a single message.
1515
+ */
1516
+ private consolidateTranscripts;
1517
+ private persistSession;
1518
+ private wireEvents;
1519
+ private handleToolCall;
1520
+ }
1521
+
1522
+ interface OpenAIRealtimeConfig {
1523
+ apiKey?: string;
1524
+ baseURL?: string;
1525
+ }
1526
+ declare class OpenAIRealtimeProvider implements RealtimeProvider {
1527
+ readonly providerId = "openai-realtime";
1528
+ readonly modelId: string;
1529
+ private apiKey?;
1530
+ private baseURL?;
1531
+ constructor(modelId?: string, config?: OpenAIRealtimeConfig);
1532
+ connect(config: RealtimeSessionConfig): Promise<RealtimeConnection>;
1533
+ private buildSessionPayload;
1534
+ }
1535
+
1536
+ interface GoogleLiveConfig {
1537
+ apiKey?: string;
1538
+ }
1539
+ declare class GoogleLiveProvider implements RealtimeProvider {
1540
+ readonly providerId = "google-live";
1541
+ readonly modelId: string;
1542
+ private apiKey?;
1543
+ constructor(modelId?: string, config?: GoogleLiveConfig);
1544
+ connect(config: RealtimeSessionConfig): Promise<RealtimeConnection>;
1545
+ }
1546
+
1547
+ /**
1548
+ * Base class for all RadarOS Toolkits.
1549
+ * A Toolkit is a collection of related tools that share configuration.
1550
+ */
1551
+ declare abstract class Toolkit {
1552
+ abstract readonly name: string;
1553
+ /**
1554
+ * Returns all tools provided by this toolkit as ToolDef[].
1555
+ * Spread them into an Agent's `tools` array.
1556
+ */
1557
+ abstract getTools(): ToolDef[];
1558
+ }
1559
+
1560
+ interface WebSearchConfig {
1561
+ /** Search provider: "tavily" or "serpapi". */
1562
+ provider: "tavily" | "serpapi";
1563
+ /** API key for the search provider. Falls back to TAVILY_API_KEY or SERPAPI_API_KEY env vars. */
1564
+ apiKey?: string;
1565
+ /** Max results to return per search (default 5). */
1566
+ maxResults?: number;
1567
+ }
1568
+ /**
1569
+ * Web Search Toolkit — search the web from your agent.
1570
+ *
1571
+ * Supports Tavily and SerpAPI backends.
1572
+ *
1573
+ * @example
1574
+ * ```ts
1575
+ * const search = new WebSearchToolkit({ provider: "tavily" });
1576
+ * const agent = new Agent({ tools: [...search.getTools()] });
1577
+ * ```
1578
+ */
1579
+ declare class WebSearchToolkit extends Toolkit {
1580
+ readonly name = "websearch";
1581
+ private config;
1582
+ constructor(config: WebSearchConfig);
1583
+ private getApiKey;
1584
+ getTools(): ToolDef[];
1585
+ private searchTavily;
1586
+ private searchSerpApi;
1587
+ }
1588
+
1589
+ interface GmailConfig {
1590
+ /** Path to OAuth2 credentials JSON file. Falls back to GMAIL_CREDENTIALS_PATH env var. */
1591
+ credentialsPath?: string;
1592
+ /** Path to saved token JSON file. Falls back to GMAIL_TOKEN_PATH env var. */
1593
+ tokenPath?: string;
1594
+ /** Pre-authenticated OAuth2 client (if you handle auth yourself). */
1595
+ authClient?: any;
1596
+ }
1597
+ /**
1598
+ * Gmail Toolkit — send, search, and read emails from your agent.
1599
+ *
1600
+ * Requires: npm install googleapis
1601
+ *
1602
+ * @example
1603
+ * ```ts
1604
+ * const gmail = new GmailToolkit({ credentialsPath: "./credentials.json", tokenPath: "./token.json" });
1605
+ * const agent = new Agent({ tools: [...gmail.getTools()] });
1606
+ * ```
1607
+ */
1608
+ declare class GmailToolkit extends Toolkit {
1609
+ readonly name = "gmail";
1610
+ private config;
1611
+ private gmail;
1612
+ constructor(config?: GmailConfig);
1613
+ private getGmailClient;
1614
+ getTools(): ToolDef[];
1615
+ }
1616
+
1617
+ interface WhatsAppConfig {
1618
+ /** WhatsApp Business API access token. Falls back to WHATSAPP_ACCESS_TOKEN env var. */
1619
+ accessToken?: string;
1620
+ /** WhatsApp Business phone number ID. Falls back to WHATSAPP_PHONE_NUMBER_ID env var. */
1621
+ phoneNumberId?: string;
1622
+ /** API version (default "v22.0"). Falls back to WHATSAPP_VERSION env var. */
1623
+ version?: string;
1624
+ /** Default recipient WhatsApp ID. Falls back to WHATSAPP_RECIPIENT_WAID env var. */
1625
+ recipientWaid?: string;
1626
+ }
1627
+ /**
1628
+ * WhatsApp Toolkit — send messages via WhatsApp Business Cloud API (Meta).
1629
+ *
1630
+ * Uses the WhatsApp Cloud API directly (no Twilio).
1631
+ * Setup: https://developers.facebook.com/docs/whatsapp/cloud-api/get-started
1632
+ *
1633
+ * @example
1634
+ * ```ts
1635
+ * const whatsapp = new WhatsAppToolkit({
1636
+ * accessToken: "...",
1637
+ * phoneNumberId: "...",
1638
+ * });
1639
+ * const agent = new Agent({ tools: [...whatsapp.getTools()] });
1640
+ * ```
1641
+ */
1642
+ declare class WhatsAppToolkit extends Toolkit {
1643
+ readonly name = "whatsapp";
1644
+ private accessToken;
1645
+ private phoneNumberId;
1646
+ private version;
1647
+ private recipientWaid;
1648
+ constructor(config?: WhatsAppConfig);
1649
+ private getBaseUrl;
1650
+ private validate;
1651
+ private resolveRecipient;
1652
+ getTools(): ToolDef[];
1653
+ }
1654
+
1655
+ interface HackerNewsConfig {
1656
+ /** Enable fetching top stories (default true). */
1657
+ enableGetTopStories?: boolean;
1658
+ /** Enable fetching user details (default true). */
1659
+ enableGetUserDetails?: boolean;
1660
+ }
1661
+ /**
1662
+ * Hacker News Toolkit — search top stories and user details from HN.
1663
+ *
1664
+ * No API key required — uses the public Hacker News API.
1665
+ *
1666
+ * @example
1667
+ * ```ts
1668
+ * const hn = new HackerNewsToolkit();
1669
+ * const agent = new Agent({ tools: [...hn.getTools()] });
1670
+ * ```
1671
+ */
1672
+ declare class HackerNewsToolkit extends Toolkit {
1673
+ readonly name = "hackernews";
1674
+ private config;
1675
+ constructor(config?: HackerNewsConfig);
1676
+ getTools(): ToolDef[];
1677
+ }
1678
+
1679
+ interface DuckDuckGoConfig {
1680
+ /** Enable web search (default true). */
1681
+ enableSearch?: boolean;
1682
+ /** Enable news search (default true). */
1683
+ enableNews?: boolean;
1684
+ /** Fixed max results per query (default 5). */
1685
+ maxResults?: number;
1686
+ }
1687
+ /**
1688
+ * DuckDuckGo Toolkit — search the web and news without any API key.
1689
+ *
1690
+ * Uses the DuckDuckGo HTML API (no key required).
1691
+ *
1692
+ * @example
1693
+ * ```ts
1694
+ * const ddg = new DuckDuckGoToolkit();
1695
+ * const agent = new Agent({ tools: [...ddg.getTools()] });
1696
+ * ```
1697
+ */
1698
+ declare class DuckDuckGoToolkit extends Toolkit {
1699
+ readonly name = "duckduckgo";
1700
+ private config;
1701
+ constructor(config?: DuckDuckGoConfig);
1702
+ getTools(): ToolDef[];
1703
+ private buildSearchTool;
1704
+ private buildNewsTool;
1705
+ private search;
1706
+ private scrapeHtmlSearch;
1707
+ private decodeDdgUrl;
1708
+ private searchNews;
1709
+ }
1710
+
1711
+ export { type A2AAgentCard, type A2AArtifact, type A2ADataPart, type A2AFilePart, type A2AJsonRpcRequest, type A2AJsonRpcResponse, type A2AMessage, type A2APart, A2ARemoteAgent, type A2ARemoteAgentConfig, type A2ASendParams, type A2ASkill, type A2ATask, type A2ATaskQueryParams, type A2ATaskState, type A2ATextPart, Agent, type AgentConfig, type AgentEventMap, type AgentHooks, type AgentStep, AnthropicProvider, type AppendResult, type Artifact, type AudioFormat, type AudioPart, type BM25Document, BM25Index, type BM25Result, BaseVectorStore, type ChatMessage, type ConditionStep, type ContentPart, type DuckDuckGoConfig, DuckDuckGoToolkit, type EmbeddingProvider, EventBus, type FilePart, type FunctionStep, type GmailConfig, GmailToolkit, GoogleEmbedding, type GoogleEmbeddingConfig, type GoogleLiveConfig, GoogleLiveProvider, GoogleProvider, type GuardrailResult, type HackerNewsConfig, HackerNewsToolkit, type HybridSearchConfig, type ImagePart, InMemoryStorage, InMemoryVectorStore, type InputGuardrail, KnowledgeBase, type KnowledgeBaseConfig, type KnowledgeBaseToolConfig, LLMLoop, type LogLevel, Logger, type LoggerConfig, MCPToolProvider, type MCPToolProviderConfig, Memory, type MemoryConfig, type MemoryEntry, type MessageContent, type MessageRole, type ModelConfig, type ModelProvider, ModelRegistry, type ModelResponse, MongoDBStorage, type MongoDBVectorConfig, MongoDBVectorStore, OllamaProvider, OpenAIEmbedding, type OpenAIEmbeddingConfig, OpenAIProvider, type OpenAIRealtimeConfig, OpenAIRealtimeProvider, type OutputGuardrail, type ParallelStep, type PgVectorConfig, PgVectorStore, PostgresStorage, type QdrantConfig, QdrantVectorStore, type RRFOptions, type RankedItem, type RealtimeConnection, type RealtimeEvent, type RealtimeEventMap, type RealtimeProvider, type RealtimeSessionConfig, type RealtimeToolCall, type ReasoningConfig, type RetryConfig, RunContext, type RunOpts, type RunOutput, type SearchMode, type Session, SessionManager, type SessionManagerConfig, SqliteStorage, type StepDef, type StepResult, type StorageDriver, type StreamChunk, Team, type TeamConfig, TeamMode, type TextPart, type TokenUsage, type ToolCacheConfig, type ToolCall, type ToolCallResult, type ToolDef, type ToolDefinition, ToolExecutor, type ToolResult, Toolkit, type TurnDetectionConfig, type UserFact, UserMemory, type UserMemoryConfig, type VectorDocument, type VectorSearchOptions, type VectorSearchResult, type VectorStore, type VertexAIConfig, VertexAIProvider, VoiceAgent, type VoiceAgentConfig, type VoiceSession, type VoiceSessionEvent, type VoiceSessionEventMap, type WebSearchConfig, WebSearchToolkit, type WhatsAppConfig, WhatsAppToolkit, Workflow, type WorkflowConfig, type WorkflowResult, anthropic, defineTool, getTextContent, google, isMultiModal, ollama, openai, reciprocalRankFusion, registry, vertex, withRetry };