@aigne/fs-memory 1.0.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2025-07-15)
4
+
5
+
6
+ ### Features
7
+
8
+ * **memory:** support did space memory adapter ([#229](https://github.com/AIGNE-io/aigne-framework/issues/229)) ([6f69b64](https://github.com/AIGNE-io/aigne-framework/commit/6f69b64e98b963db9d6ab5357306b445385eaa68))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @aigne/core bumped to 1.34.0
16
+ * @aigne/openai bumped to 0.10.0
package/LICENSE.md ADDED
@@ -0,0 +1,93 @@
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that
84
+ organization. **control** means ownership of substantially all the assets of an
85
+ entity, or the power to direct its management and policies by vote, contract, or
86
+ otherwise. Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # @aigne/fs-memory
2
+
3
+ [![GitHub star chart](https://img.shields.io/github/stars/AIGNE-io/aigne-framework?style=flat-square)](https://star-history.com/#AIGNE-io/aigne-framework)
4
+ [![Open Issues](https://img.shields.io/github/issues-raw/AIGNE-io/aigne-framework?style=flat-square)](https://github.com/AIGNE-io/aigne-framework/issues)
5
+ [![codecov](https://codecov.io/gh/AIGNE-io/aigne-framework/graph/badge.svg?token=DO07834RQL)](https://codecov.io/gh/AIGNE-io/aigne-framework)
6
+ [![NPM Version](https://img.shields.io/npm/v/@aigne/fs-memory)](https://www.npmjs.com/package/@aigne/fs-memory)
7
+ [![Elastic-2.0 licensed](https://img.shields.io/npm/l/@aigne/fs-memory)](https://github.com/AIGNE-io/aigne-framework/blob/main/LICENSE)
8
+
9
+ File system memory component for [AIGNE Framework](https://github.com/AIGNE-io/aigne-framework), providing file system-based memory storage capabilities.
10
+
11
+ ## Introduction
12
+
13
+ `@aigne/fs-memory` is the file system memory component of [AIGNE Framework](https://github.com/AIGNE-io/aigne-framework), providing local file system-based memory storage and retrieval functionality. This component stores memories as YAML files in specified directories, providing a simple and reliable memory persistence solution.
14
+
15
+ ## Features
16
+
17
+ * **File System Storage**: Uses local file system for memory file storage
18
+ * **YAML Format**: Uses YAML format for memory storage, making it easy to read and edit
19
+ * **Directory Management**: Automatically creates and manages memory directory structure
20
+ * **Path Support**: Supports absolute paths, relative paths, and home directory (~) expansion
21
+ * **AI Agent Management**: Uses AI agents to handle memory recording and retrieval
22
+ * **TypeScript Support**: Complete type definitions providing an excellent development experience
23
+
24
+ ## Installation
25
+
26
+ ### Using npm
27
+
28
+ ```bash
29
+ npm install @aigne/fs-memory
30
+ ```
31
+
32
+ ### Using yarn
33
+
34
+ ```bash
35
+ yarn add @aigne/fs-memory
36
+ ```
37
+
38
+ ### Using pnpm
39
+
40
+ ```bash
41
+ pnpm add @aigne/fs-memory
42
+ ```
43
+
44
+ ## Basic Usage
45
+
46
+ ```typescript
47
+ import { AIAgent, AIGNE } from "@aigne/core";
48
+ import { FSMemory } from "@aigne/fs-memory";
49
+ import { OpenAIChatModel } from "@aigne/openai";
50
+
51
+ // Create AI model instance
52
+ const model = new OpenAIChatModel({
53
+ apiKey: process.env.OPENAI_API_KEY,
54
+ model: "gpt-4-turbo",
55
+ });
56
+
57
+ // Create file system memory
58
+ const memory = new FSMemory({
59
+ rootDir: "./memories",
60
+ });
61
+
62
+ // Create AI agent with file-based memory
63
+ const agent = AIAgent.from({
64
+ name: "FileAssistant",
65
+ instructions: "You are a helpful assistant with file-based memory.",
66
+ memory: memory,
67
+ inputKey: "message",
68
+ });
69
+
70
+ // Use AIGNE execution engine
71
+ const aigne = new AIGNE({ model });
72
+
73
+ // Invoke agent
74
+ const userAgent = await aigne.invoke(agent);
75
+
76
+ // Send message
77
+ const response = await userAgent.invoke({
78
+ message: "Remember that I prefer working in the morning",
79
+ });
80
+
81
+ console.log(response.message);
82
+
83
+ // Query memory
84
+ const response2 = await userAgent.invoke({
85
+ message: "What do you know about my work preferences?",
86
+ });
87
+
88
+ console.log(response2.message);
89
+ ```
90
+
91
+ ## Advanced Configuration
92
+
93
+ ### Custom Memory Directory
94
+
95
+ ```typescript
96
+ import { FSMemory } from "@aigne/fs-memory";
97
+ import { join } from "path";
98
+
99
+ // Using absolute path
100
+ const memory1 = new FSMemory({
101
+ rootDir: "/absolute/path/to/memories",
102
+ });
103
+
104
+ // Using relative path
105
+ const memory2 = new FSMemory({
106
+ rootDir: "./data/memories",
107
+ });
108
+
109
+ // Using home directory
110
+ const memory3 = new FSMemory({
111
+ rootDir: "~/my-app/memories",
112
+ });
113
+
114
+ // Using dynamic path
115
+ const memory4 = new FSMemory({
116
+ rootDir: join(process.cwd(), "memories"),
117
+ });
118
+ ```
119
+
120
+ ### Configure Memory Agent Options
121
+
122
+ ```typescript
123
+ const memory = new FSMemory({
124
+ rootDir: "./memories",
125
+ // Custom memory retriever agent configuration
126
+ retrieverOptions: {
127
+ name: "CustomRetriever",
128
+ instructions: "Custom retrieval instructions for file-based memory",
129
+ },
130
+ // Custom memory recorder agent configuration
131
+ recorderOptions: {
132
+ name: "CustomRecorder",
133
+ instructions: "Custom recording instructions for file-based memory",
134
+ },
135
+ // Other agent configurations
136
+ autoUpdate: true,
137
+ });
138
+ ```
139
+
140
+ ## Using Multiple Memory Types Together
141
+
142
+ ```typescript
143
+ import { DefaultMemory } from "@aigne/default-memory";
144
+ import { FSMemory } from "@aigne/fs-memory";
145
+
146
+ // Combine multiple memory types
147
+ const agent = AIAgent.from({
148
+ name: "MultiMemoryAgent",
149
+ instructions: "You are an assistant with multiple memory types.",
150
+ memory: [
151
+ // Database memory for structured data
152
+ new DefaultMemory({
153
+ storage: {
154
+ url: "file:memory.db",
155
+ },
156
+ }),
157
+ // File system memory for long-term storage
158
+ new FSMemory({
159
+ rootDir: "./long-term-memories",
160
+ }),
161
+ ],
162
+ inputKey: "message",
163
+ });
164
+ ```
165
+
166
+ ## Memory File Structure
167
+
168
+ FSMemory creates the following structure in the specified directory:
169
+
170
+ ```
171
+ memories/
172
+ ├── conversation-id-1/
173
+ │ └── memory.yaml
174
+ ├── conversation-id-2/
175
+ │ └── memory.yaml
176
+ └── ...
177
+ ```
178
+
179
+ Each memory file contains YAML-formatted memory data:
180
+
181
+ ```yaml
182
+ - id: memory-id-1
183
+ content: "User prefers working in the morning"
184
+ timestamp: 2024-01-01T10:00:00Z
185
+ metadata:
186
+ type: "preference"
187
+
188
+ - id: memory-id-2
189
+ content: "User is a software developer"
190
+ timestamp: 2024-01-01T10:05:00Z
191
+ metadata:
192
+ type: "personal_info"
193
+ ```
194
+
195
+ ## License
196
+
197
+ Elastic-2.0
@@ -0,0 +1,2 @@
1
+ export * from "./memory.js";
2
+ export * from "./utils/index.js";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./memory.js"), exports);
18
+ __exportStar(require("./utils/index.js"), exports);
@@ -0,0 +1,59 @@
1
+ import { type AIAgentOptions, type Message } from "@aigne/core";
2
+ import { MemoryAgent, type MemoryAgentOptions, type MemoryRecorderInput, type MemoryRetrieverInput } from "@aigne/core/memory/index.js";
3
+ export declare const MEMORY_FILE_NAME = "memory.yaml";
4
+ /**
5
+ * Configuration options for the FSMemory class.
6
+ */
7
+ export interface FSMemoryOptions extends Partial<MemoryAgentOptions> {
8
+ /**
9
+ * The root directory where memory files will be stored.
10
+ * Can be absolute or relative path. Relative paths are resolved from the current working directory.
11
+ * Home directory prefix (~) will be expanded appropriately.
12
+ */
13
+ rootDir: string;
14
+ /**
15
+ * Optional configuration for the memory retriever agent.
16
+ * Controls how memories are retrieved from the file system.
17
+ */
18
+ retrieverOptions?: Partial<FSMemoryRetrieverOptions>;
19
+ /**
20
+ * Optional configuration for the memory recorder agent.
21
+ * Controls how memories are recorded to the file system.
22
+ */
23
+ recorderOptions?: Partial<FSMemoryRecorderOptions>;
24
+ }
25
+ /**
26
+ * A memory implementation that stores and retrieves memories using the file system.
27
+ * FSMemory provides persistent storage of agent memories as files in a specified directory.
28
+ *
29
+ * @example
30
+ * Here is an example of how to use the FSMemory class:
31
+ * {@includeCode ../../test/fs-memory/fs-memory.test.ts#example-fs-memory-simple}
32
+ */
33
+ export declare class FSMemory extends MemoryAgent {
34
+ /**
35
+ * Creates a new FSMemory instance.
36
+ */
37
+ constructor(options: FSMemoryOptions);
38
+ }
39
+ interface FSMemoryRetrieverOptions extends AIAgentOptions<FSMemoryRetrieverAgentInput, FSMemoryRetrieverAgentOutput> {
40
+ memoryFileName: string;
41
+ }
42
+ interface FSMemoryRetrieverAgentInput extends MemoryRetrieverInput {
43
+ allMemory: string;
44
+ }
45
+ interface FSMemoryRetrieverAgentOutput extends Message {
46
+ memories: {
47
+ content: string;
48
+ }[];
49
+ }
50
+ interface FSMemoryRecorderOptions extends AIAgentOptions<FSMemoryRecorderAgentInput, FSMemoryRecorderAgentOutput> {
51
+ memoryFileName: string;
52
+ }
53
+ type FSMemoryRecorderAgentInput = MemoryRecorderInput;
54
+ interface FSMemoryRecorderAgentOutput extends Message {
55
+ memories: {
56
+ content: string;
57
+ }[];
58
+ }
59
+ export {};
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FSMemory = exports.MEMORY_FILE_NAME = void 0;
4
+ const promises_1 = require("node:fs/promises");
5
+ const node_path_1 = require("node:path");
6
+ const core_1 = require("@aigne/core");
7
+ const index_js_1 = require("@aigne/core/memory/index.js");
8
+ const yaml_1 = require("yaml");
9
+ const zod_1 = require("zod");
10
+ const fs_js_1 = require("./utils/fs.js");
11
+ exports.MEMORY_FILE_NAME = "memory.yaml";
12
+ /**
13
+ * A memory implementation that stores and retrieves memories using the file system.
14
+ * FSMemory provides persistent storage of agent memories as files in a specified directory.
15
+ *
16
+ * @example
17
+ * Here is an example of how to use the FSMemory class:
18
+ * {@includeCode ../../test/fs-memory/fs-memory.test.ts#example-fs-memory-simple}
19
+ */
20
+ class FSMemory extends index_js_1.MemoryAgent {
21
+ /**
22
+ * Creates a new FSMemory instance.
23
+ */
24
+ constructor(options) {
25
+ let rootDir = (0, node_path_1.normalize)((0, fs_js_1.expandHome)(options.rootDir));
26
+ rootDir = (0, node_path_1.isAbsolute)(rootDir) ? rootDir : (0, node_path_1.resolve)(process.cwd(), rootDir);
27
+ const memoryFileName = (0, node_path_1.join)(rootDir, exports.MEMORY_FILE_NAME);
28
+ super({
29
+ ...options,
30
+ recorder: options.recorder ??
31
+ new FSMemoryRecorder({
32
+ memoryFileName,
33
+ ...options.recorderOptions,
34
+ }),
35
+ retriever: options.retriever ??
36
+ new FSMemoryRetriever({
37
+ memoryFileName,
38
+ ...options.retrieverOptions,
39
+ }),
40
+ autoUpdate: options.autoUpdate ?? true,
41
+ });
42
+ }
43
+ }
44
+ exports.FSMemory = FSMemory;
45
+ class FSMemoryRetriever extends index_js_1.MemoryRetriever {
46
+ options;
47
+ constructor(options) {
48
+ super({});
49
+ this.options = options;
50
+ this.agent = core_1.AIAgent.from({
51
+ name: "fs_memory_retriever",
52
+ description: "Retrieves memories from the file or directory.",
53
+ ...options,
54
+ instructions: options.instructions || DEFAULT_FS_MEMORY_RETRIEVER_INSTRUCTIONS,
55
+ outputSchema: zod_1.z.object({
56
+ memories: zod_1.z
57
+ .array(zod_1.z.object({
58
+ content: zod_1.z.string().describe("Content of the memory"),
59
+ }))
60
+ .describe("List of memories"),
61
+ }),
62
+ });
63
+ }
64
+ agent;
65
+ async process(input, options) {
66
+ if (!(await (0, fs_js_1.exists)(this.options.memoryFileName)))
67
+ return { memories: [] };
68
+ const allMemory = await (0, promises_1.readFile)(this.options.memoryFileName, "utf-8");
69
+ const { memories } = await options.context.invoke(this.agent, { ...input, allMemory });
70
+ const result = memories.map((memory) => ({
71
+ id: (0, index_js_1.newMemoryId)(),
72
+ content: memory.content,
73
+ createdAt: new Date().toISOString(),
74
+ }));
75
+ return { memories: result };
76
+ }
77
+ }
78
+ class FSMemoryRecorder extends index_js_1.MemoryRecorder {
79
+ options;
80
+ constructor(options) {
81
+ super({});
82
+ this.options = options;
83
+ this.agent = core_1.AIAgent.from({
84
+ name: "fs_memory_recorder",
85
+ description: "Records memories in files by AI agent",
86
+ ...options,
87
+ instructions: options.instructions || DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS,
88
+ outputSchema: zod_1.z.object({
89
+ memories: zod_1.z
90
+ .array(zod_1.z.object({
91
+ content: zod_1.z.string().describe("Content of the memory"),
92
+ }))
93
+ .describe("List of memories"),
94
+ }),
95
+ });
96
+ }
97
+ agent;
98
+ async process(input, options) {
99
+ const allMemory = (await (0, fs_js_1.exists)(this.options.memoryFileName))
100
+ ? await (0, promises_1.readFile)(this.options.memoryFileName, "utf-8")
101
+ : "";
102
+ const { memories } = await options.context.invoke(this.agent, { ...input, allMemory });
103
+ const raw = (0, yaml_1.stringify)(memories.map((i) => ({
104
+ content: i.content,
105
+ })));
106
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(this.options.memoryFileName), { recursive: true });
107
+ await (0, promises_1.writeFile)(this.options.memoryFileName, raw, "utf-8");
108
+ return {
109
+ memories: memories.map((i) => ({
110
+ id: (0, index_js_1.newMemoryId)(),
111
+ content: i.content,
112
+ createdAt: new Date().toISOString(),
113
+ })),
114
+ };
115
+ }
116
+ }
117
+ const DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = `You manage memory based on conversation analysis and the existing memories.
118
+
119
+ ## IMPORTANT: All existing memories are available in the allMemory variable. DO NOT call any tools.
120
+
121
+ ## FIRST: Determine If Memory Updates Needed
122
+ - Analyze if the conversation contains ANY information worth remembering
123
+ - Examples of content NOT worth storing:
124
+ * General questions ("What's the weather?", "How do I do X?")
125
+ * Greetings and small talk ("Hello", "How are you?", "Thanks")
126
+ * System instructions or commands ("Show me", "Find", "Save")
127
+ * General facts not specific to the user
128
+ * Duplicate information already stored
129
+ - If conversation lacks meaningful personal information to store:
130
+ * Return the existing memories unchanged
131
+
132
+ ## Your Workflow:
133
+ 1. Read the existing memories from the allMemory variable
134
+ 2. Extract key topics from the conversation
135
+ 3. DECIDE whether to create/update/delete memories based on the conversation
136
+ 4. Return ALL memories including your updates (remove any duplicates)
137
+
138
+ ## Memory Handling:
139
+ - CREATE: Add new memory objects for new topics
140
+ - UPDATE: Modify existing memories if substantial new information is available
141
+ - DELETE: Remove obsolete memories when appropriate
142
+
143
+ ## Memory Structure:
144
+ - Each memory has an id, content, and createdAt fields
145
+ - Keep the existing structure when returning updated memories
146
+
147
+ ## Operation Decision Rules:
148
+ - CREATE only for truly new topics not covered in any existing memory
149
+ - UPDATE only when new information is meaningfully different
150
+ - NEVER update for just rephrasing or minor differences
151
+ - DELETE only when information becomes obsolete
152
+
153
+ ## IMPORTANT: Your job is to return the complete updated memory collection.
154
+ Return ALL memories (existing and new) in your response.
155
+
156
+ ## Existing Memories:
157
+ <existing-memory>
158
+ {{allMemory}}
159
+ </existing-memory>
160
+
161
+ ## Conversation:
162
+ <conversation>
163
+ {{content}}
164
+ </conversation>
165
+ `;
166
+ const DEFAULT_FS_MEMORY_RETRIEVER_INSTRUCTIONS = `You retrieve only the most relevant memories for the current conversation.
167
+
168
+ ## IMPORTANT: All existing memories are available in the allMemory variable
169
+
170
+ ## Process:
171
+ 1. Read the existing memories from the allMemory variable
172
+ 2. Extract key topics from the conversation or search query
173
+ 3. Match memory contents against these topics
174
+
175
+ ## Existing Memories:
176
+ <existing-memory>
177
+ {{allMemory}}
178
+ </existing-memory>
179
+
180
+ ## Search Query:
181
+ <search-query>
182
+ {{search}}
183
+ </search-query>
184
+ `;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,2 @@
1
+ export declare function exists(path: string): Promise<boolean>;
2
+ export declare function expandHome(filepath: string): string;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exists = exists;
4
+ exports.expandHome = expandHome;
5
+ const promises_1 = require("node:fs/promises");
6
+ const node_os_1 = require("node:os");
7
+ const node_path_1 = require("node:path");
8
+ async function exists(path) {
9
+ try {
10
+ await (0, promises_1.stat)(path);
11
+ return true;
12
+ }
13
+ catch (e) {
14
+ if (e.code === "ENOENT") {
15
+ return false;
16
+ }
17
+ throw e;
18
+ }
19
+ }
20
+ function expandHome(filepath) {
21
+ if (filepath.startsWith("~/") || filepath === "~") {
22
+ return (0, node_path_1.join)((0, node_os_1.homedir)(), filepath.slice(1));
23
+ }
24
+ return filepath;
25
+ }
@@ -0,0 +1 @@
1
+ export * from "./fs.js";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./fs.js"), exports);
@@ -0,0 +1,2 @@
1
+ export * from "./memory.js";
2
+ export * from "./utils/index.js";
@@ -0,0 +1,59 @@
1
+ import { type AIAgentOptions, type Message } from "@aigne/core";
2
+ import { MemoryAgent, type MemoryAgentOptions, type MemoryRecorderInput, type MemoryRetrieverInput } from "@aigne/core/memory/index.js";
3
+ export declare const MEMORY_FILE_NAME = "memory.yaml";
4
+ /**
5
+ * Configuration options for the FSMemory class.
6
+ */
7
+ export interface FSMemoryOptions extends Partial<MemoryAgentOptions> {
8
+ /**
9
+ * The root directory where memory files will be stored.
10
+ * Can be absolute or relative path. Relative paths are resolved from the current working directory.
11
+ * Home directory prefix (~) will be expanded appropriately.
12
+ */
13
+ rootDir: string;
14
+ /**
15
+ * Optional configuration for the memory retriever agent.
16
+ * Controls how memories are retrieved from the file system.
17
+ */
18
+ retrieverOptions?: Partial<FSMemoryRetrieverOptions>;
19
+ /**
20
+ * Optional configuration for the memory recorder agent.
21
+ * Controls how memories are recorded to the file system.
22
+ */
23
+ recorderOptions?: Partial<FSMemoryRecorderOptions>;
24
+ }
25
+ /**
26
+ * A memory implementation that stores and retrieves memories using the file system.
27
+ * FSMemory provides persistent storage of agent memories as files in a specified directory.
28
+ *
29
+ * @example
30
+ * Here is an example of how to use the FSMemory class:
31
+ * {@includeCode ../../test/fs-memory/fs-memory.test.ts#example-fs-memory-simple}
32
+ */
33
+ export declare class FSMemory extends MemoryAgent {
34
+ /**
35
+ * Creates a new FSMemory instance.
36
+ */
37
+ constructor(options: FSMemoryOptions);
38
+ }
39
+ interface FSMemoryRetrieverOptions extends AIAgentOptions<FSMemoryRetrieverAgentInput, FSMemoryRetrieverAgentOutput> {
40
+ memoryFileName: string;
41
+ }
42
+ interface FSMemoryRetrieverAgentInput extends MemoryRetrieverInput {
43
+ allMemory: string;
44
+ }
45
+ interface FSMemoryRetrieverAgentOutput extends Message {
46
+ memories: {
47
+ content: string;
48
+ }[];
49
+ }
50
+ interface FSMemoryRecorderOptions extends AIAgentOptions<FSMemoryRecorderAgentInput, FSMemoryRecorderAgentOutput> {
51
+ memoryFileName: string;
52
+ }
53
+ type FSMemoryRecorderAgentInput = MemoryRecorderInput;
54
+ interface FSMemoryRecorderAgentOutput extends Message {
55
+ memories: {
56
+ content: string;
57
+ }[];
58
+ }
59
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function exists(path: string): Promise<boolean>;
2
+ export declare function expandHome(filepath: string): string;
@@ -0,0 +1 @@
1
+ export * from "./fs.js";
@@ -0,0 +1,2 @@
1
+ export * from "./memory.js";
2
+ export * from "./utils/index.js";
@@ -0,0 +1,2 @@
1
+ export * from "./memory.js";
2
+ export * from "./utils/index.js";
@@ -0,0 +1,59 @@
1
+ import { type AIAgentOptions, type Message } from "@aigne/core";
2
+ import { MemoryAgent, type MemoryAgentOptions, type MemoryRecorderInput, type MemoryRetrieverInput } from "@aigne/core/memory/index.js";
3
+ export declare const MEMORY_FILE_NAME = "memory.yaml";
4
+ /**
5
+ * Configuration options for the FSMemory class.
6
+ */
7
+ export interface FSMemoryOptions extends Partial<MemoryAgentOptions> {
8
+ /**
9
+ * The root directory where memory files will be stored.
10
+ * Can be absolute or relative path. Relative paths are resolved from the current working directory.
11
+ * Home directory prefix (~) will be expanded appropriately.
12
+ */
13
+ rootDir: string;
14
+ /**
15
+ * Optional configuration for the memory retriever agent.
16
+ * Controls how memories are retrieved from the file system.
17
+ */
18
+ retrieverOptions?: Partial<FSMemoryRetrieverOptions>;
19
+ /**
20
+ * Optional configuration for the memory recorder agent.
21
+ * Controls how memories are recorded to the file system.
22
+ */
23
+ recorderOptions?: Partial<FSMemoryRecorderOptions>;
24
+ }
25
+ /**
26
+ * A memory implementation that stores and retrieves memories using the file system.
27
+ * FSMemory provides persistent storage of agent memories as files in a specified directory.
28
+ *
29
+ * @example
30
+ * Here is an example of how to use the FSMemory class:
31
+ * {@includeCode ../../test/fs-memory/fs-memory.test.ts#example-fs-memory-simple}
32
+ */
33
+ export declare class FSMemory extends MemoryAgent {
34
+ /**
35
+ * Creates a new FSMemory instance.
36
+ */
37
+ constructor(options: FSMemoryOptions);
38
+ }
39
+ interface FSMemoryRetrieverOptions extends AIAgentOptions<FSMemoryRetrieverAgentInput, FSMemoryRetrieverAgentOutput> {
40
+ memoryFileName: string;
41
+ }
42
+ interface FSMemoryRetrieverAgentInput extends MemoryRetrieverInput {
43
+ allMemory: string;
44
+ }
45
+ interface FSMemoryRetrieverAgentOutput extends Message {
46
+ memories: {
47
+ content: string;
48
+ }[];
49
+ }
50
+ interface FSMemoryRecorderOptions extends AIAgentOptions<FSMemoryRecorderAgentInput, FSMemoryRecorderAgentOutput> {
51
+ memoryFileName: string;
52
+ }
53
+ type FSMemoryRecorderAgentInput = MemoryRecorderInput;
54
+ interface FSMemoryRecorderAgentOutput extends Message {
55
+ memories: {
56
+ content: string;
57
+ }[];
58
+ }
59
+ export {};
@@ -0,0 +1,180 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, isAbsolute, join, normalize, resolve } from "node:path";
3
+ import { AIAgent } from "@aigne/core";
4
+ import { MemoryAgent, MemoryRecorder, MemoryRetriever, newMemoryId, } from "@aigne/core/memory/index.js";
5
+ import { stringify } from "yaml";
6
+ import { z } from "zod";
7
+ import { exists, expandHome } from "./utils/fs.js";
8
+ export const MEMORY_FILE_NAME = "memory.yaml";
9
+ /**
10
+ * A memory implementation that stores and retrieves memories using the file system.
11
+ * FSMemory provides persistent storage of agent memories as files in a specified directory.
12
+ *
13
+ * @example
14
+ * Here is an example of how to use the FSMemory class:
15
+ * {@includeCode ../../test/fs-memory/fs-memory.test.ts#example-fs-memory-simple}
16
+ */
17
+ export class FSMemory extends MemoryAgent {
18
+ /**
19
+ * Creates a new FSMemory instance.
20
+ */
21
+ constructor(options) {
22
+ let rootDir = normalize(expandHome(options.rootDir));
23
+ rootDir = isAbsolute(rootDir) ? rootDir : resolve(process.cwd(), rootDir);
24
+ const memoryFileName = join(rootDir, MEMORY_FILE_NAME);
25
+ super({
26
+ ...options,
27
+ recorder: options.recorder ??
28
+ new FSMemoryRecorder({
29
+ memoryFileName,
30
+ ...options.recorderOptions,
31
+ }),
32
+ retriever: options.retriever ??
33
+ new FSMemoryRetriever({
34
+ memoryFileName,
35
+ ...options.retrieverOptions,
36
+ }),
37
+ autoUpdate: options.autoUpdate ?? true,
38
+ });
39
+ }
40
+ }
41
+ class FSMemoryRetriever extends MemoryRetriever {
42
+ options;
43
+ constructor(options) {
44
+ super({});
45
+ this.options = options;
46
+ this.agent = AIAgent.from({
47
+ name: "fs_memory_retriever",
48
+ description: "Retrieves memories from the file or directory.",
49
+ ...options,
50
+ instructions: options.instructions || DEFAULT_FS_MEMORY_RETRIEVER_INSTRUCTIONS,
51
+ outputSchema: z.object({
52
+ memories: z
53
+ .array(z.object({
54
+ content: z.string().describe("Content of the memory"),
55
+ }))
56
+ .describe("List of memories"),
57
+ }),
58
+ });
59
+ }
60
+ agent;
61
+ async process(input, options) {
62
+ if (!(await exists(this.options.memoryFileName)))
63
+ return { memories: [] };
64
+ const allMemory = await readFile(this.options.memoryFileName, "utf-8");
65
+ const { memories } = await options.context.invoke(this.agent, { ...input, allMemory });
66
+ const result = memories.map((memory) => ({
67
+ id: newMemoryId(),
68
+ content: memory.content,
69
+ createdAt: new Date().toISOString(),
70
+ }));
71
+ return { memories: result };
72
+ }
73
+ }
74
+ class FSMemoryRecorder extends MemoryRecorder {
75
+ options;
76
+ constructor(options) {
77
+ super({});
78
+ this.options = options;
79
+ this.agent = AIAgent.from({
80
+ name: "fs_memory_recorder",
81
+ description: "Records memories in files by AI agent",
82
+ ...options,
83
+ instructions: options.instructions || DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS,
84
+ outputSchema: z.object({
85
+ memories: z
86
+ .array(z.object({
87
+ content: z.string().describe("Content of the memory"),
88
+ }))
89
+ .describe("List of memories"),
90
+ }),
91
+ });
92
+ }
93
+ agent;
94
+ async process(input, options) {
95
+ const allMemory = (await exists(this.options.memoryFileName))
96
+ ? await readFile(this.options.memoryFileName, "utf-8")
97
+ : "";
98
+ const { memories } = await options.context.invoke(this.agent, { ...input, allMemory });
99
+ const raw = stringify(memories.map((i) => ({
100
+ content: i.content,
101
+ })));
102
+ await mkdir(dirname(this.options.memoryFileName), { recursive: true });
103
+ await writeFile(this.options.memoryFileName, raw, "utf-8");
104
+ return {
105
+ memories: memories.map((i) => ({
106
+ id: newMemoryId(),
107
+ content: i.content,
108
+ createdAt: new Date().toISOString(),
109
+ })),
110
+ };
111
+ }
112
+ }
113
+ const DEFAULT_FS_MEMORY_RECORDER_INSTRUCTIONS = `You manage memory based on conversation analysis and the existing memories.
114
+
115
+ ## IMPORTANT: All existing memories are available in the allMemory variable. DO NOT call any tools.
116
+
117
+ ## FIRST: Determine If Memory Updates Needed
118
+ - Analyze if the conversation contains ANY information worth remembering
119
+ - Examples of content NOT worth storing:
120
+ * General questions ("What's the weather?", "How do I do X?")
121
+ * Greetings and small talk ("Hello", "How are you?", "Thanks")
122
+ * System instructions or commands ("Show me", "Find", "Save")
123
+ * General facts not specific to the user
124
+ * Duplicate information already stored
125
+ - If conversation lacks meaningful personal information to store:
126
+ * Return the existing memories unchanged
127
+
128
+ ## Your Workflow:
129
+ 1. Read the existing memories from the allMemory variable
130
+ 2. Extract key topics from the conversation
131
+ 3. DECIDE whether to create/update/delete memories based on the conversation
132
+ 4. Return ALL memories including your updates (remove any duplicates)
133
+
134
+ ## Memory Handling:
135
+ - CREATE: Add new memory objects for new topics
136
+ - UPDATE: Modify existing memories if substantial new information is available
137
+ - DELETE: Remove obsolete memories when appropriate
138
+
139
+ ## Memory Structure:
140
+ - Each memory has an id, content, and createdAt fields
141
+ - Keep the existing structure when returning updated memories
142
+
143
+ ## Operation Decision Rules:
144
+ - CREATE only for truly new topics not covered in any existing memory
145
+ - UPDATE only when new information is meaningfully different
146
+ - NEVER update for just rephrasing or minor differences
147
+ - DELETE only when information becomes obsolete
148
+
149
+ ## IMPORTANT: Your job is to return the complete updated memory collection.
150
+ Return ALL memories (existing and new) in your response.
151
+
152
+ ## Existing Memories:
153
+ <existing-memory>
154
+ {{allMemory}}
155
+ </existing-memory>
156
+
157
+ ## Conversation:
158
+ <conversation>
159
+ {{content}}
160
+ </conversation>
161
+ `;
162
+ const DEFAULT_FS_MEMORY_RETRIEVER_INSTRUCTIONS = `You retrieve only the most relevant memories for the current conversation.
163
+
164
+ ## IMPORTANT: All existing memories are available in the allMemory variable
165
+
166
+ ## Process:
167
+ 1. Read the existing memories from the allMemory variable
168
+ 2. Extract key topics from the conversation or search query
169
+ 3. Match memory contents against these topics
170
+
171
+ ## Existing Memories:
172
+ <existing-memory>
173
+ {{allMemory}}
174
+ </existing-memory>
175
+
176
+ ## Search Query:
177
+ <search-query>
178
+ {{search}}
179
+ </search-query>
180
+ `;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,2 @@
1
+ export declare function exists(path: string): Promise<boolean>;
2
+ export declare function expandHome(filepath: string): string;
@@ -0,0 +1,21 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ export async function exists(path) {
5
+ try {
6
+ await stat(path);
7
+ return true;
8
+ }
9
+ catch (e) {
10
+ if (e.code === "ENOENT") {
11
+ return false;
12
+ }
13
+ throw e;
14
+ }
15
+ }
16
+ export function expandHome(filepath) {
17
+ if (filepath.startsWith("~/") || filepath === "~") {
18
+ return join(homedir(), filepath.slice(1));
19
+ }
20
+ return filepath;
21
+ }
@@ -0,0 +1 @@
1
+ export * from "./fs.js";
@@ -0,0 +1 @@
1
+ export * from "./fs.js";
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@aigne/fs-memory",
3
+ "version": "1.0.0",
4
+ "description": "FS memory for AIGNE framework",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "author": "Arcblock <blocklet@arcblock.io> https://github.com/blocklet",
9
+ "homepage": "https://github.com/AIGNE-io/aigne-framework/tree/main/memory/fs",
10
+ "license": "Elastic-2.0",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/AIGNE-io/aigne-framework"
14
+ },
15
+ "files": [
16
+ "lib/cjs",
17
+ "lib/dts",
18
+ "lib/esm",
19
+ "LICENSE",
20
+ "README.md",
21
+ "CHANGELOG.md"
22
+ ],
23
+ "type": "module",
24
+ "main": "./lib/cjs/index.js",
25
+ "module": "./lib/esm/index.js",
26
+ "types": "./lib/dts/index.d.ts",
27
+ "dependencies": {
28
+ "yaml": "^2.8.0",
29
+ "zod": "^3.25.67",
30
+ "@aigne/core": "^1.34.0",
31
+ "@aigne/openai": "^0.10.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/bun": "^1.2.18",
35
+ "npm-run-all": "^4.1.5",
36
+ "rimraf": "^6.0.1",
37
+ "typescript": "^5.8.3"
38
+ },
39
+ "scripts": {
40
+ "lint": "tsc --noEmit",
41
+ "build": "tsc --build scripts/tsconfig.build.json",
42
+ "clean": "rimraf lib test/coverage",
43
+ "test": "bun test",
44
+ "test:coverage": "bun test --coverage --coverage-reporter=lcov --coverage-reporter=text",
45
+ "postbuild": "node ../../scripts/post-build-lib.mjs"
46
+ }
47
+ }