@mastra/cloudflare 0.0.0-vector-query-sources-20250516172905 → 0.0.0-vector-query-tool-provider-options-20250828222356
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/LICENSE.md +12 -4
- package/dist/index.cjs +2035 -761
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2018 -744
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +21 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +107 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +83 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +42 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +18 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +53 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +209 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/test-utils.d.ts +25 -0
- package/dist/storage/test-utils.d.ts.map +1 -0
- package/dist/storage/types.d.ts +67 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/package.json +21 -16
- package/dist/_tsup-dts-rollup.d.cts +0 -276
- package/dist/_tsup-dts-rollup.d.ts +0 -276
- package/dist/index.d.cts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,327 +1,575 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
+
import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_SCORERS, TABLE_TRACES, StoreOperations, serializeDate, ensureDate, LegacyEvalsStorage, WorkflowsStorage, TracesStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage, safelyParseJSON } from '@mastra/core/storage';
|
|
2
3
|
import Cloudflare from 'cloudflare';
|
|
4
|
+
import { MessageList } from '@mastra/core/agent';
|
|
3
5
|
|
|
4
6
|
// src/storage/index.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
// src/storage/index.ts
|
|
12
|
-
var CloudflareStore = class extends MastraStorage {
|
|
13
|
-
client;
|
|
14
|
-
accountId;
|
|
15
|
-
namespacePrefix;
|
|
16
|
-
bindings;
|
|
17
|
-
validateWorkersConfig(config) {
|
|
18
|
-
if (!isWorkersConfig(config)) {
|
|
19
|
-
throw new Error("Invalid Workers API configuration");
|
|
20
|
-
}
|
|
21
|
-
if (!config.bindings) {
|
|
22
|
-
throw new Error("KV bindings are required when using Workers Binding API");
|
|
23
|
-
}
|
|
24
|
-
const requiredTables = [TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_TRACES];
|
|
25
|
-
for (const table of requiredTables) {
|
|
26
|
-
if (!(table in config.bindings)) {
|
|
27
|
-
throw new Error(`Missing KV binding for table: ${table}`);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
7
|
+
var LegacyEvalsStorageCloudflare = class extends LegacyEvalsStorage {
|
|
8
|
+
operations;
|
|
9
|
+
constructor({ operations }) {
|
|
10
|
+
super();
|
|
11
|
+
this.operations = operations;
|
|
30
12
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
13
|
+
async getEvalsByAgentName(agentName, type) {
|
|
14
|
+
try {
|
|
15
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
16
|
+
const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
|
|
17
|
+
const evals = [];
|
|
18
|
+
for (const { name: key } of keyObjs) {
|
|
19
|
+
const data = await this.operations.getKV(TABLE_EVALS, key);
|
|
20
|
+
if (!data) continue;
|
|
21
|
+
if (data.agent_name !== agentName) continue;
|
|
22
|
+
if (type) {
|
|
23
|
+
const isTest = data.test_info !== null && data.test_info !== void 0;
|
|
24
|
+
const evalType = isTest ? "test" : "live";
|
|
25
|
+
if (evalType !== type) continue;
|
|
26
|
+
}
|
|
27
|
+
const mappedData = {
|
|
28
|
+
...data,
|
|
29
|
+
runId: data.run_id,
|
|
30
|
+
testInfo: data.test_info
|
|
31
|
+
};
|
|
32
|
+
evals.push(mappedData);
|
|
33
|
+
}
|
|
34
|
+
evals.sort((a, b) => {
|
|
35
|
+
const aTime = new Date(a.createdAt || 0).getTime();
|
|
36
|
+
const bTime = new Date(b.createdAt || 0).getTime();
|
|
37
|
+
return bTime - aTime;
|
|
38
|
+
});
|
|
39
|
+
return evals;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw new MastraError(
|
|
42
|
+
{
|
|
43
|
+
id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
|
|
44
|
+
domain: ErrorDomain.STORAGE,
|
|
45
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
46
|
+
text: "Failed to get evals by agent name"
|
|
47
|
+
},
|
|
48
|
+
error
|
|
49
|
+
);
|
|
40
50
|
}
|
|
41
51
|
}
|
|
42
|
-
|
|
43
|
-
super({ name: "Cloudflare" });
|
|
52
|
+
async getEvals(options) {
|
|
44
53
|
try {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
55
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
56
|
+
const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
|
|
57
|
+
const evals = [];
|
|
58
|
+
for (const { name: key } of keyObjs) {
|
|
59
|
+
const data = await this.operations.getKV(TABLE_EVALS, key);
|
|
60
|
+
if (!data) continue;
|
|
61
|
+
if (agentName && data.agent_name !== agentName) continue;
|
|
62
|
+
if (type) {
|
|
63
|
+
const isTest = data.test_info !== null && data.test_info !== void 0;
|
|
64
|
+
const evalType = isTest ? "test" : "live";
|
|
65
|
+
if (evalType !== type) continue;
|
|
66
|
+
}
|
|
67
|
+
if (dateRange?.start || dateRange?.end) {
|
|
68
|
+
const evalDate = new Date(data.createdAt || data.created_at || 0);
|
|
69
|
+
if (dateRange.start && evalDate < dateRange.start) continue;
|
|
70
|
+
if (dateRange.end && evalDate > dateRange.end) continue;
|
|
71
|
+
}
|
|
72
|
+
const mappedData = {
|
|
73
|
+
...data,
|
|
74
|
+
runId: data.run_id,
|
|
75
|
+
testInfo: data.test_info
|
|
76
|
+
};
|
|
77
|
+
evals.push(mappedData);
|
|
58
78
|
}
|
|
79
|
+
evals.sort((a, b) => {
|
|
80
|
+
const aTime = new Date(a.createdAt || 0).getTime();
|
|
81
|
+
const bTime = new Date(b.createdAt || 0).getTime();
|
|
82
|
+
return bTime - aTime;
|
|
83
|
+
});
|
|
84
|
+
const start = page * perPage;
|
|
85
|
+
const end = start + perPage;
|
|
86
|
+
const paginatedEvals = evals.slice(start, end);
|
|
87
|
+
return {
|
|
88
|
+
page,
|
|
89
|
+
perPage,
|
|
90
|
+
total: evals.length,
|
|
91
|
+
hasMore: start + perPage < evals.length,
|
|
92
|
+
evals: paginatedEvals
|
|
93
|
+
};
|
|
59
94
|
} catch (error) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
95
|
+
throw new MastraError(
|
|
96
|
+
{
|
|
97
|
+
id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
|
|
98
|
+
domain: ErrorDomain.STORAGE,
|
|
99
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
100
|
+
text: "Failed to get evals"
|
|
101
|
+
},
|
|
102
|
+
error
|
|
103
|
+
);
|
|
63
104
|
}
|
|
64
105
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
return binding;
|
|
106
|
+
};
|
|
107
|
+
var MemoryStorageCloudflare = class extends MemoryStorage {
|
|
108
|
+
operations;
|
|
109
|
+
constructor({ operations }) {
|
|
110
|
+
super();
|
|
111
|
+
this.operations = operations;
|
|
72
112
|
}
|
|
73
|
-
|
|
74
|
-
if (
|
|
113
|
+
ensureMetadata(metadata) {
|
|
114
|
+
if (!metadata) return void 0;
|
|
115
|
+
return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
|
|
116
|
+
}
|
|
117
|
+
async getThreadById({ threadId }) {
|
|
118
|
+
const thread = await this.operations.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
|
|
119
|
+
if (!thread) return null;
|
|
120
|
+
try {
|
|
75
121
|
return {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}))
|
|
122
|
+
...thread,
|
|
123
|
+
createdAt: ensureDate(thread.createdAt),
|
|
124
|
+
updatedAt: ensureDate(thread.updatedAt),
|
|
125
|
+
metadata: this.ensureMetadata(thread.metadata)
|
|
81
126
|
};
|
|
127
|
+
} catch (error) {
|
|
128
|
+
const mastraError = new MastraError(
|
|
129
|
+
{
|
|
130
|
+
id: "CLOUDFLARE_STORAGE_GET_THREAD_BY_ID_FAILED",
|
|
131
|
+
domain: ErrorDomain.STORAGE,
|
|
132
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
133
|
+
details: {
|
|
134
|
+
threadId
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
error
|
|
138
|
+
);
|
|
139
|
+
this.logger?.trackException(mastraError);
|
|
140
|
+
this.logger?.error(mastraError.toString());
|
|
141
|
+
return null;
|
|
82
142
|
}
|
|
83
|
-
return await this.client.kv.namespaces.list({ account_id: this.accountId });
|
|
84
143
|
}
|
|
85
|
-
async
|
|
144
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
86
145
|
try {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
146
|
+
const keyList = await this.operations.listKV(TABLE_THREADS);
|
|
147
|
+
const threads = await Promise.all(
|
|
148
|
+
keyList.map(async (keyObj) => {
|
|
149
|
+
try {
|
|
150
|
+
const data = await this.operations.getKV(TABLE_THREADS, keyObj.name);
|
|
151
|
+
if (!data) return null;
|
|
152
|
+
const thread = typeof data === "string" ? JSON.parse(data) : data;
|
|
153
|
+
if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
|
|
154
|
+
return {
|
|
155
|
+
...thread,
|
|
156
|
+
createdAt: ensureDate(thread.createdAt),
|
|
157
|
+
updatedAt: ensureDate(thread.updatedAt),
|
|
158
|
+
metadata: this.ensureMetadata(thread.metadata)
|
|
159
|
+
};
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const mastraError = new MastraError(
|
|
162
|
+
{
|
|
163
|
+
id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
|
|
164
|
+
domain: ErrorDomain.STORAGE,
|
|
165
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
166
|
+
details: {
|
|
167
|
+
resourceId
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
error
|
|
171
|
+
);
|
|
172
|
+
this.logger?.trackException(mastraError);
|
|
173
|
+
this.logger?.error(mastraError.toString());
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
);
|
|
178
|
+
return threads.filter((thread) => thread !== null);
|
|
99
179
|
} catch (error) {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
180
|
+
const mastraError = new MastraError(
|
|
181
|
+
{
|
|
182
|
+
id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
|
|
183
|
+
domain: ErrorDomain.STORAGE,
|
|
184
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
185
|
+
details: {
|
|
186
|
+
resourceId
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
error
|
|
190
|
+
);
|
|
191
|
+
this.logger?.trackException(mastraError);
|
|
192
|
+
this.logger?.error(mastraError.toString());
|
|
193
|
+
return [];
|
|
106
194
|
}
|
|
107
195
|
}
|
|
108
|
-
async
|
|
109
|
-
tableName,
|
|
110
|
-
key,
|
|
111
|
-
value,
|
|
112
|
-
metadata
|
|
113
|
-
}) {
|
|
196
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
114
197
|
try {
|
|
115
|
-
const
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
value: serializedValue,
|
|
125
|
-
metadata: serializedMetadata
|
|
126
|
-
});
|
|
198
|
+
const { resourceId, page = 0, perPage = 100 } = args;
|
|
199
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
200
|
+
const keyObjs = await this.operations.listKV(TABLE_THREADS, { prefix: `${prefix}${TABLE_THREADS}` });
|
|
201
|
+
const threads = [];
|
|
202
|
+
for (const { name: key } of keyObjs) {
|
|
203
|
+
const data = await this.operations.getKV(TABLE_THREADS, key);
|
|
204
|
+
if (!data) continue;
|
|
205
|
+
if (data.resourceId !== resourceId) continue;
|
|
206
|
+
threads.push(data);
|
|
127
207
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
async deleteNamespaceValue(tableName, key) {
|
|
135
|
-
if (this.bindings) {
|
|
136
|
-
const binding = this.getBinding(tableName);
|
|
137
|
-
await binding.delete(key);
|
|
138
|
-
} else {
|
|
139
|
-
const namespaceId = await this.getNamespaceId(tableName);
|
|
140
|
-
await this.client.kv.namespaces.values.delete(namespaceId, key, {
|
|
141
|
-
account_id: this.accountId
|
|
208
|
+
threads.sort((a, b) => {
|
|
209
|
+
const aTime = new Date(a.createdAt || 0).getTime();
|
|
210
|
+
const bTime = new Date(b.createdAt || 0).getTime();
|
|
211
|
+
return bTime - aTime;
|
|
142
212
|
});
|
|
213
|
+
const start = page * perPage;
|
|
214
|
+
const end = start + perPage;
|
|
215
|
+
const paginatedThreads = threads.slice(start, end);
|
|
216
|
+
return {
|
|
217
|
+
page,
|
|
218
|
+
perPage,
|
|
219
|
+
total: threads.length,
|
|
220
|
+
hasMore: start + perPage < threads.length,
|
|
221
|
+
threads: paginatedThreads
|
|
222
|
+
};
|
|
223
|
+
} catch (error) {
|
|
224
|
+
throw new MastraError(
|
|
225
|
+
{
|
|
226
|
+
id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
227
|
+
domain: ErrorDomain.STORAGE,
|
|
228
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
229
|
+
text: "Failed to get threads by resource ID with pagination"
|
|
230
|
+
},
|
|
231
|
+
error
|
|
232
|
+
);
|
|
143
233
|
}
|
|
144
234
|
}
|
|
145
|
-
async
|
|
235
|
+
async saveThread({ thread }) {
|
|
146
236
|
try {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const response = await binding.list({
|
|
150
|
-
limit: options?.limit || 1e3,
|
|
151
|
-
prefix: options?.prefix
|
|
152
|
-
});
|
|
153
|
-
return response.keys;
|
|
154
|
-
} else {
|
|
155
|
-
const namespaceId = await this.getNamespaceId(tableName);
|
|
156
|
-
const response = await this.client.kv.namespaces.keys.list(namespaceId, {
|
|
157
|
-
account_id: this.accountId,
|
|
158
|
-
limit: options?.limit || 1e3,
|
|
159
|
-
prefix: options?.prefix
|
|
160
|
-
});
|
|
161
|
-
return response.result;
|
|
162
|
-
}
|
|
237
|
+
await this.operations.insert({ tableName: TABLE_THREADS, record: thread });
|
|
238
|
+
return thread;
|
|
163
239
|
} catch (error) {
|
|
164
|
-
|
|
165
|
-
|
|
240
|
+
throw new MastraError(
|
|
241
|
+
{
|
|
242
|
+
id: "CLOUDFLARE_STORAGE_SAVE_THREAD_FAILED",
|
|
243
|
+
domain: ErrorDomain.STORAGE,
|
|
244
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
245
|
+
details: {
|
|
246
|
+
threadId: thread.id
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
error
|
|
250
|
+
);
|
|
166
251
|
}
|
|
167
252
|
}
|
|
168
|
-
async
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
253
|
+
async updateThread({
|
|
254
|
+
id,
|
|
255
|
+
title,
|
|
256
|
+
metadata
|
|
257
|
+
}) {
|
|
258
|
+
try {
|
|
259
|
+
const thread = await this.getThreadById({ threadId: id });
|
|
260
|
+
if (!thread) {
|
|
261
|
+
throw new Error(`Thread ${id} not found`);
|
|
262
|
+
}
|
|
263
|
+
const updatedThread = {
|
|
264
|
+
...thread,
|
|
173
265
|
title,
|
|
174
|
-
|
|
266
|
+
metadata: this.ensureMetadata({
|
|
267
|
+
...thread.metadata ?? {},
|
|
268
|
+
...metadata
|
|
269
|
+
}),
|
|
270
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
175
271
|
};
|
|
272
|
+
await this.operations.insert({ tableName: TABLE_THREADS, record: updatedThread });
|
|
273
|
+
return updatedThread;
|
|
274
|
+
} catch (error) {
|
|
275
|
+
throw new MastraError(
|
|
276
|
+
{
|
|
277
|
+
id: "CLOUDFLARE_STORAGE_UPDATE_THREAD_FAILED",
|
|
278
|
+
domain: ErrorDomain.STORAGE,
|
|
279
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
280
|
+
details: {
|
|
281
|
+
threadId: id,
|
|
282
|
+
title
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
error
|
|
286
|
+
);
|
|
176
287
|
}
|
|
177
|
-
return await this.client.kv.namespaces.create({
|
|
178
|
-
account_id: this.accountId,
|
|
179
|
-
title
|
|
180
|
-
});
|
|
181
288
|
}
|
|
182
|
-
|
|
289
|
+
getMessageKey(threadId, messageId) {
|
|
183
290
|
try {
|
|
184
|
-
|
|
185
|
-
const namespace = response.result.find((ns) => ns.title === namespaceName);
|
|
186
|
-
return namespace ? namespace.id : null;
|
|
291
|
+
return this.operations.getKey(TABLE_MESSAGES, { threadId, id: messageId });
|
|
187
292
|
} catch (error) {
|
|
188
|
-
|
|
189
|
-
|
|
293
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
294
|
+
this.logger.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
|
|
295
|
+
throw error;
|
|
190
296
|
}
|
|
191
297
|
}
|
|
192
|
-
|
|
298
|
+
getThreadMessagesKey(threadId) {
|
|
193
299
|
try {
|
|
194
|
-
|
|
195
|
-
return response.id;
|
|
300
|
+
return this.operations.getKey(TABLE_MESSAGES, { threadId, id: "messages" });
|
|
196
301
|
} catch (error) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (namespace) return namespace.id;
|
|
201
|
-
}
|
|
202
|
-
this.logger.error("Error creating namespace:", error);
|
|
203
|
-
throw new Error(`Failed to create namespace ${namespaceName}: ${error.message}`);
|
|
302
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
303
|
+
this.logger.error(`Error getting thread messages key for thread ${threadId}:`, { message });
|
|
304
|
+
throw error;
|
|
204
305
|
}
|
|
205
306
|
}
|
|
206
|
-
async
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
307
|
+
async deleteThread({ threadId }) {
|
|
308
|
+
try {
|
|
309
|
+
const thread = await this.getThreadById({ threadId });
|
|
310
|
+
if (!thread) {
|
|
311
|
+
throw new Error(`Thread ${threadId} not found`);
|
|
312
|
+
}
|
|
313
|
+
const messageKeys = await this.operations.listKV(TABLE_MESSAGES);
|
|
314
|
+
const threadMessageKeys = messageKeys.filter((key) => key.name.includes(`${TABLE_MESSAGES}:${threadId}:`));
|
|
315
|
+
await Promise.all([
|
|
316
|
+
// Delete message order
|
|
317
|
+
this.operations.deleteKV(TABLE_MESSAGES, this.getThreadMessagesKey(threadId)),
|
|
318
|
+
// Delete all messages
|
|
319
|
+
...threadMessageKeys.map((key) => this.operations.deleteKV(TABLE_MESSAGES, key.name)),
|
|
320
|
+
// Delete thread
|
|
321
|
+
this.operations.deleteKV(TABLE_THREADS, this.operations.getKey(TABLE_THREADS, { id: threadId }))
|
|
322
|
+
]);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
throw new MastraError(
|
|
325
|
+
{
|
|
326
|
+
id: "CLOUDFLARE_STORAGE_DELETE_THREAD_FAILED",
|
|
327
|
+
domain: ErrorDomain.STORAGE,
|
|
328
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
329
|
+
details: {
|
|
330
|
+
threadId
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
error
|
|
334
|
+
);
|
|
210
335
|
}
|
|
211
|
-
return namespaceId;
|
|
212
336
|
}
|
|
213
|
-
async
|
|
214
|
-
const prefix = this.namespacePrefix ? `${this.namespacePrefix}_` : "";
|
|
337
|
+
async findMessageInAnyThread(messageId) {
|
|
215
338
|
try {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
339
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
340
|
+
const threadKeys = await this.operations.listKV(TABLE_THREADS, { prefix: `${prefix}${TABLE_THREADS}` });
|
|
341
|
+
for (const { name: threadKey } of threadKeys) {
|
|
342
|
+
const threadId = threadKey.split(":").pop();
|
|
343
|
+
if (!threadId || threadId === "messages") continue;
|
|
344
|
+
const messageKey = this.getMessageKey(threadId, messageId);
|
|
345
|
+
const message = await this.operations.getKV(TABLE_MESSAGES, messageKey);
|
|
346
|
+
if (message) {
|
|
347
|
+
return { ...message, threadId };
|
|
348
|
+
}
|
|
222
349
|
}
|
|
350
|
+
return null;
|
|
223
351
|
} catch (error) {
|
|
224
|
-
this.logger
|
|
225
|
-
|
|
352
|
+
this.logger?.error(`Error finding message ${messageId} in any thread:`, error);
|
|
353
|
+
return null;
|
|
226
354
|
}
|
|
227
355
|
}
|
|
228
356
|
/**
|
|
229
|
-
*
|
|
357
|
+
* Queue for serializing sorted order updates.
|
|
358
|
+
* Updates the sorted order for a given key. This operation is eventually consistent.
|
|
230
359
|
*/
|
|
231
|
-
|
|
232
|
-
|
|
360
|
+
updateQueue = /* @__PURE__ */ new Map();
|
|
361
|
+
async updateSorting(threadMessages) {
|
|
362
|
+
return threadMessages.map((msg) => ({
|
|
363
|
+
message: msg,
|
|
364
|
+
// Use _index if available, otherwise timestamp, matching Upstash
|
|
365
|
+
score: msg._index !== void 0 ? msg._index : msg.createdAt.getTime()
|
|
366
|
+
})).sort((a, b) => a.score - b.score).map((item) => ({
|
|
367
|
+
id: item.message.id,
|
|
368
|
+
score: item.score
|
|
369
|
+
}));
|
|
233
370
|
}
|
|
234
371
|
/**
|
|
235
|
-
*
|
|
372
|
+
* Updates the sorted order for a given key. This operation is eventually consistent.
|
|
373
|
+
* Note: Operations on the same orderKey are serialized using a queue to prevent
|
|
374
|
+
* concurrent updates from conflicting with each other.
|
|
236
375
|
*/
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
} catch {
|
|
246
|
-
return data.value;
|
|
247
|
-
}
|
|
376
|
+
async updateSortedMessages(orderKey, newEntries) {
|
|
377
|
+
const currentPromise = this.updateQueue.get(orderKey) || Promise.resolve();
|
|
378
|
+
const nextPromise = currentPromise.then(async () => {
|
|
379
|
+
try {
|
|
380
|
+
const currentOrder = await this.getSortedMessages(orderKey);
|
|
381
|
+
const orderMap = new Map(currentOrder.map((entry) => [entry.id, entry]));
|
|
382
|
+
for (const entry of newEntries) {
|
|
383
|
+
orderMap.set(entry.id, entry);
|
|
248
384
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
this.logger.error(`Failed to put KV value for ${tableName}:${key}:`, error);
|
|
268
|
-
throw new Error(`Failed to put KV value: ${error.message}`);
|
|
269
|
-
}
|
|
385
|
+
const updatedOrder = Array.from(orderMap.values()).sort((a, b) => a.score - b.score);
|
|
386
|
+
await this.operations.putKV({
|
|
387
|
+
tableName: TABLE_MESSAGES,
|
|
388
|
+
key: orderKey,
|
|
389
|
+
value: JSON.stringify(updatedOrder)
|
|
390
|
+
});
|
|
391
|
+
} catch (error) {
|
|
392
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
393
|
+
this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
|
|
394
|
+
throw error;
|
|
395
|
+
} finally {
|
|
396
|
+
if (this.updateQueue.get(orderKey) === nextPromise) {
|
|
397
|
+
this.updateQueue.delete(orderKey);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
this.updateQueue.set(orderKey, nextPromise);
|
|
402
|
+
return nextPromise;
|
|
270
403
|
}
|
|
271
|
-
async
|
|
404
|
+
async getSortedMessages(orderKey) {
|
|
405
|
+
const raw = await this.operations.getKV(TABLE_MESSAGES, orderKey);
|
|
406
|
+
if (!raw) return [];
|
|
272
407
|
try {
|
|
273
|
-
const
|
|
274
|
-
return
|
|
275
|
-
} catch (
|
|
276
|
-
this.logger.error(`
|
|
277
|
-
|
|
408
|
+
const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
|
|
409
|
+
return Array.isArray(arr) ? arr : [];
|
|
410
|
+
} catch (e) {
|
|
411
|
+
this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
|
|
412
|
+
return [];
|
|
278
413
|
}
|
|
279
414
|
}
|
|
280
|
-
async
|
|
415
|
+
async migrateMessage(messageId, fromThreadId, toThreadId) {
|
|
281
416
|
try {
|
|
282
|
-
|
|
417
|
+
const oldMessageKey = this.getMessageKey(fromThreadId, messageId);
|
|
418
|
+
const message = await this.operations.getKV(TABLE_MESSAGES, oldMessageKey);
|
|
419
|
+
if (!message) return;
|
|
420
|
+
const updatedMessage = {
|
|
421
|
+
...message,
|
|
422
|
+
threadId: toThreadId
|
|
423
|
+
};
|
|
424
|
+
const newMessageKey = this.getMessageKey(toThreadId, messageId);
|
|
425
|
+
await this.operations.putKV({ tableName: TABLE_MESSAGES, key: newMessageKey, value: updatedMessage });
|
|
426
|
+
const oldOrderKey = this.getThreadMessagesKey(fromThreadId);
|
|
427
|
+
const oldEntries = await this.getSortedMessages(oldOrderKey);
|
|
428
|
+
const filteredEntries = oldEntries.filter((entry) => entry.id !== messageId);
|
|
429
|
+
await this.updateSortedMessages(oldOrderKey, filteredEntries);
|
|
430
|
+
const newOrderKey = this.getThreadMessagesKey(toThreadId);
|
|
431
|
+
const newEntries = await this.getSortedMessages(newOrderKey);
|
|
432
|
+
const newEntry = { id: messageId, score: Date.now() };
|
|
433
|
+
newEntries.push(newEntry);
|
|
434
|
+
await this.updateSortedMessages(newOrderKey, newEntries);
|
|
435
|
+
await this.operations.deleteKV(TABLE_MESSAGES, oldMessageKey);
|
|
283
436
|
} catch (error) {
|
|
284
|
-
this.logger
|
|
285
|
-
throw
|
|
437
|
+
this.logger?.error(`Error migrating message ${messageId} from ${fromThreadId} to ${toThreadId}:`, error);
|
|
438
|
+
throw error;
|
|
286
439
|
}
|
|
287
440
|
}
|
|
288
|
-
async
|
|
441
|
+
async saveMessages(args) {
|
|
442
|
+
const { messages, format = "v1" } = args;
|
|
443
|
+
if (!Array.isArray(messages) || messages.length === 0) return [];
|
|
289
444
|
try {
|
|
290
|
-
|
|
445
|
+
const validatedMessages = messages.map((message, index) => {
|
|
446
|
+
const errors = [];
|
|
447
|
+
if (!message.id) errors.push("id is required");
|
|
448
|
+
if (!message.threadId) errors.push("threadId is required");
|
|
449
|
+
if (!message.content) errors.push("content is required");
|
|
450
|
+
if (!message.role) errors.push("role is required");
|
|
451
|
+
if (!message.createdAt) errors.push("createdAt is required");
|
|
452
|
+
if (message.resourceId === null || message.resourceId === void 0) errors.push("resourceId is required");
|
|
453
|
+
if (errors.length > 0) {
|
|
454
|
+
throw new Error(`Invalid message at index ${index}: ${errors.join(", ")}`);
|
|
455
|
+
}
|
|
456
|
+
return {
|
|
457
|
+
...message,
|
|
458
|
+
createdAt: ensureDate(message.createdAt),
|
|
459
|
+
type: message.type || "v2",
|
|
460
|
+
_index: index
|
|
461
|
+
};
|
|
462
|
+
}).filter((m) => !!m);
|
|
463
|
+
const messageMigrationTasks = [];
|
|
464
|
+
for (const message of validatedMessages) {
|
|
465
|
+
const existingMessage = await this.findMessageInAnyThread(message.id);
|
|
466
|
+
console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
|
|
467
|
+
if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
|
|
468
|
+
console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
|
|
469
|
+
messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
await Promise.all(messageMigrationTasks);
|
|
473
|
+
const messagesByThread = validatedMessages.reduce((acc, message) => {
|
|
474
|
+
if (message.threadId && !acc.has(message.threadId)) {
|
|
475
|
+
acc.set(message.threadId, []);
|
|
476
|
+
}
|
|
477
|
+
if (message.threadId) {
|
|
478
|
+
acc.get(message.threadId).push(message);
|
|
479
|
+
}
|
|
480
|
+
return acc;
|
|
481
|
+
}, /* @__PURE__ */ new Map());
|
|
482
|
+
await Promise.all(
|
|
483
|
+
Array.from(messagesByThread.entries()).map(async ([threadId, threadMessages]) => {
|
|
484
|
+
try {
|
|
485
|
+
const thread = await this.getThreadById({ threadId });
|
|
486
|
+
if (!thread) {
|
|
487
|
+
throw new Error(`Thread ${threadId} not found`);
|
|
488
|
+
}
|
|
489
|
+
await Promise.all(
|
|
490
|
+
threadMessages.map(async (message) => {
|
|
491
|
+
const key = this.getMessageKey(threadId, message.id);
|
|
492
|
+
const { _index, ...cleanMessage } = message;
|
|
493
|
+
const serializedMessage = {
|
|
494
|
+
...cleanMessage,
|
|
495
|
+
createdAt: serializeDate(cleanMessage.createdAt)
|
|
496
|
+
};
|
|
497
|
+
console.log(`Saving message ${message.id} with content:`, {
|
|
498
|
+
content: serializedMessage.content,
|
|
499
|
+
contentType: typeof serializedMessage.content,
|
|
500
|
+
isArray: Array.isArray(serializedMessage.content)
|
|
501
|
+
});
|
|
502
|
+
await this.operations.putKV({ tableName: TABLE_MESSAGES, key, value: serializedMessage });
|
|
503
|
+
})
|
|
504
|
+
);
|
|
505
|
+
const orderKey = this.getThreadMessagesKey(threadId);
|
|
506
|
+
const entries = await this.updateSorting(threadMessages);
|
|
507
|
+
await this.updateSortedMessages(orderKey, entries);
|
|
508
|
+
const updatedThread = {
|
|
509
|
+
...thread,
|
|
510
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
511
|
+
};
|
|
512
|
+
await this.operations.putKV({
|
|
513
|
+
tableName: TABLE_THREADS,
|
|
514
|
+
key: this.operations.getKey(TABLE_THREADS, { id: threadId }),
|
|
515
|
+
value: updatedThread
|
|
516
|
+
});
|
|
517
|
+
} catch (error) {
|
|
518
|
+
throw new MastraError(
|
|
519
|
+
{
|
|
520
|
+
id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
|
|
521
|
+
domain: ErrorDomain.STORAGE,
|
|
522
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
523
|
+
details: {
|
|
524
|
+
threadId
|
|
525
|
+
}
|
|
526
|
+
},
|
|
527
|
+
error
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
})
|
|
531
|
+
);
|
|
532
|
+
const prepared = validatedMessages.map(
|
|
533
|
+
({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
|
|
534
|
+
);
|
|
535
|
+
const list = new MessageList().add(prepared, "memory");
|
|
536
|
+
if (format === `v2`) return list.get.all.v2();
|
|
537
|
+
return list.get.all.v1();
|
|
291
538
|
} catch (error) {
|
|
292
|
-
|
|
293
|
-
|
|
539
|
+
throw new MastraError(
|
|
540
|
+
{
|
|
541
|
+
id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
|
|
542
|
+
domain: ErrorDomain.STORAGE,
|
|
543
|
+
category: ErrorCategory.THIRD_PARTY
|
|
544
|
+
},
|
|
545
|
+
error
|
|
546
|
+
);
|
|
294
547
|
}
|
|
295
548
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
async getSortedMessages(orderKey) {
|
|
301
|
-
const raw = await this.getKV(TABLE_MESSAGES, orderKey);
|
|
302
|
-
if (!raw) return [];
|
|
303
|
-
try {
|
|
304
|
-
const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
|
|
305
|
-
return Array.isArray(arr) ? arr : [];
|
|
306
|
-
} catch (e) {
|
|
307
|
-
this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
|
|
308
|
-
return [];
|
|
309
|
-
}
|
|
549
|
+
async getRank(orderKey, id) {
|
|
550
|
+
const order = await this.getSortedMessages(orderKey);
|
|
551
|
+
const index = order.findIndex((item) => item.id === id);
|
|
552
|
+
return index >= 0 ? index : null;
|
|
310
553
|
}
|
|
311
|
-
async
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
554
|
+
async getRange(orderKey, start, end) {
|
|
555
|
+
const order = await this.getSortedMessages(orderKey);
|
|
556
|
+
const actualStart = start < 0 ? Math.max(0, order.length + start) : start;
|
|
557
|
+
const actualEnd = end < 0 ? order.length + end : Math.min(end, order.length - 1);
|
|
558
|
+
const sliced = order.slice(actualStart, actualEnd + 1);
|
|
559
|
+
return sliced.map((item) => item.id);
|
|
560
|
+
}
|
|
561
|
+
async getLastN(orderKey, n) {
|
|
562
|
+
return this.getRange(orderKey, -n, -1);
|
|
563
|
+
}
|
|
564
|
+
async getFullOrder(orderKey) {
|
|
565
|
+
return this.getRange(orderKey, 0, -1);
|
|
320
566
|
}
|
|
321
567
|
async getIncludedMessagesWithContext(threadId, include, messageIds) {
|
|
322
|
-
const threadMessagesKey = this.getThreadMessagesKey(threadId);
|
|
323
568
|
await Promise.all(
|
|
324
569
|
include.map(async (item) => {
|
|
570
|
+
const targetThreadId = item.threadId || threadId;
|
|
571
|
+
if (!targetThreadId) return;
|
|
572
|
+
const threadMessagesKey = this.getThreadMessagesKey(targetThreadId);
|
|
325
573
|
messageIds.add(item.id);
|
|
326
574
|
if (!item.withPreviousMessages && !item.withNextMessages) return;
|
|
327
575
|
const rank = await this.getRank(threadMessagesKey, item.id);
|
|
@@ -351,14 +599,40 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
351
599
|
console.log(`No message order found for thread ${threadId}, skipping latest messages`);
|
|
352
600
|
}
|
|
353
601
|
}
|
|
354
|
-
async
|
|
602
|
+
async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
|
|
603
|
+
const messageIdToThreadId = /* @__PURE__ */ new Map();
|
|
604
|
+
if (include) {
|
|
605
|
+
for (const item of include) {
|
|
606
|
+
if (item.threadId) {
|
|
607
|
+
messageIdToThreadId.set(item.id, item.threadId);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
355
611
|
const messages = await Promise.all(
|
|
356
612
|
messageIds.map(async (id) => {
|
|
357
613
|
try {
|
|
614
|
+
let threadId = messageIdToThreadId.get(id);
|
|
615
|
+
if (!threadId) {
|
|
616
|
+
if (targetThreadId) {
|
|
617
|
+
threadId = targetThreadId;
|
|
618
|
+
} else {
|
|
619
|
+
const foundMessage = await this.findMessageInAnyThread(id);
|
|
620
|
+
if (foundMessage) {
|
|
621
|
+
threadId = foundMessage.threadId;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (!threadId) return null;
|
|
358
626
|
const key = this.getMessageKey(threadId, id);
|
|
359
|
-
const data = await this.getKV(TABLE_MESSAGES, key);
|
|
627
|
+
const data = await this.operations.getKV(TABLE_MESSAGES, key);
|
|
360
628
|
if (!data) return null;
|
|
361
|
-
|
|
629
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data;
|
|
630
|
+
console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
|
|
631
|
+
content: parsed.content,
|
|
632
|
+
contentType: typeof parsed.content,
|
|
633
|
+
isArray: Array.isArray(parsed.content)
|
|
634
|
+
});
|
|
635
|
+
return parsed;
|
|
362
636
|
} catch (error) {
|
|
363
637
|
const message = error instanceof Error ? error.message : String(error);
|
|
364
638
|
this.logger.error(`Error retrieving message ${id}:`, { message });
|
|
@@ -368,61 +642,424 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
368
642
|
);
|
|
369
643
|
return messages.filter((msg) => msg !== null);
|
|
370
644
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
const
|
|
383
|
-
const
|
|
645
|
+
async getMessages({
|
|
646
|
+
threadId,
|
|
647
|
+
resourceId,
|
|
648
|
+
selectBy,
|
|
649
|
+
format
|
|
650
|
+
}) {
|
|
651
|
+
console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
|
|
652
|
+
if (!threadId) throw new Error("threadId is required");
|
|
653
|
+
const actualFormat = format || "v1";
|
|
654
|
+
console.log(`Using format: ${actualFormat}`);
|
|
655
|
+
if (!threadId) throw new Error("threadId is required");
|
|
656
|
+
const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
657
|
+
const messageIds = /* @__PURE__ */ new Set();
|
|
658
|
+
if (limit === 0 && !selectBy?.include?.length) return [];
|
|
659
|
+
try {
|
|
660
|
+
await Promise.all([
|
|
661
|
+
selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
|
|
662
|
+
limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
|
|
663
|
+
]);
|
|
664
|
+
const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
|
|
665
|
+
const messages = await this.fetchAndParseMessagesFromMultipleThreads(
|
|
666
|
+
Array.from(messageIds),
|
|
667
|
+
selectBy?.include,
|
|
668
|
+
targetThreadId
|
|
669
|
+
);
|
|
670
|
+
if (!messages.length) return [];
|
|
384
671
|
try {
|
|
385
|
-
const
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
key: orderKey,
|
|
394
|
-
value: JSON.stringify(updatedOrder)
|
|
672
|
+
const threadMessagesKey = this.getThreadMessagesKey(threadId);
|
|
673
|
+
const messageOrder = await this.getFullOrder(threadMessagesKey);
|
|
674
|
+
const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
|
|
675
|
+
messages.sort((a, b) => {
|
|
676
|
+
const indexA = orderMap.get(a.id);
|
|
677
|
+
const indexB = orderMap.get(b.id);
|
|
678
|
+
if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
|
|
679
|
+
return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
|
395
680
|
});
|
|
396
681
|
} catch (error) {
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
682
|
+
const mastraError = new MastraError(
|
|
683
|
+
{
|
|
684
|
+
id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
|
|
685
|
+
domain: ErrorDomain.STORAGE,
|
|
686
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
687
|
+
text: `Error sorting messages for thread ${threadId} falling back to creation time`,
|
|
688
|
+
details: {
|
|
689
|
+
threadId
|
|
690
|
+
}
|
|
691
|
+
},
|
|
692
|
+
error
|
|
693
|
+
);
|
|
694
|
+
this.logger?.trackException(mastraError);
|
|
695
|
+
this.logger?.error(mastraError.toString());
|
|
696
|
+
messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
697
|
+
}
|
|
698
|
+
const prepared = messages.map(({ _index, ...message }) => ({
|
|
699
|
+
...message,
|
|
700
|
+
type: message.type === `v2` ? void 0 : message.type,
|
|
701
|
+
createdAt: ensureDate(message.createdAt)
|
|
702
|
+
}));
|
|
703
|
+
if (actualFormat === `v1`) {
|
|
704
|
+
console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
|
|
705
|
+
return prepared.map((msg) => ({
|
|
706
|
+
...msg,
|
|
707
|
+
createdAt: new Date(msg.createdAt)
|
|
708
|
+
}));
|
|
709
|
+
}
|
|
710
|
+
const list = new MessageList({ threadId, resourceId }).add(prepared, "memory");
|
|
711
|
+
return list.get.all.v2();
|
|
712
|
+
} catch (error) {
|
|
713
|
+
const mastraError = new MastraError(
|
|
714
|
+
{
|
|
715
|
+
id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
|
|
716
|
+
domain: ErrorDomain.STORAGE,
|
|
717
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
718
|
+
text: `Error retrieving messages for thread ${threadId}`,
|
|
719
|
+
details: {
|
|
720
|
+
threadId
|
|
721
|
+
}
|
|
722
|
+
},
|
|
723
|
+
error
|
|
724
|
+
);
|
|
725
|
+
this.logger?.trackException(mastraError);
|
|
726
|
+
this.logger?.error(mastraError.toString());
|
|
727
|
+
return [];
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
async getMessagesById({
|
|
731
|
+
messageIds,
|
|
732
|
+
format
|
|
733
|
+
}) {
|
|
734
|
+
if (messageIds.length === 0) return [];
|
|
735
|
+
try {
|
|
736
|
+
const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
|
|
737
|
+
(result) => !!result
|
|
738
|
+
);
|
|
739
|
+
const prepared = messages.map(({ _index, ...message }) => ({
|
|
740
|
+
...message,
|
|
741
|
+
...message.type !== `v2` && { type: message.type },
|
|
742
|
+
createdAt: ensureDate(message.createdAt)
|
|
743
|
+
}));
|
|
744
|
+
const list = new MessageList().add(prepared, "memory");
|
|
745
|
+
if (format === `v1`) return list.get.all.v1();
|
|
746
|
+
return list.get.all.v2();
|
|
747
|
+
} catch (error) {
|
|
748
|
+
const mastraError = new MastraError(
|
|
749
|
+
{
|
|
750
|
+
id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
|
|
751
|
+
domain: ErrorDomain.STORAGE,
|
|
752
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
753
|
+
text: `Error retrieving messages by ID`,
|
|
754
|
+
details: {
|
|
755
|
+
messageIds: JSON.stringify(messageIds)
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
error
|
|
759
|
+
);
|
|
760
|
+
this.logger?.trackException(mastraError);
|
|
761
|
+
this.logger?.error(mastraError.toString());
|
|
762
|
+
return [];
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
async getMessagesPaginated(args) {
|
|
766
|
+
try {
|
|
767
|
+
const { threadId, selectBy, format = "v1" } = args;
|
|
768
|
+
const { page = 0, perPage = 100 } = selectBy?.pagination || {};
|
|
769
|
+
const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
|
|
770
|
+
let filteredMessages = messages;
|
|
771
|
+
if (selectBy?.pagination?.dateRange) {
|
|
772
|
+
const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
|
|
773
|
+
filteredMessages = messages.filter((message) => {
|
|
774
|
+
const messageDate = new Date(message.createdAt);
|
|
775
|
+
if (dateStart && messageDate < dateStart) return false;
|
|
776
|
+
if (dateEnd && messageDate > dateEnd) return false;
|
|
777
|
+
return true;
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
const start = page * perPage;
|
|
781
|
+
const end = start + perPage;
|
|
782
|
+
const paginatedMessages = filteredMessages.slice(start, end);
|
|
783
|
+
return {
|
|
784
|
+
page,
|
|
785
|
+
perPage,
|
|
786
|
+
total: filteredMessages.length,
|
|
787
|
+
hasMore: start + perPage < filteredMessages.length,
|
|
788
|
+
messages: paginatedMessages
|
|
789
|
+
};
|
|
790
|
+
} catch (error) {
|
|
791
|
+
throw new MastraError(
|
|
792
|
+
{
|
|
793
|
+
id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
|
|
794
|
+
domain: ErrorDomain.STORAGE,
|
|
795
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
796
|
+
text: "Failed to get messages with pagination"
|
|
797
|
+
},
|
|
798
|
+
error
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
async updateMessages(args) {
|
|
803
|
+
try {
|
|
804
|
+
const { messages } = args;
|
|
805
|
+
const updatedMessages = [];
|
|
806
|
+
for (const messageUpdate of messages) {
|
|
807
|
+
const { id, content, ...otherFields } = messageUpdate;
|
|
808
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
809
|
+
const keyObjs = await this.operations.listKV(TABLE_MESSAGES, { prefix: `${prefix}${TABLE_MESSAGES}` });
|
|
810
|
+
let existingMessage = null;
|
|
811
|
+
let messageKey = "";
|
|
812
|
+
for (const { name: key } of keyObjs) {
|
|
813
|
+
const data = await this.operations.getKV(TABLE_MESSAGES, key);
|
|
814
|
+
if (data && data.id === id) {
|
|
815
|
+
existingMessage = data;
|
|
816
|
+
messageKey = key;
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
if (!existingMessage) {
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
const updatedMessage = {
|
|
824
|
+
...existingMessage,
|
|
825
|
+
...otherFields,
|
|
826
|
+
id
|
|
827
|
+
};
|
|
828
|
+
if (content) {
|
|
829
|
+
if (content.metadata !== void 0) {
|
|
830
|
+
updatedMessage.content = {
|
|
831
|
+
...updatedMessage.content,
|
|
832
|
+
metadata: {
|
|
833
|
+
...updatedMessage.content?.metadata,
|
|
834
|
+
...content.metadata
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
if (content.content !== void 0) {
|
|
839
|
+
updatedMessage.content = {
|
|
840
|
+
...updatedMessage.content,
|
|
841
|
+
content: content.content
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if ("threadId" in messageUpdate && messageUpdate.threadId && messageUpdate.threadId !== existingMessage.threadId) {
|
|
846
|
+
await this.operations.deleteKV(TABLE_MESSAGES, messageKey);
|
|
847
|
+
updatedMessage.threadId = messageUpdate.threadId;
|
|
848
|
+
const newMessageKey = this.getMessageKey(messageUpdate.threadId, id);
|
|
849
|
+
await this.operations.putKV({
|
|
850
|
+
tableName: TABLE_MESSAGES,
|
|
851
|
+
key: newMessageKey,
|
|
852
|
+
value: updatedMessage
|
|
853
|
+
});
|
|
854
|
+
if (existingMessage.threadId) {
|
|
855
|
+
const sourceOrderKey = this.getThreadMessagesKey(existingMessage.threadId);
|
|
856
|
+
const sourceEntries = await this.getSortedMessages(sourceOrderKey);
|
|
857
|
+
const filteredEntries = sourceEntries.filter((entry) => entry.id !== id);
|
|
858
|
+
await this.updateSortedMessages(sourceOrderKey, filteredEntries);
|
|
859
|
+
}
|
|
860
|
+
const destOrderKey = this.getThreadMessagesKey(messageUpdate.threadId);
|
|
861
|
+
const destEntries = await this.getSortedMessages(destOrderKey);
|
|
862
|
+
const newEntry = { id, score: Date.now() };
|
|
863
|
+
destEntries.push(newEntry);
|
|
864
|
+
await this.updateSortedMessages(destOrderKey, destEntries);
|
|
865
|
+
} else {
|
|
866
|
+
await this.operations.putKV({
|
|
867
|
+
tableName: TABLE_MESSAGES,
|
|
868
|
+
key: messageKey,
|
|
869
|
+
value: updatedMessage
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
const threadsToUpdate = /* @__PURE__ */ new Set();
|
|
873
|
+
if (updatedMessage.threadId) {
|
|
874
|
+
threadsToUpdate.add(updatedMessage.threadId);
|
|
875
|
+
}
|
|
876
|
+
if ("threadId" in messageUpdate && messageUpdate.threadId && messageUpdate.threadId !== existingMessage.threadId) {
|
|
877
|
+
if (existingMessage.threadId) {
|
|
878
|
+
threadsToUpdate.add(existingMessage.threadId);
|
|
879
|
+
}
|
|
880
|
+
threadsToUpdate.add(messageUpdate.threadId);
|
|
403
881
|
}
|
|
882
|
+
for (const threadId of threadsToUpdate) {
|
|
883
|
+
const thread = await this.getThreadById({ threadId });
|
|
884
|
+
if (thread) {
|
|
885
|
+
const updatedThread = {
|
|
886
|
+
...thread,
|
|
887
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
888
|
+
};
|
|
889
|
+
await this.operations.putKV({
|
|
890
|
+
tableName: TABLE_THREADS,
|
|
891
|
+
key: this.operations.getKey(TABLE_THREADS, { id: threadId }),
|
|
892
|
+
value: updatedThread
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
updatedMessages.push(updatedMessage);
|
|
404
897
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
898
|
+
return updatedMessages;
|
|
899
|
+
} catch (error) {
|
|
900
|
+
throw new MastraError(
|
|
901
|
+
{
|
|
902
|
+
id: "CLOUDFLARE_STORAGE_UPDATE_MESSAGES_FAILED",
|
|
903
|
+
domain: ErrorDomain.STORAGE,
|
|
904
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
905
|
+
text: "Failed to update messages"
|
|
906
|
+
},
|
|
907
|
+
error
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async getResourceById({ resourceId }) {
|
|
912
|
+
try {
|
|
913
|
+
const data = await this.operations.getKV(TABLE_RESOURCES, resourceId);
|
|
914
|
+
if (!data) return null;
|
|
915
|
+
const resource = typeof data === "string" ? JSON.parse(data) : data;
|
|
916
|
+
return {
|
|
917
|
+
...resource,
|
|
918
|
+
createdAt: ensureDate(resource.createdAt),
|
|
919
|
+
updatedAt: ensureDate(resource.updatedAt),
|
|
920
|
+
metadata: this.ensureMetadata(resource.metadata)
|
|
921
|
+
};
|
|
922
|
+
} catch (error) {
|
|
923
|
+
const mastraError = new MastraError(
|
|
924
|
+
{
|
|
925
|
+
id: "CLOUDFLARE_STORAGE_GET_RESOURCE_BY_ID_FAILED",
|
|
926
|
+
domain: ErrorDomain.STORAGE,
|
|
927
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
928
|
+
details: {
|
|
929
|
+
resourceId
|
|
930
|
+
}
|
|
931
|
+
},
|
|
932
|
+
error
|
|
933
|
+
);
|
|
934
|
+
this.logger?.trackException(mastraError);
|
|
935
|
+
this.logger?.error(mastraError.toString());
|
|
936
|
+
return null;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
async saveResource({ resource }) {
|
|
940
|
+
try {
|
|
941
|
+
const resourceToSave = {
|
|
942
|
+
...resource,
|
|
943
|
+
metadata: resource.metadata ? JSON.stringify(resource.metadata) : null
|
|
944
|
+
};
|
|
945
|
+
await this.operations.putKV({
|
|
946
|
+
tableName: TABLE_RESOURCES,
|
|
947
|
+
key: resource.id,
|
|
948
|
+
value: resourceToSave
|
|
949
|
+
});
|
|
950
|
+
return resource;
|
|
951
|
+
} catch (error) {
|
|
952
|
+
throw new MastraError(
|
|
953
|
+
{
|
|
954
|
+
id: "CLOUDFLARE_STORAGE_SAVE_RESOURCE_FAILED",
|
|
955
|
+
domain: ErrorDomain.STORAGE,
|
|
956
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
957
|
+
details: {
|
|
958
|
+
resourceId: resource.id
|
|
959
|
+
}
|
|
960
|
+
},
|
|
961
|
+
error
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
async updateResource({
|
|
966
|
+
resourceId,
|
|
967
|
+
workingMemory,
|
|
968
|
+
metadata
|
|
969
|
+
}) {
|
|
970
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
971
|
+
if (!existingResource) {
|
|
972
|
+
const newResource = {
|
|
973
|
+
id: resourceId,
|
|
974
|
+
workingMemory,
|
|
975
|
+
metadata: metadata || {},
|
|
976
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
977
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
978
|
+
};
|
|
979
|
+
return this.saveResource({ resource: newResource });
|
|
980
|
+
}
|
|
981
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
982
|
+
const updatedResource = {
|
|
983
|
+
...existingResource,
|
|
984
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
985
|
+
metadata: {
|
|
986
|
+
...existingResource.metadata,
|
|
987
|
+
...metadata
|
|
988
|
+
},
|
|
989
|
+
updatedAt
|
|
990
|
+
};
|
|
991
|
+
return this.saveResource({ resource: updatedResource });
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
var StoreOperationsCloudflare = class extends StoreOperations {
|
|
995
|
+
bindings;
|
|
996
|
+
client;
|
|
997
|
+
accountId;
|
|
998
|
+
namespacePrefix;
|
|
999
|
+
constructor({
|
|
1000
|
+
namespacePrefix,
|
|
1001
|
+
bindings,
|
|
1002
|
+
client,
|
|
1003
|
+
accountId
|
|
1004
|
+
}) {
|
|
1005
|
+
super();
|
|
1006
|
+
this.bindings = bindings;
|
|
1007
|
+
this.namespacePrefix = namespacePrefix;
|
|
1008
|
+
this.client = client;
|
|
1009
|
+
this.accountId = accountId;
|
|
408
1010
|
}
|
|
409
|
-
async
|
|
410
|
-
|
|
411
|
-
const index = order.findIndex((item) => item.id === id);
|
|
412
|
-
return index >= 0 ? index : null;
|
|
1011
|
+
async hasColumn() {
|
|
1012
|
+
return true;
|
|
413
1013
|
}
|
|
414
|
-
async
|
|
415
|
-
const order = await this.getSortedMessages(orderKey);
|
|
416
|
-
const actualStart = start < 0 ? Math.max(0, order.length + start) : start;
|
|
417
|
-
const actualEnd = end < 0 ? order.length + end : Math.min(end, order.length - 1);
|
|
418
|
-
const sliced = order.slice(actualStart, actualEnd + 1);
|
|
419
|
-
return sliced.map((item) => item.id);
|
|
1014
|
+
async alterTable(_args) {
|
|
420
1015
|
}
|
|
421
|
-
async
|
|
422
|
-
|
|
1016
|
+
async clearTable({ tableName }) {
|
|
1017
|
+
try {
|
|
1018
|
+
const keys = await this.listKV(tableName);
|
|
1019
|
+
if (keys.length > 0) {
|
|
1020
|
+
await Promise.all(keys.map((keyObj) => this.deleteKV(tableName, keyObj.name)));
|
|
1021
|
+
}
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
throw new MastraError(
|
|
1024
|
+
{
|
|
1025
|
+
id: "CLOUDFLARE_STORAGE_CLEAR_TABLE_FAILED",
|
|
1026
|
+
domain: ErrorDomain.STORAGE,
|
|
1027
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1028
|
+
details: {
|
|
1029
|
+
tableName
|
|
1030
|
+
}
|
|
1031
|
+
},
|
|
1032
|
+
error
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
423
1035
|
}
|
|
424
|
-
async
|
|
425
|
-
|
|
1036
|
+
async dropTable({ tableName }) {
|
|
1037
|
+
try {
|
|
1038
|
+
const keys = await this.listKV(tableName);
|
|
1039
|
+
if (keys.length > 0) {
|
|
1040
|
+
await Promise.all(keys.map((keyObj) => this.deleteKV(tableName, keyObj.name)));
|
|
1041
|
+
}
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
throw new MastraError(
|
|
1044
|
+
{
|
|
1045
|
+
id: "CLOUDFLARE_STORAGE_DROP_TABLE_FAILED",
|
|
1046
|
+
domain: ErrorDomain.STORAGE,
|
|
1047
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1048
|
+
details: {
|
|
1049
|
+
tableName
|
|
1050
|
+
}
|
|
1051
|
+
},
|
|
1052
|
+
error
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
getBinding(tableName) {
|
|
1057
|
+
if (!this.bindings) {
|
|
1058
|
+
throw new Error(`Cannot use Workers API binding for ${tableName}: Store initialized with REST API configuration`);
|
|
1059
|
+
}
|
|
1060
|
+
const binding = this.bindings[tableName];
|
|
1061
|
+
if (!binding) throw new Error(`No binding found for namespace ${tableName}`);
|
|
1062
|
+
return binding;
|
|
426
1063
|
}
|
|
427
1064
|
getKey(tableName, record) {
|
|
428
1065
|
const prefix = this.namespacePrefix ? `${this.namespacePrefix}:` : "";
|
|
@@ -434,10 +1071,10 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
434
1071
|
if (!record.threadId || !record.id) throw new Error("Thread ID and Message ID are required");
|
|
435
1072
|
return `${prefix}${tableName}:${record.threadId}:${record.id}`;
|
|
436
1073
|
case TABLE_WORKFLOW_SNAPSHOT:
|
|
437
|
-
if (!record.
|
|
438
|
-
throw new Error("
|
|
1074
|
+
if (!record.workflow_name || !record.run_id) {
|
|
1075
|
+
throw new Error("Workflow name, and run ID are required");
|
|
439
1076
|
}
|
|
440
|
-
let key = `${prefix}${tableName}:${record.
|
|
1077
|
+
let key = `${prefix}${tableName}:${record.workflow_name}:${record.run_id}`;
|
|
441
1078
|
if (record.resourceId) {
|
|
442
1079
|
key = `${key}:${record.resourceId}`;
|
|
443
1080
|
}
|
|
@@ -445,6 +1082,13 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
445
1082
|
case TABLE_TRACES:
|
|
446
1083
|
if (!record.id) throw new Error("Trace ID is required");
|
|
447
1084
|
return `${prefix}${tableName}:${record.id}`;
|
|
1085
|
+
case TABLE_EVALS:
|
|
1086
|
+
const evalId = record.id || record.run_id;
|
|
1087
|
+
if (!evalId) throw new Error("Eval ID or run_id is required");
|
|
1088
|
+
return `${prefix}${tableName}:${evalId}`;
|
|
1089
|
+
case TABLE_SCORERS:
|
|
1090
|
+
if (!record.id) throw new Error("Score ID is required");
|
|
1091
|
+
return `${prefix}${tableName}:${record.id}`;
|
|
448
1092
|
default:
|
|
449
1093
|
throw new Error(`Unsupported table: ${tableName}`);
|
|
450
1094
|
}
|
|
@@ -453,6 +1097,146 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
453
1097
|
const prefix = this.namespacePrefix ? `${this.namespacePrefix}:` : "";
|
|
454
1098
|
return `${prefix}schema:${tableName}`;
|
|
455
1099
|
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Helper to safely parse data from KV storage
|
|
1102
|
+
*/
|
|
1103
|
+
safeParse(text) {
|
|
1104
|
+
if (!text) return null;
|
|
1105
|
+
try {
|
|
1106
|
+
const data = JSON.parse(text);
|
|
1107
|
+
if (data && typeof data === "object" && "value" in data) {
|
|
1108
|
+
if (typeof data.value === "string") {
|
|
1109
|
+
try {
|
|
1110
|
+
return JSON.parse(data.value);
|
|
1111
|
+
} catch {
|
|
1112
|
+
return data.value;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return null;
|
|
1116
|
+
}
|
|
1117
|
+
return data;
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1120
|
+
this.logger.error("Failed to parse text:", { message, text });
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
async createNamespaceById(title) {
|
|
1125
|
+
if (this.bindings) {
|
|
1126
|
+
return {
|
|
1127
|
+
id: title,
|
|
1128
|
+
// Use title as ID since that's what we need
|
|
1129
|
+
title,
|
|
1130
|
+
supports_url_encoding: true
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
return await this.client.kv.namespaces.create({
|
|
1134
|
+
account_id: this.accountId,
|
|
1135
|
+
title
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
async createNamespace(namespaceName) {
|
|
1139
|
+
try {
|
|
1140
|
+
const response = await this.createNamespaceById(namespaceName);
|
|
1141
|
+
return response.id;
|
|
1142
|
+
} catch (error) {
|
|
1143
|
+
if (error.message && error.message.includes("already exists")) {
|
|
1144
|
+
const namespaces = await this.listNamespaces();
|
|
1145
|
+
const namespace = namespaces.result.find((ns) => ns.title === namespaceName);
|
|
1146
|
+
if (namespace) return namespace.id;
|
|
1147
|
+
}
|
|
1148
|
+
this.logger.error("Error creating namespace:", error);
|
|
1149
|
+
throw new Error(`Failed to create namespace ${namespaceName}: ${error.message}`);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
async listNamespaces() {
|
|
1153
|
+
if (this.bindings) {
|
|
1154
|
+
return {
|
|
1155
|
+
result: Object.keys(this.bindings).map((name) => ({
|
|
1156
|
+
id: name,
|
|
1157
|
+
title: name,
|
|
1158
|
+
supports_url_encoding: true
|
|
1159
|
+
}))
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
let allNamespaces = [];
|
|
1163
|
+
let currentPage = 1;
|
|
1164
|
+
const perPage = 50;
|
|
1165
|
+
let morePagesExist = true;
|
|
1166
|
+
while (morePagesExist) {
|
|
1167
|
+
const response = await this.client.kv.namespaces.list({
|
|
1168
|
+
account_id: this.accountId,
|
|
1169
|
+
page: currentPage,
|
|
1170
|
+
per_page: perPage
|
|
1171
|
+
});
|
|
1172
|
+
if (response.result) {
|
|
1173
|
+
allNamespaces = allNamespaces.concat(response.result);
|
|
1174
|
+
}
|
|
1175
|
+
morePagesExist = response.result ? response.result.length === perPage : false;
|
|
1176
|
+
if (morePagesExist) {
|
|
1177
|
+
currentPage++;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return { result: allNamespaces };
|
|
1181
|
+
}
|
|
1182
|
+
async getNamespaceIdByName(namespaceName) {
|
|
1183
|
+
try {
|
|
1184
|
+
const response = await this.listNamespaces();
|
|
1185
|
+
const namespace = response.result.find((ns) => ns.title === namespaceName);
|
|
1186
|
+
return namespace ? namespace.id : null;
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
this.logger.error(`Failed to get namespace ID for ${namespaceName}:`, error);
|
|
1189
|
+
return null;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
async getOrCreateNamespaceId(namespaceName) {
|
|
1193
|
+
let namespaceId = await this.getNamespaceIdByName(namespaceName);
|
|
1194
|
+
if (!namespaceId) {
|
|
1195
|
+
namespaceId = await this.createNamespace(namespaceName);
|
|
1196
|
+
}
|
|
1197
|
+
return namespaceId;
|
|
1198
|
+
}
|
|
1199
|
+
async getNamespaceId(tableName) {
|
|
1200
|
+
const prefix = this.namespacePrefix ? `${this.namespacePrefix}_` : "";
|
|
1201
|
+
try {
|
|
1202
|
+
return await this.getOrCreateNamespaceId(`${prefix}${tableName}`);
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
this.logger.error("Error fetching namespace ID:", error);
|
|
1205
|
+
throw new Error(`Failed to fetch namespace ID for table ${tableName}: ${error.message}`);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
async getNamespaceValue(tableName, key) {
|
|
1209
|
+
try {
|
|
1210
|
+
if (this.bindings) {
|
|
1211
|
+
const binding = this.getBinding(tableName);
|
|
1212
|
+
const result = await binding.getWithMetadata(key, "text");
|
|
1213
|
+
if (!result) return null;
|
|
1214
|
+
return JSON.stringify(result);
|
|
1215
|
+
} else {
|
|
1216
|
+
const namespaceId = await this.getNamespaceId(tableName);
|
|
1217
|
+
const response = await this.client.kv.namespaces.values.get(namespaceId, key, {
|
|
1218
|
+
account_id: this.accountId
|
|
1219
|
+
});
|
|
1220
|
+
return await response.text();
|
|
1221
|
+
}
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
if (error.message && error.message.includes("key not found")) {
|
|
1224
|
+
return null;
|
|
1225
|
+
}
|
|
1226
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1227
|
+
this.logger.error(`Failed to get value for ${tableName} ${key}:`, { message });
|
|
1228
|
+
throw error;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
async getKV(tableName, key) {
|
|
1232
|
+
try {
|
|
1233
|
+
const text = await this.getNamespaceValue(tableName, key);
|
|
1234
|
+
return this.safeParse(text);
|
|
1235
|
+
} catch (error) {
|
|
1236
|
+
this.logger.error(`Failed to get KV value for ${tableName}:${key}:`, error);
|
|
1237
|
+
throw new Error(`Failed to get KV value: ${error.message}`);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
456
1240
|
async getTableSchema(tableName) {
|
|
457
1241
|
try {
|
|
458
1242
|
const schemaKey = this.getSchemaKey(tableName);
|
|
@@ -532,7 +1316,7 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
532
1316
|
}
|
|
533
1317
|
break;
|
|
534
1318
|
case TABLE_WORKFLOW_SNAPSHOT:
|
|
535
|
-
if (!("
|
|
1319
|
+
if (!("workflow_name" in recordTyped) || !("run_id" in recordTyped)) {
|
|
536
1320
|
throw new Error("Workflow record missing required fields");
|
|
537
1321
|
}
|
|
538
1322
|
break;
|
|
@@ -541,6 +1325,16 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
541
1325
|
throw new Error("Trace record missing required fields");
|
|
542
1326
|
}
|
|
543
1327
|
break;
|
|
1328
|
+
case TABLE_EVALS:
|
|
1329
|
+
if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
|
|
1330
|
+
throw new Error("Eval record missing required fields");
|
|
1331
|
+
}
|
|
1332
|
+
break;
|
|
1333
|
+
case TABLE_SCORERS:
|
|
1334
|
+
if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
|
|
1335
|
+
throw new Error("Score record missing required fields");
|
|
1336
|
+
}
|
|
1337
|
+
break;
|
|
544
1338
|
default:
|
|
545
1339
|
throw new Error(`Unknown table type: ${tableName}`);
|
|
546
1340
|
}
|
|
@@ -550,19 +1344,139 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
550
1344
|
throw error;
|
|
551
1345
|
}
|
|
552
1346
|
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
1347
|
+
async insert({ tableName, record }) {
|
|
1348
|
+
try {
|
|
1349
|
+
const key = this.getKey(tableName, record);
|
|
1350
|
+
const processedRecord = {
|
|
1351
|
+
...record,
|
|
1352
|
+
createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
|
|
1353
|
+
updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
|
|
1354
|
+
metadata: record.metadata ? JSON.stringify(record.metadata) : ""
|
|
1355
|
+
};
|
|
1356
|
+
await this.validateRecord(processedRecord, tableName);
|
|
1357
|
+
await this.putKV({ tableName, key, value: processedRecord });
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
throw new MastraError(
|
|
1360
|
+
{
|
|
1361
|
+
id: "CLOUDFLARE_STORAGE_INSERT_FAILED",
|
|
1362
|
+
domain: ErrorDomain.STORAGE,
|
|
1363
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1364
|
+
details: {
|
|
1365
|
+
tableName
|
|
1366
|
+
}
|
|
1367
|
+
},
|
|
1368
|
+
error
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
561
1371
|
}
|
|
562
1372
|
ensureMetadata(metadata) {
|
|
563
1373
|
if (!metadata) return {};
|
|
564
1374
|
return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
|
|
565
1375
|
}
|
|
1376
|
+
async load({ tableName, keys }) {
|
|
1377
|
+
try {
|
|
1378
|
+
const key = this.getKey(tableName, keys);
|
|
1379
|
+
const data = await this.getKV(tableName, key);
|
|
1380
|
+
if (!data) return null;
|
|
1381
|
+
const processed = {
|
|
1382
|
+
...data,
|
|
1383
|
+
createdAt: ensureDate(data.createdAt),
|
|
1384
|
+
updatedAt: ensureDate(data.updatedAt),
|
|
1385
|
+
metadata: this.ensureMetadata(data.metadata)
|
|
1386
|
+
};
|
|
1387
|
+
return processed;
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
const mastraError = new MastraError(
|
|
1390
|
+
{
|
|
1391
|
+
id: "CLOUDFLARE_STORAGE_LOAD_FAILED",
|
|
1392
|
+
domain: ErrorDomain.STORAGE,
|
|
1393
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1394
|
+
details: {
|
|
1395
|
+
tableName
|
|
1396
|
+
}
|
|
1397
|
+
},
|
|
1398
|
+
error
|
|
1399
|
+
);
|
|
1400
|
+
this.logger?.trackException(mastraError);
|
|
1401
|
+
this.logger?.error(mastraError.toString());
|
|
1402
|
+
return null;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
async batchInsert(input) {
|
|
1406
|
+
if (!input.records || input.records.length === 0) return;
|
|
1407
|
+
try {
|
|
1408
|
+
await Promise.all(
|
|
1409
|
+
input.records.map(async (record) => {
|
|
1410
|
+
const key = this.getKey(input.tableName, record);
|
|
1411
|
+
const processedRecord = {
|
|
1412
|
+
...record,
|
|
1413
|
+
createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
|
|
1414
|
+
updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
|
|
1415
|
+
metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
|
|
1416
|
+
};
|
|
1417
|
+
await this.putKV({ tableName: input.tableName, key, value: processedRecord });
|
|
1418
|
+
})
|
|
1419
|
+
);
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
throw new MastraError(
|
|
1422
|
+
{
|
|
1423
|
+
id: "CLOUDFLARE_STORAGE_BATCH_INSERT_FAILED",
|
|
1424
|
+
domain: ErrorDomain.STORAGE,
|
|
1425
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1426
|
+
text: `Error in batch insert for table ${input.tableName}`,
|
|
1427
|
+
details: {
|
|
1428
|
+
tableName: input.tableName
|
|
1429
|
+
}
|
|
1430
|
+
},
|
|
1431
|
+
error
|
|
1432
|
+
);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Helper to safely serialize data for KV storage
|
|
1437
|
+
*/
|
|
1438
|
+
safeSerialize(data) {
|
|
1439
|
+
return typeof data === "string" ? data : JSON.stringify(data);
|
|
1440
|
+
}
|
|
1441
|
+
async putNamespaceValue({
|
|
1442
|
+
tableName,
|
|
1443
|
+
key,
|
|
1444
|
+
value,
|
|
1445
|
+
metadata
|
|
1446
|
+
}) {
|
|
1447
|
+
try {
|
|
1448
|
+
const serializedValue = this.safeSerialize(value);
|
|
1449
|
+
const serializedMetadata = metadata ? this.safeSerialize(metadata) : "";
|
|
1450
|
+
if (this.bindings) {
|
|
1451
|
+
const binding = this.getBinding(tableName);
|
|
1452
|
+
await binding.put(key, serializedValue, { metadata: serializedMetadata });
|
|
1453
|
+
} else {
|
|
1454
|
+
const namespaceId = await this.getNamespaceId(tableName);
|
|
1455
|
+
await this.client.kv.namespaces.values.update(namespaceId, key, {
|
|
1456
|
+
account_id: this.accountId,
|
|
1457
|
+
value: serializedValue,
|
|
1458
|
+
metadata: serializedMetadata
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
} catch (error) {
|
|
1462
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1463
|
+
this.logger.error(`Failed to put value for ${tableName} ${key}:`, { message });
|
|
1464
|
+
throw error;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
async putKV({
|
|
1468
|
+
tableName,
|
|
1469
|
+
key,
|
|
1470
|
+
value,
|
|
1471
|
+
metadata
|
|
1472
|
+
}) {
|
|
1473
|
+
try {
|
|
1474
|
+
await this.putNamespaceValue({ tableName, key, value, metadata });
|
|
1475
|
+
} catch (error) {
|
|
1476
|
+
this.logger.error(`Failed to put KV value for ${tableName}:${key}:`, error);
|
|
1477
|
+
throw new Error(`Failed to put KV value: ${error.message}`);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
566
1480
|
async createTable({
|
|
567
1481
|
tableName,
|
|
568
1482
|
schema
|
|
@@ -576,475 +1490,518 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
576
1490
|
};
|
|
577
1491
|
await this.putKV({ tableName, key: schemaKey, value: schema, metadata });
|
|
578
1492
|
} catch (error) {
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
1493
|
+
throw new MastraError(
|
|
1494
|
+
{
|
|
1495
|
+
id: "CLOUDFLARE_STORAGE_CREATE_TABLE_FAILED",
|
|
1496
|
+
domain: ErrorDomain.STORAGE,
|
|
1497
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1498
|
+
details: {
|
|
1499
|
+
tableName
|
|
1500
|
+
}
|
|
1501
|
+
},
|
|
1502
|
+
error
|
|
1503
|
+
);
|
|
587
1504
|
}
|
|
588
1505
|
}
|
|
589
|
-
async
|
|
590
|
-
tableName,
|
|
591
|
-
record
|
|
592
|
-
}) {
|
|
1506
|
+
async listNamespaceKeys(tableName, options) {
|
|
593
1507
|
try {
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
1508
|
+
if (this.bindings) {
|
|
1509
|
+
const binding = this.getBinding(tableName);
|
|
1510
|
+
const response = await binding.list({
|
|
1511
|
+
limit: options?.limit || 1e3,
|
|
1512
|
+
prefix: options?.prefix
|
|
1513
|
+
});
|
|
1514
|
+
return response.keys;
|
|
1515
|
+
} else {
|
|
1516
|
+
const namespaceId = await this.getNamespaceId(tableName);
|
|
1517
|
+
const response = await this.client.kv.namespaces.keys.list(namespaceId, {
|
|
1518
|
+
account_id: this.accountId,
|
|
1519
|
+
limit: options?.limit || 1e3,
|
|
1520
|
+
prefix: options?.prefix
|
|
1521
|
+
});
|
|
1522
|
+
return response.result;
|
|
1523
|
+
}
|
|
603
1524
|
} catch (error) {
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
1525
|
+
throw new MastraError(
|
|
1526
|
+
{
|
|
1527
|
+
id: "CLOUDFLARE_STORAGE_LIST_NAMESPACE_KEYS_FAILED",
|
|
1528
|
+
domain: ErrorDomain.STORAGE,
|
|
1529
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1530
|
+
details: {
|
|
1531
|
+
tableName
|
|
1532
|
+
}
|
|
1533
|
+
},
|
|
1534
|
+
error
|
|
1535
|
+
);
|
|
607
1536
|
}
|
|
608
1537
|
}
|
|
609
|
-
async
|
|
610
|
-
|
|
611
|
-
const
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
const
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
updatedAt: this.ensureDate(data.updatedAt),
|
|
618
|
-
metadata: this.ensureMetadata(data.metadata)
|
|
619
|
-
};
|
|
620
|
-
return processed;
|
|
621
|
-
} catch (error) {
|
|
622
|
-
this.logger.error(`Failed to load data for ${tableName}:`, {
|
|
623
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1538
|
+
async deleteNamespaceValue(tableName, key) {
|
|
1539
|
+
if (this.bindings) {
|
|
1540
|
+
const binding = this.getBinding(tableName);
|
|
1541
|
+
await binding.delete(key);
|
|
1542
|
+
} else {
|
|
1543
|
+
const namespaceId = await this.getNamespaceId(tableName);
|
|
1544
|
+
await this.client.kv.namespaces.values.delete(namespaceId, key, {
|
|
1545
|
+
account_id: this.accountId
|
|
624
1546
|
});
|
|
625
|
-
return null;
|
|
626
1547
|
}
|
|
627
1548
|
}
|
|
628
|
-
async
|
|
629
|
-
const thread = await this.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
|
|
630
|
-
if (!thread) return null;
|
|
1549
|
+
async deleteKV(tableName, key) {
|
|
631
1550
|
try {
|
|
632
|
-
|
|
633
|
-
...thread,
|
|
634
|
-
createdAt: this.ensureDate(thread.createdAt),
|
|
635
|
-
updatedAt: this.ensureDate(thread.updatedAt),
|
|
636
|
-
metadata: this.ensureMetadata(thread.metadata)
|
|
637
|
-
};
|
|
1551
|
+
await this.deleteNamespaceValue(tableName, key);
|
|
638
1552
|
} catch (error) {
|
|
639
|
-
this.logger.error(`
|
|
640
|
-
|
|
641
|
-
});
|
|
642
|
-
return null;
|
|
1553
|
+
this.logger.error(`Failed to delete KV value for ${tableName}:${key}:`, error);
|
|
1554
|
+
throw new Error(`Failed to delete KV value: ${error.message}`);
|
|
643
1555
|
}
|
|
644
1556
|
}
|
|
645
|
-
async
|
|
1557
|
+
async listKV(tableName, options) {
|
|
646
1558
|
try {
|
|
647
|
-
|
|
648
|
-
const threads = await Promise.all(
|
|
649
|
-
keyList.map(async (keyObj) => {
|
|
650
|
-
try {
|
|
651
|
-
const data = await this.getKV(TABLE_THREADS, keyObj.name);
|
|
652
|
-
if (!data) return null;
|
|
653
|
-
const thread = typeof data === "string" ? JSON.parse(data) : data;
|
|
654
|
-
if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
|
|
655
|
-
return {
|
|
656
|
-
...thread,
|
|
657
|
-
createdAt: this.ensureDate(thread.createdAt),
|
|
658
|
-
updatedAt: this.ensureDate(thread.updatedAt),
|
|
659
|
-
metadata: this.ensureMetadata(thread.metadata)
|
|
660
|
-
};
|
|
661
|
-
} catch (error) {
|
|
662
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
663
|
-
this.logger.error(`Error processing thread from key ${keyObj.name}:`, { message });
|
|
664
|
-
return null;
|
|
665
|
-
}
|
|
666
|
-
})
|
|
667
|
-
);
|
|
668
|
-
return threads.filter((thread) => thread !== null);
|
|
1559
|
+
return await this.listNamespaceKeys(tableName, options);
|
|
669
1560
|
} catch (error) {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
return [];
|
|
1561
|
+
this.logger.error(`Failed to list KV for ${tableName}:`, error);
|
|
1562
|
+
throw new Error(`Failed to list KV: ${error.message}`);
|
|
673
1563
|
}
|
|
674
1564
|
}
|
|
675
|
-
|
|
1565
|
+
};
|
|
1566
|
+
function transformScoreRow(row) {
|
|
1567
|
+
const deserialized = { ...row };
|
|
1568
|
+
deserialized.input = safelyParseJSON(row.input);
|
|
1569
|
+
deserialized.output = safelyParseJSON(row.output);
|
|
1570
|
+
deserialized.scorer = safelyParseJSON(row.scorer);
|
|
1571
|
+
deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
|
|
1572
|
+
deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
|
|
1573
|
+
deserialized.metadata = safelyParseJSON(row.metadata);
|
|
1574
|
+
deserialized.additionalContext = safelyParseJSON(row.additionalContext);
|
|
1575
|
+
deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
|
|
1576
|
+
deserialized.entity = safelyParseJSON(row.entity);
|
|
1577
|
+
return deserialized;
|
|
1578
|
+
}
|
|
1579
|
+
var ScoresStorageCloudflare = class extends ScoresStorage {
|
|
1580
|
+
operations;
|
|
1581
|
+
constructor({ operations }) {
|
|
1582
|
+
super();
|
|
1583
|
+
this.operations = operations;
|
|
1584
|
+
}
|
|
1585
|
+
async getScoreById({ id }) {
|
|
676
1586
|
try {
|
|
677
|
-
await this.
|
|
678
|
-
|
|
1587
|
+
const score = await this.operations.getKV(TABLE_SCORERS, id);
|
|
1588
|
+
if (!score) {
|
|
1589
|
+
return null;
|
|
1590
|
+
}
|
|
1591
|
+
return transformScoreRow(score);
|
|
679
1592
|
} catch (error) {
|
|
680
|
-
const
|
|
681
|
-
|
|
682
|
-
|
|
1593
|
+
const mastraError = new MastraError(
|
|
1594
|
+
{
|
|
1595
|
+
id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORE_BY_ID_FAILED",
|
|
1596
|
+
domain: ErrorDomain.STORAGE,
|
|
1597
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1598
|
+
text: `Failed to get score by id: ${id}`
|
|
1599
|
+
},
|
|
1600
|
+
error
|
|
1601
|
+
);
|
|
1602
|
+
this.logger.trackException(mastraError);
|
|
1603
|
+
this.logger.error(mastraError.toString());
|
|
1604
|
+
return null;
|
|
683
1605
|
}
|
|
684
1606
|
}
|
|
685
|
-
async
|
|
686
|
-
id,
|
|
687
|
-
title,
|
|
688
|
-
metadata
|
|
689
|
-
}) {
|
|
1607
|
+
async saveScore(score) {
|
|
690
1608
|
try {
|
|
691
|
-
const
|
|
692
|
-
|
|
693
|
-
|
|
1609
|
+
const id = crypto.randomUUID();
|
|
1610
|
+
const { input, ...rest } = score;
|
|
1611
|
+
const serializedRecord = {};
|
|
1612
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
1613
|
+
if (value !== null && value !== void 0) {
|
|
1614
|
+
if (typeof value === "object") {
|
|
1615
|
+
serializedRecord[key] = JSON.stringify(value);
|
|
1616
|
+
} else {
|
|
1617
|
+
serializedRecord[key] = value;
|
|
1618
|
+
}
|
|
1619
|
+
} else {
|
|
1620
|
+
serializedRecord[key] = null;
|
|
1621
|
+
}
|
|
694
1622
|
}
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
};
|
|
704
|
-
|
|
705
|
-
return updatedThread;
|
|
1623
|
+
serializedRecord.id = id;
|
|
1624
|
+
serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1625
|
+
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1626
|
+
await this.operations.putKV({
|
|
1627
|
+
tableName: TABLE_SCORERS,
|
|
1628
|
+
key: id,
|
|
1629
|
+
value: serializedRecord
|
|
1630
|
+
});
|
|
1631
|
+
const scoreFromDb = await this.getScoreById({ id: score.id });
|
|
1632
|
+
return { score: scoreFromDb };
|
|
706
1633
|
} catch (error) {
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
1634
|
+
const mastraError = new MastraError(
|
|
1635
|
+
{
|
|
1636
|
+
id: "CLOUDFLARE_STORAGE_SCORES_SAVE_SCORE_FAILED",
|
|
1637
|
+
domain: ErrorDomain.STORAGE,
|
|
1638
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1639
|
+
text: `Failed to save score: ${score.id}`
|
|
1640
|
+
},
|
|
1641
|
+
error
|
|
1642
|
+
);
|
|
1643
|
+
this.logger.trackException(mastraError);
|
|
1644
|
+
this.logger.error(mastraError.toString());
|
|
1645
|
+
throw mastraError;
|
|
710
1646
|
}
|
|
711
1647
|
}
|
|
712
|
-
async
|
|
1648
|
+
async getScoresByScorerId({
|
|
1649
|
+
scorerId,
|
|
1650
|
+
entityId,
|
|
1651
|
+
entityType,
|
|
1652
|
+
source,
|
|
1653
|
+
pagination
|
|
1654
|
+
}) {
|
|
713
1655
|
try {
|
|
714
|
-
const
|
|
715
|
-
|
|
716
|
-
|
|
1656
|
+
const keys = await this.operations.listKV(TABLE_SCORERS);
|
|
1657
|
+
const scores = [];
|
|
1658
|
+
for (const { name: key } of keys) {
|
|
1659
|
+
const score = await this.operations.getKV(TABLE_SCORERS, key);
|
|
1660
|
+
if (entityId && score.entityId !== entityId) {
|
|
1661
|
+
continue;
|
|
1662
|
+
}
|
|
1663
|
+
if (entityType && score.entityType !== entityType) {
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
if (source && score.source !== source) {
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
if (score && score.scorerId === scorerId) {
|
|
1670
|
+
scores.push(transformScoreRow(score));
|
|
1671
|
+
}
|
|
717
1672
|
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
1673
|
+
scores.sort((a, b) => {
|
|
1674
|
+
const dateA = new Date(a.createdAt || 0).getTime();
|
|
1675
|
+
const dateB = new Date(b.createdAt || 0).getTime();
|
|
1676
|
+
return dateB - dateA;
|
|
1677
|
+
});
|
|
1678
|
+
const total = scores.length;
|
|
1679
|
+
const start = pagination.page * pagination.perPage;
|
|
1680
|
+
const end = start + pagination.perPage;
|
|
1681
|
+
const pagedScores = scores.slice(start, end);
|
|
1682
|
+
return {
|
|
1683
|
+
pagination: {
|
|
1684
|
+
total,
|
|
1685
|
+
page: pagination.page,
|
|
1686
|
+
perPage: pagination.perPage,
|
|
1687
|
+
hasMore: end < total
|
|
1688
|
+
},
|
|
1689
|
+
scores: pagedScores
|
|
1690
|
+
};
|
|
728
1691
|
} catch (error) {
|
|
729
|
-
const
|
|
730
|
-
|
|
731
|
-
|
|
1692
|
+
const mastraError = new MastraError(
|
|
1693
|
+
{
|
|
1694
|
+
id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
1695
|
+
domain: ErrorDomain.STORAGE,
|
|
1696
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1697
|
+
text: `Failed to get scores by scorer id: ${scorerId}`
|
|
1698
|
+
},
|
|
1699
|
+
error
|
|
1700
|
+
);
|
|
1701
|
+
this.logger?.trackException(mastraError);
|
|
1702
|
+
this.logger?.error(mastraError.toString());
|
|
1703
|
+
return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
|
|
732
1704
|
}
|
|
733
1705
|
}
|
|
734
|
-
|
|
1706
|
+
async getScoresByRunId({
|
|
1707
|
+
runId,
|
|
1708
|
+
pagination
|
|
1709
|
+
}) {
|
|
735
1710
|
try {
|
|
736
|
-
|
|
1711
|
+
const keys = await this.operations.listKV(TABLE_SCORERS);
|
|
1712
|
+
const scores = [];
|
|
1713
|
+
for (const { name: key } of keys) {
|
|
1714
|
+
const score = await this.operations.getKV(TABLE_SCORERS, key);
|
|
1715
|
+
if (score && score.runId === runId) {
|
|
1716
|
+
scores.push(transformScoreRow(score));
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
scores.sort((a, b) => {
|
|
1720
|
+
const dateA = new Date(a.createdAt || 0).getTime();
|
|
1721
|
+
const dateB = new Date(b.createdAt || 0).getTime();
|
|
1722
|
+
return dateB - dateA;
|
|
1723
|
+
});
|
|
1724
|
+
const total = scores.length;
|
|
1725
|
+
const start = pagination.page * pagination.perPage;
|
|
1726
|
+
const end = start + pagination.perPage;
|
|
1727
|
+
const pagedScores = scores.slice(start, end);
|
|
1728
|
+
return {
|
|
1729
|
+
pagination: {
|
|
1730
|
+
total,
|
|
1731
|
+
page: pagination.page,
|
|
1732
|
+
perPage: pagination.perPage,
|
|
1733
|
+
hasMore: end < total
|
|
1734
|
+
},
|
|
1735
|
+
scores: pagedScores
|
|
1736
|
+
};
|
|
737
1737
|
} catch (error) {
|
|
738
|
-
const
|
|
739
|
-
|
|
740
|
-
|
|
1738
|
+
const mastraError = new MastraError(
|
|
1739
|
+
{
|
|
1740
|
+
id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
|
|
1741
|
+
domain: ErrorDomain.STORAGE,
|
|
1742
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1743
|
+
text: `Failed to get scores by run id: ${runId}`
|
|
1744
|
+
},
|
|
1745
|
+
error
|
|
1746
|
+
);
|
|
1747
|
+
this.logger.trackException(mastraError);
|
|
1748
|
+
this.logger.error(mastraError.toString());
|
|
1749
|
+
return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
|
|
741
1750
|
}
|
|
742
1751
|
}
|
|
743
|
-
|
|
1752
|
+
async getScoresByEntityId({
|
|
1753
|
+
entityId,
|
|
1754
|
+
entityType,
|
|
1755
|
+
pagination
|
|
1756
|
+
}) {
|
|
744
1757
|
try {
|
|
745
|
-
|
|
1758
|
+
const keys = await this.operations.listKV(TABLE_SCORERS);
|
|
1759
|
+
const scores = [];
|
|
1760
|
+
for (const { name: key } of keys) {
|
|
1761
|
+
const score = await this.operations.getKV(TABLE_SCORERS, key);
|
|
1762
|
+
if (score && score.entityId === entityId && score.entityType === entityType) {
|
|
1763
|
+
scores.push(transformScoreRow(score));
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
scores.sort((a, b) => {
|
|
1767
|
+
const dateA = new Date(a.createdAt || 0).getTime();
|
|
1768
|
+
const dateB = new Date(b.createdAt || 0).getTime();
|
|
1769
|
+
return dateB - dateA;
|
|
1770
|
+
});
|
|
1771
|
+
const total = scores.length;
|
|
1772
|
+
const start = pagination.page * pagination.perPage;
|
|
1773
|
+
const end = start + pagination.perPage;
|
|
1774
|
+
const pagedScores = scores.slice(start, end);
|
|
1775
|
+
return {
|
|
1776
|
+
pagination: {
|
|
1777
|
+
total,
|
|
1778
|
+
page: pagination.page,
|
|
1779
|
+
perPage: pagination.perPage,
|
|
1780
|
+
hasMore: end < total
|
|
1781
|
+
},
|
|
1782
|
+
scores: pagedScores
|
|
1783
|
+
};
|
|
746
1784
|
} catch (error) {
|
|
747
|
-
const
|
|
748
|
-
|
|
749
|
-
|
|
1785
|
+
const mastraError = new MastraError(
|
|
1786
|
+
{
|
|
1787
|
+
id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
1788
|
+
domain: ErrorDomain.STORAGE,
|
|
1789
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1790
|
+
text: `Failed to get scores by entity id: ${entityId}, type: ${entityType}`
|
|
1791
|
+
},
|
|
1792
|
+
error
|
|
1793
|
+
);
|
|
1794
|
+
this.logger.trackException(mastraError);
|
|
1795
|
+
this.logger.error(mastraError.toString());
|
|
1796
|
+
return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
|
|
750
1797
|
}
|
|
751
1798
|
}
|
|
752
|
-
|
|
753
|
-
|
|
1799
|
+
};
|
|
1800
|
+
var TracesStorageCloudflare = class extends TracesStorage {
|
|
1801
|
+
operations;
|
|
1802
|
+
constructor({ operations }) {
|
|
1803
|
+
super();
|
|
1804
|
+
this.operations = operations;
|
|
1805
|
+
}
|
|
1806
|
+
async getTraces(args) {
|
|
1807
|
+
const paginatedArgs = {
|
|
1808
|
+
name: args.name,
|
|
1809
|
+
scope: args.scope,
|
|
1810
|
+
page: args.page,
|
|
1811
|
+
perPage: args.perPage,
|
|
1812
|
+
attributes: args.attributes,
|
|
1813
|
+
filters: args.filters,
|
|
1814
|
+
dateRange: args.fromDate || args.toDate ? {
|
|
1815
|
+
start: args.fromDate,
|
|
1816
|
+
end: args.toDate
|
|
1817
|
+
} : void 0
|
|
1818
|
+
};
|
|
754
1819
|
try {
|
|
755
|
-
const
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
createdAt: this.ensureDate(message.createdAt),
|
|
768
|
-
type: message.type || "text",
|
|
769
|
-
_index: index
|
|
770
|
-
};
|
|
771
|
-
});
|
|
772
|
-
const messagesByThread = validatedMessages.reduce((acc, message) => {
|
|
773
|
-
if (!acc.has(message.threadId)) {
|
|
774
|
-
acc.set(message.threadId, []);
|
|
775
|
-
}
|
|
776
|
-
acc.get(message.threadId).push(message);
|
|
777
|
-
return acc;
|
|
778
|
-
}, /* @__PURE__ */ new Map());
|
|
779
|
-
await Promise.all(
|
|
780
|
-
Array.from(messagesByThread.entries()).map(async ([threadId, threadMessages]) => {
|
|
781
|
-
try {
|
|
782
|
-
const thread = await this.getThreadById({ threadId });
|
|
783
|
-
if (!thread) {
|
|
784
|
-
throw new Error(`Thread ${threadId} not found`);
|
|
785
|
-
}
|
|
786
|
-
await Promise.all(
|
|
787
|
-
threadMessages.map(async (message) => {
|
|
788
|
-
const key = await this.getMessageKey(threadId, message.id);
|
|
789
|
-
const { _index, ...cleanMessage } = message;
|
|
790
|
-
const serializedMessage = {
|
|
791
|
-
...cleanMessage,
|
|
792
|
-
createdAt: this.serializeDate(cleanMessage.createdAt)
|
|
793
|
-
};
|
|
794
|
-
await this.putKV({ tableName: TABLE_MESSAGES, key, value: serializedMessage });
|
|
795
|
-
})
|
|
796
|
-
);
|
|
797
|
-
const orderKey = this.getThreadMessagesKey(threadId);
|
|
798
|
-
const entries = await this.updateSorting(threadMessages);
|
|
799
|
-
await this.updateSortedMessages(orderKey, entries);
|
|
800
|
-
} catch (error) {
|
|
801
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
802
|
-
this.logger.error(`Error processing messages for thread ${threadId}: ${errorMessage}`);
|
|
803
|
-
throw error;
|
|
1820
|
+
const result = await this.getTracesPaginated(paginatedArgs);
|
|
1821
|
+
return result.traces;
|
|
1822
|
+
} catch (error) {
|
|
1823
|
+
throw new MastraError(
|
|
1824
|
+
{
|
|
1825
|
+
id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
|
|
1826
|
+
domain: ErrorDomain.STORAGE,
|
|
1827
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1828
|
+
text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
|
|
1829
|
+
details: {
|
|
1830
|
+
name: args.name ?? "",
|
|
1831
|
+
scope: args.scope ?? ""
|
|
804
1832
|
}
|
|
805
|
-
}
|
|
1833
|
+
},
|
|
1834
|
+
error
|
|
806
1835
|
);
|
|
807
|
-
return validatedMessages.map(({ _index, ...message }) => message);
|
|
808
|
-
} catch (error) {
|
|
809
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
810
|
-
this.logger.error(`Error saving messages: ${errorMessage}`);
|
|
811
|
-
throw error;
|
|
812
1836
|
}
|
|
813
1837
|
}
|
|
814
|
-
async
|
|
815
|
-
if (!threadId) throw new Error("threadId is required");
|
|
816
|
-
let limit = 40;
|
|
817
|
-
if (typeof selectBy?.last === "number") {
|
|
818
|
-
limit = Math.max(0, selectBy.last);
|
|
819
|
-
} else if (selectBy?.last === false) {
|
|
820
|
-
limit = 0;
|
|
821
|
-
}
|
|
822
|
-
const messageIds = /* @__PURE__ */ new Set();
|
|
823
|
-
if (limit === 0 && !selectBy?.include?.length) return [];
|
|
1838
|
+
async getTracesPaginated(args) {
|
|
824
1839
|
try {
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
]
|
|
829
|
-
const
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
1840
|
+
const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
|
|
1841
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
1842
|
+
const keyObjs = await this.operations.listKV(TABLE_TRACES, { prefix: `${prefix}${TABLE_TRACES}` });
|
|
1843
|
+
const traces = [];
|
|
1844
|
+
for (const { name: key } of keyObjs) {
|
|
1845
|
+
try {
|
|
1846
|
+
const data = await this.operations.getKV(TABLE_TRACES, key);
|
|
1847
|
+
if (!data) continue;
|
|
1848
|
+
if (name && data.name !== name) continue;
|
|
1849
|
+
if (scope && data.scope !== scope) continue;
|
|
1850
|
+
if (attributes) {
|
|
1851
|
+
const dataAttributes = data.attributes || {};
|
|
1852
|
+
let shouldSkip = false;
|
|
1853
|
+
for (const [key2, value] of Object.entries(attributes)) {
|
|
1854
|
+
if (dataAttributes[key2] !== value) {
|
|
1855
|
+
shouldSkip = true;
|
|
1856
|
+
break;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
if (shouldSkip) continue;
|
|
1860
|
+
}
|
|
1861
|
+
if (dateRange?.start || dateRange?.end) {
|
|
1862
|
+
const traceDate = new Date(data.createdAt || 0);
|
|
1863
|
+
if (dateRange.start && traceDate < dateRange.start) continue;
|
|
1864
|
+
if (dateRange.end && traceDate > dateRange.end) continue;
|
|
1865
|
+
}
|
|
1866
|
+
if (filters) {
|
|
1867
|
+
let shouldSkip = false;
|
|
1868
|
+
for (const [key2, value] of Object.entries(filters)) {
|
|
1869
|
+
if (data[key2] !== value) {
|
|
1870
|
+
shouldSkip = true;
|
|
1871
|
+
break;
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
if (shouldSkip) continue;
|
|
1875
|
+
}
|
|
1876
|
+
traces.push(data);
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
this.logger.error("Failed to parse trace:", { key, error: err });
|
|
1879
|
+
}
|
|
845
1880
|
}
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
1881
|
+
traces.sort((a, b) => {
|
|
1882
|
+
const aTime = new Date(a.createdAt || 0).getTime();
|
|
1883
|
+
const bTime = new Date(b.createdAt || 0).getTime();
|
|
1884
|
+
return bTime - aTime;
|
|
1885
|
+
});
|
|
1886
|
+
const total = traces.length;
|
|
1887
|
+
const start = page * perPage;
|
|
1888
|
+
const end = start + perPage;
|
|
1889
|
+
const pagedTraces = traces.slice(start, end);
|
|
1890
|
+
return {
|
|
1891
|
+
traces: pagedTraces,
|
|
1892
|
+
total,
|
|
1893
|
+
page,
|
|
1894
|
+
perPage,
|
|
1895
|
+
hasMore: end < total
|
|
1896
|
+
};
|
|
850
1897
|
} catch (error) {
|
|
851
|
-
const
|
|
852
|
-
|
|
853
|
-
|
|
1898
|
+
const mastraError = new MastraError(
|
|
1899
|
+
{
|
|
1900
|
+
id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
|
|
1901
|
+
domain: ErrorDomain.STORAGE,
|
|
1902
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1903
|
+
text: "Error getting traces with pagination"
|
|
1904
|
+
},
|
|
1905
|
+
error
|
|
1906
|
+
);
|
|
1907
|
+
this.logger.trackException?.(mastraError);
|
|
1908
|
+
this.logger.error(mastraError.toString());
|
|
1909
|
+
return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
|
|
854
1910
|
}
|
|
855
1911
|
}
|
|
1912
|
+
async batchTraceInsert({ records }) {
|
|
1913
|
+
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
1914
|
+
await this.operations.batchInsert({
|
|
1915
|
+
tableName: TABLE_TRACES,
|
|
1916
|
+
records
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
};
|
|
1920
|
+
var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
|
|
1921
|
+
operations;
|
|
1922
|
+
constructor({ operations }) {
|
|
1923
|
+
super();
|
|
1924
|
+
this.operations = operations;
|
|
1925
|
+
}
|
|
856
1926
|
validateWorkflowParams(params) {
|
|
857
|
-
const {
|
|
858
|
-
if (!
|
|
1927
|
+
const { workflowName, runId } = params;
|
|
1928
|
+
if (!workflowName || !runId) {
|
|
859
1929
|
throw new Error("Invalid workflow snapshot parameters");
|
|
860
1930
|
}
|
|
861
1931
|
}
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
normalizedSteps[stepId] = {
|
|
871
|
-
status: step.status,
|
|
872
|
-
payload: step.payload || step.result,
|
|
873
|
-
error: step.error
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
return normalizedSteps;
|
|
1932
|
+
updateWorkflowResults({
|
|
1933
|
+
// workflowName,
|
|
1934
|
+
// runId,
|
|
1935
|
+
// stepId,
|
|
1936
|
+
// result,
|
|
1937
|
+
// runtimeContext,
|
|
1938
|
+
}) {
|
|
1939
|
+
throw new Error("Method not implemented.");
|
|
877
1940
|
}
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
steps: this.normalizeSteps(steps),
|
|
885
|
-
triggerData: data.context?.triggerData || {},
|
|
886
|
-
attempts: data.context?.attempts || {}
|
|
887
|
-
},
|
|
888
|
-
suspendedPaths: data.suspendedPaths || {},
|
|
889
|
-
activePaths: data.activePaths || [],
|
|
890
|
-
timestamp: data.timestamp || Date.now()
|
|
891
|
-
};
|
|
1941
|
+
updateWorkflowState({
|
|
1942
|
+
// workflowName,
|
|
1943
|
+
// runId,
|
|
1944
|
+
// opts,
|
|
1945
|
+
}) {
|
|
1946
|
+
throw new Error("Method not implemented.");
|
|
892
1947
|
}
|
|
893
1948
|
async persistWorkflowSnapshot(params) {
|
|
894
1949
|
try {
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
const normalizedState = this.normalizeWorkflowState(snapshot);
|
|
898
|
-
this.validateWorkflowState(normalizedState);
|
|
899
|
-
await this.insert({
|
|
1950
|
+
const { workflowName, runId, snapshot } = params;
|
|
1951
|
+
await this.operations.putKV({
|
|
900
1952
|
tableName: TABLE_WORKFLOW_SNAPSHOT,
|
|
901
|
-
|
|
902
|
-
|
|
1953
|
+
key: this.operations.getKey(TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId }),
|
|
1954
|
+
value: {
|
|
903
1955
|
workflow_name: workflowName,
|
|
904
1956
|
run_id: runId,
|
|
905
|
-
snapshot:
|
|
1957
|
+
snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
|
|
906
1958
|
createdAt: /* @__PURE__ */ new Date(),
|
|
907
1959
|
updatedAt: /* @__PURE__ */ new Date()
|
|
908
1960
|
}
|
|
909
1961
|
});
|
|
910
1962
|
} catch (error) {
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1963
|
+
throw new MastraError(
|
|
1964
|
+
{
|
|
1965
|
+
id: "CLOUDFLARE_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
1966
|
+
domain: ErrorDomain.STORAGE,
|
|
1967
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1968
|
+
text: `Error persisting workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
|
|
1969
|
+
details: {
|
|
1970
|
+
workflowName: params.workflowName,
|
|
1971
|
+
runId: params.runId
|
|
1972
|
+
}
|
|
1973
|
+
},
|
|
1974
|
+
error
|
|
1975
|
+
);
|
|
914
1976
|
}
|
|
915
1977
|
}
|
|
916
1978
|
async loadWorkflowSnapshot(params) {
|
|
917
1979
|
try {
|
|
918
1980
|
this.validateWorkflowParams(params);
|
|
919
|
-
const {
|
|
920
|
-
const key = this.getKey(TABLE_WORKFLOW_SNAPSHOT, {
|
|
921
|
-
const data = await this.getKV(TABLE_WORKFLOW_SNAPSHOT, key);
|
|
1981
|
+
const { workflowName, runId } = params;
|
|
1982
|
+
const key = this.operations.getKey(TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
|
|
1983
|
+
const data = await this.operations.getKV(TABLE_WORKFLOW_SNAPSHOT, key);
|
|
922
1984
|
if (!data) return null;
|
|
923
|
-
const
|
|
924
|
-
|
|
925
|
-
return state;
|
|
926
|
-
} catch (error) {
|
|
927
|
-
this.logger.error("Error loading workflow snapshot:", {
|
|
928
|
-
error: error instanceof Error ? error.message : String(error)
|
|
929
|
-
});
|
|
930
|
-
return null;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
async batchInsert(input) {
|
|
934
|
-
if (!input.records || input.records.length === 0) return;
|
|
935
|
-
try {
|
|
936
|
-
await Promise.all(
|
|
937
|
-
input.records.map(async (record) => {
|
|
938
|
-
const key = this.getKey(input.tableName, record);
|
|
939
|
-
const processedRecord = {
|
|
940
|
-
...record,
|
|
941
|
-
createdAt: record.createdAt ? this.serializeDate(record.createdAt) : void 0,
|
|
942
|
-
updatedAt: record.updatedAt ? this.serializeDate(record.updatedAt) : void 0,
|
|
943
|
-
metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
|
|
944
|
-
};
|
|
945
|
-
await this.putKV({ tableName: input.tableName, key, value: processedRecord });
|
|
946
|
-
})
|
|
947
|
-
);
|
|
1985
|
+
const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
|
|
1986
|
+
return snapshotData;
|
|
948
1987
|
} catch (error) {
|
|
949
|
-
const
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
toDate
|
|
962
|
-
}) {
|
|
963
|
-
try {
|
|
964
|
-
let keys;
|
|
965
|
-
if (this.bindings) {
|
|
966
|
-
keys = (await this.listKV(TABLE_TRACES))?.map((k) => k.name) || [];
|
|
967
|
-
} else {
|
|
968
|
-
const namespaceId = await this.getNamespaceId(TABLE_TRACES);
|
|
969
|
-
const result = await this.client.kv.namespaces.keys.list(namespaceId, {
|
|
970
|
-
prefix: "",
|
|
971
|
-
limit: 1e3,
|
|
972
|
-
account_id: this.accountId
|
|
973
|
-
});
|
|
974
|
-
keys = result.result?.map((k) => k.name) || [];
|
|
975
|
-
}
|
|
976
|
-
const traceRecords = await Promise.all(
|
|
977
|
-
keys.map(async (key) => {
|
|
978
|
-
const record = await this.getKV(TABLE_TRACES, key);
|
|
979
|
-
if (!record) return null;
|
|
980
|
-
return record;
|
|
981
|
-
})
|
|
982
|
-
);
|
|
983
|
-
let filteredTraces = traceRecords.filter(
|
|
984
|
-
(record) => record !== null && typeof record === "object"
|
|
1988
|
+
const mastraError = new MastraError(
|
|
1989
|
+
{
|
|
1990
|
+
id: "CLOUDFLARE_STORAGE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
1991
|
+
domain: ErrorDomain.STORAGE,
|
|
1992
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
1993
|
+
text: `Error loading workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
|
|
1994
|
+
details: {
|
|
1995
|
+
workflowName: params.workflowName,
|
|
1996
|
+
runId: params.runId
|
|
1997
|
+
}
|
|
1998
|
+
},
|
|
1999
|
+
error
|
|
985
2000
|
);
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
if (scope) {
|
|
990
|
-
filteredTraces = filteredTraces.filter((record) => record.scope === scope);
|
|
991
|
-
}
|
|
992
|
-
if (attributes) {
|
|
993
|
-
filteredTraces = filteredTraces.filter((record) => {
|
|
994
|
-
if (!record.attributes) return false;
|
|
995
|
-
const recordAttrs = this.parseJSON(record.attributes);
|
|
996
|
-
if (!recordAttrs) return false;
|
|
997
|
-
return Object.entries(attributes).every(([key, value]) => recordAttrs[key] === value);
|
|
998
|
-
});
|
|
999
|
-
}
|
|
1000
|
-
if (fromDate) {
|
|
1001
|
-
filteredTraces = filteredTraces.filter((record) => new Date(record.createdAt).getTime() >= fromDate.getTime());
|
|
1002
|
-
}
|
|
1003
|
-
if (toDate) {
|
|
1004
|
-
filteredTraces = filteredTraces.filter((record) => new Date(record.createdAt).getTime() <= toDate.getTime());
|
|
1005
|
-
}
|
|
1006
|
-
filteredTraces.sort((a, b) => {
|
|
1007
|
-
const dateA = new Date(a.createdAt).getTime();
|
|
1008
|
-
const dateB = new Date(b.createdAt).getTime();
|
|
1009
|
-
return dateB - dateA;
|
|
1010
|
-
});
|
|
1011
|
-
const start = page * perPage;
|
|
1012
|
-
const end = start + perPage;
|
|
1013
|
-
const paginatedTraces = filteredTraces.slice(start, end);
|
|
1014
|
-
return paginatedTraces.map((record) => ({
|
|
1015
|
-
id: record.id,
|
|
1016
|
-
parentSpanId: record.parentSpanId,
|
|
1017
|
-
traceId: record.traceId,
|
|
1018
|
-
name: record.name,
|
|
1019
|
-
scope: record.scope,
|
|
1020
|
-
kind: record.kind,
|
|
1021
|
-
status: this.parseJSON(record.status),
|
|
1022
|
-
events: this.parseJSON(record.events) || [],
|
|
1023
|
-
links: this.parseJSON(record.links) || [],
|
|
1024
|
-
attributes: this.parseJSON(record?.attributes) || {},
|
|
1025
|
-
startTime: record.startTime,
|
|
1026
|
-
endTime: record.endTime,
|
|
1027
|
-
other: this.parseJSON(record.other) || {},
|
|
1028
|
-
createdAt: record.createdAt
|
|
1029
|
-
}));
|
|
1030
|
-
} catch (error) {
|
|
1031
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1032
|
-
this.logger.error("Failed to get traces:", { message });
|
|
1033
|
-
return [];
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
parseJSON(value) {
|
|
1037
|
-
if (typeof value === "string") {
|
|
1038
|
-
try {
|
|
1039
|
-
return JSON.parse(value);
|
|
1040
|
-
} catch {
|
|
1041
|
-
return value;
|
|
1042
|
-
}
|
|
2001
|
+
this.logger.trackException?.(mastraError);
|
|
2002
|
+
this.logger.error(mastraError.toString());
|
|
2003
|
+
return null;
|
|
1043
2004
|
}
|
|
1044
|
-
return value;
|
|
1045
|
-
}
|
|
1046
|
-
getEvalsByAgentName(_agentName, _type) {
|
|
1047
|
-
throw new Error("Method not implemented.");
|
|
1048
2005
|
}
|
|
1049
2006
|
parseWorkflowRun(row) {
|
|
1050
2007
|
let parsedSnapshot = row.snapshot;
|
|
@@ -1059,28 +2016,24 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
1059
2016
|
workflowName: row.workflow_name,
|
|
1060
2017
|
runId: row.run_id,
|
|
1061
2018
|
snapshot: parsedSnapshot,
|
|
1062
|
-
createdAt:
|
|
1063
|
-
updatedAt:
|
|
2019
|
+
createdAt: ensureDate(row.createdAt),
|
|
2020
|
+
updatedAt: ensureDate(row.updatedAt),
|
|
1064
2021
|
resourceId: row.resourceId
|
|
1065
2022
|
};
|
|
1066
2023
|
}
|
|
1067
2024
|
buildWorkflowSnapshotPrefix({
|
|
1068
|
-
namespace,
|
|
1069
2025
|
workflowName,
|
|
1070
2026
|
runId,
|
|
1071
2027
|
resourceId
|
|
1072
2028
|
}) {
|
|
1073
|
-
const prefix = this.namespacePrefix ? `${this.namespacePrefix}:` : "";
|
|
2029
|
+
const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
|
|
1074
2030
|
let key = `${prefix}${TABLE_WORKFLOW_SNAPSHOT}`;
|
|
1075
|
-
if (namespace) key += `:${namespace}`;
|
|
1076
2031
|
if (workflowName) key += `:${workflowName}`;
|
|
1077
2032
|
if (runId) key += `:${runId}`;
|
|
1078
2033
|
if (resourceId) key += `:${resourceId}`;
|
|
1079
|
-
if (!resourceId && (runId || workflowName || namespace)) key += ":";
|
|
1080
2034
|
return key;
|
|
1081
2035
|
}
|
|
1082
2036
|
async getWorkflowRuns({
|
|
1083
|
-
namespace,
|
|
1084
2037
|
workflowName,
|
|
1085
2038
|
limit = 20,
|
|
1086
2039
|
offset = 0,
|
|
@@ -1089,28 +2042,32 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
1089
2042
|
toDate
|
|
1090
2043
|
} = {}) {
|
|
1091
2044
|
try {
|
|
1092
|
-
const prefix = this.buildWorkflowSnapshotPrefix({
|
|
1093
|
-
const keyObjs = await this.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
|
|
2045
|
+
const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
|
|
2046
|
+
const keyObjs = await this.operations.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
|
|
1094
2047
|
const runs = [];
|
|
1095
2048
|
for (const { name: key } of keyObjs) {
|
|
1096
2049
|
const parts = key.split(":");
|
|
1097
2050
|
const idx = parts.indexOf(TABLE_WORKFLOW_SNAPSHOT);
|
|
1098
|
-
if (idx === -1 || parts.length < idx +
|
|
1099
|
-
const
|
|
1100
|
-
const
|
|
1101
|
-
|
|
1102
|
-
if (
|
|
1103
|
-
|
|
1104
|
-
const data = await this.getKV(TABLE_WORKFLOW_SNAPSHOT, key);
|
|
2051
|
+
if (idx === -1 || parts.length < idx + 3) continue;
|
|
2052
|
+
const wfName = parts[idx + 1];
|
|
2053
|
+
const keyResourceId = parts.length > idx + 3 ? parts[idx + 3] : void 0;
|
|
2054
|
+
if (workflowName && wfName !== workflowName) continue;
|
|
2055
|
+
if (resourceId && keyResourceId !== resourceId) continue;
|
|
2056
|
+
const data = await this.operations.getKV(TABLE_WORKFLOW_SNAPSHOT, key);
|
|
1105
2057
|
if (!data) continue;
|
|
1106
2058
|
try {
|
|
1107
|
-
if (resourceId &&
|
|
1108
|
-
const createdAt =
|
|
2059
|
+
if (resourceId && !keyResourceId) continue;
|
|
2060
|
+
const createdAt = ensureDate(data.createdAt);
|
|
1109
2061
|
if (fromDate && createdAt && createdAt < fromDate) continue;
|
|
1110
2062
|
if (toDate && createdAt && createdAt > toDate) continue;
|
|
1111
|
-
const
|
|
1112
|
-
|
|
1113
|
-
const run = this.parseWorkflowRun({
|
|
2063
|
+
const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
|
|
2064
|
+
const resourceIdToUse = keyResourceId || data.resourceId;
|
|
2065
|
+
const run = this.parseWorkflowRun({
|
|
2066
|
+
...data,
|
|
2067
|
+
workflow_name: wfName,
|
|
2068
|
+
resourceId: resourceIdToUse,
|
|
2069
|
+
snapshot: snapshotData
|
|
2070
|
+
});
|
|
1114
2071
|
runs.push(run);
|
|
1115
2072
|
} catch (err) {
|
|
1116
2073
|
this.logger.error("Failed to parse workflow snapshot:", { key, error: err });
|
|
@@ -1127,37 +2084,354 @@ var CloudflareStore = class extends MastraStorage {
|
|
|
1127
2084
|
total: runs.length
|
|
1128
2085
|
};
|
|
1129
2086
|
} catch (error) {
|
|
1130
|
-
const
|
|
1131
|
-
|
|
2087
|
+
const mastraError = new MastraError(
|
|
2088
|
+
{
|
|
2089
|
+
id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
|
|
2090
|
+
domain: ErrorDomain.STORAGE,
|
|
2091
|
+
category: ErrorCategory.THIRD_PARTY
|
|
2092
|
+
},
|
|
2093
|
+
error
|
|
2094
|
+
);
|
|
2095
|
+
this.logger.trackException?.(mastraError);
|
|
2096
|
+
this.logger.error(mastraError.toString());
|
|
1132
2097
|
return { runs: [], total: 0 };
|
|
1133
2098
|
}
|
|
1134
2099
|
}
|
|
1135
2100
|
async getWorkflowRunById({
|
|
1136
|
-
namespace,
|
|
1137
2101
|
runId,
|
|
1138
2102
|
workflowName
|
|
1139
2103
|
}) {
|
|
1140
2104
|
try {
|
|
1141
|
-
if (!runId || !workflowName
|
|
1142
|
-
throw new Error("runId, workflowName,
|
|
2105
|
+
if (!runId || !workflowName) {
|
|
2106
|
+
throw new Error("runId, workflowName, are required");
|
|
1143
2107
|
}
|
|
1144
|
-
const prefix = this.buildWorkflowSnapshotPrefix({
|
|
1145
|
-
const keyObjs = await this.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
|
|
2108
|
+
const prefix = this.buildWorkflowSnapshotPrefix({ workflowName, runId });
|
|
2109
|
+
const keyObjs = await this.operations.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
|
|
1146
2110
|
if (!keyObjs.length) return null;
|
|
1147
|
-
const
|
|
1148
|
-
|
|
2111
|
+
const exactKey = keyObjs.find((k) => {
|
|
2112
|
+
const parts = k.name.split(":");
|
|
2113
|
+
const idx = parts.indexOf(TABLE_WORKFLOW_SNAPSHOT);
|
|
2114
|
+
if (idx === -1 || parts.length < idx + 3) return false;
|
|
2115
|
+
const wfName = parts[idx + 1];
|
|
2116
|
+
const rId = parts[idx + 2];
|
|
2117
|
+
return wfName === workflowName && rId === runId;
|
|
2118
|
+
});
|
|
2119
|
+
if (!exactKey) return null;
|
|
2120
|
+
const data = await this.operations.getKV(TABLE_WORKFLOW_SNAPSHOT, exactKey.name);
|
|
1149
2121
|
if (!data) return null;
|
|
1150
|
-
const
|
|
1151
|
-
this.
|
|
1152
|
-
return this.parseWorkflowRun({ ...data, snapshot: state });
|
|
2122
|
+
const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
|
|
2123
|
+
return this.parseWorkflowRun({ ...data, snapshot: snapshotData });
|
|
1153
2124
|
} catch (error) {
|
|
1154
|
-
const
|
|
1155
|
-
|
|
2125
|
+
const mastraError = new MastraError(
|
|
2126
|
+
{
|
|
2127
|
+
id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
2128
|
+
domain: ErrorDomain.STORAGE,
|
|
2129
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
2130
|
+
details: {
|
|
2131
|
+
workflowName,
|
|
2132
|
+
runId
|
|
2133
|
+
}
|
|
2134
|
+
},
|
|
2135
|
+
error
|
|
2136
|
+
);
|
|
2137
|
+
this.logger.trackException?.(mastraError);
|
|
2138
|
+
this.logger.error(mastraError.toString());
|
|
1156
2139
|
return null;
|
|
1157
2140
|
}
|
|
1158
2141
|
}
|
|
2142
|
+
};
|
|
2143
|
+
|
|
2144
|
+
// src/storage/types.ts
|
|
2145
|
+
function isWorkersConfig(config) {
|
|
2146
|
+
return "bindings" in config;
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
// src/storage/index.ts
|
|
2150
|
+
var CloudflareStore = class extends MastraStorage {
|
|
2151
|
+
stores;
|
|
2152
|
+
client;
|
|
2153
|
+
accountId;
|
|
2154
|
+
namespacePrefix;
|
|
2155
|
+
bindings;
|
|
2156
|
+
validateWorkersConfig(config) {
|
|
2157
|
+
if (!isWorkersConfig(config)) {
|
|
2158
|
+
throw new Error("Invalid Workers API configuration");
|
|
2159
|
+
}
|
|
2160
|
+
if (!config.bindings) {
|
|
2161
|
+
throw new Error("KV bindings are required when using Workers Binding API");
|
|
2162
|
+
}
|
|
2163
|
+
const requiredTables = [
|
|
2164
|
+
TABLE_THREADS,
|
|
2165
|
+
TABLE_MESSAGES,
|
|
2166
|
+
TABLE_WORKFLOW_SNAPSHOT,
|
|
2167
|
+
TABLE_EVALS,
|
|
2168
|
+
TABLE_SCORERS,
|
|
2169
|
+
TABLE_TRACES
|
|
2170
|
+
];
|
|
2171
|
+
for (const table of requiredTables) {
|
|
2172
|
+
if (!(table in config.bindings)) {
|
|
2173
|
+
throw new Error(`Missing KV binding for table: ${table}`);
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
validateRestConfig(config) {
|
|
2178
|
+
if (isWorkersConfig(config)) {
|
|
2179
|
+
throw new Error("Invalid REST API configuration");
|
|
2180
|
+
}
|
|
2181
|
+
if (!config.accountId?.trim()) {
|
|
2182
|
+
throw new Error("accountId is required for REST API");
|
|
2183
|
+
}
|
|
2184
|
+
if (!config.apiToken?.trim()) {
|
|
2185
|
+
throw new Error("apiToken is required for REST API");
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
constructor(config) {
|
|
2189
|
+
super({ name: "Cloudflare" });
|
|
2190
|
+
try {
|
|
2191
|
+
if (isWorkersConfig(config)) {
|
|
2192
|
+
this.validateWorkersConfig(config);
|
|
2193
|
+
this.bindings = config.bindings;
|
|
2194
|
+
this.namespacePrefix = config.keyPrefix?.trim() || "";
|
|
2195
|
+
this.logger.info("Using Cloudflare KV Workers Binding API");
|
|
2196
|
+
} else {
|
|
2197
|
+
this.validateRestConfig(config);
|
|
2198
|
+
this.accountId = config.accountId.trim();
|
|
2199
|
+
this.namespacePrefix = config.namespacePrefix?.trim() || "";
|
|
2200
|
+
this.client = new Cloudflare({
|
|
2201
|
+
apiToken: config.apiToken.trim()
|
|
2202
|
+
});
|
|
2203
|
+
this.logger.info("Using Cloudflare KV REST API");
|
|
2204
|
+
}
|
|
2205
|
+
const operations = new StoreOperationsCloudflare({
|
|
2206
|
+
accountId: this.accountId,
|
|
2207
|
+
client: this.client,
|
|
2208
|
+
namespacePrefix: this.namespacePrefix,
|
|
2209
|
+
bindings: this.bindings
|
|
2210
|
+
});
|
|
2211
|
+
const legacyEvals = new LegacyEvalsStorageCloudflare({
|
|
2212
|
+
operations
|
|
2213
|
+
});
|
|
2214
|
+
const workflows = new WorkflowsStorageCloudflare({
|
|
2215
|
+
operations
|
|
2216
|
+
});
|
|
2217
|
+
const traces = new TracesStorageCloudflare({
|
|
2218
|
+
operations
|
|
2219
|
+
});
|
|
2220
|
+
const memory = new MemoryStorageCloudflare({
|
|
2221
|
+
operations
|
|
2222
|
+
});
|
|
2223
|
+
const scores = new ScoresStorageCloudflare({
|
|
2224
|
+
operations
|
|
2225
|
+
});
|
|
2226
|
+
this.stores = {
|
|
2227
|
+
operations,
|
|
2228
|
+
legacyEvals,
|
|
2229
|
+
workflows,
|
|
2230
|
+
traces,
|
|
2231
|
+
memory,
|
|
2232
|
+
scores
|
|
2233
|
+
};
|
|
2234
|
+
} catch (error) {
|
|
2235
|
+
throw new MastraError(
|
|
2236
|
+
{
|
|
2237
|
+
id: "CLOUDFLARE_STORAGE_INIT_FAILED",
|
|
2238
|
+
domain: ErrorDomain.STORAGE,
|
|
2239
|
+
category: ErrorCategory.THIRD_PARTY
|
|
2240
|
+
},
|
|
2241
|
+
error
|
|
2242
|
+
);
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
async createTable({
|
|
2246
|
+
tableName,
|
|
2247
|
+
schema
|
|
2248
|
+
}) {
|
|
2249
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
2250
|
+
}
|
|
2251
|
+
async alterTable(_args) {
|
|
2252
|
+
return this.stores.operations.alterTable(_args);
|
|
2253
|
+
}
|
|
2254
|
+
async clearTable({ tableName }) {
|
|
2255
|
+
return this.stores.operations.clearTable({ tableName });
|
|
2256
|
+
}
|
|
2257
|
+
async dropTable({ tableName }) {
|
|
2258
|
+
return this.stores.operations.dropTable({ tableName });
|
|
2259
|
+
}
|
|
2260
|
+
async insert({
|
|
2261
|
+
tableName,
|
|
2262
|
+
record
|
|
2263
|
+
}) {
|
|
2264
|
+
return this.stores.operations.insert({ tableName, record });
|
|
2265
|
+
}
|
|
2266
|
+
async load({ tableName, keys }) {
|
|
2267
|
+
return this.stores.operations.load({ tableName, keys });
|
|
2268
|
+
}
|
|
2269
|
+
async getThreadById({ threadId }) {
|
|
2270
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
2271
|
+
}
|
|
2272
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
2273
|
+
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2274
|
+
}
|
|
2275
|
+
async saveThread({ thread }) {
|
|
2276
|
+
return this.stores.memory.saveThread({ thread });
|
|
2277
|
+
}
|
|
2278
|
+
async updateThread({
|
|
2279
|
+
id,
|
|
2280
|
+
title,
|
|
2281
|
+
metadata
|
|
2282
|
+
}) {
|
|
2283
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
2284
|
+
}
|
|
2285
|
+
async deleteThread({ threadId }) {
|
|
2286
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
2287
|
+
}
|
|
2288
|
+
async saveMessages(args) {
|
|
2289
|
+
return this.stores.memory.saveMessages(args);
|
|
2290
|
+
}
|
|
2291
|
+
async getMessages({
|
|
2292
|
+
threadId,
|
|
2293
|
+
resourceId,
|
|
2294
|
+
selectBy,
|
|
2295
|
+
format
|
|
2296
|
+
}) {
|
|
2297
|
+
return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
|
|
2298
|
+
}
|
|
2299
|
+
async updateWorkflowResults({
|
|
2300
|
+
workflowName,
|
|
2301
|
+
runId,
|
|
2302
|
+
stepId,
|
|
2303
|
+
result,
|
|
2304
|
+
runtimeContext
|
|
2305
|
+
}) {
|
|
2306
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
|
|
2307
|
+
}
|
|
2308
|
+
async updateWorkflowState({
|
|
2309
|
+
workflowName,
|
|
2310
|
+
runId,
|
|
2311
|
+
opts
|
|
2312
|
+
}) {
|
|
2313
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
2314
|
+
}
|
|
2315
|
+
async getMessagesById({
|
|
2316
|
+
messageIds,
|
|
2317
|
+
format
|
|
2318
|
+
}) {
|
|
2319
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2320
|
+
}
|
|
2321
|
+
async persistWorkflowSnapshot(params) {
|
|
2322
|
+
return this.stores.workflows.persistWorkflowSnapshot(params);
|
|
2323
|
+
}
|
|
2324
|
+
async loadWorkflowSnapshot(params) {
|
|
2325
|
+
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2326
|
+
}
|
|
2327
|
+
async batchInsert(input) {
|
|
2328
|
+
return this.stores.operations.batchInsert(input);
|
|
2329
|
+
}
|
|
2330
|
+
async getTraces({
|
|
2331
|
+
name,
|
|
2332
|
+
scope,
|
|
2333
|
+
page = 0,
|
|
2334
|
+
perPage = 100,
|
|
2335
|
+
attributes,
|
|
2336
|
+
fromDate,
|
|
2337
|
+
toDate
|
|
2338
|
+
}) {
|
|
2339
|
+
return this.stores.traces.getTraces({
|
|
2340
|
+
name,
|
|
2341
|
+
scope,
|
|
2342
|
+
page,
|
|
2343
|
+
perPage,
|
|
2344
|
+
attributes,
|
|
2345
|
+
fromDate,
|
|
2346
|
+
toDate
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
async getEvalsByAgentName(agentName, type) {
|
|
2350
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2351
|
+
}
|
|
2352
|
+
async getEvals(options) {
|
|
2353
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
2354
|
+
}
|
|
2355
|
+
async getWorkflowRuns({
|
|
2356
|
+
workflowName,
|
|
2357
|
+
limit = 20,
|
|
2358
|
+
offset = 0,
|
|
2359
|
+
resourceId,
|
|
2360
|
+
fromDate,
|
|
2361
|
+
toDate
|
|
2362
|
+
} = {}) {
|
|
2363
|
+
return this.stores.workflows.getWorkflowRuns({
|
|
2364
|
+
workflowName,
|
|
2365
|
+
limit,
|
|
2366
|
+
offset,
|
|
2367
|
+
resourceId,
|
|
2368
|
+
fromDate,
|
|
2369
|
+
toDate
|
|
2370
|
+
});
|
|
2371
|
+
}
|
|
2372
|
+
async getWorkflowRunById({
|
|
2373
|
+
runId,
|
|
2374
|
+
workflowName
|
|
2375
|
+
}) {
|
|
2376
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
2377
|
+
}
|
|
2378
|
+
async getTracesPaginated(args) {
|
|
2379
|
+
return this.stores.traces.getTracesPaginated(args);
|
|
2380
|
+
}
|
|
2381
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
2382
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2383
|
+
}
|
|
2384
|
+
async getMessagesPaginated(args) {
|
|
2385
|
+
return this.stores.memory.getMessagesPaginated(args);
|
|
2386
|
+
}
|
|
2387
|
+
async updateMessages(args) {
|
|
2388
|
+
return this.stores.memory.updateMessages(args);
|
|
2389
|
+
}
|
|
2390
|
+
async getScoreById({ id }) {
|
|
2391
|
+
return this.stores.scores.getScoreById({ id });
|
|
2392
|
+
}
|
|
2393
|
+
async saveScore(score) {
|
|
2394
|
+
return this.stores.scores.saveScore(score);
|
|
2395
|
+
}
|
|
2396
|
+
async getScoresByRunId({
|
|
2397
|
+
runId,
|
|
2398
|
+
pagination
|
|
2399
|
+
}) {
|
|
2400
|
+
return this.stores.scores.getScoresByRunId({ runId, pagination });
|
|
2401
|
+
}
|
|
2402
|
+
async getScoresByEntityId({
|
|
2403
|
+
entityId,
|
|
2404
|
+
entityType,
|
|
2405
|
+
pagination
|
|
2406
|
+
}) {
|
|
2407
|
+
return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
|
|
2408
|
+
}
|
|
2409
|
+
async getScoresByScorerId({
|
|
2410
|
+
scorerId,
|
|
2411
|
+
entityId,
|
|
2412
|
+
entityType,
|
|
2413
|
+
source,
|
|
2414
|
+
pagination
|
|
2415
|
+
}) {
|
|
2416
|
+
return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
|
|
2417
|
+
}
|
|
2418
|
+
async getResourceById({ resourceId }) {
|
|
2419
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
2420
|
+
}
|
|
2421
|
+
async saveResource({ resource }) {
|
|
2422
|
+
return this.stores.memory.saveResource({ resource });
|
|
2423
|
+
}
|
|
2424
|
+
async updateResource({
|
|
2425
|
+
resourceId,
|
|
2426
|
+
workingMemory,
|
|
2427
|
+
metadata
|
|
2428
|
+
}) {
|
|
2429
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
2430
|
+
}
|
|
1159
2431
|
async close() {
|
|
1160
2432
|
}
|
|
1161
2433
|
};
|
|
1162
2434
|
|
|
1163
2435
|
export { CloudflareStore };
|
|
2436
|
+
//# sourceMappingURL=index.js.map
|
|
2437
|
+
//# sourceMappingURL=index.js.map
|