@mastra/core 0.9.4 → 0.10.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +3 -2
  2. package/dist/agent/index.cjs +2 -2
  3. package/dist/agent/index.d.cts +13 -14
  4. package/dist/agent/index.d.ts +13 -14
  5. package/dist/agent/index.js +1 -1
  6. package/dist/{base-BCfssGt6.d.ts → base-DttB7sJD.d.ts} +1187 -886
  7. package/dist/{base-CAEcd6q2.d.cts → base-aJ3etsh5.d.cts} +1187 -886
  8. package/dist/{base-H7siSAfu.d.cts → base-aPYtPBT2.d.cts} +3 -3
  9. package/dist/{base-4Z34GQL8.d.ts → base-tc5kgDTD.d.ts} +3 -3
  10. package/dist/base.cjs +2 -2
  11. package/dist/base.d.cts +2 -3
  12. package/dist/base.d.ts +2 -3
  13. package/dist/base.js +1 -1
  14. package/dist/bundler/index.cjs +2 -2
  15. package/dist/bundler/index.d.cts +2 -3
  16. package/dist/bundler/index.d.ts +2 -3
  17. package/dist/bundler/index.js +1 -1
  18. package/dist/{chunk-W4BSLENO.js → chunk-2NTUAUGH.js} +1 -1
  19. package/dist/{chunk-S34QVMKE.js → chunk-2PW6UJMW.js} +77 -10
  20. package/dist/{chunk-WE36CRQV.cjs → chunk-2U7ZZUFO.cjs} +2 -2
  21. package/dist/{workflows/vNext/index.js → chunk-3SQ3G2EJ.js} +19 -16
  22. package/dist/chunk-5HULBQ2W.cjs +38 -0
  23. package/dist/{chunk-XRGDVLM4.cjs → chunk-5JRD3NDP.cjs} +15 -15
  24. package/dist/{chunk-GXKODTLA.cjs → chunk-5W2G7S44.cjs} +83 -68
  25. package/dist/chunk-75Z4BZEE.js +36 -0
  26. package/dist/{chunk-66GQROSI.cjs → chunk-AOGUTJUO.cjs} +58 -51
  27. package/dist/{chunk-WIKOYZ63.js → chunk-BPTSLJHA.js} +9 -9
  28. package/dist/{chunk-JBJ7KXN5.js → chunk-C3ICEF6E.js} +1 -1
  29. package/dist/{chunk-E4FAXBUV.cjs → chunk-CWSFP2HS.cjs} +2 -2
  30. package/dist/{chunk-FW5RS6WV.js → chunk-E7CLY6SK.js} +42 -35
  31. package/dist/{chunk-235X76GC.js → chunk-FI7R232B.js} +2 -2
  32. package/dist/chunk-GQ2XQ4UN.js +321 -0
  33. package/dist/{chunk-H4CEZSRM.js → chunk-J7GDGV6F.js} +1 -1
  34. package/dist/{chunk-NLBJOFNG.js → chunk-JW5TMK2L.js} +1 -1
  35. package/dist/{chunk-NOPY74PV.js → chunk-KJQFFEEQ.js} +1 -1
  36. package/dist/{chunk-V2Q2FEVO.cjs → chunk-KSPHQSZX.cjs} +2 -2
  37. package/dist/{chunk-NZV4OA6P.js → chunk-LHRZV5VG.js} +2 -23
  38. package/dist/chunk-NMDM4IZN.cjs +78 -0
  39. package/dist/chunk-OBEALYTK.js +74 -0
  40. package/dist/{chunk-PEK4TY3P.js → chunk-OCT2762Q.js} +1 -1
  41. package/dist/{chunk-5DUFC7TV.cjs → chunk-P7BGXOQV.cjs} +2 -2
  42. package/dist/{chunk-WQKOM7XM.cjs → chunk-PIZM25KI.cjs} +3 -24
  43. package/dist/{chunk-S7J63JOG.cjs → chunk-RVS6OUJN.cjs} +2 -2
  44. package/dist/{chunk-5JUWUTPJ.cjs → chunk-SKG2NIZW.cjs} +2 -2
  45. package/dist/chunk-SWW4EBUZ.cjs +96 -0
  46. package/dist/{chunk-RGE4UF6A.cjs → chunk-TMPFLJLG.cjs} +2 -2
  47. package/dist/{workflows/vNext/index.cjs → chunk-TTKQ37ZZ.cjs} +24 -21
  48. package/dist/{chunk-EJITEVAB.cjs → chunk-U3L3NEOM.cjs} +81 -10
  49. package/dist/chunk-VHLL4AZK.js +90 -0
  50. package/dist/{chunk-EG74VBSP.cjs → chunk-YEULQPUY.cjs} +6 -6
  51. package/dist/{chunk-SOLXHDNQ.js → chunk-ZB3LEHL2.js} +81 -66
  52. package/dist/{chunk-TAFOICHR.js → chunk-ZKN6HYYQ.js} +1 -1
  53. package/dist/chunk-ZZDAC5KD.cjs +325 -0
  54. package/dist/deployer/index.cjs +2 -2
  55. package/dist/deployer/index.d.cts +2 -3
  56. package/dist/deployer/index.d.ts +2 -3
  57. package/dist/deployer/index.js +1 -1
  58. package/dist/eval/index.d.cts +13 -14
  59. package/dist/eval/index.d.ts +13 -14
  60. package/dist/hooks/index.d.cts +1 -1
  61. package/dist/hooks/index.d.ts +1 -1
  62. package/dist/index.cjs +88 -159
  63. package/dist/index.d.cts +17 -25
  64. package/dist/index.d.ts +17 -25
  65. package/dist/index.js +18 -25
  66. package/dist/integration/index.cjs +3 -3
  67. package/dist/integration/index.d.cts +12 -13
  68. package/dist/integration/index.d.ts +12 -13
  69. package/dist/integration/index.js +1 -1
  70. package/dist/llm/index.d.cts +13 -14
  71. package/dist/llm/index.d.ts +13 -14
  72. package/dist/logger/index.cjs +18 -17
  73. package/dist/logger/index.d.cts +42 -2
  74. package/dist/logger/index.d.ts +42 -2
  75. package/dist/logger/index.js +2 -1
  76. package/dist/{index-QV27jkxQ.d.ts → logger-EhZkzZOr.d.cts} +38 -52
  77. package/dist/{index-QV27jkxQ.d.cts → logger-EhZkzZOr.d.ts} +38 -52
  78. package/dist/mastra/index.cjs +2 -2
  79. package/dist/mastra/index.d.cts +11 -12
  80. package/dist/mastra/index.d.ts +11 -12
  81. package/dist/mastra/index.js +1 -1
  82. package/dist/mcp/index.cjs +75 -17
  83. package/dist/mcp/index.d.cts +14 -15
  84. package/dist/mcp/index.d.ts +14 -15
  85. package/dist/mcp/index.js +69 -15
  86. package/dist/memory/index.cjs +4 -4
  87. package/dist/memory/index.d.cts +12 -13
  88. package/dist/memory/index.d.ts +12 -13
  89. package/dist/memory/index.js +1 -1
  90. package/dist/network/index.cjs +8 -8
  91. package/dist/network/index.d.cts +12 -13
  92. package/dist/network/index.d.ts +12 -13
  93. package/dist/network/index.js +5 -5
  94. package/dist/relevance/index.cjs +4 -4
  95. package/dist/relevance/index.d.cts +15 -16
  96. package/dist/relevance/index.d.ts +15 -16
  97. package/dist/relevance/index.js +1 -1
  98. package/dist/server/index.cjs +4 -0
  99. package/dist/server/index.d.cts +13 -12
  100. package/dist/server/index.d.ts +13 -12
  101. package/dist/server/index.js +4 -1
  102. package/dist/storage/index.cjs +184 -3
  103. package/dist/storage/index.d.cts +83 -13
  104. package/dist/storage/index.d.ts +83 -13
  105. package/dist/storage/index.js +186 -1
  106. package/dist/telemetry/index.d.cts +14 -15
  107. package/dist/telemetry/index.d.ts +14 -15
  108. package/dist/telemetry/otel-vendor.cjs +2 -2
  109. package/dist/telemetry/otel-vendor.d.cts +1 -1
  110. package/dist/telemetry/otel-vendor.d.ts +1 -1
  111. package/dist/telemetry/otel-vendor.js +1 -1
  112. package/dist/tools/index.cjs +4 -4
  113. package/dist/tools/index.d.cts +12 -13
  114. package/dist/tools/index.d.ts +12 -13
  115. package/dist/tools/index.js +1 -1
  116. package/dist/tts/index.cjs +2 -2
  117. package/dist/tts/index.d.cts +2 -3
  118. package/dist/tts/index.d.ts +2 -3
  119. package/dist/tts/index.js +1 -1
  120. package/dist/{types-BtMyV38I.d.ts → types-Bo1uigWx.d.cts} +1 -1
  121. package/dist/{types-BtMyV38I.d.cts → types-Bo1uigWx.d.ts} +1 -1
  122. package/dist/utils.cjs +28 -12
  123. package/dist/utils.d.cts +59 -16
  124. package/dist/utils.d.ts +59 -16
  125. package/dist/utils.js +1 -1
  126. package/dist/vector/filter/index.cjs +189 -7
  127. package/dist/vector/filter/index.js +190 -1
  128. package/dist/vector/index.cjs +2 -2
  129. package/dist/vector/index.d.cts +28 -20
  130. package/dist/vector/index.d.ts +28 -20
  131. package/dist/vector/index.js +1 -1
  132. package/dist/voice/index.cjs +4 -4
  133. package/dist/voice/index.d.cts +12 -13
  134. package/dist/voice/index.d.ts +12 -13
  135. package/dist/voice/index.js +1 -1
  136. package/dist/workflows/index.cjs +17 -69
  137. package/dist/workflows/index.d.cts +197 -77
  138. package/dist/workflows/index.d.ts +197 -77
  139. package/dist/workflows/index.js +1 -1
  140. package/dist/workflows/legacy/index.cjs +90 -0
  141. package/dist/workflows/legacy/index.d.cts +87 -0
  142. package/dist/workflows/legacy/index.d.ts +87 -0
  143. package/dist/workflows/legacy/index.js +1 -0
  144. package/package.json +19 -40
  145. package/workflows/legacy.d.ts +1 -0
  146. package/dist/chunk-4WABQORE.js +0 -781
  147. package/dist/chunk-CIEPFV6B.js +0 -658
  148. package/dist/chunk-CMPPXW4U.js +0 -154
  149. package/dist/chunk-CTKNWYK2.js +0 -131
  150. package/dist/chunk-LGERQTJM.js +0 -190
  151. package/dist/chunk-O44MSFMZ.cjs +0 -168
  152. package/dist/chunk-QDAMIZY3.cjs +0 -783
  153. package/dist/chunk-QHDPLMHB.cjs +0 -667
  154. package/dist/chunk-RAQBTCIR.cjs +0 -134
  155. package/dist/chunk-YK3XJ52U.cjs +0 -192
  156. package/dist/storage/libsql/index.cjs +0 -581
  157. package/dist/storage/libsql/index.d.cts +0 -104
  158. package/dist/storage/libsql/index.d.ts +0 -104
  159. package/dist/storage/libsql/index.js +0 -578
  160. package/dist/vector/libsql/index.cjs +0 -14
  161. package/dist/vector/libsql/index.d.cts +0 -82
  162. package/dist/vector/libsql/index.d.ts +0 -82
  163. package/dist/vector/libsql/index.js +0 -1
  164. package/dist/workflows/vNext/index.d.cts +0 -209
  165. package/dist/workflows/vNext/index.d.ts +0 -209
  166. package/storage/libsql.d.ts +0 -1
  167. package/vector/libsql.d.ts +0 -1
  168. package/workflows/vNext.d.ts +0 -1
@@ -1,104 +0,0 @@
1
- import { Config } from '@libsql/client';
2
- import { b as MastraStorage, T as TABLE_NAMES, S as StorageColumn, c as StorageThreadType, d as MessageType, e as StorageGetMessagesArg, E as EvalRow, W as WorkflowRuns, f as WorkflowRun } from '../../base-BCfssGt6.js';
3
- import 'ai';
4
- import '../../base-4Z34GQL8.js';
5
- import '@opentelemetry/api';
6
- import '../../index-QV27jkxQ.js';
7
- import 'stream';
8
- import 'pino';
9
- import '@opentelemetry/sdk-trace-base';
10
- import '../../types-BtMyV38I.js';
11
- import 'sift';
12
- import 'zod';
13
- import 'json-schema';
14
- import '../../runtime-context/index.js';
15
- import 'xstate';
16
- import 'node:events';
17
- import '../../vector/index.js';
18
- import '../../vector/filter/index.js';
19
- import '../../tts/index.js';
20
- import 'node:http';
21
- import 'hono';
22
- import 'events';
23
- import '../../deployer/index.js';
24
- import '../../bundler/index.js';
25
- import 'hono/cors';
26
- import 'hono-openapi';
27
- import 'ai/test';
28
-
29
- declare class LibSQLStore extends MastraStorage {
30
- private client;
31
- constructor({ config }: {
32
- config: Config;
33
- });
34
- protected rewriteDbUrl(url: string): string;
35
- private getCreateTableSQL;
36
- createTable({ tableName, schema, }: {
37
- tableName: TABLE_NAMES;
38
- schema: Record<string, StorageColumn>;
39
- }): Promise<void>;
40
- clearTable({ tableName }: {
41
- tableName: TABLE_NAMES;
42
- }): Promise<void>;
43
- private prepareStatement;
44
- insert({ tableName, record }: {
45
- tableName: TABLE_NAMES;
46
- record: Record<string, any>;
47
- }): Promise<void>;
48
- batchInsert({ tableName, records }: {
49
- tableName: TABLE_NAMES;
50
- records: Record<string, any>[];
51
- }): Promise<void>;
52
- load<R>({ tableName, keys }: {
53
- tableName: TABLE_NAMES;
54
- keys: Record<string, string>;
55
- }): Promise<R | null>;
56
- getThreadById({ threadId }: {
57
- threadId: string;
58
- }): Promise<StorageThreadType | null>;
59
- getThreadsByResourceId({ resourceId }: {
60
- resourceId: string;
61
- }): Promise<StorageThreadType[]>;
62
- saveThread({ thread }: {
63
- thread: StorageThreadType;
64
- }): Promise<StorageThreadType>;
65
- updateThread({ id, title, metadata, }: {
66
- id: string;
67
- title: string;
68
- metadata: Record<string, unknown>;
69
- }): Promise<StorageThreadType>;
70
- deleteThread({ threadId }: {
71
- threadId: string;
72
- }): Promise<void>;
73
- private parseRow;
74
- getMessages<T extends MessageType[]>({ threadId, selectBy }: StorageGetMessagesArg): Promise<T>;
75
- saveMessages({ messages }: {
76
- messages: MessageType[];
77
- }): Promise<MessageType[]>;
78
- private transformEvalRow;
79
- getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
80
- getTraces({ name, scope, page, perPage, attributes, filters, fromDate, toDate, }?: {
81
- name?: string;
82
- scope?: string;
83
- page: number;
84
- perPage: number;
85
- attributes?: Record<string, string>;
86
- filters?: Record<string, any>;
87
- fromDate?: Date;
88
- toDate?: Date;
89
- }): Promise<any[]>;
90
- getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, }?: {
91
- workflowName?: string;
92
- fromDate?: Date;
93
- toDate?: Date;
94
- limit?: number;
95
- offset?: number;
96
- }): Promise<WorkflowRuns>;
97
- getWorkflowRunById({ runId, workflowName, }: {
98
- runId: string;
99
- workflowName?: string;
100
- }): Promise<WorkflowRun | null>;
101
- private parseWorkflowRun;
102
- }
103
-
104
- export { LibSQLStore as DefaultStorage, LibSQLStore };
@@ -1,578 +0,0 @@
1
- import { MastraStorage } from '../../chunk-TAFOICHR.js';
2
- import { TABLE_WORKFLOW_SNAPSHOT, TABLE_THREADS, TABLE_MESSAGES, TABLE_EVALS, TABLE_TRACES } from '../../chunk-SEOWDGC2.js';
3
- import { isAbsolute, join, resolve } from 'node:path';
4
- import { createClient } from '@libsql/client';
5
-
6
- function safelyParseJSON(jsonString) {
7
- try {
8
- return JSON.parse(jsonString);
9
- } catch {
10
- return {};
11
- }
12
- }
13
- var hasWarned = false;
14
- function warnDeprecation(logger) {
15
- if (hasWarned) return;
16
- hasWarned = true;
17
- logger?.warn(`The default storage is deprecated, please add any storage to Mastra itself.
18
-
19
- In \`src/mastra/index.ts\` add:
20
- Import { LibSQLStore } from \`@mastra/libsql\`.
21
-
22
- export const mastra = new Mastra({
23
- // other config
24
- storage: new LibSQLStore({
25
- url: 'file:../mastra.db',
26
- }),
27
- }
28
- `);
29
- }
30
- var LibSQLStore = class extends MastraStorage {
31
- client;
32
- constructor({ config }) {
33
- super({ name: `LibSQLStore` });
34
- if (config.url === ":memory:" || config.url.startsWith("file::memory:")) {
35
- this.shouldCacheInit = false;
36
- }
37
- this.client = createClient({
38
- url: this.rewriteDbUrl(config.url),
39
- authToken: config.authToken
40
- });
41
- }
42
- // If we're in the .mastra/output directory, use the dir outside .mastra dir
43
- // reason we need to do this is libsql relative file paths are based on cwd, not current file path
44
- // since mastra dev sets cwd to .mastra/output this means running an agent directly vs running with mastra dev
45
- // will put db files in different locations, leading to an inconsistent experience between the two.
46
- // Ex: with `file:ex.db`
47
- // 1. `mastra dev`: ${cwd}/.mastra/output/ex.db
48
- // 2. `tsx src/index.ts`: ${cwd}/ex.db
49
- // so if we're in .mastra/output we need to rewrite the file url to be relative to the project root dir
50
- // or the experience will be inconsistent
51
- // this means `file:` urls are always relative to project root
52
- // TODO: can we make this easier via bundling? https://github.com/mastra-ai/mastra/pull/2783#pullrequestreview-2662444241
53
- rewriteDbUrl(url) {
54
- if (url.startsWith("file:") && url !== "file::memory:") {
55
- const pathPart = url.slice("file:".length);
56
- if (isAbsolute(pathPart)) {
57
- return url;
58
- }
59
- const cwd = process.cwd();
60
- if (cwd.includes(".mastra") && (cwd.endsWith(`output`) || cwd.endsWith(`output/`) || cwd.endsWith(`output\\`))) {
61
- const baseDir = join(cwd, `..`, `..`);
62
- const fullPath = resolve(baseDir, pathPart);
63
- this.logger.debug(
64
- `Initializing LibSQL db with url ${url} with relative file path from inside .mastra/output directory. Rewriting relative file url to "file:${fullPath}". This ensures it's outside the .mastra/output directory.`
65
- );
66
- return `file:${fullPath}`;
67
- }
68
- }
69
- return url;
70
- }
71
- getCreateTableSQL(tableName, schema) {
72
- const columns = Object.entries(schema).map(([name, col]) => {
73
- let type = col.type.toUpperCase();
74
- if (type === "TEXT") type = "TEXT";
75
- if (type === "TIMESTAMP") type = "TEXT";
76
- const nullable = col.nullable ? "" : "NOT NULL";
77
- const primaryKey = col.primaryKey ? "PRIMARY KEY" : "";
78
- return `${name} ${type} ${nullable} ${primaryKey}`.trim();
79
- });
80
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
81
- const stmnt = `CREATE TABLE IF NOT EXISTS ${tableName} (
82
- ${columns.join(",\n")},
83
- PRIMARY KEY (workflow_name, run_id)
84
- )`;
85
- return stmnt;
86
- }
87
- return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
88
- }
89
- async createTable({
90
- tableName,
91
- schema
92
- }) {
93
- try {
94
- this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
95
- const sql = this.getCreateTableSQL(tableName, schema);
96
- await this.client.execute(sql);
97
- } catch (error) {
98
- this.logger.error(`Error creating table ${tableName}: ${error}`);
99
- throw error;
100
- }
101
- }
102
- async clearTable({ tableName }) {
103
- try {
104
- await this.client.execute(`DELETE FROM ${tableName}`);
105
- } catch (e) {
106
- if (e instanceof Error) {
107
- this.logger.error(e.message);
108
- }
109
- }
110
- }
111
- prepareStatement({ tableName, record }) {
112
- const columns = Object.keys(record);
113
- const values = Object.values(record).map((v) => {
114
- if (typeof v === `undefined`) {
115
- return null;
116
- }
117
- if (v instanceof Date) {
118
- return v.toISOString();
119
- }
120
- return typeof v === "object" ? JSON.stringify(v) : v;
121
- });
122
- const placeholders = values.map(() => "?").join(", ");
123
- return {
124
- sql: `INSERT OR REPLACE INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
125
- args: values
126
- };
127
- }
128
- async insert({ tableName, record }) {
129
- warnDeprecation(this.logger);
130
- try {
131
- await this.client.execute(
132
- this.prepareStatement({
133
- tableName,
134
- record
135
- })
136
- );
137
- } catch (error) {
138
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
139
- throw error;
140
- }
141
- }
142
- async batchInsert({ tableName, records }) {
143
- if (records.length === 0) return;
144
- warnDeprecation(this.logger);
145
- try {
146
- const batchStatements = records.map((r) => this.prepareStatement({ tableName, record: r }));
147
- await this.client.batch(batchStatements, "write");
148
- } catch (error) {
149
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
150
- throw error;
151
- }
152
- }
153
- async load({ tableName, keys }) {
154
- const conditions = Object.entries(keys).map(([key]) => `${key} = ?`).join(" AND ");
155
- const values = Object.values(keys);
156
- const result = await this.client.execute({
157
- sql: `SELECT * FROM ${tableName} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
158
- args: values
159
- });
160
- if (!result.rows || result.rows.length === 0) {
161
- return null;
162
- }
163
- const row = result.rows[0];
164
- const parsed = Object.fromEntries(
165
- Object.entries(row || {}).map(([k, v]) => {
166
- try {
167
- return [k, typeof v === "string" ? v.startsWith("{") || v.startsWith("[") ? JSON.parse(v) : v : v];
168
- } catch {
169
- return [k, v];
170
- }
171
- })
172
- );
173
- return parsed;
174
- }
175
- async getThreadById({ threadId }) {
176
- const result = await this.load({
177
- tableName: TABLE_THREADS,
178
- keys: { id: threadId }
179
- });
180
- if (!result) {
181
- return null;
182
- }
183
- return {
184
- ...result,
185
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
186
- };
187
- }
188
- async getThreadsByResourceId({ resourceId }) {
189
- const result = await this.client.execute({
190
- sql: `SELECT * FROM ${TABLE_THREADS} WHERE resourceId = ?`,
191
- args: [resourceId]
192
- });
193
- if (!result.rows) {
194
- return [];
195
- }
196
- return result.rows.map((thread) => ({
197
- id: thread.id,
198
- resourceId: thread.resourceId,
199
- title: thread.title,
200
- createdAt: thread.createdAt,
201
- updatedAt: thread.updatedAt,
202
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata
203
- }));
204
- }
205
- async saveThread({ thread }) {
206
- await this.insert({
207
- tableName: TABLE_THREADS,
208
- record: {
209
- ...thread,
210
- metadata: JSON.stringify(thread.metadata)
211
- }
212
- });
213
- return thread;
214
- }
215
- async updateThread({
216
- id,
217
- title,
218
- metadata
219
- }) {
220
- const thread = await this.getThreadById({ threadId: id });
221
- if (!thread) {
222
- throw new Error(`Thread ${id} not found`);
223
- }
224
- const updatedThread = {
225
- ...thread,
226
- title,
227
- metadata: {
228
- ...thread.metadata,
229
- ...metadata
230
- }
231
- };
232
- await this.client.execute({
233
- sql: `UPDATE ${TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
234
- args: [title, JSON.stringify(updatedThread.metadata), id]
235
- });
236
- return updatedThread;
237
- }
238
- async deleteThread({ threadId }) {
239
- await this.client.execute({
240
- sql: `DELETE FROM ${TABLE_THREADS} WHERE id = ?`,
241
- args: [threadId]
242
- });
243
- }
244
- parseRow(row) {
245
- let content = row.content;
246
- try {
247
- content = JSON.parse(row.content);
248
- } catch {
249
- }
250
- return {
251
- id: row.id,
252
- content,
253
- role: row.role,
254
- type: row.type,
255
- createdAt: new Date(row.createdAt),
256
- threadId: row.thread_id
257
- };
258
- }
259
- async getMessages({ threadId, selectBy }) {
260
- try {
261
- const messages = [];
262
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
263
- if (selectBy?.include?.length) {
264
- const includeIds = selectBy.include.map((i) => i.id);
265
- const maxPrev = Math.max(...selectBy.include.map((i) => i.withPreviousMessages || 0));
266
- const maxNext = Math.max(...selectBy.include.map((i) => i.withNextMessages || 0));
267
- const includeResult = await this.client.execute({
268
- sql: `
269
- WITH numbered_messages AS (
270
- SELECT
271
- id,
272
- content,
273
- role,
274
- type,
275
- "createdAt",
276
- thread_id,
277
- ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
278
- FROM "${TABLE_MESSAGES}"
279
- WHERE thread_id = ?
280
- ),
281
- target_positions AS (
282
- SELECT row_num as target_pos
283
- FROM numbered_messages
284
- WHERE id IN (${includeIds.map(() => "?").join(", ")})
285
- )
286
- SELECT DISTINCT m.*
287
- FROM numbered_messages m
288
- CROSS JOIN target_positions t
289
- WHERE m.row_num BETWEEN (t.target_pos - ?) AND (t.target_pos + ?)
290
- ORDER BY m."createdAt" ASC
291
- `,
292
- args: [threadId, ...includeIds, maxPrev, maxNext]
293
- });
294
- if (includeResult.rows) {
295
- messages.push(...includeResult.rows.map((row) => this.parseRow(row)));
296
- }
297
- }
298
- const excludeIds = messages.map((m) => m.id);
299
- const remainingSql = `
300
- SELECT
301
- id,
302
- content,
303
- role,
304
- type,
305
- "createdAt",
306
- thread_id
307
- FROM "${TABLE_MESSAGES}"
308
- WHERE thread_id = ?
309
- ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
310
- ORDER BY "createdAt" DESC
311
- LIMIT ?
312
- `;
313
- const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
314
- const remainingResult = await this.client.execute({
315
- sql: remainingSql,
316
- args: remainingArgs
317
- });
318
- if (remainingResult.rows) {
319
- messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
320
- }
321
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
322
- return messages;
323
- } catch (error) {
324
- this.logger.error("Error getting messages:", error);
325
- throw error;
326
- }
327
- }
328
- async saveMessages({ messages }) {
329
- if (messages.length === 0) return messages;
330
- try {
331
- const threadId = messages[0]?.threadId;
332
- if (!threadId) {
333
- throw new Error("Thread ID is required");
334
- }
335
- const batchStatements = messages.map((message) => {
336
- const time = message.createdAt || /* @__PURE__ */ new Date();
337
- return {
338
- sql: `INSERT INTO ${TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt)
339
- VALUES (?, ?, ?, ?, ?, ?)`,
340
- args: [
341
- message.id,
342
- threadId,
343
- typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
344
- message.role,
345
- message.type,
346
- time instanceof Date ? time.toISOString() : time
347
- ]
348
- };
349
- });
350
- await this.client.batch(batchStatements, "write");
351
- return messages;
352
- } catch (error) {
353
- this.logger.error("Failed to save messages in database: " + error?.message);
354
- throw error;
355
- }
356
- }
357
- transformEvalRow(row) {
358
- const resultValue = JSON.parse(row.result);
359
- const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
360
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
361
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
362
- }
363
- return {
364
- input: row.input,
365
- output: row.output,
366
- result: resultValue,
367
- agentName: row.agent_name,
368
- metricName: row.metric_name,
369
- instructions: row.instructions,
370
- testInfo: testInfoValue,
371
- globalRunId: row.global_run_id,
372
- runId: row.run_id,
373
- createdAt: row.created_at
374
- };
375
- }
376
- async getEvalsByAgentName(agentName, type) {
377
- try {
378
- const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
379
- const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
380
- const result = await this.client.execute({
381
- sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
382
- args: [agentName]
383
- });
384
- return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
385
- } catch (error) {
386
- if (error instanceof Error && error.message.includes("no such table")) {
387
- return [];
388
- }
389
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
390
- throw error;
391
- }
392
- }
393
- // TODO: add types
394
- async getTraces({
395
- name,
396
- scope,
397
- page,
398
- perPage,
399
- attributes,
400
- filters,
401
- fromDate,
402
- toDate
403
- } = {
404
- page: 0,
405
- perPage: 100
406
- }) {
407
- const limit = perPage;
408
- const offset = page * perPage;
409
- const args = [];
410
- const conditions = [];
411
- if (name) {
412
- conditions.push("name LIKE CONCAT(?, '%')");
413
- }
414
- if (scope) {
415
- conditions.push("scope = ?");
416
- }
417
- if (attributes) {
418
- Object.keys(attributes).forEach((key) => {
419
- conditions.push(`attributes->>'$.${key}' = ?`);
420
- });
421
- }
422
- if (filters) {
423
- Object.entries(filters).forEach(([key, _value]) => {
424
- conditions.push(`${key} = ?`);
425
- });
426
- }
427
- if (fromDate) {
428
- conditions.push("createdAt >= ?");
429
- }
430
- if (toDate) {
431
- conditions.push("createdAt <= ?");
432
- }
433
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
434
- if (name) {
435
- args.push(name);
436
- }
437
- if (scope) {
438
- args.push(scope);
439
- }
440
- if (attributes) {
441
- for (const [, value] of Object.entries(attributes)) {
442
- args.push(value);
443
- }
444
- }
445
- if (filters) {
446
- for (const [, value] of Object.entries(filters)) {
447
- args.push(value);
448
- }
449
- }
450
- if (fromDate) {
451
- args.push(fromDate.toISOString());
452
- }
453
- if (toDate) {
454
- args.push(toDate.toISOString());
455
- }
456
- args.push(limit, offset);
457
- const result = await this.client.execute({
458
- sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
459
- args
460
- });
461
- if (!result.rows) {
462
- return [];
463
- }
464
- return result.rows.map((row) => ({
465
- id: row.id,
466
- parentSpanId: row.parentSpanId,
467
- traceId: row.traceId,
468
- name: row.name,
469
- scope: row.scope,
470
- kind: row.kind,
471
- status: safelyParseJSON(row.status),
472
- events: safelyParseJSON(row.events),
473
- links: safelyParseJSON(row.links),
474
- attributes: safelyParseJSON(row.attributes),
475
- startTime: row.startTime,
476
- endTime: row.endTime,
477
- other: safelyParseJSON(row.other),
478
- createdAt: row.createdAt
479
- }));
480
- }
481
- async getWorkflowRuns({
482
- workflowName,
483
- fromDate,
484
- toDate,
485
- limit,
486
- offset
487
- } = {}) {
488
- const conditions = [];
489
- const args = [];
490
- if (workflowName) {
491
- conditions.push("workflow_name = ?");
492
- args.push(workflowName);
493
- }
494
- if (fromDate) {
495
- conditions.push("createdAt >= ?");
496
- args.push(fromDate.toISOString());
497
- }
498
- if (toDate) {
499
- conditions.push("createdAt <= ?");
500
- args.push(toDate.toISOString());
501
- }
502
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
503
- let total = 0;
504
- if (limit !== void 0 && offset !== void 0) {
505
- const countResult = await this.client.execute({
506
- sql: `SELECT COUNT(*) as count FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
507
- args
508
- });
509
- total = Number(countResult.rows?.[0]?.count ?? 0);
510
- }
511
- const result = await this.client.execute({
512
- sql: `SELECT * FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
513
- args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
514
- });
515
- const runs = (result.rows || []).map((row) => {
516
- let parsedSnapshot = row.snapshot;
517
- if (typeof parsedSnapshot === "string") {
518
- try {
519
- parsedSnapshot = JSON.parse(row.snapshot);
520
- } catch (e) {
521
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
522
- }
523
- }
524
- return {
525
- workflowName: row.workflow_name,
526
- runId: row.run_id,
527
- snapshot: parsedSnapshot,
528
- createdAt: new Date(row.createdAt),
529
- updatedAt: new Date(row.updatedAt)
530
- };
531
- });
532
- return { runs, total: total || runs.length };
533
- }
534
- async getWorkflowRunById({
535
- runId,
536
- workflowName
537
- }) {
538
- const conditions = [];
539
- const args = [];
540
- if (runId) {
541
- conditions.push("run_id = ?");
542
- args.push(runId);
543
- }
544
- if (workflowName) {
545
- conditions.push("workflow_name = ?");
546
- args.push(workflowName);
547
- }
548
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
549
- const result = await this.client.execute({
550
- sql: `SELECT * FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
551
- args
552
- });
553
- if (!result.rows?.[0]) {
554
- return null;
555
- }
556
- return this.parseWorkflowRun(result.rows[0]);
557
- }
558
- parseWorkflowRun(row) {
559
- let parsedSnapshot = row.snapshot;
560
- if (typeof parsedSnapshot === "string") {
561
- try {
562
- parsedSnapshot = JSON.parse(row.snapshot);
563
- } catch (e) {
564
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
565
- }
566
- }
567
- return {
568
- workflowName: row.workflow_name,
569
- runId: row.run_id,
570
- snapshot: parsedSnapshot,
571
- resourceId: row.resourceId,
572
- createdAt: new Date(row.created_at),
573
- updatedAt: new Date(row.updated_at)
574
- };
575
- }
576
- };
577
-
578
- export { LibSQLStore as DefaultStorage, LibSQLStore };
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkQDAMIZY3_cjs = require('../../chunk-QDAMIZY3.cjs');
4
-
5
-
6
-
7
- Object.defineProperty(exports, "DefaultVectorDB", {
8
- enumerable: true,
9
- get: function () { return chunkQDAMIZY3_cjs.LibSQLVector; }
10
- });
11
- Object.defineProperty(exports, "LibSQLVector", {
12
- enumerable: true,
13
- get: function () { return chunkQDAMIZY3_cjs.LibSQLVector; }
14
- });