@mastra/libsql 1.2.0-alpha.0 → 1.3.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +176 -0
- package/dist/docs/SKILL.md +36 -26
- package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
- package/dist/docs/{agents/03-agent-approval.md → references/docs-agents-agent-approval.md} +19 -19
- package/dist/docs/references/docs-agents-agent-memory.md +212 -0
- package/dist/docs/{agents/04-network-approval.md → references/docs-agents-network-approval.md} +13 -12
- package/dist/docs/{agents/02-networks.md → references/docs-agents-networks.md} +10 -12
- package/dist/docs/{memory/06-memory-processors.md → references/docs-memory-memory-processors.md} +6 -8
- package/dist/docs/{memory/03-message-history.md → references/docs-memory-message-history.md} +31 -20
- package/dist/docs/{memory/01-overview.md → references/docs-memory-overview.md} +8 -8
- package/dist/docs/{memory/05-semantic-recall.md → references/docs-memory-semantic-recall.md} +33 -17
- package/dist/docs/{memory/02-storage.md → references/docs-memory-storage.md} +29 -39
- package/dist/docs/{memory/04-working-memory.md → references/docs-memory-working-memory.md} +16 -27
- package/dist/docs/{observability/01-overview.md → references/docs-observability-overview.md} +4 -7
- package/dist/docs/{observability/02-default.md → references/docs-observability-tracing-exporters-default.md} +11 -14
- package/dist/docs/{rag/01-retrieval.md → references/docs-rag-retrieval.md} +26 -53
- package/dist/docs/{workflows/01-snapshots.md → references/docs-workflows-snapshots.md} +3 -5
- package/dist/docs/{guides/01-ai-sdk.md → references/guides-agent-frameworks-ai-sdk.md} +25 -9
- package/dist/docs/references/reference-core-getMemory.md +50 -0
- package/dist/docs/references/reference-core-listMemory.md +56 -0
- package/dist/docs/references/reference-core-mastra-class.md +66 -0
- package/dist/docs/{memory/07-reference.md → references/reference-memory-memory-class.md} +28 -14
- package/dist/docs/references/reference-storage-composite.md +235 -0
- package/dist/docs/references/reference-storage-dynamodb.md +282 -0
- package/dist/docs/references/reference-storage-libsql.md +135 -0
- package/dist/docs/{vectors/01-reference.md → references/reference-vectors-libsql.md} +105 -13
- package/dist/index.cjs +1676 -194
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1676 -196
- package/dist/index.js.map +1 -1
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/domains/agents/index.d.ts +9 -12
- package/dist/storage/domains/agents/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +7 -1
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
- package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +3 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +5 -6
- package/dist/docs/README.md +0 -39
- package/dist/docs/agents/01-agent-memory.md +0 -166
- package/dist/docs/core/01-reference.md +0 -151
- package/dist/docs/storage/01-reference.md +0 -556
package/dist/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { createClient } from '@libsql/client';
|
|
2
2
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
3
|
-
import { createVectorErrorId, AgentsStorage, AGENTS_SCHEMA, TABLE_AGENTS, AGENT_VERSIONS_SCHEMA, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, SPAN_SCHEMA, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, transformScoreRow, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getSqlType, safelyParseJSON } from '@mastra/core/storage';
|
|
3
|
+
import { createVectorErrorId, AgentsStorage, AGENTS_SCHEMA, TABLE_AGENTS, AGENT_VERSIONS_SCHEMA, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, SPAN_SCHEMA, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, PROMPT_BLOCKS_SCHEMA, TABLE_PROMPT_BLOCKS, PROMPT_BLOCK_VERSIONS_SCHEMA, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, SCORER_DEFINITIONS_SCHEMA, TABLE_SCORER_DEFINITIONS, SCORER_DEFINITION_VERSIONS_SCHEMA, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, transformScoreRow, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getSqlType, safelyParseJSON } from '@mastra/core/storage';
|
|
4
4
|
import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
|
|
5
5
|
import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
|
|
6
6
|
import { BaseFilterTranslator } from '@mastra/core/vector/filter';
|
|
7
7
|
import { MastraBase } from '@mastra/core/base';
|
|
8
|
+
import { randomUUID } from 'crypto';
|
|
8
9
|
import { MessageList } from '@mastra/core/agent';
|
|
9
10
|
import { saveScorePayloadSchema } from '@mastra/core/evals';
|
|
10
11
|
|
|
@@ -1991,7 +1992,7 @@ Note: This migration may take some time for large tables.
|
|
|
1991
1992
|
if (!existingColumns.has(columnName.toLowerCase()) && schema[columnName]) {
|
|
1992
1993
|
const columnDef = schema[columnName];
|
|
1993
1994
|
const sqlType = this.getSqlType(columnDef.type);
|
|
1994
|
-
const defaultValue = this.getDefaultValue(columnDef.type);
|
|
1995
|
+
const defaultValue = columnDef.nullable ? "DEFAULT NULL" : this.getDefaultValue(columnDef.type);
|
|
1995
1996
|
const alterSql = `ALTER TABLE ${parsedTableName} ADD COLUMN "${columnName}" ${sqlType} ${defaultValue}`;
|
|
1996
1997
|
await this.client.execute(alterSql);
|
|
1997
1998
|
this.logger.debug(`LibSQLDB: Added column ${columnName} to table ${tableName}`);
|
|
@@ -2073,6 +2074,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2073
2074
|
schema: AGENTS_SCHEMA,
|
|
2074
2075
|
ifNotExists: ["status", "authorId"]
|
|
2075
2076
|
});
|
|
2077
|
+
await this.#migrateToolsToJsonbFormat();
|
|
2076
2078
|
await this.#cleanupStaleDrafts();
|
|
2077
2079
|
}
|
|
2078
2080
|
/**
|
|
@@ -2124,7 +2126,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2124
2126
|
versionNumber: 1,
|
|
2125
2127
|
name: row.name ?? agentId,
|
|
2126
2128
|
description: row.description ?? null,
|
|
2127
|
-
instructions: row.instructions ?? "",
|
|
2129
|
+
instructions: this.serializeInstructions(row.instructions ?? ""),
|
|
2128
2130
|
model: row.model ?? "{}",
|
|
2129
2131
|
tools: row.tools ?? null,
|
|
2130
2132
|
defaultOptions: row.defaultOptions ?? null,
|
|
@@ -2173,6 +2175,52 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2173
2175
|
} catch {
|
|
2174
2176
|
}
|
|
2175
2177
|
}
|
|
2178
|
+
/**
|
|
2179
|
+
* Migrates the tools field from string[] format to JSONB format { "tool-key": { "description": "..." } }.
|
|
2180
|
+
* This handles the transition from the old format where tools were stored as an array of string keys
|
|
2181
|
+
* to the new format where tools can have per-agent description overrides.
|
|
2182
|
+
*/
|
|
2183
|
+
async #migrateToolsToJsonbFormat() {
|
|
2184
|
+
try {
|
|
2185
|
+
const result = await this.#client.execute({
|
|
2186
|
+
sql: `SELECT id, tools FROM "${TABLE_AGENT_VERSIONS}" WHERE tools IS NOT NULL`
|
|
2187
|
+
});
|
|
2188
|
+
if (!result.rows || result.rows.length === 0) {
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
for (const row of result.rows) {
|
|
2192
|
+
const toolsValue = row.tools;
|
|
2193
|
+
let parsedTools;
|
|
2194
|
+
try {
|
|
2195
|
+
if (typeof toolsValue === "string") {
|
|
2196
|
+
parsedTools = JSON.parse(toolsValue);
|
|
2197
|
+
} else if (toolsValue instanceof ArrayBuffer) {
|
|
2198
|
+
const decoder = new TextDecoder();
|
|
2199
|
+
parsedTools = JSON.parse(decoder.decode(toolsValue));
|
|
2200
|
+
} else {
|
|
2201
|
+
parsedTools = toolsValue;
|
|
2202
|
+
}
|
|
2203
|
+
} catch {
|
|
2204
|
+
continue;
|
|
2205
|
+
}
|
|
2206
|
+
if (Array.isArray(parsedTools)) {
|
|
2207
|
+
const toolsObject = {};
|
|
2208
|
+
for (const toolKey of parsedTools) {
|
|
2209
|
+
if (typeof toolKey === "string") {
|
|
2210
|
+
toolsObject[toolKey] = {};
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
await this.#client.execute({
|
|
2214
|
+
sql: `UPDATE "${TABLE_AGENT_VERSIONS}" SET tools = ? WHERE id = ?`,
|
|
2215
|
+
args: [JSON.stringify(toolsObject), row.id]
|
|
2216
|
+
});
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
this.logger?.info?.(`Migrated agent version tools from array to object format`);
|
|
2220
|
+
} catch (error) {
|
|
2221
|
+
this.logger?.warn?.("Failed to migrate tools to JSONB format:", error);
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2176
2224
|
async dangerouslyClearAll() {
|
|
2177
2225
|
await this.#db.deleteData({ tableName: TABLE_AGENT_VERSIONS });
|
|
2178
2226
|
await this.#db.deleteData({ tableName: TABLE_AGENTS });
|
|
@@ -2222,7 +2270,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2222
2270
|
updatedAt: new Date(row.updatedAt)
|
|
2223
2271
|
};
|
|
2224
2272
|
}
|
|
2225
|
-
async
|
|
2273
|
+
async getById(id) {
|
|
2226
2274
|
try {
|
|
2227
2275
|
const result = await this.#db.select({
|
|
2228
2276
|
tableName: TABLE_AGENTS,
|
|
@@ -2230,6 +2278,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2230
2278
|
});
|
|
2231
2279
|
return result ? this.parseRow(result) : null;
|
|
2232
2280
|
} catch (error) {
|
|
2281
|
+
if (error instanceof MastraError) throw error;
|
|
2233
2282
|
throw new MastraError(
|
|
2234
2283
|
{
|
|
2235
2284
|
id: createStorageErrorId("LIBSQL", "GET_AGENT_BY_ID", "FAILED"),
|
|
@@ -2241,7 +2290,8 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2241
2290
|
);
|
|
2242
2291
|
}
|
|
2243
2292
|
}
|
|
2244
|
-
async
|
|
2293
|
+
async create(input) {
|
|
2294
|
+
const { agent } = input;
|
|
2245
2295
|
try {
|
|
2246
2296
|
const now = /* @__PURE__ */ new Date();
|
|
2247
2297
|
await this.#db.insert({
|
|
@@ -2266,7 +2316,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2266
2316
|
changedFields: Object.keys(snapshotConfig),
|
|
2267
2317
|
changeMessage: "Initial version"
|
|
2268
2318
|
});
|
|
2269
|
-
const created = await this.
|
|
2319
|
+
const created = await this.getById(agent.id);
|
|
2270
2320
|
if (!created) {
|
|
2271
2321
|
throw new MastraError({
|
|
2272
2322
|
id: createStorageErrorId("LIBSQL", "CREATE_AGENT", "NOT_FOUND_AFTER_CREATE"),
|
|
@@ -2292,9 +2342,10 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2292
2342
|
);
|
|
2293
2343
|
}
|
|
2294
2344
|
}
|
|
2295
|
-
async
|
|
2345
|
+
async update(input) {
|
|
2346
|
+
const { id, ...updates } = input;
|
|
2296
2347
|
try {
|
|
2297
|
-
const existingAgent = await this.
|
|
2348
|
+
const existingAgent = await this.getById(id);
|
|
2298
2349
|
if (!existingAgent) {
|
|
2299
2350
|
throw new MastraError({
|
|
2300
2351
|
id: createStorageErrorId("LIBSQL", "UPDATE_AGENT", "NOT_FOUND"),
|
|
@@ -2333,14 +2384,17 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2333
2384
|
latestSnapshot[field] = latestVersion[field];
|
|
2334
2385
|
}
|
|
2335
2386
|
}
|
|
2387
|
+
const sanitizedConfigFields = Object.fromEntries(
|
|
2388
|
+
Object.entries(configFields).map(([key, value]) => [key, value === null ? void 0 : value])
|
|
2389
|
+
);
|
|
2336
2390
|
const versionInput = {
|
|
2337
2391
|
id: crypto.randomUUID(),
|
|
2338
2392
|
agentId: id,
|
|
2339
2393
|
versionNumber: nextVersionNumber,
|
|
2340
2394
|
...latestSnapshot,
|
|
2341
2395
|
// Start from latest version
|
|
2342
|
-
...
|
|
2343
|
-
// Apply updates
|
|
2396
|
+
...sanitizedConfigFields,
|
|
2397
|
+
// Apply updates (null values converted to undefined)
|
|
2344
2398
|
changedFields: Object.keys(configFields),
|
|
2345
2399
|
changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
|
|
2346
2400
|
};
|
|
@@ -2363,7 +2417,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2363
2417
|
data
|
|
2364
2418
|
});
|
|
2365
2419
|
}
|
|
2366
|
-
const updatedAgent = await this.
|
|
2420
|
+
const updatedAgent = await this.getById(id);
|
|
2367
2421
|
if (!updatedAgent) {
|
|
2368
2422
|
throw new MastraError({
|
|
2369
2423
|
id: createStorageErrorId("LIBSQL", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
|
|
@@ -2389,14 +2443,15 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2389
2443
|
);
|
|
2390
2444
|
}
|
|
2391
2445
|
}
|
|
2392
|
-
async
|
|
2446
|
+
async delete(id) {
|
|
2393
2447
|
try {
|
|
2394
|
-
await this.
|
|
2448
|
+
await this.deleteVersionsByParentId(id);
|
|
2395
2449
|
await this.#db.delete({
|
|
2396
2450
|
tableName: TABLE_AGENTS,
|
|
2397
2451
|
keys: { id }
|
|
2398
2452
|
});
|
|
2399
2453
|
} catch (error) {
|
|
2454
|
+
if (error instanceof MastraError) throw error;
|
|
2400
2455
|
throw new MastraError(
|
|
2401
2456
|
{
|
|
2402
2457
|
id: createStorageErrorId("LIBSQL", "DELETE_AGENT", "FAILED"),
|
|
@@ -2408,7 +2463,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2408
2463
|
);
|
|
2409
2464
|
}
|
|
2410
2465
|
}
|
|
2411
|
-
async
|
|
2466
|
+
async list(args) {
|
|
2412
2467
|
const { page = 0, perPage: perPageInput, orderBy } = args || {};
|
|
2413
2468
|
const { field, direction } = this.parseOrderBy(orderBy);
|
|
2414
2469
|
if (page < 0) {
|
|
@@ -2451,6 +2506,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2451
2506
|
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
2452
2507
|
};
|
|
2453
2508
|
} catch (error) {
|
|
2509
|
+
if (error instanceof MastraError) throw error;
|
|
2454
2510
|
throw new MastraError(
|
|
2455
2511
|
{
|
|
2456
2512
|
id: createStorageErrorId("LIBSQL", "LIST_AGENTS", "FAILED"),
|
|
@@ -2461,88 +2517,6 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2461
2517
|
);
|
|
2462
2518
|
}
|
|
2463
2519
|
}
|
|
2464
|
-
async listAgentsResolved(args) {
|
|
2465
|
-
const { page = 0, perPage: perPageInput, orderBy } = args || {};
|
|
2466
|
-
const { field, direction } = this.parseOrderBy(orderBy);
|
|
2467
|
-
if (page < 0) {
|
|
2468
|
-
throw new MastraError(
|
|
2469
|
-
{
|
|
2470
|
-
id: createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
|
|
2471
|
-
domain: ErrorDomain.STORAGE,
|
|
2472
|
-
category: ErrorCategory.USER,
|
|
2473
|
-
details: { page }
|
|
2474
|
-
},
|
|
2475
|
-
new Error("page must be >= 0")
|
|
2476
|
-
);
|
|
2477
|
-
}
|
|
2478
|
-
const perPage = normalizePerPage(perPageInput, 100);
|
|
2479
|
-
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
2480
|
-
try {
|
|
2481
|
-
const total = await this.#db.selectTotalCount({ tableName: TABLE_AGENTS });
|
|
2482
|
-
if (total === 0) {
|
|
2483
|
-
return {
|
|
2484
|
-
agents: [],
|
|
2485
|
-
total: 0,
|
|
2486
|
-
page,
|
|
2487
|
-
perPage: perPageForResponse,
|
|
2488
|
-
hasMore: false
|
|
2489
|
-
};
|
|
2490
|
-
}
|
|
2491
|
-
const limitValue = perPageInput === false ? total : perPage;
|
|
2492
|
-
const agents = await this.#db.selectMany({
|
|
2493
|
-
tableName: TABLE_AGENTS,
|
|
2494
|
-
orderBy: `"${field}" ${direction}`,
|
|
2495
|
-
limit: limitValue,
|
|
2496
|
-
offset
|
|
2497
|
-
});
|
|
2498
|
-
const resolvedAgents = await Promise.all(
|
|
2499
|
-
agents.map(async (agent) => {
|
|
2500
|
-
let version = null;
|
|
2501
|
-
if (agent.activeVersionId) {
|
|
2502
|
-
version = await this.getVersion(agent.activeVersionId);
|
|
2503
|
-
}
|
|
2504
|
-
if (!version) {
|
|
2505
|
-
version = await this.getLatestVersion(agent.id);
|
|
2506
|
-
}
|
|
2507
|
-
if (!version) {
|
|
2508
|
-
return agent;
|
|
2509
|
-
}
|
|
2510
|
-
return {
|
|
2511
|
-
...agent,
|
|
2512
|
-
name: version.name,
|
|
2513
|
-
description: version.description,
|
|
2514
|
-
instructions: version.instructions,
|
|
2515
|
-
model: version.model,
|
|
2516
|
-
tools: version.tools,
|
|
2517
|
-
defaultOptions: version.defaultOptions,
|
|
2518
|
-
workflows: version.workflows,
|
|
2519
|
-
agents: version.agents,
|
|
2520
|
-
integrationTools: version.integrationTools,
|
|
2521
|
-
inputProcessors: version.inputProcessors,
|
|
2522
|
-
outputProcessors: version.outputProcessors,
|
|
2523
|
-
memory: version.memory,
|
|
2524
|
-
scorers: version.scorers
|
|
2525
|
-
};
|
|
2526
|
-
})
|
|
2527
|
-
);
|
|
2528
|
-
return {
|
|
2529
|
-
agents: resolvedAgents,
|
|
2530
|
-
total,
|
|
2531
|
-
page,
|
|
2532
|
-
perPage: perPageForResponse,
|
|
2533
|
-
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
2534
|
-
};
|
|
2535
|
-
} catch (error) {
|
|
2536
|
-
throw new MastraError(
|
|
2537
|
-
{
|
|
2538
|
-
id: createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "FAILED"),
|
|
2539
|
-
domain: ErrorDomain.STORAGE,
|
|
2540
|
-
category: ErrorCategory.THIRD_PARTY
|
|
2541
|
-
},
|
|
2542
|
-
error
|
|
2543
|
-
);
|
|
2544
|
-
}
|
|
2545
|
-
}
|
|
2546
2520
|
// ==========================================================================
|
|
2547
2521
|
// Agent Version Methods
|
|
2548
2522
|
// ==========================================================================
|
|
@@ -2557,7 +2531,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2557
2531
|
versionNumber: input.versionNumber,
|
|
2558
2532
|
name: input.name ?? null,
|
|
2559
2533
|
description: input.description ?? null,
|
|
2560
|
-
instructions: input.instructions,
|
|
2534
|
+
instructions: this.serializeInstructions(input.instructions),
|
|
2561
2535
|
model: input.model,
|
|
2562
2536
|
tools: input.tools ?? null,
|
|
2563
2537
|
defaultOptions: input.defaultOptions ?? null,
|
|
@@ -2578,6 +2552,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2578
2552
|
createdAt: now
|
|
2579
2553
|
};
|
|
2580
2554
|
} catch (error) {
|
|
2555
|
+
if (error instanceof MastraError) throw error;
|
|
2581
2556
|
throw new MastraError(
|
|
2582
2557
|
{
|
|
2583
2558
|
id: createStorageErrorId("LIBSQL", "CREATE_VERSION", "FAILED"),
|
|
@@ -2600,6 +2575,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2600
2575
|
}
|
|
2601
2576
|
return this.parseVersionRow(result);
|
|
2602
2577
|
} catch (error) {
|
|
2578
|
+
if (error instanceof MastraError) throw error;
|
|
2603
2579
|
throw new MastraError(
|
|
2604
2580
|
{
|
|
2605
2581
|
id: createStorageErrorId("LIBSQL", "GET_VERSION", "FAILED"),
|
|
@@ -2626,6 +2602,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2626
2602
|
}
|
|
2627
2603
|
return this.parseVersionRow(rows[0]);
|
|
2628
2604
|
} catch (error) {
|
|
2605
|
+
if (error instanceof MastraError) throw error;
|
|
2629
2606
|
throw new MastraError(
|
|
2630
2607
|
{
|
|
2631
2608
|
id: createStorageErrorId("LIBSQL", "GET_VERSION_BY_NUMBER", "FAILED"),
|
|
@@ -2653,6 +2630,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2653
2630
|
}
|
|
2654
2631
|
return this.parseVersionRow(rows[0]);
|
|
2655
2632
|
} catch (error) {
|
|
2633
|
+
if (error instanceof MastraError) throw error;
|
|
2656
2634
|
throw new MastraError(
|
|
2657
2635
|
{
|
|
2658
2636
|
id: createStorageErrorId("LIBSQL", "GET_LATEST_VERSION", "FAILED"),
|
|
@@ -2717,6 +2695,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2717
2695
|
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
2718
2696
|
};
|
|
2719
2697
|
} catch (error) {
|
|
2698
|
+
if (error instanceof MastraError) throw error;
|
|
2720
2699
|
throw new MastraError(
|
|
2721
2700
|
{
|
|
2722
2701
|
id: createStorageErrorId("LIBSQL", "LIST_VERSIONS", "FAILED"),
|
|
@@ -2735,6 +2714,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2735
2714
|
keys: { id }
|
|
2736
2715
|
});
|
|
2737
2716
|
} catch (error) {
|
|
2717
|
+
if (error instanceof MastraError) throw error;
|
|
2738
2718
|
throw new MastraError(
|
|
2739
2719
|
{
|
|
2740
2720
|
id: createStorageErrorId("LIBSQL", "DELETE_VERSION", "FAILED"),
|
|
@@ -2746,13 +2726,13 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2746
2726
|
);
|
|
2747
2727
|
}
|
|
2748
2728
|
}
|
|
2749
|
-
async
|
|
2729
|
+
async deleteVersionsByParentId(entityId) {
|
|
2750
2730
|
try {
|
|
2751
2731
|
const versions = await this.#db.selectMany({
|
|
2752
2732
|
tableName: TABLE_AGENT_VERSIONS,
|
|
2753
2733
|
whereClause: {
|
|
2754
2734
|
sql: "WHERE agentId = ?",
|
|
2755
|
-
args: [
|
|
2735
|
+
args: [entityId]
|
|
2756
2736
|
}
|
|
2757
2737
|
});
|
|
2758
2738
|
for (const version of versions) {
|
|
@@ -2762,12 +2742,13 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2762
2742
|
});
|
|
2763
2743
|
}
|
|
2764
2744
|
} catch (error) {
|
|
2745
|
+
if (error instanceof MastraError) throw error;
|
|
2765
2746
|
throw new MastraError(
|
|
2766
2747
|
{
|
|
2767
2748
|
id: createStorageErrorId("LIBSQL", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
|
|
2768
2749
|
domain: ErrorDomain.STORAGE,
|
|
2769
2750
|
category: ErrorCategory.THIRD_PARTY,
|
|
2770
|
-
details: { agentId }
|
|
2751
|
+
details: { agentId: entityId }
|
|
2771
2752
|
},
|
|
2772
2753
|
error
|
|
2773
2754
|
);
|
|
@@ -2784,6 +2765,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2784
2765
|
});
|
|
2785
2766
|
return count;
|
|
2786
2767
|
} catch (error) {
|
|
2768
|
+
if (error instanceof MastraError) throw error;
|
|
2787
2769
|
throw new MastraError(
|
|
2788
2770
|
{
|
|
2789
2771
|
id: createStorageErrorId("LIBSQL", "COUNT_VERSIONS", "FAILED"),
|
|
@@ -2798,6 +2780,18 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2798
2780
|
// ==========================================================================
|
|
2799
2781
|
// Private Helper Methods
|
|
2800
2782
|
// ==========================================================================
|
|
2783
|
+
serializeInstructions(instructions) {
|
|
2784
|
+
return Array.isArray(instructions) ? JSON.stringify(instructions) : instructions;
|
|
2785
|
+
}
|
|
2786
|
+
deserializeInstructions(raw) {
|
|
2787
|
+
if (!raw) return raw;
|
|
2788
|
+
try {
|
|
2789
|
+
const parsed = JSON.parse(raw);
|
|
2790
|
+
if (Array.isArray(parsed)) return parsed;
|
|
2791
|
+
} catch {
|
|
2792
|
+
}
|
|
2793
|
+
return raw;
|
|
2794
|
+
}
|
|
2801
2795
|
parseVersionRow(row) {
|
|
2802
2796
|
return {
|
|
2803
2797
|
id: row.id,
|
|
@@ -2805,7 +2799,7 @@ var AgentsLibSQL = class extends AgentsStorage {
|
|
|
2805
2799
|
versionNumber: row.versionNumber,
|
|
2806
2800
|
name: row.name,
|
|
2807
2801
|
description: row.description,
|
|
2808
|
-
instructions: row.instructions,
|
|
2802
|
+
instructions: this.deserializeInstructions(row.instructions),
|
|
2809
2803
|
model: this.parseJson(row.model, "model"),
|
|
2810
2804
|
tools: this.parseJson(row.tools, "tools"),
|
|
2811
2805
|
defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
|
|
@@ -2851,7 +2845,22 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
2851
2845
|
await this.#db.alterTable({
|
|
2852
2846
|
tableName: OM_TABLE,
|
|
2853
2847
|
schema: omSchema,
|
|
2854
|
-
ifNotExists: [
|
|
2848
|
+
ifNotExists: [
|
|
2849
|
+
"observedMessageIds",
|
|
2850
|
+
"observedTimezone",
|
|
2851
|
+
"bufferedObservations",
|
|
2852
|
+
"bufferedObservationTokens",
|
|
2853
|
+
"bufferedMessageIds",
|
|
2854
|
+
"bufferedReflection",
|
|
2855
|
+
"bufferedReflectionTokens",
|
|
2856
|
+
"bufferedReflectionInputTokens",
|
|
2857
|
+
"reflectedObservationLineCount",
|
|
2858
|
+
"bufferedObservationChunks",
|
|
2859
|
+
"isBufferingObservation",
|
|
2860
|
+
"isBufferingReflection",
|
|
2861
|
+
"lastBufferedAtTokens",
|
|
2862
|
+
"lastBufferedAtTime"
|
|
2863
|
+
]
|
|
2855
2864
|
});
|
|
2856
2865
|
}
|
|
2857
2866
|
await this.#db.alterTable({
|
|
@@ -3895,12 +3904,26 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
3895
3904
|
originType: row.originType || "initial",
|
|
3896
3905
|
generationCount: Number(row.generationCount || 0),
|
|
3897
3906
|
activeObservations: row.activeObservations || "",
|
|
3907
|
+
// Handle new chunk-based structure
|
|
3908
|
+
bufferedObservationChunks: row.bufferedObservationChunks ? typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks : void 0,
|
|
3909
|
+
// Deprecated fields (for backward compatibility)
|
|
3898
3910
|
bufferedObservations: row.activeObservationsPendingUpdate || void 0,
|
|
3911
|
+
bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
|
|
3912
|
+
bufferedMessageIds: void 0,
|
|
3913
|
+
// Use bufferedObservationChunks instead
|
|
3914
|
+
bufferedReflection: row.bufferedReflection || void 0,
|
|
3915
|
+
bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
|
|
3916
|
+
bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
|
|
3917
|
+
reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
|
|
3899
3918
|
totalTokensObserved: Number(row.totalTokensObserved || 0),
|
|
3900
3919
|
observationTokenCount: Number(row.observationTokenCount || 0),
|
|
3901
3920
|
pendingMessageTokens: Number(row.pendingMessageTokens || 0),
|
|
3902
3921
|
isReflecting: Boolean(row.isReflecting),
|
|
3903
3922
|
isObserving: Boolean(row.isObserving),
|
|
3923
|
+
isBufferingObservation: row.isBufferingObservation === true || row.isBufferingObservation === "true" || row.isBufferingObservation === 1,
|
|
3924
|
+
isBufferingReflection: row.isBufferingReflection === true || row.isBufferingReflection === "true" || row.isBufferingReflection === 1,
|
|
3925
|
+
lastBufferedAtTokens: typeof row.lastBufferedAtTokens === "number" ? row.lastBufferedAtTokens : parseInt(String(row.lastBufferedAtTokens ?? "0"), 10) || 0,
|
|
3926
|
+
lastBufferedAtTime: row.lastBufferedAtTime ? new Date(String(row.lastBufferedAtTime)) : null,
|
|
3904
3927
|
config: row.config ? JSON.parse(row.config) : {},
|
|
3905
3928
|
metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
|
|
3906
3929
|
observedMessageIds: row.observedMessageIds ? JSON.parse(row.observedMessageIds) : void 0,
|
|
@@ -3972,6 +3995,10 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
3972
3995
|
pendingMessageTokens: 0,
|
|
3973
3996
|
isReflecting: false,
|
|
3974
3997
|
isObserving: false,
|
|
3998
|
+
isBufferingObservation: false,
|
|
3999
|
+
isBufferingReflection: false,
|
|
4000
|
+
lastBufferedAtTokens: 0,
|
|
4001
|
+
lastBufferedAtTime: null,
|
|
3975
4002
|
config: input.config,
|
|
3976
4003
|
observedTimezone: input.observedTimezone
|
|
3977
4004
|
};
|
|
@@ -3981,8 +4008,9 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
3981
4008
|
"activeObservations", "activeObservationsPendingUpdate",
|
|
3982
4009
|
"originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
|
|
3983
4010
|
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
3984
|
-
"isObserving", "isReflecting", "
|
|
3985
|
-
|
|
4011
|
+
"isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
|
|
4012
|
+
"observedTimezone", "createdAt", "updatedAt"
|
|
4013
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
3986
4014
|
args: [
|
|
3987
4015
|
id,
|
|
3988
4016
|
lookupKey,
|
|
@@ -4001,6 +4029,14 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4001
4029
|
0,
|
|
4002
4030
|
false,
|
|
4003
4031
|
false,
|
|
4032
|
+
false,
|
|
4033
|
+
// isBufferingObservation
|
|
4034
|
+
false,
|
|
4035
|
+
// isBufferingReflection
|
|
4036
|
+
0,
|
|
4037
|
+
// lastBufferedAtTokens
|
|
4038
|
+
null,
|
|
4039
|
+
// lastBufferedAtTime
|
|
4004
4040
|
input.observedTimezone || null,
|
|
4005
4041
|
now.toISOString(),
|
|
4006
4042
|
now.toISOString()
|
|
@@ -4088,6 +4124,10 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4088
4124
|
pendingMessageTokens: 0,
|
|
4089
4125
|
isReflecting: false,
|
|
4090
4126
|
isObserving: false,
|
|
4127
|
+
isBufferingObservation: false,
|
|
4128
|
+
isBufferingReflection: false,
|
|
4129
|
+
lastBufferedAtTokens: 0,
|
|
4130
|
+
lastBufferedAtTime: null,
|
|
4091
4131
|
config: input.currentRecord.config,
|
|
4092
4132
|
metadata: input.currentRecord.metadata,
|
|
4093
4133
|
observedTimezone: input.currentRecord.observedTimezone
|
|
@@ -4098,8 +4138,9 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4098
4138
|
"activeObservations", "activeObservationsPendingUpdate",
|
|
4099
4139
|
"originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
|
|
4100
4140
|
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
4101
|
-
"isObserving", "isReflecting", "
|
|
4102
|
-
|
|
4141
|
+
"isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
|
|
4142
|
+
"observedTimezone", "createdAt", "updatedAt"
|
|
4143
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
4103
4144
|
args: [
|
|
4104
4145
|
id,
|
|
4105
4146
|
lookupKey,
|
|
@@ -4117,7 +4158,17 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4117
4158
|
record.totalTokensObserved,
|
|
4118
4159
|
record.observationTokenCount,
|
|
4119
4160
|
false,
|
|
4161
|
+
// isObserving
|
|
4162
|
+
false,
|
|
4163
|
+
// isReflecting
|
|
4120
4164
|
false,
|
|
4165
|
+
// isBufferingObservation
|
|
4166
|
+
false,
|
|
4167
|
+
// isBufferingReflection
|
|
4168
|
+
0,
|
|
4169
|
+
// lastBufferedAtTokens
|
|
4170
|
+
null,
|
|
4171
|
+
// lastBufferedAtTime
|
|
4121
4172
|
record.observedTimezone || null,
|
|
4122
4173
|
now.toISOString(),
|
|
4123
4174
|
now.toISOString()
|
|
@@ -4196,6 +4247,73 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4196
4247
|
);
|
|
4197
4248
|
}
|
|
4198
4249
|
}
|
|
4250
|
+
async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
|
|
4251
|
+
try {
|
|
4252
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
4253
|
+
let sql;
|
|
4254
|
+
let args;
|
|
4255
|
+
if (lastBufferedAtTokens !== void 0) {
|
|
4256
|
+
sql = `UPDATE "${OM_TABLE}" SET "isBufferingObservation" = ?, "lastBufferedAtTokens" = ?, "updatedAt" = ? WHERE id = ?`;
|
|
4257
|
+
args = [isBuffering, lastBufferedAtTokens, nowStr, id];
|
|
4258
|
+
} else {
|
|
4259
|
+
sql = `UPDATE "${OM_TABLE}" SET "isBufferingObservation" = ?, "updatedAt" = ? WHERE id = ?`;
|
|
4260
|
+
args = [isBuffering, nowStr, id];
|
|
4261
|
+
}
|
|
4262
|
+
const result = await this.#client.execute({ sql, args });
|
|
4263
|
+
if (result.rowsAffected === 0) {
|
|
4264
|
+
throw new MastraError({
|
|
4265
|
+
id: createStorageErrorId("LIBSQL", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
|
|
4266
|
+
text: `Observational memory record not found: ${id}`,
|
|
4267
|
+
domain: ErrorDomain.STORAGE,
|
|
4268
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4269
|
+
details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
|
|
4270
|
+
});
|
|
4271
|
+
}
|
|
4272
|
+
} catch (error) {
|
|
4273
|
+
if (error instanceof MastraError) {
|
|
4274
|
+
throw error;
|
|
4275
|
+
}
|
|
4276
|
+
throw new MastraError(
|
|
4277
|
+
{
|
|
4278
|
+
id: createStorageErrorId("LIBSQL", "SET_BUFFERING_OBSERVATION_FLAG", "FAILED"),
|
|
4279
|
+
domain: ErrorDomain.STORAGE,
|
|
4280
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4281
|
+
details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
|
|
4282
|
+
},
|
|
4283
|
+
error
|
|
4284
|
+
);
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
async setBufferingReflectionFlag(id, isBuffering) {
|
|
4288
|
+
try {
|
|
4289
|
+
const result = await this.#client.execute({
|
|
4290
|
+
sql: `UPDATE "${OM_TABLE}" SET "isBufferingReflection" = ?, "updatedAt" = ? WHERE id = ?`,
|
|
4291
|
+
args: [isBuffering, (/* @__PURE__ */ new Date()).toISOString(), id]
|
|
4292
|
+
});
|
|
4293
|
+
if (result.rowsAffected === 0) {
|
|
4294
|
+
throw new MastraError({
|
|
4295
|
+
id: createStorageErrorId("LIBSQL", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
|
|
4296
|
+
text: `Observational memory record not found: ${id}`,
|
|
4297
|
+
domain: ErrorDomain.STORAGE,
|
|
4298
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4299
|
+
details: { id, isBuffering }
|
|
4300
|
+
});
|
|
4301
|
+
}
|
|
4302
|
+
} catch (error) {
|
|
4303
|
+
if (error instanceof MastraError) {
|
|
4304
|
+
throw error;
|
|
4305
|
+
}
|
|
4306
|
+
throw new MastraError(
|
|
4307
|
+
{
|
|
4308
|
+
id: createStorageErrorId("LIBSQL", "SET_BUFFERING_REFLECTION_FLAG", "FAILED"),
|
|
4309
|
+
domain: ErrorDomain.STORAGE,
|
|
4310
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4311
|
+
details: { id, isBuffering }
|
|
4312
|
+
},
|
|
4313
|
+
error
|
|
4314
|
+
);
|
|
4315
|
+
}
|
|
4316
|
+
}
|
|
4199
4317
|
async clearObservationalMemory(threadId, resourceId) {
|
|
4200
4318
|
try {
|
|
4201
4319
|
const lookupKey = this.getOMKey(threadId, resourceId);
|
|
@@ -4248,109 +4366,433 @@ var MemoryLibSQL = class extends MemoryStorage {
|
|
|
4248
4366
|
);
|
|
4249
4367
|
}
|
|
4250
4368
|
}
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
super();
|
|
4256
|
-
const client = resolveClient(config);
|
|
4257
|
-
this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
|
|
4258
|
-
}
|
|
4259
|
-
async init() {
|
|
4260
|
-
await this.#db.createTable({ tableName: TABLE_SPANS, schema: SPAN_SCHEMA });
|
|
4261
|
-
}
|
|
4262
|
-
async dangerouslyClearAll() {
|
|
4263
|
-
await this.#db.deleteData({ tableName: TABLE_SPANS });
|
|
4264
|
-
}
|
|
4265
|
-
/**
|
|
4266
|
-
* Manually run the spans migration to deduplicate and add the unique constraint.
|
|
4267
|
-
* This is intended to be called from the CLI when duplicates are detected.
|
|
4268
|
-
*
|
|
4269
|
-
* @returns Migration result with status and details
|
|
4270
|
-
*/
|
|
4271
|
-
async migrateSpans() {
|
|
4272
|
-
return this.#db.migrateSpans();
|
|
4273
|
-
}
|
|
4274
|
-
/**
|
|
4275
|
-
* Check migration status for the spans table.
|
|
4276
|
-
* Returns information about whether migration is needed.
|
|
4277
|
-
*/
|
|
4278
|
-
async checkSpansMigrationStatus() {
|
|
4279
|
-
return this.#db.checkSpansMigrationStatus();
|
|
4280
|
-
}
|
|
4281
|
-
get tracingStrategy() {
|
|
4282
|
-
return {
|
|
4283
|
-
preferred: "batch-with-updates",
|
|
4284
|
-
supported: ["batch-with-updates", "insert-only"]
|
|
4285
|
-
};
|
|
4286
|
-
}
|
|
4287
|
-
async createSpan(args) {
|
|
4288
|
-
const { span } = args;
|
|
4289
|
-
try {
|
|
4290
|
-
const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
|
|
4291
|
-
const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
|
|
4292
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4293
|
-
const record = {
|
|
4294
|
-
...span,
|
|
4295
|
-
startedAt,
|
|
4296
|
-
endedAt,
|
|
4297
|
-
createdAt: now,
|
|
4298
|
-
updatedAt: now
|
|
4299
|
-
};
|
|
4300
|
-
return this.#db.insert({ tableName: TABLE_SPANS, record });
|
|
4301
|
-
} catch (error) {
|
|
4302
|
-
throw new MastraError(
|
|
4303
|
-
{
|
|
4304
|
-
id: createStorageErrorId("LIBSQL", "CREATE_SPAN", "FAILED"),
|
|
4305
|
-
domain: ErrorDomain.STORAGE,
|
|
4306
|
-
category: ErrorCategory.USER,
|
|
4307
|
-
details: {
|
|
4308
|
-
spanId: span.spanId,
|
|
4309
|
-
traceId: span.traceId,
|
|
4310
|
-
spanType: span.spanType,
|
|
4311
|
-
name: span.name
|
|
4312
|
-
}
|
|
4313
|
-
},
|
|
4314
|
-
error
|
|
4315
|
-
);
|
|
4316
|
-
}
|
|
4317
|
-
}
|
|
4318
|
-
async getSpan(args) {
|
|
4319
|
-
const { traceId, spanId } = args;
|
|
4369
|
+
// ============================================
|
|
4370
|
+
// Async Buffering Methods
|
|
4371
|
+
// ============================================
|
|
4372
|
+
async updateBufferedObservations(input) {
|
|
4320
4373
|
try {
|
|
4321
|
-
const
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4374
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
4375
|
+
const current = await this.#client.execute({
|
|
4376
|
+
sql: `SELECT "bufferedObservationChunks" FROM "${OM_TABLE}" WHERE id = ?`,
|
|
4377
|
+
args: [input.id]
|
|
4325
4378
|
});
|
|
4326
|
-
if (!rows || rows.length === 0) {
|
|
4327
|
-
|
|
4379
|
+
if (!current.rows || current.rows.length === 0) {
|
|
4380
|
+
throw new MastraError({
|
|
4381
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
|
|
4382
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
4383
|
+
domain: ErrorDomain.STORAGE,
|
|
4384
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4385
|
+
details: { id: input.id }
|
|
4386
|
+
});
|
|
4328
4387
|
}
|
|
4329
|
-
|
|
4330
|
-
|
|
4388
|
+
const row = current.rows[0];
|
|
4389
|
+
let existingChunks = [];
|
|
4390
|
+
if (row.bufferedObservationChunks) {
|
|
4391
|
+
try {
|
|
4392
|
+
const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
|
|
4393
|
+
existingChunks = Array.isArray(parsed) ? parsed : [];
|
|
4394
|
+
} catch {
|
|
4395
|
+
existingChunks = [];
|
|
4396
|
+
}
|
|
4397
|
+
}
|
|
4398
|
+
const newChunk = {
|
|
4399
|
+
id: `ombuf-${randomUUID()}`,
|
|
4400
|
+
cycleId: input.chunk.cycleId,
|
|
4401
|
+
observations: input.chunk.observations,
|
|
4402
|
+
tokenCount: input.chunk.tokenCount,
|
|
4403
|
+
messageIds: input.chunk.messageIds,
|
|
4404
|
+
messageTokens: input.chunk.messageTokens,
|
|
4405
|
+
lastObservedAt: input.chunk.lastObservedAt,
|
|
4406
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
4407
|
+
suggestedContinuation: input.chunk.suggestedContinuation,
|
|
4408
|
+
currentTask: input.chunk.currentTask
|
|
4331
4409
|
};
|
|
4410
|
+
const newChunks = [...existingChunks, newChunk];
|
|
4411
|
+
const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
|
|
4412
|
+
const result = await this.#client.execute({
|
|
4413
|
+
sql: `UPDATE "${OM_TABLE}" SET
|
|
4414
|
+
"bufferedObservationChunks" = ?,
|
|
4415
|
+
"lastBufferedAtTime" = COALESCE(?, "lastBufferedAtTime"),
|
|
4416
|
+
"updatedAt" = ?
|
|
4417
|
+
WHERE id = ?`,
|
|
4418
|
+
args: [JSON.stringify(newChunks), lastBufferedAtTime, nowStr, input.id]
|
|
4419
|
+
});
|
|
4420
|
+
if (result.rowsAffected === 0) {
|
|
4421
|
+
throw new MastraError({
|
|
4422
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
|
|
4423
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
4424
|
+
domain: ErrorDomain.STORAGE,
|
|
4425
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4426
|
+
details: { id: input.id }
|
|
4427
|
+
});
|
|
4428
|
+
}
|
|
4332
4429
|
} catch (error) {
|
|
4430
|
+
if (error instanceof MastraError) {
|
|
4431
|
+
throw error;
|
|
4432
|
+
}
|
|
4333
4433
|
throw new MastraError(
|
|
4334
4434
|
{
|
|
4335
|
-
id: createStorageErrorId("LIBSQL", "
|
|
4435
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "FAILED"),
|
|
4336
4436
|
domain: ErrorDomain.STORAGE,
|
|
4337
|
-
category: ErrorCategory.
|
|
4338
|
-
details: {
|
|
4437
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4438
|
+
details: { id: input.id }
|
|
4339
4439
|
},
|
|
4340
4440
|
error
|
|
4341
4441
|
);
|
|
4342
4442
|
}
|
|
4343
4443
|
}
|
|
4344
|
-
async
|
|
4345
|
-
const { traceId } = args;
|
|
4444
|
+
async swapBufferedToActive(input) {
|
|
4346
4445
|
try {
|
|
4347
|
-
const
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4446
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
4447
|
+
const current = await this.#client.execute({
|
|
4448
|
+
sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
|
|
4449
|
+
args: [input.id]
|
|
4351
4450
|
});
|
|
4352
|
-
if (!rows || rows.length === 0) {
|
|
4353
|
-
|
|
4451
|
+
if (!current.rows || current.rows.length === 0) {
|
|
4452
|
+
throw new MastraError({
|
|
4453
|
+
id: createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
|
|
4454
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
4455
|
+
domain: ErrorDomain.STORAGE,
|
|
4456
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4457
|
+
details: { id: input.id }
|
|
4458
|
+
});
|
|
4459
|
+
}
|
|
4460
|
+
const row = current.rows[0];
|
|
4461
|
+
let chunks = [];
|
|
4462
|
+
if (row.bufferedObservationChunks) {
|
|
4463
|
+
try {
|
|
4464
|
+
const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
|
|
4465
|
+
chunks = Array.isArray(parsed) ? parsed : [];
|
|
4466
|
+
} catch {
|
|
4467
|
+
chunks = [];
|
|
4468
|
+
}
|
|
4469
|
+
}
|
|
4470
|
+
if (chunks.length === 0) {
|
|
4471
|
+
return {
|
|
4472
|
+
chunksActivated: 0,
|
|
4473
|
+
messageTokensActivated: 0,
|
|
4474
|
+
observationTokensActivated: 0,
|
|
4475
|
+
messagesActivated: 0,
|
|
4476
|
+
activatedCycleIds: [],
|
|
4477
|
+
activatedMessageIds: []
|
|
4478
|
+
};
|
|
4479
|
+
}
|
|
4480
|
+
const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
|
|
4481
|
+
const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
|
|
4482
|
+
let cumulativeMessageTokens = 0;
|
|
4483
|
+
let bestBoundary = 0;
|
|
4484
|
+
let bestBoundaryMessageTokens = 0;
|
|
4485
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
4486
|
+
cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
|
|
4487
|
+
const boundary = i + 1;
|
|
4488
|
+
const isUnder = cumulativeMessageTokens <= targetMessageTokens;
|
|
4489
|
+
const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
|
|
4490
|
+
if (bestBoundary === 0) {
|
|
4491
|
+
bestBoundary = boundary;
|
|
4492
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
4493
|
+
} else if (isUnder && !bestIsUnder) {
|
|
4494
|
+
bestBoundary = boundary;
|
|
4495
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
4496
|
+
} else if (isUnder && bestIsUnder) {
|
|
4497
|
+
if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
|
|
4498
|
+
bestBoundary = boundary;
|
|
4499
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
4500
|
+
}
|
|
4501
|
+
} else if (!isUnder && !bestIsUnder) {
|
|
4502
|
+
if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
|
|
4503
|
+
bestBoundary = boundary;
|
|
4504
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
4505
|
+
}
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
const chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
|
|
4509
|
+
const activatedChunks = chunks.slice(0, chunksToActivate);
|
|
4510
|
+
const remainingChunks = chunks.slice(chunksToActivate);
|
|
4511
|
+
const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
|
|
4512
|
+
const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
|
|
4513
|
+
const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
|
|
4514
|
+
const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
|
|
4515
|
+
const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
|
|
4516
|
+
const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
|
|
4517
|
+
const latestChunk = activatedChunks[activatedChunks.length - 1];
|
|
4518
|
+
const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
|
|
4519
|
+
const lastObservedAtStr = lastObservedAt.toISOString();
|
|
4520
|
+
const existingActive = row.activeObservations || "";
|
|
4521
|
+
const existingTokenCount = Number(row.observationTokenCount || 0);
|
|
4522
|
+
const newActive = existingActive ? `${existingActive}
|
|
4523
|
+
|
|
4524
|
+
${activatedContent}` : activatedContent;
|
|
4525
|
+
const newTokenCount = existingTokenCount + activatedTokens;
|
|
4526
|
+
const existingPending = Number(row.pendingMessageTokens || 0);
|
|
4527
|
+
const newPending = Math.max(0, existingPending - activatedMessageTokens);
|
|
4528
|
+
await this.#client.execute({
|
|
4529
|
+
sql: `UPDATE "${OM_TABLE}" SET
|
|
4530
|
+
"activeObservations" = ?,
|
|
4531
|
+
"observationTokenCount" = ?,
|
|
4532
|
+
"pendingMessageTokens" = ?,
|
|
4533
|
+
"bufferedObservationChunks" = ?,
|
|
4534
|
+
"lastObservedAt" = ?,
|
|
4535
|
+
"updatedAt" = ?
|
|
4536
|
+
WHERE id = ?`,
|
|
4537
|
+
args: [
|
|
4538
|
+
newActive,
|
|
4539
|
+
newTokenCount,
|
|
4540
|
+
newPending,
|
|
4541
|
+
remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
|
|
4542
|
+
lastObservedAtStr,
|
|
4543
|
+
nowStr,
|
|
4544
|
+
input.id
|
|
4545
|
+
]
|
|
4546
|
+
});
|
|
4547
|
+
return {
|
|
4548
|
+
chunksActivated: activatedChunks.length,
|
|
4549
|
+
messageTokensActivated: activatedMessageTokens,
|
|
4550
|
+
observationTokensActivated: activatedTokens,
|
|
4551
|
+
messagesActivated: activatedMessageCount,
|
|
4552
|
+
activatedCycleIds,
|
|
4553
|
+
activatedMessageIds,
|
|
4554
|
+
observations: activatedContent,
|
|
4555
|
+
perChunk: activatedChunks.map((c) => ({
|
|
4556
|
+
cycleId: c.cycleId ?? "",
|
|
4557
|
+
messageTokens: c.messageTokens ?? 0,
|
|
4558
|
+
observationTokens: c.tokenCount,
|
|
4559
|
+
messageCount: c.messageIds.length,
|
|
4560
|
+
observations: c.observations
|
|
4561
|
+
}))
|
|
4562
|
+
};
|
|
4563
|
+
} catch (error) {
|
|
4564
|
+
if (error instanceof MastraError) {
|
|
4565
|
+
throw error;
|
|
4566
|
+
}
|
|
4567
|
+
throw new MastraError(
|
|
4568
|
+
{
|
|
4569
|
+
id: createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "FAILED"),
|
|
4570
|
+
domain: ErrorDomain.STORAGE,
|
|
4571
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4572
|
+
details: { id: input.id }
|
|
4573
|
+
},
|
|
4574
|
+
error
|
|
4575
|
+
);
|
|
4576
|
+
}
|
|
4577
|
+
}
|
|
4578
|
+
async updateBufferedReflection(input) {
|
|
4579
|
+
try {
|
|
4580
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
4581
|
+
const result = await this.#client.execute({
|
|
4582
|
+
sql: `UPDATE "${OM_TABLE}" SET
|
|
4583
|
+
"bufferedReflection" = CASE
|
|
4584
|
+
WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
|
|
4585
|
+
THEN "bufferedReflection" || char(10) || char(10) || ?
|
|
4586
|
+
ELSE ?
|
|
4587
|
+
END,
|
|
4588
|
+
"bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + ?,
|
|
4589
|
+
"bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + ?,
|
|
4590
|
+
"reflectedObservationLineCount" = ?,
|
|
4591
|
+
"updatedAt" = ?
|
|
4592
|
+
WHERE id = ?`,
|
|
4593
|
+
args: [
|
|
4594
|
+
input.reflection,
|
|
4595
|
+
input.reflection,
|
|
4596
|
+
input.tokenCount,
|
|
4597
|
+
input.inputTokenCount,
|
|
4598
|
+
input.reflectedObservationLineCount,
|
|
4599
|
+
nowStr,
|
|
4600
|
+
input.id
|
|
4601
|
+
]
|
|
4602
|
+
});
|
|
4603
|
+
if (result.rowsAffected === 0) {
|
|
4604
|
+
throw new MastraError({
|
|
4605
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
|
|
4606
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
4607
|
+
domain: ErrorDomain.STORAGE,
|
|
4608
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4609
|
+
details: { id: input.id }
|
|
4610
|
+
});
|
|
4611
|
+
}
|
|
4612
|
+
} catch (error) {
|
|
4613
|
+
if (error instanceof MastraError) {
|
|
4614
|
+
throw error;
|
|
4615
|
+
}
|
|
4616
|
+
throw new MastraError(
|
|
4617
|
+
{
|
|
4618
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_REFLECTION", "FAILED"),
|
|
4619
|
+
domain: ErrorDomain.STORAGE,
|
|
4620
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4621
|
+
details: { id: input.id }
|
|
4622
|
+
},
|
|
4623
|
+
error
|
|
4624
|
+
);
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
async swapBufferedReflectionToActive(input) {
|
|
4628
|
+
try {
|
|
4629
|
+
const current = await this.#client.execute({
|
|
4630
|
+
sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
|
|
4631
|
+
args: [input.currentRecord.id]
|
|
4632
|
+
});
|
|
4633
|
+
if (!current.rows || current.rows.length === 0) {
|
|
4634
|
+
throw new MastraError({
|
|
4635
|
+
id: createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
|
|
4636
|
+
text: `Observational memory record not found: ${input.currentRecord.id}`,
|
|
4637
|
+
domain: ErrorDomain.STORAGE,
|
|
4638
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4639
|
+
details: { id: input.currentRecord.id }
|
|
4640
|
+
});
|
|
4641
|
+
}
|
|
4642
|
+
const row = current.rows[0];
|
|
4643
|
+
const bufferedReflection = row.bufferedReflection || "";
|
|
4644
|
+
const reflectedLineCount = Number(row.reflectedObservationLineCount || 0);
|
|
4645
|
+
if (!bufferedReflection) {
|
|
4646
|
+
throw new MastraError({
|
|
4647
|
+
id: createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
|
|
4648
|
+
text: "No buffered reflection to swap",
|
|
4649
|
+
domain: ErrorDomain.STORAGE,
|
|
4650
|
+
category: ErrorCategory.USER,
|
|
4651
|
+
details: { id: input.currentRecord.id }
|
|
4652
|
+
});
|
|
4653
|
+
}
|
|
4654
|
+
const currentObservations = row.activeObservations || "";
|
|
4655
|
+
const allLines = currentObservations.split("\n");
|
|
4656
|
+
const unreflectedLines = allLines.slice(reflectedLineCount);
|
|
4657
|
+
const unreflectedContent = unreflectedLines.join("\n").trim();
|
|
4658
|
+
const newObservations = unreflectedContent ? `${bufferedReflection}
|
|
4659
|
+
|
|
4660
|
+
${unreflectedContent}` : bufferedReflection;
|
|
4661
|
+
const newRecord = await this.createReflectionGeneration({
|
|
4662
|
+
currentRecord: input.currentRecord,
|
|
4663
|
+
reflection: newObservations,
|
|
4664
|
+
tokenCount: input.tokenCount
|
|
4665
|
+
});
|
|
4666
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
4667
|
+
await this.#client.execute({
|
|
4668
|
+
sql: `UPDATE "${OM_TABLE}" SET
|
|
4669
|
+
"bufferedReflection" = NULL,
|
|
4670
|
+
"bufferedReflectionTokens" = NULL,
|
|
4671
|
+
"bufferedReflectionInputTokens" = NULL,
|
|
4672
|
+
"reflectedObservationLineCount" = NULL,
|
|
4673
|
+
"updatedAt" = ?
|
|
4674
|
+
WHERE id = ?`,
|
|
4675
|
+
args: [nowStr, input.currentRecord.id]
|
|
4676
|
+
});
|
|
4677
|
+
return newRecord;
|
|
4678
|
+
} catch (error) {
|
|
4679
|
+
if (error instanceof MastraError) {
|
|
4680
|
+
throw error;
|
|
4681
|
+
}
|
|
4682
|
+
throw new MastraError(
|
|
4683
|
+
{
|
|
4684
|
+
id: createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "FAILED"),
|
|
4685
|
+
domain: ErrorDomain.STORAGE,
|
|
4686
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
4687
|
+
details: { id: input.currentRecord.id }
|
|
4688
|
+
},
|
|
4689
|
+
error
|
|
4690
|
+
);
|
|
4691
|
+
}
|
|
4692
|
+
}
|
|
4693
|
+
};
|
|
4694
|
+
var ObservabilityLibSQL = class extends ObservabilityStorage {
|
|
4695
|
+
#db;
|
|
4696
|
+
constructor(config) {
|
|
4697
|
+
super();
|
|
4698
|
+
const client = resolveClient(config);
|
|
4699
|
+
this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
|
|
4700
|
+
}
|
|
4701
|
+
async init() {
|
|
4702
|
+
await this.#db.createTable({ tableName: TABLE_SPANS, schema: SPAN_SCHEMA });
|
|
4703
|
+
}
|
|
4704
|
+
async dangerouslyClearAll() {
|
|
4705
|
+
await this.#db.deleteData({ tableName: TABLE_SPANS });
|
|
4706
|
+
}
|
|
4707
|
+
/**
|
|
4708
|
+
* Manually run the spans migration to deduplicate and add the unique constraint.
|
|
4709
|
+
* This is intended to be called from the CLI when duplicates are detected.
|
|
4710
|
+
*
|
|
4711
|
+
* @returns Migration result with status and details
|
|
4712
|
+
*/
|
|
4713
|
+
async migrateSpans() {
|
|
4714
|
+
return this.#db.migrateSpans();
|
|
4715
|
+
}
|
|
4716
|
+
/**
|
|
4717
|
+
* Check migration status for the spans table.
|
|
4718
|
+
* Returns information about whether migration is needed.
|
|
4719
|
+
*/
|
|
4720
|
+
async checkSpansMigrationStatus() {
|
|
4721
|
+
return this.#db.checkSpansMigrationStatus();
|
|
4722
|
+
}
|
|
4723
|
+
get tracingStrategy() {
|
|
4724
|
+
return {
|
|
4725
|
+
preferred: "batch-with-updates",
|
|
4726
|
+
supported: ["batch-with-updates", "insert-only"]
|
|
4727
|
+
};
|
|
4728
|
+
}
|
|
4729
|
+
async createSpan(args) {
|
|
4730
|
+
const { span } = args;
|
|
4731
|
+
try {
|
|
4732
|
+
const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
|
|
4733
|
+
const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
|
|
4734
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4735
|
+
const record = {
|
|
4736
|
+
...span,
|
|
4737
|
+
startedAt,
|
|
4738
|
+
endedAt,
|
|
4739
|
+
createdAt: now,
|
|
4740
|
+
updatedAt: now
|
|
4741
|
+
};
|
|
4742
|
+
return this.#db.insert({ tableName: TABLE_SPANS, record });
|
|
4743
|
+
} catch (error) {
|
|
4744
|
+
throw new MastraError(
|
|
4745
|
+
{
|
|
4746
|
+
id: createStorageErrorId("LIBSQL", "CREATE_SPAN", "FAILED"),
|
|
4747
|
+
domain: ErrorDomain.STORAGE,
|
|
4748
|
+
category: ErrorCategory.USER,
|
|
4749
|
+
details: {
|
|
4750
|
+
spanId: span.spanId,
|
|
4751
|
+
traceId: span.traceId,
|
|
4752
|
+
spanType: span.spanType,
|
|
4753
|
+
name: span.name
|
|
4754
|
+
}
|
|
4755
|
+
},
|
|
4756
|
+
error
|
|
4757
|
+
);
|
|
4758
|
+
}
|
|
4759
|
+
}
|
|
4760
|
+
async getSpan(args) {
|
|
4761
|
+
const { traceId, spanId } = args;
|
|
4762
|
+
try {
|
|
4763
|
+
const rows = await this.#db.selectMany({
|
|
4764
|
+
tableName: TABLE_SPANS,
|
|
4765
|
+
whereClause: { sql: " WHERE traceId = ? AND spanId = ?", args: [traceId, spanId] },
|
|
4766
|
+
limit: 1
|
|
4767
|
+
});
|
|
4768
|
+
if (!rows || rows.length === 0) {
|
|
4769
|
+
return null;
|
|
4770
|
+
}
|
|
4771
|
+
return {
|
|
4772
|
+
span: transformFromSqlRow({ tableName: TABLE_SPANS, sqlRow: rows[0] })
|
|
4773
|
+
};
|
|
4774
|
+
} catch (error) {
|
|
4775
|
+
throw new MastraError(
|
|
4776
|
+
{
|
|
4777
|
+
id: createStorageErrorId("LIBSQL", "GET_SPAN", "FAILED"),
|
|
4778
|
+
domain: ErrorDomain.STORAGE,
|
|
4779
|
+
category: ErrorCategory.USER,
|
|
4780
|
+
details: { traceId, spanId }
|
|
4781
|
+
},
|
|
4782
|
+
error
|
|
4783
|
+
);
|
|
4784
|
+
}
|
|
4785
|
+
}
|
|
4786
|
+
async getRootSpan(args) {
|
|
4787
|
+
const { traceId } = args;
|
|
4788
|
+
try {
|
|
4789
|
+
const rows = await this.#db.selectMany({
|
|
4790
|
+
tableName: TABLE_SPANS,
|
|
4791
|
+
whereClause: { sql: " WHERE traceId = ? AND parentSpanId IS NULL", args: [traceId] },
|
|
4792
|
+
limit: 1
|
|
4793
|
+
});
|
|
4794
|
+
if (!rows || rows.length === 0) {
|
|
4795
|
+
return null;
|
|
4354
4796
|
}
|
|
4355
4797
|
return {
|
|
4356
4798
|
span: transformFromSqlRow({ tableName: TABLE_SPANS, sqlRow: rows[0] })
|
|
@@ -4700,6 +5142,1040 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
|
|
|
4700
5142
|
}
|
|
4701
5143
|
}
|
|
4702
5144
|
};
|
|
5145
|
+
var SNAPSHOT_FIELDS2 = ["name", "description", "content", "rules"];
|
|
5146
|
+
var PromptBlocksLibSQL = class extends PromptBlocksStorage {
|
|
5147
|
+
#db;
|
|
5148
|
+
#client;
|
|
5149
|
+
constructor(config) {
|
|
5150
|
+
super();
|
|
5151
|
+
const client = resolveClient(config);
|
|
5152
|
+
this.#client = client;
|
|
5153
|
+
this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
|
|
5154
|
+
}
|
|
5155
|
+
async init() {
|
|
5156
|
+
await this.#db.createTable({ tableName: TABLE_PROMPT_BLOCKS, schema: PROMPT_BLOCKS_SCHEMA });
|
|
5157
|
+
await this.#db.createTable({ tableName: TABLE_PROMPT_BLOCK_VERSIONS, schema: PROMPT_BLOCK_VERSIONS_SCHEMA });
|
|
5158
|
+
await this.#client.execute(
|
|
5159
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS idx_prompt_block_versions_block_version ON "${TABLE_PROMPT_BLOCK_VERSIONS}" ("blockId", "versionNumber")`
|
|
5160
|
+
);
|
|
5161
|
+
}
|
|
5162
|
+
async dangerouslyClearAll() {
|
|
5163
|
+
await this.#db.deleteData({ tableName: TABLE_PROMPT_BLOCKS });
|
|
5164
|
+
await this.#db.deleteData({ tableName: TABLE_PROMPT_BLOCK_VERSIONS });
|
|
5165
|
+
}
|
|
5166
|
+
// ==========================================================================
|
|
5167
|
+
// Prompt Block CRUD
|
|
5168
|
+
// ==========================================================================
|
|
5169
|
+
async getById(id) {
|
|
5170
|
+
try {
|
|
5171
|
+
const result = await this.#client.execute({
|
|
5172
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCKS)} FROM "${TABLE_PROMPT_BLOCKS}" WHERE id = ?`,
|
|
5173
|
+
args: [id]
|
|
5174
|
+
});
|
|
5175
|
+
const row = result.rows?.[0];
|
|
5176
|
+
return row ? this.#parseBlockRow(row) : null;
|
|
5177
|
+
} catch (error) {
|
|
5178
|
+
if (error instanceof MastraError) throw error;
|
|
5179
|
+
throw new MastraError(
|
|
5180
|
+
{
|
|
5181
|
+
id: createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK", "FAILED"),
|
|
5182
|
+
domain: ErrorDomain.STORAGE,
|
|
5183
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5184
|
+
},
|
|
5185
|
+
error
|
|
5186
|
+
);
|
|
5187
|
+
}
|
|
5188
|
+
}
|
|
5189
|
+
async create(input) {
|
|
5190
|
+
const { promptBlock } = input;
|
|
5191
|
+
try {
|
|
5192
|
+
const now = /* @__PURE__ */ new Date();
|
|
5193
|
+
await this.#db.insert({
|
|
5194
|
+
tableName: TABLE_PROMPT_BLOCKS,
|
|
5195
|
+
record: {
|
|
5196
|
+
id: promptBlock.id,
|
|
5197
|
+
status: "draft",
|
|
5198
|
+
activeVersionId: null,
|
|
5199
|
+
authorId: promptBlock.authorId ?? null,
|
|
5200
|
+
metadata: promptBlock.metadata ?? null,
|
|
5201
|
+
createdAt: now.toISOString(),
|
|
5202
|
+
updatedAt: now.toISOString()
|
|
5203
|
+
}
|
|
5204
|
+
});
|
|
5205
|
+
const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = promptBlock;
|
|
5206
|
+
const versionId = crypto.randomUUID();
|
|
5207
|
+
await this.createVersion({
|
|
5208
|
+
id: versionId,
|
|
5209
|
+
blockId: promptBlock.id,
|
|
5210
|
+
versionNumber: 1,
|
|
5211
|
+
...snapshotConfig,
|
|
5212
|
+
changedFields: Object.keys(snapshotConfig),
|
|
5213
|
+
changeMessage: "Initial version"
|
|
5214
|
+
});
|
|
5215
|
+
return {
|
|
5216
|
+
id: promptBlock.id,
|
|
5217
|
+
status: "draft",
|
|
5218
|
+
activeVersionId: void 0,
|
|
5219
|
+
authorId: promptBlock.authorId,
|
|
5220
|
+
metadata: promptBlock.metadata,
|
|
5221
|
+
createdAt: now,
|
|
5222
|
+
updatedAt: now
|
|
5223
|
+
};
|
|
5224
|
+
} catch (error) {
|
|
5225
|
+
if (error instanceof MastraError) throw error;
|
|
5226
|
+
throw new MastraError(
|
|
5227
|
+
{
|
|
5228
|
+
id: createStorageErrorId("LIBSQL", "CREATE_PROMPT_BLOCK", "FAILED"),
|
|
5229
|
+
domain: ErrorDomain.STORAGE,
|
|
5230
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5231
|
+
},
|
|
5232
|
+
error
|
|
5233
|
+
);
|
|
5234
|
+
}
|
|
5235
|
+
}
|
|
5236
|
+
async update(input) {
|
|
5237
|
+
const { id, ...updates } = input;
|
|
5238
|
+
try {
|
|
5239
|
+
const existing = await this.getById(id);
|
|
5240
|
+
if (!existing) {
|
|
5241
|
+
throw new Error(`Prompt block with id ${id} not found`);
|
|
5242
|
+
}
|
|
5243
|
+
const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
|
|
5244
|
+
const configFieldNames = SNAPSHOT_FIELDS2;
|
|
5245
|
+
const hasConfigUpdate = configFieldNames.some((field) => field in configFields);
|
|
5246
|
+
const updateData = {
|
|
5247
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5248
|
+
};
|
|
5249
|
+
if (authorId !== void 0) updateData.authorId = authorId;
|
|
5250
|
+
if (activeVersionId !== void 0) {
|
|
5251
|
+
updateData.activeVersionId = activeVersionId;
|
|
5252
|
+
if (status === void 0) {
|
|
5253
|
+
updateData.status = "published";
|
|
5254
|
+
}
|
|
5255
|
+
}
|
|
5256
|
+
if (status !== void 0) updateData.status = status;
|
|
5257
|
+
if (metadata !== void 0) {
|
|
5258
|
+
updateData.metadata = { ...existing.metadata, ...metadata };
|
|
5259
|
+
}
|
|
5260
|
+
await this.#db.update({
|
|
5261
|
+
tableName: TABLE_PROMPT_BLOCKS,
|
|
5262
|
+
keys: { id },
|
|
5263
|
+
data: updateData
|
|
5264
|
+
});
|
|
5265
|
+
if (hasConfigUpdate) {
|
|
5266
|
+
const latestVersion = await this.getLatestVersion(id);
|
|
5267
|
+
if (!latestVersion) {
|
|
5268
|
+
throw new Error(`No versions found for prompt block ${id}`);
|
|
5269
|
+
}
|
|
5270
|
+
const {
|
|
5271
|
+
id: _versionId,
|
|
5272
|
+
blockId: _blockId,
|
|
5273
|
+
versionNumber: _versionNumber,
|
|
5274
|
+
changedFields: _changedFields,
|
|
5275
|
+
changeMessage: _changeMessage,
|
|
5276
|
+
createdAt: _createdAt,
|
|
5277
|
+
...latestConfig
|
|
5278
|
+
} = latestVersion;
|
|
5279
|
+
const newConfig = { ...latestConfig, ...configFields };
|
|
5280
|
+
const changedFields = configFieldNames.filter(
|
|
5281
|
+
(field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
|
|
5282
|
+
);
|
|
5283
|
+
const newVersionId = crypto.randomUUID();
|
|
5284
|
+
await this.createVersion({
|
|
5285
|
+
id: newVersionId,
|
|
5286
|
+
blockId: id,
|
|
5287
|
+
versionNumber: latestVersion.versionNumber + 1,
|
|
5288
|
+
...newConfig,
|
|
5289
|
+
changedFields,
|
|
5290
|
+
changeMessage: `Updated ${changedFields.join(", ")}`
|
|
5291
|
+
});
|
|
5292
|
+
}
|
|
5293
|
+
const updated = await this.getById(id);
|
|
5294
|
+
if (!updated) {
|
|
5295
|
+
throw new MastraError({
|
|
5296
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
|
|
5297
|
+
domain: ErrorDomain.STORAGE,
|
|
5298
|
+
category: ErrorCategory.SYSTEM,
|
|
5299
|
+
text: `Prompt block ${id} not found after update`,
|
|
5300
|
+
details: { id }
|
|
5301
|
+
});
|
|
5302
|
+
}
|
|
5303
|
+
return updated;
|
|
5304
|
+
} catch (error) {
|
|
5305
|
+
if (error instanceof MastraError) throw error;
|
|
5306
|
+
throw new MastraError(
|
|
5307
|
+
{
|
|
5308
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_PROMPT_BLOCK", "FAILED"),
|
|
5309
|
+
domain: ErrorDomain.STORAGE,
|
|
5310
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5311
|
+
},
|
|
5312
|
+
error
|
|
5313
|
+
);
|
|
5314
|
+
}
|
|
5315
|
+
}
|
|
5316
|
+
async delete(id) {
|
|
5317
|
+
try {
|
|
5318
|
+
await this.deleteVersionsByParentId(id);
|
|
5319
|
+
await this.#client.execute({
|
|
5320
|
+
sql: `DELETE FROM "${TABLE_PROMPT_BLOCKS}" WHERE "id" = ?`,
|
|
5321
|
+
args: [id]
|
|
5322
|
+
});
|
|
5323
|
+
} catch (error) {
|
|
5324
|
+
if (error instanceof MastraError) throw error;
|
|
5325
|
+
throw new MastraError(
|
|
5326
|
+
{
|
|
5327
|
+
id: createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK", "FAILED"),
|
|
5328
|
+
domain: ErrorDomain.STORAGE,
|
|
5329
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5330
|
+
},
|
|
5331
|
+
error
|
|
5332
|
+
);
|
|
5333
|
+
}
|
|
5334
|
+
}
|
|
5335
|
+
async list(args) {
|
|
5336
|
+
try {
|
|
5337
|
+
const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
|
|
5338
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
5339
|
+
const conditions = [];
|
|
5340
|
+
const queryParams = [];
|
|
5341
|
+
if (authorId !== void 0) {
|
|
5342
|
+
conditions.push("authorId = ?");
|
|
5343
|
+
queryParams.push(authorId);
|
|
5344
|
+
}
|
|
5345
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
5346
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
5347
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
5348
|
+
throw new MastraError({
|
|
5349
|
+
id: createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCKS", "INVALID_METADATA_KEY"),
|
|
5350
|
+
domain: ErrorDomain.STORAGE,
|
|
5351
|
+
category: ErrorCategory.USER,
|
|
5352
|
+
text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
|
|
5353
|
+
details: { key }
|
|
5354
|
+
});
|
|
5355
|
+
}
|
|
5356
|
+
conditions.push(`json_extract(metadata, '$.${key}') = ?`);
|
|
5357
|
+
queryParams.push(typeof value === "string" ? value : JSON.stringify(value));
|
|
5358
|
+
}
|
|
5359
|
+
}
|
|
5360
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
5361
|
+
const countResult = await this.#client.execute({
|
|
5362
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_PROMPT_BLOCKS}" ${whereClause}`,
|
|
5363
|
+
args: queryParams
|
|
5364
|
+
});
|
|
5365
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
5366
|
+
if (total === 0) {
|
|
5367
|
+
return {
|
|
5368
|
+
promptBlocks: [],
|
|
5369
|
+
total: 0,
|
|
5370
|
+
page,
|
|
5371
|
+
perPage: perPageInput ?? 100,
|
|
5372
|
+
hasMore: false
|
|
5373
|
+
};
|
|
5374
|
+
}
|
|
5375
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
5376
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
5377
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
5378
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
5379
|
+
const result = await this.#client.execute({
|
|
5380
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCKS)} FROM "${TABLE_PROMPT_BLOCKS}" ${whereClause} ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
|
|
5381
|
+
args: [...queryParams, limitValue, start]
|
|
5382
|
+
});
|
|
5383
|
+
const promptBlocks = result.rows?.map((row) => this.#parseBlockRow(row)) ?? [];
|
|
5384
|
+
return {
|
|
5385
|
+
promptBlocks,
|
|
5386
|
+
total,
|
|
5387
|
+
page,
|
|
5388
|
+
perPage: perPageForResponse,
|
|
5389
|
+
hasMore: end < total
|
|
5390
|
+
};
|
|
5391
|
+
} catch (error) {
|
|
5392
|
+
if (error instanceof MastraError) throw error;
|
|
5393
|
+
throw new MastraError(
|
|
5394
|
+
{
|
|
5395
|
+
id: createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCKS", "FAILED"),
|
|
5396
|
+
domain: ErrorDomain.STORAGE,
|
|
5397
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5398
|
+
},
|
|
5399
|
+
error
|
|
5400
|
+
);
|
|
5401
|
+
}
|
|
5402
|
+
}
|
|
5403
|
+
// ==========================================================================
|
|
5404
|
+
// Prompt Block Version Methods
|
|
5405
|
+
// ==========================================================================
|
|
5406
|
+
async createVersion(input) {
|
|
5407
|
+
try {
|
|
5408
|
+
const now = /* @__PURE__ */ new Date();
|
|
5409
|
+
await this.#db.insert({
|
|
5410
|
+
tableName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
5411
|
+
record: {
|
|
5412
|
+
id: input.id,
|
|
5413
|
+
blockId: input.blockId,
|
|
5414
|
+
versionNumber: input.versionNumber,
|
|
5415
|
+
name: input.name,
|
|
5416
|
+
description: input.description ?? null,
|
|
5417
|
+
content: input.content,
|
|
5418
|
+
rules: input.rules ?? null,
|
|
5419
|
+
changedFields: input.changedFields ?? null,
|
|
5420
|
+
changeMessage: input.changeMessage ?? null,
|
|
5421
|
+
createdAt: now.toISOString()
|
|
5422
|
+
}
|
|
5423
|
+
});
|
|
5424
|
+
return {
|
|
5425
|
+
...input,
|
|
5426
|
+
createdAt: now
|
|
5427
|
+
};
|
|
5428
|
+
} catch (error) {
|
|
5429
|
+
if (error instanceof MastraError) throw error;
|
|
5430
|
+
throw new MastraError(
|
|
5431
|
+
{
|
|
5432
|
+
id: createStorageErrorId("LIBSQL", "CREATE_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
5433
|
+
domain: ErrorDomain.STORAGE,
|
|
5434
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5435
|
+
},
|
|
5436
|
+
error
|
|
5437
|
+
);
|
|
5438
|
+
}
|
|
5439
|
+
}
|
|
5440
|
+
async getVersion(id) {
|
|
5441
|
+
try {
|
|
5442
|
+
const result = await this.#client.execute({
|
|
5443
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE id = ?`,
|
|
5444
|
+
args: [id]
|
|
5445
|
+
});
|
|
5446
|
+
const row = result.rows?.[0];
|
|
5447
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
5448
|
+
} catch (error) {
|
|
5449
|
+
if (error instanceof MastraError) throw error;
|
|
5450
|
+
throw new MastraError(
|
|
5451
|
+
{
|
|
5452
|
+
id: createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
5453
|
+
domain: ErrorDomain.STORAGE,
|
|
5454
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5455
|
+
},
|
|
5456
|
+
error
|
|
5457
|
+
);
|
|
5458
|
+
}
|
|
5459
|
+
}
|
|
5460
|
+
async getVersionByNumber(blockId, versionNumber) {
|
|
5461
|
+
try {
|
|
5462
|
+
const result = await this.#client.execute({
|
|
5463
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? AND versionNumber = ?`,
|
|
5464
|
+
args: [blockId, versionNumber]
|
|
5465
|
+
});
|
|
5466
|
+
const row = result.rows?.[0];
|
|
5467
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
5468
|
+
} catch (error) {
|
|
5469
|
+
if (error instanceof MastraError) throw error;
|
|
5470
|
+
throw new MastraError(
|
|
5471
|
+
{
|
|
5472
|
+
id: createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK_VERSION_BY_NUMBER", "FAILED"),
|
|
5473
|
+
domain: ErrorDomain.STORAGE,
|
|
5474
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5475
|
+
},
|
|
5476
|
+
error
|
|
5477
|
+
);
|
|
5478
|
+
}
|
|
5479
|
+
}
|
|
5480
|
+
async getLatestVersion(blockId) {
|
|
5481
|
+
try {
|
|
5482
|
+
const result = await this.#client.execute({
|
|
5483
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? ORDER BY versionNumber DESC LIMIT 1`,
|
|
5484
|
+
args: [blockId]
|
|
5485
|
+
});
|
|
5486
|
+
const row = result.rows?.[0];
|
|
5487
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
5488
|
+
} catch (error) {
|
|
5489
|
+
if (error instanceof MastraError) throw error;
|
|
5490
|
+
throw new MastraError(
|
|
5491
|
+
{
|
|
5492
|
+
id: createStorageErrorId("LIBSQL", "GET_LATEST_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
5493
|
+
domain: ErrorDomain.STORAGE,
|
|
5494
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5495
|
+
},
|
|
5496
|
+
error
|
|
5497
|
+
);
|
|
5498
|
+
}
|
|
5499
|
+
}
|
|
5500
|
+
async listVersions(input) {
|
|
5501
|
+
try {
|
|
5502
|
+
const { blockId, page = 0, perPage: perPageInput, orderBy } = input;
|
|
5503
|
+
const { field, direction } = this.parseVersionOrderBy(orderBy);
|
|
5504
|
+
const countResult = await this.#client.execute({
|
|
5505
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ?`,
|
|
5506
|
+
args: [blockId]
|
|
5507
|
+
});
|
|
5508
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
5509
|
+
if (total === 0) {
|
|
5510
|
+
return {
|
|
5511
|
+
versions: [],
|
|
5512
|
+
total: 0,
|
|
5513
|
+
page,
|
|
5514
|
+
perPage: perPageInput ?? 20,
|
|
5515
|
+
hasMore: false
|
|
5516
|
+
};
|
|
5517
|
+
}
|
|
5518
|
+
const perPage = normalizePerPage(perPageInput, 20);
|
|
5519
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
5520
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
5521
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
5522
|
+
const result = await this.#client.execute({
|
|
5523
|
+
sql: `SELECT ${buildSelectColumns(TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
|
|
5524
|
+
args: [blockId, limitValue, start]
|
|
5525
|
+
});
|
|
5526
|
+
const versions = result.rows?.map((row) => this.#parseVersionRow(row)) ?? [];
|
|
5527
|
+
return {
|
|
5528
|
+
versions,
|
|
5529
|
+
total,
|
|
5530
|
+
page,
|
|
5531
|
+
perPage: perPageForResponse,
|
|
5532
|
+
hasMore: end < total
|
|
5533
|
+
};
|
|
5534
|
+
} catch (error) {
|
|
5535
|
+
if (error instanceof MastraError) throw error;
|
|
5536
|
+
throw new MastraError(
|
|
5537
|
+
{
|
|
5538
|
+
id: createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCK_VERSIONS", "FAILED"),
|
|
5539
|
+
domain: ErrorDomain.STORAGE,
|
|
5540
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5541
|
+
},
|
|
5542
|
+
error
|
|
5543
|
+
);
|
|
5544
|
+
}
|
|
5545
|
+
}
|
|
5546
|
+
async deleteVersion(id) {
|
|
5547
|
+
try {
|
|
5548
|
+
await this.#client.execute({
|
|
5549
|
+
sql: `DELETE FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE "id" = ?`,
|
|
5550
|
+
args: [id]
|
|
5551
|
+
});
|
|
5552
|
+
} catch (error) {
|
|
5553
|
+
if (error instanceof MastraError) throw error;
|
|
5554
|
+
throw new MastraError(
|
|
5555
|
+
{
|
|
5556
|
+
id: createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
5557
|
+
domain: ErrorDomain.STORAGE,
|
|
5558
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5559
|
+
},
|
|
5560
|
+
error
|
|
5561
|
+
);
|
|
5562
|
+
}
|
|
5563
|
+
}
|
|
5564
|
+
async deleteVersionsByParentId(entityId) {
|
|
5565
|
+
try {
|
|
5566
|
+
await this.#client.execute({
|
|
5567
|
+
sql: `DELETE FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE "blockId" = ?`,
|
|
5568
|
+
args: [entityId]
|
|
5569
|
+
});
|
|
5570
|
+
} catch (error) {
|
|
5571
|
+
if (error instanceof MastraError) throw error;
|
|
5572
|
+
throw new MastraError(
|
|
5573
|
+
{
|
|
5574
|
+
id: createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK_VERSIONS_BY_BLOCK", "FAILED"),
|
|
5575
|
+
domain: ErrorDomain.STORAGE,
|
|
5576
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5577
|
+
},
|
|
5578
|
+
error
|
|
5579
|
+
);
|
|
5580
|
+
}
|
|
5581
|
+
}
|
|
5582
|
+
async countVersions(blockId) {
|
|
5583
|
+
try {
|
|
5584
|
+
const result = await this.#client.execute({
|
|
5585
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ?`,
|
|
5586
|
+
args: [blockId]
|
|
5587
|
+
});
|
|
5588
|
+
return Number(result.rows?.[0]?.count ?? 0);
|
|
5589
|
+
} catch (error) {
|
|
5590
|
+
if (error instanceof MastraError) throw error;
|
|
5591
|
+
throw new MastraError(
|
|
5592
|
+
{
|
|
5593
|
+
id: createStorageErrorId("LIBSQL", "COUNT_PROMPT_BLOCK_VERSIONS", "FAILED"),
|
|
5594
|
+
domain: ErrorDomain.STORAGE,
|
|
5595
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5596
|
+
},
|
|
5597
|
+
error
|
|
5598
|
+
);
|
|
5599
|
+
}
|
|
5600
|
+
}
|
|
5601
|
+
// ==========================================================================
|
|
5602
|
+
// Private Helpers
|
|
5603
|
+
// ==========================================================================
|
|
5604
|
+
#parseBlockRow(row) {
|
|
5605
|
+
const safeParseJSON = (val) => {
|
|
5606
|
+
if (val === null || val === void 0) return void 0;
|
|
5607
|
+
if (typeof val === "string") {
|
|
5608
|
+
try {
|
|
5609
|
+
return JSON.parse(val);
|
|
5610
|
+
} catch {
|
|
5611
|
+
return val;
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
return val;
|
|
5615
|
+
};
|
|
5616
|
+
return {
|
|
5617
|
+
id: row.id,
|
|
5618
|
+
status: row.status ?? "draft",
|
|
5619
|
+
activeVersionId: row.activeVersionId ?? void 0,
|
|
5620
|
+
authorId: row.authorId ?? void 0,
|
|
5621
|
+
metadata: safeParseJSON(row.metadata),
|
|
5622
|
+
createdAt: new Date(row.createdAt),
|
|
5623
|
+
updatedAt: new Date(row.updatedAt)
|
|
5624
|
+
};
|
|
5625
|
+
}
|
|
5626
|
+
#parseVersionRow(row) {
|
|
5627
|
+
const safeParseJSON = (val) => {
|
|
5628
|
+
if (val === null || val === void 0) return void 0;
|
|
5629
|
+
if (typeof val === "string") {
|
|
5630
|
+
try {
|
|
5631
|
+
return JSON.parse(val);
|
|
5632
|
+
} catch {
|
|
5633
|
+
return val;
|
|
5634
|
+
}
|
|
5635
|
+
}
|
|
5636
|
+
return val;
|
|
5637
|
+
};
|
|
5638
|
+
return {
|
|
5639
|
+
id: row.id,
|
|
5640
|
+
blockId: row.blockId,
|
|
5641
|
+
versionNumber: Number(row.versionNumber),
|
|
5642
|
+
name: row.name,
|
|
5643
|
+
description: row.description ?? void 0,
|
|
5644
|
+
content: row.content,
|
|
5645
|
+
rules: safeParseJSON(row.rules),
|
|
5646
|
+
changedFields: safeParseJSON(row.changedFields),
|
|
5647
|
+
changeMessage: row.changeMessage ?? void 0,
|
|
5648
|
+
createdAt: new Date(row.createdAt)
|
|
5649
|
+
};
|
|
5650
|
+
}
|
|
5651
|
+
};
|
|
5652
|
+
var SNAPSHOT_FIELDS3 = [
|
|
5653
|
+
"name",
|
|
5654
|
+
"description",
|
|
5655
|
+
"type",
|
|
5656
|
+
"model",
|
|
5657
|
+
"instructions",
|
|
5658
|
+
"scoreRange",
|
|
5659
|
+
"presetConfig",
|
|
5660
|
+
"defaultSampling"
|
|
5661
|
+
];
|
|
5662
|
+
var ScorerDefinitionsLibSQL = class extends ScorerDefinitionsStorage {
|
|
5663
|
+
#db;
|
|
5664
|
+
#client;
|
|
5665
|
+
constructor(config) {
|
|
5666
|
+
super();
|
|
5667
|
+
const client = resolveClient(config);
|
|
5668
|
+
this.#client = client;
|
|
5669
|
+
this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
|
|
5670
|
+
}
|
|
5671
|
+
async init() {
|
|
5672
|
+
await this.#db.createTable({ tableName: TABLE_SCORER_DEFINITIONS, schema: SCORER_DEFINITIONS_SCHEMA });
|
|
5673
|
+
await this.#db.createTable({
|
|
5674
|
+
tableName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
5675
|
+
schema: SCORER_DEFINITION_VERSIONS_SCHEMA
|
|
5676
|
+
});
|
|
5677
|
+
await this.#client.execute(
|
|
5678
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS idx_scorer_definition_versions_scorer_version ON "${TABLE_SCORER_DEFINITION_VERSIONS}" ("scorerDefinitionId", "versionNumber")`
|
|
5679
|
+
);
|
|
5680
|
+
}
|
|
5681
|
+
async dangerouslyClearAll() {
|
|
5682
|
+
await this.#db.deleteData({ tableName: TABLE_SCORER_DEFINITIONS });
|
|
5683
|
+
await this.#db.deleteData({ tableName: TABLE_SCORER_DEFINITION_VERSIONS });
|
|
5684
|
+
}
|
|
5685
|
+
// ==========================================================================
|
|
5686
|
+
// Scorer Definition CRUD
|
|
5687
|
+
// ==========================================================================
|
|
5688
|
+
async getById(id) {
|
|
5689
|
+
try {
|
|
5690
|
+
const result = await this.#client.execute({
|
|
5691
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITIONS)} FROM "${TABLE_SCORER_DEFINITIONS}" WHERE id = ?`,
|
|
5692
|
+
args: [id]
|
|
5693
|
+
});
|
|
5694
|
+
const row = result.rows?.[0];
|
|
5695
|
+
return row ? this.#parseScorerRow(row) : null;
|
|
5696
|
+
} catch (error) {
|
|
5697
|
+
if (error instanceof MastraError) throw error;
|
|
5698
|
+
throw new MastraError(
|
|
5699
|
+
{
|
|
5700
|
+
id: createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION", "FAILED"),
|
|
5701
|
+
domain: ErrorDomain.STORAGE,
|
|
5702
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5703
|
+
},
|
|
5704
|
+
error
|
|
5705
|
+
);
|
|
5706
|
+
}
|
|
5707
|
+
}
|
|
5708
|
+
async create(input) {
|
|
5709
|
+
const { scorerDefinition } = input;
|
|
5710
|
+
try {
|
|
5711
|
+
const now = /* @__PURE__ */ new Date();
|
|
5712
|
+
await this.#db.insert({
|
|
5713
|
+
tableName: TABLE_SCORER_DEFINITIONS,
|
|
5714
|
+
record: {
|
|
5715
|
+
id: scorerDefinition.id,
|
|
5716
|
+
status: "draft",
|
|
5717
|
+
activeVersionId: null,
|
|
5718
|
+
authorId: scorerDefinition.authorId ?? null,
|
|
5719
|
+
metadata: scorerDefinition.metadata ?? null,
|
|
5720
|
+
createdAt: now.toISOString(),
|
|
5721
|
+
updatedAt: now.toISOString()
|
|
5722
|
+
}
|
|
5723
|
+
});
|
|
5724
|
+
const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
|
|
5725
|
+
const versionId = crypto.randomUUID();
|
|
5726
|
+
await this.createVersion({
|
|
5727
|
+
id: versionId,
|
|
5728
|
+
scorerDefinitionId: scorerDefinition.id,
|
|
5729
|
+
versionNumber: 1,
|
|
5730
|
+
...snapshotConfig,
|
|
5731
|
+
changedFields: Object.keys(snapshotConfig),
|
|
5732
|
+
changeMessage: "Initial version"
|
|
5733
|
+
});
|
|
5734
|
+
return {
|
|
5735
|
+
id: scorerDefinition.id,
|
|
5736
|
+
status: "draft",
|
|
5737
|
+
activeVersionId: void 0,
|
|
5738
|
+
authorId: scorerDefinition.authorId,
|
|
5739
|
+
metadata: scorerDefinition.metadata,
|
|
5740
|
+
createdAt: now,
|
|
5741
|
+
updatedAt: now
|
|
5742
|
+
};
|
|
5743
|
+
} catch (error) {
|
|
5744
|
+
if (error instanceof MastraError) throw error;
|
|
5745
|
+
throw new MastraError(
|
|
5746
|
+
{
|
|
5747
|
+
id: createStorageErrorId("LIBSQL", "CREATE_SCORER_DEFINITION", "FAILED"),
|
|
5748
|
+
domain: ErrorDomain.STORAGE,
|
|
5749
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5750
|
+
},
|
|
5751
|
+
error
|
|
5752
|
+
);
|
|
5753
|
+
}
|
|
5754
|
+
}
|
|
5755
|
+
async update(input) {
|
|
5756
|
+
const { id, ...updates } = input;
|
|
5757
|
+
try {
|
|
5758
|
+
const existing = await this.getById(id);
|
|
5759
|
+
if (!existing) {
|
|
5760
|
+
throw new Error(`Scorer definition with id ${id} not found`);
|
|
5761
|
+
}
|
|
5762
|
+
const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
|
|
5763
|
+
const configFieldNames = SNAPSHOT_FIELDS3;
|
|
5764
|
+
const hasConfigUpdate = configFieldNames.some((field) => field in configFields);
|
|
5765
|
+
const updateData = {
|
|
5766
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5767
|
+
};
|
|
5768
|
+
if (authorId !== void 0) updateData.authorId = authorId;
|
|
5769
|
+
if (activeVersionId !== void 0) {
|
|
5770
|
+
updateData.activeVersionId = activeVersionId;
|
|
5771
|
+
if (status === void 0) {
|
|
5772
|
+
updateData.status = "published";
|
|
5773
|
+
}
|
|
5774
|
+
}
|
|
5775
|
+
if (status !== void 0) updateData.status = status;
|
|
5776
|
+
if (metadata !== void 0) {
|
|
5777
|
+
updateData.metadata = { ...existing.metadata, ...metadata };
|
|
5778
|
+
}
|
|
5779
|
+
await this.#db.update({
|
|
5780
|
+
tableName: TABLE_SCORER_DEFINITIONS,
|
|
5781
|
+
keys: { id },
|
|
5782
|
+
data: updateData
|
|
5783
|
+
});
|
|
5784
|
+
if (hasConfigUpdate) {
|
|
5785
|
+
const latestVersion = await this.getLatestVersion(id);
|
|
5786
|
+
if (!latestVersion) {
|
|
5787
|
+
throw new Error(`No versions found for scorer definition ${id}`);
|
|
5788
|
+
}
|
|
5789
|
+
const {
|
|
5790
|
+
id: _versionId,
|
|
5791
|
+
scorerDefinitionId: _scorerDefinitionId,
|
|
5792
|
+
versionNumber: _versionNumber,
|
|
5793
|
+
changedFields: _changedFields,
|
|
5794
|
+
changeMessage: _changeMessage,
|
|
5795
|
+
createdAt: _createdAt,
|
|
5796
|
+
...latestConfig
|
|
5797
|
+
} = latestVersion;
|
|
5798
|
+
const newConfig = { ...latestConfig, ...configFields };
|
|
5799
|
+
const changedFields = configFieldNames.filter(
|
|
5800
|
+
(field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
|
|
5801
|
+
);
|
|
5802
|
+
const newVersionId = crypto.randomUUID();
|
|
5803
|
+
await this.createVersion({
|
|
5804
|
+
id: newVersionId,
|
|
5805
|
+
scorerDefinitionId: id,
|
|
5806
|
+
versionNumber: latestVersion.versionNumber + 1,
|
|
5807
|
+
...newConfig,
|
|
5808
|
+
changedFields,
|
|
5809
|
+
changeMessage: `Updated ${changedFields.join(", ")}`
|
|
5810
|
+
});
|
|
5811
|
+
}
|
|
5812
|
+
const updated = await this.getById(id);
|
|
5813
|
+
if (!updated) {
|
|
5814
|
+
throw new MastraError({
|
|
5815
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
|
|
5816
|
+
domain: ErrorDomain.STORAGE,
|
|
5817
|
+
category: ErrorCategory.SYSTEM,
|
|
5818
|
+
text: `Scorer definition ${id} not found after update`,
|
|
5819
|
+
details: { id }
|
|
5820
|
+
});
|
|
5821
|
+
}
|
|
5822
|
+
return updated;
|
|
5823
|
+
} catch (error) {
|
|
5824
|
+
if (error instanceof MastraError) throw error;
|
|
5825
|
+
throw new MastraError(
|
|
5826
|
+
{
|
|
5827
|
+
id: createStorageErrorId("LIBSQL", "UPDATE_SCORER_DEFINITION", "FAILED"),
|
|
5828
|
+
domain: ErrorDomain.STORAGE,
|
|
5829
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5830
|
+
},
|
|
5831
|
+
error
|
|
5832
|
+
);
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
5835
|
+
async delete(id) {
|
|
5836
|
+
try {
|
|
5837
|
+
await this.deleteVersionsByParentId(id);
|
|
5838
|
+
await this.#client.execute({
|
|
5839
|
+
sql: `DELETE FROM "${TABLE_SCORER_DEFINITIONS}" WHERE "id" = ?`,
|
|
5840
|
+
args: [id]
|
|
5841
|
+
});
|
|
5842
|
+
} catch (error) {
|
|
5843
|
+
if (error instanceof MastraError) throw error;
|
|
5844
|
+
throw new MastraError(
|
|
5845
|
+
{
|
|
5846
|
+
id: createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION", "FAILED"),
|
|
5847
|
+
domain: ErrorDomain.STORAGE,
|
|
5848
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5849
|
+
},
|
|
5850
|
+
error
|
|
5851
|
+
);
|
|
5852
|
+
}
|
|
5853
|
+
}
|
|
5854
|
+
async list(args) {
|
|
5855
|
+
try {
|
|
5856
|
+
const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
|
|
5857
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
5858
|
+
const conditions = [];
|
|
5859
|
+
const queryParams = [];
|
|
5860
|
+
if (authorId !== void 0) {
|
|
5861
|
+
conditions.push("authorId = ?");
|
|
5862
|
+
queryParams.push(authorId);
|
|
5863
|
+
}
|
|
5864
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
5865
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
5866
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
|
5867
|
+
throw new MastraError({
|
|
5868
|
+
id: createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITIONS", "INVALID_METADATA_KEY"),
|
|
5869
|
+
domain: ErrorDomain.STORAGE,
|
|
5870
|
+
category: ErrorCategory.USER,
|
|
5871
|
+
text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
|
|
5872
|
+
details: { key }
|
|
5873
|
+
});
|
|
5874
|
+
}
|
|
5875
|
+
conditions.push(`json_extract(metadata, '$.${key}') = ?`);
|
|
5876
|
+
queryParams.push(typeof value === "string" ? value : JSON.stringify(value));
|
|
5877
|
+
}
|
|
5878
|
+
}
|
|
5879
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
5880
|
+
const countResult = await this.#client.execute({
|
|
5881
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_SCORER_DEFINITIONS}" ${whereClause}`,
|
|
5882
|
+
args: queryParams
|
|
5883
|
+
});
|
|
5884
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
5885
|
+
if (total === 0) {
|
|
5886
|
+
return {
|
|
5887
|
+
scorerDefinitions: [],
|
|
5888
|
+
total: 0,
|
|
5889
|
+
page,
|
|
5890
|
+
perPage: perPageInput ?? 100,
|
|
5891
|
+
hasMore: false
|
|
5892
|
+
};
|
|
5893
|
+
}
|
|
5894
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
5895
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
5896
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
5897
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
5898
|
+
const result = await this.#client.execute({
|
|
5899
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITIONS)} FROM "${TABLE_SCORER_DEFINITIONS}" ${whereClause} ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
|
|
5900
|
+
args: [...queryParams, limitValue, start]
|
|
5901
|
+
});
|
|
5902
|
+
const scorerDefinitions = result.rows?.map((row) => this.#parseScorerRow(row)) ?? [];
|
|
5903
|
+
return {
|
|
5904
|
+
scorerDefinitions,
|
|
5905
|
+
total,
|
|
5906
|
+
page,
|
|
5907
|
+
perPage: perPageForResponse,
|
|
5908
|
+
hasMore: end < total
|
|
5909
|
+
};
|
|
5910
|
+
} catch (error) {
|
|
5911
|
+
if (error instanceof MastraError) throw error;
|
|
5912
|
+
throw new MastraError(
|
|
5913
|
+
{
|
|
5914
|
+
id: createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITIONS", "FAILED"),
|
|
5915
|
+
domain: ErrorDomain.STORAGE,
|
|
5916
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5917
|
+
},
|
|
5918
|
+
error
|
|
5919
|
+
);
|
|
5920
|
+
}
|
|
5921
|
+
}
|
|
5922
|
+
// ==========================================================================
|
|
5923
|
+
// Scorer Definition Version Methods
|
|
5924
|
+
// ==========================================================================
|
|
5925
|
+
async createVersion(input) {
|
|
5926
|
+
try {
|
|
5927
|
+
const now = /* @__PURE__ */ new Date();
|
|
5928
|
+
await this.#db.insert({
|
|
5929
|
+
tableName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
5930
|
+
record: {
|
|
5931
|
+
id: input.id,
|
|
5932
|
+
scorerDefinitionId: input.scorerDefinitionId,
|
|
5933
|
+
versionNumber: input.versionNumber,
|
|
5934
|
+
name: input.name,
|
|
5935
|
+
description: input.description ?? null,
|
|
5936
|
+
type: input.type,
|
|
5937
|
+
model: input.model ?? null,
|
|
5938
|
+
instructions: input.instructions ?? null,
|
|
5939
|
+
scoreRange: input.scoreRange ?? null,
|
|
5940
|
+
presetConfig: input.presetConfig ?? null,
|
|
5941
|
+
defaultSampling: input.defaultSampling ?? null,
|
|
5942
|
+
changedFields: input.changedFields ?? null,
|
|
5943
|
+
changeMessage: input.changeMessage ?? null,
|
|
5944
|
+
createdAt: now.toISOString()
|
|
5945
|
+
}
|
|
5946
|
+
});
|
|
5947
|
+
return {
|
|
5948
|
+
...input,
|
|
5949
|
+
createdAt: now
|
|
5950
|
+
};
|
|
5951
|
+
} catch (error) {
|
|
5952
|
+
if (error instanceof MastraError) throw error;
|
|
5953
|
+
throw new MastraError(
|
|
5954
|
+
{
|
|
5955
|
+
id: createStorageErrorId("LIBSQL", "CREATE_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
5956
|
+
domain: ErrorDomain.STORAGE,
|
|
5957
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5958
|
+
},
|
|
5959
|
+
error
|
|
5960
|
+
);
|
|
5961
|
+
}
|
|
5962
|
+
}
|
|
5963
|
+
async getVersion(id) {
|
|
5964
|
+
try {
|
|
5965
|
+
const result = await this.#client.execute({
|
|
5966
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE id = ?`,
|
|
5967
|
+
args: [id]
|
|
5968
|
+
});
|
|
5969
|
+
const row = result.rows?.[0];
|
|
5970
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
5971
|
+
} catch (error) {
|
|
5972
|
+
if (error instanceof MastraError) throw error;
|
|
5973
|
+
throw new MastraError(
|
|
5974
|
+
{
|
|
5975
|
+
id: createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
5976
|
+
domain: ErrorDomain.STORAGE,
|
|
5977
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5978
|
+
},
|
|
5979
|
+
error
|
|
5980
|
+
);
|
|
5981
|
+
}
|
|
5982
|
+
}
|
|
5983
|
+
async getVersionByNumber(scorerDefinitionId, versionNumber) {
|
|
5984
|
+
try {
|
|
5985
|
+
const result = await this.#client.execute({
|
|
5986
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? AND versionNumber = ?`,
|
|
5987
|
+
args: [scorerDefinitionId, versionNumber]
|
|
5988
|
+
});
|
|
5989
|
+
const row = result.rows?.[0];
|
|
5990
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
5991
|
+
} catch (error) {
|
|
5992
|
+
if (error instanceof MastraError) throw error;
|
|
5993
|
+
throw new MastraError(
|
|
5994
|
+
{
|
|
5995
|
+
id: createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION_VERSION_BY_NUMBER", "FAILED"),
|
|
5996
|
+
domain: ErrorDomain.STORAGE,
|
|
5997
|
+
category: ErrorCategory.THIRD_PARTY
|
|
5998
|
+
},
|
|
5999
|
+
error
|
|
6000
|
+
);
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
6003
|
+
async getLatestVersion(scorerDefinitionId) {
|
|
6004
|
+
try {
|
|
6005
|
+
const result = await this.#client.execute({
|
|
6006
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? ORDER BY versionNumber DESC LIMIT 1`,
|
|
6007
|
+
args: [scorerDefinitionId]
|
|
6008
|
+
});
|
|
6009
|
+
const row = result.rows?.[0];
|
|
6010
|
+
return row ? this.#parseVersionRow(row) : null;
|
|
6011
|
+
} catch (error) {
|
|
6012
|
+
if (error instanceof MastraError) throw error;
|
|
6013
|
+
throw new MastraError(
|
|
6014
|
+
{
|
|
6015
|
+
id: createStorageErrorId("LIBSQL", "GET_LATEST_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
6016
|
+
domain: ErrorDomain.STORAGE,
|
|
6017
|
+
category: ErrorCategory.THIRD_PARTY
|
|
6018
|
+
},
|
|
6019
|
+
error
|
|
6020
|
+
);
|
|
6021
|
+
}
|
|
6022
|
+
}
|
|
6023
|
+
async listVersions(input) {
|
|
6024
|
+
try {
|
|
6025
|
+
const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
|
|
6026
|
+
const { field, direction } = this.parseVersionOrderBy(orderBy);
|
|
6027
|
+
const countResult = await this.#client.execute({
|
|
6028
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ?`,
|
|
6029
|
+
args: [scorerDefinitionId]
|
|
6030
|
+
});
|
|
6031
|
+
const total = Number(countResult.rows?.[0]?.count ?? 0);
|
|
6032
|
+
if (total === 0) {
|
|
6033
|
+
return {
|
|
6034
|
+
versions: [],
|
|
6035
|
+
total: 0,
|
|
6036
|
+
page,
|
|
6037
|
+
perPage: perPageInput ?? 20,
|
|
6038
|
+
hasMore: false
|
|
6039
|
+
};
|
|
6040
|
+
}
|
|
6041
|
+
const perPage = normalizePerPage(perPageInput, 20);
|
|
6042
|
+
const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
6043
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
6044
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
6045
|
+
const result = await this.#client.execute({
|
|
6046
|
+
sql: `SELECT ${buildSelectColumns(TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
|
|
6047
|
+
args: [scorerDefinitionId, limitValue, start]
|
|
6048
|
+
});
|
|
6049
|
+
const versions = result.rows?.map((row) => this.#parseVersionRow(row)) ?? [];
|
|
6050
|
+
return {
|
|
6051
|
+
versions,
|
|
6052
|
+
total,
|
|
6053
|
+
page,
|
|
6054
|
+
perPage: perPageForResponse,
|
|
6055
|
+
hasMore: end < total
|
|
6056
|
+
};
|
|
6057
|
+
} catch (error) {
|
|
6058
|
+
if (error instanceof MastraError) throw error;
|
|
6059
|
+
throw new MastraError(
|
|
6060
|
+
{
|
|
6061
|
+
id: createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITION_VERSIONS", "FAILED"),
|
|
6062
|
+
domain: ErrorDomain.STORAGE,
|
|
6063
|
+
category: ErrorCategory.THIRD_PARTY
|
|
6064
|
+
},
|
|
6065
|
+
error
|
|
6066
|
+
);
|
|
6067
|
+
}
|
|
6068
|
+
}
|
|
6069
|
+
async deleteVersion(id) {
|
|
6070
|
+
try {
|
|
6071
|
+
await this.#client.execute({
|
|
6072
|
+
sql: `DELETE FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE "id" = ?`,
|
|
6073
|
+
args: [id]
|
|
6074
|
+
});
|
|
6075
|
+
} catch (error) {
|
|
6076
|
+
if (error instanceof MastraError) throw error;
|
|
6077
|
+
throw new MastraError(
|
|
6078
|
+
{
|
|
6079
|
+
id: createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
6080
|
+
domain: ErrorDomain.STORAGE,
|
|
6081
|
+
category: ErrorCategory.THIRD_PARTY
|
|
6082
|
+
},
|
|
6083
|
+
error
|
|
6084
|
+
);
|
|
6085
|
+
}
|
|
6086
|
+
}
|
|
6087
|
+
async deleteVersionsByParentId(entityId) {
|
|
6088
|
+
try {
|
|
6089
|
+
await this.#client.execute({
|
|
6090
|
+
sql: `DELETE FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE "scorerDefinitionId" = ?`,
|
|
6091
|
+
args: [entityId]
|
|
6092
|
+
});
|
|
6093
|
+
} catch (error) {
|
|
6094
|
+
if (error instanceof MastraError) throw error;
|
|
6095
|
+
throw new MastraError(
|
|
6096
|
+
{
|
|
6097
|
+
id: createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION_VERSIONS_BY_SCORER", "FAILED"),
|
|
6098
|
+
domain: ErrorDomain.STORAGE,
|
|
6099
|
+
category: ErrorCategory.THIRD_PARTY
|
|
6100
|
+
},
|
|
6101
|
+
error
|
|
6102
|
+
);
|
|
6103
|
+
}
|
|
6104
|
+
}
|
|
6105
|
+
async countVersions(scorerDefinitionId) {
|
|
6106
|
+
try {
|
|
6107
|
+
const result = await this.#client.execute({
|
|
6108
|
+
sql: `SELECT COUNT(*) as count FROM "${TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ?`,
|
|
6109
|
+
args: [scorerDefinitionId]
|
|
6110
|
+
});
|
|
6111
|
+
return Number(result.rows?.[0]?.count ?? 0);
|
|
6112
|
+
} catch (error) {
|
|
6113
|
+
if (error instanceof MastraError) throw error;
|
|
6114
|
+
throw new MastraError(
|
|
6115
|
+
{
|
|
6116
|
+
id: createStorageErrorId("LIBSQL", "COUNT_SCORER_DEFINITION_VERSIONS", "FAILED"),
|
|
6117
|
+
domain: ErrorDomain.STORAGE,
|
|
6118
|
+
category: ErrorCategory.THIRD_PARTY
|
|
6119
|
+
},
|
|
6120
|
+
error
|
|
6121
|
+
);
|
|
6122
|
+
}
|
|
6123
|
+
}
|
|
6124
|
+
// ==========================================================================
|
|
6125
|
+
// Private Helpers
|
|
6126
|
+
// ==========================================================================
|
|
6127
|
+
#parseScorerRow(row) {
|
|
6128
|
+
const safeParseJSON = (val) => {
|
|
6129
|
+
if (val === null || val === void 0) return void 0;
|
|
6130
|
+
if (typeof val === "string") {
|
|
6131
|
+
try {
|
|
6132
|
+
return JSON.parse(val);
|
|
6133
|
+
} catch {
|
|
6134
|
+
return val;
|
|
6135
|
+
}
|
|
6136
|
+
}
|
|
6137
|
+
return val;
|
|
6138
|
+
};
|
|
6139
|
+
return {
|
|
6140
|
+
id: row.id,
|
|
6141
|
+
status: row.status ?? "draft",
|
|
6142
|
+
activeVersionId: row.activeVersionId ?? void 0,
|
|
6143
|
+
authorId: row.authorId ?? void 0,
|
|
6144
|
+
metadata: safeParseJSON(row.metadata),
|
|
6145
|
+
createdAt: new Date(row.createdAt),
|
|
6146
|
+
updatedAt: new Date(row.updatedAt)
|
|
6147
|
+
};
|
|
6148
|
+
}
|
|
6149
|
+
#parseVersionRow(row) {
|
|
6150
|
+
const safeParseJSON = (val) => {
|
|
6151
|
+
if (val === null || val === void 0) return void 0;
|
|
6152
|
+
if (typeof val === "string") {
|
|
6153
|
+
try {
|
|
6154
|
+
return JSON.parse(val);
|
|
6155
|
+
} catch {
|
|
6156
|
+
return val;
|
|
6157
|
+
}
|
|
6158
|
+
}
|
|
6159
|
+
return val;
|
|
6160
|
+
};
|
|
6161
|
+
return {
|
|
6162
|
+
id: row.id,
|
|
6163
|
+
scorerDefinitionId: row.scorerDefinitionId,
|
|
6164
|
+
versionNumber: Number(row.versionNumber),
|
|
6165
|
+
name: row.name,
|
|
6166
|
+
description: row.description ?? void 0,
|
|
6167
|
+
type: row.type,
|
|
6168
|
+
model: safeParseJSON(row.model),
|
|
6169
|
+
instructions: row.instructions ?? void 0,
|
|
6170
|
+
scoreRange: safeParseJSON(row.scoreRange),
|
|
6171
|
+
presetConfig: safeParseJSON(row.presetConfig),
|
|
6172
|
+
defaultSampling: safeParseJSON(row.defaultSampling),
|
|
6173
|
+
changedFields: safeParseJSON(row.changedFields),
|
|
6174
|
+
changeMessage: row.changeMessage ?? void 0,
|
|
6175
|
+
createdAt: new Date(row.createdAt)
|
|
6176
|
+
};
|
|
6177
|
+
}
|
|
6178
|
+
};
|
|
4703
6179
|
var ScoresLibSQL = class extends ScoresStorage {
|
|
4704
6180
|
#db;
|
|
4705
6181
|
#client;
|
|
@@ -5352,12 +6828,16 @@ var LibSQLStore = class extends MastraCompositeStore {
|
|
|
5352
6828
|
const memory = new MemoryLibSQL(domainConfig);
|
|
5353
6829
|
const observability = new ObservabilityLibSQL(domainConfig);
|
|
5354
6830
|
const agents = new AgentsLibSQL(domainConfig);
|
|
6831
|
+
const promptBlocks = new PromptBlocksLibSQL(domainConfig);
|
|
6832
|
+
const scorerDefinitions = new ScorerDefinitionsLibSQL(domainConfig);
|
|
5355
6833
|
this.stores = {
|
|
5356
6834
|
scores,
|
|
5357
6835
|
workflows,
|
|
5358
6836
|
memory,
|
|
5359
6837
|
observability,
|
|
5360
|
-
agents
|
|
6838
|
+
agents,
|
|
6839
|
+
promptBlocks,
|
|
6840
|
+
scorerDefinitions
|
|
5361
6841
|
};
|
|
5362
6842
|
}
|
|
5363
6843
|
};
|
|
@@ -5461,6 +6941,6 @@ Example Complex Query:
|
|
|
5461
6941
|
]
|
|
5462
6942
|
}`;
|
|
5463
6943
|
|
|
5464
|
-
export { AgentsLibSQL, LibSQLStore as DefaultStorage, LIBSQL_PROMPT, LibSQLStore, LibSQLVector, MemoryLibSQL, ObservabilityLibSQL, ScoresLibSQL, WorkflowsLibSQL };
|
|
6944
|
+
export { AgentsLibSQL, LibSQLStore as DefaultStorage, LIBSQL_PROMPT, LibSQLStore, LibSQLVector, MemoryLibSQL, ObservabilityLibSQL, PromptBlocksLibSQL, ScorerDefinitionsLibSQL, ScoresLibSQL, WorkflowsLibSQL };
|
|
5465
6945
|
//# sourceMappingURL=index.js.map
|
|
5466
6946
|
//# sourceMappingURL=index.js.map
|