-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclient-cli.ts
More file actions
242 lines (226 loc) · 7.4 KB
/
client-cli.ts
File metadata and controls
242 lines (226 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* PowerMem CLI backend.
* Spawns `pmem` (or pmemPath) with -j and parses JSON stdout.
* Use when mode is "cli" (no HTTP server required).
*/
import { existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import type { PowerMemConfig } from "./config.js";
import type { PowerMemAddResult, PowerMemSearchResult } from "./client.js";
const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024; // 10 MiB
export type PowerMemCLIClientOptions = {
pmemPath: string;
/** Path passed to pmem only if the file exists on disk. */
resolvedEnvFile?: string;
userId: string;
agentId: string;
/**
* Vars merged into the subprocess environment (after process.env).
* OpenClaw + SQLite defaults; cached for the plugin process lifetime.
*/
buildProcessEnv?: () => Promise<Record<string, string>>;
};
function parseJsonOrThrow<T>(stdout: string, context: string): T {
const trimmed = stdout.trim();
if (!trimmed) {
throw new Error(`${context}: empty output`);
}
try {
return JSON.parse(trimmed) as T;
} catch (err) {
throw new Error(`${context}: invalid JSON - ${String(err)}`);
}
}
/** Normalize CLI add result to PowerMemAddResult[]. */
function normalizeAddOutput(raw: unknown): PowerMemAddResult[] {
if (Array.isArray(raw)) {
return raw.map((r) => ({
memory_id: Number((r as Record<string, unknown>).id ?? (r as Record<string, unknown>).memory_id ?? 0),
content: String((r as Record<string, unknown>).memory ?? (r as Record<string, unknown>).content ?? ""),
user_id: (r as Record<string, unknown>).user_id as string | undefined,
agent_id: (r as Record<string, unknown>).agent_id as string | undefined,
metadata: (r as Record<string, unknown>).metadata as Record<string, unknown> | undefined,
}));
}
const obj = raw as Record<string, unknown>;
const results = obj?.results ?? obj?.data;
if (Array.isArray(results)) {
return results.map((r: Record<string, unknown>) => ({
memory_id: Number(r.id ?? r.memory_id ?? 0),
content: String(r.memory ?? r.content ?? ""),
user_id: r.user_id as string | undefined,
agent_id: r.agent_id as string | undefined,
metadata: r.metadata as Record<string, unknown> | undefined,
}));
}
return [];
}
/** Normalize CLI search result to PowerMemSearchResult[]. */
function normalizeSearchOutput(raw: unknown): PowerMemSearchResult[] {
if (Array.isArray(raw)) {
return raw.map((r) => ({
memory_id: Number((r as Record<string, unknown>).memory_id ?? (r as Record<string, unknown>).id ?? 0),
content: String((r as Record<string, unknown>).content ?? (r as Record<string, unknown>).memory ?? ""),
score: Number((r as Record<string, unknown>).score ?? (r as Record<string, unknown>).similarity ?? 0),
metadata: (r as Record<string, unknown>).metadata as Record<string, unknown> | undefined,
}));
}
const obj = raw as Record<string, unknown>;
const results = obj?.results ?? obj?.data ?? obj?.memories;
if (Array.isArray(results)) {
return results.map((r: Record<string, unknown>) => ({
memory_id: Number(r.memory_id ?? r.id ?? 0),
content: String(r.content ?? r.memory ?? ""),
score: Number(r.score ?? r.similarity ?? 0),
metadata: r.metadata as Record<string, unknown> | undefined,
}));
}
return [];
}
export class PowerMemCLIClient {
private readonly pmemPath: string;
private readonly resolvedEnvFile?: string;
private readonly userId: string;
private readonly agentId: string;
private readonly buildProcessEnv?: () => Promise<Record<string, string>>;
private injectPromise: Promise<Record<string, string>> | null = null;
constructor(options: PowerMemCLIClientOptions) {
this.pmemPath = options.pmemPath;
this.resolvedEnvFile = options.resolvedEnvFile;
this.userId = options.userId;
this.agentId = options.agentId;
this.buildProcessEnv = options.buildProcessEnv;
}
static fromConfig(
cfg: PowerMemConfig,
userId: string,
agentId: string,
extras?: { buildProcessEnv?: () => Promise<Record<string, string>> },
): PowerMemCLIClient {
const raw = cfg.envFile?.trim();
const resolved = raw && existsSync(raw) ? raw : undefined;
return new PowerMemCLIClient({
pmemPath: cfg.pmemPath ?? "pmem",
resolvedEnvFile: resolved,
userId,
agentId,
buildProcessEnv: extras?.buildProcessEnv,
});
}
private async getInjectedEnv(): Promise<Record<string, string>> {
if (!this.buildProcessEnv) return {};
if (!this.injectPromise) {
this.injectPromise = this.buildProcessEnv().catch((err) => {
this.injectPromise = null;
throw err;
});
}
return this.injectPromise;
}
private async run(args: string[], context: string): Promise<string> {
const inject = await this.getInjectedEnv();
const env: NodeJS.ProcessEnv = { ...process.env, ...inject };
if (this.resolvedEnvFile) {
env.POWERMEM_ENV_FILE = this.resolvedEnvFile;
}
try {
const out = execFileSync(this.pmemPath, args, {
encoding: "utf-8",
maxBuffer: DEFAULT_MAX_BUFFER,
env,
});
return out;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const stderr =
err && typeof err === "object" && "stderr" in err
? String((err as { stderr: unknown }).stderr)
: "";
throw new Error(`${context}: ${msg}${stderr ? ` ${stderr}` : ""}`);
}
}
private envFileArgs(): string[] {
return this.resolvedEnvFile ? ["--env-file", this.resolvedEnvFile] : [];
}
async health(): Promise<{ status: string }> {
const argsList = [
...this.envFileArgs(),
"--json",
"-j",
"memory",
"list",
"--user-id",
this.userId,
"--agent-id",
this.agentId,
"--limit",
"1",
];
try {
await this.run(argsList, "health");
return { status: "healthy" };
} catch {
return { status: "unhealthy" };
}
}
async add(
content: string,
options: { infer?: boolean; metadata?: Record<string, unknown> } = {},
): Promise<PowerMemAddResult[]> {
const args = [
...this.envFileArgs(),
"--json",
"-j",
"memory",
"add",
content,
"--user-id",
this.userId,
"--agent-id",
this.agentId,
];
if (options.infer === false) {
args.push("--no-infer");
}
if (options.metadata && Object.keys(options.metadata).length > 0) {
args.push("--metadata", JSON.stringify(options.metadata));
}
const stdout = await this.run(args, "add");
const raw = parseJsonOrThrow<unknown>(stdout, "add");
return normalizeAddOutput(raw);
}
async search(query: string, limit = 5): Promise<PowerMemSearchResult[]> {
const args = [
...this.envFileArgs(),
"--json",
"-j",
"memory",
"search",
query,
"--user-id",
this.userId,
"--agent-id",
this.agentId,
"--limit",
String(limit),
];
const stdout = await this.run(args, "search");
const raw = parseJsonOrThrow<unknown>(stdout, "search");
return normalizeSearchOutput(raw);
}
async delete(memoryId: number | string): Promise<void> {
const id = String(memoryId);
const args = [
...this.envFileArgs(),
"memory",
"delete",
id,
"--user-id",
this.userId,
"--agent-id",
this.agentId,
"--yes",
];
await this.run(args, "delete");
}
}