@easbot/memory 0.3.36 → 0.3.39
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 +207 -49
- package/README.md +86 -18
- package/dist/chunks/{chunk-YUWHNHAY.mjs → chunk-7RA6RQGC.mjs} +1 -1
- package/dist/chunks/{chunk-FZ3RTYIJ.mjs → chunk-HTBMVZF7.mjs} +11 -11
- package/dist/chunks/{chunk-AEAMQDNV.mjs → chunk-IPUFIEKC.mjs} +6 -6
- package/dist/chunks/{chunk-QAEIHJOF.cjs → chunk-KWSPFECY.cjs} +5 -5
- package/dist/chunks/{chunk-4G4FSAFY.cjs → chunk-SAGLLJTU.cjs} +1 -1
- package/dist/chunks/{chunk-ISYAE6B7.cjs → chunk-SEKBFDEC.cjs} +12 -12
- package/dist/chunks/cli-handler-HUTXCEXM.cjs +1 -0
- package/dist/chunks/cli-handler-TUILJT7W.mjs +1 -0
- package/dist/chunks/{consolidate-OOAMW7XW.mjs → consolidate-JMXYI3NF.mjs} +1 -1
- package/dist/chunks/{consolidate-IKQVVWIQ.cjs → consolidate-TYCVXZFF.cjs} +1 -1
- package/dist/chunks/{doctor-ZGHICE2Q.mjs → doctor-3W3MVUZF.mjs} +1 -1
- package/dist/chunks/{doctor-N6HHFR6Y.cjs → doctor-GRS3CZWD.cjs} +1 -1
- package/dist/chunks/{extract-7DQ6OV34.cjs → extract-IKAJ3GHK.cjs} +1 -1
- package/dist/chunks/{extract-AJY2ETKE.mjs → extract-XT6HBENH.mjs} +1 -1
- package/dist/chunks/{forget-NIBBY6FG.mjs → forget-2OAYPXCB.mjs} +1 -1
- package/dist/chunks/{forget-4KGLTQ5Q.cjs → forget-GXJPG4P4.cjs} +1 -1
- package/dist/chunks/{graph-4K56ZAVL.mjs → graph-2AL2R3KO.mjs} +1 -1
- package/dist/chunks/{graph-OG23VZZM.cjs → graph-LJYAUA3C.cjs} +1 -1
- package/dist/chunks/{init-HWR4SD6N.mjs → init-M5CEJUEY.mjs} +1 -1
- package/dist/chunks/{init-UQTPANNI.cjs → init-OFCTBJGM.cjs} +1 -1
- package/dist/chunks/{mcp-ONIMP7FB.cjs → mcp-OKBJHIXH.cjs} +1 -1
- package/dist/chunks/{mcp-ZWZYH52C.mjs → mcp-OWOAIP2Z.mjs} +1 -1
- package/dist/chunks/{recall-KZRYTTWA.cjs → recall-K3DU2S23.cjs} +1 -1
- package/dist/chunks/{recall-BRXHJPR4.mjs → recall-ZEDO4S5I.mjs} +1 -1
- package/dist/chunks/{remember-GLOJH457.cjs → remember-FR7JL2ZC.cjs} +1 -1
- package/dist/chunks/{remember-3XSYCWKK.mjs → remember-TEAHLG4E.mjs} +1 -1
- package/dist/chunks/{status-SW5BUHJ3.mjs → status-BGRJ224S.mjs} +1 -1
- package/dist/chunks/{status-POX2GWSQ.cjs → status-KLQSENQX.cjs} +1 -1
- package/dist/chunks/stdio-server-EEWPIACW.mjs +1 -0
- package/dist/chunks/{stdio-server-W52CMVJO.cjs → stdio-server-ME6A6STR.cjs} +1 -1
- package/dist/chunks/{sync-EE4ZD3WB.mjs → sync-2D3E4DPE.mjs} +1 -1
- package/dist/chunks/{sync-I423W5G7.cjs → sync-QZCZXNNN.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +38 -8
- package/dist/index.d.cts +179 -16
- package/dist/index.d.ts +179 -16
- package/dist/index.mjs +38 -8
- package/package.json +13 -11
- package/dist/assets/txt/src/plugin/tool/description.txt +0 -12
- package/dist/chunks/cli-handler-JHSDGJHK.mjs +0 -1
- package/dist/chunks/cli-handler-USK4CPAU.cjs +0 -1
- package/dist/chunks/stdio-server-3A3H4YJ7.mjs +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as _easbot_types from '@easbot/types';
|
|
|
2
2
|
import { KnowledgeSearchOptions, MemoryKnowledgeConfigWithModels, KnowledgeDoctorResult, MemoryStatus, IGlobal, IInstance } from '@easbot/types';
|
|
3
3
|
export { GRAPH_ENTITY_TYPE_DEFINITIONS, GRAPH_RELATION_TYPE_DEFINITIONS } from '@easbot/types';
|
|
4
4
|
import { ILLMInitConfig, ILLMCapabilities, EmbeddingModelRef, LanguageModelRef, ExtractedEntity, ExtractedRelation } from '@easbot/llm';
|
|
5
|
-
import
|
|
5
|
+
import { z, ZodType } from 'zod';
|
|
6
6
|
import { StdioServerConfig } from '@easbot/mcp';
|
|
7
7
|
import { SyncSqliteConnection } from '@easbot/database';
|
|
8
8
|
import { Plugin, PluginManifest, HookMatcher, HookHandler, HookInfo } from '@easbot/plugin';
|
|
@@ -446,7 +446,7 @@ interface OpHandlerContext {
|
|
|
446
446
|
remote?: boolean;
|
|
447
447
|
config?: unknown;
|
|
448
448
|
}
|
|
449
|
-
interface MemoryOp<TSchema extends
|
|
449
|
+
interface MemoryOp<TSchema extends ZodType | undefined = undefined, TResult = unknown> {
|
|
450
450
|
name: string;
|
|
451
451
|
scope: OpScope;
|
|
452
452
|
schema?: TSchema;
|
|
@@ -638,12 +638,12 @@ declare namespace MemoryCache {
|
|
|
638
638
|
declare const MemoryPlugin: Plugin;
|
|
639
639
|
|
|
640
640
|
declare const MEMORY_PLUGIN_ID = "memory";
|
|
641
|
-
declare const MEMORY_PLUGIN_VERSION = "0.3.
|
|
641
|
+
declare const MEMORY_PLUGIN_VERSION = "0.3.39";
|
|
642
642
|
declare const MEMORY_PLUGIN_MANIFEST: PluginManifest;
|
|
643
643
|
|
|
644
644
|
declare function createMemoryHookMatchers(): HookMatcher[];
|
|
645
645
|
|
|
646
|
-
declare const MEMORY_HOOK_EVENTS: readonly ["context.
|
|
646
|
+
declare const MEMORY_HOOK_EVENTS: readonly ["context.collect", "session.compacting", "tool.failure", "loop.end"];
|
|
647
647
|
type MemoryHookEvent = (typeof MEMORY_HOOK_EVENTS)[number];
|
|
648
648
|
type MemoryHookHandler = HookHandler<unknown>;
|
|
649
649
|
|
|
@@ -657,19 +657,182 @@ declare const MemoryPluginHook: HookInfo;
|
|
|
657
657
|
|
|
658
658
|
declare const MEMORY_TOOL_ID = "memory";
|
|
659
659
|
declare const MEMORY_TOOL_OPS: readonly ["recall", "remember", "update", "forget", "extract", "graph_query", "status"];
|
|
660
|
+
type MemoryToolOperation = (typeof MEMORY_TOOL_OPS)[number];
|
|
661
|
+
declare const MEMORY_TOOL_ARGS: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
662
|
+
operation: z.ZodLiteral<"recall">;
|
|
663
|
+
query: z.ZodString;
|
|
664
|
+
limit: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
665
|
+
category: z.ZodOptional<z.ZodEnum<{
|
|
666
|
+
user_preference: "user_preference";
|
|
667
|
+
task_context: "task_context";
|
|
668
|
+
technical_fact: "technical_fact";
|
|
669
|
+
decision: "decision";
|
|
670
|
+
relationship: "relationship";
|
|
671
|
+
reminder: "reminder";
|
|
672
|
+
error_pattern: "error_pattern";
|
|
673
|
+
workflow: "workflow";
|
|
674
|
+
exploration_finding: "exploration_finding";
|
|
675
|
+
experience_summary: "experience_summary";
|
|
676
|
+
tool_usage: "tool_usage";
|
|
677
|
+
skill_creation: "skill_creation";
|
|
678
|
+
test: "test";
|
|
679
|
+
other: "other";
|
|
680
|
+
}>>;
|
|
681
|
+
minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
682
|
+
maxEdgesPerNode: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
683
|
+
includeGraph: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
684
|
+
includeShared: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
685
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
686
|
+
operation: z.ZodLiteral<"remember">;
|
|
687
|
+
content: z.ZodString;
|
|
688
|
+
category: z.ZodEnum<{
|
|
689
|
+
user_preference: "user_preference";
|
|
690
|
+
task_context: "task_context";
|
|
691
|
+
technical_fact: "technical_fact";
|
|
692
|
+
decision: "decision";
|
|
693
|
+
relationship: "relationship";
|
|
694
|
+
reminder: "reminder";
|
|
695
|
+
error_pattern: "error_pattern";
|
|
696
|
+
workflow: "workflow";
|
|
697
|
+
exploration_finding: "exploration_finding";
|
|
698
|
+
experience_summary: "experience_summary";
|
|
699
|
+
tool_usage: "tool_usage";
|
|
700
|
+
skill_creation: "skill_creation";
|
|
701
|
+
test: "test";
|
|
702
|
+
other: "other";
|
|
703
|
+
}>;
|
|
704
|
+
importance: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>;
|
|
705
|
+
tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
|
|
706
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
707
|
+
operation: z.ZodLiteral<"update">;
|
|
708
|
+
factId: z.ZodString;
|
|
709
|
+
content: z.ZodOptional<z.ZodString>;
|
|
710
|
+
category: z.ZodOptional<z.ZodEnum<{
|
|
711
|
+
user_preference: "user_preference";
|
|
712
|
+
task_context: "task_context";
|
|
713
|
+
technical_fact: "technical_fact";
|
|
714
|
+
decision: "decision";
|
|
715
|
+
relationship: "relationship";
|
|
716
|
+
reminder: "reminder";
|
|
717
|
+
error_pattern: "error_pattern";
|
|
718
|
+
workflow: "workflow";
|
|
719
|
+
exploration_finding: "exploration_finding";
|
|
720
|
+
experience_summary: "experience_summary";
|
|
721
|
+
tool_usage: "tool_usage";
|
|
722
|
+
skill_creation: "skill_creation";
|
|
723
|
+
test: "test";
|
|
724
|
+
other: "other";
|
|
725
|
+
}>>;
|
|
726
|
+
importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
727
|
+
tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
|
|
728
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
729
|
+
operation: z.ZodLiteral<"forget">;
|
|
730
|
+
factId: z.ZodString;
|
|
731
|
+
dryRun: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
732
|
+
force: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
733
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
734
|
+
operation: z.ZodLiteral<"extract">;
|
|
735
|
+
lastN: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
736
|
+
fromMessageId: z.ZodOptional<z.ZodString>;
|
|
737
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
738
|
+
operation: z.ZodLiteral<"graph_query">;
|
|
739
|
+
query: z.ZodString;
|
|
740
|
+
maxDepth: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
741
|
+
maxNodes: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
742
|
+
maxEdgesPerNode: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
743
|
+
relation: z.ZodOptional<z.ZodString>;
|
|
744
|
+
type: z.ZodOptional<z.ZodString>;
|
|
745
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
746
|
+
operation: z.ZodLiteral<"status">;
|
|
747
|
+
}, z.core.$strict>], "operation">;
|
|
660
748
|
declare const MemoryTool: _easbot_types.ToolDefinition & {
|
|
661
|
-
args: {
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
749
|
+
args: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
750
|
+
operation: z.ZodLiteral<"recall">;
|
|
751
|
+
query: z.ZodString;
|
|
752
|
+
limit: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
753
|
+
category: z.ZodOptional<z.ZodEnum<{
|
|
754
|
+
user_preference: "user_preference";
|
|
755
|
+
task_context: "task_context";
|
|
756
|
+
technical_fact: "technical_fact";
|
|
757
|
+
decision: "decision";
|
|
758
|
+
relationship: "relationship";
|
|
759
|
+
reminder: "reminder";
|
|
760
|
+
error_pattern: "error_pattern";
|
|
761
|
+
workflow: "workflow";
|
|
762
|
+
exploration_finding: "exploration_finding";
|
|
763
|
+
experience_summary: "experience_summary";
|
|
764
|
+
tool_usage: "tool_usage";
|
|
765
|
+
skill_creation: "skill_creation";
|
|
766
|
+
test: "test";
|
|
767
|
+
other: "other";
|
|
768
|
+
}>>;
|
|
769
|
+
minImportance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
770
|
+
maxEdgesPerNode: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
771
|
+
includeGraph: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
772
|
+
includeShared: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
773
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
774
|
+
operation: z.ZodLiteral<"remember">;
|
|
775
|
+
content: z.ZodString;
|
|
776
|
+
category: z.ZodEnum<{
|
|
777
|
+
user_preference: "user_preference";
|
|
778
|
+
task_context: "task_context";
|
|
779
|
+
technical_fact: "technical_fact";
|
|
780
|
+
decision: "decision";
|
|
781
|
+
relationship: "relationship";
|
|
782
|
+
reminder: "reminder";
|
|
783
|
+
error_pattern: "error_pattern";
|
|
784
|
+
workflow: "workflow";
|
|
785
|
+
exploration_finding: "exploration_finding";
|
|
786
|
+
experience_summary: "experience_summary";
|
|
787
|
+
tool_usage: "tool_usage";
|
|
788
|
+
skill_creation: "skill_creation";
|
|
789
|
+
test: "test";
|
|
790
|
+
other: "other";
|
|
670
791
|
}>;
|
|
671
|
-
|
|
672
|
-
|
|
792
|
+
importance: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>;
|
|
793
|
+
tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
|
|
794
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
795
|
+
operation: z.ZodLiteral<"update">;
|
|
796
|
+
factId: z.ZodString;
|
|
797
|
+
content: z.ZodOptional<z.ZodString>;
|
|
798
|
+
category: z.ZodOptional<z.ZodEnum<{
|
|
799
|
+
user_preference: "user_preference";
|
|
800
|
+
task_context: "task_context";
|
|
801
|
+
technical_fact: "technical_fact";
|
|
802
|
+
decision: "decision";
|
|
803
|
+
relationship: "relationship";
|
|
804
|
+
reminder: "reminder";
|
|
805
|
+
error_pattern: "error_pattern";
|
|
806
|
+
workflow: "workflow";
|
|
807
|
+
exploration_finding: "exploration_finding";
|
|
808
|
+
experience_summary: "experience_summary";
|
|
809
|
+
tool_usage: "tool_usage";
|
|
810
|
+
skill_creation: "skill_creation";
|
|
811
|
+
test: "test";
|
|
812
|
+
other: "other";
|
|
813
|
+
}>>;
|
|
814
|
+
importance: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
815
|
+
tags: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodString]>, z.ZodTransform<string[], string | string[]>>, z.ZodArray<z.ZodString>>>;
|
|
816
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
817
|
+
operation: z.ZodLiteral<"forget">;
|
|
818
|
+
factId: z.ZodString;
|
|
819
|
+
dryRun: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
820
|
+
force: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
821
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
822
|
+
operation: z.ZodLiteral<"extract">;
|
|
823
|
+
lastN: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
824
|
+
fromMessageId: z.ZodOptional<z.ZodString>;
|
|
825
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
826
|
+
operation: z.ZodLiteral<"graph_query">;
|
|
827
|
+
query: z.ZodString;
|
|
828
|
+
maxDepth: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
829
|
+
maxNodes: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
830
|
+
maxEdgesPerNode: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
831
|
+
relation: z.ZodOptional<z.ZodString>;
|
|
832
|
+
type: z.ZodOptional<z.ZodString>;
|
|
833
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
834
|
+
operation: z.ZodLiteral<"status">;
|
|
835
|
+
}, z.core.$strict>], "operation">;
|
|
673
836
|
};
|
|
674
837
|
|
|
675
|
-
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_HOOK_BINDINGS, MEMORY_HOOK_EVENTS, MEMORY_JSON_REL_PATH, MEMORY_PLUGIN_ID, MEMORY_PLUGIN_MANIFEST, MEMORY_PLUGIN_VERSION, MEMORY_TOOL_ID, MEMORY_TOOL_OPS, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, MemoryPlugin, MemoryPlugin as MemoryPluginEntry, MemoryPluginHook, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryTool, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, createMemoryHookMatchers, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
|
|
838
|
+
export { ALL_OPS, type ArchiveRecord, type ArchiveResult, COMMANDS_HELP, type CommandHelp, type ConsolidateParams, type ConsolidateResult, DEFAULT_MEMORY_JSON, type DoctorResult, type EdgeQueryFilter, type ExtractParams, type ExtractResult, type ForgetParams, type ForgetResult, type GraphQueryParams, type GraphQueryResult, GraphStore, type InitParams, type InitResult, type KGScope, LATEST_SCHEMA_VERSION, Llm, type LlmInitConfig, type LlmModels, MEMORY_CATEGORIES, MEMORY_HOOK_BINDINGS, MEMORY_HOOK_EVENTS, MEMORY_JSON_REL_PATH, MEMORY_PLUGIN_ID, MEMORY_PLUGIN_MANIFEST, MEMORY_PLUGIN_VERSION, MEMORY_TOOL_ARGS, MEMORY_TOOL_ID, MEMORY_TOOL_OPS, MIGRATIONS, MemoryCache, type MemoryCategory, type MemoryCliDeps, type MemoryCliResult, MemoryDatabaseManager, type MemoryEdge, type MemoryFact, type MemoryJson, MemoryJsonSchema, type MemoryNode, type MemoryNodeWithEdges, type MemoryOp, MemoryPlugin, MemoryPlugin as MemoryPluginEntry, MemoryPluginHook, type MemoryQuery, type MemoryRecallResult, type MemorySource, MemoryStdioServer, type MemorySystemConfig, MemoryTool, type MemoryToolOperation, type MemoryVector, type NodeQueryFilter, OP_REGISTRY, type OpAnnotations, type OpHandlerContext, type OpScope, type RecallParams, type RecallResult, type RememberParams, type RememberResult, type StatusResult, type SyncParams, type SyncResult, type UpdateParams, type UpdateResult, addWord, closeTokenizer, consolidate, createMemoryHookMatchers, doctor, executeOp, extract, forget, getGlobal, getHomeDir, getInstance, getMemoryDbPath, getMemoryDir, getXdgData, graphQuery, handleMemoryCli, init, initTokenizer, isInitialized, loadCustomDict, readCurrentSchemaVersion, recall, remember, renderBanner, renderHelp, renderOperationMarkdown, resetGlobalAdapter, resetInstanceAdapter, runMigrations, setGlobalAdapter, setInstanceAdapter, status, sync, toFtsTokens, toFtsTokensForSearch, tokenize, tokenizeForSearch, update };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,38 @@
|
|
|
1
|
-
import {a}from'./chunks/chunk-
|
|
2
|
-
${
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
${
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import {a}from'./chunks/chunk-HTBMVZF7.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-HTBMVZF7.mjs';import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-7RA6RQGC.mjs';import {A as A$1,z as z$1}from'./chunks/chunk-IPUFIEKC.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,v as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,w as init,b as recall,n as remember,u as status,s as sync,o as update}from'./chunks/chunk-IPUFIEKC.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-YJLHS7JB.mjs';import {a as a$1}from'./chunks/chunk-HH7EA2UE.mjs';export{a as Llm}from'./chunks/chunk-HH7EA2UE.mjs';import {a as a$2}from'./chunks/chunk-AJDMZTCQ.mjs';import {d}from'./chunks/chunk-SE3F5YQE.mjs';export{b as DEFAULT_MEMORY_JSON,c as MEMORY_JSON_REL_PATH,d as MemoryCache,a as MemoryJsonSchema}from'./chunks/chunk-SE3F5YQE.mjs';import {j as j$1,f}from'./chunks/chunk-HX3TV7FD.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-HX3TV7FD.mjs';import'./chunks/chunk-S4DPVKMV.mjs';import {DefaultContextMode}from'@easbot/types';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as h from'jieba-wasm';import {Log,loadTextFile,Schema,Locale,ServiceError,ServiceErrorBus,errorMeta,TruncateContent,Identifier,NameErrors,Markdown,Token,Filesystem}from'@easbot/utils';import {HookEvent,createTool}from'@easbot/plugin';import {createHash}from'crypto';import {Agent,Provider,LanguageProvider}from'@easbot/llm';import {stepCountIs}from'ai';import {existsSync}from'fs';import {renderKnowledgeStatus}from'@easbot/terminal';import {z}from'zod';var ar=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];var y=Log.create({service:"memory.tokenizer"}),I=false,ft=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function gr(e){if(!I)try{y.debug("Initializing jieba tokenizer");let r=ft();if(h.with_dict(r),y.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let t of e.dictPath)await yt(t);I=!0,y.debug("Jieba tokenizer initialized successfully");}catch(r){y.error("Failed to initialize jieba tokenizer",{error:errorMeta(r)}),y.warn("Using fallback tokenization (space-based)");}}async function yt(e){if(!I)throw new a$2.TokenizerNotInitializedError({message:"Tokenizer not initialized"});try{let r=await Filesystem.readText(e);y.debug("Loading custom dictionary",{dictPath:e}),h.with_dict(r),y.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){y.warn("Failed to load custom dictionary",{dictPath:e,error:errorMeta(r)});}}function Mt(e){if(!I)return e.split(/\s+/).filter(Boolean);try{return h.cut(e)}catch(r){return y.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function xt(e){if(!I)return e.split(/\s+/).filter(Boolean);try{return h.cut_for_search(e)}catch(r){return y.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean)}}function fr(e,r,t){if(I)try{h.add_word(e,r,t),y.debug("Word added to dictionary",{word:e,freq:r,tag:t});}catch(o){y.warn("Failed to add word",{word:e,error:errorMeta(o)});}}function yr(){return I}async function Mr(){I=false,y.debug("Tokenizer closed");}function xr(e){if(!I)return e.split(/\s+/).filter(Boolean).join(" ");try{return Mt(e).join(" ")}catch(r){return y.warn("Tokenization failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function br(e){if(!I)return e.split(/\s+/).filter(Boolean).join(" ");try{return xt(e).join(" ")}catch(r){return y.warn("Tokenization for search failed, using fallback",{error:errorMeta(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}var J="memory",X="0.3.39",G={name:J,version:X,description:"EASBot memory plugin: lifecycle hooks and memory tool",entry:"./index.mjs",capabilities:["hooks","tools"]};async function E(){return d.exists()}function M(e,r){if(typeof e!="object"||e===null)return;let t=e;for(let o of r){let n=t[o];if(typeof n=="string"&&n.length>0)return n}}function he(e){if(typeof e!="object"||e===null)return {};let r=e.extras;return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{}}function Ee(e){if(typeof e!="object"||e===null)return;let r=e.protocolMetadata;if(typeof r!="object"||r===null)return;let t=r.agentId;return typeof t=="string"&&t.length>0?t:void 0}function P(e,r){let t={...he(e),...he(r)};return {agentId:M(r,["agentId"])??Ee(e)??Ee(r)??M(e,["agentId"])??M(r,["agent"])??M(e,["agent"])??"",sessionId:M(r,["sessionId"])??M(e,["sessionId"]),toolName:M(e,["toolName","tool","name"])??M(r,["toolName"]),error:M(e,["error","message"])??M(r,["error"]),messagePreview:M(e,["messagePreview"])??M(r,["messagePreview"]),contextPreview:M(e,["contextPreview","text","prompt"])??M(r,["contextPreview"]),extras:t}}function S(e){let r=f().worktree,t=j$1(r),o=e.trim()||"memory-plugin";return {agentId:o,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:t,workspaceDir:r,rootDir:r,config:A$1({agentId:o,dbPath:t,workspaceDir:r})}}function x(e,r){return {modified:false,input:e,output:{...r}}}function _e(e,r){return M(e,[r])}var Z=Log.create({service:"memory.plugin.hook"}),Re=1200;function ht(e,r){let t=e;for(let n of [t?.query,r.query])if(typeof n=="string"&&n.trim().length>0)return n;return _e(e,"userMessage")??""}var Y=async(e,r)=>{let t=HookEvent.ContextCollect,o=P(e,r);if(!o.agentId.trim())return {modified:false,input:e,output:{hook:t,ok:false,error:"context collect: agentId is required",fragments:[]}};if(!await E())return Z.debug("context.collect: memory not configured, skip recall"),{modified:false,input:e,output:{hook:t,ok:true,fragments:[],logLine:"memory not configured"}};let n=typeof o.extras.topK=="number"?o.extras.topK:5,l=ht(e,o.extras);if(l.trim().length===0)return Z.debug("context.collect: empty query, skip recall"),{modified:false,input:e,output:{hook:t,ok:true,fragments:[],logLine:"context collect: empty query"}};try{let c=await z$1("recall",{query:l,maxResults:n},S(o.agentId));if(c.hits.length===0)return {modified:!1,input:e,output:{hook:t,ok:!0,fragments:[],logLine:"context collect: no facts found"}};let m=c.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet}`).join(`
|
|
2
|
+
`),s=await TruncateContent.truncate(m,{maxChars:Math.min(Re*4,TruncateContent.DEFAULT_MAX_CHARS),label:"memory recall fragments"}),a={id:"memory:recall",title:"Relevant Memory",content:s.content,source:"memory",order:10,markers:["<memory-recall>","</memory-recall>"]};return {modified:!1,input:e,output:{hook:t,ok:!0,fragments:[a],logLine:`context collect: contributed ${c.hits.length} facts${s.truncated?" (truncated; full content saved for agent read-back)":""}`}}}catch(c){let m=errorMeta(c);return Z.warn("memory context collect hook failed",{error:m}),{modified:false,input:e,output:{hook:t,ok:false,error:m.message,fragments:[]}}}};var Oe=Log.create({service:"memory.plugin.hook"}),Rt=200,j=async(e,r)=>{let t=HookEvent.SessionCompacting,o=P(e,r);if(!o.agentId.trim())return x(e,{hook:t,ok:false,error:"pre compact: agentId is required"});if(!await E())return Oe.debug("pre-compact: memory not configured, skip recall"),x(e,{hook:t,ok:true,context:[],logLine:"memory not configured"});let l=(o.contextPreview??o.messagePreview??"").slice(0,Rt).replace(/\s+/g," ").trim(),c=typeof o.extras.topK=="number"?o.extras.topK:3;if(!l)return x(e,{hook:t,ok:true,context:[],logLine:"pre compact: empty context preview; skipping recall injection"});try{let m=await z$1("recall",{query:l,maxResults:c,minImportance:5},S(o.agentId));if(m.hits.length===0)return x(e,{hook:t,ok:!0,context:[],logLine:"pre compact: no facts matched query"});let s=m.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet.slice(0,150)}`),a=`[memory:pre-compact recall top-${m.hits.length} (imp>=5)]
|
|
3
|
+
${s.join(`
|
|
4
|
+
`)}`;return x(e,{hook:t,ok:!0,context:[a],logLine:`pre compact: injected ${m.hits.length} facts before compaction`})}catch(m){let s=errorMeta(m);return Oe.warn("memory pre compact hook failed",{error:s}),x(e,{hook:t,ok:false,error:s.message})}};var He=Log.create({service:"memory.plugin.hook"}),vt=8,q=async(e,r)=>{let t=HookEvent.ToolFailure,o=P(e,r);if(!o.agentId.trim())return x(e,{hook:t,ok:false,error:"tool failure: agentId is required"});if(!o.toolName?.trim()||!o.error?.trim())return x(e,{hook:t,ok:false,error:"tool failure: toolName and error are required"});if(!await E())return He.debug("tool.failure: memory not configured, skip remember"),x(e,{hook:t,ok:true,logLine:"memory not configured"});let n=createHash("sha256").update(`${o.toolName}:${o.error}`).digest("hex").slice(0,vt),l=o.messagePreview?o.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",c=[`[error_pattern] tool=${o.toolName}`,`[error] ${o.error}`,l?`[preview] ${l}`:"",`[errHash] ${n}`].filter(Boolean).join(`
|
|
5
|
+
`);try{let m=await z$1("remember",{content:c,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${o.toolName}`,`err:${n}`],sessionId:o.sessionId,msgId:typeof o.extras.msgId=="string"?o.extras.msgId:void 0},S(o.agentId));return x(e,{hook:t,ok:!0,logLine:`tool failure: wrote error_pattern fact ${m.fact.id} (tool=${o.toolName}, errHash=${n})`})}catch(m){let s=errorMeta(m);return He.warn("memory tool failure hook failed",{error:s}),x(e,{hook:t,ok:false,error:s.message})}};var b=Log.create({service:"memory.plugin.extract"}),Pe=2e3,Dt=4096,Se="memory",ve=["memory","read","glob","grep"];function $t(e){return (e??[]).filter(r=>r.type==="text"&&!r.synthetic&&!r.ignored).map(r=>r.text??"").join("")}async function Gt(e,r){let t=[];for(let n of await e.messagesByParent(r)){if(n.role!=="assistant")continue;let l=n.parts.filter(c=>c.type==="text").map(c=>c.text??"").join("");l&&t.push({role:"assistant",content:l});}let o=await e.message(r);if(o&&o.role==="user"){let n=$t(o.parts);n&&t.push({role:"user",content:n});}return t}async function Yt(e){if(e.length===0)return "";let r=`### Our Conversation
|
|
6
|
+
|
|
7
|
+
`;for(let t of e){let o=Token.estimate(t.content),n=t.content,l=false;if(o>Pe){n=t.content.slice(-8e3),l=true;}l?r+=`**${t.role==="user"?"User":"Me"}**: ${n}
|
|
8
|
+
|
|
9
|
+
[Content truncated from ${o} tokens]
|
|
10
|
+
|
|
11
|
+
`:r+=`**${t.role==="user"?"User":"Me"}**: ${n||"(empty)"}
|
|
12
|
+
|
|
13
|
+
`;}return r}async function jt(){let r=(await Agent.get(Se))?.prompt?.trim();if(!r)throw new Error(`memory extract: agent "${Se}" has no prompt (\u8BB0\u5FC6\u89C4\u8303\u7F3A\u5931)`);return r}async function qt(e,r,t,o,n){let l=o.agent||await Agent.defaultAgent(),c=l?await Agent.get(l):void 0;if(!c)throw new Error(`memory extract: agent not found (${l})`);let m=o.model??await Provider.defaultModel(),s=typeof m=="string"?Provider.parseModel(m):m,a=await Provider.getModel(s.providerId,s.modelId),i=await t.get();if(!i)throw new Error(`memory extract: session not found (${e.sessionId})`);let p=r.identity?.();if(!p)throw new Error("memory extract: identity capability unavailable");let{metadata:T,initialized:_}=await p.protocol(),ie=i.contextMode??DefaultContextMode,De=await jt(),$e=await p.staticPrompt({agent:c,model:{providerId:a.providerId,modelId:a.api?.id??a.id},workspaceDir:i.directory,mode:ie}),Ge=await p.environment({agent:c,model:{providerId:a.providerId,modelId:a.api?.id??a.id},mode:ie}),Ye=[Markdown.replaceVariables(De,T),...$e.map(V=>V.content),...Ge],je=await t.tools({agent:c.name,model:{providerId:a.providerId,modelId:a.api?.id??a.id},toolFilter:V=>ve.includes(V)}),qe=`Review the conversation below and decide what is worth remembering. Store it with the \`memory\` tool.
|
|
14
|
+
|
|
15
|
+
${await Yt(n)}`,me=await LanguageProvider.generate({user:{id:Identifier.ascending("message"),sessionId:e.sessionId,model:o.model??{providerId:a.providerId,modelId:a.api?.id??a.id}},sessionId:e.sessionId,agent:c,system:Ye,model:a,temperature:Provider.LIMITS.TEMPERATURE.SUMMARY,maxOutputTokens:Dt,messages:[{role:"user",content:[{type:"text",text:qe}]}],tools:je,activeTools:ve,stopWhen:stepCountIs(5),abort:new AbortController().signal});return b.debug("memory extract finished",{sessionId:e.sessionId,outputLength:me.text.length}),me.text}async function ee(e,r,t,o,n){try{await e.updatePart({...t,messageId:r,status:n.status,time:{start:o,end:Date.now()},...n.result!==void 0?{result:n.result}:{},...n.error!==void 0?{error:n.error}:{},...n.reason!==void 0?{reason:n.reason}:{}});}catch(l){b.error("memory part status update failed",{error:errorMeta(l),status:n.status});}}async function Ne(e,r){let t=e;if(!t.userMessageId)return b.debug("loop.end: no userMessageId, skip"),{modified:false,input:e};if(!await E())return b.debug("loop.end: memory not configured, skip extract"),{modified:false,input:e};let o=`${t.sessionId}:${t.userMessageId}`;if(b.debug("loop.end: memory extract started",{loopKey:o,step:t.step,result:t.result}),r.agent&&await Agent.isSubagent(r.agent))return b.debug("loop.end: skip memory extract, subagent",{loopKey:o}),{modified:false,input:e};let n=r.session?.(t.sessionId);if(!n)return b.debug("loop.end: skip memory extract, session capability unavailable",{loopKey:o}),{modified:false,input:e};let l=await n.message(t.userMessageId);if(!l)return b.debug("loop.end: user message not found, skip",{loopKey:o}),{modified:false,input:e};if(l.parts.some(p=>p.type==="memory"))return b.debug("loop.end: skip memory extract, already processed"),{modified:false,input:e};let c=Identifier.ascending("part"),m=Date.now(),s={id:c,type:"memory",status:"in_progress",time:{start:m}};await n.updatePart({...s,messageId:t.userMessageId});let a=await Gt(n,t.userMessageId);return a.some(p=>p.role==="assistant"&&p.content)?(qt(t,r,n,l,a).then(p=>ee(n,t.userMessageId,s,m,{status:"completed",result:p})).catch(p=>(b.error("memory extract failed",{error:errorMeta(p)}),ee(n,t.userMessageId,s,m,{status:"failed",error:errorMeta(p).message}))),{modified:false,input:e}):(b.debug("loop.end: skip memory extract, no assistant text content",{loopKey:o}),await ee(n,t.userMessageId,s,m,{status:"skipped",reason:"No assistant text content"}),{modified:false,input:e})}var R=[{event:HookEvent.ContextCollect,handler:Y},{event:HookEvent.SessionCompacting,handler:j},{event:HookEvent.ToolFailure,handler:q},{event:HookEvent.LoopEnd,handler:Ne}];function A(){return R.map(({event:e,handler:r})=>({event:e,hooks:[{type:"function",handler:r}]}))}var L=Log.create({service:"memory.plugin.tool"}),ne="memory",ae=["recall","remember","update","forget","extract","graph_query","status"],Xt=500,Ce="Access EASBot long-term memory via `operation` (recall / remember / update / forget / extract / graph_query / status).",re=z.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),Ae=z.discriminatedUnion("operation",[z.object({operation:z.literal("recall"),query:z.string().describe("Search query text"),limit:Schema.positiveInt.optional().default(10).describe("Max results (default 10)"),category:re.optional().describe("Filter by memory category"),minImportance:Schema.positiveInt.optional().refine(e=>e===void 0||e>=1&&e<=10,{message:"minImportance must be in [1, 10] (inclusive); the service uses `WHERE importance >= ?` SQL"}).describe("INCLUSIVE `>=` filter on 1-10 importance scale; e.g. `5` keeps importance 5"),maxEdgesPerNode:Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per KG neighbor node returned by recall (default 10; range [1, 100])"),includeGraph:z.boolean().optional().default(false).describe("Include KG neighbor subgraph (default false; pass true to get BFS neighbors alongside hits)"),includeShared:z.boolean().optional().default(false).describe("Include shared KG nodes from other agents (requires trusted local; default false)")}).strict(),z.object({operation:z.literal("remember"),content:z.string().describe("Memory content"),category:re.describe("Memory category"),importance:Schema.positiveInt.describe("Importance 1-10 (service layer enforces range)"),tags:Schema.stringArray.optional().describe("Optional tags (string[])")}).strict(),z.object({operation:z.literal("update"),factId:z.string().describe("Target fact id (must belong to ctx.agentId)"),content:z.string().optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:re.optional().describe("New category"),importance:Schema.positiveInt.optional().describe("New importance 1-10"),tags:Schema.stringArray.optional().describe("New tags (string[]; empty array clears tags)")}).strict().refine(e=>e.content!==void 0||e.category!==void 0||e.importance!==void 0||e.tags!==void 0,{message:"update requires at least one of: `content`, `category`, `importance`, `tags`"}),z.object({operation:z.literal("forget"),factId:z.string().describe("Target fact id to delete (required; must belong to ctx.agentId)"),dryRun:z.boolean().optional().default(false).describe("Preview without deleting (returns matched count, never deletes)"),force:z.boolean().optional().default(false).describe("Skip KG reference check and delete anyway (required when fact is referenced by other facts; use after dryRun confirms the match)")}).strict(),z.object({operation:z.literal("extract"),lastN:Schema.positiveInt.optional().default(10).describe("Recent messages (default 10)"),fromMessageId:z.string().optional().describe("Process messages after this id")}).strict(),z.object({operation:z.literal("graph_query"),query:z.string().min(1).describe('**Node name fragment** (NOT natural-language query): used to locate a single root node by case-insensitive `LIKE %name%` match against the `nodes.name` column. After matching, the service performs BFS neighbor expansion automatically. Pass only short identifiers \u2014 e.g. an entity name like "easbot" or "decision-0034" as it appears in `nodes.name`. Tags and relation types live on edges, not on node names, so searching for them here returns 0 nodes \u2014 `recall` is the right tool for natural-language fact search.'),maxDepth:Schema.positiveInt.optional().default(2).describe("BFS depth for neighbor expansion (default 2; service range [1, 5])"),maxNodes:Schema.nonNegativeInt.optional().default(100).describe("Max nodes returned after BFS (default 100; service max 500)"),maxEdgesPerNode:Schema.positiveInt.optional().default(10).refine(e=>e===void 0||e>=1&&e<=100,{message:"maxEdgesPerNode must be in [1, 100]"}).describe("Max edges per BFS neighbor node (default 10; range [1, 100])"),relation:z.string().optional().describe('Edge relation filter (e.g. "uses"; single-value exact match; differs from note.graph_query relationTypes[])'),type:z.string().optional().describe('Node type filter for root node (e.g. "decision"; only affects CLI query path; nodeId path bypasses)')}).strict(),z.object({operation:z.literal("status")}).strict()]),se=Ae;function Zt(){try{let e=loadTextFile("./memory.txt",import.meta.url)();return e.trim().length>0?e:Ce}catch(e){return L.warn("memory tool description unavailable, using fallback",{error:errorMeta(e)}),Ce}}function er(e){let r=e.agent?.trim();if(!r)throw new NameErrors.MissingFieldError({message:"memory tool: agentId is required (ctx.agent must be set)",field:"agentId"});return r}function tr(e){if(e?.sessionId?.trim())return e.sessionId;throw new NameErrors.MissingFieldError({message:"memory tool: sessionId is required (ctx.sessionId must be set)",field:"sessionId"})}async function rr(e,r){let t=j$1(e);if(!existsSync(t)){L.debug("memory db not found, auto-initializing",{dbPath:t,workspaceDir:e});try{await z$1("init",{workspaceDir:e,force:!1},r);}catch(o){throw new NameErrors.OperationFailedError({message:`memory tool: auto-init failed (${errorMeta(o).message}). Try running \`easbot memory init\` manually.`,operation:"memory-auto-init"})}}}async function or(){if(!(a$1.isInitialized()&&a$1.capabilities().graph))try{let e=await d.getMemoryJson();a$1.init({models:{embedding:e?.embedding_model??void 0,graph:e?.graph_model??void 0}});}catch(e){L.warn("memory Llm init failed; KG extraction will be skipped",{error:errorMeta(e)});}}var F=createTool({description:Zt(),args:Ae,isEnabled:()=>d.exists(),execute:async(e,r)=>{let t=e,o=t.operation;try{await r.ask({permission:"memory",patterns:o==="recall"?[t.query]:["*"],always:["*"],metadata:{operation:o}});let n=er(r),l=r.worktree||r.directory||process.cwd(),c=j$1(l),m={agentId:n,isTrustedLocal:!0,remote:!1,locale:Locale.resolveLocaleLang(),dbPath:c,workspaceDir:l,rootDir:l,config:A$1({agentId:n,dbPath:c,workspaceDir:l}),signal:r.abort};switch(await or(),await rr(l,m),o){case "recall":{let s=await z$1("recall",{query:t.query,maxResults:t.limit,category:t.category,minImportance:t.minImportance,maxEdgesPerNode:t.maxEdgesPerNode,includeGraph:t.includeGraph??!1,includeShared:t.includeShared??!1,snippetMaxChars:Xt},m);return {output:await a("recall",{kind:"recall",query:t.query,agentId:m.agentId,scope:"agent_only",totalCount:s.total,truncated:s.truncated,hits:s.hits.map(i=>({fact:{id:i.memoryId,agentId:i.agentId,category:i.category,content:i.content,importance:i.importance,tags:i.tags??null,source:i.source,sessionId:i.sessionId??null,msgId:i.msgId??null,parentMsgId:i.parentMsgId??null,filePath:i.filePath??null,createdAt:i.createdAt,updatedAt:i.updatedAt??i.createdAt,truncated:i.content.length>200},score:i.score,source:"hybrid",snippet:i.snippet,nodeIds:i.nodes?.map(p=>p.id)??[],nodes:i.nodes}))},{toolName:"memory_recall"}),title:`Memory: recall (${t.query})`,metadata:{operation:"recall",enabled:!0,agentId:n,query:t.query}}}case "remember":{let s=await z$1("remember",{content:t.content,category:t.category,importance:t.importance,tags:t.tags,sessionId:r.sessionId},m);return {output:`<memory_result>
|
|
16
|
+
Memory saved.
|
|
17
|
+
id: ${s.fact.id}
|
|
18
|
+
category: ${s.fact.category}
|
|
19
|
+
importance: ${t.importance}
|
|
20
|
+
linked nodes: ${s.nodeIds?.length??0}
|
|
21
|
+
</memory_result>`,title:"Memory saved",metadata:{operation:"remember",enabled:!0,agentId:n,memoryId:s.fact.id,category:s.fact.category,importance:t.importance}}}case "update":{let s=await z$1("update",{factId:t.factId,content:t.content,category:t.category,importance:t.importance,tags:t.tags},m),a=s.fieldsUpdated.length>0?s.fieldsUpdated.join(", "):"(no-op)",i=s.contentChanged?" (embedding rewritten)":"";return {output:`<memory_result>
|
|
22
|
+
Memory updated.
|
|
23
|
+
id: ${s.fact.id}
|
|
24
|
+
category: ${s.fact.category}
|
|
25
|
+
importance: ${s.fact.importance}
|
|
26
|
+
fields updated: ${a}${i}
|
|
27
|
+
updated_at: ${s.fact.updatedAt}
|
|
28
|
+
</memory_result>`,title:"Memory updated",metadata:{operation:"update",enabled:!0,agentId:n,memoryId:s.fact.id,category:s.fact.category,importance:s.fact.importance}}}case "forget":{let s=await z$1("forget",{factId:t.factId,dryRun:t.dryRun,force:t.force},m);return {output:await a("forget",s,{toolName:"memory_forget"}),title:"Memory: forget",metadata:{operation:"forget",enabled:!0,agentId:n}}}case "extract":{let s=tr(r),a=await z$1("extract",{sessionId:s,lastN:t.lastN,fromMessageId:t.fromMessageId},m);return {output:`<memory_result>
|
|
29
|
+
Extract completed.
|
|
30
|
+
sessionId: ${s}
|
|
31
|
+
extractedCount: ${a.extractedCount}
|
|
32
|
+
factIds: ${a.factIds.length>0?a.factIds.join(", "):"(none)"}
|
|
33
|
+
messageRange: ${a.messageRange.fromMessageId} -> ${a.messageRange.toMessageId}
|
|
34
|
+
</memory_result>`,title:"memory: extract",metadata:{operation:"extract",enabled:!0,agentId:n,total:a.extractedCount}}}case "graph_query":{let s=await z$1("graph_query",{query:t.query,maxDepth:t.maxDepth,maxNodes:t.maxNodes,maxEdgesPerNode:t.maxEdgesPerNode,...t.relation!==void 0?{relation:t.relation}:{},...t.type!==void 0?{type:t.type}:{}},m);return {output:await a("graph_query",s,{toolName:"memory_graph_query"}),title:"Memory: graph_query",metadata:{operation:"graph_query",enabled:!0,agentId:n}}}case "status":{let a=await z$1("status",{},m);return {output:renderKnowledgeStatus({packageName:"memory",rootDir:a.workspaceDir??"",configPath:a.configPath??"",configExists:typeof a.configExists=="boolean"?a.configExists:!0,dbPath:a.dbPath,dbExists:typeof a.dbExists=="boolean"?a.dbExists:!0,dbSize:a.dbSize,indexState:a.indexState,schemaVersion:a.schemaVersion,extractionVersion:a.extractionVersion,lastSyncAt:a.lastSyncAt,vectorEnabled:a.vectorEnabled,embeddingDims:a.embeddingDims,llm:a.llm??{initialized:!1,capabilities:{}},backend:a.backend,healthy:a.healthy,recommendation:a.recommendation,dbStats:a.dbStats??a.integrityStats,extras:(()=>{let p={};if(typeof a.agentId=="string"&&(p.agent_id=a.agentId),typeof a.ftsAvailable=="boolean"&&(p.fts_available=a.ftsAvailable?"yes":"no"),a.factsByCategory&&typeof a.factsByCategory=="object")for(let[T,_]of Object.entries(a.factsByCategory))typeof _=="number"&&_>0&&(p[`facts/${T}`]=_);if(a.meta&&typeof a.meta=="object")for(let[T,_]of Object.entries(a.meta))_!==void 0&&(p[`meta/${T}`]=_);return Object.keys(p).length>0?p:void 0})()}),title:"Memory: status",metadata:{operation:"status",enabled:!0,agentId:n}}}}}catch(n){if(ServiceError.isInstance(n))try{return {output:ServiceErrorBus.toMarkdown(n,{tool:"memory",operation:o,resultTag:"<memory_result>",pack:"memory"}),title:`Memory: ${o} (${n.data.code})`,metadata:{operation:o,enabled:!0,businessErrorCode:n.data.code}}}catch(l){return L.error("memory tool ServiceErrorBus formatting failed",{error:errorMeta(l)}),{output:`<memory_result>
|
|
35
|
+
Error: ${n.data.message}
|
|
36
|
+
</memory_result>`,title:`Memory: ${o} (${n.data.code})`,metadata:{operation:o,enabled:true,businessErrorCode:n.data.code}}}return L.error("memory tool execution failed",{operation:o,error:errorMeta(n)}),{output:`<memory_result>
|
|
37
|
+
Error: ${errorMeta(n).message}
|
|
38
|
+
</memory_result>`,title:`Memory: ${o} (error)`,metadata:{operation:o,enabled:true}}}}});var D=async e=>({hooks:A(),tools:{[G.name]:F}});var Le=[HookEvent.ContextCollect,HookEvent.SessionCompacting,HookEvent.ToolFailure,HookEvent.LoopEnd];var Fe={name:"memory.plugin",async init(){return {isEnabled:()=>true,handlers:R.map(({event:e,handler:r})=>({name:e,handler:r}))}}};export{ar as MEMORY_CATEGORIES,R as MEMORY_HOOK_BINDINGS,Le as MEMORY_HOOK_EVENTS,J as MEMORY_PLUGIN_ID,G as MEMORY_PLUGIN_MANIFEST,X as MEMORY_PLUGIN_VERSION,se as MEMORY_TOOL_ARGS,ne as MEMORY_TOOL_ID,ae as MEMORY_TOOL_OPS,D as MemoryPlugin,D as MemoryPluginEntry,Fe as MemoryPluginHook,F as MemoryTool,fr as addWord,Mr as closeTokenizer,A as createMemoryHookMatchers,gr as initTokenizer,yr as isInitialized,yt as loadCustomDict,xr as toFtsTokens,br as toFtsTokensForSearch,Mt as tokenize,xt as tokenizeForSearch};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easbot/memory",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.39",
|
|
4
4
|
"description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -53,15 +53,15 @@
|
|
|
53
53
|
"ai": "^6.0.253",
|
|
54
54
|
"better-sqlite3": "^13.0.3",
|
|
55
55
|
"jieba-wasm": "^2.4.0",
|
|
56
|
-
"@easbot/database": "0.3.
|
|
57
|
-
"@easbot/
|
|
58
|
-
"@easbot/
|
|
59
|
-
"@easbot/types": "0.3.
|
|
60
|
-
"@easbot/terminal": "0.3.
|
|
61
|
-
"@easbot/utils": "0.3.
|
|
62
|
-
"@easbot/
|
|
63
|
-
"@easbot/
|
|
64
|
-
"@easbot/
|
|
56
|
+
"@easbot/database": "0.3.39",
|
|
57
|
+
"@easbot/mcp": "0.3.39",
|
|
58
|
+
"@easbot/plugin": "0.3.39",
|
|
59
|
+
"@easbot/types": "0.3.39",
|
|
60
|
+
"@easbot/terminal": "0.3.39",
|
|
61
|
+
"@easbot/utils": "0.3.39",
|
|
62
|
+
"@easbot/llm": "0.3.39",
|
|
63
|
+
"@easbot/local-model-sdk": "0.3.39",
|
|
64
|
+
"@easbot/ollama-sdk": "0.3.39"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@types/node": "^25.9.5",
|
|
@@ -78,11 +78,13 @@
|
|
|
78
78
|
},
|
|
79
79
|
"scripts": {
|
|
80
80
|
"dev": "tsup --watch --env.NODE_ENV development",
|
|
81
|
-
"build": "tsup --env.NODE_ENV production",
|
|
81
|
+
"build": "tsup --env.NODE_ENV production && pnpm plugin:generate",
|
|
82
82
|
"test": "vitest",
|
|
83
83
|
"test:run": "vitest run",
|
|
84
84
|
"test:coverage": "vitest run --coverage",
|
|
85
85
|
"test:clean": "tsx scripts/clean-test-fixtures.ts",
|
|
86
|
+
"plugin:generate": "tsx scripts/generate-plugin-distribution.ts",
|
|
87
|
+
"plugin:check": "tsx scripts/generate-plugin-distribution.ts --check",
|
|
86
88
|
"lint": "biome check .",
|
|
87
89
|
"lint:fix": "biome check --write .",
|
|
88
90
|
"lint:report": "biome check --reporter=summary .",
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
WHEN TO USE:
|
|
2
|
-
Use this tool to read or write EASBot long-term memory. Call it when the user asks to remember something, when you need prior facts or error patterns before answering, or when you need the memory subsystem health status.
|
|
3
|
-
|
|
4
|
-
AFTER THIS:
|
|
5
|
-
Review the returned markdown or JSON. For `recall`, use the returned facts as context and cite them when relevant. For `remember` / `update` / `forget`, report the affected fact id. For `status`, report the health summary.
|
|
6
|
-
|
|
7
|
-
NOTES:
|
|
8
|
-
- `op` selects one of: recall, remember, update, forget, extract, graph_query, status.
|
|
9
|
-
- `params` carries the operation arguments as a flat object; see the memory op schemas for field names.
|
|
10
|
-
- Operations run against the current workspace memory database. Write operations require a trusted local caller.
|
|
11
|
-
- `update` / `extract` return JSON text; the other operations return rendered markdown.
|
|
12
|
-
- Failures return a diagnostic string instead of throwing. Keep going with the rest of the task.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{a as COMMANDS_HELP,d as handleMemoryCli,e as mapMemoryDoctor,b as renderBanner,c as renderHelp}from'./chunk-YUWHNHAY.mjs';import'./chunk-HX3TV7FD.mjs';import'./chunk-S4DPVKMV.mjs';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunk4G4FSAFY_cjs=require('./chunk-4G4FSAFY.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.d}});Object.defineProperty(exports,"mapMemoryDoctor",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.e}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk4G4FSAFY_cjs.c}});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as MemoryStdioServer}from'./chunk-FZ3RTYIJ.mjs';import'./chunk-AEAMQDNV.mjs';import'./chunk-YJLHS7JB.mjs';import'./chunk-HH7EA2UE.mjs';import'./chunk-AJDMZTCQ.mjs';import'./chunk-SE3F5YQE.mjs';import'./chunk-HX3TV7FD.mjs';import'./chunk-S4DPVKMV.mjs';
|