@elizaos/plugin-rlm 2.0.3-beta.6 → 2.0.3-beta.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.
- package/dist/index.d.ts +166 -0
- package/dist/index.js +613 -0
- package/dist/index.js.map +1 -0
- package/package.json +4 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { Plugin } from '@elizaos/core';
|
|
2
|
+
|
|
3
|
+
/** Types for the RLM (Recursive Language Model) plugin. */
|
|
4
|
+
type RLMBackend = "openai" | "anthropic" | "gemini" | "groq" | "openrouter";
|
|
5
|
+
type RLMEnvironment = "local" | "docker" | "modal" | "prime";
|
|
6
|
+
interface RLMConfig {
|
|
7
|
+
backend: RLMBackend;
|
|
8
|
+
backendKwargs: Record<string, string>;
|
|
9
|
+
environment: RLMEnvironment;
|
|
10
|
+
maxIterations: number;
|
|
11
|
+
maxDepth: number;
|
|
12
|
+
verbose: boolean;
|
|
13
|
+
pythonPath: string;
|
|
14
|
+
maxRetries?: number;
|
|
15
|
+
retryBaseDelay?: number;
|
|
16
|
+
retryMaxDelay?: number;
|
|
17
|
+
}
|
|
18
|
+
interface RLMMessage {
|
|
19
|
+
role: "user" | "assistant" | "system";
|
|
20
|
+
content: string;
|
|
21
|
+
}
|
|
22
|
+
interface RLMMetadata {
|
|
23
|
+
synthetic: boolean;
|
|
24
|
+
iterations?: number;
|
|
25
|
+
depth?: number;
|
|
26
|
+
error?: string;
|
|
27
|
+
}
|
|
28
|
+
interface RLMResult {
|
|
29
|
+
text: string;
|
|
30
|
+
metadata: RLMMetadata;
|
|
31
|
+
}
|
|
32
|
+
interface RLMInferOptions {
|
|
33
|
+
/** Model identifier for this request */
|
|
34
|
+
model?: string;
|
|
35
|
+
/** Maximum tokens to generate */
|
|
36
|
+
maxTokens?: number;
|
|
37
|
+
/** Sampling temperature */
|
|
38
|
+
temperature?: number;
|
|
39
|
+
/** Top-p sampling parameter */
|
|
40
|
+
topP?: number;
|
|
41
|
+
/** Stop sequences */
|
|
42
|
+
stopSequences?: string[];
|
|
43
|
+
/** User identifier for tracking */
|
|
44
|
+
user?: string;
|
|
45
|
+
/** Request streaming; RLM currently returns complete text responses only. */
|
|
46
|
+
stream?: boolean;
|
|
47
|
+
/** Override max iterations for this request */
|
|
48
|
+
maxIterations?: number;
|
|
49
|
+
/** Override max recursion depth for this request */
|
|
50
|
+
maxDepth?: number;
|
|
51
|
+
/** Override root model for this request */
|
|
52
|
+
rootModel?: string;
|
|
53
|
+
/** Override subcall model for this request */
|
|
54
|
+
subcallModel?: string;
|
|
55
|
+
/** Enable trajectory logging for this request */
|
|
56
|
+
logTrajectories?: boolean;
|
|
57
|
+
/** Enable cost tracking for this request */
|
|
58
|
+
trackCosts?: boolean;
|
|
59
|
+
}
|
|
60
|
+
interface RLMStatusResponse {
|
|
61
|
+
available: boolean;
|
|
62
|
+
backend: string;
|
|
63
|
+
environment: string;
|
|
64
|
+
maxIterations: number;
|
|
65
|
+
maxDepth: number;
|
|
66
|
+
}
|
|
67
|
+
interface GenerateTextParams {
|
|
68
|
+
prompt?: string;
|
|
69
|
+
system?: string;
|
|
70
|
+
messages?: RLMMessage[];
|
|
71
|
+
model?: string;
|
|
72
|
+
maxTokens?: number;
|
|
73
|
+
temperature?: number;
|
|
74
|
+
topP?: number;
|
|
75
|
+
stopSequences?: string[];
|
|
76
|
+
user?: string;
|
|
77
|
+
stream?: boolean;
|
|
78
|
+
}
|
|
79
|
+
declare const DEFAULT_CONFIG: RLMConfig;
|
|
80
|
+
interface RLMMetrics {
|
|
81
|
+
totalRequests: number;
|
|
82
|
+
successfulRequests: number;
|
|
83
|
+
failedRequests: number;
|
|
84
|
+
totalRetries: number;
|
|
85
|
+
averageLatencyMs: number;
|
|
86
|
+
p95LatencyMs: number;
|
|
87
|
+
lastRequestTimestamp: number;
|
|
88
|
+
lastErrorTimestamp?: number;
|
|
89
|
+
lastError?: string;
|
|
90
|
+
}
|
|
91
|
+
type MetricsCallback = (metrics: RLMMetrics) => void;
|
|
92
|
+
declare const ENV_VARS: {
|
|
93
|
+
readonly BACKEND: "ELIZA_RLM_BACKEND";
|
|
94
|
+
readonly ENVIRONMENT: "ELIZA_RLM_ENV";
|
|
95
|
+
readonly MAX_ITERATIONS: "ELIZA_RLM_MAX_ITERATIONS";
|
|
96
|
+
readonly MAX_DEPTH: "ELIZA_RLM_MAX_DEPTH";
|
|
97
|
+
readonly VERBOSE: "ELIZA_RLM_VERBOSE";
|
|
98
|
+
readonly PYTHON_PATH: "ELIZA_RLM_PYTHON_PATH";
|
|
99
|
+
readonly MAX_RETRIES: "ELIZA_RLM_MAX_RETRIES";
|
|
100
|
+
readonly RETRY_BASE_DELAY: "ELIZA_RLM_RETRY_BASE_DELAY";
|
|
101
|
+
readonly RETRY_MAX_DELAY: "ELIZA_RLM_RETRY_MAX_DELAY";
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** RLM Client - communicates with Python subprocess via JSON-RPC IPC. */
|
|
105
|
+
|
|
106
|
+
interface Logger {
|
|
107
|
+
info: (message: string, ...args: unknown[]) => void;
|
|
108
|
+
warn: (message: string, ...args: unknown[]) => void;
|
|
109
|
+
error: (message: string, ...args: unknown[]) => void;
|
|
110
|
+
debug: (message: string, ...args: unknown[]) => void;
|
|
111
|
+
}
|
|
112
|
+
declare function configFromEnv(env?: NodeJS.ProcessEnv): RLMConfig;
|
|
113
|
+
declare class RLMClient {
|
|
114
|
+
private config;
|
|
115
|
+
private process;
|
|
116
|
+
private reader;
|
|
117
|
+
private requestId;
|
|
118
|
+
private pendingRequests;
|
|
119
|
+
private isReady;
|
|
120
|
+
private isAvailable;
|
|
121
|
+
private hasStartupError;
|
|
122
|
+
private logger;
|
|
123
|
+
private metrics;
|
|
124
|
+
private static readonly MAX_LATENCY_SAMPLES;
|
|
125
|
+
private latencies;
|
|
126
|
+
private latencyIndex;
|
|
127
|
+
private latencyCount;
|
|
128
|
+
private metricsCallback;
|
|
129
|
+
constructor(config?: Partial<RLMConfig>, logger?: Logger, strictValidation?: boolean);
|
|
130
|
+
private startServer;
|
|
131
|
+
private waitForReady;
|
|
132
|
+
private handleMessage;
|
|
133
|
+
private sendRequest;
|
|
134
|
+
private ensureServer;
|
|
135
|
+
get available(): boolean;
|
|
136
|
+
getMetrics(): RLMMetrics;
|
|
137
|
+
onMetrics(callback: MetricsCallback): void;
|
|
138
|
+
private updateMetrics;
|
|
139
|
+
static normalizeMessages(messages: string | RLMMessage[]): RLMMessage[];
|
|
140
|
+
infer(messages: string | RLMMessage[], opts?: RLMInferOptions): Promise<RLMResult>;
|
|
141
|
+
getStatus(): Promise<RLMStatusResponse>;
|
|
142
|
+
shutdown(): Promise<void>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* RLM (Recursive Language Model) plugin for elizaOS.
|
|
147
|
+
*
|
|
148
|
+
* This plugin integrates Recursive Language Models into elizaOS, enabling
|
|
149
|
+
* LLMs to process arbitrarily long contexts through recursive self-calls
|
|
150
|
+
* in a REPL environment.
|
|
151
|
+
*
|
|
152
|
+
* Reference:
|
|
153
|
+
* - Paper: https://arxiv.org/abs/2512.24601
|
|
154
|
+
* - Implementation: https://github.com/alexzhang13/rlm
|
|
155
|
+
*/
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Reset the client singleton. Useful for testing or forced reinitialization.
|
|
159
|
+
*/
|
|
160
|
+
declare function resetClient(): Promise<void>;
|
|
161
|
+
/**
|
|
162
|
+
* RLM plugin definition.
|
|
163
|
+
*/
|
|
164
|
+
declare const rlmPlugin: Plugin;
|
|
165
|
+
|
|
166
|
+
export { DEFAULT_CONFIG, ENV_VARS, type GenerateTextParams, RLMClient, type RLMConfig, type RLMInferOptions, type RLMMessage, type RLMMetadata, type RLMResult, type RLMStatusResponse, configFromEnv, rlmPlugin as default, resetClient, rlmPlugin };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
// index.ts
|
|
2
|
+
import {
|
|
3
|
+
buildCanonicalSystemPrompt,
|
|
4
|
+
logger,
|
|
5
|
+
ModelType,
|
|
6
|
+
recordLlmCall,
|
|
7
|
+
resolveEffectiveSystemPrompt
|
|
8
|
+
} from "@elizaos/core";
|
|
9
|
+
|
|
10
|
+
// client.ts
|
|
11
|
+
import { spawn } from "child_process";
|
|
12
|
+
import * as path from "path";
|
|
13
|
+
import * as readline from "readline";
|
|
14
|
+
import { assertRecordedLlmCall } from "@elizaos/core";
|
|
15
|
+
|
|
16
|
+
// types.ts
|
|
17
|
+
var DEFAULT_CONFIG = {
|
|
18
|
+
backend: "gemini",
|
|
19
|
+
backendKwargs: {},
|
|
20
|
+
environment: "local",
|
|
21
|
+
maxIterations: 4,
|
|
22
|
+
maxDepth: 1,
|
|
23
|
+
verbose: false,
|
|
24
|
+
pythonPath: "python",
|
|
25
|
+
maxRetries: 3,
|
|
26
|
+
retryBaseDelay: 1e3,
|
|
27
|
+
retryMaxDelay: 3e4
|
|
28
|
+
};
|
|
29
|
+
var ENV_VARS = {
|
|
30
|
+
BACKEND: "ELIZA_RLM_BACKEND",
|
|
31
|
+
ENVIRONMENT: "ELIZA_RLM_ENV",
|
|
32
|
+
MAX_ITERATIONS: "ELIZA_RLM_MAX_ITERATIONS",
|
|
33
|
+
MAX_DEPTH: "ELIZA_RLM_MAX_DEPTH",
|
|
34
|
+
VERBOSE: "ELIZA_RLM_VERBOSE",
|
|
35
|
+
PYTHON_PATH: "ELIZA_RLM_PYTHON_PATH",
|
|
36
|
+
MAX_RETRIES: "ELIZA_RLM_MAX_RETRIES",
|
|
37
|
+
RETRY_BASE_DELAY: "ELIZA_RLM_RETRY_BASE_DELAY",
|
|
38
|
+
RETRY_MAX_DELAY: "ELIZA_RLM_RETRY_MAX_DELAY"
|
|
39
|
+
};
|
|
40
|
+
var VALID_BACKENDS = [
|
|
41
|
+
"openai",
|
|
42
|
+
"anthropic",
|
|
43
|
+
"gemini",
|
|
44
|
+
"groq",
|
|
45
|
+
"openrouter"
|
|
46
|
+
];
|
|
47
|
+
var VALID_ENVIRONMENTS = ["local", "docker", "modal", "prime"];
|
|
48
|
+
var RLMConfigError = class extends Error {
|
|
49
|
+
constructor(message) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "RLMConfigError";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
function validateConfig(config, strict = false) {
|
|
55
|
+
const errors = [];
|
|
56
|
+
if (config.backend !== void 0 && !VALID_BACKENDS.includes(config.backend)) {
|
|
57
|
+
errors.push(`Invalid backend '${config.backend}'. Valid options: ${VALID_BACKENDS.join(", ")}`);
|
|
58
|
+
}
|
|
59
|
+
if (config.environment !== void 0 && !VALID_ENVIRONMENTS.includes(config.environment)) {
|
|
60
|
+
errors.push(
|
|
61
|
+
`Invalid environment '${config.environment}'. Valid options: ${VALID_ENVIRONMENTS.join(", ")}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
if (config.maxIterations !== void 0 && config.maxIterations < 1) {
|
|
65
|
+
errors.push("maxIterations must be >= 1");
|
|
66
|
+
}
|
|
67
|
+
if (config.maxDepth !== void 0 && config.maxDepth < 1) {
|
|
68
|
+
errors.push("maxDepth must be >= 1");
|
|
69
|
+
}
|
|
70
|
+
if (config.maxRetries !== void 0 && config.maxRetries < 0) {
|
|
71
|
+
errors.push("maxRetries must be >= 0");
|
|
72
|
+
}
|
|
73
|
+
if (config.retryBaseDelay !== void 0 && config.retryBaseDelay < 0) {
|
|
74
|
+
errors.push("retryBaseDelay must be >= 0");
|
|
75
|
+
}
|
|
76
|
+
if (config.retryBaseDelay !== void 0 && config.retryMaxDelay !== void 0 && config.retryMaxDelay < config.retryBaseDelay) {
|
|
77
|
+
errors.push("retryMaxDelay must be >= retryBaseDelay");
|
|
78
|
+
}
|
|
79
|
+
if (strict && errors.length > 0) {
|
|
80
|
+
throw new RLMConfigError(errors.join("; "));
|
|
81
|
+
}
|
|
82
|
+
return errors;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// client.ts
|
|
86
|
+
var defaultLogger = {
|
|
87
|
+
info: (msg, ...args) => console.log(`[RLM] ${msg}`, ...args),
|
|
88
|
+
warn: (msg, ...args) => console.warn(`[RLM] ${msg}`, ...args),
|
|
89
|
+
error: (msg, ...args) => console.error(`[RLM] ${msg}`, ...args),
|
|
90
|
+
debug: (msg, ...args) => console.debug(`[RLM] ${msg}`, ...args)
|
|
91
|
+
};
|
|
92
|
+
function configFromEnv(env2 = process.env) {
|
|
93
|
+
return {
|
|
94
|
+
backend: env2[ENV_VARS.BACKEND] ?? DEFAULT_CONFIG.backend,
|
|
95
|
+
backendKwargs: {},
|
|
96
|
+
environment: env2[ENV_VARS.ENVIRONMENT] ?? DEFAULT_CONFIG.environment,
|
|
97
|
+
maxIterations: Number.parseInt(env2[ENV_VARS.MAX_ITERATIONS] ?? "", 10) || DEFAULT_CONFIG.maxIterations,
|
|
98
|
+
maxDepth: Number.parseInt(env2[ENV_VARS.MAX_DEPTH] ?? "", 10) || DEFAULT_CONFIG.maxDepth,
|
|
99
|
+
verbose: ["1", "true", "yes"].includes((env2[ENV_VARS.VERBOSE] ?? "").toLowerCase()),
|
|
100
|
+
pythonPath: env2[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath,
|
|
101
|
+
maxRetries: Number.parseInt(env2[ENV_VARS.MAX_RETRIES] ?? "", 10) || DEFAULT_CONFIG.maxRetries,
|
|
102
|
+
retryBaseDelay: Number.parseInt(env2[ENV_VARS.RETRY_BASE_DELAY] ?? "", 10) || DEFAULT_CONFIG.retryBaseDelay,
|
|
103
|
+
retryMaxDelay: Number.parseInt(env2[ENV_VARS.RETRY_MAX_DELAY] ?? "", 10) || DEFAULT_CONFIG.retryMaxDelay
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
var RLMClient = class _RLMClient {
|
|
107
|
+
config;
|
|
108
|
+
process = null;
|
|
109
|
+
reader = null;
|
|
110
|
+
requestId = 0;
|
|
111
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
112
|
+
isReady = false;
|
|
113
|
+
isAvailable = false;
|
|
114
|
+
hasStartupError = false;
|
|
115
|
+
logger;
|
|
116
|
+
metrics = {
|
|
117
|
+
totalRequests: 0,
|
|
118
|
+
successfulRequests: 0,
|
|
119
|
+
failedRequests: 0,
|
|
120
|
+
totalRetries: 0,
|
|
121
|
+
averageLatencyMs: 0,
|
|
122
|
+
p95LatencyMs: 0,
|
|
123
|
+
lastRequestTimestamp: 0
|
|
124
|
+
};
|
|
125
|
+
static MAX_LATENCY_SAMPLES = 1e3;
|
|
126
|
+
latencies = new Array(_RLMClient.MAX_LATENCY_SAMPLES).fill(0);
|
|
127
|
+
latencyIndex = 0;
|
|
128
|
+
latencyCount = 0;
|
|
129
|
+
metricsCallback = null;
|
|
130
|
+
constructor(config, logger2, strictValidation = false) {
|
|
131
|
+
this.config = { ...configFromEnv(), ...config };
|
|
132
|
+
this.logger = logger2 ?? defaultLogger;
|
|
133
|
+
const errors = validateConfig(this.config);
|
|
134
|
+
if (errors.length > 0) {
|
|
135
|
+
if (strictValidation) {
|
|
136
|
+
throw new Error(`RLM configuration invalid: ${errors.join("; ")}`);
|
|
137
|
+
}
|
|
138
|
+
for (const error of errors) {
|
|
139
|
+
this.logger.warn(`Configuration warning: ${error}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async startServer() {
|
|
144
|
+
if (this.process) return;
|
|
145
|
+
this.hasStartupError = false;
|
|
146
|
+
this.logger.debug(
|
|
147
|
+
`Starting RLM server: ${this.config.pythonPath} -m elizaos_plugin_rlm.server`
|
|
148
|
+
);
|
|
149
|
+
try {
|
|
150
|
+
this.process = spawn(this.config.pythonPath, ["-m", "elizaos_plugin_rlm.server"], {
|
|
151
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
152
|
+
env: {
|
|
153
|
+
...process.env,
|
|
154
|
+
[ENV_VARS.BACKEND]: this.config.backend,
|
|
155
|
+
[ENV_VARS.ENVIRONMENT]: this.config.environment,
|
|
156
|
+
[ENV_VARS.MAX_ITERATIONS]: String(this.config.maxIterations),
|
|
157
|
+
[ENV_VARS.MAX_DEPTH]: String(this.config.maxDepth),
|
|
158
|
+
[ENV_VARS.VERBOSE]: this.config.verbose ? "true" : "false"
|
|
159
|
+
},
|
|
160
|
+
cwd: path.join(__dirname, "..", "python")
|
|
161
|
+
});
|
|
162
|
+
} catch (error) {
|
|
163
|
+
this.logger.warn(`Failed to start RLM server: ${error}`);
|
|
164
|
+
this.isAvailable = false;
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!this.process.stdout || !this.process.stdin) {
|
|
168
|
+
this.logger.warn("RLM server process missing stdio streams");
|
|
169
|
+
this.isAvailable = false;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
this.reader = readline.createInterface({
|
|
173
|
+
input: this.process.stdout,
|
|
174
|
+
crlfDelay: Number.POSITIVE_INFINITY
|
|
175
|
+
});
|
|
176
|
+
this.reader.on("line", (line) => {
|
|
177
|
+
this.handleMessage(line);
|
|
178
|
+
});
|
|
179
|
+
this.process.stderr?.on("data", (data) => {
|
|
180
|
+
this.logger.debug(`RLM server stderr: ${data.toString()}`);
|
|
181
|
+
});
|
|
182
|
+
this.process.on("error", (error) => {
|
|
183
|
+
this.logger.error(`RLM server error: ${error.message}`);
|
|
184
|
+
this.isAvailable = false;
|
|
185
|
+
this.hasStartupError = true;
|
|
186
|
+
});
|
|
187
|
+
this.process.on("exit", (code) => {
|
|
188
|
+
this.logger.debug(`RLM server exited with code ${code}`);
|
|
189
|
+
this.isReady = false;
|
|
190
|
+
this.isAvailable = false;
|
|
191
|
+
this.process = null;
|
|
192
|
+
});
|
|
193
|
+
await this.waitForReady();
|
|
194
|
+
}
|
|
195
|
+
waitForReady() {
|
|
196
|
+
return new Promise((resolve, reject) => {
|
|
197
|
+
const TIMEOUT_MS = 1e4;
|
|
198
|
+
const POLL_INTERVAL_MS = 100;
|
|
199
|
+
const deadline = Date.now() + TIMEOUT_MS;
|
|
200
|
+
const checkReady = () => {
|
|
201
|
+
if (this.isReady) {
|
|
202
|
+
resolve();
|
|
203
|
+
} else if (!this.process || this.hasStartupError) {
|
|
204
|
+
reject(new Error("RLM server process failed before ready"));
|
|
205
|
+
} else if (Date.now() > deadline) {
|
|
206
|
+
reject(new Error("RLM server startup timeout"));
|
|
207
|
+
} else {
|
|
208
|
+
setTimeout(checkReady, POLL_INTERVAL_MS);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
checkReady();
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
handleMessage(line) {
|
|
215
|
+
try {
|
|
216
|
+
const message = JSON.parse(line);
|
|
217
|
+
if ("ready" in message) {
|
|
218
|
+
const readyMsg = message;
|
|
219
|
+
this.isReady = true;
|
|
220
|
+
this.isAvailable = readyMsg.available;
|
|
221
|
+
this.logger.info(`RLM server ready, available: ${this.isAvailable}`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const response = message;
|
|
225
|
+
const pending = this.pendingRequests.get(response.id);
|
|
226
|
+
if (pending) {
|
|
227
|
+
this.pendingRequests.delete(response.id);
|
|
228
|
+
pending.resolve(response);
|
|
229
|
+
}
|
|
230
|
+
} catch (_error) {
|
|
231
|
+
this.logger.error(`Failed to parse RLM server message: ${line}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async sendRequest(method, params = {}) {
|
|
235
|
+
await this.ensureServer();
|
|
236
|
+
if (!this.process?.stdin) {
|
|
237
|
+
throw new Error("RLM server not running");
|
|
238
|
+
}
|
|
239
|
+
const id = ++this.requestId;
|
|
240
|
+
const request = { id, method, params };
|
|
241
|
+
return new Promise((resolve, reject) => {
|
|
242
|
+
const timeout = setTimeout(() => {
|
|
243
|
+
this.pendingRequests.delete(id);
|
|
244
|
+
reject(new Error(`RLM request timeout: ${method}`));
|
|
245
|
+
}, 6e4);
|
|
246
|
+
this.pendingRequests.set(id, {
|
|
247
|
+
resolve: (response) => {
|
|
248
|
+
clearTimeout(timeout);
|
|
249
|
+
if (response.error) {
|
|
250
|
+
reject(new Error(response.error));
|
|
251
|
+
} else {
|
|
252
|
+
resolve(response.result);
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
reject: (error) => {
|
|
256
|
+
clearTimeout(timeout);
|
|
257
|
+
reject(error);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
this.process?.stdin?.write(`${JSON.stringify(request)}
|
|
261
|
+
`);
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
async ensureServer() {
|
|
265
|
+
if (!this.process || !this.isReady) {
|
|
266
|
+
await this.startServer();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
get available() {
|
|
270
|
+
return this.isAvailable;
|
|
271
|
+
}
|
|
272
|
+
getMetrics() {
|
|
273
|
+
return { ...this.metrics };
|
|
274
|
+
}
|
|
275
|
+
onMetrics(callback) {
|
|
276
|
+
this.metricsCallback = callback;
|
|
277
|
+
}
|
|
278
|
+
updateMetrics(latencyMs, success, error) {
|
|
279
|
+
this.metrics.totalRequests++;
|
|
280
|
+
this.metrics.lastRequestTimestamp = Date.now();
|
|
281
|
+
if (success) {
|
|
282
|
+
this.metrics.successfulRequests++;
|
|
283
|
+
} else {
|
|
284
|
+
this.metrics.failedRequests++;
|
|
285
|
+
this.metrics.lastErrorTimestamp = Date.now();
|
|
286
|
+
this.metrics.lastError = error;
|
|
287
|
+
}
|
|
288
|
+
this.latencies[this.latencyIndex] = latencyMs;
|
|
289
|
+
this.latencyIndex = (this.latencyIndex + 1) % _RLMClient.MAX_LATENCY_SAMPLES;
|
|
290
|
+
this.latencyCount = Math.min(this.latencyCount + 1, _RLMClient.MAX_LATENCY_SAMPLES);
|
|
291
|
+
if (this.latencyCount > 0) {
|
|
292
|
+
const valid = this.latencies.slice(0, this.latencyCount);
|
|
293
|
+
this.metrics.averageLatencyMs = valid.reduce((a, b) => a + b, 0) / this.latencyCount;
|
|
294
|
+
this.metrics.p95LatencyMs = [...valid].sort((a, b) => a - b)[Math.floor(valid.length * 0.95)] ?? 0;
|
|
295
|
+
}
|
|
296
|
+
this.metricsCallback?.(this.getMetrics());
|
|
297
|
+
}
|
|
298
|
+
static normalizeMessages(messages) {
|
|
299
|
+
return typeof messages === "string" ? [{ role: "user", content: messages }] : messages;
|
|
300
|
+
}
|
|
301
|
+
async infer(messages, opts) {
|
|
302
|
+
assertRecordedLlmCall({
|
|
303
|
+
actionType: "rlm.client.infer",
|
|
304
|
+
model: opts?.rootModel,
|
|
305
|
+
purpose: "external_llm"
|
|
306
|
+
});
|
|
307
|
+
const startTime = Date.now();
|
|
308
|
+
const { maxRetries = 3, retryBaseDelay = 1e3, retryMaxDelay = 3e4 } = this.config;
|
|
309
|
+
const RETRYABLE_PATTERNS = ["timeout", "rate limit", "connection", "503", "429", "econnreset"];
|
|
310
|
+
let lastError = null;
|
|
311
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
312
|
+
try {
|
|
313
|
+
await this.ensureServer();
|
|
314
|
+
if (!this.isReady) {
|
|
315
|
+
throw new Error("RLM backend is not available");
|
|
316
|
+
}
|
|
317
|
+
const result = await this.sendRequest("infer", {
|
|
318
|
+
messages: _RLMClient.normalizeMessages(messages),
|
|
319
|
+
opts: opts ?? {}
|
|
320
|
+
});
|
|
321
|
+
this.updateMetrics(Date.now() - startTime, true);
|
|
322
|
+
return result;
|
|
323
|
+
} catch (error) {
|
|
324
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
325
|
+
const isRetryable = RETRYABLE_PATTERNS.some(
|
|
326
|
+
(p) => lastError?.message.toLowerCase().includes(p)
|
|
327
|
+
);
|
|
328
|
+
if (!isRetryable || attempt === maxRetries - 1) {
|
|
329
|
+
this.logger.error(`RLM inference failed after ${attempt + 1} attempts: ${error}`);
|
|
330
|
+
this.updateMetrics(Date.now() - startTime, false, lastError.message);
|
|
331
|
+
throw lastError;
|
|
332
|
+
}
|
|
333
|
+
const delay = Math.min(retryBaseDelay * 2 ** attempt, retryMaxDelay) * (0.75 + Math.random() * 0.5);
|
|
334
|
+
this.metrics.totalRetries++;
|
|
335
|
+
this.logger.warn(
|
|
336
|
+
`RLM attempt ${attempt + 1}/${maxRetries} failed. Retrying in ${Math.round(delay)}ms`
|
|
337
|
+
);
|
|
338
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
this.updateMetrics(Date.now() - startTime, false, lastError?.message);
|
|
342
|
+
throw lastError ?? new Error("RLM inference failed");
|
|
343
|
+
}
|
|
344
|
+
async getStatus() {
|
|
345
|
+
try {
|
|
346
|
+
await this.ensureServer();
|
|
347
|
+
return await this.sendRequest("status");
|
|
348
|
+
} catch {
|
|
349
|
+
return {
|
|
350
|
+
available: false,
|
|
351
|
+
backend: this.config.backend,
|
|
352
|
+
environment: this.config.environment,
|
|
353
|
+
maxIterations: this.config.maxIterations,
|
|
354
|
+
maxDepth: this.config.maxDepth
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
async shutdown() {
|
|
359
|
+
if (!this.process) return;
|
|
360
|
+
try {
|
|
361
|
+
await this.sendRequest("shutdown");
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
this.reader?.close();
|
|
365
|
+
this.process?.kill();
|
|
366
|
+
this.process = null;
|
|
367
|
+
this.isReady = false;
|
|
368
|
+
this.isAvailable = false;
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
// cost.ts
|
|
373
|
+
var MODEL_PRICING = {
|
|
374
|
+
openai: {
|
|
375
|
+
"gpt-5": { input: 2.5, output: 10 },
|
|
376
|
+
"gpt-5-preview": { input: 10, output: 30 },
|
|
377
|
+
"gpt-5-mini": { input: 0.15, output: 0.6 },
|
|
378
|
+
"gpt-3.5-turbo": { input: 0.5, output: 1.5 }
|
|
379
|
+
},
|
|
380
|
+
anthropic: {
|
|
381
|
+
"claude-3-5-sonnet-20241022": { input: 3, output: 15 },
|
|
382
|
+
"claude-3-5-haiku-20241022": { input: 0.8, output: 4 },
|
|
383
|
+
"claude-3-opus-20240229": { input: 15, output: 75 },
|
|
384
|
+
"claude-3-sonnet-20240229": { input: 3, output: 15 },
|
|
385
|
+
"claude-3-haiku-20240307": { input: 0.25, output: 1.25 }
|
|
386
|
+
},
|
|
387
|
+
gemini: {
|
|
388
|
+
"gemini-2.0-flash-exp": { input: 0, output: 0 },
|
|
389
|
+
"gemini-2.0-flash": { input: 0.075, output: 0.3 },
|
|
390
|
+
"gemini-1.5-flash": { input: 0.075, output: 0.3 },
|
|
391
|
+
"gemini-1.5-pro": { input: 1.25, output: 5 }
|
|
392
|
+
},
|
|
393
|
+
groq: {
|
|
394
|
+
"openai/gpt-oss-120b": { input: 0.5, output: 0.8 }
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
function setModelPricing(backend, model, inputCost, outputCost) {
|
|
398
|
+
if (!MODEL_PRICING[backend]) {
|
|
399
|
+
MODEL_PRICING[backend] = {};
|
|
400
|
+
}
|
|
401
|
+
MODEL_PRICING[backend][model] = { input: inputCost, output: outputCost };
|
|
402
|
+
}
|
|
403
|
+
function loadPricingFromEnv() {
|
|
404
|
+
const env2 = typeof process !== "undefined" ? process.env : {};
|
|
405
|
+
const pricingJson = env2.ELIZA_RLM_PRICING_JSON;
|
|
406
|
+
if (!pricingJson) return;
|
|
407
|
+
try {
|
|
408
|
+
const customPricing = JSON.parse(pricingJson);
|
|
409
|
+
for (const [backend, models] of Object.entries(customPricing)) {
|
|
410
|
+
for (const [model, prices] of Object.entries(models)) {
|
|
411
|
+
setModelPricing(backend, model, prices.input ?? 1, prices.output ?? 3);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
} catch (e) {
|
|
415
|
+
console.warn(`[RLM] Failed to parse ELIZA_RLM_PRICING_JSON: ${e}`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
loadPricingFromEnv();
|
|
419
|
+
function estimateTokenCount(text) {
|
|
420
|
+
return Math.ceil(text.length / 4);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// index.ts
|
|
424
|
+
var env = typeof process !== "undefined" ? process.env : {};
|
|
425
|
+
function resolveBackend(value) {
|
|
426
|
+
return VALID_BACKENDS.includes(value) ? value : DEFAULT_CONFIG.backend;
|
|
427
|
+
}
|
|
428
|
+
function resolveEnvironment(value) {
|
|
429
|
+
return VALID_ENVIRONMENTS.includes(value) ? value : DEFAULT_CONFIG.environment;
|
|
430
|
+
}
|
|
431
|
+
function getRuntimeConfig(runtime) {
|
|
432
|
+
return runtime.rlmConfig;
|
|
433
|
+
}
|
|
434
|
+
function setRuntimeConfig(runtime, config) {
|
|
435
|
+
runtime.rlmConfig = config;
|
|
436
|
+
}
|
|
437
|
+
var clientState = {
|
|
438
|
+
client: null,
|
|
439
|
+
initPromise: null,
|
|
440
|
+
configHash: null
|
|
441
|
+
};
|
|
442
|
+
function computeConfigHash(config) {
|
|
443
|
+
const key = [
|
|
444
|
+
config.backend ?? "",
|
|
445
|
+
config.environment ?? "",
|
|
446
|
+
String(config.maxIterations ?? ""),
|
|
447
|
+
String(config.maxDepth ?? ""),
|
|
448
|
+
config.pythonPath ?? ""
|
|
449
|
+
].join("|");
|
|
450
|
+
return key;
|
|
451
|
+
}
|
|
452
|
+
function getOrCreateClient(runtime) {
|
|
453
|
+
const runtimeConfig = getRuntimeConfig(runtime);
|
|
454
|
+
const configHash = computeConfigHash(runtimeConfig ?? {});
|
|
455
|
+
if (clientState.client && clientState.configHash !== configHash) {
|
|
456
|
+
logger.info("[RLM] Config changed, recreating client");
|
|
457
|
+
clientState.client.shutdown().catch((err) => {
|
|
458
|
+
logger.warn("[RLM] Error shutting down old client:", err);
|
|
459
|
+
});
|
|
460
|
+
clientState.client = null;
|
|
461
|
+
clientState.initPromise = null;
|
|
462
|
+
}
|
|
463
|
+
if (clientState.client) {
|
|
464
|
+
return clientState.client;
|
|
465
|
+
}
|
|
466
|
+
const client = new RLMClient(runtimeConfig);
|
|
467
|
+
clientState.client = client;
|
|
468
|
+
clientState.configHash = configHash;
|
|
469
|
+
return client;
|
|
470
|
+
}
|
|
471
|
+
async function resetClient() {
|
|
472
|
+
if (clientState.client) {
|
|
473
|
+
await clientState.client.shutdown();
|
|
474
|
+
}
|
|
475
|
+
clientState.client = null;
|
|
476
|
+
clientState.initPromise = null;
|
|
477
|
+
clientState.configHash = null;
|
|
478
|
+
}
|
|
479
|
+
async function handleTextGeneration(runtime, params) {
|
|
480
|
+
const client = getOrCreateClient(runtime);
|
|
481
|
+
const input = params.prompt ?? "";
|
|
482
|
+
const opts = {
|
|
483
|
+
maxTokens: params.maxTokens,
|
|
484
|
+
temperature: params.temperature,
|
|
485
|
+
topP: params.topP,
|
|
486
|
+
stopSequences: params.stopSequences,
|
|
487
|
+
user: params.user
|
|
488
|
+
};
|
|
489
|
+
const cleanOpts = Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== void 0));
|
|
490
|
+
const runtimeConfig = getRuntimeConfig(runtime);
|
|
491
|
+
const backend = runtimeConfig?.backend ?? DEFAULT_CONFIG.backend;
|
|
492
|
+
const model = `${backend}:rlm`;
|
|
493
|
+
const details = {
|
|
494
|
+
model,
|
|
495
|
+
systemPrompt: resolveEffectiveSystemPrompt({
|
|
496
|
+
params,
|
|
497
|
+
fallback: buildCanonicalSystemPrompt({ character: runtime.character })
|
|
498
|
+
}) ?? "",
|
|
499
|
+
userPrompt: input,
|
|
500
|
+
temperature: params.temperature ?? 0,
|
|
501
|
+
maxTokens: params.maxTokens ?? 0,
|
|
502
|
+
purpose: "external_llm",
|
|
503
|
+
actionType: "rlm.client.infer",
|
|
504
|
+
promptTokens: estimateTokenCount(input)
|
|
505
|
+
};
|
|
506
|
+
const result = await recordLlmCall(runtime, details, async () => {
|
|
507
|
+
const response = await client.infer(input, cleanOpts);
|
|
508
|
+
details.response = response.text;
|
|
509
|
+
details.completionTokens = estimateTokenCount(response.text);
|
|
510
|
+
return response;
|
|
511
|
+
});
|
|
512
|
+
return result.text;
|
|
513
|
+
}
|
|
514
|
+
var rlmPlugin = {
|
|
515
|
+
name: "rlm",
|
|
516
|
+
description: "RLM (Recursive Language Model) adapter for elizaOS - enables processing of arbitrarily long contexts through recursive self-calls",
|
|
517
|
+
config: {
|
|
518
|
+
[ENV_VARS.BACKEND]: env[ENV_VARS.BACKEND] ?? DEFAULT_CONFIG.backend,
|
|
519
|
+
[ENV_VARS.ENVIRONMENT]: env[ENV_VARS.ENVIRONMENT] ?? DEFAULT_CONFIG.environment,
|
|
520
|
+
[ENV_VARS.MAX_ITERATIONS]: env[ENV_VARS.MAX_ITERATIONS] ?? String(DEFAULT_CONFIG.maxIterations),
|
|
521
|
+
[ENV_VARS.MAX_DEPTH]: env[ENV_VARS.MAX_DEPTH] ?? String(DEFAULT_CONFIG.maxDepth),
|
|
522
|
+
[ENV_VARS.VERBOSE]: env[ENV_VARS.VERBOSE] ?? "false",
|
|
523
|
+
[ENV_VARS.PYTHON_PATH]: env[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath
|
|
524
|
+
},
|
|
525
|
+
async init(config, runtime) {
|
|
526
|
+
logger.info("[RLM] Initializing RLM plugin");
|
|
527
|
+
setRuntimeConfig(runtime, {
|
|
528
|
+
backend: resolveBackend(config[ENV_VARS.BACKEND]),
|
|
529
|
+
environment: resolveEnvironment(config[ENV_VARS.ENVIRONMENT]),
|
|
530
|
+
maxIterations: Number.parseInt(config[ENV_VARS.MAX_ITERATIONS] ?? "", 10) || DEFAULT_CONFIG.maxIterations,
|
|
531
|
+
maxDepth: Number.parseInt(config[ENV_VARS.MAX_DEPTH] ?? "", 10) || DEFAULT_CONFIG.maxDepth,
|
|
532
|
+
verbose: ["1", "true", "yes"].includes((config[ENV_VARS.VERBOSE] ?? "").toLowerCase()),
|
|
533
|
+
pythonPath: config[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath
|
|
534
|
+
});
|
|
535
|
+
const client = getOrCreateClient(runtime);
|
|
536
|
+
const status = await client.getStatus();
|
|
537
|
+
if (status.available) {
|
|
538
|
+
logger.info(`[RLM] Backend available: ${status.backend}`);
|
|
539
|
+
} else {
|
|
540
|
+
logger.warn("[RLM] Backend not available; RLM model calls will fail until configured");
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
models: {
|
|
544
|
+
[ModelType.TEXT_SMALL]: handleTextGeneration,
|
|
545
|
+
[ModelType.TEXT_LARGE]: handleTextGeneration,
|
|
546
|
+
[ModelType.TEXT_REASONING_SMALL]: handleTextGeneration,
|
|
547
|
+
[ModelType.TEXT_REASONING_LARGE]: handleTextGeneration,
|
|
548
|
+
[ModelType.TEXT_COMPLETION]: handleTextGeneration
|
|
549
|
+
},
|
|
550
|
+
tests: [
|
|
551
|
+
{
|
|
552
|
+
name: "rlm_plugin_tests",
|
|
553
|
+
tests: [
|
|
554
|
+
{
|
|
555
|
+
name: "rlm_test_backend_status",
|
|
556
|
+
fn: async (runtime) => {
|
|
557
|
+
const client = getOrCreateClient(runtime);
|
|
558
|
+
const status = await client.getStatus();
|
|
559
|
+
if (typeof status.available !== "boolean") {
|
|
560
|
+
throw new Error("RLM status should report backend availability");
|
|
561
|
+
}
|
|
562
|
+
logger.info(`[RLM Test] Backend available: ${status.available}`);
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
{
|
|
566
|
+
name: "rlm_test_text_generation",
|
|
567
|
+
fn: async (runtime) => {
|
|
568
|
+
const status = await getOrCreateClient(runtime).getStatus();
|
|
569
|
+
if (!status.available) {
|
|
570
|
+
logger.warn("[RLM Test] Skipping text generation; backend unavailable");
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const text = await runtime.useModel(ModelType.TEXT_LARGE, {
|
|
574
|
+
prompt: "Say 'hello' in exactly one word."
|
|
575
|
+
});
|
|
576
|
+
if (typeof text !== "string") {
|
|
577
|
+
throw new Error("TEXT_LARGE should return string");
|
|
578
|
+
}
|
|
579
|
+
logger.info(`[RLM Test] TEXT_LARGE generated: "${text.substring(0, 50)}..."`);
|
|
580
|
+
}
|
|
581
|
+
},
|
|
582
|
+
{
|
|
583
|
+
name: "rlm_test_message_format",
|
|
584
|
+
fn: async (runtime) => {
|
|
585
|
+
const status = await getOrCreateClient(runtime).getStatus();
|
|
586
|
+
if (!status.available) {
|
|
587
|
+
logger.warn("[RLM Test] Skipping message format generation; backend unavailable");
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
const text = await runtime.useModel(ModelType.TEXT_LARGE, {
|
|
591
|
+
prompt: "What is 2 + 2?"
|
|
592
|
+
});
|
|
593
|
+
if (typeof text !== "string") {
|
|
594
|
+
throw new Error("TEXT_LARGE with prompt should return string");
|
|
595
|
+
}
|
|
596
|
+
logger.info("[RLM Test] Message format test passed");
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
]
|
|
600
|
+
}
|
|
601
|
+
]
|
|
602
|
+
};
|
|
603
|
+
var index_default = rlmPlugin;
|
|
604
|
+
export {
|
|
605
|
+
DEFAULT_CONFIG,
|
|
606
|
+
ENV_VARS,
|
|
607
|
+
RLMClient,
|
|
608
|
+
configFromEnv,
|
|
609
|
+
index_default as default,
|
|
610
|
+
resetClient,
|
|
611
|
+
rlmPlugin
|
|
612
|
+
};
|
|
613
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../index.ts","../client.ts","../types.ts","../cost.ts"],"sourcesContent":["/**\n * RLM (Recursive Language Model) plugin for elizaOS.\n *\n * This plugin integrates Recursive Language Models into elizaOS, enabling\n * LLMs to process arbitrarily long contexts through recursive self-calls\n * in a REPL environment.\n *\n * Reference:\n * - Paper: https://arxiv.org/abs/2512.24601\n * - Implementation: https://github.com/alexzhang13/rlm\n */\n\nimport type {\n GenerateTextParams,\n IAgentRuntime,\n Plugin,\n RecordLlmCallDetails,\n} from \"@elizaos/core\";\nimport {\n buildCanonicalSystemPrompt,\n logger,\n ModelType,\n recordLlmCall,\n resolveEffectiveSystemPrompt,\n} from \"@elizaos/core\";\n\nimport { RLMClient } from \"./client\";\nimport { estimateTokenCount } from \"./cost\";\nimport type { RLMConfig } from \"./types\";\nimport { DEFAULT_CONFIG, ENV_VARS, VALID_BACKENDS, VALID_ENVIRONMENTS } from \"./types\";\n\n// Safe env access for browser/non-Node environments\nconst env: Record<string, string | undefined> = typeof process !== \"undefined\" ? process.env : {};\n\nfunction resolveBackend(value: string | undefined): RLMConfig[\"backend\"] {\n return VALID_BACKENDS.includes(value as RLMConfig[\"backend\"])\n ? (value as RLMConfig[\"backend\"])\n : DEFAULT_CONFIG.backend;\n}\n\nfunction resolveEnvironment(value: string | undefined): RLMConfig[\"environment\"] {\n return VALID_ENVIRONMENTS.includes(value as RLMConfig[\"environment\"])\n ? (value as RLMConfig[\"environment\"])\n : DEFAULT_CONFIG.environment;\n}\n\n// ============================================================================\n// Thread-safe Singleton Client Management\n// ============================================================================\n\n/**\n * Singleton state for thread-safe client initialization.\n *\n * In concurrent environments, multiple requests could try to initialize\n * the client simultaneously. We use a promise-based lock to ensure\n * only one initialization happens.\n */\ninterface ClientState {\n client: RLMClient | null;\n initPromise: Promise<RLMClient> | null;\n configHash: string | null;\n}\n\ntype RuntimeWithRLMConfig = IAgentRuntime & {\n rlmConfig?: Partial<RLMConfig>;\n};\n\nfunction getRuntimeConfig(runtime: IAgentRuntime): Partial<RLMConfig> | undefined {\n return (runtime as RuntimeWithRLMConfig).rlmConfig;\n}\n\nfunction setRuntimeConfig(runtime: IAgentRuntime, config: Partial<RLMConfig>): void {\n (runtime as RuntimeWithRLMConfig).rlmConfig = config;\n}\n\nconst clientState: ClientState = {\n client: null,\n initPromise: null,\n configHash: null,\n};\n\n/**\n * Compute a simple hash of config for detecting changes.\n */\nfunction computeConfigHash(config: Partial<RLMConfig>): string {\n const key = [\n config.backend ?? \"\",\n config.environment ?? \"\",\n String(config.maxIterations ?? \"\"),\n String(config.maxDepth ?? \"\"),\n config.pythonPath ?? \"\",\n ].join(\"|\");\n return key;\n}\n\n/**\n * Get or create the shared RLM client instance (thread-safe).\n *\n * This implementation ensures:\n * 1. Only one client is created even under concurrent initialization\n * 2. Config changes are detected and client is recreated\n * 3. Initialization errors are properly handled\n */\nfunction getOrCreateClient(runtime: IAgentRuntime): RLMClient {\n // Get config from runtime or environment\n const runtimeConfig = getRuntimeConfig(runtime);\n const configHash = computeConfigHash(runtimeConfig ?? {});\n\n // Check if config changed - need to recreate client\n if (clientState.client && clientState.configHash !== configHash) {\n logger.info(\"[RLM] Config changed, recreating client\");\n // Shutdown old client (fire and forget)\n clientState.client.shutdown().catch((err) => {\n logger.warn(\"[RLM] Error shutting down old client:\", err);\n });\n clientState.client = null;\n clientState.initPromise = null;\n }\n\n // Fast path: client already exists with same config\n if (clientState.client) {\n return clientState.client;\n }\n\n // Slow path: need to create client\n // Create synchronously to avoid Promise in synchronous getter\n const client = new RLMClient(runtimeConfig);\n clientState.client = client;\n clientState.configHash = configHash;\n\n return client;\n}\n\n/**\n * Reset the client singleton. Useful for testing or forced reinitialization.\n */\nexport async function resetClient(): Promise<void> {\n if (clientState.client) {\n await clientState.client.shutdown();\n }\n clientState.client = null;\n clientState.initPromise = null;\n clientState.configHash = null;\n}\n\n/**\n * Handle text generation using RLM.\n */\nasync function handleTextGeneration(\n runtime: IAgentRuntime,\n params: GenerateTextParams,\n): Promise<string> {\n const client = getOrCreateClient(runtime);\n\n // Use prompt from params\n const input = params.prompt ?? \"\";\n\n const opts = {\n maxTokens: params.maxTokens,\n temperature: params.temperature,\n topP: params.topP,\n stopSequences: params.stopSequences,\n user: params.user,\n };\n\n // Remove undefined values\n const cleanOpts = Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined));\n\n const runtimeConfig = getRuntimeConfig(runtime);\n const backend = runtimeConfig?.backend ?? DEFAULT_CONFIG.backend;\n const model = `${backend}:rlm`;\n const details: RecordLlmCallDetails = {\n model,\n systemPrompt:\n resolveEffectiveSystemPrompt({\n params,\n fallback: buildCanonicalSystemPrompt({ character: runtime.character }),\n }) ?? \"\",\n userPrompt: input,\n temperature: params.temperature ?? 0,\n maxTokens: params.maxTokens ?? 0,\n purpose: \"external_llm\",\n actionType: \"rlm.client.infer\",\n promptTokens: estimateTokenCount(input),\n };\n\n const result = await recordLlmCall(runtime, details, async () => {\n const response = await client.infer(input, cleanOpts);\n details.response = response.text;\n details.completionTokens = estimateTokenCount(response.text);\n return response;\n });\n return result.text;\n}\n\n/**\n * RLM plugin definition.\n */\nexport const rlmPlugin: Plugin = {\n name: \"rlm\",\n description:\n \"RLM (Recursive Language Model) adapter for elizaOS - enables processing of arbitrarily long contexts through recursive self-calls\",\n\n config: {\n [ENV_VARS.BACKEND]: env[ENV_VARS.BACKEND] ?? DEFAULT_CONFIG.backend,\n [ENV_VARS.ENVIRONMENT]: env[ENV_VARS.ENVIRONMENT] ?? DEFAULT_CONFIG.environment,\n [ENV_VARS.MAX_ITERATIONS]: env[ENV_VARS.MAX_ITERATIONS] ?? String(DEFAULT_CONFIG.maxIterations),\n [ENV_VARS.MAX_DEPTH]: env[ENV_VARS.MAX_DEPTH] ?? String(DEFAULT_CONFIG.maxDepth),\n [ENV_VARS.VERBOSE]: env[ENV_VARS.VERBOSE] ?? \"false\",\n [ENV_VARS.PYTHON_PATH]: env[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath,\n },\n\n async init(config: Record<string, string>, runtime: IAgentRuntime): Promise<void> {\n logger.info(\"[RLM] Initializing RLM plugin\");\n\n // Store config on runtime\n setRuntimeConfig(runtime, {\n backend: resolveBackend(config[ENV_VARS.BACKEND]),\n environment: resolveEnvironment(config[ENV_VARS.ENVIRONMENT]),\n maxIterations:\n Number.parseInt(config[ENV_VARS.MAX_ITERATIONS] ?? \"\", 10) || DEFAULT_CONFIG.maxIterations,\n maxDepth: Number.parseInt(config[ENV_VARS.MAX_DEPTH] ?? \"\", 10) || DEFAULT_CONFIG.maxDepth,\n verbose: [\"1\", \"true\", \"yes\"].includes((config[ENV_VARS.VERBOSE] ?? \"\").toLowerCase()),\n pythonPath: config[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath,\n });\n\n // Pre-initialize client\n const client = getOrCreateClient(runtime);\n const status = await client.getStatus();\n\n if (status.available) {\n logger.info(`[RLM] Backend available: ${status.backend}`);\n } else {\n logger.warn(\"[RLM] Backend not available; RLM model calls will fail until configured\");\n }\n },\n\n models: {\n [ModelType.TEXT_SMALL]: handleTextGeneration,\n [ModelType.TEXT_LARGE]: handleTextGeneration,\n [ModelType.TEXT_REASONING_SMALL]: handleTextGeneration,\n [ModelType.TEXT_REASONING_LARGE]: handleTextGeneration,\n [ModelType.TEXT_COMPLETION]: handleTextGeneration,\n },\n\n tests: [\n {\n name: \"rlm_plugin_tests\",\n tests: [\n {\n name: \"rlm_test_backend_status\",\n fn: async (runtime: IAgentRuntime): Promise<void> => {\n const client = getOrCreateClient(runtime);\n const status = await client.getStatus();\n if (typeof status.available !== \"boolean\") {\n throw new Error(\"RLM status should report backend availability\");\n }\n logger.info(`[RLM Test] Backend available: ${status.available}`);\n },\n },\n {\n name: \"rlm_test_text_generation\",\n fn: async (runtime: IAgentRuntime): Promise<void> => {\n const status = await getOrCreateClient(runtime).getStatus();\n if (!status.available) {\n logger.warn(\"[RLM Test] Skipping text generation; backend unavailable\");\n return;\n }\n\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: \"Say 'hello' in exactly one word.\",\n });\n\n if (typeof text !== \"string\") {\n throw new Error(\"TEXT_LARGE should return string\");\n }\n\n logger.info(`[RLM Test] TEXT_LARGE generated: \"${text.substring(0, 50)}...\"`);\n },\n },\n {\n name: \"rlm_test_message_format\",\n fn: async (runtime: IAgentRuntime): Promise<void> => {\n const status = await getOrCreateClient(runtime).getStatus();\n if (!status.available) {\n logger.warn(\"[RLM Test] Skipping message format generation; backend unavailable\");\n return;\n }\n\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: \"What is 2 + 2?\",\n });\n\n if (typeof text !== \"string\") {\n throw new Error(\"TEXT_LARGE with prompt should return string\");\n }\n\n logger.info(\"[RLM Test] Message format test passed\");\n },\n },\n ],\n },\n ],\n};\n\nexport default rlmPlugin;\n\n// Re-export types and client\nexport { configFromEnv, RLMClient } from \"./client\";\nexport type {\n GenerateTextParams,\n RLMConfig,\n RLMInferOptions,\n RLMMessage,\n RLMMetadata,\n RLMResult,\n RLMStatusResponse,\n} from \"./types\";\nexport { DEFAULT_CONFIG, ENV_VARS } from \"./types\";\n","/** RLM Client - communicates with Python subprocess via JSON-RPC IPC. */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport * as path from \"node:path\";\nimport * as readline from \"node:readline\";\n\nimport { assertRecordedLlmCall } from \"@elizaos/core\";\nimport type {\n IPCReadyMessage,\n IPCRequest,\n IPCResponse,\n MetricsCallback,\n RLMConfig,\n RLMInferOptions,\n RLMMessage,\n RLMMetrics,\n RLMResult,\n RLMStatusResponse,\n} from \"./types\";\nimport { DEFAULT_CONFIG, ENV_VARS, validateConfig } from \"./types\";\n\nexport type { MetricsCallback, RLMMetrics };\nexport { DEFAULT_CONFIG };\n\ninterface Logger {\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n}\n\nconst defaultLogger: Logger = {\n info: (msg, ...args) => console.log(`[RLM] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[RLM] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[RLM] ${msg}`, ...args),\n debug: (msg, ...args) => console.debug(`[RLM] ${msg}`, ...args),\n};\n\nexport function configFromEnv(env: NodeJS.ProcessEnv = process.env): RLMConfig {\n return {\n backend: (env[ENV_VARS.BACKEND] as RLMConfig[\"backend\"]) ?? DEFAULT_CONFIG.backend,\n backendKwargs: {},\n environment:\n (env[ENV_VARS.ENVIRONMENT] as RLMConfig[\"environment\"]) ?? DEFAULT_CONFIG.environment,\n maxIterations:\n Number.parseInt(env[ENV_VARS.MAX_ITERATIONS] ?? \"\", 10) || DEFAULT_CONFIG.maxIterations,\n maxDepth: Number.parseInt(env[ENV_VARS.MAX_DEPTH] ?? \"\", 10) || DEFAULT_CONFIG.maxDepth,\n verbose: [\"1\", \"true\", \"yes\"].includes((env[ENV_VARS.VERBOSE] ?? \"\").toLowerCase()),\n pythonPath: env[ENV_VARS.PYTHON_PATH] ?? DEFAULT_CONFIG.pythonPath,\n maxRetries: Number.parseInt(env[ENV_VARS.MAX_RETRIES] ?? \"\", 10) || DEFAULT_CONFIG.maxRetries,\n retryBaseDelay:\n Number.parseInt(env[ENV_VARS.RETRY_BASE_DELAY] ?? \"\", 10) || DEFAULT_CONFIG.retryBaseDelay,\n retryMaxDelay:\n Number.parseInt(env[ENV_VARS.RETRY_MAX_DELAY] ?? \"\", 10) || DEFAULT_CONFIG.retryMaxDelay,\n };\n}\n\nexport class RLMClient {\n private config: RLMConfig;\n private process: ChildProcess | null = null;\n private reader: readline.Interface | null = null;\n private requestId = 0;\n private pendingRequests = new Map<\n number,\n { resolve: (value: IPCResponse) => void; reject: (error: Error) => void }\n >();\n private isReady = false;\n private isAvailable = false;\n private hasStartupError = false;\n private logger: Logger;\n private metrics: RLMMetrics = {\n totalRequests: 0,\n successfulRequests: 0,\n failedRequests: 0,\n totalRetries: 0,\n averageLatencyMs: 0,\n p95LatencyMs: 0,\n lastRequestTimestamp: 0,\n };\n private static readonly MAX_LATENCY_SAMPLES = 1000;\n private latencies: number[] = new Array(RLMClient.MAX_LATENCY_SAMPLES).fill(0);\n private latencyIndex = 0;\n private latencyCount = 0;\n private metricsCallback: MetricsCallback | null = null;\n\n constructor(config?: Partial<RLMConfig>, logger?: Logger, strictValidation = false) {\n this.config = { ...configFromEnv(), ...config };\n this.logger = logger ?? defaultLogger;\n\n const errors = validateConfig(this.config);\n if (errors.length > 0) {\n if (strictValidation) {\n throw new Error(`RLM configuration invalid: ${errors.join(\"; \")}`);\n }\n for (const error of errors) {\n this.logger.warn(`Configuration warning: ${error}`);\n }\n }\n }\n\n private async startServer(): Promise<void> {\n if (this.process) return;\n this.hasStartupError = false;\n\n this.logger.debug(\n `Starting RLM server: ${this.config.pythonPath} -m elizaos_plugin_rlm.server`,\n );\n\n try {\n this.process = spawn(this.config.pythonPath, [\"-m\", \"elizaos_plugin_rlm.server\"], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n [ENV_VARS.BACKEND]: this.config.backend,\n [ENV_VARS.ENVIRONMENT]: this.config.environment,\n [ENV_VARS.MAX_ITERATIONS]: String(this.config.maxIterations),\n [ENV_VARS.MAX_DEPTH]: String(this.config.maxDepth),\n [ENV_VARS.VERBOSE]: this.config.verbose ? \"true\" : \"false\",\n },\n cwd: path.join(__dirname, \"..\", \"python\"),\n });\n } catch (error) {\n this.logger.warn(`Failed to start RLM server: ${error}`);\n this.isAvailable = false;\n return;\n }\n\n if (!this.process.stdout || !this.process.stdin) {\n this.logger.warn(\"RLM server process missing stdio streams\");\n this.isAvailable = false;\n return;\n }\n\n // Set up line reader for responses\n this.reader = readline.createInterface({\n input: this.process.stdout,\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n\n // Handle incoming messages\n this.reader.on(\"line\", (line: string) => {\n this.handleMessage(line);\n });\n\n // Handle errors\n this.process.stderr?.on(\"data\", (data: Buffer) => {\n this.logger.debug(`RLM server stderr: ${data.toString()}`);\n });\n\n this.process.on(\"error\", (error: Error) => {\n this.logger.error(`RLM server error: ${error.message}`);\n this.isAvailable = false;\n this.hasStartupError = true;\n });\n\n this.process.on(\"exit\", (code: number | null) => {\n this.logger.debug(`RLM server exited with code ${code}`);\n this.isReady = false;\n this.isAvailable = false;\n this.process = null;\n });\n\n await this.waitForReady();\n }\n\n private waitForReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n const TIMEOUT_MS = 10000;\n const POLL_INTERVAL_MS = 100;\n const deadline = Date.now() + TIMEOUT_MS;\n\n const checkReady = () => {\n if (this.isReady) {\n resolve();\n } else if (!this.process || this.hasStartupError) {\n reject(new Error(\"RLM server process failed before ready\"));\n } else if (Date.now() > deadline) {\n reject(new Error(\"RLM server startup timeout\"));\n } else {\n setTimeout(checkReady, POLL_INTERVAL_MS);\n }\n };\n checkReady();\n });\n }\n\n private handleMessage(line: string): void {\n try {\n const message = JSON.parse(line) as IPCResponse | IPCReadyMessage;\n\n // Check for ready message\n if (\"ready\" in message) {\n const readyMsg = message as IPCReadyMessage;\n this.isReady = true;\n this.isAvailable = readyMsg.available;\n this.logger.info(`RLM server ready, available: ${this.isAvailable}`);\n return;\n }\n\n // Handle response\n const response = message as IPCResponse;\n const pending = this.pendingRequests.get(response.id);\n if (pending) {\n this.pendingRequests.delete(response.id);\n pending.resolve(response);\n }\n } catch (_error) {\n this.logger.error(`Failed to parse RLM server message: ${line}`);\n }\n }\n\n private async sendRequest<T>(\n method: IPCRequest[\"method\"],\n params: Record<string, unknown> = {},\n ): Promise<T> {\n await this.ensureServer();\n\n if (!this.process?.stdin) {\n throw new Error(\"RLM server not running\");\n }\n\n const id = ++this.requestId;\n const request: IPCRequest = { id, method, params };\n\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`RLM request timeout: ${method}`));\n }, 60000);\n\n this.pendingRequests.set(id, {\n resolve: (response: IPCResponse) => {\n clearTimeout(timeout);\n if (response.error) {\n reject(new Error(response.error));\n } else {\n resolve(response.result as T);\n }\n },\n reject: (error: Error) => {\n clearTimeout(timeout);\n reject(error);\n },\n });\n\n this.process?.stdin?.write(`${JSON.stringify(request)}\\n`);\n });\n }\n\n private async ensureServer(): Promise<void> {\n if (!this.process || !this.isReady) {\n await this.startServer();\n }\n }\n\n get available(): boolean {\n return this.isAvailable;\n }\n\n getMetrics(): RLMMetrics {\n return { ...this.metrics };\n }\n\n onMetrics(callback: MetricsCallback): void {\n this.metricsCallback = callback;\n }\n\n private updateMetrics(latencyMs: number, success: boolean, error?: string): void {\n this.metrics.totalRequests++;\n this.metrics.lastRequestTimestamp = Date.now();\n\n if (success) {\n this.metrics.successfulRequests++;\n } else {\n this.metrics.failedRequests++;\n this.metrics.lastErrorTimestamp = Date.now();\n this.metrics.lastError = error;\n }\n\n // Track latency in circular buffer\n this.latencies[this.latencyIndex] = latencyMs;\n this.latencyIndex = (this.latencyIndex + 1) % RLMClient.MAX_LATENCY_SAMPLES;\n this.latencyCount = Math.min(this.latencyCount + 1, RLMClient.MAX_LATENCY_SAMPLES);\n\n // Calculate stats from valid samples\n if (this.latencyCount > 0) {\n const valid = this.latencies.slice(0, this.latencyCount);\n this.metrics.averageLatencyMs = valid.reduce((a, b) => a + b, 0) / this.latencyCount;\n this.metrics.p95LatencyMs =\n [...valid].sort((a, b) => a - b)[Math.floor(valid.length * 0.95)] ?? 0;\n }\n\n this.metricsCallback?.(this.getMetrics());\n }\n\n static normalizeMessages(messages: string | RLMMessage[]): RLMMessage[] {\n return typeof messages === \"string\" ? [{ role: \"user\", content: messages }] : messages;\n }\n\n async infer(messages: string | RLMMessage[], opts?: RLMInferOptions): Promise<RLMResult> {\n assertRecordedLlmCall({\n actionType: \"rlm.client.infer\",\n model: opts?.rootModel,\n purpose: \"external_llm\",\n });\n\n const startTime = Date.now();\n const { maxRetries = 3, retryBaseDelay = 1000, retryMaxDelay = 30000 } = this.config;\n const RETRYABLE_PATTERNS = [\"timeout\", \"rate limit\", \"connection\", \"503\", \"429\", \"econnreset\"];\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n await this.ensureServer();\n\n if (!this.isReady) {\n throw new Error(\"RLM backend is not available\");\n }\n\n const result = await this.sendRequest<RLMResult>(\"infer\", {\n messages: RLMClient.normalizeMessages(messages),\n opts: opts ?? {},\n });\n\n this.updateMetrics(Date.now() - startTime, true);\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n const isRetryable = RETRYABLE_PATTERNS.some((p) =>\n lastError?.message.toLowerCase().includes(p),\n );\n\n if (!isRetryable || attempt === maxRetries - 1) {\n this.logger.error(`RLM inference failed after ${attempt + 1} attempts: ${error}`);\n this.updateMetrics(Date.now() - startTime, false, lastError.message);\n throw lastError;\n }\n\n const delay =\n Math.min(retryBaseDelay * 2 ** attempt, retryMaxDelay) * (0.75 + Math.random() * 0.5);\n this.metrics.totalRetries++;\n this.logger.warn(\n `RLM attempt ${attempt + 1}/${maxRetries} failed. Retrying in ${Math.round(delay)}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n this.updateMetrics(Date.now() - startTime, false, lastError?.message);\n throw lastError ?? new Error(\"RLM inference failed\");\n }\n\n async getStatus(): Promise<RLMStatusResponse> {\n try {\n await this.ensureServer();\n return await this.sendRequest<RLMStatusResponse>(\"status\");\n } catch {\n return {\n available: false,\n backend: this.config.backend,\n environment: this.config.environment,\n maxIterations: this.config.maxIterations,\n maxDepth: this.config.maxDepth,\n };\n }\n }\n\n async shutdown(): Promise<void> {\n if (!this.process) return;\n try {\n await this.sendRequest(\"shutdown\");\n } catch {\n /* ignore */\n }\n this.reader?.close();\n this.process?.kill();\n this.process = null;\n this.isReady = false;\n this.isAvailable = false;\n }\n}\n","/** Types for the RLM (Recursive Language Model) plugin. */\n\nexport type RLMBackend = \"openai\" | \"anthropic\" | \"gemini\" | \"groq\" | \"openrouter\";\nexport type RLMEnvironment = \"local\" | \"docker\" | \"modal\" | \"prime\";\n\nexport interface RLMConfig {\n backend: RLMBackend;\n backendKwargs: Record<string, string>;\n environment: RLMEnvironment;\n maxIterations: number;\n maxDepth: number;\n verbose: boolean;\n pythonPath: string;\n maxRetries?: number;\n retryBaseDelay?: number;\n retryMaxDelay?: number;\n}\n\nexport interface RLMMessage {\n role: \"user\" | \"assistant\" | \"system\";\n content: string;\n}\n\nexport interface RLMMetadata {\n synthetic: boolean;\n iterations?: number;\n depth?: number;\n error?: string;\n}\n\nexport interface RLMResult {\n text: string;\n metadata: RLMMetadata;\n}\n\nexport interface RLMInferOptions {\n /** Model identifier for this request */\n model?: string;\n /** Maximum tokens to generate */\n maxTokens?: number;\n /** Sampling temperature */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Stop sequences */\n stopSequences?: string[];\n /** User identifier for tracking */\n user?: string;\n /** Request streaming; RLM currently returns complete text responses only. */\n stream?: boolean;\n\n // Per-request RLM overrides (Paper Algorithm 1)\n /** Override max iterations for this request */\n maxIterations?: number;\n /** Override max recursion depth for this request */\n maxDepth?: number;\n /** Override root model for this request */\n rootModel?: string;\n /** Override subcall model for this request */\n subcallModel?: string;\n /** Enable trajectory logging for this request */\n logTrajectories?: boolean;\n /** Enable cost tracking for this request */\n trackCosts?: boolean;\n\n // NOTE: Custom REPL tool injection is NOT supported by the upstream RLM library.\n // See: https://arxiv.org/abs/2512.24601 Section 3.3 - the paper describes the concept\n // but the current library implementation does not expose this capability.\n}\n\nexport interface RLMStatusResponse {\n available: boolean;\n backend: string;\n environment: string;\n maxIterations: number;\n maxDepth: number;\n}\n\nexport interface IPCRequest {\n id: number;\n method: \"infer\" | \"status\" | \"shutdown\";\n params: Record<string, unknown>;\n}\n\nexport interface IPCResponse<T = unknown> {\n id: number;\n result?: T;\n error?: string;\n}\n\nexport interface IPCReadyMessage {\n ready: boolean;\n available: boolean;\n}\n\nexport interface GenerateTextParams {\n prompt?: string;\n system?: string;\n messages?: RLMMessage[];\n model?: string;\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n user?: string;\n stream?: boolean;\n}\n\nexport const DEFAULT_CONFIG: RLMConfig = {\n backend: \"gemini\",\n backendKwargs: {},\n environment: \"local\",\n maxIterations: 4,\n maxDepth: 1,\n verbose: false,\n pythonPath: \"python\",\n maxRetries: 3,\n retryBaseDelay: 1000,\n retryMaxDelay: 30000,\n};\n\nexport interface RLMMetrics {\n totalRequests: number;\n successfulRequests: number;\n failedRequests: number;\n totalRetries: number;\n averageLatencyMs: number;\n p95LatencyMs: number;\n lastRequestTimestamp: number;\n lastErrorTimestamp?: number;\n lastError?: string;\n}\n\nexport type MetricsCallback = (metrics: RLMMetrics) => void;\n\nexport const ENV_VARS = {\n BACKEND: \"ELIZA_RLM_BACKEND\",\n ENVIRONMENT: \"ELIZA_RLM_ENV\",\n MAX_ITERATIONS: \"ELIZA_RLM_MAX_ITERATIONS\",\n MAX_DEPTH: \"ELIZA_RLM_MAX_DEPTH\",\n VERBOSE: \"ELIZA_RLM_VERBOSE\",\n PYTHON_PATH: \"ELIZA_RLM_PYTHON_PATH\",\n MAX_RETRIES: \"ELIZA_RLM_MAX_RETRIES\",\n RETRY_BASE_DELAY: \"ELIZA_RLM_RETRY_BASE_DELAY\",\n RETRY_MAX_DELAY: \"ELIZA_RLM_RETRY_MAX_DELAY\",\n} as const;\n\nexport const VALID_BACKENDS: readonly RLMBackend[] = [\n \"openai\",\n \"anthropic\",\n \"gemini\",\n \"groq\",\n \"openrouter\",\n];\nexport const VALID_ENVIRONMENTS: readonly RLMEnvironment[] = [\"local\", \"docker\", \"modal\", \"prime\"];\n\nexport class RLMConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RLMConfigError\";\n }\n}\n\n/** Validate config. Returns errors array, or throws if strict=true. */\nexport function validateConfig(config: Partial<RLMConfig>, strict = false): string[] {\n const errors: string[] = [];\n\n if (config.backend !== undefined && !VALID_BACKENDS.includes(config.backend)) {\n errors.push(`Invalid backend '${config.backend}'. Valid options: ${VALID_BACKENDS.join(\", \")}`);\n }\n\n if (config.environment !== undefined && !VALID_ENVIRONMENTS.includes(config.environment)) {\n errors.push(\n `Invalid environment '${config.environment}'. Valid options: ${VALID_ENVIRONMENTS.join(\", \")}`,\n );\n }\n\n if (config.maxIterations !== undefined && config.maxIterations < 1) {\n errors.push(\"maxIterations must be >= 1\");\n }\n\n if (config.maxDepth !== undefined && config.maxDepth < 1) {\n errors.push(\"maxDepth must be >= 1\");\n }\n\n if (config.maxRetries !== undefined && config.maxRetries < 0) {\n errors.push(\"maxRetries must be >= 0\");\n }\n\n if (config.retryBaseDelay !== undefined && config.retryBaseDelay < 0) {\n errors.push(\"retryBaseDelay must be >= 0\");\n }\n\n if (\n config.retryBaseDelay !== undefined &&\n config.retryMaxDelay !== undefined &&\n config.retryMaxDelay < config.retryBaseDelay\n ) {\n errors.push(\"retryMaxDelay must be >= retryBaseDelay\");\n }\n\n if (strict && errors.length > 0) {\n throw new RLMConfigError(errors.join(\"; \"));\n }\n\n return errors;\n}\n","/**\n * Cost estimation for RLM inference.\n *\n * Provides model pricing data and cost estimation utilities matching\n * the Python implementation (client.py).\n *\n * Pricing is per 1M tokens (USD). Override via ELIZA_RLM_PRICING_JSON env var.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Cost per 1M tokens for a model. */\nexport interface ModelPricingEntry {\n /** Cost per 1M input tokens (USD). */\n input: number;\n /** Cost per 1M output tokens (USD). */\n output: number;\n}\n\n/** Result of a cost estimation. */\nexport interface CostEstimate {\n /** Model name. */\n model: string;\n /** Backend name (openai, anthropic, gemini, groq). */\n backend: string;\n /** Number of input tokens. */\n inputTokens: number;\n /** Number of output tokens. */\n outputTokens: number;\n /** Cost for input tokens (USD). */\n inputCostUsd: number;\n /** Cost for output tokens (USD). */\n outputCostUsd: number;\n /** Total cost (USD). */\n totalCostUsd: number;\n}\n\ntype PricingTable = Record<string, Record<string, ModelPricingEntry>>;\n\n// ============================================================================\n// Pricing Data — matches Python MODEL_PRICING in client.py\n// ============================================================================\n\n/**\n * Default model pricing per 1M tokens (USD).\n *\n * Organized by backend → model → {input, output}.\n * Matches the Python MODEL_PRICING dictionary exactly.\n */\nexport const MODEL_PRICING: PricingTable = {\n openai: {\n \"gpt-5\": { input: 2.5, output: 10.0 },\n \"gpt-5-preview\": { input: 10.0, output: 30.0 },\n \"gpt-5-mini\": { input: 0.15, output: 0.6 },\n \"gpt-3.5-turbo\": { input: 0.5, output: 1.5 },\n },\n anthropic: {\n \"claude-3-5-sonnet-20241022\": { input: 3.0, output: 15.0 },\n \"claude-3-5-haiku-20241022\": { input: 0.8, output: 4.0 },\n \"claude-3-opus-20240229\": { input: 15.0, output: 75.0 },\n \"claude-3-sonnet-20240229\": { input: 3.0, output: 15.0 },\n \"claude-3-haiku-20240307\": { input: 0.25, output: 1.25 },\n },\n gemini: {\n \"gemini-2.0-flash-exp\": { input: 0.0, output: 0.0 },\n \"gemini-2.0-flash\": { input: 0.075, output: 0.3 },\n \"gemini-1.5-flash\": { input: 0.075, output: 0.3 },\n \"gemini-1.5-pro\": { input: 1.25, output: 5.0 },\n },\n groq: {\n \"openai/gpt-oss-120b\": { input: 0.5, output: 0.8 },\n },\n};\n\n/** Fallback pricing when model is not found in the table. */\nexport const DEFAULT_PRICING: ModelPricingEntry = { input: 1.0, output: 3.0 };\n\n// ============================================================================\n// Pricing Management\n// ============================================================================\n\n/**\n * Set or override pricing for a model (costs per 1M tokens USD).\n *\n * Matches Python `set_model_pricing()`.\n */\nexport function setModelPricing(\n backend: string,\n model: string,\n inputCost: number,\n outputCost: number,\n): void {\n if (!MODEL_PRICING[backend]) {\n MODEL_PRICING[backend] = {};\n }\n MODEL_PRICING[backend][model] = { input: inputCost, output: outputCost };\n}\n\n/**\n * Load custom pricing from ELIZA_RLM_PRICING_JSON environment variable.\n *\n * JSON format: `{ \"backend\": { \"model\": { \"input\": X, \"output\": Y } } }`\n *\n * Matches Python `load_pricing_from_env()`.\n */\nexport function loadPricingFromEnv(): void {\n const env: Record<string, string | undefined> = typeof process !== \"undefined\" ? process.env : {};\n const pricingJson = env.ELIZA_RLM_PRICING_JSON;\n if (!pricingJson) return;\n\n try {\n const customPricing = JSON.parse(pricingJson) as PricingTable;\n for (const [backend, models] of Object.entries(customPricing)) {\n for (const [model, prices] of Object.entries(models)) {\n setModelPricing(backend, model, prices.input ?? 1.0, prices.output ?? 3.0);\n }\n }\n } catch (e) {\n console.warn(`[RLM] Failed to parse ELIZA_RLM_PRICING_JSON: ${e}`);\n }\n}\n\n// Load custom pricing on module import\nloadPricingFromEnv();\n\n// ============================================================================\n// Cost Estimation Functions\n// ============================================================================\n\n/**\n * Estimate API cost in USD based on token counts.\n *\n * Looks up pricing for the given model. If `backend` is provided, searches\n * only that backend; otherwise searches all backends. Falls back to\n * DEFAULT_PRICING if the model is not found.\n *\n * Matches Python `estimate_cost()`.\n *\n * @param model - Model identifier (e.g. \"gpt-5\", \"claude-3-opus-20240229\")\n * @param inputTokens - Number of input tokens\n * @param outputTokens - Number of output tokens\n * @param backend - Optional backend to restrict search (e.g. \"openai\")\n * @returns CostEstimate with computed costs\n */\nexport function estimateCost(\n model: string,\n inputTokens: number,\n outputTokens: number,\n backend?: string,\n): CostEstimate {\n let pricing: ModelPricingEntry | undefined;\n let resolvedBackend = backend ?? \"\";\n\n if (backend) {\n pricing = MODEL_PRICING[backend]?.[model];\n } else {\n // Search all backends for the model\n for (const [b, models] of Object.entries(MODEL_PRICING)) {\n if (models[model]) {\n pricing = models[model];\n resolvedBackend = b;\n break;\n }\n }\n }\n\n if (!pricing) {\n pricing = DEFAULT_PRICING;\n }\n\n const inputCostUsd = (inputTokens / 1_000_000) * pricing.input;\n const outputCostUsd = (outputTokens / 1_000_000) * pricing.output;\n\n return {\n model,\n backend: resolvedBackend,\n inputTokens,\n outputTokens,\n inputCostUsd,\n outputCostUsd,\n totalCostUsd: inputCostUsd + outputCostUsd,\n };\n}\n\n/**\n * Estimate token count for a text string.\n *\n * Uses a len/4 approximation (~4 characters per token). This matches\n * the Python fallback when tiktoken is not available.\n *\n * Matches Python `estimate_token_count()`.\n *\n * @param text - Input text to estimate tokens for\n * @returns Estimated number of tokens\n */\nexport function estimateTokenCount(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Detect RLM strategy from generated code.\n *\n * Strategies (from Paper Section 4.1):\n * - **peek**: Examining prefix/suffix of the prompt (`[:=`, `[:-`, `prompt[`)\n * - **grep**: Regex filtering (`re.search`, `re.findall`, `grep`)\n * - **chunk**: Splitting for parallel processing (`split(`, `partition(`, `chunk`)\n * - **stitch**: Combining sub-call results (`join(`, `concat`, `+=`)\n * - **subcall**: Recursive self-call (`rlm(`, `completion(`, `subcall`)\n * - **other**: Unclassified strategy\n *\n * Matches Python `detect_strategy()`.\n *\n * @param code - Code string to classify\n * @returns Strategy name\n */\nexport function detectStrategy(code: string): string {\n const c = code.toLowerCase();\n\n if (code.includes(\"[:=\") || code.includes(\"[:-\") || c.includes(\"prompt[\")) {\n return \"peek\";\n }\n if ([\"re.search\", \"re.findall\", \"grep\"].some((p) => c.includes(p))) {\n return \"grep\";\n }\n if ([\"split(\", \"partition(\", \"chunk\"].some((p) => c.includes(p))) {\n return \"chunk\";\n }\n if (c.includes(\"join(\") || c.includes(\"concat\") || code.includes(\"+=\")) {\n return \"stitch\";\n }\n if ([\"rlm(\", \"completion(\", \"subcall\"].some((p) => c.includes(p))) {\n return \"subcall\";\n }\n return \"other\";\n}\n"],"mappings":";AAkBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACtBP,SAA4B,aAAa;AACzC,YAAY,UAAU;AACtB,YAAY,cAAc;AAE1B,SAAS,6BAA6B;;;ACsG/B,IAAM,iBAA4B;AAAA,EACvC,SAAS;AAAA,EACT,eAAe,CAAC;AAAA,EAChB,aAAa;AAAA,EACb,eAAe;AAAA,EACf,UAAU;AAAA,EACV,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,eAAe;AACjB;AAgBO,IAAM,WAAW;AAAA,EACtB,SAAS;AAAA,EACT,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,SAAS;AAAA,EACT,aAAa;AAAA,EACb,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,iBAAiB;AAC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;AACrB,qBAAO,KAAK,oEAAoE;AAChF;AAAA,YACF;AAEA,kBAAM,OAAO,MAAM,QAAQ,SAAS,UAAU,YAAY;AAAA,cACxD,QAAQ;AAAA,YACV,CAAC;AAED,gBAAI,OAAO,SAAS,UAAU;AAC5B,oBAAM,IAAI,MAAM,6CAA6C;AAAA,YAC/D;AAEA,mBAAO,KAAK,uCAAuC;AAAA,UACrD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["env","logger","env"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elizaos/plugin-rlm",
|
|
3
|
-
"version": "2.0.3-beta.
|
|
3
|
+
"version": "2.0.3-beta.7",
|
|
4
4
|
"description": "RLM (Recursive Language Model) plugin for elizaOS - enables processing of arbitrarily long contexts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"directory": "plugins/plugin-rlm"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@elizaos/core": "2.0.3-beta.
|
|
54
|
+
"@elizaos/core": "2.0.3-beta.7"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@biomejs/biome": "^2.4.14",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"vitest": "^4.0.0"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
|
-
"@elizaos/core": "2.0.3-beta.
|
|
64
|
+
"@elizaos/core": "2.0.3-beta.7"
|
|
65
65
|
},
|
|
66
66
|
"engines": {
|
|
67
67
|
"node": ">=24.0.0"
|
|
@@ -78,5 +78,5 @@
|
|
|
78
78
|
"publishConfig": {
|
|
79
79
|
"access": "public"
|
|
80
80
|
},
|
|
81
|
-
"gitHead": "
|
|
81
|
+
"gitHead": "61094f10458d11055c75b3dd0bae374e3f66bac5"
|
|
82
82
|
}
|