@aigne/afs-history 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.
Files changed (36) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE.md +93 -0
  3. package/README.md +396 -0
  4. package/lib/cjs/index.d.ts +23 -0
  5. package/lib/cjs/index.js +60 -0
  6. package/lib/cjs/package.json +3 -0
  7. package/lib/cjs/storage/index.d.ts +25 -0
  8. package/lib/cjs/storage/index.js +87 -0
  9. package/lib/cjs/storage/migrate.d.ts +3 -0
  10. package/lib/cjs/storage/migrate.js +31 -0
  11. package/lib/cjs/storage/migrations/001-init.d.ts +2 -0
  12. package/lib/cjs/storage/migrations/001-init.js +25 -0
  13. package/lib/cjs/storage/models/entries.d.ts +199 -0
  14. package/lib/cjs/storage/models/entries.js +28 -0
  15. package/lib/cjs/storage/type.d.ts +23 -0
  16. package/lib/cjs/storage/type.js +2 -0
  17. package/lib/dts/index.d.ts +23 -0
  18. package/lib/dts/storage/index.d.ts +25 -0
  19. package/lib/dts/storage/migrate.d.ts +3 -0
  20. package/lib/dts/storage/migrations/001-init.d.ts +2 -0
  21. package/lib/dts/storage/models/entries.d.ts +199 -0
  22. package/lib/dts/storage/type.d.ts +23 -0
  23. package/lib/esm/index.d.ts +23 -0
  24. package/lib/esm/index.js +42 -0
  25. package/lib/esm/package.json +3 -0
  26. package/lib/esm/storage/index.d.ts +25 -0
  27. package/lib/esm/storage/index.js +68 -0
  28. package/lib/esm/storage/migrate.d.ts +3 -0
  29. package/lib/esm/storage/migrate.js +28 -0
  30. package/lib/esm/storage/migrations/001-init.d.ts +2 -0
  31. package/lib/esm/storage/migrations/001-init.js +22 -0
  32. package/lib/esm/storage/models/entries.d.ts +199 -0
  33. package/lib/esm/storage/models/entries.js +23 -0
  34. package/lib/esm/storage/type.d.ts +23 -0
  35. package/lib/esm/storage/type.js +1 -0
  36. package/package.json +69 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2025-11-14)
4
+
5
+
6
+ ### Features
7
+
8
+ * support mount mcp agent into AFS ([#740](https://github.com/AIGNE-io/aigne-framework/issues/740)) ([6d474fc](https://github.com/AIGNE-io/aigne-framework/commit/6d474fc05845a15e2c3e8fa97727b409bdd70945))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @aigne/afs bumped to 1.2.0-beta
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,396 @@
1
+ # @aigne/afs-history
2
+
3
+ **@aigne/afs-history** is a history tracking module for the Agentic File System (AFS). It automatically records conversation history and agent interactions, storing them in a persistent SQLite database.
4
+
5
+ ## Overview
6
+
7
+ AFSHistory is an AFS module that listens to agent events and automatically records conversation history. Each conversation is stored with a unique identifier, making it easy to retrieve and review past interactions.
8
+
9
+ ## Features
10
+
11
+ - **Automatic Recording**: Listens to `agentSucceed` events and automatically stores conversation history
12
+ - **SQLite Storage**: Uses SQLite database for persistent, structured storage
13
+ - **UUID-based Paths**: Each conversation is stored with a UUID v7 path for easy retrieval
14
+ - **Event Integration**: Emits `historyCreated` events when new history entries are recorded
15
+ - **Full CRUD Support**: Supports list, read, and write operations
16
+ - **Shared Storage**: Can share storage with other AFS modules using `SharedAFSStorage`
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @aigne/afs-history
22
+ # or
23
+ yarn add @aigne/afs-history
24
+ # or
25
+ pnpm add @aigne/afs-history
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```typescript
31
+ import { AFS } from "@aigne/afs";
32
+ import { AFSHistory } from "@aigne/afs-history";
33
+
34
+ // Create AFS instance
35
+ const afs = new AFS();
36
+
37
+ // Mount history module
38
+ afs.mount(new AFSHistory({
39
+ storage: { url: "file:./memory.sqlite3" }
40
+ }));
41
+
42
+ // History entries are now accessible at /modules/history
43
+ const { list } = await afs.list('/modules/history');
44
+ console.log(list); // Array of conversation history entries
45
+ ```
46
+
47
+ ## Configuration
48
+
49
+ ### AFSHistoryOptions
50
+
51
+ ```typescript
52
+ interface AFSHistoryOptions {
53
+ storage?: SharedAFSStorage | SharedAFSStorageOptions;
54
+ }
55
+ ```
56
+
57
+ #### Storage Options
58
+
59
+ ```typescript
60
+ interface SharedAFSStorageOptions {
61
+ url?: string; // Database URL (default: ":memory:")
62
+ }
63
+ ```
64
+
65
+ **Examples:**
66
+
67
+ ```typescript
68
+ // In-memory database (default)
69
+ new AFSHistory()
70
+
71
+ // File-based database
72
+ new AFSHistory({
73
+ storage: { url: "file:./memory.sqlite3" }
74
+ })
75
+
76
+ // Shared storage instance
77
+ const sharedStorage = new SharedAFSStorage({ url: "file:./memory.sqlite3" });
78
+ new AFSHistory({ storage: sharedStorage })
79
+ ```
80
+
81
+ ## API Reference
82
+
83
+ ### AFSHistory Class
84
+
85
+ #### Constructor
86
+
87
+ ```typescript
88
+ new AFSHistory(options?: AFSHistoryOptions)
89
+ ```
90
+
91
+ #### Properties
92
+
93
+ - `name`: `string` - Module name (always `"history"`)
94
+
95
+ #### Methods
96
+
97
+ ##### list(path: string, options?: AFSListOptions)
98
+
99
+ List history entries:
100
+
101
+ ```typescript
102
+ const { list } = await afs.list('/modules/history');
103
+
104
+ // With options
105
+ const { list } = await afs.list('/modules/history', {
106
+ maxDepth: 1,
107
+ limit: 10,
108
+ offset: 0
109
+ });
110
+ ```
111
+
112
+ **Returns:** `Promise<{ list: AFSEntry[] }>`
113
+
114
+ **Note:** Only root path `/` is supported. Subdirectories return empty arrays.
115
+
116
+ ##### read(path: string)
117
+
118
+ Read a specific history entry:
119
+
120
+ ```typescript
121
+ const { result } = await afs.read('/modules/history/01933e4e-7c8f-7000-8000-123456789abc');
122
+
123
+ if (result) {
124
+ console.log(result.content.input); // Original input
125
+ console.log(result.content.output); // Agent's output
126
+ console.log(result.createdAt); // Timestamp
127
+ }
128
+ ```
129
+
130
+ **Returns:** `Promise<{ result?: AFSEntry; message?: string }>`
131
+
132
+ ##### write(path: string, content: AFSWriteEntryPayload)
133
+
134
+ Manually create a history entry:
135
+
136
+ ```typescript
137
+ const { result } = await afs.write('/modules/history/custom-id', {
138
+ content: {
139
+ input: "User question",
140
+ output: "Agent response"
141
+ },
142
+ summary: "Conversation summary",
143
+ metadata: { tags: ["important"] }
144
+ });
145
+ ```
146
+
147
+ **Returns:** `Promise<{ result: AFSEntry; message?: string }>`
148
+
149
+ #### Lifecycle
150
+
151
+ ##### onMount(afs: AFSRoot)
152
+
153
+ Called when the module is mounted. Sets up event listeners:
154
+
155
+ ```typescript
156
+ onMount(afs: AFSRoot) {
157
+ afs.on('agentSucceed', ({ input, output }) => {
158
+ // Automatically stores history
159
+ });
160
+ }
161
+ ```
162
+
163
+ ## Data Structure
164
+
165
+ ### AFSEntry Format
166
+
167
+ History entries follow the standard AFSEntry structure:
168
+
169
+ ```typescript
170
+ interface AFSEntry {
171
+ id: string; // UUID v7
172
+ path: string; // Full path in AFS (e.g., "/modules/history/01933e4e...")
173
+ content: {
174
+ input: string | object; // Original input to agent
175
+ output: string | object; // Agent's output
176
+ };
177
+ summary?: string; // Optional summary
178
+ metadata?: Record<string, any>; // Custom metadata
179
+ createdAt: Date; // Creation timestamp
180
+ updatedAt: Date; // Last update timestamp
181
+ userId?: string; // Associated user (if available)
182
+ sessionId?: string; // Associated session (if available)
183
+ linkTo?: string; // Link to another entry
184
+ }
185
+ ```
186
+
187
+ ### Database Schema
188
+
189
+ History entries are stored in SQLite with the following schema:
190
+
191
+ ```sql
192
+ CREATE TABLE Entries_history (
193
+ "id" TEXT NOT NULL PRIMARY KEY,
194
+ "createdAt" DATETIME NOT NULL,
195
+ "updatedAt" DATETIME NOT NULL,
196
+ "path" TEXT NOT NULL UNIQUE,
197
+ "userId" TEXT,
198
+ "sessionId" TEXT,
199
+ "summary" TEXT,
200
+ "metadata" JSON,
201
+ "linkTo" TEXT,
202
+ "content" JSON
203
+ )
204
+ ```
205
+
206
+ ## Events
207
+
208
+ ### Listening to Events
209
+
210
+ AFSHistory listens to these events from the AFS root:
211
+
212
+ - `agentSucceed`: Triggered when an agent successfully completes. Automatically creates a history entry.
213
+
214
+ ### Emitting Events
215
+
216
+ AFSHistory emits these events:
217
+
218
+ - `historyCreated`: Emitted after a history entry is successfully created
219
+
220
+ **Example:**
221
+
222
+ ```typescript
223
+ afs.on('historyCreated', ({ entry }) => {
224
+ console.log('New history entry:', entry.id);
225
+ console.log('Input:', entry.content.input);
226
+ console.log('Output:', entry.content.output);
227
+ });
228
+ ```
229
+
230
+ ## Usage with AI Agents
231
+
232
+ When AFS is configured with an AI agent, history tracking happens automatically:
233
+
234
+ ```typescript
235
+ import { AIGNE, AIAgent } from "@aigne/core";
236
+ import { AFS } from "@aigne/afs";
237
+ import { AFSHistory } from "@aigne/afs-history";
238
+ import { OpenAIChatModel } from "@aigne/openai";
239
+
240
+ // Create AIGNE instance
241
+ const aigne = new AIGNE({
242
+ model: new OpenAIChatModel({ apiKey: process.env.OPENAI_API_KEY })
243
+ });
244
+
245
+ // Create AFS with history
246
+ const afs = new AFS();
247
+ afs.mount(new AFSHistory({
248
+ storage: { url: "file:./memory.sqlite3" }
249
+ }));
250
+
251
+ // Create agent
252
+ const agent = AIAgent.from({
253
+ name: "assistant",
254
+ instructions: "You are a helpful assistant",
255
+ afs
256
+ });
257
+
258
+ // Use the agent - history is automatically tracked
259
+ const context = aigne.newContext();
260
+ const result = await context.invoke(agent, {
261
+ message: "Hello, how are you?"
262
+ });
263
+
264
+ // View history
265
+ const { list } = await afs.list('/modules/history');
266
+ console.log(`Total conversations: ${list.length}`);
267
+ ```
268
+
269
+ ## Advanced Usage
270
+
271
+ ### Shared Storage
272
+
273
+ Share storage between multiple AFS modules:
274
+
275
+ ```typescript
276
+ import { SharedAFSStorage } from "@aigne/afs-history";
277
+
278
+ const storage = new SharedAFSStorage({
279
+ url: "file:./shared-memory.sqlite3"
280
+ });
281
+
282
+ const history = new AFSHistory({ storage });
283
+ const customModule = new CustomModule({ storage });
284
+
285
+ afs.mount(history);
286
+ afs.mount(customModule);
287
+ ```
288
+
289
+ ### Custom Event Handling
290
+
291
+ React to history creation:
292
+
293
+ ```typescript
294
+ afs.on('historyCreated', async ({ entry }) => {
295
+ // Custom processing
296
+ console.log(`Stored conversation ${entry.id}`);
297
+
298
+ // Update external analytics
299
+ await analytics.track('conversation_stored', {
300
+ entryId: entry.id,
301
+ timestamp: entry.createdAt
302
+ });
303
+ });
304
+ ```
305
+
306
+ ### Manual History Recording
307
+
308
+ Manually record history without agent events:
309
+
310
+ ```typescript
311
+ const { result } = await afs.write('/modules/history/manual-entry', {
312
+ content: {
313
+ input: "Manual input",
314
+ output: "Manual output"
315
+ },
316
+ summary: "Manually recorded conversation",
317
+ metadata: {
318
+ source: "manual",
319
+ tags: ["important", "review"]
320
+ },
321
+ userId: "user-123",
322
+ sessionId: "session-456"
323
+ });
324
+ ```
325
+
326
+ ### Searching History
327
+
328
+ If your storage implementation supports search:
329
+
330
+ ```typescript
331
+ const { list } = await afs.search('/modules/history', 'authentication error');
332
+
333
+ for (const entry of list) {
334
+ console.log(`Found in ${entry.id}:`, entry.content);
335
+ }
336
+ ```
337
+
338
+ ## Migration from @aigne/afs
339
+
340
+ If you were previously using AFSHistory from `@aigne/afs`, update your imports:
341
+
342
+ **Before:**
343
+ ```typescript
344
+ import { AFS, AFSHistory } from "@aigne/afs";
345
+ ```
346
+
347
+ **After:**
348
+ ```typescript
349
+ import { AFS } from "@aigne/afs";
350
+ import { AFSHistory } from "@aigne/afs-history";
351
+ ```
352
+
353
+ No other changes are required - the API remains identical.
354
+
355
+ ## TypeScript Support
356
+
357
+ This package includes full TypeScript type definitions:
358
+
359
+ ```typescript
360
+ import type {
361
+ AFSHistory,
362
+ AFSHistoryOptions,
363
+ AFSStorage,
364
+ SharedAFSStorage,
365
+ SharedAFSStorageOptions,
366
+ AFSStorageWithModule,
367
+ AFSStorageCreatePayload,
368
+ AFSStorageListOptions
369
+ } from "@aigne/afs-history";
370
+ ```
371
+
372
+ ## Testing
373
+
374
+ Run the test suite:
375
+
376
+ ```bash
377
+ # Run tests
378
+ npm test
379
+
380
+ # Run with coverage
381
+ npm run test:coverage
382
+ ```
383
+
384
+ ## License
385
+
386
+ [Elastic-2.0](../../LICENSE.md)
387
+
388
+ ## Related Packages
389
+
390
+ - [@aigne/afs](../core/README.md) - Core AFS implementation
391
+ - [@aigne/afs-local-fs](../local-fs/README.md) - Local file system module
392
+ - [@aigne/afs-user-profile-memory](../user-profile-memory/README.md) - User profile memory module
393
+
394
+ ## Examples
395
+
396
+ See the [AFS examples](../../examples/afs-memory/README.md) for more usage examples.
@@ -0,0 +1,23 @@
1
+ import type { AFSEntry, AFSListOptions, AFSModule, AFSRoot, AFSWriteEntryPayload } from "@aigne/afs";
2
+ import { SharedAFSStorage, type SharedAFSStorageOptions } from "./storage/index.js";
3
+ export * from "./storage/index.js";
4
+ export interface AFSHistoryOptions {
5
+ storage?: SharedAFSStorage | SharedAFSStorageOptions;
6
+ }
7
+ export declare class AFSHistory implements AFSModule {
8
+ constructor(options?: AFSHistoryOptions);
9
+ private storage;
10
+ readonly name: string;
11
+ onMount(afs: AFSRoot): void;
12
+ list(path: string, options?: AFSListOptions): Promise<{
13
+ list: AFSEntry[];
14
+ }>;
15
+ read(path: string): Promise<{
16
+ result: AFSEntry | undefined;
17
+ message?: string;
18
+ }>;
19
+ write(path: string, content: AFSWriteEntryPayload): Promise<{
20
+ result: AFSEntry;
21
+ message?: string;
22
+ }>;
23
+ }
@@ -0,0 +1,60 @@
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
+ exports.AFSHistory = void 0;
18
+ const uuid_1 = require("@aigne/uuid");
19
+ const ufo_1 = require("ufo");
20
+ const index_js_1 = require("./storage/index.js");
21
+ __exportStar(require("./storage/index.js"), exports);
22
+ class AFSHistory {
23
+ constructor(options) {
24
+ this.storage =
25
+ options?.storage instanceof index_js_1.SharedAFSStorage
26
+ ? options.storage.withModule(this)
27
+ : new index_js_1.SharedAFSStorage(options?.storage).withModule(this);
28
+ }
29
+ storage;
30
+ name = "history";
31
+ onMount(afs) {
32
+ afs.on("agentSucceed", ({ input, output }) => {
33
+ this.storage
34
+ .create({
35
+ path: (0, ufo_1.joinURL)("/", (0, uuid_1.v7)()),
36
+ content: { input, output },
37
+ })
38
+ .then((entry) => {
39
+ afs.emit("historyCreated", { entry });
40
+ })
41
+ .catch((error) => {
42
+ console.error("Failed to store history entry", error);
43
+ });
44
+ });
45
+ }
46
+ async list(path, options) {
47
+ if (path !== "/")
48
+ return { list: [] };
49
+ return await this.storage.list(options);
50
+ }
51
+ async read(path) {
52
+ const result = await this.storage.read(path);
53
+ return { result };
54
+ }
55
+ async write(path, content) {
56
+ const result = await this.storage.create({ ...content, path });
57
+ return { result };
58
+ }
59
+ }
60
+ exports.AFSHistory = AFSHistory;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,25 @@
1
+ import type { AFSEntry, AFSModule } from "@aigne/afs";
2
+ import { initDatabase } from "@aigne/sqlite";
3
+ import { entriesTable } from "./models/entries.js";
4
+ import type { AFSStorage, AFSStorageCreatePayload, AFSStorageListOptions } from "./type.js";
5
+ export * from "./type.js";
6
+ export interface SharedAFSStorageOptions {
7
+ url?: string;
8
+ }
9
+ export declare class SharedAFSStorage {
10
+ options?: SharedAFSStorageOptions | undefined;
11
+ constructor(options?: SharedAFSStorageOptions | undefined);
12
+ private _db;
13
+ get db(): Promise<import("drizzle-orm/libsql/driver-core.js").LibSQLDatabase<Record<string, never>> | import("drizzle-orm/sqlite-proxy/driver.js").SqliteRemoteDatabase<Record<string, never>>>;
14
+ withModule(module: AFSModule): AFSStorage;
15
+ }
16
+ export declare class AFSStorageWithModule implements AFSStorage {
17
+ private db;
18
+ private table;
19
+ constructor(db: ReturnType<typeof initDatabase>, table: Promise<ReturnType<typeof entriesTable>>);
20
+ list(options?: AFSStorageListOptions): Promise<{
21
+ list: AFSEntry[];
22
+ }>;
23
+ read(path: string): Promise<AFSEntry | undefined>;
24
+ create(entry: AFSStorageCreatePayload): Promise<AFSEntry>;
25
+ }
@@ -0,0 +1,87 @@
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
+ exports.AFSStorageWithModule = exports.SharedAFSStorage = void 0;
18
+ const sqlite_1 = require("@aigne/sqlite");
19
+ const migrate_js_1 = require("./migrate.js");
20
+ const entries_js_1 = require("./models/entries.js");
21
+ __exportStar(require("./type.js"), exports);
22
+ const DEFAULT_AFS_STORAGE_LIST_LIMIT = 10;
23
+ class SharedAFSStorage {
24
+ options;
25
+ constructor(options) {
26
+ this.options = options;
27
+ }
28
+ _db;
29
+ get db() {
30
+ this._db ??= (0, sqlite_1.initDatabase)({ url: this.options?.url });
31
+ return this._db;
32
+ }
33
+ withModule(module) {
34
+ return new AFSStorageWithModule(this.db, (0, migrate_js_1.migrate)(this.db, module).then(() => (0, entries_js_1.entriesTable)(module)));
35
+ }
36
+ }
37
+ exports.SharedAFSStorage = SharedAFSStorage;
38
+ class AFSStorageWithModule {
39
+ db;
40
+ table;
41
+ constructor(db, table) {
42
+ this.db = db;
43
+ this.table = table;
44
+ }
45
+ async list(options = {}) {
46
+ const { filter, limit = DEFAULT_AFS_STORAGE_LIST_LIMIT } = options;
47
+ const db = await this.db;
48
+ const table = await this.table;
49
+ const list = await db
50
+ .select()
51
+ .from(table)
52
+ .where((0, sqlite_1.and)(filter?.userId ? (0, sqlite_1.eq)(table.userId, filter.userId) : undefined, filter?.sessionId ? (0, sqlite_1.eq)(table.sessionId, filter.sessionId) : undefined))
53
+ .orderBy(...(options.orderBy ?? []).map((item) => (item[1] === "asc" ? sqlite_1.asc : sqlite_1.desc)(sqlite_1.sql.identifier(item[0]))))
54
+ .limit(limit)
55
+ .execute();
56
+ return { list };
57
+ }
58
+ async read(path) {
59
+ const db = await this.db;
60
+ const table = await this.table;
61
+ return db
62
+ .select()
63
+ .from(table)
64
+ .where((0, sqlite_1.eq)(table.path, path))
65
+ .limit(1)
66
+ .execute()
67
+ .then((memory) => memory.at(0));
68
+ }
69
+ async create(entry) {
70
+ const db = await this.db;
71
+ const table = await this.table;
72
+ let result = await db
73
+ .update(table)
74
+ .set(entry)
75
+ .where((0, sqlite_1.eq)(table.path, entry.path))
76
+ .returning()
77
+ .execute();
78
+ if (!result.length) {
79
+ result = await db.insert(table).values(entry).returning().execute();
80
+ }
81
+ const [res] = result;
82
+ if (!res)
83
+ throw new Error("Failed to create AFS entry, no result");
84
+ return res;
85
+ }
86
+ }
87
+ exports.AFSStorageWithModule = AFSStorageWithModule;