@cloudwarriors-ai/rlm 0.1.5

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 (220) hide show
  1. package/README.md +208 -0
  2. package/dist/application/index.d.ts +4 -0
  3. package/dist/application/index.d.ts.map +1 -0
  4. package/dist/application/index.js +4 -0
  5. package/dist/application/index.js.map +1 -0
  6. package/dist/application/query-handler.d.ts +49 -0
  7. package/dist/application/query-handler.d.ts.map +1 -0
  8. package/dist/application/query-handler.js +311 -0
  9. package/dist/application/query-handler.js.map +1 -0
  10. package/dist/application/rlm-service.d.ts +68 -0
  11. package/dist/application/rlm-service.d.ts.map +1 -0
  12. package/dist/application/rlm-service.js +132 -0
  13. package/dist/application/rlm-service.js.map +1 -0
  14. package/dist/application/session-manager.d.ts +70 -0
  15. package/dist/application/session-manager.d.ts.map +1 -0
  16. package/dist/application/session-manager.js +237 -0
  17. package/dist/application/session-manager.js.map +1 -0
  18. package/dist/cli/commands/config.d.ts +34 -0
  19. package/dist/cli/commands/config.d.ts.map +1 -0
  20. package/dist/cli/commands/config.js +157 -0
  21. package/dist/cli/commands/config.js.map +1 -0
  22. package/dist/cli/commands/index.d.ts +4 -0
  23. package/dist/cli/commands/index.d.ts.map +1 -0
  24. package/dist/cli/commands/index.js +4 -0
  25. package/dist/cli/commands/index.js.map +1 -0
  26. package/dist/cli/commands/query.d.ts +26 -0
  27. package/dist/cli/commands/query.d.ts.map +1 -0
  28. package/dist/cli/commands/query.js +90 -0
  29. package/dist/cli/commands/query.js.map +1 -0
  30. package/dist/cli/commands/session.d.ts +40 -0
  31. package/dist/cli/commands/session.d.ts.map +1 -0
  32. package/dist/cli/commands/session.js +55 -0
  33. package/dist/cli/commands/session.js.map +1 -0
  34. package/dist/cli/config-loader.d.ts +63 -0
  35. package/dist/cli/config-loader.d.ts.map +1 -0
  36. package/dist/cli/config-loader.js +94 -0
  37. package/dist/cli/config-loader.js.map +1 -0
  38. package/dist/cli/index.d.ts +3 -0
  39. package/dist/cli/index.d.ts.map +1 -0
  40. package/dist/cli/index.js +120 -0
  41. package/dist/cli/index.js.map +1 -0
  42. package/dist/cli/output/formatter.d.ts +24 -0
  43. package/dist/cli/output/formatter.d.ts.map +1 -0
  44. package/dist/cli/output/formatter.js +196 -0
  45. package/dist/cli/output/formatter.js.map +1 -0
  46. package/dist/cli/output/index.d.ts +3 -0
  47. package/dist/cli/output/index.d.ts.map +1 -0
  48. package/dist/cli/output/index.js +3 -0
  49. package/dist/cli/output/index.js.map +1 -0
  50. package/dist/cli/output/progress.d.ts +60 -0
  51. package/dist/cli/output/progress.d.ts.map +1 -0
  52. package/dist/cli/output/progress.js +142 -0
  53. package/dist/cli/output/progress.js.map +1 -0
  54. package/dist/domain/errors/base-error.d.ts +17 -0
  55. package/dist/domain/errors/base-error.d.ts.map +1 -0
  56. package/dist/domain/errors/base-error.js +29 -0
  57. package/dist/domain/errors/base-error.js.map +1 -0
  58. package/dist/domain/errors/execution-error.d.ts +61 -0
  59. package/dist/domain/errors/execution-error.d.ts.map +1 -0
  60. package/dist/domain/errors/execution-error.js +86 -0
  61. package/dist/domain/errors/execution-error.js.map +1 -0
  62. package/dist/domain/errors/index.d.ts +14 -0
  63. package/dist/domain/errors/index.d.ts.map +1 -0
  64. package/dist/domain/errors/index.js +26 -0
  65. package/dist/domain/errors/index.js.map +1 -0
  66. package/dist/domain/errors/limit-exceeded.d.ts +38 -0
  67. package/dist/domain/errors/limit-exceeded.d.ts.map +1 -0
  68. package/dist/domain/errors/limit-exceeded.js +71 -0
  69. package/dist/domain/errors/limit-exceeded.js.map +1 -0
  70. package/dist/domain/errors/llm-error.d.ts +60 -0
  71. package/dist/domain/errors/llm-error.d.ts.map +1 -0
  72. package/dist/domain/errors/llm-error.js +92 -0
  73. package/dist/domain/errors/llm-error.js.map +1 -0
  74. package/dist/domain/errors/validation-error.d.ts +58 -0
  75. package/dist/domain/errors/validation-error.d.ts.map +1 -0
  76. package/dist/domain/errors/validation-error.js +81 -0
  77. package/dist/domain/errors/validation-error.js.map +1 -0
  78. package/dist/domain/interfaces/code-executor.d.ts +98 -0
  79. package/dist/domain/interfaces/code-executor.d.ts.map +1 -0
  80. package/dist/domain/interfaces/code-executor.js +2 -0
  81. package/dist/domain/interfaces/code-executor.js.map +1 -0
  82. package/dist/domain/interfaces/event-emitter.d.ts +137 -0
  83. package/dist/domain/interfaces/event-emitter.d.ts.map +1 -0
  84. package/dist/domain/interfaces/event-emitter.js +2 -0
  85. package/dist/domain/interfaces/event-emitter.js.map +1 -0
  86. package/dist/domain/interfaces/index.d.ts +5 -0
  87. package/dist/domain/interfaces/index.d.ts.map +1 -0
  88. package/dist/domain/interfaces/index.js +2 -0
  89. package/dist/domain/interfaces/index.js.map +1 -0
  90. package/dist/domain/interfaces/llm-provider.d.ts +64 -0
  91. package/dist/domain/interfaces/llm-provider.d.ts.map +1 -0
  92. package/dist/domain/interfaces/llm-provider.js +2 -0
  93. package/dist/domain/interfaces/llm-provider.js.map +1 -0
  94. package/dist/domain/interfaces/session-store.d.ts +65 -0
  95. package/dist/domain/interfaces/session-store.d.ts.map +1 -0
  96. package/dist/domain/interfaces/session-store.js +2 -0
  97. package/dist/domain/interfaces/session-store.js.map +1 -0
  98. package/dist/domain/services/context-chunker.d.ts +43 -0
  99. package/dist/domain/services/context-chunker.d.ts.map +1 -0
  100. package/dist/domain/services/context-chunker.js +152 -0
  101. package/dist/domain/services/context-chunker.js.map +1 -0
  102. package/dist/domain/services/cost-calculator.d.ts +63 -0
  103. package/dist/domain/services/cost-calculator.d.ts.map +1 -0
  104. package/dist/domain/services/cost-calculator.js +121 -0
  105. package/dist/domain/services/cost-calculator.js.map +1 -0
  106. package/dist/domain/services/index.d.ts +5 -0
  107. package/dist/domain/services/index.d.ts.map +1 -0
  108. package/dist/domain/services/index.js +9 -0
  109. package/dist/domain/services/index.js.map +1 -0
  110. package/dist/domain/services/limit-checker.d.ts +54 -0
  111. package/dist/domain/services/limit-checker.d.ts.map +1 -0
  112. package/dist/domain/services/limit-checker.js +146 -0
  113. package/dist/domain/services/limit-checker.js.map +1 -0
  114. package/dist/domain/services/result-aggregator.d.ts +49 -0
  115. package/dist/domain/services/result-aggregator.d.ts.map +1 -0
  116. package/dist/domain/services/result-aggregator.js +131 -0
  117. package/dist/domain/services/result-aggregator.js.map +1 -0
  118. package/dist/domain/types/config.d.ts +41 -0
  119. package/dist/domain/types/config.d.ts.map +1 -0
  120. package/dist/domain/types/config.js +22 -0
  121. package/dist/domain/types/config.js.map +1 -0
  122. package/dist/domain/types/context.d.ts +64 -0
  123. package/dist/domain/types/context.d.ts.map +1 -0
  124. package/dist/domain/types/context.js +20 -0
  125. package/dist/domain/types/context.js.map +1 -0
  126. package/dist/domain/types/index.d.ts +5 -0
  127. package/dist/domain/types/index.d.ts.map +1 -0
  128. package/dist/domain/types/index.js +9 -0
  129. package/dist/domain/types/index.js.map +1 -0
  130. package/dist/domain/types/result.d.ts +137 -0
  131. package/dist/domain/types/result.d.ts.map +1 -0
  132. package/dist/domain/types/result.js +27 -0
  133. package/dist/domain/types/result.js.map +1 -0
  134. package/dist/domain/types/session.d.ts +74 -0
  135. package/dist/domain/types/session.d.ts.map +1 -0
  136. package/dist/domain/types/session.js +31 -0
  137. package/dist/domain/types/session.js.map +1 -0
  138. package/dist/factory/create-rlm.d.ts +77 -0
  139. package/dist/factory/create-rlm.d.ts.map +1 -0
  140. package/dist/factory/create-rlm.js +82 -0
  141. package/dist/factory/create-rlm.js.map +1 -0
  142. package/dist/factory/default-config.d.ts +27 -0
  143. package/dist/factory/default-config.d.ts.map +1 -0
  144. package/dist/factory/default-config.js +98 -0
  145. package/dist/factory/default-config.js.map +1 -0
  146. package/dist/factory/index.d.ts +3 -0
  147. package/dist/factory/index.d.ts.map +1 -0
  148. package/dist/factory/index.js +3 -0
  149. package/dist/factory/index.js.map +1 -0
  150. package/dist/index.d.ts +37 -0
  151. package/dist/index.d.ts.map +1 -0
  152. package/dist/index.js +40 -0
  153. package/dist/index.js.map +1 -0
  154. package/dist/infrastructure/events/event-types.d.ts +35 -0
  155. package/dist/infrastructure/events/event-types.d.ts.map +1 -0
  156. package/dist/infrastructure/events/event-types.js +44 -0
  157. package/dist/infrastructure/events/event-types.js.map +1 -0
  158. package/dist/infrastructure/events/index.d.ts +3 -0
  159. package/dist/infrastructure/events/index.d.ts.map +1 -0
  160. package/dist/infrastructure/events/index.js +3 -0
  161. package/dist/infrastructure/events/index.js.map +1 -0
  162. package/dist/infrastructure/events/node-emitter.d.ts +72 -0
  163. package/dist/infrastructure/events/node-emitter.d.ts.map +1 -0
  164. package/dist/infrastructure/events/node-emitter.js +125 -0
  165. package/dist/infrastructure/events/node-emitter.js.map +1 -0
  166. package/dist/infrastructure/llm/index.d.ts +3 -0
  167. package/dist/infrastructure/llm/index.d.ts.map +1 -0
  168. package/dist/infrastructure/llm/index.js +3 -0
  169. package/dist/infrastructure/llm/index.js.map +1 -0
  170. package/dist/infrastructure/llm/openrouter-provider.d.ts +35 -0
  171. package/dist/infrastructure/llm/openrouter-provider.d.ts.map +1 -0
  172. package/dist/infrastructure/llm/openrouter-provider.js +158 -0
  173. package/dist/infrastructure/llm/openrouter-provider.js.map +1 -0
  174. package/dist/infrastructure/llm/prompts/code-gen-prompt.d.ts +21 -0
  175. package/dist/infrastructure/llm/prompts/code-gen-prompt.d.ts.map +1 -0
  176. package/dist/infrastructure/llm/prompts/code-gen-prompt.js +78 -0
  177. package/dist/infrastructure/llm/prompts/code-gen-prompt.js.map +1 -0
  178. package/dist/infrastructure/llm/prompts/error-recovery-prompt.d.ts +24 -0
  179. package/dist/infrastructure/llm/prompts/error-recovery-prompt.d.ts.map +1 -0
  180. package/dist/infrastructure/llm/prompts/error-recovery-prompt.js +70 -0
  181. package/dist/infrastructure/llm/prompts/error-recovery-prompt.js.map +1 -0
  182. package/dist/infrastructure/llm/prompts/index.d.ts +4 -0
  183. package/dist/infrastructure/llm/prompts/index.d.ts.map +1 -0
  184. package/dist/infrastructure/llm/prompts/index.js +4 -0
  185. package/dist/infrastructure/llm/prompts/index.js.map +1 -0
  186. package/dist/infrastructure/llm/prompts/system-prompt.d.ts +12 -0
  187. package/dist/infrastructure/llm/prompts/system-prompt.d.ts.map +1 -0
  188. package/dist/infrastructure/llm/prompts/system-prompt.js +96 -0
  189. package/dist/infrastructure/llm/prompts/system-prompt.js.map +1 -0
  190. package/dist/infrastructure/persistence/index.d.ts +3 -0
  191. package/dist/infrastructure/persistence/index.d.ts.map +1 -0
  192. package/dist/infrastructure/persistence/index.js +3 -0
  193. package/dist/infrastructure/persistence/index.js.map +1 -0
  194. package/dist/infrastructure/persistence/memory-store.d.ts +24 -0
  195. package/dist/infrastructure/persistence/memory-store.d.ts.map +1 -0
  196. package/dist/infrastructure/persistence/memory-store.js +71 -0
  197. package/dist/infrastructure/persistence/memory-store.js.map +1 -0
  198. package/dist/infrastructure/persistence/schema.d.ts +120 -0
  199. package/dist/infrastructure/persistence/schema.d.ts.map +1 -0
  200. package/dist/infrastructure/persistence/schema.js +130 -0
  201. package/dist/infrastructure/persistence/schema.js.map +1 -0
  202. package/dist/infrastructure/sandbox/ast-validator.d.ts +23 -0
  203. package/dist/infrastructure/sandbox/ast-validator.d.ts.map +1 -0
  204. package/dist/infrastructure/sandbox/ast-validator.js +249 -0
  205. package/dist/infrastructure/sandbox/ast-validator.js.map +1 -0
  206. package/dist/infrastructure/sandbox/index.d.ts +4 -0
  207. package/dist/infrastructure/sandbox/index.d.ts.map +1 -0
  208. package/dist/infrastructure/sandbox/index.js +4 -0
  209. package/dist/infrastructure/sandbox/index.js.map +1 -0
  210. package/dist/infrastructure/sandbox/prelude/rlm_prelude.py +376 -0
  211. package/dist/infrastructure/sandbox/process-manager.d.ts +98 -0
  212. package/dist/infrastructure/sandbox/process-manager.d.ts.map +1 -0
  213. package/dist/infrastructure/sandbox/process-manager.js +186 -0
  214. package/dist/infrastructure/sandbox/process-manager.js.map +1 -0
  215. package/dist/infrastructure/sandbox/python-executor.d.ts +29 -0
  216. package/dist/infrastructure/sandbox/python-executor.d.ts.map +1 -0
  217. package/dist/infrastructure/sandbox/python-executor.js +182 -0
  218. package/dist/infrastructure/sandbox/python-executor.js.map +1 -0
  219. package/package.json +65 -0
  220. package/src/infrastructure/sandbox/prelude/rlm_prelude.py +376 -0
@@ -0,0 +1,158 @@
1
+ import { calculateCost } from '../../domain/services/cost-calculator.js';
2
+ import { LLMError, RateLimitError, AuthenticationError, } from '../../domain/errors/index.js';
3
+ /**
4
+ * OpenRouter LLM provider implementation
5
+ */
6
+ export class OpenRouterProvider {
7
+ config;
8
+ constructor(config) {
9
+ this.config = {
10
+ apiKey: config.apiKey,
11
+ model: config.model,
12
+ baseUrl: config.baseUrl ?? 'https://openrouter.ai/api/v1',
13
+ siteUrl: config.siteUrl ?? '',
14
+ siteName: config.siteName ?? 'RLM',
15
+ timeoutMs: config.timeoutMs ?? 60000,
16
+ maxRetries: config.maxRetries ?? 3,
17
+ };
18
+ }
19
+ async generate(messages, options) {
20
+ const openRouterMessages = [];
21
+ // Add system prompt if provided
22
+ if (options?.systemPrompt) {
23
+ openRouterMessages.push({
24
+ role: 'system',
25
+ content: options.systemPrompt,
26
+ });
27
+ }
28
+ // Add conversation messages
29
+ for (const msg of messages) {
30
+ openRouterMessages.push({
31
+ role: msg.role,
32
+ content: msg.content,
33
+ });
34
+ }
35
+ const requestBody = {
36
+ model: this.config.model,
37
+ messages: openRouterMessages,
38
+ temperature: options?.temperature,
39
+ max_tokens: options?.maxTokens,
40
+ stop: options?.stopSequences ? [...options.stopSequences] : undefined,
41
+ };
42
+ const response = await this.makeRequest(requestBody);
43
+ const choice = response.choices[0];
44
+ if (!choice) {
45
+ throw new LLMError('No response choice returned from OpenRouter');
46
+ }
47
+ const usage = {
48
+ promptTokens: response.usage.prompt_tokens,
49
+ completionTokens: response.usage.completion_tokens,
50
+ totalTokens: response.usage.total_tokens,
51
+ };
52
+ const cost = calculateCost(usage, this.config.model);
53
+ return {
54
+ content: choice.message.content,
55
+ usage,
56
+ model: response.model,
57
+ finishReason: this.mapFinishReason(choice.finish_reason),
58
+ cost,
59
+ };
60
+ }
61
+ estimateTokens(text) {
62
+ // Rough estimate: ~4 characters per token for English text
63
+ // This is a simple heuristic; real tokenization varies by model
64
+ return Math.ceil(text.length / 4);
65
+ }
66
+ getModel() {
67
+ return this.config.model;
68
+ }
69
+ async healthCheck() {
70
+ try {
71
+ // Make a minimal request to check connectivity
72
+ const response = await fetch(`${this.config.baseUrl}/models`, {
73
+ method: 'GET',
74
+ headers: {
75
+ Authorization: `Bearer ${this.config.apiKey}`,
76
+ },
77
+ signal: AbortSignal.timeout(5000),
78
+ });
79
+ return response.ok;
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ async makeRequest(body) {
86
+ let lastError = null;
87
+ for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
88
+ try {
89
+ const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
90
+ method: 'POST',
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ Authorization: `Bearer ${this.config.apiKey}`,
94
+ 'HTTP-Referer': this.config.siteUrl,
95
+ 'X-Title': this.config.siteName,
96
+ },
97
+ body: JSON.stringify(body),
98
+ signal: AbortSignal.timeout(this.config.timeoutMs),
99
+ });
100
+ if (!response.ok) {
101
+ const errorBody = (await response.json().catch(() => ({})));
102
+ const errorMessage = errorBody.error?.message ?? `HTTP ${response.status}`;
103
+ if (response.status === 401) {
104
+ throw new AuthenticationError('Invalid OpenRouter API key');
105
+ }
106
+ if (response.status === 429) {
107
+ const retryAfter = parseInt(response.headers.get('retry-after') ?? '60', 10);
108
+ throw new RateLimitError('OpenRouter rate limit exceeded', retryAfter);
109
+ }
110
+ if (response.status >= 500) {
111
+ // Retry on server errors
112
+ lastError = new LLMError(errorMessage, { statusCode: response.status });
113
+ await this.sleep(1000 * (attempt + 1));
114
+ continue;
115
+ }
116
+ throw new LLMError(errorMessage, { statusCode: response.status });
117
+ }
118
+ return (await response.json());
119
+ }
120
+ catch (error) {
121
+ if (error instanceof AuthenticationError || error instanceof RateLimitError) {
122
+ throw error;
123
+ }
124
+ if (error instanceof LLMError) {
125
+ lastError = error;
126
+ }
127
+ else if (error instanceof Error) {
128
+ lastError = new LLMError(error.message);
129
+ }
130
+ else {
131
+ lastError = new LLMError('Unknown error');
132
+ }
133
+ // Retry on network errors
134
+ if (attempt < this.config.maxRetries - 1) {
135
+ await this.sleep(1000 * (attempt + 1));
136
+ }
137
+ }
138
+ }
139
+ throw lastError ?? new LLMError('Request failed after retries');
140
+ }
141
+ mapFinishReason(reason) {
142
+ switch (reason) {
143
+ case 'stop':
144
+ return 'stop';
145
+ case 'length':
146
+ case 'max_tokens':
147
+ return 'length';
148
+ case 'content_filter':
149
+ return 'content_filter';
150
+ default:
151
+ return 'error';
152
+ }
153
+ }
154
+ sleep(ms) {
155
+ return new Promise((resolve) => setTimeout(resolve, ms));
156
+ }
157
+ }
158
+ //# sourceMappingURL=openrouter-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openrouter-provider.js","sourceRoot":"","sources":["../../../src/infrastructure/llm/openrouter-provider.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AACzE,OAAO,EACL,QAAQ,EACR,cAAc,EACd,mBAAmB,GAEpB,MAAM,8BAA8B,CAAC;AAkEtC;;GAEG;AACH,MAAM,OAAO,kBAAkB;IACZ,MAAM,CAA6B;IAEpD,YAAY,MAAwB;QAClC,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,8BAA8B;YACzD,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,EAAE;YAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,KAAK;YAClC,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,KAAK;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AAQ,CAAC;YACd,KAAK,YAAY;gBACf,OAAO,QAAQ,CAAC;YAClB,KAAK,gBAAgB;gBACnB,OAAO,gBAAgB,CAAC;YAC1B;gBACE,OAAO,OAAO,CAAC;QACnB,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,EAAU;QACtB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Prompt for generating Python code to process context
3
+ */
4
+ export declare const CODE_GEN_PROMPT = "Based on the context and query, write Python code to accomplish the task.\n\n## Rules\n1. Use only the provided functions: llm_query(), set_result(), set_variable()\n2. Do NOT use: file I/O, network requests, subprocess, exec, eval\n3. Do NOT import modules except: json, re, collections, itertools, functools\n4. Always call set_result() with your final answer\n5. Keep code simple and focused on the task\n\n## Context Info\n{context_info}\n\n## Query\n{query}\n\nWrite your Python code inside a code block:";
5
+ /**
6
+ * Prompt for recursive query processing
7
+ */
8
+ export declare const RECURSIVE_QUERY_PROMPT = "You are processing a recursive query as part of a larger RLM task.\n\n## Context\n{context}\n\n## Query\n{query}\n\nProvide a direct, focused answer to this specific query. Be concise but thorough.";
9
+ /**
10
+ * Format the code generation prompt
11
+ */
12
+ export declare function formatCodeGenPrompt(contextInfo: string, query: string): string;
13
+ /**
14
+ * Format the recursive query prompt
15
+ */
16
+ export declare function formatRecursiveQueryPrompt(context: string, query: string): string;
17
+ /**
18
+ * Extract Python code from LLM response
19
+ */
20
+ export declare function extractPythonCode(response: string): string | null;
21
+ //# sourceMappingURL=code-gen-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-gen-prompt.d.ts","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/code-gen-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,eAAe,kgBAegB,CAAC;AAE7C;;GAEG;AACH,eAAO,MAAM,sBAAsB,0MAQ+C,CAAC;AAEnF;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,MAAM,GACZ,MAAM,CAIR;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,MAAM,CAIR;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAkCjE"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Prompt for generating Python code to process context
3
+ */
4
+ export const CODE_GEN_PROMPT = `Based on the context and query, write Python code to accomplish the task.
5
+
6
+ ## Rules
7
+ 1. Use only the provided functions: llm_query(), set_result(), set_variable()
8
+ 2. Do NOT use: file I/O, network requests, subprocess, exec, eval
9
+ 3. Do NOT import modules except: json, re, collections, itertools, functools
10
+ 4. Always call set_result() with your final answer
11
+ 5. Keep code simple and focused on the task
12
+
13
+ ## Context Info
14
+ {context_info}
15
+
16
+ ## Query
17
+ {query}
18
+
19
+ Write your Python code inside a code block:`;
20
+ /**
21
+ * Prompt for recursive query processing
22
+ */
23
+ export const RECURSIVE_QUERY_PROMPT = `You are processing a recursive query as part of a larger RLM task.
24
+
25
+ ## Context
26
+ {context}
27
+
28
+ ## Query
29
+ {query}
30
+
31
+ Provide a direct, focused answer to this specific query. Be concise but thorough.`;
32
+ /**
33
+ * Format the code generation prompt
34
+ */
35
+ export function formatCodeGenPrompt(contextInfo, query) {
36
+ return CODE_GEN_PROMPT
37
+ .replace('{context_info}', contextInfo)
38
+ .replace('{query}', query);
39
+ }
40
+ /**
41
+ * Format the recursive query prompt
42
+ */
43
+ export function formatRecursiveQueryPrompt(context, query) {
44
+ return RECURSIVE_QUERY_PROMPT
45
+ .replace('{context}', context)
46
+ .replace('{query}', query);
47
+ }
48
+ /**
49
+ * Extract Python code from LLM response
50
+ */
51
+ export function extractPythonCode(response) {
52
+ // Try to find code in markdown code blocks
53
+ const codeBlockRegex = /```(?:python)?\s*\n([\s\S]*?)\n```/g;
54
+ const matches = [];
55
+ let match;
56
+ while ((match = codeBlockRegex.exec(response)) !== null) {
57
+ if (match[1]) {
58
+ matches.push(match[1].trim());
59
+ }
60
+ }
61
+ if (matches.length > 0) {
62
+ // Return the longest code block (likely the main code)
63
+ return matches.reduce((a, b) => (a.length > b.length ? a : b));
64
+ }
65
+ // If no code blocks, check if the entire response looks like Python code
66
+ const lines = response.trim().split('\n');
67
+ const looksLikePython = lines.some((line) => line.startsWith('def ') ||
68
+ line.startsWith('class ') ||
69
+ line.startsWith('import ') ||
70
+ line.startsWith('from ') ||
71
+ line.includes('llm_query(') ||
72
+ line.includes('set_result('));
73
+ if (looksLikePython) {
74
+ return response.trim();
75
+ }
76
+ return null;
77
+ }
78
+ //# sourceMappingURL=code-gen-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-gen-prompt.js","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/code-gen-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;4CAea,CAAC;AAE7C;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;;;;;;;;kFAQ4C,CAAC;AAEnF;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,WAAmB,EACnB,KAAa;IAEb,OAAO,eAAe;SACnB,OAAO,CAAC,gBAAgB,EAAE,WAAW,CAAC;SACtC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,0BAA0B,CACxC,OAAe,EACf,KAAa;IAEb,OAAO,sBAAsB;SAC1B,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iBAAiB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 @@
1
+ /**
2
+ * Prompt for recovering from code execution errors
3
+ */
4
+ export declare const ERROR_RECOVERY_PROMPT = "Your previous code failed to execute. Please fix the error and try again.\n\n## Previous Code\n```python\n{previous_code}\n```\n\n## Error\n{error}\n\n## Traceback\n{traceback}\n\n## Guidelines\n1. Analyze the error message carefully\n2. Fix the specific issue that caused the error\n3. Ensure your fix doesn't introduce new problems\n4. Keep the same overall approach if it was correct\n5. Always call set_result() with your final answer\n\nWrite the corrected Python code:";
5
+ /**
6
+ * Prompt for recovering from validation errors
7
+ */
8
+ export declare const VALIDATION_ERROR_PROMPT = "Your code failed security validation. Please rewrite it following the restrictions.\n\n## Previous Code\n```python\n{previous_code}\n```\n\n## Validation Errors\n{validation_errors}\n\n## Restrictions\n- Do NOT use: file I/O (open, read, write)\n- Do NOT use: network (requests, urllib, socket)\n- Do NOT use: subprocess, os.system, exec, eval\n- Do NOT import: os, sys, subprocess, socket, requests\n- Only allowed imports: json, re, collections, itertools, functools\n\nWrite the corrected Python code following these restrictions:";
9
+ /**
10
+ * Format error recovery prompt
11
+ */
12
+ export declare function formatErrorRecoveryPrompt(previousCode: string, error: string, traceback?: string): string;
13
+ /**
14
+ * Format validation error recovery prompt
15
+ */
16
+ export declare function formatValidationErrorPrompt(previousCode: string, validationErrors: readonly {
17
+ line: number;
18
+ message: string;
19
+ }[]): string;
20
+ /**
21
+ * Maximum number of error recovery attempts
22
+ */
23
+ export declare const MAX_RECOVERY_ATTEMPTS = 3;
24
+ //# sourceMappingURL=error-recovery-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-recovery-prompt.d.ts","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/error-recovery-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,qBAAqB,+dAoBD,CAAC;AAElC;;GAEG;AACH,eAAO,MAAM,uBAAuB,0hBAiB0B,CAAC;AAE/D;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,MAAM,EACb,SAAS,CAAC,EAAE,MAAM,GACjB,MAAM,CAKR;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CACzC,YAAY,EAAE,MAAM,EACpB,gBAAgB,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,EAAE,GAC7D,MAAM,CAQR;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,IAAI,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Prompt for recovering from code execution errors
3
+ */
4
+ export const ERROR_RECOVERY_PROMPT = `Your previous code failed to execute. Please fix the error and try again.
5
+
6
+ ## Previous Code
7
+ \`\`\`python
8
+ {previous_code}
9
+ \`\`\`
10
+
11
+ ## Error
12
+ {error}
13
+
14
+ ## Traceback
15
+ {traceback}
16
+
17
+ ## Guidelines
18
+ 1. Analyze the error message carefully
19
+ 2. Fix the specific issue that caused the error
20
+ 3. Ensure your fix doesn't introduce new problems
21
+ 4. Keep the same overall approach if it was correct
22
+ 5. Always call set_result() with your final answer
23
+
24
+ Write the corrected Python code:`;
25
+ /**
26
+ * Prompt for recovering from validation errors
27
+ */
28
+ export const VALIDATION_ERROR_PROMPT = `Your code failed security validation. Please rewrite it following the restrictions.
29
+
30
+ ## Previous Code
31
+ \`\`\`python
32
+ {previous_code}
33
+ \`\`\`
34
+
35
+ ## Validation Errors
36
+ {validation_errors}
37
+
38
+ ## Restrictions
39
+ - Do NOT use: file I/O (open, read, write)
40
+ - Do NOT use: network (requests, urllib, socket)
41
+ - Do NOT use: subprocess, os.system, exec, eval
42
+ - Do NOT import: os, sys, subprocess, socket, requests
43
+ - Only allowed imports: json, re, collections, itertools, functools
44
+
45
+ Write the corrected Python code following these restrictions:`;
46
+ /**
47
+ * Format error recovery prompt
48
+ */
49
+ export function formatErrorRecoveryPrompt(previousCode, error, traceback) {
50
+ return ERROR_RECOVERY_PROMPT
51
+ .replace('{previous_code}', previousCode)
52
+ .replace('{error}', error)
53
+ .replace('{traceback}', traceback ?? 'No traceback available');
54
+ }
55
+ /**
56
+ * Format validation error recovery prompt
57
+ */
58
+ export function formatValidationErrorPrompt(previousCode, validationErrors) {
59
+ const errorList = validationErrors
60
+ .map((e) => `- Line ${e.line}: ${e.message}`)
61
+ .join('\n');
62
+ return VALIDATION_ERROR_PROMPT
63
+ .replace('{previous_code}', previousCode)
64
+ .replace('{validation_errors}', errorList);
65
+ }
66
+ /**
67
+ * Maximum number of error recovery attempts
68
+ */
69
+ export const MAX_RECOVERY_ATTEMPTS = 3;
70
+ //# sourceMappingURL=error-recovery-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-recovery-prompt.js","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/error-recovery-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;iCAoBJ,CAAC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;;;;;;;;;;;;;;;;;8DAiBuB,CAAC;AAE/D;;GAEG;AACH,MAAM,UAAU,yBAAyB,CACvC,YAAoB,EACpB,KAAa,EACb,SAAkB;IAElB,OAAO,qBAAqB;SACzB,OAAO,CAAC,iBAAiB,EAAE,YAAY,CAAC;SACxC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC;SACzB,OAAO,CAAC,aAAa,EAAE,SAAS,IAAI,wBAAwB,CAAC,CAAC;AACnE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,2BAA2B,CACzC,YAAoB,EACpB,gBAA8D;IAE9D,MAAM,SAAS,GAAG,gBAAgB;SAC/B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;SAC5C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,OAAO,uBAAuB;SAC3B,OAAO,CAAC,iBAAiB,EAAE,YAAY,CAAC;SACxC,OAAO,CAAC,qBAAqB,EAAE,SAAS,CAAC,CAAC;AAC/C,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { RLM_SYSTEM_PROMPT, formatSystemPrompt, } from './system-prompt.js';
2
+ export { CODE_GEN_PROMPT, RECURSIVE_QUERY_PROMPT, formatCodeGenPrompt, formatRecursiveQueryPrompt, extractPythonCode, } from './code-gen-prompt.js';
3
+ export { ERROR_RECOVERY_PROMPT, VALIDATION_ERROR_PROMPT, formatErrorRecoveryPrompt, formatValidationErrorPrompt, MAX_RECOVERY_ATTEMPTS, } from './error-recovery-prompt.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,4BAA4B,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { RLM_SYSTEM_PROMPT, formatSystemPrompt, } from './system-prompt.js';
2
+ export { CODE_GEN_PROMPT, RECURSIVE_QUERY_PROMPT, formatCodeGenPrompt, formatRecursiveQueryPrompt, extractPythonCode, } from './code-gen-prompt.js';
3
+ export { ERROR_RECOVERY_PROMPT, VALIDATION_ERROR_PROMPT, formatErrorRecoveryPrompt, formatValidationErrorPrompt, MAX_RECOVERY_ATTEMPTS, } from './error-recovery-prompt.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,4BAA4B,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Base system prompt for RLM
3
+ */
4
+ export declare const RLM_SYSTEM_PROMPT = "You are an RLM (Recursive Language Model) agent. Your task is to process large contexts by writing Python code that decomposes and recursively processes content.\n\n## Available Python Functions\n\nYou have access to these special functions in your Python environment:\n\n### llm_query(query: str, *context_vars) -> str\nMake a recursive LLM call with a subset of context.\n- query: The question or task to perform\n- context_vars: Variable names (strings) containing context to include\n- Returns: The LLM's response as a string\n\nExample:\n```python\n# Query with full context\nresult = llm_query(\"Summarize the main points\", \"context\")\n\n# Query with a chunk\nchunk = context[:10000]\nresult = llm_query(\"What are the key findings?\", chunk)\n```\n\n### set_result(result: str) -> None\nSet the final result of your processing. Call this when you have the answer.\n\nExample:\n```python\nset_result(\"The analysis shows three main themes: ...\")\n```\n\n### set_variable(name: str, value: str) -> None\nStore a value for use in subsequent code blocks.\n\nExample:\n```python\nset_variable(\"summary\", \"Key points from analysis...\")\n```\n\n## Available Context Variables\n\nThe following variables contain your input context:\n{context_variables}\n\n## Guidelines\n\n1. **Analyze First**: Examine the context size and structure before processing\n2. **Chunk Large Content**: If context is too large, split it into manageable chunks\n3. **Recursive Decomposition**: Use llm_query() to process chunks recursively\n4. **Aggregate Results**: Combine results from recursive calls into a coherent answer\n5. **Call set_result()**: Always call set_result() with your final answer\n\n## Example Pattern\n\n```python\n# Check if context is small enough to process directly\nif len(context) < 50000:\n result = llm_query(\"Answer the question based on this context\", \"context\")\n set_result(result)\nelse:\n # Split into chunks and process recursively\n chunk_size = len(context) // 4\n chunks = [context[i:i+chunk_size] for i in range(0, len(context), chunk_size)]\n\n results = []\n for i, chunk in enumerate(chunks):\n set_variable(f\"chunk_{i}\", chunk)\n result = llm_query(f\"Analyze chunk {i+1}/{len(chunks)}\", f\"chunk_{i}\")\n results.append(result)\n\n # Combine results\n combined = \"\\n\\n\".join(results)\n set_variable(\"combined\", combined)\n final = llm_query(\"Synthesize these partial analyses into a complete answer\", \"combined\")\n set_result(final)\n```\n\n## Current Task\n\n{query}\n\nWrite Python code to accomplish this task. Your code will be executed in a sandboxed environment.";
5
+ /**
6
+ * Format the system prompt with context variables and query
7
+ */
8
+ export declare function formatSystemPrompt(contextVariables: readonly {
9
+ name: string;
10
+ sizeHint: string;
11
+ }[], query: string): string;
12
+ //# sourceMappingURL=system-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,iBAAiB,snFAgFoE,CAAC;AAEnG;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,gBAAgB,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,EAAE,EAC/D,KAAK,EAAE,MAAM,GACZ,MAAM,CAQR"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Base system prompt for RLM
3
+ */
4
+ export const RLM_SYSTEM_PROMPT = `You are an RLM (Recursive Language Model) agent. Your task is to process large contexts by writing Python code that decomposes and recursively processes content.
5
+
6
+ ## Available Python Functions
7
+
8
+ You have access to these special functions in your Python environment:
9
+
10
+ ### llm_query(query: str, *context_vars) -> str
11
+ Make a recursive LLM call with a subset of context.
12
+ - query: The question or task to perform
13
+ - context_vars: Variable names (strings) containing context to include
14
+ - Returns: The LLM's response as a string
15
+
16
+ Example:
17
+ \`\`\`python
18
+ # Query with full context
19
+ result = llm_query("Summarize the main points", "context")
20
+
21
+ # Query with a chunk
22
+ chunk = context[:10000]
23
+ result = llm_query("What are the key findings?", chunk)
24
+ \`\`\`
25
+
26
+ ### set_result(result: str) -> None
27
+ Set the final result of your processing. Call this when you have the answer.
28
+
29
+ Example:
30
+ \`\`\`python
31
+ set_result("The analysis shows three main themes: ...")
32
+ \`\`\`
33
+
34
+ ### set_variable(name: str, value: str) -> None
35
+ Store a value for use in subsequent code blocks.
36
+
37
+ Example:
38
+ \`\`\`python
39
+ set_variable("summary", "Key points from analysis...")
40
+ \`\`\`
41
+
42
+ ## Available Context Variables
43
+
44
+ The following variables contain your input context:
45
+ {context_variables}
46
+
47
+ ## Guidelines
48
+
49
+ 1. **Analyze First**: Examine the context size and structure before processing
50
+ 2. **Chunk Large Content**: If context is too large, split it into manageable chunks
51
+ 3. **Recursive Decomposition**: Use llm_query() to process chunks recursively
52
+ 4. **Aggregate Results**: Combine results from recursive calls into a coherent answer
53
+ 5. **Call set_result()**: Always call set_result() with your final answer
54
+
55
+ ## Example Pattern
56
+
57
+ \`\`\`python
58
+ # Check if context is small enough to process directly
59
+ if len(context) < 50000:
60
+ result = llm_query("Answer the question based on this context", "context")
61
+ set_result(result)
62
+ else:
63
+ # Split into chunks and process recursively
64
+ chunk_size = len(context) // 4
65
+ chunks = [context[i:i+chunk_size] for i in range(0, len(context), chunk_size)]
66
+
67
+ results = []
68
+ for i, chunk in enumerate(chunks):
69
+ set_variable(f"chunk_{i}", chunk)
70
+ result = llm_query(f"Analyze chunk {i+1}/{len(chunks)}", f"chunk_{i}")
71
+ results.append(result)
72
+
73
+ # Combine results
74
+ combined = "\\n\\n".join(results)
75
+ set_variable("combined", combined)
76
+ final = llm_query("Synthesize these partial analyses into a complete answer", "combined")
77
+ set_result(final)
78
+ \`\`\`
79
+
80
+ ## Current Task
81
+
82
+ {query}
83
+
84
+ Write Python code to accomplish this task. Your code will be executed in a sandboxed environment.`;
85
+ /**
86
+ * Format the system prompt with context variables and query
87
+ */
88
+ export function formatSystemPrompt(contextVariables, query) {
89
+ const varList = contextVariables
90
+ .map((v) => `- \`${v.name}\`: ${v.sizeHint}`)
91
+ .join('\n');
92
+ return RLM_SYSTEM_PROMPT
93
+ .replace('{context_variables}', varList || '(none)')
94
+ .replace('{query}', query);
95
+ }
96
+ //# sourceMappingURL=system-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../../../src/infrastructure/llm/prompts/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kGAgFiE,CAAC;AAEnG;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,gBAA+D,EAC/D,KAAa;IAEb,MAAM,OAAO,GAAG,gBAAgB;SAC7B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;SAC5C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,OAAO,iBAAiB;SACrB,OAAO,CAAC,qBAAqB,EAAE,OAAO,IAAI,QAAQ,CAAC;SACnD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC/B,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { MemorySessionStore } from './memory-store.js';
2
+ export { SESSION_STATUSES, type RLMSessionRow, type RLMCallRow, rlmSessionColumns, rlmCallColumns, CREATE_TABLES_SQL, } from './schema.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/persistence/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EACL,gBAAgB,EAChB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,iBAAiB,EACjB,cAAc,EACd,iBAAiB,GAClB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { MemorySessionStore } from './memory-store.js';
2
+ export { SESSION_STATUSES, rlmSessionColumns, rlmCallColumns, CREATE_TABLES_SQL, } from './schema.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/infrastructure/persistence/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EACL,gBAAgB,EAGhB,iBAAiB,EACjB,cAAc,EACd,iBAAiB,GAClB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { ISessionStore, SessionFilter, SessionPatch } from '../../domain/interfaces/session-store.js';
2
+ import type { RLMSession } from '../../domain/types/session.js';
3
+ /**
4
+ * In-memory session store implementation
5
+ * Suitable for single-process usage and testing
6
+ */
7
+ export declare class MemorySessionStore implements ISessionStore {
8
+ private readonly sessions;
9
+ save(session: RLMSession): Promise<void>;
10
+ load(id: string): Promise<RLMSession | null>;
11
+ update(id: string, patch: SessionPatch): Promise<void>;
12
+ delete(id: string): Promise<void>;
13
+ list(filter?: SessionFilter): Promise<readonly RLMSession[]>;
14
+ count(filter?: SessionFilter): Promise<number>;
15
+ /**
16
+ * Clear all sessions (useful for testing)
17
+ */
18
+ clear(): void;
19
+ /**
20
+ * Get total number of sessions
21
+ */
22
+ get size(): number;
23
+ }
24
+ //# sourceMappingURL=memory-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/persistence/memory-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,YAAY,EACb,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAEhE;;;GAGG;AACH,qBAAa,kBAAmB,YAAW,aAAa;IACtD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsC;IAEzD,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxC,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;IAI5C,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IActD,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjC,IAAI,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC;IAoC5D,KAAK,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAKpD;;OAEG;IACH,KAAK,IAAI,IAAI;IAIb;;OAEG;IACH,IAAI,IAAI,IAAI,MAAM,CAEjB;CACF"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * In-memory session store implementation
3
+ * Suitable for single-process usage and testing
4
+ */
5
+ export class MemorySessionStore {
6
+ sessions = new Map();
7
+ async save(session) {
8
+ this.sessions.set(session.id, session);
9
+ }
10
+ async load(id) {
11
+ return this.sessions.get(id) ?? null;
12
+ }
13
+ async update(id, patch) {
14
+ const session = this.sessions.get(id);
15
+ if (!session) {
16
+ throw new Error(`Session not found: ${id}`);
17
+ }
18
+ const updated = {
19
+ ...session,
20
+ ...patch,
21
+ };
22
+ this.sessions.set(id, updated);
23
+ }
24
+ async delete(id) {
25
+ this.sessions.delete(id);
26
+ }
27
+ async list(filter) {
28
+ let sessions = Array.from(this.sessions.values());
29
+ // Apply filters
30
+ if (filter?.status) {
31
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
32
+ sessions = sessions.filter((s) => statuses.includes(s.status));
33
+ }
34
+ if (filter?.createdAfter) {
35
+ sessions = sessions.filter((s) => s.createdAt >= filter.createdAfter);
36
+ }
37
+ if (filter?.createdBefore) {
38
+ sessions = sessions.filter((s) => s.createdAt <= filter.createdBefore);
39
+ }
40
+ // Apply ordering (only createdAt is supported for in-memory store)
41
+ const orderDir = filter?.orderDir ?? 'desc';
42
+ sessions.sort((a, b) => {
43
+ const aVal = a.createdAt;
44
+ const bVal = b.createdAt;
45
+ return orderDir === 'desc'
46
+ ? bVal.getTime() - aVal.getTime()
47
+ : aVal.getTime() - bVal.getTime();
48
+ });
49
+ // Apply pagination
50
+ const offset = filter?.offset ?? 0;
51
+ const limit = filter?.limit ?? sessions.length;
52
+ return sessions.slice(offset, offset + limit);
53
+ }
54
+ async count(filter) {
55
+ const sessions = await this.list(filter);
56
+ return sessions.length;
57
+ }
58
+ /**
59
+ * Clear all sessions (useful for testing)
60
+ */
61
+ clear() {
62
+ this.sessions.clear();
63
+ }
64
+ /**
65
+ * Get total number of sessions
66
+ */
67
+ get size() {
68
+ return this.sessions.size;
69
+ }
70
+ }
71
+ //# sourceMappingURL=memory-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.js","sourceRoot":"","sources":["../../../src/infrastructure/persistence/memory-store.ts"],"names":[],"mappings":"AAOA;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACZ,QAAQ,GAA4B,IAAI,GAAG,EAAE,CAAC;IAE/D,KAAK,CAAC,IAAI,CAAC,OAAmB;QAC5B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,EAAU;QACnB,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,MAAM,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