@easbot/memory 0.3.17 → 0.3.19
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/README.en.md +101 -0
- package/README.md +116 -11
- package/dist/chunks/chunk-4GSXSIV5.cjs +1 -0
- package/dist/chunks/chunk-5Q6SIVSP.cjs +50 -0
- package/dist/chunks/chunk-6CQMBEIQ.mjs +1 -0
- package/dist/chunks/chunk-746FKSL5.mjs +50 -0
- package/dist/chunks/chunk-ARA4LMAI.mjs +1 -0
- package/dist/chunks/chunk-CN6WBJLX.mjs +60 -0
- package/dist/chunks/{chunk-OIUUTVLL.cjs → chunk-EGWJG65Q.cjs} +22 -4
- package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
- package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
- package/dist/chunks/chunk-QHPGDNEG.cjs +1 -0
- package/dist/chunks/{chunk-MWRDF6VN.mjs → chunk-QYBWHFOX.mjs} +1 -1
- package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
- package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
- package/dist/chunks/chunk-X66LENNV.cjs +60 -0
- package/dist/chunks/cli-handler-CN4Q7BCY.mjs +1 -0
- package/dist/chunks/cli-handler-IRPYADZF.cjs +1 -0
- package/dist/chunks/consolidate-PUOAAQN3.cjs +2 -0
- package/dist/chunks/consolidate-UEYNLKQN.mjs +2 -0
- package/dist/chunks/doctor-KPAZWVVZ.mjs +1 -0
- package/dist/chunks/doctor-U4HOSXGW.cjs +1 -0
- package/dist/chunks/extract-7FFIDVG3.cjs +2 -0
- package/dist/chunks/extract-EOZJMLTP.mjs +2 -0
- package/dist/chunks/{forget-A4UJI3LE.mjs → forget-5AXV3GHW.mjs} +1 -1
- package/dist/chunks/forget-GBMYCUPJ.cjs +3 -0
- package/dist/chunks/graph-KOJYJTA4.cjs +3 -0
- package/dist/chunks/{graph-XZ46LEO7.mjs → graph-Y6AYRFCN.mjs} +1 -1
- package/dist/chunks/init-B24TNUSD.cjs +1 -0
- package/dist/chunks/init-HGEBZTJW.mjs +1 -0
- package/dist/chunks/llm-RMPVWEVP.cjs +1 -0
- package/dist/chunks/llm-UHTBU2HA.mjs +1 -0
- package/dist/chunks/{mcp-BOD4ZOZS.mjs → mcp-BMAB3TT7.mjs} +1 -1
- package/dist/chunks/{mcp-BXVXTUJK.cjs → mcp-BS6XHEBR.cjs} +1 -1
- package/dist/chunks/recall-LKETADTB.cjs +2 -0
- package/dist/chunks/recall-UPGGKBNX.mjs +2 -0
- package/dist/chunks/remember-KCQN2UWN.mjs +2 -0
- package/dist/chunks/remember-VZF4O7ZF.cjs +2 -0
- package/dist/chunks/status-2BFVXY5J.cjs +1 -0
- package/dist/chunks/status-HGN2YLKJ.mjs +1 -0
- package/dist/chunks/stdio-server-GABA2MLR.cjs +1 -0
- package/dist/chunks/stdio-server-JPMLMEWY.mjs +1 -0
- package/dist/chunks/sync-7Y2DEDDW.mjs +2 -0
- package/dist/chunks/sync-W5A2O5TS.cjs +2 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +87 -38
- package/dist/index.d.ts +87 -38
- package/dist/index.mjs +4 -4
- package/package.json +9 -8
- package/dist/chunks/chunk-BSKFK4RC.mjs +0 -1
- package/dist/chunks/chunk-DFWC6WII.mjs +0 -53
- package/dist/chunks/chunk-DXU5WPK3.cjs +0 -42
- package/dist/chunks/chunk-EECBJNZI.mjs +0 -59
- package/dist/chunks/chunk-FMEXQ5YE.cjs +0 -59
- package/dist/chunks/chunk-HSK27DQ7.cjs +0 -1
- package/dist/chunks/chunk-I6XVFDN2.mjs +0 -42
- package/dist/chunks/chunk-QNDG7BTB.cjs +0 -1
- package/dist/chunks/chunk-RSJ2KT6X.cjs +0 -1
- package/dist/chunks/chunk-TPSRK4M3.mjs +0 -1
- package/dist/chunks/cli-handler-6VTKYXXM.mjs +0 -1
- package/dist/chunks/cli-handler-HNPA3STD.cjs +0 -1
- package/dist/chunks/consolidate-6P7LUPPL.cjs +0 -2
- package/dist/chunks/consolidate-NYH4IKJK.mjs +0 -2
- package/dist/chunks/doctor-IJJ5UYGT.cjs +0 -2
- package/dist/chunks/doctor-MZSZGVRL.mjs +0 -2
- package/dist/chunks/extract-6B7OD3VK.mjs +0 -2
- package/dist/chunks/extract-ERTOHQV6.cjs +0 -2
- package/dist/chunks/forget-KLFM5SBQ.cjs +0 -3
- package/dist/chunks/graph-P5ZHB4ZM.cjs +0 -3
- package/dist/chunks/init-CCOSHE3F.cjs +0 -3
- package/dist/chunks/init-WEPU32KF.mjs +0 -3
- package/dist/chunks/recall-BV4Z7HUJ.mjs +0 -2
- package/dist/chunks/recall-FEINUJKO.cjs +0 -2
- package/dist/chunks/remember-ESVRA73C.mjs +0 -2
- package/dist/chunks/remember-YNSY2JJB.cjs +0 -2
- package/dist/chunks/status-KVM7I6YC.cjs +0 -2
- package/dist/chunks/status-QQZS3ZCN.mjs +0 -2
- package/dist/chunks/stdio-server-MQKTUGNG.cjs +0 -1
- package/dist/chunks/stdio-server-ZLMSUTC5.mjs +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, IGlobal, IInstance } from '@easbot/types';
|
|
1
|
+
import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
|
|
2
2
|
export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
|
|
3
3
|
import { EmbeddingModel, LanguageModel } from 'ai';
|
|
4
4
|
export { EmbeddingModel, LanguageModel } from 'ai';
|
|
5
|
-
import {
|
|
5
|
+
import { ILLMInitConfig, ILLMCapabilities } from '@easbot/llm';
|
|
6
6
|
import { ZodTypeAny } from 'zod';
|
|
7
7
|
import { StdioServerConfig } from '@easbot/mcp';
|
|
8
8
|
import { SyncSqliteConnection } from '@easbot/database';
|
|
@@ -158,35 +158,27 @@ interface LlmModels {
|
|
|
158
158
|
embeddingLlm?: EmbeddingModel;
|
|
159
159
|
graphLlm?: LanguageModel;
|
|
160
160
|
}
|
|
161
|
-
interface
|
|
162
|
-
maxOutputTokens?: number;
|
|
163
|
-
temperature?: number;
|
|
164
|
-
}
|
|
165
|
-
interface LlmInitConfig {
|
|
166
|
-
models: LlmModels;
|
|
161
|
+
interface LlmInitConfig extends ILLMInitConfig {
|
|
167
162
|
options?: {
|
|
168
|
-
graph?:
|
|
169
|
-
|
|
163
|
+
graph?: {
|
|
164
|
+
maxOutputTokens?: number;
|
|
165
|
+
temperature?: number;
|
|
166
|
+
};
|
|
167
|
+
embedding?: {
|
|
168
|
+
maxOutputTokens?: number;
|
|
169
|
+
temperature?: number;
|
|
170
|
+
};
|
|
170
171
|
};
|
|
171
172
|
}
|
|
172
173
|
declare namespace Llm {
|
|
173
|
-
function init(config:
|
|
174
|
+
function init(config: ILLMInitConfig): void;
|
|
174
175
|
function isInitialized(): boolean;
|
|
175
176
|
function reset(): void;
|
|
176
|
-
function capabilities():
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
};
|
|
177
|
+
function capabilities(): ILLMCapabilities;
|
|
178
|
+
function getEmbeddingLlm(): EmbeddingModel | undefined;
|
|
179
|
+
function getGraphLlm(): LanguageModel | undefined;
|
|
180
180
|
function embedText(value: string): Promise<Float32Array>;
|
|
181
181
|
function embedTexts(values: string[]): Promise<Float32Array[]>;
|
|
182
|
-
function generateGraph(chunks: string[], entityTypes: ReadonlyArray<{
|
|
183
|
-
type: string;
|
|
184
|
-
rule: string;
|
|
185
|
-
}>, relationTypes: ReadonlyArray<{
|
|
186
|
-
type: string;
|
|
187
|
-
rule: string;
|
|
188
|
-
}>, options?: BuildPromptOptions & LlmOptions): Promise<string>;
|
|
189
|
-
function generate(prompt: string, options?: LlmOptions): Promise<string>;
|
|
190
182
|
const embed: typeof embedText;
|
|
191
183
|
const embedMany: typeof embedTexts;
|
|
192
184
|
}
|
|
@@ -243,6 +235,8 @@ interface RememberResult {
|
|
|
243
235
|
nodeIds?: number[];
|
|
244
236
|
vectorsWritten: number;
|
|
245
237
|
vectorDims: number;
|
|
238
|
+
entitiesExtracted: number;
|
|
239
|
+
relationsExtracted: number;
|
|
246
240
|
}
|
|
247
241
|
interface ForgetParams {
|
|
248
242
|
factId?: string;
|
|
@@ -315,29 +309,37 @@ interface GraphQueryResult {
|
|
|
315
309
|
durationMs: number;
|
|
316
310
|
}
|
|
317
311
|
type StatusParams = {};
|
|
318
|
-
interface StatusResult {
|
|
319
|
-
dbPath: string;
|
|
320
|
-
workspaceDir: string;
|
|
312
|
+
interface StatusResult extends MemoryStatus {
|
|
321
313
|
factsCount: number;
|
|
322
314
|
nodesCount: number;
|
|
323
315
|
edgesCount: number;
|
|
324
316
|
factsByCategory: Record<MemoryCategory, number>;
|
|
325
317
|
ftsAvailable: boolean;
|
|
326
|
-
vectorEnabled: boolean;
|
|
327
|
-
kgScopeEnabled: boolean;
|
|
328
|
-
healthy: boolean;
|
|
329
|
-
meta: Record<string, string>;
|
|
330
318
|
}
|
|
331
319
|
type DoctorParams = {};
|
|
332
|
-
interface DoctorResult {
|
|
333
|
-
|
|
334
|
-
checks: Array<{
|
|
320
|
+
interface DoctorResult extends KnowledgeDoctorResult {
|
|
321
|
+
legacyChecks: Array<{
|
|
335
322
|
name: string;
|
|
336
323
|
passed: boolean;
|
|
337
324
|
message: string;
|
|
338
325
|
details?: Record<string, unknown>;
|
|
339
|
-
severity?: 'error' | 'info';
|
|
326
|
+
severity?: 'error' | 'info' | 'warn' | 'ok';
|
|
340
327
|
}>;
|
|
328
|
+
integrityStats?: {
|
|
329
|
+
memory_facts: number;
|
|
330
|
+
memory_vectors: number;
|
|
331
|
+
embedding_cache: number;
|
|
332
|
+
memory_facts_fts: number;
|
|
333
|
+
nodes: number;
|
|
334
|
+
edges: number;
|
|
335
|
+
meta: number;
|
|
336
|
+
schema_migrations: number;
|
|
337
|
+
};
|
|
338
|
+
backendAvailable?: {
|
|
339
|
+
'better-sqlite3': boolean;
|
|
340
|
+
'node:sqlite': boolean;
|
|
341
|
+
'@tursodatabase/database': boolean;
|
|
342
|
+
};
|
|
341
343
|
}
|
|
342
344
|
interface InitParams {
|
|
343
345
|
dbPath?: string;
|
|
@@ -349,12 +351,33 @@ interface InitResult {
|
|
|
349
351
|
initialized: boolean;
|
|
350
352
|
dbPath: string;
|
|
351
353
|
configPath: string;
|
|
354
|
+
schemaVersion: number;
|
|
352
355
|
workspaceDir: string;
|
|
353
356
|
tablesCreated: number;
|
|
354
357
|
migrationsApplied: number;
|
|
355
358
|
durationMs: number;
|
|
356
359
|
configCreated: boolean;
|
|
357
360
|
}
|
|
361
|
+
interface SyncParams {
|
|
362
|
+
windowDays?: number;
|
|
363
|
+
dryRun?: boolean;
|
|
364
|
+
}
|
|
365
|
+
interface SyncResult {
|
|
366
|
+
generatedCount: number;
|
|
367
|
+
skippedCount: number;
|
|
368
|
+
failedGenerateCount: number;
|
|
369
|
+
archivedCount: number;
|
|
370
|
+
archiveThreshold: string;
|
|
371
|
+
archivedRecords: Array<{
|
|
372
|
+
source: string;
|
|
373
|
+
target: string;
|
|
374
|
+
firstCreatedAt: string;
|
|
375
|
+
firstFactId: string;
|
|
376
|
+
}>;
|
|
377
|
+
windowDays: number;
|
|
378
|
+
dryRun: boolean;
|
|
379
|
+
durationMs: number;
|
|
380
|
+
}
|
|
358
381
|
|
|
359
382
|
declare function recall(ctx: MemoryServiceContext, params: RecallParams): Promise<RecallResult>;
|
|
360
383
|
|
|
@@ -366,11 +389,21 @@ declare function extract(ctx: MemoryServiceContext, params: ExtractParams): Prom
|
|
|
366
389
|
|
|
367
390
|
declare function consolidate(ctx: MemoryServiceContext, params?: ConsolidateParams): Promise<ConsolidateResult>;
|
|
368
391
|
|
|
392
|
+
declare function sync(ctx: MemoryServiceContext, params?: SyncParams): Promise<SyncResult>;
|
|
393
|
+
|
|
369
394
|
declare function graphQuery(ctx: MemoryServiceContext, params: GraphQueryParams): Promise<GraphQueryResult>;
|
|
370
395
|
|
|
371
|
-
|
|
396
|
+
interface StatusOptions {
|
|
397
|
+
skipEmbeddingProbe?: boolean;
|
|
398
|
+
skipLlm?: boolean;
|
|
399
|
+
}
|
|
400
|
+
declare function status(ctx: MemoryServiceContext, _params?: StatusParams, options?: StatusOptions): Promise<StatusResult>;
|
|
372
401
|
|
|
373
|
-
|
|
402
|
+
interface DoctorOptions {
|
|
403
|
+
skipEmbeddingProbe?: boolean;
|
|
404
|
+
skipLlm?: boolean;
|
|
405
|
+
}
|
|
406
|
+
declare function doctor(ctx: MemoryServiceContext, _params?: DoctorParams, options?: DoctorOptions): Promise<DoctorResult>;
|
|
374
407
|
|
|
375
408
|
declare function init(ctx: MemoryServiceContext, params?: InitParams): Promise<InitResult>;
|
|
376
409
|
|
|
@@ -480,7 +513,7 @@ declare function getMemoryDbPath(input?: string | {
|
|
|
480
513
|
}): string;
|
|
481
514
|
|
|
482
515
|
type MigrationDb = SyncSqliteConnection;
|
|
483
|
-
declare const LATEST_SCHEMA_VERSION =
|
|
516
|
+
declare const LATEST_SCHEMA_VERSION = 1;
|
|
484
517
|
interface SchemaMigration {
|
|
485
518
|
id: number;
|
|
486
519
|
description: string;
|
|
@@ -532,6 +565,22 @@ declare class MemoryDatabaseManager {
|
|
|
532
565
|
getSchemaVersion(): number;
|
|
533
566
|
close(): void;
|
|
534
567
|
healthCheck(): boolean;
|
|
568
|
+
checkIntegrity(): {
|
|
569
|
+
issues: Array<{
|
|
570
|
+
severity: 'error' | 'warn' | 'info';
|
|
571
|
+
message: string;
|
|
572
|
+
}>;
|
|
573
|
+
stats: {
|
|
574
|
+
memory_facts: number;
|
|
575
|
+
memory_vectors: number;
|
|
576
|
+
embedding_cache: number;
|
|
577
|
+
memory_facts_fts: number;
|
|
578
|
+
nodes: number;
|
|
579
|
+
edges: number;
|
|
580
|
+
meta: number;
|
|
581
|
+
schema_migrations: number;
|
|
582
|
+
};
|
|
583
|
+
};
|
|
535
584
|
getMeta(key: string): string | null;
|
|
536
585
|
setMeta(key: string, value: string): void;
|
|
537
586
|
}
|
|
@@ -581,4 +630,4 @@ declare function registerAllDefaultHooks(): void;
|
|
|
581
630
|
declare function clearAllHooks(): void;
|
|
582
631
|
declare function dispatchHook(name: HookName, ctx: HookContext): Promise<HookResult>;
|
|
583
632
|
|
|
584
|
-
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels,
|
|
633
|
+
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, IGlobal, IInstance } from '@easbot/types';
|
|
1
|
+
import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
|
|
2
2
|
export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
|
|
3
3
|
import { EmbeddingModel, LanguageModel } from 'ai';
|
|
4
4
|
export { EmbeddingModel, LanguageModel } from 'ai';
|
|
5
|
-
import {
|
|
5
|
+
import { ILLMInitConfig, ILLMCapabilities } from '@easbot/llm';
|
|
6
6
|
import { ZodTypeAny } from 'zod';
|
|
7
7
|
import { StdioServerConfig } from '@easbot/mcp';
|
|
8
8
|
import { SyncSqliteConnection } from '@easbot/database';
|
|
@@ -158,35 +158,27 @@ interface LlmModels {
|
|
|
158
158
|
embeddingLlm?: EmbeddingModel;
|
|
159
159
|
graphLlm?: LanguageModel;
|
|
160
160
|
}
|
|
161
|
-
interface
|
|
162
|
-
maxOutputTokens?: number;
|
|
163
|
-
temperature?: number;
|
|
164
|
-
}
|
|
165
|
-
interface LlmInitConfig {
|
|
166
|
-
models: LlmModels;
|
|
161
|
+
interface LlmInitConfig extends ILLMInitConfig {
|
|
167
162
|
options?: {
|
|
168
|
-
graph?:
|
|
169
|
-
|
|
163
|
+
graph?: {
|
|
164
|
+
maxOutputTokens?: number;
|
|
165
|
+
temperature?: number;
|
|
166
|
+
};
|
|
167
|
+
embedding?: {
|
|
168
|
+
maxOutputTokens?: number;
|
|
169
|
+
temperature?: number;
|
|
170
|
+
};
|
|
170
171
|
};
|
|
171
172
|
}
|
|
172
173
|
declare namespace Llm {
|
|
173
|
-
function init(config:
|
|
174
|
+
function init(config: ILLMInitConfig): void;
|
|
174
175
|
function isInitialized(): boolean;
|
|
175
176
|
function reset(): void;
|
|
176
|
-
function capabilities():
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
};
|
|
177
|
+
function capabilities(): ILLMCapabilities;
|
|
178
|
+
function getEmbeddingLlm(): EmbeddingModel | undefined;
|
|
179
|
+
function getGraphLlm(): LanguageModel | undefined;
|
|
180
180
|
function embedText(value: string): Promise<Float32Array>;
|
|
181
181
|
function embedTexts(values: string[]): Promise<Float32Array[]>;
|
|
182
|
-
function generateGraph(chunks: string[], entityTypes: ReadonlyArray<{
|
|
183
|
-
type: string;
|
|
184
|
-
rule: string;
|
|
185
|
-
}>, relationTypes: ReadonlyArray<{
|
|
186
|
-
type: string;
|
|
187
|
-
rule: string;
|
|
188
|
-
}>, options?: BuildPromptOptions & LlmOptions): Promise<string>;
|
|
189
|
-
function generate(prompt: string, options?: LlmOptions): Promise<string>;
|
|
190
182
|
const embed: typeof embedText;
|
|
191
183
|
const embedMany: typeof embedTexts;
|
|
192
184
|
}
|
|
@@ -243,6 +235,8 @@ interface RememberResult {
|
|
|
243
235
|
nodeIds?: number[];
|
|
244
236
|
vectorsWritten: number;
|
|
245
237
|
vectorDims: number;
|
|
238
|
+
entitiesExtracted: number;
|
|
239
|
+
relationsExtracted: number;
|
|
246
240
|
}
|
|
247
241
|
interface ForgetParams {
|
|
248
242
|
factId?: string;
|
|
@@ -315,29 +309,37 @@ interface GraphQueryResult {
|
|
|
315
309
|
durationMs: number;
|
|
316
310
|
}
|
|
317
311
|
type StatusParams = {};
|
|
318
|
-
interface StatusResult {
|
|
319
|
-
dbPath: string;
|
|
320
|
-
workspaceDir: string;
|
|
312
|
+
interface StatusResult extends MemoryStatus {
|
|
321
313
|
factsCount: number;
|
|
322
314
|
nodesCount: number;
|
|
323
315
|
edgesCount: number;
|
|
324
316
|
factsByCategory: Record<MemoryCategory, number>;
|
|
325
317
|
ftsAvailable: boolean;
|
|
326
|
-
vectorEnabled: boolean;
|
|
327
|
-
kgScopeEnabled: boolean;
|
|
328
|
-
healthy: boolean;
|
|
329
|
-
meta: Record<string, string>;
|
|
330
318
|
}
|
|
331
319
|
type DoctorParams = {};
|
|
332
|
-
interface DoctorResult {
|
|
333
|
-
|
|
334
|
-
checks: Array<{
|
|
320
|
+
interface DoctorResult extends KnowledgeDoctorResult {
|
|
321
|
+
legacyChecks: Array<{
|
|
335
322
|
name: string;
|
|
336
323
|
passed: boolean;
|
|
337
324
|
message: string;
|
|
338
325
|
details?: Record<string, unknown>;
|
|
339
|
-
severity?: 'error' | 'info';
|
|
326
|
+
severity?: 'error' | 'info' | 'warn' | 'ok';
|
|
340
327
|
}>;
|
|
328
|
+
integrityStats?: {
|
|
329
|
+
memory_facts: number;
|
|
330
|
+
memory_vectors: number;
|
|
331
|
+
embedding_cache: number;
|
|
332
|
+
memory_facts_fts: number;
|
|
333
|
+
nodes: number;
|
|
334
|
+
edges: number;
|
|
335
|
+
meta: number;
|
|
336
|
+
schema_migrations: number;
|
|
337
|
+
};
|
|
338
|
+
backendAvailable?: {
|
|
339
|
+
'better-sqlite3': boolean;
|
|
340
|
+
'node:sqlite': boolean;
|
|
341
|
+
'@tursodatabase/database': boolean;
|
|
342
|
+
};
|
|
341
343
|
}
|
|
342
344
|
interface InitParams {
|
|
343
345
|
dbPath?: string;
|
|
@@ -349,12 +351,33 @@ interface InitResult {
|
|
|
349
351
|
initialized: boolean;
|
|
350
352
|
dbPath: string;
|
|
351
353
|
configPath: string;
|
|
354
|
+
schemaVersion: number;
|
|
352
355
|
workspaceDir: string;
|
|
353
356
|
tablesCreated: number;
|
|
354
357
|
migrationsApplied: number;
|
|
355
358
|
durationMs: number;
|
|
356
359
|
configCreated: boolean;
|
|
357
360
|
}
|
|
361
|
+
interface SyncParams {
|
|
362
|
+
windowDays?: number;
|
|
363
|
+
dryRun?: boolean;
|
|
364
|
+
}
|
|
365
|
+
interface SyncResult {
|
|
366
|
+
generatedCount: number;
|
|
367
|
+
skippedCount: number;
|
|
368
|
+
failedGenerateCount: number;
|
|
369
|
+
archivedCount: number;
|
|
370
|
+
archiveThreshold: string;
|
|
371
|
+
archivedRecords: Array<{
|
|
372
|
+
source: string;
|
|
373
|
+
target: string;
|
|
374
|
+
firstCreatedAt: string;
|
|
375
|
+
firstFactId: string;
|
|
376
|
+
}>;
|
|
377
|
+
windowDays: number;
|
|
378
|
+
dryRun: boolean;
|
|
379
|
+
durationMs: number;
|
|
380
|
+
}
|
|
358
381
|
|
|
359
382
|
declare function recall(ctx: MemoryServiceContext, params: RecallParams): Promise<RecallResult>;
|
|
360
383
|
|
|
@@ -366,11 +389,21 @@ declare function extract(ctx: MemoryServiceContext, params: ExtractParams): Prom
|
|
|
366
389
|
|
|
367
390
|
declare function consolidate(ctx: MemoryServiceContext, params?: ConsolidateParams): Promise<ConsolidateResult>;
|
|
368
391
|
|
|
392
|
+
declare function sync(ctx: MemoryServiceContext, params?: SyncParams): Promise<SyncResult>;
|
|
393
|
+
|
|
369
394
|
declare function graphQuery(ctx: MemoryServiceContext, params: GraphQueryParams): Promise<GraphQueryResult>;
|
|
370
395
|
|
|
371
|
-
|
|
396
|
+
interface StatusOptions {
|
|
397
|
+
skipEmbeddingProbe?: boolean;
|
|
398
|
+
skipLlm?: boolean;
|
|
399
|
+
}
|
|
400
|
+
declare function status(ctx: MemoryServiceContext, _params?: StatusParams, options?: StatusOptions): Promise<StatusResult>;
|
|
372
401
|
|
|
373
|
-
|
|
402
|
+
interface DoctorOptions {
|
|
403
|
+
skipEmbeddingProbe?: boolean;
|
|
404
|
+
skipLlm?: boolean;
|
|
405
|
+
}
|
|
406
|
+
declare function doctor(ctx: MemoryServiceContext, _params?: DoctorParams, options?: DoctorOptions): Promise<DoctorResult>;
|
|
374
407
|
|
|
375
408
|
declare function init(ctx: MemoryServiceContext, params?: InitParams): Promise<InitResult>;
|
|
376
409
|
|
|
@@ -480,7 +513,7 @@ declare function getMemoryDbPath(input?: string | {
|
|
|
480
513
|
}): string;
|
|
481
514
|
|
|
482
515
|
type MigrationDb = SyncSqliteConnection;
|
|
483
|
-
declare const LATEST_SCHEMA_VERSION =
|
|
516
|
+
declare const LATEST_SCHEMA_VERSION = 1;
|
|
484
517
|
interface SchemaMigration {
|
|
485
518
|
id: number;
|
|
486
519
|
description: string;
|
|
@@ -532,6 +565,22 @@ declare class MemoryDatabaseManager {
|
|
|
532
565
|
getSchemaVersion(): number;
|
|
533
566
|
close(): void;
|
|
534
567
|
healthCheck(): boolean;
|
|
568
|
+
checkIntegrity(): {
|
|
569
|
+
issues: Array<{
|
|
570
|
+
severity: 'error' | 'warn' | 'info';
|
|
571
|
+
message: string;
|
|
572
|
+
}>;
|
|
573
|
+
stats: {
|
|
574
|
+
memory_facts: number;
|
|
575
|
+
memory_vectors: number;
|
|
576
|
+
embedding_cache: number;
|
|
577
|
+
memory_facts_fts: number;
|
|
578
|
+
nodes: number;
|
|
579
|
+
edges: number;
|
|
580
|
+
meta: number;
|
|
581
|
+
schema_migrations: number;
|
|
582
|
+
};
|
|
583
|
+
};
|
|
535
584
|
getMeta(key: string): string | null;
|
|
536
585
|
setMeta(key: string, value: string): void;
|
|
537
586
|
}
|
|
@@ -581,4 +630,4 @@ declare function registerAllDefaultHooks(): void;
|
|
|
581
630
|
declare function clearAllHooks(): void;
|
|
582
631
|
declare function dispatchHook(name: HookName, ctx: HookContext): Promise<HookResult>;
|
|
583
632
|
|
|
584
|
-
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels,
|
|
633
|
+
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, type DoctorResult, type EdgeQueryFilter, type ErrorCode, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type HookContext, type HookHandler, type HookName, type HookResult, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MIGRATIONS, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseError, MemoryDatabaseManager, type MemoryEdge, MemoryEmbeddingError, MemoryError, MemoryErrorCode, type MemoryFact, MemoryFileError, type MemoryNode, type MemoryNodeWithEdges, MemoryNotFoundError, type MemoryOp, MemoryPermissionError, type MemoryQuery, type MemoryRecallResult, MemorySearchError, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryValidationError, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RegisteredHook, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, addWord, clearAllHooks, closeTokenizer, consolidate, dispatchHook, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, listHooks, loadCustomDict, readCurrentSchemaVersion, recall, registerAllDefaultHooks, registerHook, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, unregisterHook };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-ARA4LMAI.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-CN6WBJLX.mjs';import {v as v$1,w}from'./chunks/chunk-746FKSL5.mjs';export{u as ALL_OPS,a as GraphStore,t as OP_REGISTRY,n as consolidate,s as doctor,v as executeOp,m as extract,l as forget,p as graphQuery,q as init,b as recall,k as remember,r as status,o as sync}from'./chunks/chunk-746FKSL5.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-JDPZ5U53.mjs';import {f as f$1,j as j$1}from'./chunks/chunk-WDVDYZ25.mjs';export{c as getGlobal,g as getHomeDir,f as getInstance,j as getMemoryDbPath,i as getMemoryDir,h as getXdgData,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-WDVDYZ25.mjs';export{a as Llm}from'./chunks/chunk-6CQMBEIQ.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as m from'jieba-wasm';import {Log,loadTextFile,Filesystem}from'@easbot/utils';import {createHash}from'crypto';var Se=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],d=class extends Error{constructor(t,o,n){super(t,{cause:n});a(this,"code",o);a(this,"cause",n);this.name="MemoryError";}},N=class extends d{constructor(r,t){super(r,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},D=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},T=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},v=class extends d{constructor(r,t){super(r,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},F=class extends d{constructor(r,t){super(r,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},L=class extends d{constructor(r,t){super(r,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},$=class extends d{constructor(r,t){super(r,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},ue=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(ue||{});var s=Log.create({service:"memory.tokenizer"}),c=false,Re=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function Fe(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=Re();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await ke(t);c=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function ke(e){if(!c)throw new Error("Tokenizer not initialized");try{let r=await Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),m.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function xe(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function He(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function Le(e,r,t){if(c)try{m.add_word(e,r,t),s.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){s.warn("Failed to add word",{word:e,error:String(o)});}}function $e(){return c}async function je(){c=false,s.debug("Tokenizer closed");}function ze(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return xe(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Ye(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function u(e){let r=f$1().worktree,t=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:w({agentId:e,dbPath:t,workspaceDir:r})}}var j=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,t=e.extras?.query??"";try{let o=await v$1("recall",{query:t,maxResults:r},u(e.agentId));if(o.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=o.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${o.hits.length}]
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:o instanceof Error?o.message:String(o)}}};var
|
|
3
|
+
`)}`,logLine:`session-start: injected ${o.hits.length} facts into context (agent=${e.agentId})`}}catch(o){return {ok:false,error:o instanceof Error?o.message:String(o)}}};var z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=e.extras?.windowDays??1;try{let t=await v$1("consolidate",{windowDays:r},u(e.agentId));return {ok:!0,logLine:`session-end: total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let t=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),o=e.extras?.topK??3;if(!t)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await v$1("recall",{query:t,maxResults:o,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let h=n.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
|
|
4
4
|
${h.join(`
|
|
5
|
-
`)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var
|
|
6
|
-
`);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await
|
|
5
|
+
`)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var G=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),t=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",o=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,t?`[preview] ${t}`:"",`[errHash] ${r}`].filter(Boolean).join(`
|
|
6
|
+
`);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await v$1("remember",{content:o,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},u(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var g=Log.create({service:"memory.hooks"}),f=new Map;function y(e,r){let t={name:e,handler:r,registeredAt:new Date().toISOString()},o=f.get(e);f.set(e,t),o?g.info("Hook overwritten",{name:e,prevRegisteredAt:o.registeredAt,newRegisteredAt:t.registeredAt}):g.info("Hook registered",{name:e,registeredAt:t.registeredAt});}function be(e){return f.delete(e)}function Ie(){return Array.from(f.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function Me(){y("session-start",j),y("session-end",z),y("pre-compact",Y),y("post-tool-failure",G);}function _e(){f.clear(),g.debug("All hooks cleared");}async function Oe(e,r){let t=f.get(e);if(!t)return g.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let o=await t.handler(r);return o.ok?o.logLine&&g.debug("dispatchHook: ok",{name:e,logLine:o.logLine}):g.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:o.error}),o}catch(o){let n=o instanceof Error?o.message:String(o);return g.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}export{Se as MEMORY_CATEGORIES,v as MemoryDatabaseError,$ as MemoryEmbeddingError,d as MemoryError,ue as MemoryErrorCode,F as MemoryFileError,D as MemoryNotFoundError,T as MemoryPermissionError,L as MemorySearchError,N as MemoryValidationError,Le as addWord,_e as clearAllHooks,je as closeTokenizer,Oe as dispatchHook,Fe as initTokenizer,$e as isInitialized,Ie as listHooks,ke as loadCustomDict,Me as registerAllDefaultHooks,y as registerHook,ze as toFtsTokens,Ye as toFtsTokensForSearch,xe as tokenize,He as tokenizeForSearch,be as unregisterHook};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easbot/memory",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.19",
|
|
4
4
|
"description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -54,13 +54,14 @@
|
|
|
54
54
|
"better-sqlite3": "^13.0.3",
|
|
55
55
|
"jieba-wasm": "^2.4.0",
|
|
56
56
|
"xdg-basedir": "^5.1.0",
|
|
57
|
-
"@easbot/database": "0.3.
|
|
58
|
-
"@easbot/mcp": "0.3.
|
|
59
|
-
"@easbot/terminal": "0.3.
|
|
60
|
-
"@easbot/utils": "0.3.
|
|
61
|
-
"@easbot/types": "0.3.
|
|
62
|
-
"@easbot/local-model-sdk": "0.3.
|
|
63
|
-
"@easbot/
|
|
57
|
+
"@easbot/database": "0.3.19",
|
|
58
|
+
"@easbot/mcp": "0.3.19",
|
|
59
|
+
"@easbot/terminal": "0.3.19",
|
|
60
|
+
"@easbot/utils": "0.3.19",
|
|
61
|
+
"@easbot/types": "0.3.19",
|
|
62
|
+
"@easbot/local-model-sdk": "0.3.19",
|
|
63
|
+
"@easbot/llm": "0.3.19",
|
|
64
|
+
"@easbot/ollama-sdk": "0.3.19"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
66
67
|
"@types/node": "^25.9.5",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var f={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var L=f.languages,C=L.filter(e=>e.supported).map(e=>e.value),a={defaultLocale:"zh-CN",locales:C},m={},p=(e,t)=>{let r=m[e]||{translation:{}};return m[e]={translation:{...r.translation,...t.translation}},m[e]},u=(e=a.defaultLocale)=>(m[e]||p(e,{translation:{}}),{locale:e,resources:m[e]||{translation:{}}});var S={translation:{"cli.cmd.init.description":"\u521D\u59CB\u5316\u8BB0\u5FC6 workspace\uFF08.easbot/memory.db\uFF09","cli.cmd.recall.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF\uFF09\u67E5\u8BE2\u8BB0\u5FC6","cli.cmd.remember.description":"\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u81EA\u5E26 dedup + \u77E5\u8BC6\u56FE\u8C31\u62BD\u53D6\uFF09","cli.cmd.forget.description":"\u5220\u9664\u8BB0\u5FC6\uFF08factId / category / \u65F6\u95F4\u7A97 / \u8BD5\u8FD0\u884C\uFF09","cli.cmd.extract.description":"\u4ECE session \u62BD\u53D6 facts\uFF08sessionId + lastN\uFF09","cli.cmd.consolidate.description":"\u8FD0\u884C consolidation \u6D41\u6C34\u7EBF\uFF08extract \u2192 dedup \u2192 archive\uFF09","cli.cmd.graph.description":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08nodes / edges / neighbors\uFF0Cscope \u4E09\u6863\uFF09","cli.cmd.status.description":"\u663E\u793A\u8BB0\u5FC6\u72B6\u6001 / \u6570\u636E\u5E93\u7EDF\u8BA1 / \u5404\u7C7B\u522B\u8BA1\u6570","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / schema / \u9501\uFF09","cli.cmd.config.description":"\u67E5\u770B / \u6821\u9A8C\u8BB0\u5FC6\u914D\u7F6E\uFF08dry-read\uFF09","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 9 \u4E2A memory \u5DE5\u5177\uFF09","memory.recall.empty":"\uFF08\u65E0\u5339\u914D\u8BB0\u5FC6\uFF09","memory.recall.summary":"\u5171\u5339\u914D {{total}} \u6761\u8BB0\u5FC6\uFF1A","memory.recall.item":" - {{id}} [{{category}}/\u91CD\u8981\u6027={{importance}}/\u5206\u6570={{score}}] {{content}}","memory.forget.empty":"\uFF08\u672A\u547D\u4E2D\u53EF\u5220\u9664\u7684\u8BB0\u5F55\uFF09\uFF09","memory.forget.summary":"\u5220\u9664 {{deletedCount}} \u6761\u8BB0\u5FC6\uFF08dryRun={{dryRun}}\uFF09\uFF1A","memory.forget.item":" - {{id}}","memory.remember.summary":"\u8BB0\u5FC6\u5DF2\u5199\u5165\uFF1A","memory.remember.item":" - id={{id}} \u7C7B\u522B={{category}} \u91CD\u8981\u6027={{importance}}","memory.consolidate.summary":"consolidation \u5B8C\u6210\uFF1A","memory.consolidate.item":" - \u603B\u8BA1 {{totalFacts}} \u53BB\u91CD {{dedupedCount}} \u5F52\u6863 {{archivedCount}}","memory.status.empty":"\uFF08\u6682\u65E0\u6570\u636E\uFF09","memory.status.summary":"\u8BB0\u5FC6\u72B6\u6001\uFF1A","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"\uFF08\u65E0\u68C0\u67E5\u9879\uFF09","memory.doctor.summary":"\u5065\u5EB7\u68C0\u67E5\uFF1A{{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"\uFF08\u65E0\u8282\u70B9\u547D\u4E2D\uFF09","memory.graph.summary":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08\u5171 {{totalNodes}} \u8282\u70B9\uFF09\uFF1A","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"\u62BD\u53D6 {{extractedCount}} \u6761 facts\uFF1A","memory.extract.item":" - {{id}}","memory.init.summary":"\u521D\u59CB\u5316\u5B8C\u6210\uFF1A","memory.init.item":" - db={{dbPath}} \u8FC1\u79FB={{migrationsApplied}} \u8868={{tablesCreated}}"}},h=S;var v={translation:{"cli.cmd.init.description":"Initialize memory workspace (.easbot/memory.db)","cli.cmd.recall.description":"Hybrid search (FTS + vector) over memory facts","cli.cmd.remember.description":"Persist a new memory fact (with dedup + KG extraction)","cli.cmd.forget.description":"Delete memory facts (factId / category / timeRange / dryRun)","cli.cmd.extract.description":"Extract facts from a session (sessionId + lastN)","cli.cmd.consolidate.description":"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)","cli.cmd.graph.description":"KG query (nodes / edges / neighbors with scope \u4E09\u6863)","cli.cmd.status.description":"Show memory state / db stats / facts by category","cli.cmd.doctor.description":"Run health checks (backend, FTS, schema, lock)","cli.cmd.config.description":"Show / validate memory configuration (dry-read)","cli.cmd.mcp.description":"Start stdio MCP server (exposes 9 memory tools)","memory.recall.empty":"(no matching facts)","memory.recall.summary":"Found {{total}} fact(s):","memory.recall.item":" - {{id}} [{{category}}/imp={{importance}}/score={{score}}] {{content}}","memory.forget.empty":"(no records to delete)","memory.forget.summary":"Deleted {{deletedCount}} fact(s) (dryRun={{dryRun}}):","memory.forget.item":" - {{id}}","memory.remember.summary":"Memory persisted:","memory.remember.item":" - id={{id}} category={{category}} importance={{importance}}","memory.consolidate.summary":"Consolidation complete:","memory.consolidate.item":" - total {{totalFacts}} deduped {{dedupedCount}} archived {{archivedCount}}","memory.status.empty":"(no data)","memory.status.summary":"Memory status:","memory.status.item":" - {{key}}: {{value}}","memory.doctor.empty":"(no checks)","memory.doctor.summary":"Health check: {{status}}","memory.doctor.item":" - {{name}}: {{message}}","memory.graph.empty":"(no nodes matched)","memory.graph.summary":"KG query ({{totalNodes}} node(s)):","memory.graph.item":" - {{id}} {{name}} [{{type}}]","memory.extract.summary":"Extracted {{extractedCount}} fact(s):","memory.extract.item":" - {{id}}","memory.init.summary":"Initialization complete:","memory.init.item":" - db={{dbPath}} migrations={{migrationsApplied}} tables={{tablesCreated}}"}},x=v;var w=()=>{u("zh-CN"),u("en-US"),p("zh-CN",h),p("en-US",x);};w();var g=new Map;var y=new Map;var k=e=>{if(y.has(e))return y.get(e);let t=/{{\s*(\w+)\s*}}/g,r=[],o;for(;(o=t.exec(e))!==null;){let n=o[1];n&&!r.includes(n)&&r.push(n);}let i=new RegExp("{{\\s*("+r.join("|")+")\\s*}}","g"),s={keys:r,regex:i};return y.set(e,s),s},R=(e,t)=>{if(!e||typeof e!="string")return "";if(!t||Object.keys(t).length===0)return e;let{regex:r,keys:o}=k(e);return o.length===0||!o.some(s=>s in t)?e:e.replace(r,(s,n)=>{let c=t[n];return c==null?"":String(c)})},I=e=>{if(e&&a.locales.includes(e))return e;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let r=t.replace(/_/g,"-");if(a.locales.includes(r))return r;let o=r.split("-")[0];if(o==="zh")return "zh-CN";if(o==="en")return "en-US"}return a.defaultLocale},T=e=>{if(!g.has(e)){let{resources:t}=u(e);g.set(e,t);}return g.get(e)},N=(e,t={})=>{let r=I(t.locale),i=T(r)?.translation[e];if(i&&typeof i=="string"){let s=R(i,t.vars);return s!=null?String(s):String(e)}if(r!==a.defaultLocale){let n=T(a.defaultLocale)?.translation[e];if(n&&typeof n=="string"){let c=R(n,t.vars);return c!=null?String(c):String(e)}}return String(t.fallback??e)},B=N;export{B as a};
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var d=Log.create({service:"memory-schema-migrations"}),T=2,S=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
agent_id TEXT NOT NULL,
|
|
4
|
-
session_id TEXT,
|
|
5
|
-
msg_id TEXT,
|
|
6
|
-
parent_msg_id TEXT,
|
|
7
|
-
content TEXT NOT NULL,
|
|
8
|
-
category TEXT NOT NULL,
|
|
9
|
-
importance INTEGER NOT NULL CHECK(importance >= 1 AND importance <= 10),
|
|
10
|
-
source TEXT NOT NULL CHECK(source IN ('session_self_write', 'historical')),
|
|
11
|
-
tags TEXT,
|
|
12
|
-
node_ids TEXT,
|
|
13
|
-
file_path TEXT,
|
|
14
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
15
|
-
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
16
|
-
UNIQUE(session_id, msg_id)
|
|
17
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)","CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)",`CREATE TABLE IF NOT EXISTS memory_vectors (
|
|
18
|
-
fact_id TEXT PRIMARY KEY,
|
|
19
|
-
embedding BLOB NOT NULL,
|
|
20
|
-
FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
|
|
21
|
-
)`,`CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
22
|
-
content_hash TEXT PRIMARY KEY,
|
|
23
|
-
embedding BLOB NOT NULL,
|
|
24
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
-
)`,`CREATE VIRTUAL TABLE IF NOT EXISTS memory_facts_fts USING fts5(
|
|
26
|
-
fact_id UNINDEXED,
|
|
27
|
-
agent_id UNINDEXED,
|
|
28
|
-
content,
|
|
29
|
-
tags,
|
|
30
|
-
tokenize='porter unicode61'
|
|
31
|
-
)`,`CREATE TABLE IF NOT EXISTS nodes (
|
|
32
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
33
|
-
name TEXT NOT NULL,
|
|
34
|
-
type TEXT NOT NULL,
|
|
35
|
-
properties TEXT,
|
|
36
|
-
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
37
|
-
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
38
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS edges (
|
|
39
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
-
source INTEGER NOT NULL,
|
|
41
|
-
target INTEGER NOT NULL,
|
|
42
|
-
relation TEXT NOT NULL,
|
|
43
|
-
properties TEXT,
|
|
44
|
-
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
45
|
-
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
46
|
-
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
47
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
|
|
48
|
-
key TEXT PRIMARY KEY,
|
|
49
|
-
value TEXT
|
|
50
|
-
)`]},{id:2,description:"v2: \u7ED9 nodes \u8868\u52A0 owner_agent_id \u5217 + \u7D22\u5F15\uFF08ADR 0056 KG scope \u4E09\u6863\uFF0Cper-agent \u9694\u79BB\uFF09",up:["ALTER TABLE nodes ADD COLUMN owner_agent_id TEXT","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)"]}];function m(n,e=T,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
51
|
-
id INTEGER PRIMARY KEY,
|
|
52
|
-
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
53
|
-
)`);let i=n.prepare("SELECT id FROM schema_migrations").all(),a=new Set(i.map(t=>t.id)),s={applied:[],pending:[],errors:[],currentVersion:i.length===0?0:Math.max(...i.map(t=>t.id)),targetVersion:e};for(let t of S){if(t.id>e)break;if(a.has(t.id)){s.pending.push(t.id);continue}if(r.dryRun){s.applied.push(t.id);continue}try{_(n,t.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(t.id),a.add(t.id),s.applied.push(t.id),d.info("migration applied",{id:t.id,description:t.description});}catch(E){let l=E instanceof Error?E.message:String(E),h=t.up[0]??"";s.errors.push({migrationId:t.id,sql:h,error:l}),d.warn("migration step failed",{id:t.id,error:l,sqlCount:t.up.length});}}return s}function _(n,e){for(let r of e)try{n.exec(r);}catch(i){let a=i instanceof Error?i.message:String(i);if(R(a)){d.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw i}}function R(n){return /duplicate column name/i.test(n)}function g(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var c=Log.create({service:"memory-database"}),p=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw c.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){c.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=m(this.db,T);if(e.errors.length>0){let r=e.errors.map(i=>`migration ${i.migrationId}: ${i.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e);return r?i.all(...r):i.all()}catch(i){throw new Error(`Query failed: ${i.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e),a=r?i.run(...r):i.run();return {lastID:Number(a.lastInsertRowid),changes:a.changes}}catch(i){throw new Error(`Write failed: ${i.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return g(this.db)}close(){if(this.db){try{this.db.close();}catch(e){c.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{T as a,S as b,m as c,g as d,p as e};
|