@radaros/core 0.3.6 → 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 (3) hide show
  1. package/dist/index.d.ts +316 -12
  2. package/dist/index.js +1148 -76
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -181,8 +181,10 @@ interface StorageDriver {
181
181
 
182
182
  interface MemoryConfig {
183
183
  storage?: StorageDriver;
184
- maxShortTermMessages?: number;
185
- enableLongTerm?: boolean;
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;
186
188
  }
187
189
  interface MemoryEntry {
188
190
  key: string;
@@ -190,16 +192,33 @@ interface MemoryEntry {
190
192
  createdAt: Date;
191
193
  }
192
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
+ */
193
205
  declare class Memory {
194
206
  private storage;
195
- private maxShortTermMessages;
196
- private enableLongTerm;
207
+ private model?;
208
+ private maxSummaries;
209
+ private initPromise;
197
210
  constructor(config?: MemoryConfig);
198
- addMessages(sessionId: string, messages: ChatMessage[]): Promise<void>;
199
- getMessages(sessionId: string): Promise<ChatMessage[]>;
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. */
200
218
  getSummaries(sessionId: string): Promise<string[]>;
219
+ /** Get summaries formatted as a context string for injection into the system prompt. */
201
220
  getContextString(sessionId: string): Promise<string>;
202
- private summarizeAndStore;
221
+ /** Clear all summaries for a session. */
203
222
  clear(sessionId: string): Promise<void>;
204
223
  }
205
224
 
@@ -392,6 +411,35 @@ type AgentEventMap = {
392
411
  stepName: string;
393
412
  status: "start" | "done" | "error";
394
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
+ };
395
443
  };
396
444
 
397
445
  type EventKey = keyof AgentEventMap;
@@ -954,6 +1002,15 @@ declare class GoogleEmbedding implements EmbeddingProvider {
954
1002
  embedBatch(texts: string[]): Promise<number[][]>;
955
1003
  }
956
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
+ }
957
1014
  interface KnowledgeBaseConfig {
958
1015
  /** Display name used in tool description auto-generation. */
959
1016
  name: string;
@@ -961,6 +1018,15 @@ interface KnowledgeBaseConfig {
961
1018
  vectorStore: VectorStore;
962
1019
  /** Collection/index name inside the vector store. */
963
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;
964
1030
  }
965
1031
  interface KnowledgeBaseToolConfig {
966
1032
  /** Tool name exposed to the LLM. Defaults to `search_<collection>`. */
@@ -973,6 +1039,8 @@ interface KnowledgeBaseToolConfig {
973
1039
  minScore?: number;
974
1040
  /** Metadata filter applied to every search. */
975
1041
  filter?: Record<string, unknown>;
1042
+ /** Override the search mode for this tool. Inherits from KB config if not set. */
1043
+ searchMode?: SearchMode;
976
1044
  /** Custom formatter for search results. Defaults to numbered list with scores. */
977
1045
  formatResults?: (results: VectorSearchResult[]) => string;
978
1046
  }
@@ -981,11 +1049,16 @@ declare class KnowledgeBase {
981
1049
  readonly collection: string;
982
1050
  private store;
983
1051
  private initialized;
1052
+ private bm25;
1053
+ private defaultSearchMode;
1054
+ private hybridConfig;
984
1055
  constructor(config: KnowledgeBaseConfig);
985
1056
  initialize(): Promise<void>;
986
1057
  add(doc: VectorDocument): Promise<void>;
987
1058
  addDocuments(docs: VectorDocument[]): Promise<void>;
988
- search(query: string, options?: VectorSearchOptions): Promise<VectorSearchResult[]>;
1059
+ search(query: string, options?: VectorSearchOptions & {
1060
+ searchMode?: SearchMode;
1061
+ }): Promise<VectorSearchResult[]>;
989
1062
  get(id: string): Promise<VectorDocument | null>;
990
1063
  delete(id: string): Promise<void>;
991
1064
  clear(): Promise<void>;
@@ -995,9 +1068,79 @@ declare class KnowledgeBase {
995
1068
  * Plug the result directly into `Agent({ tools: [kb.asTool()] })`.
996
1069
  */
997
1070
  asTool(config?: KnowledgeBaseToolConfig): ToolDef;
1071
+ private keywordSearch;
1072
+ private hybridSearch;
998
1073
  private ensureInit;
999
1074
  }
1000
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
+
1001
1144
  interface Session {
1002
1145
  sessionId: string;
1003
1146
  userId?: string;
@@ -1007,12 +1150,21 @@ interface Session {
1007
1150
  updatedAt: Date;
1008
1151
  }
1009
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
+ }
1010
1161
  declare class SessionManager {
1011
1162
  private storage;
1012
- constructor(storage: StorageDriver);
1163
+ private maxMessages?;
1164
+ constructor(storage: StorageDriver, config?: SessionManagerConfig);
1013
1165
  getOrCreate(sessionId: string, userId?: string): Promise<Session>;
1014
- appendMessage(sessionId: string, msg: ChatMessage): Promise<void>;
1015
- appendMessages(sessionId: string, msgs: ChatMessage[]): Promise<void>;
1166
+ appendMessage(sessionId: string, msg: ChatMessage): Promise<AppendResult>;
1167
+ appendMessages(sessionId: string, msgs: ChatMessage[]): Promise<AppendResult>;
1016
1168
  getHistory(sessionId: string, limit?: number): Promise<ChatMessage[]>;
1017
1169
  updateState(sessionId: string, patch: Record<string, unknown>): Promise<void>;
1018
1170
  getState(sessionId: string): Promise<Record<string, unknown>>;
@@ -1240,6 +1392,158 @@ declare class A2ARemoteAgent {
1240
1392
  private partsToText;
1241
1393
  }
1242
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
+
1243
1547
  /**
1244
1548
  * Base class for all RadarOS Toolkits.
1245
1549
  * A Toolkit is a collection of related tools that share configuration.
@@ -1404,4 +1708,4 @@ declare class DuckDuckGoToolkit extends Toolkit {
1404
1708
  private searchNews;
1405
1709
  }
1406
1710
 
1407
- 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 Artifact, type AudioPart, BaseVectorStore, type ChatMessage, type ConditionStep, type ContentPart, type DuckDuckGoConfig, DuckDuckGoToolkit, type EmbeddingProvider, EventBus, type FilePart, type FunctionStep, type GmailConfig, GmailToolkit, GoogleEmbedding, type GoogleEmbeddingConfig, GoogleProvider, type GuardrailResult, type HackerNewsConfig, HackerNewsToolkit, 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 OutputGuardrail, type ParallelStep, type PgVectorConfig, PgVectorStore, PostgresStorage, type QdrantConfig, QdrantVectorStore, type ReasoningConfig, type RetryConfig, RunContext, type RunOpts, type RunOutput, type Session, SessionManager, 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 UserFact, UserMemory, type UserMemoryConfig, type VectorDocument, type VectorSearchOptions, type VectorSearchResult, type VectorStore, type VertexAIConfig, VertexAIProvider, type WebSearchConfig, WebSearchToolkit, type WhatsAppConfig, WhatsAppToolkit, Workflow, type WorkflowConfig, type WorkflowResult, anthropic, defineTool, getTextContent, google, isMultiModal, ollama, openai, registry, vertex, withRetry };
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 };