@aigne/afs-history 1.1.3 → 1.2.0-beta.10

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 (55) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/lib/cjs/index.d.ts +38 -13
  3. package/lib/cjs/index.js +244 -23
  4. package/lib/cjs/storage/index.d.ts +11 -7
  5. package/lib/cjs/storage/index.js +69 -23
  6. package/lib/cjs/storage/migrate.d.ts +1 -1
  7. package/lib/cjs/storage/migrate.js +15 -5
  8. package/lib/cjs/storage/migrations/002-add-agent-id.d.ts +2 -0
  9. package/lib/cjs/storage/migrations/002-add-agent-id.js +13 -0
  10. package/lib/cjs/storage/migrations/003-add-compact-table.d.ts +2 -0
  11. package/lib/cjs/storage/migrations/003-add-compact-table.js +23 -0
  12. package/lib/cjs/storage/migrations/004-add-memory-table.d.ts +2 -0
  13. package/lib/cjs/storage/migrations/004-add-memory-table.js +23 -0
  14. package/lib/cjs/storage/migrations/005-add-indexes.d.ts +2 -0
  15. package/lib/cjs/storage/migrations/005-add-indexes.js +31 -0
  16. package/lib/cjs/storage/models/compact.d.ts +183 -0
  17. package/lib/cjs/storage/models/compact.js +27 -0
  18. package/lib/cjs/storage/models/entries.d.ts +19 -0
  19. package/lib/cjs/storage/models/entries.js +1 -0
  20. package/lib/cjs/storage/models/memory.d.ts +182 -0
  21. package/lib/cjs/storage/models/memory.js +27 -0
  22. package/lib/cjs/storage/type.d.ts +33 -5
  23. package/lib/dts/index.d.ts +38 -13
  24. package/lib/dts/storage/index.d.ts +11 -7
  25. package/lib/dts/storage/migrate.d.ts +1 -1
  26. package/lib/dts/storage/migrations/002-add-agent-id.d.ts +2 -0
  27. package/lib/dts/storage/migrations/003-add-compact-table.d.ts +2 -0
  28. package/lib/dts/storage/migrations/004-add-memory-table.d.ts +2 -0
  29. package/lib/dts/storage/migrations/005-add-indexes.d.ts +2 -0
  30. package/lib/dts/storage/models/compact.d.ts +183 -0
  31. package/lib/dts/storage/models/entries.d.ts +19 -0
  32. package/lib/dts/storage/models/memory.d.ts +182 -0
  33. package/lib/dts/storage/type.d.ts +33 -5
  34. package/lib/esm/index.d.ts +38 -13
  35. package/lib/esm/index.js +244 -23
  36. package/lib/esm/storage/index.d.ts +11 -7
  37. package/lib/esm/storage/index.js +70 -24
  38. package/lib/esm/storage/migrate.d.ts +1 -1
  39. package/lib/esm/storage/migrate.js +15 -5
  40. package/lib/esm/storage/migrations/002-add-agent-id.d.ts +2 -0
  41. package/lib/esm/storage/migrations/002-add-agent-id.js +10 -0
  42. package/lib/esm/storage/migrations/003-add-compact-table.d.ts +2 -0
  43. package/lib/esm/storage/migrations/003-add-compact-table.js +20 -0
  44. package/lib/esm/storage/migrations/004-add-memory-table.d.ts +2 -0
  45. package/lib/esm/storage/migrations/004-add-memory-table.js +20 -0
  46. package/lib/esm/storage/migrations/005-add-indexes.d.ts +2 -0
  47. package/lib/esm/storage/migrations/005-add-indexes.js +28 -0
  48. package/lib/esm/storage/models/compact.d.ts +183 -0
  49. package/lib/esm/storage/models/compact.js +22 -0
  50. package/lib/esm/storage/models/entries.d.ts +19 -0
  51. package/lib/esm/storage/models/entries.js +1 -0
  52. package/lib/esm/storage/models/memory.d.ts +182 -0
  53. package/lib/esm/storage/models/memory.js +22 -0
  54. package/lib/esm/storage/type.d.ts +33 -5
  55. package/package.json +5 -3
package/CHANGELOG.md CHANGED
@@ -6,6 +6,141 @@
6
6
  * dependencies
7
7
  * @aigne/afs bumped to 1.2.0
8
8
 
9
+ ## [1.2.0-beta.10](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.9...afs-history-v1.2.0-beta.10) (2026-01-14)
10
+
11
+
12
+ ### Features
13
+
14
+ * **afs:** add module access control and schema validation support ([#904](https://github.com/AIGNE-io/aigne-framework/issues/904)) ([d0b279a](https://github.com/AIGNE-io/aigne-framework/commit/d0b279aac07ebe2bcc1fd4148498fc3f6bbcd561))
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * improve test coverage tracking and reporting ([#903](https://github.com/AIGNE-io/aigne-framework/issues/903)) ([031144e](https://github.com/AIGNE-io/aigne-framework/commit/031144e74f29e882cffe52ffda8f7a18c76ace7f))
20
+
21
+
22
+ ### Dependencies
23
+
24
+ * The following workspace dependencies were updated
25
+ * dependencies
26
+ * @aigne/afs bumped to 1.4.0-beta.9
27
+ * @aigne/sqlite bumped to 0.4.9-beta.2
28
+
29
+ ## [1.2.0-beta.9](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.8...afs-history-v1.2.0-beta.9) (2026-01-12)
30
+
31
+
32
+ ### Dependencies
33
+
34
+ * The following workspace dependencies were updated
35
+ * dependencies
36
+ * @aigne/afs bumped to 1.4.0-beta.8
37
+
38
+ ## [1.2.0-beta.8](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.7...afs-history-v1.2.0-beta.8) (2026-01-08)
39
+
40
+
41
+ ### Bug Fixes
42
+
43
+ * bump version ([696560f](https://github.com/AIGNE-io/aigne-framework/commit/696560fa2673eddcb4d00ac0523fbbbde7273cb3))
44
+
45
+
46
+ ### Dependencies
47
+
48
+ * The following workspace dependencies were updated
49
+ * dependencies
50
+ * @aigne/afs bumped to 1.4.0-beta.7
51
+ * @aigne/sqlite bumped to 0.4.9-beta.1
52
+
53
+ ## [1.2.0-beta.7](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.6...afs-history-v1.2.0-beta.7) (2026-01-06)
54
+
55
+
56
+ ### Dependencies
57
+
58
+ * The following workspace dependencies were updated
59
+ * dependencies
60
+ * @aigne/afs bumped to 1.4.0-beta.6
61
+
62
+ ## [1.2.0-beta.6](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.5...afs-history-v1.2.0-beta.6) (2026-01-06)
63
+
64
+
65
+ ### Features
66
+
67
+ * **core:** add cross session user memory support ([#873](https://github.com/AIGNE-io/aigne-framework/issues/873)) ([f377aa1](https://github.com/AIGNE-io/aigne-framework/commit/f377aa17f2cf8004fd3225ade4a37fd90af1292f))
68
+
69
+ ## [1.2.0-beta.5](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.4...afs-history-v1.2.0-beta.5) (2025-12-31)
70
+
71
+
72
+ ### Features
73
+
74
+ * add session compact support for AIAgent ([#863](https://github.com/AIGNE-io/aigne-framework/issues/863)) ([9010918](https://github.com/AIGNE-io/aigne-framework/commit/9010918cd3f18b02b5c60ddc9ed5c34b568d0b28))
75
+
76
+
77
+ ### Dependencies
78
+
79
+ * The following workspace dependencies were updated
80
+ * dependencies
81
+ * @aigne/afs bumped to 1.4.0-beta.5
82
+
83
+ ## [1.2.0-beta.4](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.3...afs-history-v1.2.0-beta.4) (2025-12-26)
84
+
85
+
86
+ ### Features
87
+
88
+ * **core:** add session history support ([#858](https://github.com/AIGNE-io/aigne-framework/issues/858)) ([28a070e](https://github.com/AIGNE-io/aigne-framework/commit/28a070ed33b821d1fd344b899706d817ca992b9f))
89
+
90
+
91
+ ### Dependencies
92
+
93
+ * The following workspace dependencies were updated
94
+ * dependencies
95
+ * @aigne/afs bumped to 1.4.0-beta.4
96
+
97
+ ## [1.2.0-beta.3](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.2...afs-history-v1.2.0-beta.3) (2025-12-24)
98
+
99
+
100
+ ### Dependencies
101
+
102
+ * The following workspace dependencies were updated
103
+ * dependencies
104
+ * @aigne/afs bumped to 1.4.0-beta.3
105
+
106
+ ## [1.2.0-beta.2](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta.1...afs-history-v1.2.0-beta.2) (2025-12-19)
107
+
108
+
109
+ ### Dependencies
110
+
111
+ * The following workspace dependencies were updated
112
+ * dependencies
113
+ * @aigne/afs bumped to 1.4.0-beta.2
114
+
115
+ ## [1.2.0-beta.1](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.2.0-beta...afs-history-v1.2.0-beta.1) (2025-12-17)
116
+
117
+
118
+ ### Bug Fixes
119
+
120
+ * bump version ([70d217c](https://github.com/AIGNE-io/aigne-framework/commit/70d217c8360dd0dda7f5f17011c4e92ec836e801))
121
+
122
+
123
+ ### Dependencies
124
+
125
+ * The following workspace dependencies were updated
126
+ * dependencies
127
+ * @aigne/afs bumped to 1.4.0-beta.1
128
+ * @aigne/sqlite bumped to 0.4.9-beta
129
+
130
+ ## [1.2.0-beta](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.1.3...afs-history-v1.2.0-beta) (2025-12-17)
131
+
132
+
133
+ ### Features
134
+
135
+ * **afs:** support expand context into prompt template by call `$afs.xxx` ([#830](https://github.com/AIGNE-io/aigne-framework/issues/830)) ([5616acd](https://github.com/AIGNE-io/aigne-framework/commit/5616acd6ea257c91aa0b766608f45c5ce17f0345))
136
+
137
+
138
+ ### Dependencies
139
+
140
+ * The following workspace dependencies were updated
141
+ * dependencies
142
+ * @aigne/afs bumped to 1.4.0-beta
143
+
9
144
  ## [1.1.3](https://github.com/AIGNE-io/aigne-framework/compare/afs-history-v1.1.3-beta.3...afs-history-v1.1.3) (2025-12-12)
10
145
 
11
146
 
@@ -1,23 +1,48 @@
1
- import type { AFSEntry, AFSListOptions, AFSModule, AFSRoot, AFSWriteEntryPayload } from "@aigne/afs";
1
+ import { type AFSAccessMode, type AFSDeleteOptions, type AFSDeleteResult, type AFSListOptions, type AFSListResult, type AFSModule, type AFSModuleLoadParams, type AFSReadOptions, type AFSReadResult, type AFSRoot, type AFSWriteEntryPayload, type AFSWriteOptions, type AFSWriteResult } from "@aigne/afs";
2
+ import { z } from "zod";
2
3
  import { SharedAFSStorage, type SharedAFSStorageOptions } from "./storage/index.js";
3
4
  export * from "./storage/index.js";
4
5
  export interface AFSHistoryOptions {
5
6
  storage?: SharedAFSStorage | SharedAFSStorageOptions;
7
+ /**
8
+ * Access mode for this module.
9
+ * @default "readwrite"
10
+ */
11
+ accessMode?: AFSAccessMode;
6
12
  }
7
13
  export declare class AFSHistory implements AFSModule {
14
+ static schema(): z.ZodObject<{
15
+ storage: z.ZodOptional<z.ZodObject<{
16
+ url: z.ZodOptional<z.ZodString>;
17
+ }, "strip", z.ZodTypeAny, {
18
+ url?: string | undefined;
19
+ }, {
20
+ url?: string | undefined;
21
+ }>>;
22
+ accessMode: z.ZodOptional<z.ZodEnum<["readonly", "readwrite"]>>;
23
+ }, "strip", z.ZodTypeAny, {
24
+ storage?: {
25
+ url?: string | undefined;
26
+ } | undefined;
27
+ accessMode?: "readonly" | "readwrite" | undefined;
28
+ }, {
29
+ storage?: {
30
+ url?: string | undefined;
31
+ } | undefined;
32
+ accessMode?: "readonly" | "readwrite" | undefined;
33
+ }>;
34
+ static load({ parsed }: AFSModuleLoadParams): Promise<AFSHistory>;
8
35
  constructor(options?: AFSHistoryOptions);
9
- private storage;
10
36
  readonly name: string;
37
+ readonly accessMode: AFSAccessMode;
38
+ private storage;
39
+ private afs?;
40
+ private router;
41
+ private rootEntries;
11
42
  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
- }>;
43
+ list(path: string, options?: AFSListOptions): Promise<AFSListResult>;
44
+ read(path: string, options?: AFSReadOptions): Promise<AFSReadResult>;
45
+ write(path: string, content: AFSWriteEntryPayload, options: AFSWriteOptions): Promise<AFSWriteResult>;
46
+ delete(path: string, _options?: AFSDeleteOptions): Promise<AFSDeleteResult>;
47
+ private normalizePath;
23
48
  }
package/lib/cjs/index.js CHANGED
@@ -15,46 +15,267 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.AFSHistory = void 0;
18
+ const afs_1 = require("@aigne/afs");
18
19
  const uuid_1 = require("@aigne/uuid");
20
+ const radix3_1 = require("radix3");
19
21
  const ufo_1 = require("ufo");
22
+ const zod_1 = require("zod");
20
23
  const index_js_1 = require("./storage/index.js");
21
24
  __exportStar(require("./storage/index.js"), exports);
25
+ const sharedAFSStorageOptionsSchema = zod_1.z.object({
26
+ url: zod_1.z.string().describe("Database URL for storage").optional(),
27
+ });
28
+ const afsHistoryOptionsSchema = preprocessSchema((v) => {
29
+ if (!v || typeof v !== "object") {
30
+ return v;
31
+ }
32
+ return { ...v, accessMode: v.accessMode || v.access_mode };
33
+ }, zod_1.z.object({
34
+ storage: sharedAFSStorageOptionsSchema.optional(),
35
+ accessMode: afs_1.accessModeSchema,
36
+ }));
22
37
  class AFSHistory {
38
+ static schema() {
39
+ return afsHistoryOptionsSchema;
40
+ }
41
+ static async load({ parsed }) {
42
+ const valid = await AFSHistory.schema().parseAsync(parsed);
43
+ return new AFSHistory(valid);
44
+ }
23
45
  constructor(options) {
24
46
  this.storage =
25
47
  options?.storage instanceof index_js_1.SharedAFSStorage
26
48
  ? options.storage.withModule(this)
27
49
  : new index_js_1.SharedAFSStorage(options?.storage).withModule(this);
50
+ this.accessMode = options?.accessMode ?? "readwrite";
28
51
  }
29
- storage;
30
52
  name = "history";
53
+ accessMode;
54
+ storage;
55
+ afs;
56
+ router = (0, radix3_1.createRouter)({
57
+ routes: {
58
+ "/by-session": { action: "list", type: "history", scope: "session" },
59
+ "/by-session/:sessionId": { action: "list", type: "history", scope: "session" },
60
+ "/by-session/:sessionId/new": { action: "create", type: "history", scope: "session" },
61
+ "/by-session/:sessionId/@metadata/compact": {
62
+ action: "list",
63
+ type: "compact",
64
+ scope: "session",
65
+ },
66
+ "/by-session/:sessionId/@metadata/compact/new": {
67
+ action: "create",
68
+ type: "compact",
69
+ scope: "session",
70
+ },
71
+ "/by-session/:sessionId/@metadata/compact/:compactId": {
72
+ action: "read",
73
+ type: "compact",
74
+ scope: "session",
75
+ },
76
+ "/by-session/:sessionId/@metadata/memory": {
77
+ action: "list",
78
+ type: "memory",
79
+ scope: "session",
80
+ },
81
+ "/by-session/:sessionId/@metadata/memory/new": {
82
+ action: "create",
83
+ type: "memory",
84
+ scope: "session",
85
+ },
86
+ "/by-session/:sessionId/@metadata/memory/:memoryId": {
87
+ action: "read",
88
+ type: "memory",
89
+ scope: "session",
90
+ },
91
+ "/by-session/:sessionId/:entryId": { action: "read", type: "history", scope: "session" },
92
+ "/by-user": { action: "list", type: "history", scope: "user" },
93
+ "/by-user/:userId": { action: "list", type: "history", scope: "user" },
94
+ "/by-user/:userId/new": { action: "create", type: "history", scope: "user" },
95
+ "/by-user/:userId/@metadata/compact": { action: "list", type: "compact", scope: "user" },
96
+ "/by-user/:userId/@metadata/compact/new": {
97
+ action: "create",
98
+ type: "compact",
99
+ scope: "user",
100
+ },
101
+ "/by-user/:userId/@metadata/compact/:compactId": {
102
+ action: "read",
103
+ type: "compact",
104
+ scope: "user",
105
+ },
106
+ "/by-user/:userId/@metadata/memory": { action: "list", type: "memory", scope: "user" },
107
+ "/by-user/:userId/@metadata/memory/new": { action: "create", type: "memory", scope: "user" },
108
+ "/by-user/:userId/@metadata/memory/:memoryId": {
109
+ action: "read",
110
+ type: "memory",
111
+ scope: "user",
112
+ },
113
+ "/by-user/:userId/:entryId": { action: "read", type: "history", scope: "user" },
114
+ "/by-agent": { action: "list", type: "history", scope: "agent" },
115
+ "/by-agent/:agentId": { action: "list", type: "history", scope: "agent" },
116
+ "/by-agent/:agentId/new": { action: "create", type: "history", scope: "agent" },
117
+ "/by-agent/:agentId/@metadata/compact": { action: "list", type: "compact", scope: "agent" },
118
+ "/by-agent/:agentId/@metadata/compact/new": {
119
+ action: "create",
120
+ type: "compact",
121
+ scope: "agent",
122
+ },
123
+ "/by-agent/:agentId/@metadata/compact/:compactId": {
124
+ action: "read",
125
+ type: "compact",
126
+ scope: "agent",
127
+ },
128
+ "/by-agent/:agentId/:entryId": { action: "read", type: "history", scope: "agent" },
129
+ },
130
+ });
131
+ rootEntries = [
132
+ {
133
+ id: "by-session",
134
+ path: "/by-session",
135
+ description: "Retrieve history entries by session ID.",
136
+ },
137
+ {
138
+ id: "by-user",
139
+ path: "/by-user",
140
+ description: "Retrieve history entries by user ID.",
141
+ },
142
+ {
143
+ id: "by-agent",
144
+ path: "/by-agent",
145
+ description: "Retrieve history entries by agent ID.",
146
+ },
147
+ ];
31
148
  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
- });
149
+ this.afs = afs;
45
150
  }
46
151
  async list(path, options) {
47
- if (path !== "/")
48
- return { list: [] };
49
- return await this.storage.list(options);
152
+ if (path === "/")
153
+ return { data: this.rootEntries };
154
+ const match = this.router.lookup(path);
155
+ if (!match || match.action !== "list") {
156
+ return { data: [] };
157
+ }
158
+ const { type, scope } = match;
159
+ const mergedFilter = {
160
+ ...options?.filter,
161
+ ...match.params,
162
+ };
163
+ const result = await this.storage.list({
164
+ ...options,
165
+ type,
166
+ scope,
167
+ filter: mergedFilter,
168
+ });
169
+ return {
170
+ ...result,
171
+ data: result.data.map((entry) => ({
172
+ ...entry,
173
+ path: this.normalizePath(entry, scope, type),
174
+ })),
175
+ };
176
+ }
177
+ async read(path, options) {
178
+ const match = this.router.lookup(path);
179
+ if (!match || match.action !== "read")
180
+ return {};
181
+ const { type, scope } = match;
182
+ const entryId = match.params?.entryId ?? match.params?.compactId ?? match.params?.memoryId;
183
+ if (!entryId)
184
+ throw new Error(`Entry ID is required in the path to read ${type}.`);
185
+ const mergedFilter = {
186
+ ...options?.filter,
187
+ ...match.params,
188
+ };
189
+ const data = await this.storage.read(entryId, {
190
+ type,
191
+ scope,
192
+ filter: mergedFilter,
193
+ });
194
+ // Add virtual path prefix for entries
195
+ return {
196
+ data: data && {
197
+ ...data,
198
+ path: this.normalizePath(data, scope, type),
199
+ },
200
+ };
50
201
  }
51
- async read(path) {
52
- const result = await this.storage.read(path);
53
- return { result };
202
+ async write(path, content, options) {
203
+ const id = (0, uuid_1.v7)();
204
+ const match = this.router.lookup(path);
205
+ if (!match || match.action !== "create") {
206
+ throw new Error("Can only write to paths with 'new' suffix: /by-{scope}/{scopeId}/new or /by-{scope}/{scopeId}/@metadata/{type}/new");
207
+ }
208
+ const { type, scope } = match;
209
+ // Validate that scope ID is provided in path params
210
+ const scopeIdField = `${scope}Id`;
211
+ const scopeIdValue = match.params?.[scopeIdField];
212
+ if (!scopeIdValue) {
213
+ throw new Error(`${scopeIdField} is required in the path to create ${type} entry.`);
214
+ }
215
+ const entry = await this.storage.create({
216
+ ...match.params,
217
+ ...content,
218
+ id,
219
+ path: (0, ufo_1.joinURL)("/", type, id),
220
+ }, { type, scope });
221
+ // Emit event for history entries
222
+ if (type === "history") {
223
+ this.afs?.emit("historyCreated", { entry }, options);
224
+ }
225
+ return {
226
+ data: {
227
+ ...entry,
228
+ path: this.normalizePath(entry, scope, type),
229
+ },
230
+ };
54
231
  }
55
- async write(path, content) {
56
- const result = await this.storage.create({ ...content, path });
57
- return { result };
232
+ async delete(path, _options) {
233
+ const match = this.router.lookup(path);
234
+ if (!match || match.action !== "read") {
235
+ throw new Error(`Cannot delete: path not found or not a valid entry path`);
236
+ }
237
+ const { type, scope } = match;
238
+ const entryId = match.params?.entryId ?? match.params?.compactId ?? match.params?.memoryId;
239
+ if (!entryId)
240
+ throw new Error(`Entry ID is required in the path to delete ${type}.`);
241
+ const result = await this.storage.delete(entryId, {
242
+ type,
243
+ scope,
244
+ filter: match.params,
245
+ });
246
+ if (result.deletedCount === 0) {
247
+ return {
248
+ message: `No ${type} entry found with id ${entryId}`,
249
+ };
250
+ }
251
+ return {
252
+ message: `Deleted ${result.deletedCount} ${type} entry`,
253
+ };
254
+ }
255
+ normalizePath(entry, scope, entryType) {
256
+ const scopeIdMap = {
257
+ session: entry.sessionId,
258
+ user: entry.userId,
259
+ agent: entry.agentId,
260
+ };
261
+ const scopeId = scopeIdMap[scope];
262
+ if (!scopeId) {
263
+ throw new Error(`Cannot reset path for entry without ${scope} info.`);
264
+ }
265
+ const prefix = `by-${scope}`;
266
+ // Build path based on entry type
267
+ if (entryType === "compact") {
268
+ return (0, ufo_1.joinURL)("/", prefix, scopeId, "@metadata/compact", entry.id);
269
+ }
270
+ if (entryType === "memory") {
271
+ return (0, ufo_1.joinURL)("/", prefix, scopeId, "@metadata/memory", entry.id);
272
+ }
273
+ // Default: history entry
274
+ return (0, ufo_1.joinURL)("/", prefix, scopeId, entry.id);
58
275
  }
59
276
  }
60
277
  exports.AFSHistory = AFSHistory;
278
+ const _typeCheck = AFSHistory;
279
+ function preprocessSchema(fn, schema) {
280
+ return zod_1.z.preprocess(fn, schema);
281
+ }
@@ -1,7 +1,6 @@
1
1
  import type { AFSEntry, AFSModule } from "@aigne/afs";
2
2
  import { initDatabase } from "@aigne/sqlite";
3
- import { entriesTable } from "./models/entries.js";
4
- import type { AFSStorage, AFSStorageCreatePayload, AFSStorageListOptions } from "./type.js";
3
+ import type { AFSStorage, AFSStorageCreateOptions, AFSStorageCreatePayload, AFSStorageDeleteOptions, AFSStorageListOptions, AFSStorageReadOptions } from "./type.js";
5
4
  export * from "./type.js";
6
5
  export interface SharedAFSStorageOptions {
7
6
  url?: string;
@@ -15,11 +14,16 @@ export declare class SharedAFSStorage {
15
14
  }
16
15
  export declare class AFSStorageWithModule implements AFSStorage {
17
16
  private db;
18
- private table;
19
- constructor(db: ReturnType<typeof initDatabase>, table: Promise<ReturnType<typeof entriesTable>>);
17
+ private module;
18
+ constructor(db: ReturnType<typeof initDatabase>, module: AFSModule);
19
+ private _tables?;
20
+ private get tables();
20
21
  list(options?: AFSStorageListOptions): Promise<{
21
- list: AFSEntry[];
22
+ data: AFSEntry[];
23
+ }>;
24
+ read(id: string, options?: AFSStorageReadOptions): Promise<AFSEntry | undefined>;
25
+ create(entry: AFSStorageCreatePayload, options?: AFSStorageCreateOptions): Promise<AFSEntry>;
26
+ delete(id: string, options?: AFSStorageDeleteOptions): Promise<{
27
+ deletedCount: number;
22
28
  }>;
23
- read(path: string): Promise<AFSEntry | undefined>;
24
- create(entry: AFSStorageCreatePayload): Promise<AFSEntry>;
25
29
  }
@@ -17,7 +17,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.AFSStorageWithModule = exports.SharedAFSStorage = void 0;
18
18
  const sqlite_1 = require("@aigne/sqlite");
19
19
  const migrate_js_1 = require("./migrate.js");
20
+ const compact_js_1 = require("./models/compact.js");
20
21
  const entries_js_1 = require("./models/entries.js");
22
+ const memory_js_1 = require("./models/memory.js");
21
23
  __exportStar(require("./type.js"), exports);
22
24
  const DEFAULT_AFS_STORAGE_LIST_LIMIT = 10;
23
25
  class SharedAFSStorage {
@@ -31,57 +33,101 @@ class SharedAFSStorage {
31
33
  return this._db;
32
34
  }
33
35
  withModule(module) {
34
- return new AFSStorageWithModule(this.db, (0, migrate_js_1.migrate)(this.db, module).then(() => (0, entries_js_1.entriesTable)(module)));
36
+ return new AFSStorageWithModule(this.db, module);
35
37
  }
36
38
  }
37
39
  exports.SharedAFSStorage = SharedAFSStorage;
38
40
  class AFSStorageWithModule {
39
41
  db;
40
- table;
41
- constructor(db, table) {
42
+ module;
43
+ constructor(db, module) {
42
44
  this.db = db;
43
- this.table = table;
45
+ this.module = module;
46
+ }
47
+ _tables;
48
+ get tables() {
49
+ if (!this._tables) {
50
+ this._tables = this.db.then((db) => (0, migrate_js_1.migrate)(db, this.module).then(() => ({
51
+ db,
52
+ entries: (0, entries_js_1.entriesTable)(this.module),
53
+ compact: (0, compact_js_1.compactTable)(this.module),
54
+ memory: (0, memory_js_1.memoryTable)(this.module),
55
+ })));
56
+ }
57
+ return this._tables;
44
58
  }
45
59
  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
60
+ const { type = "history", scope, filter, limit = DEFAULT_AFS_STORAGE_LIST_LIMIT } = options;
61
+ const { db, entries, compact, memory } = await this.tables;
62
+ // Select table based on type
63
+ const table = type === "compact" ? compact : type === "memory" ? memory : entries;
64
+ const data = await db
50
65
  .select()
51
66
  .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]))))
67
+ .where((0, sqlite_1.and)(
68
+ // Add scope filter for compact/memory tables
69
+ scope && type !== "history"
70
+ ? (0, sqlite_1.eq)((0, sqlite_1.sql) `json_extract(${table.metadata}, '$.scope')`, scope)
71
+ : undefined, filter?.agentId ? (0, sqlite_1.eq)(table.agentId, filter.agentId) : undefined, filter?.userId ? (0, sqlite_1.eq)(table.userId, filter.userId) : undefined, filter?.sessionId ? (0, sqlite_1.eq)(table.sessionId, filter.sessionId) : undefined, filter?.before ? (0, sqlite_1.lt)(table.createdAt, new Date(filter.before)) : undefined, filter?.after ? (0, sqlite_1.gt)(table.createdAt, new Date(filter.after)) : undefined))
72
+ .orderBy(...(options.orderBy ?? [["createdAt", "desc"]]).map((item) => (item[1] === "asc" ? sqlite_1.asc : sqlite_1.desc)(sqlite_1.sql.identifier(item[0]))))
54
73
  .limit(limit)
55
74
  .execute();
56
- return { list };
75
+ return { data };
57
76
  }
58
- async read(path) {
59
- const db = await this.db;
60
- const table = await this.table;
77
+ async read(id, options) {
78
+ const { type = "history", scope, filter } = options ?? {};
79
+ const { db, entries, compact, memory } = await this.tables;
80
+ // Select table based on type
81
+ const table = type === "compact" ? compact : type === "memory" ? memory : entries;
61
82
  return db
62
83
  .select()
63
84
  .from(table)
64
- .where((0, sqlite_1.eq)(table.path, path))
85
+ .where((0, sqlite_1.and)((0, sqlite_1.eq)(table.id, id),
86
+ // Add scope filter for compact/memory tables
87
+ scope && type !== "history"
88
+ ? (0, sqlite_1.eq)((0, sqlite_1.sql) `json_extract(${table.metadata}, '$.scope')`, scope)
89
+ : undefined, filter?.agentId ? (0, sqlite_1.eq)(table.agentId, filter.agentId) : undefined, filter?.userId ? (0, sqlite_1.eq)(table.userId, filter.userId) : undefined, filter?.sessionId ? (0, sqlite_1.eq)(table.sessionId, filter.sessionId) : undefined))
65
90
  .limit(1)
66
91
  .execute()
67
- .then((memory) => memory.at(0));
92
+ .then((rows) => rows.at(0));
68
93
  }
69
- async create(entry) {
70
- const db = await this.db;
71
- const table = await this.table;
94
+ async create(entry, options) {
95
+ const { type = "history", scope } = options ?? {};
96
+ const { db, entries, compact, memory } = await this.tables;
97
+ // Select table based on type
98
+ const table = type === "compact" ? compact : type === "memory" ? memory : entries;
99
+ // Prepare entry data - only add scope to metadata for compact/memory types
100
+ const entryData = { ...entry, metadata: { ...entry.metadata, scope } };
101
+ // Try update first, then insert if not found (upsert)
72
102
  let result = await db
73
103
  .update(table)
74
- .set(entry)
75
- .where((0, sqlite_1.eq)(table.path, entry.path))
104
+ .set(entryData)
105
+ .where((0, sqlite_1.eq)(table.id, entry.id))
76
106
  .returning()
77
107
  .execute();
78
108
  if (!result.length) {
79
- result = await db.insert(table).values(entry).returning().execute();
109
+ result = await db.insert(table).values(entryData).returning().execute();
80
110
  }
81
111
  const [res] = result;
82
112
  if (!res)
83
- throw new Error("Failed to create AFS entry, no result");
113
+ throw new Error(`Failed to create ${type} entry, no result`);
84
114
  return res;
85
115
  }
116
+ async delete(id, options) {
117
+ const { type = "history", scope, filter } = options ?? {};
118
+ const { db, entries, compact, memory } = await this.tables;
119
+ // Select table based on type
120
+ const table = type === "compact" ? compact : type === "memory" ? memory : entries;
121
+ const result = await db
122
+ .delete(table)
123
+ .where((0, sqlite_1.and)((0, sqlite_1.eq)(table.id, id),
124
+ // Add scope filter for compact/memory tables
125
+ scope && type !== "history"
126
+ ? (0, sqlite_1.eq)((0, sqlite_1.sql) `json_extract(${table.metadata}, '$.scope')`, scope)
127
+ : undefined, filter?.agentId ? (0, sqlite_1.eq)(table.agentId, filter.agentId) : undefined, filter?.userId ? (0, sqlite_1.eq)(table.userId, filter.userId) : undefined, filter?.sessionId ? (0, sqlite_1.eq)(table.sessionId, filter.sessionId) : undefined))
128
+ .returning()
129
+ .execute();
130
+ return { deletedCount: result.length };
131
+ }
86
132
  }
87
133
  exports.AFSStorageWithModule = AFSStorageWithModule;
@@ -1,3 +1,3 @@
1
1
  import type { AFSModule } from "@aigne/afs";
2
2
  import { type initDatabase } from "@aigne/sqlite";
3
- export declare function migrate(db: ReturnType<typeof initDatabase>, module: AFSModule): Promise<void>;
3
+ export declare function migrate(db: Awaited<ReturnType<typeof initDatabase>>, module: AFSModule): Promise<void>;