@mingxy/cerebro 2.3.4 → 2.3.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.
package/src/client.ts CHANGED
@@ -1,403 +1,412 @@
1
- import { logWarn, logError } from "./logger.js";
2
- import type { CerebroPluginConfig } from "./config.js";
3
-
4
- function sanitizeContent(text: string, maxLen: number): string {
5
- let clean = text.replace(/<[\w-]+[^>]*>[\s\S]*?<\/[\w-]+>/g, "");
6
- clean = clean.replace(/<[\w-]+[^>]*\/>/g, "");
7
- clean = clean.replace(/\s+/g, " ").trim();
8
- if (clean.length <= maxLen) return clean;
9
- return clean.slice(0, maxLen) + "…[truncated]";
10
- }
11
-
12
- function truncateQuery(query: string, maxLen: number): string {
13
- if (query.length <= maxLen) return query;
14
- return query.slice(0, maxLen);
15
- }
16
-
17
- export interface IngestOptions {
18
- mode?: "smart" | "raw";
19
- agentId?: string;
20
- sessionId?: string;
21
- entityContext?: string;
22
- tags?: string[];
23
- projectName?: string;
24
- projectPath?: string;
25
- }
26
-
27
- export interface SearchResult {
28
- memory: MemoryDto;
29
- score: number;
30
- refine_relevance?: string;
31
- refine_reasoning?: string;
32
- }
33
-
34
- export interface SearchResponse {
35
- results: SearchResult[];
36
- trace?: unknown;
37
- }
38
-
39
- export interface ListResponse {
40
- memories: MemoryDto[];
41
- limit: number;
42
- offset: number;
43
- }
44
-
45
- export interface PreferenceDto {
46
- id: string;
47
- slot: string;
48
- value: string;
49
- confidence: number;
50
- scope: string;
51
- project_path?: string;
52
- source: string;
53
- status: string;
54
- created_at: string;
55
- updated_at: string;
56
- }
57
-
58
- export interface MemoryRelation {
59
- relation_type: string;
60
- target_id: string;
61
- context_label?: string;
62
- }
63
-
64
- export interface MemoryDto {
65
- id: string;
66
- content: string;
67
- l2_content?: string;
68
- category: string;
69
- memory_type: string;
70
- state: string;
71
- tags: string[];
72
- relations?: MemoryRelation[];
73
- source?: string;
74
- tenant_id: string;
75
- agent_id?: string;
76
- importance: number;
77
- created_at: string;
78
- updated_at: string;
79
- }
80
-
81
- export class CerebroClient {
82
- constructor(
83
- private baseUrl: string,
84
- private apiKey: string,
85
- private config?: Partial<CerebroPluginConfig>,
86
- ) {
87
- this.baseUrl = baseUrl.replace(/\/+$/, "");
88
- }
89
-
90
- private getCfg<S extends keyof CerebroPluginConfig, K extends string & keyof CerebroPluginConfig[S]>(
91
- section: S, key: K, fallback: CerebroPluginConfig[S][K],
92
- ): CerebroPluginConfig[S][K] {
93
- const sec = this.config?.[section] as Record<string, unknown> | undefined;
94
- return (sec?.[key] ?? fallback) as CerebroPluginConfig[S][K];
95
- }
96
-
97
- private async request<T>(
98
- path: string,
99
- init: RequestInit = {},
100
- timeoutMs?: number,
101
- ): Promise<T | null> {
102
- const url = `${this.baseUrl}${path}`;
103
- const controller = new AbortController();
104
- const timeout = setTimeout(
105
- () => controller.abort(),
106
- timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000),
107
- );
108
-
109
- try {
110
- const res = await fetch(url, {
111
- ...init,
112
- signal: controller.signal,
113
- headers: {
114
- "Content-Type": "application/json",
115
- "X-API-Key": this.apiKey,
116
- ...(init.headers as Record<string, string>),
117
- },
118
- });
119
-
120
- if (!res.ok) {
121
- const errorBody = await res.text().catch(() => "");
122
- logWarn("HTTP error", { method: init.method ?? "GET", path, status: res.status, statusText: res.statusText, errorBody });
123
- throw new Error(`[cerebro] ${res.status} ${res.statusText}${errorBody ? ": " + errorBody : ""}`);
124
- }
125
-
126
- if (res.status === 204) return null;
127
-
128
- const text = await res.text();
129
- const trimmed = text.replace(/^\uFEFF/, "").trim();
130
- if (!trimmed) return null;
131
- try {
132
- return JSON.parse(trimmed) as T;
133
- } catch (parseErr) {
134
- logError("JSON parse failed", { method: init.method ?? "GET", path, status: res.status, bodyLen: text.length, bodyPreview: text.slice(0, 200) });
135
- throw parseErr;
136
- }
137
- } catch (err) {
138
- if ((err as Error).name === "AbortError") {
139
- logWarn("Request timed out", { method: init.method ?? "GET", path, timeoutMs: timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000) });
140
- throw new Error(`[cerebro] Request timed out (${timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000)}ms)`);
141
- } else {
142
- logError("Request failed", { method: init.method ?? "GET", path, error: String(err) });
143
- throw err;
144
- }
145
- } finally {
146
- clearTimeout(timeout);
147
- }
148
- }
149
-
150
- private post<T>(path: string, body: unknown, timeoutMs?: number): Promise<T | null> {
151
- return this.request<T>(path, {
152
- method: "POST",
153
- body: JSON.stringify(body),
154
- }, timeoutMs);
155
- }
156
-
157
- private put<T>(path: string, body: unknown): Promise<T | null> {
158
- return this.request<T>(path, {
159
- method: "PUT",
160
- body: JSON.stringify(body),
161
- });
162
- }
163
-
164
- private patch<T>(path: string, body: unknown, timeoutMs?: number): Promise<T | null> {
165
- return this.request<T>(path, {
166
- method: "PATCH",
167
- body: JSON.stringify(body),
168
- }, timeoutMs);
169
- }
170
-
171
- private del<T>(path: string): Promise<T | null> {
172
- return this.request<T>(path, { method: "DELETE" });
173
- }
174
-
175
- async createMemory(
176
- content: string,
177
- tags?: string[],
178
- source?: string,
179
- scope?: string,
180
- agentId?: string,
181
- sessionId?: string,
182
- visibility?: string,
183
- category?: string,
184
- projectPath?: string,
185
- ): Promise<MemoryDto | null> {
186
- const safeContent = sanitizeContent(content, this.getCfg("content", "maxContentLength", 3000));
187
- return this.post<MemoryDto>("/v1/memories", {
188
- content: safeContent,
189
- tags,
190
- source,
191
- scope,
192
- agent_id: agentId,
193
- session_id: sessionId,
194
- visibility,
195
- category,
196
- project_path: projectPath,
197
- });
198
- }
199
-
200
- async searchMemories(
201
- query: string,
202
- limit = 10,
203
- scope?: string,
204
- tags?: string[],
205
- projectPath?: string,
206
- ): Promise<SearchResult[]> {
207
- const safeQ = truncateQuery(query, this.getCfg("content", "maxQueryLength", 200));
208
- const params = new URLSearchParams({ q: safeQ, limit: String(limit) });
209
- if (scope) params.set("scope", scope);
210
- if (tags && tags.length > 0) params.set("tags", tags.join(","));
211
- if (projectPath) params.set("project_path", projectPath);
212
- const res = await this.request<SearchResponse>(
213
- `/v1/memories/search?${params}`,
214
- {},
215
- 20_000,
216
- );
217
- return res?.results ?? [];
218
- }
219
-
220
- async getMemory(id: string): Promise<MemoryDto | null> {
221
- return this.request<MemoryDto>(`/v1/memories/${encodeURIComponent(id)}`);
222
- }
223
-
224
- async updateMemory(
225
- id: string,
226
- content: string,
227
- tags?: string[],
228
- ): Promise<MemoryDto | null> {
229
- return this.put<MemoryDto>(
230
- `/v1/memories/${encodeURIComponent(id)}`,
231
- { content, tags },
232
- );
233
- }
234
-
235
- async deleteMemory(id: string): Promise<void> {
236
- await this.del(`/v1/memories/${encodeURIComponent(id)}`);
237
- }
238
-
239
- async ingestMessages(
240
- messages: Array<{ role: string; content: string }>,
241
- opts: IngestOptions = {},
242
- ): Promise<unknown> {
243
- const safeMessages = messages.map(m => ({
244
- role: m.role,
245
- content: sanitizeContent(m.content, this.getCfg("content", "maxContentLength", 3000)),
246
- }));
247
- return this.post("/v1/memories", {
248
- messages: safeMessages,
249
- mode: opts.mode ?? "smart",
250
- agent_id: opts.agentId,
251
- session_id: opts.sessionId,
252
- entity_context: opts.entityContext,
253
- tags: opts.tags,
254
- project_name: opts.projectName,
255
- project_path: opts.projectPath,
256
- });
257
- }
258
-
259
- async getProfile(projectPath?: string): Promise<PreferenceDto[]> {
260
- const params = projectPath ? `?project_path=${encodeURIComponent(projectPath)}` : "";
261
- const res = await this.request<PreferenceDto[]>(`/v2/profile${params}`);
262
- return res ?? [];
263
- }
264
-
265
- async getInjection(projectPath?: string): Promise<{
266
- content: string;
267
- preference_count: number;
268
- estimated_tokens: number;
269
- } | null> {
270
- const params = projectPath ? `?project_path=${encodeURIComponent(projectPath)}` : "";
271
- return this.request(`/v2/profile/inject${params}`);
272
- }
273
-
274
- async getStats(): Promise<unknown> {
275
- return this.request("/v1/stats");
276
- }
277
-
278
- async getProfileStats(): Promise<unknown> {
279
- return this.request("/v2/profile/stats");
280
- }
281
-
282
- async listRecent(limit = 20, projectPath?: string): Promise<MemoryDto[]> {
283
- const params = new URLSearchParams({ limit: String(limit), offset: "0", sort: "updated_at", order: "desc" });
284
- if (projectPath) params.set("project_path", projectPath);
285
- const res = await this.request<ListResponse>(
286
- `/v1/memories?${params}`,
287
- );
288
- return res?.memories ?? [];
289
- }
290
-
291
- async createSpace(
292
- name: string,
293
- spaceType: string,
294
- members?: Array<{ user_id: string; role: string }>,
295
- ): Promise<unknown> {
296
- return this.post("/v1/spaces", { name, space_type: spaceType, members });
297
- }
298
-
299
- async listSpaces(): Promise<unknown[]> {
300
- const res = await this.request<{ spaces: unknown[] }>("/v1/spaces");
301
- return res?.spaces ?? [];
302
- }
303
-
304
- async addSpaceMember(
305
- spaceId: string,
306
- userId: string,
307
- role: string,
308
- ): Promise<unknown> {
309
- return this.post(
310
- `/v1/spaces/${encodeURIComponent(spaceId)}/members`,
311
- { user_id: userId, role },
312
- );
313
- }
314
-
315
- async shareMemory(
316
- memoryId: string,
317
- targetSpace: string,
318
- ): Promise<unknown> {
319
- return this.post(
320
- `/v1/memories/${encodeURIComponent(memoryId)}/share`,
321
- { target_space: targetSpace },
322
- );
323
- }
324
-
325
- async pullMemory(
326
- memoryId: string,
327
- sourceSpace: string,
328
- visibility?: string,
329
- ): Promise<unknown> {
330
- return this.post(
331
- `/v1/memories/${encodeURIComponent(memoryId)}/pull`,
332
- { source_space: sourceSpace, visibility },
333
- );
334
- }
335
-
336
- async reshareMemory(
337
- memoryId: string,
338
- targetSpace?: string,
339
- ): Promise<unknown> {
340
- return this.post(
341
- `/v1/memories/${encodeURIComponent(memoryId)}/reshare`,
342
- { target_space: targetSpace },
343
- );
344
- }
345
-
346
- async updateProfileInjected(
347
- event_id: string,
348
- profile_injected: boolean,
349
- profile_content?: string,
350
- ): Promise<unknown | null> {
351
- const body: Record<string, unknown> = { profile_injected };
352
- if (profile_content !== undefined) {
353
- body.profile_content = profile_content;
354
- }
355
- const res = await this.patch(
356
- `/v1/recall-events/${event_id}/profile-injected`,
357
- body,
358
- 10_000,
359
- );
360
- return res;
361
- }
362
-
363
- async createRecallEvent(params: {
364
- session_id: string;
365
- recall_type?: string;
366
- query_text: string;
367
- max_score: number;
368
- llm_confidence: number;
369
- profile_injected: boolean;
370
- kept_count: number;
371
- discarded_count: number;
372
- injected_count: number;
373
- profile_content?: string;
374
- injected_content?: string;
375
- items?: Array<{
376
- memory_id: string;
377
- score: number;
378
- refine_relevance?: string;
379
- refine_reasoning?: string;
380
- is_kept: boolean;
381
- }>;
382
- }): Promise<{ ok: boolean; event_id?: string } | null> {
383
- return this.post("/v1/recall-events", params, 10_000);
384
- }
385
-
386
- async sessionIngest(
387
- messages: Array<{ role: string; content: string }>,
388
- sessionId?: string,
389
- agentId?: string,
390
- sessionTitle?: string,
391
- projectName?: string,
392
- projectPath?: string,
393
- ): Promise<unknown> {
394
- return this.post("/v1/memories/session-ingest", {
395
- messages,
396
- session_id: sessionId,
397
- agent_id: agentId,
398
- session_title: sessionTitle,
399
- project_name: projectName,
400
- project_path: projectPath,
401
- }, 60000);
402
- }
403
- }
1
+ import { homedir } from "node:os";
2
+ import { logWarn, logError } from "./logger.js";
3
+ import type { CerebroPluginConfig } from "./config.js";
4
+
5
+ function sanitizeContent(text: string, maxLen: number): string {
6
+ let clean = text.replace(/<[\w-]+[^>]*>[\s\S]*?<\/[\w-]+>/g, "");
7
+ clean = clean.replace(/<[\w-]+[^>]*\/>/g, "");
8
+ clean = clean.replace(/\s+/g, " ").trim();
9
+ if (clean.length <= maxLen) return clean;
10
+ return clean.slice(0, maxLen) + "…[truncated]";
11
+ }
12
+
13
+ function truncateQuery(query: string, maxLen: number): string {
14
+ if (query.length <= maxLen) return query;
15
+ return query.slice(0, maxLen);
16
+ }
17
+
18
+ export interface IngestOptions {
19
+ mode?: "smart" | "raw";
20
+ agentId?: string;
21
+ sessionId?: string;
22
+ entityContext?: string;
23
+ tags?: string[];
24
+ projectName?: string;
25
+ projectPath?: string;
26
+ }
27
+
28
+ export interface SearchResult {
29
+ memory: MemoryDto;
30
+ score: number;
31
+ refine_relevance?: string;
32
+ refine_reasoning?: string;
33
+ }
34
+
35
+ export interface SearchResponse {
36
+ results: SearchResult[];
37
+ trace?: unknown;
38
+ }
39
+
40
+ export interface ListResponse {
41
+ memories: MemoryDto[];
42
+ limit: number;
43
+ offset: number;
44
+ }
45
+
46
+ export interface PreferenceDto {
47
+ id: string;
48
+ slot: string;
49
+ value: string;
50
+ confidence: number;
51
+ scope: string;
52
+ project_path?: string;
53
+ source: string;
54
+ status: string;
55
+ created_at: string;
56
+ updated_at: string;
57
+ }
58
+
59
+ export interface MemoryRelation {
60
+ relation_type: string;
61
+ target_id: string;
62
+ context_label?: string;
63
+ }
64
+
65
+ export interface MemoryDto {
66
+ id: string;
67
+ content: string;
68
+ l2_content?: string;
69
+ category: string;
70
+ memory_type: string;
71
+ state: string;
72
+ tags: string[];
73
+ relations?: MemoryRelation[];
74
+ source?: string;
75
+ tenant_id: string;
76
+ agent_id?: string;
77
+ importance: number;
78
+ created_at: string;
79
+ updated_at: string;
80
+ }
81
+
82
+ export class CerebroClient {
83
+ constructor(
84
+ private baseUrl: string,
85
+ private apiKey: string,
86
+ private config?: Partial<CerebroPluginConfig>,
87
+ ) {
88
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
89
+ }
90
+
91
+ private getCfg<S extends keyof CerebroPluginConfig, K extends string & keyof CerebroPluginConfig[S]>(
92
+ section: S, key: K, fallback: CerebroPluginConfig[S][K],
93
+ ): CerebroPluginConfig[S][K] {
94
+ const sec = this.config?.[section] as Record<string, unknown> | undefined;
95
+ return (sec?.[key] ?? fallback) as CerebroPluginConfig[S][K];
96
+ }
97
+
98
+ private async request<T>(
99
+ path: string,
100
+ init: RequestInit = {},
101
+ timeoutMs?: number,
102
+ ): Promise<T | null> {
103
+ const url = `${this.baseUrl}${path}`;
104
+ const controller = new AbortController();
105
+ const timeout = setTimeout(
106
+ () => controller.abort(),
107
+ timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000),
108
+ );
109
+
110
+ try {
111
+ const res = await fetch(url, {
112
+ ...init,
113
+ signal: controller.signal,
114
+ headers: {
115
+ "Content-Type": "application/json",
116
+ "X-API-Key": this.apiKey,
117
+ ...(init.headers as Record<string, string>),
118
+ },
119
+ });
120
+
121
+ if (!res.ok) {
122
+ const errorBody = await res.text().catch(() => "");
123
+ logWarn("HTTP error", { method: init.method ?? "GET", path, status: res.status, statusText: res.statusText, errorBody });
124
+ throw new Error(`[cerebro] ${res.status} ${res.statusText}${errorBody ? ": " + errorBody : ""}`);
125
+ }
126
+
127
+ if (res.status === 204) return null;
128
+
129
+ const text = await res.text();
130
+ const trimmed = text.replace(/^\uFEFF/, "").trim();
131
+ if (!trimmed) return null;
132
+ try {
133
+ return JSON.parse(trimmed) as T;
134
+ } catch (parseErr) {
135
+ logError("JSON parse failed", { method: init.method ?? "GET", path, status: res.status, bodyLen: text.length, bodyPreview: text.slice(0, 200) });
136
+ throw parseErr;
137
+ }
138
+ } catch (err) {
139
+ if ((err as Error).name === "AbortError") {
140
+ logWarn("Request timed out", { method: init.method ?? "GET", path, timeoutMs: timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000) });
141
+ throw new Error(`[cerebro] Request timed out (${timeoutMs ?? this.getCfg("connection", "requestTimeoutMs", 15000)}ms)`);
142
+ } else {
143
+ logError("Request failed", { method: init.method ?? "GET", path, error: String(err) });
144
+ throw err;
145
+ }
146
+ } finally {
147
+ clearTimeout(timeout);
148
+ }
149
+ }
150
+
151
+ private post<T>(path: string, body: unknown, timeoutMs?: number): Promise<T | null> {
152
+ return this.request<T>(path, {
153
+ method: "POST",
154
+ body: JSON.stringify(body),
155
+ }, timeoutMs);
156
+ }
157
+
158
+ private put<T>(path: string, body: unknown): Promise<T | null> {
159
+ return this.request<T>(path, {
160
+ method: "PUT",
161
+ body: JSON.stringify(body),
162
+ });
163
+ }
164
+
165
+ private patch<T>(path: string, body: unknown, timeoutMs?: number): Promise<T | null> {
166
+ return this.request<T>(path, {
167
+ method: "PATCH",
168
+ body: JSON.stringify(body),
169
+ }, timeoutMs);
170
+ }
171
+
172
+ private del<T>(path: string): Promise<T | null> {
173
+ return this.request<T>(path, { method: "DELETE" });
174
+ }
175
+
176
+ async createMemory(
177
+ content: string,
178
+ tags?: string[],
179
+ source?: string,
180
+ scope?: string,
181
+ agentId?: string,
182
+ sessionId?: string,
183
+ visibility?: string,
184
+ category?: string,
185
+ projectPath?: string,
186
+ ): Promise<MemoryDto | null> {
187
+ const safeContent = sanitizeContent(content, this.getCfg("content", "maxContentLength", 3000));
188
+ return this.post<MemoryDto>("/v1/memories", {
189
+ content: safeContent,
190
+ tags,
191
+ source,
192
+ scope,
193
+ agent_id: agentId,
194
+ session_id: sessionId,
195
+ visibility,
196
+ category,
197
+ project_path: projectPath,
198
+ home_path: homedir(),
199
+ });
200
+ }
201
+
202
+ async searchMemories(
203
+ query: string,
204
+ limit = 10,
205
+ scope?: string,
206
+ tags?: string[],
207
+ projectPath?: string,
208
+ globalOnly?: boolean,
209
+ excludeGlobal?: boolean,
210
+ ): Promise<SearchResult[]> {
211
+ const safeQ = truncateQuery(query, this.getCfg("content", "maxQueryLength", 200));
212
+ const params = new URLSearchParams({ q: safeQ, limit: String(limit) });
213
+ if (scope) params.set("scope", scope);
214
+ if (tags && tags.length > 0) params.set("tags", tags.join(","));
215
+ if (projectPath) params.set("project_path", projectPath);
216
+ if (globalOnly) params.set("global_only", "1");
217
+ if (excludeGlobal) params.set("exclude_global", "1");
218
+ const res = await this.request<SearchResponse>(
219
+ `/v1/memories/search?${params}`,
220
+ {},
221
+ 20_000,
222
+ );
223
+ return res?.results ?? [];
224
+ }
225
+
226
+ async getMemory(id: string): Promise<MemoryDto | null> {
227
+ return this.request<MemoryDto>(`/v1/memories/${encodeURIComponent(id)}`);
228
+ }
229
+
230
+ async updateMemory(
231
+ id: string,
232
+ content: string,
233
+ tags?: string[],
234
+ ): Promise<MemoryDto | null> {
235
+ return this.put<MemoryDto>(
236
+ `/v1/memories/${encodeURIComponent(id)}`,
237
+ { content, tags },
238
+ );
239
+ }
240
+
241
+ async deleteMemory(id: string): Promise<void> {
242
+ await this.del(`/v1/memories/${encodeURIComponent(id)}`);
243
+ }
244
+
245
+ async ingestMessages(
246
+ messages: Array<{ role: string; content: string }>,
247
+ opts: IngestOptions = {},
248
+ ): Promise<unknown> {
249
+ const safeMessages = messages.map(m => ({
250
+ role: m.role,
251
+ content: sanitizeContent(m.content, this.getCfg("content", "maxContentLength", 3000)),
252
+ }));
253
+ return this.post("/v1/memories", {
254
+ messages: safeMessages,
255
+ mode: opts.mode ?? "smart",
256
+ agent_id: opts.agentId,
257
+ session_id: opts.sessionId,
258
+ entity_context: opts.entityContext,
259
+ tags: opts.tags,
260
+ project_name: opts.projectName,
261
+ project_path: opts.projectPath,
262
+ home_path: homedir(),
263
+ });
264
+ }
265
+
266
+ async getProfile(projectPath?: string): Promise<PreferenceDto[]> {
267
+ const params = projectPath ? `?project_path=${encodeURIComponent(projectPath)}` : "";
268
+ const res = await this.request<PreferenceDto[]>(`/v2/profile${params}`);
269
+ return res ?? [];
270
+ }
271
+
272
+ async getInjection(projectPath?: string): Promise<{
273
+ content: string;
274
+ preference_count: number;
275
+ estimated_tokens: number;
276
+ } | null> {
277
+ const params = projectPath ? `?project_path=${encodeURIComponent(projectPath)}` : "";
278
+ return this.request(`/v2/profile/inject${params}`);
279
+ }
280
+
281
+ async getStats(): Promise<unknown> {
282
+ return this.request("/v1/stats");
283
+ }
284
+
285
+ async getProfileStats(): Promise<unknown> {
286
+ return this.request("/v2/profile/stats");
287
+ }
288
+
289
+ async listRecent(limit = 20, projectPath?: string, excludeGlobal?: boolean): Promise<MemoryDto[]> {
290
+ const params = new URLSearchParams({ limit: String(limit), offset: "0", sort: "updated_at", order: "desc" });
291
+ if (projectPath) params.set("project_path", projectPath);
292
+ if (excludeGlobal) params.set("exclude_global", "1");
293
+ const res = await this.request<ListResponse>(
294
+ `/v1/memories?${params}`,
295
+ );
296
+ return res?.memories ?? [];
297
+ }
298
+
299
+ async createSpace(
300
+ name: string,
301
+ spaceType: string,
302
+ members?: Array<{ user_id: string; role: string }>,
303
+ ): Promise<unknown> {
304
+ return this.post("/v1/spaces", { name, space_type: spaceType, members });
305
+ }
306
+
307
+ async listSpaces(): Promise<unknown[]> {
308
+ const res = await this.request<{ spaces: unknown[] }>("/v1/spaces");
309
+ return res?.spaces ?? [];
310
+ }
311
+
312
+ async addSpaceMember(
313
+ spaceId: string,
314
+ userId: string,
315
+ role: string,
316
+ ): Promise<unknown> {
317
+ return this.post(
318
+ `/v1/spaces/${encodeURIComponent(spaceId)}/members`,
319
+ { user_id: userId, role },
320
+ );
321
+ }
322
+
323
+ async shareMemory(
324
+ memoryId: string,
325
+ targetSpace: string,
326
+ ): Promise<unknown> {
327
+ return this.post(
328
+ `/v1/memories/${encodeURIComponent(memoryId)}/share`,
329
+ { target_space: targetSpace },
330
+ );
331
+ }
332
+
333
+ async pullMemory(
334
+ memoryId: string,
335
+ sourceSpace: string,
336
+ visibility?: string,
337
+ ): Promise<unknown> {
338
+ return this.post(
339
+ `/v1/memories/${encodeURIComponent(memoryId)}/pull`,
340
+ { source_space: sourceSpace, visibility },
341
+ );
342
+ }
343
+
344
+ async reshareMemory(
345
+ memoryId: string,
346
+ targetSpace?: string,
347
+ ): Promise<unknown> {
348
+ return this.post(
349
+ `/v1/memories/${encodeURIComponent(memoryId)}/reshare`,
350
+ { target_space: targetSpace },
351
+ );
352
+ }
353
+
354
+ async updateProfileInjected(
355
+ event_id: string,
356
+ profile_injected: boolean,
357
+ profile_content?: string,
358
+ ): Promise<unknown | null> {
359
+ const body: Record<string, unknown> = { profile_injected };
360
+ if (profile_content !== undefined) {
361
+ body.profile_content = profile_content;
362
+ }
363
+ const res = await this.patch(
364
+ `/v1/recall-events/${event_id}/profile-injected`,
365
+ body,
366
+ 10_000,
367
+ );
368
+ return res;
369
+ }
370
+
371
+ async createRecallEvent(params: {
372
+ session_id: string;
373
+ recall_type?: string;
374
+ query_text: string;
375
+ max_score: number;
376
+ llm_confidence: number;
377
+ profile_injected: boolean;
378
+ kept_count: number;
379
+ discarded_count: number;
380
+ injected_count: number;
381
+ profile_content?: string;
382
+ injected_content?: string;
383
+ items?: Array<{
384
+ memory_id: string;
385
+ score: number;
386
+ refine_relevance?: string;
387
+ refine_reasoning?: string;
388
+ is_kept: boolean;
389
+ }>;
390
+ }): Promise<{ ok: boolean; event_id?: string } | null> {
391
+ return this.post("/v1/recall-events", params, 10_000);
392
+ }
393
+
394
+ async sessionIngest(
395
+ messages: Array<{ role: string; content: string }>,
396
+ sessionId?: string,
397
+ agentId?: string,
398
+ sessionTitle?: string,
399
+ projectName?: string,
400
+ projectPath?: string,
401
+ ): Promise<unknown> {
402
+ return this.post("/v1/memories/session-ingest", {
403
+ messages,
404
+ session_id: sessionId,
405
+ agent_id: agentId,
406
+ session_title: sessionTitle,
407
+ project_name: projectName,
408
+ project_path: projectPath,
409
+ home_path: homedir(),
410
+ }, 60000);
411
+ }
412
+ }