@mastra/core
Version:
4,527 lines • 109 kB
JavaScript
import { v as SpanType } from "./utils-DU_pU5SK.js";
import { An as tagsField, C as dateRangeSchema, En as sortDirectionSchema, Jt as metadataField, M as deltaInfoSchema, Mn as traceIdField, N as deltaLimitSchema, On as spanContextFields, an as paginationInfoSchema, in as paginationArgsSchema, j as deltaCursorSchema, kn as spanIdField, ln as refineObservabilityListMode, nn as normalizeObservabilityListArgs, pn as resourceIdField, rn as organizationIdField, w as dbTimestamps, zt as listModeSchema } from "./storage-Cc50aQAp.js";
import { s as truncatePreview } from "./observability-D3dpuDDk.js";
import { n as getZodInnerType, r as getZodTypeName } from "./zod-utils-BDDS_mxU.js";
import { z } from "zod/v4";
// src/evals/types.ts
const scoringSourceSchema = z.enum(["LIVE", "TEST"]);
const scoringEntityTypeSchema = z.enum([
"AGENT",
"WORKFLOW",
"TRAJECTORY",
"STEP",
"SCORER",
"PROCESSOR",
"EXTERNAL",
...Object.values(SpanType)
]);
const scoringPromptsSchema = z.object({
description: z.string(),
prompt: z.string()
});
/** Reusable schema for required record fields (e.g., scorer, entity) */
const recordSchema = z.record(z.string(), z.unknown());
/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */
const optionalRecordSchema = recordSchema.optional();
const scoringInputSchema = z.object({
runId: z.string().optional(),
input: z.unknown().optional(),
output: z.unknown(),
additionalContext: optionalRecordSchema,
requestContext: optionalRecordSchema
});
const scoringHookInputSchema = z.object({
runId: z.string().optional(),
scorer: recordSchema,
input: z.unknown(),
output: z.unknown(),
metadata: optionalRecordSchema,
additionalContext: optionalRecordSchema,
source: scoringSourceSchema,
entity: recordSchema,
entityType: scoringEntityTypeSchema,
requestContext: optionalRecordSchema,
structuredOutput: z.boolean().optional(),
traceId: z.string().optional(),
spanId: z.string().optional(),
resourceId: z.string().optional(),
threadId: z.string().optional(),
projectId: z.string().optional()
});
const scoringExtractStepResultSchema = optionalRecordSchema;
const scoringValueSchema = z.number();
const scoreResultSchema = z.object({
result: optionalRecordSchema,
score: scoringValueSchema,
prompt: z.string().optional()
});
const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({
runId: z.string(),
extractStepResult: optionalRecordSchema,
extractPrompt: z.string().optional()
});
const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema = scoringInputWithExtractStepResultSchema.extend({
score: z.number(),
analyzeStepResult: optionalRecordSchema,
analyzePrompt: z.string().optional()
});
const scoringInputWithExtractStepResultAndScoreAndReasonSchema = scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({
reason: z.string().optional(),
reasonPrompt: z.string().optional()
});
const scoreRowDataSchema = z.object({
id: z.string(),
scorerId: z.string(),
entityId: z.string(),
runId: z.string(),
input: z.unknown().optional(),
output: z.unknown(),
additionalContext: optionalRecordSchema,
requestContext: optionalRecordSchema,
extractStepResult: optionalRecordSchema,
extractPrompt: z.string().optional(),
score: z.number(),
analyzeStepResult: optionalRecordSchema,
analyzePrompt: z.string().optional(),
reason: z.string().optional(),
reasonPrompt: z.string().optional(),
scorer: recordSchema,
metadata: optionalRecordSchema,
source: scoringSourceSchema,
entity: recordSchema,
entityType: scoringEntityTypeSchema.optional(),
structuredOutput: z.boolean().optional(),
traceId: z.string().optional(),
spanId: z.string().optional(),
resourceId: z.string().optional(),
threadId: z.string().optional(),
organizationId: z.string().nullish(),
projectId: z.string().nullish(),
batchId: z.string().nullish(),
datasetId: z.string().nullish(),
datasetItemId: z.string().nullish(),
preprocessStepResult: optionalRecordSchema,
preprocessPrompt: z.string().optional(),
generateScorePrompt: z.string().optional(),
generateReasonPrompt: z.string().optional(),
...dbTimestamps
});
const saveScorePayloadSchema = scoreRowDataSchema.omit({
id: true,
createdAt: true,
updatedAt: true
}).extend({
/**
* Optional caller-supplied stable id. When provided, storage adapters
* upsert by this id (latest write wins) instead of inserting a new row
* with a random id. Used by caller-driven experiments so retried
* submissions converge on one score row per (experiment, item, attempt,
* scorer).
*/
id: z.string().optional() });
const listScoresResponseSchema = z.object({
pagination: paginationInfoSchema,
scores: z.array(scoreRowDataSchema)
});
/**
* Extracts a Trajectory from agent output messages by walking through
* tool invocations.
*
* This is called automatically by `runEvals` when using `AgentScorerConfig.trajectory`
* scorers — trajectory scorers receive a pre-extracted `Trajectory` as their `output`
* instead of raw `MastraDBMessage[]`.
*
* @param output - The raw agent output messages
* @returns A Trajectory with ToolCallStep entries extracted from tool invocations
*/
function extractTrajectory(output) {
const steps = [];
for (const message of output) {
const legacy = message?.content?.toolInvocations;
const fromParts = message?.content?.parts?.filter((p) => p.type === "tool-invocation").map((p) => p.toolInvocation).filter(Boolean) ?? [];
const partCallIds = new Set(fromParts.map((invocation) => invocation.toolCallId).filter(Boolean));
const legacyInvocations = legacy ?? [];
const legacyPositions = new Map(legacyInvocations.map((invocation, index) => [invocation?.toolCallId, index]));
const toolInvocations = [];
let legacyIndex = 0;
for (const invocation of fromParts) {
const sharedIndex = invocation.toolCallId ? legacyPositions.get(invocation.toolCallId) : void 0;
if (sharedIndex !== void 0 && sharedIndex >= legacyIndex) {
for (; legacyIndex < sharedIndex; legacyIndex++) {
const previous = legacyInvocations[legacyIndex];
if (previous && !partCallIds.has(previous.toolCallId)) toolInvocations.push(previous);
}
legacyIndex++;
}
toolInvocations.push(invocation);
}
for (; legacyIndex < legacyInvocations.length; legacyIndex++) {
const invocation = legacyInvocations[legacyIndex];
if (invocation && !partCallIds.has(invocation.toolCallId)) toolInvocations.push(invocation);
}
if (!toolInvocations?.length) continue;
for (const invocation of toolInvocations) if (invocation && invocation.toolName && (invocation.state === "result" || invocation.state === "call" || invocation.state === "output-error")) {
const toolArgs = invocation.args != null && typeof invocation.args === "object" && !Array.isArray(invocation.args) ? invocation.args : invocation.args != null ? { value: invocation.args } : void 0;
const rawResult = invocation.state === "result" ? invocation.result : void 0;
const toolResult = rawResult != null && typeof rawResult === "object" && !Array.isArray(rawResult) ? rawResult : rawResult != null ? { value: rawResult } : void 0;
steps.push({
stepType: "tool_call",
name: invocation.toolName,
toolArgs,
toolResult,
success: invocation.state === "result" && invocation.isError !== true
});
}
}
return {
steps,
rawOutput: output
};
}
/**
* Extracts a Trajectory from workflow step results.
*
* Converts the `stepResults` record (and optional `stepExecutionPath` ordering)
* into a flat list of `WorkflowStepStep` entries. Each step captures its status,
* output, and timing.
*
* This is called automatically by `runEvals` when using `WorkflowScorerConfig.trajectory`
* scorers.
*
* @param stepResults - The workflow step results record
* @param stepExecutionPath - Optional ordered list of step IDs for execution ordering
* @returns A Trajectory with WorkflowStepStep entries
*/
function extractWorkflowTrajectory(stepResults, stepExecutionPath) {
const steps = [];
const stepIds = stepExecutionPath ?? Object.keys(stepResults);
let totalStartedAt;
let totalEndedAt;
for (const stepId of stepIds) {
const result = stepResults[stepId];
if (!result) continue;
if (result.startedAt != null) {
if (totalStartedAt == null || result.startedAt < totalStartedAt) totalStartedAt = result.startedAt;
}
const endedAt = "endedAt" in result ? result.endedAt : void 0;
if (endedAt != null) {
if (totalEndedAt == null || endedAt > totalEndedAt) totalEndedAt = endedAt;
}
const durationMs = result.startedAt != null && endedAt != null ? endedAt - result.startedAt : void 0;
const output = "output" in result && result.output != null && typeof result.output === "object" && !Array.isArray(result.output) ? result.output : "output" in result && result.output != null ? { value: result.output } : void 0;
steps.push({
stepType: "workflow_step",
name: stepId,
stepId,
status: result.status,
output,
durationMs,
metadata: result.metadata
});
}
return {
steps,
totalDurationMs: totalStartedAt != null && totalEndedAt != null ? totalEndedAt - totalStartedAt : void 0,
rawWorkflowResult: {
stepResults,
stepExecutionPath
}
};
}
/**
* Span types that are considered noise and should be skipped during
* trace-to-trajectory conversion (internal implementation details, not
* meaningful trajectory steps).
*/
const SKIPPED_SPAN_TYPES = /* @__PURE__ */ new Set([
"scorer_run",
"scorer_step",
"generic",
"skill_resolution",
"model_step",
"model_inference",
"model_chunk",
"workflow_conditional_eval"
]);
/**
* Converts a `SpanTreeNode` to `TrajectoryStep` entries.
*
* Returns an array because a skipped span promotes its children into the
* parent's list rather than dropping them entirely.
*/
function spanToTrajectorySteps(node) {
const { span, children: childNodes } = node;
if (SKIPPED_SPAN_TYPES.has(span.spanType)) return childNodes.flatMap(spanToTrajectorySteps);
const durationMs = span.endedAt != null && span.startedAt != null ? span.endedAt.getTime() - span.startedAt.getTime() : void 0;
const childSteps = childNodes.flatMap(spanToTrajectorySteps);
const base = {
name: span.name,
durationMs,
metadata: span.metadata,
...childSteps.length > 0 ? { children: childSteps } : {}
};
const attrs = span.attributes ?? {};
switch (span.spanType) {
case "tool_call": {
const toolArgs = toRecordOrUndefined(span.input);
const toolResult = toRecordOrUndefined(span.output);
return [{
...base,
stepType: "tool_call",
name: span.entityId ?? span.entityName ?? span.name,
toolArgs,
toolResult,
success: typeof attrs.success === "boolean" ? attrs.success : void 0
}];
}
case "mcp_tool_call": {
const toolArgs = toRecordOrUndefined(span.input);
const toolResult = toRecordOrUndefined(span.output);
return [{
...base,
stepType: "mcp_tool_call",
name: span.entityId ?? span.entityName ?? span.name,
toolArgs,
toolResult,
mcpServer: typeof attrs.mcpServer === "string" ? attrs.mcpServer : void 0,
success: typeof attrs.success === "boolean" ? attrs.success : void 0
}];
}
case "provider_tool_call": {
const toolArgs = toRecordOrUndefined(span.input);
const toolResult = toRecordOrUndefined(span.output);
return [{
...base,
stepType: "provider_tool_call",
name: span.entityId ?? span.entityName ?? span.name,
toolArgs,
toolResult,
success: typeof attrs.success === "boolean" ? attrs.success : void 0
}];
}
case "model_generation": {
const usage = attrs.usage;
return [{
...base,
stepType: "model_generation",
modelId: typeof attrs.model === "string" ? attrs.model : void 0,
promptTokens: usage?.inputTokens,
completionTokens: usage?.outputTokens,
finishReason: typeof attrs.finishReason === "string" ? attrs.finishReason : void 0
}];
}
case "agent_run": return [{
...base,
stepType: "agent_run",
agentId: span.entityId ?? void 0
}];
case "workflow_run": return [{
...base,
stepType: "workflow_run",
workflowId: span.entityId ?? void 0
}];
case "workflow_step": {
const output = toRecordOrUndefined(span.output);
return [{
...base,
stepType: "workflow_step",
stepId: span.name,
output
}];
}
case "workflow_conditional": return [{
...base,
stepType: "workflow_conditional"
}];
case "workflow_parallel": return [{
...base,
stepType: "workflow_parallel"
}];
case "workflow_loop": return [{
...base,
stepType: "workflow_loop"
}];
case "workflow_sleep": return [{
...base,
stepType: "workflow_sleep"
}];
case "workflow_wait_event": return [{
...base,
stepType: "workflow_wait_event"
}];
case "processor_run": return [{
...base,
stepType: "processor_run"
}];
default: return childSteps;
}
}
/**
* Safely converts a value to `Record<string, unknown>` or returns undefined.
*/
function toRecordOrUndefined(value) {
if (value == null) return void 0;
if (typeof value === "object" && !Array.isArray(value)) return value;
return { value };
}
/**
* Extracts a hierarchical Trajectory from trace spans (as returned by the
* observability store's `getTrace()`).
*
* Builds a parent-child tree from `parentSpanId` references, then recursively
* converts each span to the appropriate `TrajectoryStep` discriminated union
* type with nested `children`.
*
* Noise spans (`generic`, `model_step`, `model_chunk`, `workflow_conditional_eval`)
* are automatically skipped.
*
* This is used by `runEvals` when storage is available to produce richer,
* hierarchical trajectories that include nested agent runs, tool calls, and
* model generations inside workflow or agent steps.
*
* @param spans - Flat array of span records from `getTrace().spans`
* @param rootSpanId - Optional span ID to use as root. If omitted, spans with
* no parent are used as roots.
* @returns A Trajectory with hierarchical TrajectoryStep entries
*
* @example
* ```ts
* const trace = await observabilityStore.getTrace({ traceId });
* const trajectory = extractTrajectoryFromTrace(trace.spans, workflowSpanId);
* ```
*/
function extractTrajectoryFromTrace(spans, rootSpanId) {
if (spans.length === 0) return { steps: [] };
const nodeMap = /* @__PURE__ */ new Map();
for (const span of spans) nodeMap.set(span.spanId, {
span,
children: []
});
const roots = [];
for (const span of spans) {
const node = nodeMap.get(span.spanId);
if (span.parentSpanId && nodeMap.has(span.parentSpanId)) nodeMap.get(span.parentSpanId).children.push(node);
else roots.push(node);
}
for (const node of nodeMap.values()) node.children.sort((a, b) => a.span.startedAt.getTime() - b.span.startedAt.getTime());
let targetRoots;
if (rootSpanId) {
const rootNode = nodeMap.get(rootSpanId);
targetRoots = rootNode ? [rootNode] : roots;
} else targetRoots = roots;
let stepsToConvert;
if (targetRoots.length === 1) {
const root = targetRoots[0];
if ((/* @__PURE__ */ new Set(["workflow_run", "agent_run"])).has(root.span.spanType)) stepsToConvert = root.children;
else stepsToConvert = targetRoots;
} else stepsToConvert = targetRoots;
const steps = stepsToConvert.flatMap(spanToTrajectorySteps);
let totalDurationMs;
if (targetRoots.length === 1) {
const root = targetRoots[0].span;
if (root.endedAt && root.startedAt) totalDurationMs = root.endedAt.getTime() - root.startedAt.getTime();
}
return {
steps,
totalDurationMs
};
}
// ../_internal-core/dist/memory/index.js
/**
* Shared rules for observational memory lifecycle writes. Every storage adapter applies
* these inside its own atomic section (lock, transaction, or conditional update), so the
* decisions are identical across adapters.
*/
/**
* Observational memory columns that lifecycle writes depend on. Storage adapters merge these
* into the table schema they get from `@mastra/core`, so the columns exist even when the
* installed core predates them.
*/
const OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS = { supersededBy: {
type: "text",
nullable: true
} };
/**
* Canonical head order: `generationCount DESC, createdAt ASC, id ASC`.
* Returns a negative number when `a` sorts before `b` (i.e. `a` is the better head candidate).
*/
function compareObservationalMemoryHeadOrder(a, b) {
if (a.generationCount !== b.generationCount) return b.generationCount - a.generationCount;
const at = new Date(a.createdAt).getTime();
const bt = new Date(b.createdAt).getTime();
if (at !== bt) return at - bt;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
}
/**
* A buffered chunk stores `lastObservedAt = max message time + 1ms`. It is wholly covered
* (every message it observed is already at or before the cursor) iff
* `cursor >= chunk.lastObservedAt - 1ms`.
*/
function isBufferedChunkCoveredByCursor(chunkLastObservedAt, cursor) {
if (!cursor) return false;
return new Date(cursor).getTime() >= new Date(chunkLastObservedAt).getTime() - 1;
}
/** The later of two cursors; `undefined` only when both are absent. */
function maxObservationCursor(a, b) {
if (!a) return b ? new Date(b) : void 0;
if (!b) return new Date(a);
return new Date(Math.max(new Date(a).getTime(), new Date(b).getTime()));
}
/**
* Decide the new generation's text when a reflection built from `snapshot` commits against
* the stored record.
*
* - Stored text equals the snapshot: the reflection replaces it.
* - Stored text extends the snapshot (activation only appends): the appended tail is kept
* after the reflection, and its tokens are added.
* - Anything else (a non-append rewrite): `null` — the reflection must not be applied.
*/
function planReflectionGenerationText(input) {
const stored = input.storedObservations ?? "";
const snapshot = input.snapshotObservations ?? "";
if (stored === snapshot) return {
mode: "equal",
observations: input.reflection,
tokenCount: input.tokenCount
};
if (!stored.startsWith(snapshot)) return null;
const tail = stored.slice(snapshot.length).trimStart();
if (!tail.trim()) return {
mode: "equal",
observations: input.reflection,
tokenCount: input.tokenCount
};
return {
mode: "append",
observations: input.reflection ? `${input.reflection}\n\n${tail}` : tail,
tokenCount: input.tokenCount + Math.max(0, (input.storedObservationTokenCount ?? 0) - (input.snapshotObservationTokenCount ?? 0))
};
}
/**
* Backs `updateActiveObservations` in adapters that implement `commitActiveObservations`.
* Callers of `updateActiveObservations` (which resolves `void`) can't see a commit result, so a
* write that was not applied throws instead of resolving as if it had committed.
*/
function assertActiveObservationsApplied(result, id) {
if (result.applied) return;
throw new Error(result.reason === "retired" ? `Observational memory record ${id} was superseded by a newer generation; observations were not written` : `Observational memory record ${id} changed since the observations were composed; observations were not written`);
}
/**
* Whether the stored text can still accept a reflection built from `snapshot`
* (equal, or only appended to since).
*/
function isAppendOnlySince(storedObservations, snapshotObservations) {
const stored = storedObservations ?? "";
const snapshot = snapshotObservations ?? "";
return stored === snapshot || stored.startsWith(snapshot);
}
// src/storage/domains/observability/tracing.ts
/**
* Creates an omit key object from a Zod schema shape.
* This allows dynamically deriving omit keys from existing schema definitions.
*/
const createOmitKeys = (shape) => Object.fromEntries(Object.keys(shape).map((k) => [k, true]));
const spanNameField = z.string().describe("Human-readable span name");
const parentSpanIdField = z.string().describe("Parent span reference (null = root span)");
const spanTypeField = z.nativeEnum(SpanType).describe("Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)");
const attributesField = z.record(z.string(), z.unknown()).describe("Span-type specific attributes (e.g., model, tokens, tools)");
const linksField = z.array(z.unknown()).describe("References to related spans in other traces");
const inputField = z.unknown().describe("Input data passed to the span");
const outputField = z.unknown().describe("Output data returned from the span");
const errorField = z.unknown().describe("Error info - presence indicates failure (status derived from this)");
const isEventField = z.boolean().describe("Whether this is an event (point-in-time) vs a span (duration)");
const startedAtField = z.date().describe("When the span started");
const endedAtField = z.date().describe("When the span ended (null = running, status derived from this)");
/** Derived status of a trace, computed from the root span's error and endedAt fields. */
let TraceStatus = /* @__PURE__ */ function(TraceStatus) {
TraceStatus["SUCCESS"] = "success";
TraceStatus["ERROR"] = "error";
TraceStatus["RUNNING"] = "running";
return TraceStatus;
}({});
const traceStatusField = z.nativeEnum(TraceStatus).describe("Current status of the trace");
const hasChildErrorField = z.preprocess((v) => {
if (v === "true") return true;
if (v === "false") return false;
return v;
}, z.boolean()).describe("True if any span in the trace encountered an error");
/**
* All optional fields shared between span records and trace filters.
* Built from spanContextFields plus span-specific metadata/tags.
* Note: When filtering traces, these fields are matched against the root span.
*/
const sharedFields = {
...spanContextFields,
metadata: metadataField.nullish(),
tags: tagsField.nullish()
};
/** Shape containing trace and span identifier fields */
const spanIds = {
traceId: traceIdField,
spanId: spanIdField
};
/** Schema for span identifiers (traceId and spanId) */
const spanIdsSchema = z.object({ ...spanIds });
const omitDbTimestamps = createOmitKeys(dbTimestamps);
const omitSpanIds = createOmitKeys(spanIds);
/** Schema for a complete span record as stored in the database */
const spanRecordSchema = z.object({
...spanIds,
name: spanNameField,
spanType: spanTypeField,
isEvent: isEventField,
startedAt: startedAtField,
parentSpanId: parentSpanIdField.nullish(),
...sharedFields,
experimentId: z.string().nullish().describe("Experiment or eval run identifier"),
attributes: attributesField.nullish(),
links: linksField.nullish(),
input: inputField.nullish(),
output: outputField.nullish(),
error: errorField.nullish(),
endedAt: endedAtField.nullish(),
requestContext: z.record(z.string(), z.unknown()).nullish().describe("Request context data"),
inputPreview: z.string().nullish().describe("Short text preview of the span input"),
outputPreview: z.string().nullish().describe("Short text preview of the span output"),
errorPreview: z.string().nullish().describe("Short text preview of the span error"),
timeToFirstChunkMs: z.number().nullish().describe("Milliseconds from span start to the first streamed chunk; null when the span never streamed one"),
externalParentSpanId: z.string().nullish().describe("Immediate parent span owned by an external tracing system; null when Mastra owns the parent"),
resumedFromSpanId: z.string().nullish().describe("Span id of the initial invocation a resumed execution continues; null on the initial execution"),
model: z.string().nullish().describe("Model identity for this span, where applicable"),
provider: z.string().nullish().describe("Provider paired with model"),
outcome: z.string().nullish().describe("How this execution ended; null while it is still running"),
stopReason: z.string().nullish().describe("Machine-readable cause of stopping, when known"),
stopReasonContext: z.record(z.string(), z.unknown()).nullish().describe("Structured details behind stopReason, such as the limit that was hit; null when unknown"),
timeToFirstTokenMs: z.number().nullish().describe("Milliseconds from the model call to the first token received; null when unknown"),
errorCount: z.number().int().nullish().describe("Failures originating directly on this span; null when unknown"),
...dbTimestamps
}).describe("Span record data");
/**
* Computes the trace status from a root span's error and endedAt fields.
* - ERROR: if error is present (regardless of endedAt)
* - RUNNING: if endedAt is null/undefined and no error
* - SUCCESS: if endedAt is present and no error
*/
function computeTraceStatus(span) {
if (span.error != null) return "error";
if (span.endedAt == null) return "running";
return "success";
}
/**
* A string attribute of a span, or null when unset or not a string.
* Model-call spans keep `model` and `provider` in `attributes`; the native
* columns of the same name fall back to it for rows written before the
* columns existed, since those rows are never backfilled.
*/
function getStringAttribute(attributes, key) {
const value = attributes?.[key];
return typeof value === "string" ? value : null;
}
/** Schema for a trace span (root span with computed status) */
const traceSpanSchema = spanRecordSchema.extend({ status: traceStatusField }).describe("Trace span with computed status (root spans only)");
/**
* Converts a SpanRecord to a TraceSpan by adding computed status.
* Used when returning root spans from listTraces.
*/
function toTraceSpan(span) {
return {
...span,
status: computeTraceStatus(span)
};
}
/**
* Converts an array of SpanRecords to TraceSpans by adding computed status.
* Used when returning root spans from listTraces.
*/
function toTraceSpans(spans) {
return spans.map(toTraceSpan);
}
/**
* Schema for creating a span (without db timestamps)
*/
const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);
/**
* Schema for createSpan operation arguments
*/
const createSpanArgsSchema = z.object({ span: createSpanRecordSchema }).describe("Arguments for creating a single span");
/**
* Schema for batchCreateSpans operation arguments
*/
const batchCreateSpansArgsSchema = z.object({ records: z.array(createSpanRecordSchema) }).describe("Arguments for batch creating spans");
/**
* Schema for getSpan operation arguments
*/
const getSpanArgsSchema = z.object({
traceId: traceIdField.min(1),
spanId: spanIdField.min(1)
}).describe("Arguments for getting a single span");
/**
* Response schema for getSpan operation
*/
const getSpanResponseSchema = z.object({ span: spanRecordSchema });
/**
* Schema for getSpans (batch) operation arguments.
*
* Fetches multiple spans in a trace by spanId in one call. Used to power the
* progressive-disclosure path in {@link getBranchArgsSchema}: walk the
* lightweight {@link getStructureResponseSchema} to find which spanIds belong
* to a branch, then fetch only those with full data instead of pulling the
* entire trace.
*/
const getSpansArgsSchema = z.object({
traceId: traceIdField.min(1),
spanIds: z.array(spanIdField.min(1)).min(1).describe("Span IDs to fetch within the trace")
}).describe("Arguments for batch-fetching spans by spanId within a trace");
/** Response schema for getSpans operation */
const getSpansResponseSchema = z.object({
traceId: traceIdField,
spans: z.array(spanRecordSchema)
});
/**
* Schema for getRootSpan operation arguments
*/
const getRootSpanArgsSchema = z.object({ traceId: traceIdField.min(1) }).describe("Arguments for getting a root span");
/**
* Response schema for getRootSpan operation
*/
const getRootSpanResponseSchema = z.object({ span: spanRecordSchema });
/**
* Schema for getTrace operation arguments
*/
const getTraceArgsSchema = z.object({ traceId: traceIdField.min(1) }).describe("Arguments for getting a single trace");
/**
* Response schema for getTrace operation
*/
const getTraceResponseSchema = z.object({
traceId: traceIdField,
spans: z.array(spanRecordSchema)
});
/**
* Schema for getBranch operation arguments.
*
* Returns the subtree rooted at `spanId`. When `depth` is omitted the full
* descendant subtree is returned; with a finite `depth` only that many levels
* below the anchor are returned (depth: 0 → only the anchor span; depth: 1 →
* anchor plus immediate children; etc).
*/
const getBranchArgsSchema = z.object({
traceId: traceIdField.min(1),
spanId: spanIdField.min(1),
depth: z.coerce.number().int().min(0).optional().describe("Maximum descendant levels below the anchor span (omit for full subtree)")
}).describe("Arguments for getting a span branch (subtree rooted at a span)");
/**
* Response schema for getBranch operation. Mirrors getTrace -- a flat list of
* spans, traversal-agnostic. The anchor span is included as the first matching
* span; callers reconstruct the tree via parentSpanId.
*/
const getBranchResponseSchema = z.object({
traceId: traceIdField,
spans: z.array(spanRecordSchema)
});
/**
* Extracts the subtree rooted at `anchorSpanId` from a flat list of trace
* spans. The anchor itself is included as the first element; descendants are
* walked via `parentSpanId` and returned sorted by `startedAt` ascending after
* the anchor. When `maxDepth` is provided, only that many levels of
* descendants are returned (anchor counts as depth 0).
*
* Cycles in `parentSpanId` (which shouldn't happen in well-formed traces but
* could surface from corrupted data) are handled by tracking visited spanIds
* and skipping any span seen during this walk.
*
* Returns an empty array if the anchor isn't in the input.
*
* Generic over the span shape so it works on both full {@link SpanRecord}
* lists (e.g. result of `getTrace`) and lightweight skeletons (result of
* `getStructure`).
*/
function extractBranchSpans(spans, anchorSpanId, maxDepth) {
const anchor = spans.find((s) => s.spanId === anchorSpanId);
if (!anchor) return [];
const childrenByParent = /* @__PURE__ */ new Map();
for (const span of spans) {
if (span.parentSpanId == null) continue;
const bucket = childrenByParent.get(span.parentSpanId);
if (bucket) bucket.push(span);
else childrenByParent.set(span.parentSpanId, [span]);
}
const visited = /* @__PURE__ */ new Set([anchor.spanId]);
const descendants = [];
let frontier = [anchor];
let depth = 0;
while (frontier.length > 0) {
if (maxDepth != null && depth >= maxDepth) break;
const next = [];
for (const span of frontier) {
const children = childrenByParent.get(span.spanId);
if (!children) continue;
for (const child of children) {
if (visited.has(child.spanId)) continue;
visited.add(child.spanId);
descendants.push(child);
next.push(child);
}
}
frontier = next;
depth++;
}
descendants.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());
return [anchor, ...descendants];
}
/** @deprecated Use {@link PREVIEW_MAX_LENGTH}. */
const INPUT_PREVIEW_MAX_LENGTH = 100;
const inputPreviewField = z.string().describe("Short text preview of the span input");
const outputPreviewField = z.string().describe("Short text preview of the span output");
const errorPreviewField = z.string().describe("Short text preview of the span error");
function isMessage(value) {
return value != null && typeof value === "object" && typeof value.role === "string";
}
/** A message list is a bare array or a `messages` array whose elements carry a string `role`. */
function extractMessages(value) {
const list = value && typeof value === "object" && !Array.isArray(value) && "messages" in value ? value.messages : value;
return Array.isArray(list) && list.some(isMessage) ? list : null;
}
function textFromContent(content) {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
return content.map((part) => {
if (typeof part === "string") return part;
if (part && typeof part === "object" && part.type === "text") {
const text = part.text;
return typeof text === "string" ? text : "";
}
return "";
}).filter(Boolean).join(" ");
}
/**
* Preview of an agent signal recorded as a run's input (`agent.sendSignal()`): a user signal previews
* as its text, any other signal as its text labelled by what it is (`Skill <name>: …`, `<tag>: …`).
*/
function signalText(value) {
const signal = value;
if (signal.__isCreatedSignal !== true || !("contents" in signal)) return null;
const text = textFromContent(signal.contents).trim();
const type = signal.type;
if (type === "user" || type === "user-message") return text || null;
const attributes = signal.attributes;
const tagName = typeof signal.tagName === "string" ? signal.tagName : void 0;
const label = tagName === "skill" && typeof attributes?.name === "string" ? `Skill ${attributes.name}` : tagName ?? (typeof type === "string" ? type : "signal");
return text ? `${label}: ${text}` : label;
}
function lastMessageText(messages, accept) {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (!isMessage(message) || !accept(message.role)) continue;
const text = textFromContent(message.content).trim();
if (text) return text;
}
return null;
}
function textField(value) {
for (const key of ["text", "message"]) {
const field = value[key];
if (typeof field === "string" && field.trim()) return field;
}
return null;
}
/**
* Short text preview of a decoded span payload (`input`, `output` or `error`), at most
* {@link PREVIEW_MAX_LENGTH} characters plus `…` when cut. Returns `null` when there is nothing
* to preview.
*
* - A string previews as itself.
* - A message list (a bare array, or a `messages` array, of objects with a string `role`)
* previews as the last user message's text, else the last non-system message's text.
* - An agent signal (a run started by `agent.sendSignal()`) previews as its contents; a non-user
* signal is labelled by its tag, or `Skill <name>` for a skill.
* - An object with a non-blank `text` or `message` string previews as that string.
* - Anything else previews as its compact JSON.
*
* `serialized` is the value's JSON text when the caller already has it, so the compact-JSON
* case does not serialize it twice. Writers call this on the value they store; readers of a
* stored JSON column call {@link buildPreviewFromJson}, so both produce the same preview.
*/
function buildPreview(value, serialized) {
return previewOf(value, serialized, 100);
}
function previewOf(value, serialized, maxLength) {
if (value == null) return null;
if (typeof value === "string") return truncatePreview(value, maxLength);
const messages = extractMessages(value);
if (messages) {
const text = lastMessageText(messages, (role) => role === "user") ?? lastMessageText(messages, (role) => role !== "system");
return text == null ? null : truncatePreview(text, maxLength);
}
if (typeof value === "object" && !Array.isArray(value)) {
const text = signalText(value) ?? textField(value);
if (text != null) return truncatePreview(text, maxLength);
}
return truncatePreview(serialized ?? JSON.stringify(value) ?? "", maxLength);
}
/**
* Preview of a stored JSON payload column. Stores always write valid JSON, so text that does not
* parse previews as blank rather than as a guess at a sliced document.
*/
function buildPreviewFromJson(json) {
return previewOfJson(json, 100);
}
function previewOfJson(json, maxLength) {
if (json == null || !json.trim()) return null;
let value;
try {
value = JSON.parse(json);
} catch {
return null;
}
return previewOf(value, json, maxLength);
}
/**
* The preview a store writes for one payload: an upstream preview when the span record carries
* a string (including an intentionally empty one), otherwise one built from the payload. Both are capped the same way, at
* {@link PREVIEW_MAX_LENGTH} characters plus `…`, so an exporter can't store an unbounded preview.
* `''` means there is nothing to preview.
*/
function buildStoredPreview(upstream, value, serialized) {
if (upstream != null) return truncatePreview(upstream) ?? "";
return buildPreview(value, serialized) ?? "";
}
/**
* Whether a preview built by {@link buildPreview} was cut. A cut preview is the first
* {@link PREVIEW_MAX_LENGTH} characters plus `…`, or one character fewer plus `…` when the cut
* would split a surrogate pair; an uncut one is at most {@link PREVIEW_MAX_LENGTH} characters.
* An uncut text of exactly {@link PREVIEW_MAX_LENGTH} characters that itself ends in `…` reads as
* cut, which is the one case the preview alone cannot tell apart.
*/
function isPreviewTruncated(preview) {
if (!preview) return false;
return preview.endsWith("…") && (preview.length === 100 || preview.length === 101);
}
/**
* @deprecated Use {@link buildPreview} (decoded values) or {@link buildPreviewFromJson} (stored
* JSON text). Kept for callers of the old trace-list preview; it now uses the shared preview
* format, so a message list previews as its last user message rather than every user message
* joined with ` | `.
*
* Accepts a decoded value or a JSON string. A string that looks like a JSON document or a
* JSON-encoded scalar is parsed first; an unparseable JSON document previews as empty.
* `maxLength` caps the preview at that many characters plus `…`, as before.
*/
function buildInputPreview(input, maxLength = 100) {
if (input == null) return void 0;
if (typeof input === "string") {
const trimmed = input.trim();
if (trimmed.startsWith("{") || trimmed.startsWith("[")) return previewOfJson(trimmed, maxLength) ?? void 0;
if (trimmed.startsWith("\"")) try {
return previewOf(JSON.parse(trimmed), void 0, maxLength) ?? void 0;
} catch {}
}
return previewOf(input, void 0, maxLength) ?? void 0;
}
/** Stored preview when the record carries one (`''` means none), else one built from the value. */
function lightPreview(stored, value) {
return stored == null ? buildPreview(value) : stored.trim() || null;
}
/**
* Projects a full span record down to the lightweight row a trace list renders,
* with `inputPreview` / `outputPreview` / `errorPreview`: the stored previews when the record
* carries them, otherwise built from `input` / `output` / `error` with {@link buildPreview}.
*
* This is the read-time fallback. Backends that can project inside the query should
* do so instead — that is what keeps the blob columns off the read path — but every
* backend can serve a correct lightweight list through this.
*/
function toLightSpanRecord(span) {
return {
traceId: span.traceId,
spanId: span.spanId,
parentSpanId: span.parentSpanId,
name: span.name,
spanType: span.spanType,
isEvent: span.isEvent,
startedAt: span.startedAt,
endedAt: span.endedAt,
error: span.error,
status: computeTraceStatus(span),
entityType: span.entityType,
entityId: span.entityId,
entityName: span.entityName,
threadId: span.threadId,
resourceId: span.resourceId,
metadata: span.metadata,
inputPreview: lightPreview(span.inputPreview, span.input),
outputPreview: lightPreview(span.outputPreview, span.output),
errorPreview: lightPreview(span.errorPreview, span.error),
createdAt: span.createdAt,
updatedAt: span.updatedAt
};
}
/**
* Lightweight span record containing only the fields trace lists and timelines render.
* Excludes heavy fields: input, output, attributes, tags, links.
* This keeps the per-span payload a small fraction of a full span record's.
*/
const lightSpanRecordSchema = z.object({
...spanIds,
name: spanNameField,
spanType: spanTypeField,
isEvent: isEventField,
startedAt: startedAtField,
parentSpanId: parentSpanIdField.nullish(),
endedAt: endedAtField.nullish(),
error: errorField.nullish(),
status: traceStatusField.nullable().optional(),
entityType: spanContextFields.entityType,
entityId: spanContextFields.entityId,
entityName: spanContextFields.entityName,
threadId: spanContextFields.threadId.nullable(),
resourceId: spanContextFields.resourceId.nullable(),
metadata: metadataField.nullable().optional(),
inputPreview: inputPreviewField.nullable().optional(),
outputPreview: outputPreviewField.nullable().optional(),
errorPreview: errorPreviewField.nullable().optional(),
...dbTimestamps
}).describe("Lightweight span record for trace lists and timelines (excludes input, output, attributes, tags, links)");
/**
* Response schema for getStructure operation.
* Returns a trace with lightweight spans (only fields needed for timeline).
*/
const getStructureResponseSchema = z.object({
traceId: traceIdField,
spans: z.array(lightSpanRecordSchema)
});
/** @deprecated Use {@link getStructureResponseSchema} instead. */
const getTraceLightResponseSchema = getStructureResponseSchema;
/** Schema for filtering traces in list queries */
const tracesFilterSchema = z.object({
startedAt: dateRangeSchema.optional().describe("Filter by span start time range"),
endedAt: dateRangeSchema.optional().describe("Filter by span end time range"),
spanType: spanTypeField.optional(),
traceId: traceIdField.optional().describe("Filter by trace ID (matches root span)"),
...sharedFields,
status: traceStatusField.optional(),
hasChildError: hasChildErrorField.optional()
}).describe("Filters for querying traces");
/**
* Fields available for ordering trace results
*/
const tracesOrderByFieldSchema = z.enum(["startedAt", "endedAt"]).describe("Field to order by: 'startedAt' | 'endedAt'");
/**
* Order by configuration for trace queries
* Follows the existing StorageOrderBy pattern
* Defaults to startedAt desc (newest first)
*/
const tracesOrderBySchema = z.object({
field: tracesOrderByFieldSchema.default("startedAt").describe("Field to order by"),
direction: sortDirectionSchema.default("DESC").describe("Sort direction")
}).describe("Order by configuration");
/**
* Arguments for listing traces
*/
const listTracesArgsSchema = z.object({
mode: listModeSchema.optional(),
filters: tracesFilterSchema.optional().describe("Optional filters to apply"),
pagination: paginationArgsSchema.optional(),
orderBy: tracesOrderBySchema.optional(),
after: deltaCursorSchema.optional(),
limit: deltaLimitSchema
}).strict().superRefine(refineObservabilityListMode).transform((value) => normalizeObservabilityListArgs(value, { orderBy: {
field: "startedAt",
direction: "DESC"
} })).describe("Arguments for listing traces.");
/** Schema for listTraces operation response */
const listTracesResponseSchema = z.object({
pagination: paginationInfoSchema.optional(),
delta: deltaInfoSchema.optional(),
deltaCursor: deltaCursorSchema.optional(),
spans: z.array(traceSpanSchema)
});
/** Schema for listTracesLight operation response */
const listTracesLightResponseSchema = z.object({
pagination: paginationInfoSchema.optional(),
delta: deltaInfoSchema.optional(),
deltaCursor: deltaCursorSchema.optional(),
spans: z.array(lightSpanRecordSchema)
});
/**
* Span types that anchor a listable trace branch -- the spans a user thinks
* about when looking for a specific run (agent/workflow/tool/etc.),
* regardless of whether the entity ran as the root of its trace or nested
* under a parent. Each row in {@link listBranchesArgsSchema} corresponds to
* one such anchor span; the subtree below it is fetched via
* {@link getBranchArgsSchema}.
*
* Excludes sub-operation spans (model_step, workflow_step, scorer_step,
* memory_operation, rag_*, etc.) which are internal to a containing branch
* rather than separately listable.
*/
const BRANCH_SPAN_TYPES = [
"agent_run",
"workflow_run",
"processor_run",
"scorer_run",
"rag_ingestion",
"tool_call",
"mcp_tool_call",
"mcp_server_request",
"provider_tool_call"
];
/** Set form of {@link BRANCH_SPAN_TYPES} for fast membership checks. */
const BRANCH_SPAN_TYPE_SET = new Set(BRANCH_SPAN_TYPES);
/** Schema for filtering branch anchor spans in list queries. */
const branchesFilterSchema = z.object({
startedAt: dateRangeSchema.optional().describe("Filter by span start time range"),
endedAt: dateRangeSchema.optional().describe("Filter by span end time range"),
spanType: spanTypeField.optional(),
traceId: traceIdField.optional().describe("Filter by parent trace ID"),
...sharedFields,
status: traceStatusField.optional()
}).describe("Filters for querying trace branches");
const branchesOrderByFieldSchema = z.enum(["startedAt", "endedAt"]).describe("Field to order by: 'startedAt' | 'endedAt'");
const branchesOrderBySchema = z.object({
field: branchesOrderByFieldSchema.default("startedAt").describe("Field to order by"),
direction: sortDirectionSchema.default("DESC").describe("Sort direction")
}).describe("Order by configuration");
/**
* Arguments for listing trace branches.
*
* Each row is a single branch anchor span ({@link BRANCH_SPAN_TYPES}),
* including ones nested under a different root entity. Use this when you
* want every run of a given agent/processor/tool regardless of how it was
* triggered. Use {@link listTracesArgsSchema} when you want one row per
* trace, and {@link getBranchArgsSchema} to expand a single branch into its
* subtree.
*/
const listBranchesArgsSchema = z.object({
mode: listModeSchema.optional(),
filters: branchesFilterSchema.optional().describe("Optional filters to apply"),
pagination: paginationArgsSchema.optional(),
orderBy: branchesOrderBySchema.optional(),
after: deltaCursorSchema.optional(),
limit: deltaLimitSchema
}).strict().superRefine(refineObservabilityListMode).transform((value) => normalizeObservabilityListArgs(value, { orderBy: {
field: "startedAt",
direction: "DESC"
} })).describe("Arguments for listing trace branches.");
/**
* Schema for listBranches operation response. Each row is a single branch
* anchor span -- repeated runs of the same entity within one parent trace
* surface as separate rows.
*/
const listBranchesResponseSchema = z.object({
pagination: paginationInfoSchema.optional(),
delta: deltaInfoSchema.optional(),
deltaCursor: deltaCursorSchema.optional(),
branches: z.array(traceSpanSchema)
});
/**
* Schema for updating a span (without db timestamps and span IDs)
*/
const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);
/**
* Schema for updateSpan operation arguments
*/
const updateSpanArgsSchema = z.object({
spanId: spanIdField,
traceId: traceIdField,
updates: updateSpanRecordSchema.partial()
}).describe("Arguments for updating a single span");
/**
* Schema for batchUpdateSpans operation arguments
*/
const batchUpdateSpansArgsSchema = z.object({ records: z.array(z.object({
traceId: traceIdField,
spanId: spanIdField,
updates: updateSpanRecordSchema.partial()
})) }).describe("Arguments for batch updating spans");
/** Maximum number of trace IDs accepted by a single batch delete request. */
const BATCH_DELETE_TRACES_MAX_IDS = 1e3;
/**
* Schema for batchDeleteTraces operation arguments
*/
const batchDeleteTracesArgsSchema = z.object({
traceIds: z.array(traceIdField).max(BATCH_DELETE_TRACES_MAX_IDS).describe(`Trace IDs to delete (maximum ${BATCH_DELETE_TRACES_MAX_IDS})`),
organizationId: organizationIdField.optional().describe("Optional tenant scope: only delete rows belonging to this organization"),
resourceId: resourceIdField.optional().describe("Optional tenant scope: only delete rows belonging to this resource")
}).describe("Arguments for batch deleting traces");
/** Schema for batchDeleteTraces route response */
const batchDeleteTracesResponseSchema = z.object({ success: z.literal(true) }).describe("Response for batch deleting traces");
/** Schema for listScoresBySpan operation response */
const listScoresBySpanResponseSchema = z.object({
pagination: paginationInfoSchema,
scores: z.array(scoreRowDataSchema)
});
/** Schema for scoreTraces operation request */
const scoreTracesRequestSchema = z.object({
scorerName: z.string().min(1),
targets: z.array(z.object({
traceId: traceIdField,
spanId: spanIdField.optional()
})).min(1)
});
/** Schema for scoreTraces operation response */
const scoreTracesResponseSchema = z.object({
status: z.string(),
message: z.string(),
traceCount: z.number()
});
// src/storage/types.ts
const STORAGE_VISIBILITY_VALUES = ["private", "public"];
/**
* Returns true when a snapshot's current status satisfies an `expectedStatus` guard.
* Stores call this inside their `updateWorkflowState` critical section.
*/
function matchesExpectedWorkflowStatus(currentStatus, expectedStatus) {
if (expectedStatus === void 0) return true;
return currentStatus !== void 0 && (Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus]).includes(currentStatus);
}
function unwrapSchema(schema) {
let current = schema;
let nullable = false;
while (true) {
const typeName = getZodTypeName(current);
if (!typeName) break;
if (typeName === "ZodNullable" || typeName === "ZodOptional") nullable = true;
const inner = getZodInnerType(current, typeName);
if (!inner) break;
current = inner;
}
return {
base: current,
nullable
};
}
/**
* Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.
* Zod 3 uses _def.checks with {kind: "..."} objects
* Zod 4 uses _zod.def.checks with {def: {check: "...", format: "..."}} objects
*/
function getZodChecks(schema) {
if ("_zod" in schema) {
const checks = schema._zod?.def?.checks;
if (checks && Array.isArray(checks)) return checks.map((check) => {
if (typeof check === "object" && check !== null && "def" in check && typeof check.def === "object" && check.def !== null) {
const def = check.def;
if (def.check === "number_format" && def.format === "safeint") return { kind: "int" };
if (def.check === "string_format" && typeof def.format === "string") return { kind: def.format };
return { kind: typeof def.check === "string" ? def.check : "unknown" };
}
return { kind: "unknown" };
});
}
if ("_def" in schema) {
const checks = schema._def?.checks;
if (checks && Array.isArray(checks)) return checks;
}
return [];
}
function zodToStorageType(schema) {
const typeName = getZodTypeName(schema);
if (typeName === "ZodString") {
if (getZodChecks(schema).some((c) => c.kind === "uuid")) return "uuid";
return "text";
}
if (typeName === "ZodNativeEnum" || typeName === "ZodEnum") return "text";
if (typeName === "ZodNumber") return getZodChecks(schema).some((c) => c.kind === "int") ? "integer" : "float";
if (typeName === "ZodBigInt" || typeName === "ZodBigint") return "bigint";
if (typeName === "ZodDate") return "timestamp";
if (typeName === "ZodBoolean") return "boolean";
return "jsonb";
}
/**
* Converts a zod schema into a database schema
* @param zObject A zod schema object
* @returns database schema record with StorageColumns
*/
function buildStorageSchema(zObject) {
const shape = zObject.shape;
const result = {};
for (const [key, field] of Object.entries(shape)) {
const { base, nullable } = unwrapSchema(field);
result[key] = {
type: zodToStorageType(base),
nullable
};
}
return result;
}
const STORAGE_FAVORITE_ENTITY_TYPES = ["agent", "skill"];
// src/storage/constants.ts
const TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
const TABLE_MESSAGES = "mastra_messages";
const TABLE_THREADS = "mastra_threads";
const TABLE_TRACES = "mastra_traces";
const TABLE_RESOURCES = "mastra_resources";
const TABLE_SCORERS = "mastra_scorers";
const TABLE_SPANS = "mastra_ai_spans";
const TABLE_AGENTS = "mastra_agents";
const TABLE_AGENT_VERSIONS = "mastra_agent_versions";
const TABLE_OBSERVATIONAL_MEMORY = "mastra_observational_memory";
const TABLE_PROMPT_BLOCKS = "mastra_prompt_blocks";
const TABLE_PROMPT_BLOCK_VERSIONS = "mastra_prompt_block_versions";
const TABLE_SCORER_DEFINITIONS = "mastra_scorer_definitions";
const TABLE_SCORER_DEFINITION_VERSIONS = "mastra_scorer_definition_versions";
const TABLE_MCP_CLIENTS = "mastra_mcp_clients";
const TABLE_MCP_CLIENT_VERSIONS = "mastra_mcp_client_versions";
const TABLE_MCP_SERVERS = "mastra_mcp_servers";
const TABLE_MCP_SERVER_VERSIONS = "mastra_mcp_server_versions";
const TABLE_WORKSPACES = "mastra_workspaces";
const TABLE_WORKSPACE_VERSIONS = "mastra_workspace_versions";
const TABLE_SKILLS = "mastra_skills";
const TABLE_SKILL_VERSIONS = "mastra_skill_versions";
const TABLE_SKILL_BLOBS = "mastra_skill_blobs";
const TABLE_FAVORITES = "mastra_favorites";
const TABLE_DATASETS = "mastra_datasets";
const TABLE_DATASET_ITEMS = "mastra_dataset_items";
const TABLE_DATASET_VERSIONS = "mastra_dataset_versions";
const TABLE_EXPERIMENTS = "mastra_experiments";
const TABLE_EXPERIMENT_RESULTS = "mastra_experiment_results";
const TABLE_BACKGROUND_TASKS = "mastra_background_tasks";
const TABLE_SCHEDULES = "mastra_schedules";
const TABLE_SCHEDULE_TRIGGERS = "mastra_schedule_triggers";
const TABLE_WORKFLOW_DEFINITIONS = "mastra_workflow_definitions";
const TABLE_CHANNEL_INSTALLATIONS = "mastra_channel_installations";
const TABLE_CHANNEL_CONFIG = "mastra_channel_config";
const TABLE_TOOL_PROVIDER_CONNECTIONS = "mastra_tool_provider_connections";
const TABLE_NOTIFICATIONS = "mastra_notifications";
const TABLE_HARNESS_SESSIONS = "mastra_harness_sessions";
const TABLE_THREAD_STATE = "mastra_thread_state";
const TABLE_KNOWLEDGE_NODES = "mastra_knowledge_nodes";
const TABLE_KNOWLEDGE_RECORDS = "mastra_knowledge_records";
const TABLE_KNOWLEDGE_MENTIONS = "mastra_knowledge_mentions";
/**
* @deprecated Curation cursors were removed and Knowledge no longer creates this table. Kept so adapters built
* against earlier Core versions still resolve the export.
*/
const TABLE_KNOWLEDGE_CURSORS = "mastra_knowledge_cursors";
const TABLE_KNOWLEDGE_ACTIVITY = "mastra_knowledge_activity";
const TABLE_KNOWLEDGE_SEMANTIC_OUTBOX = "mastra_knowledge_semantic_outbox";
const TABLE_KNOWLEDGE_NODE_SCOPES = "mastra_knowledge_node_scopes";
const TABLE_KNOWLEDGE_RECORD_SCOPES = "mastra_knowledge_record_scopes";
const TABLE_KNOWLEDGE_SCOPE_GRANTS = "mastra_knowledge_scope_grants";
const TABLE_KNOWLEDGE_ACCESS_STATE = "mastra_knowledge_access_state";
const TABLE_KNOWLEDGE_SCOPE_ADDRESSES = "mastra_knowledge_scope_addresses";
const TABLE_KNOWLEDGE_NODE_ADDRESSES = "mastra_knowledge_node_addresses";
const TABLE_KNOWLEDGE_IMPORT_STATE = "mastra_knowledge_import_state";
const TABLE_KNOWLEDGE_IMPORT_RUNS = "mastra_knowledge_import_runs";
const TABLE_KNOWLEDGE_PROPOSALS = "mastra_knowledge_proposals";
/** Physical tables owned by one Knowledge domain. Explicit reset may target only this list. */
const KNOWLEDGE_TABLE_NAMES = [
TABLE_KNOWLEDGE_NODES,
TABLE_KNOWLEDGE_RECORDS,
TABLE_KNOWLEDGE_MENTIONS,
TABLE_KNOWLEDGE_ACTIVITY,
TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
TABLE_KNOWLEDGE_NODE_SCOPES,
TABLE_KNOWLEDGE_RECORD_SCOPES,
TABLE_KNOWLEDGE_SCOPE_GRANTS,
TABLE_KNOWLEDGE_ACCESS_STATE,
TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
TABLE_KNOWLEDGE_NODE_ADDRESSES,
TABLE_KNOWLEDGE_IMPORT_STATE,
TABLE_KNOWLEDGE_IMPORT_RUNS,
TABLE_KNOWLEDGE_PROPOSALS
];
const SCORERS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
scorerId: { type: "text" },
traceId: {
type: "text",
nullable: true
},
spanId: {
type: "text",
nullable: true
},
runId: { type: "text" },
scorer: { type: "jsonb" },
preprocessStepResult: {
type: "jsonb",
nullable: true
},
extractStepResult: {
type: "jsonb",
nullable: true
},
analyzeStepResult: {
type: "jsonb",
nullable: true
},
score: { type: "float" },
reason: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
preprocessPrompt: {
type: "text",
nullable: true
},
extractPrompt: {
type: "text",
nullable: true
},
generateScorePrompt: {
type: "text",
nullable: true
},
generateReasonPrompt: {
type: "text",
nullable: true
},
analyzePrompt: {
type: "text",
nullable: true
},
reasonPrompt: {
type: "text",
nullable: true
},
input: { type: "jsonb" },
output: { type: "jsonb" },
additionalContext: {
type: "jsonb",
nullable: true
},
requestContext: {
type: "jsonb",
nullable: true
},
/**
* Things you can evaluate
*/
entityType: {
type: "text",
nullable: true
},
entity: {
type: "jsonb",
nullable: true
},
entityId: {
type: "text",
nullable: true
},
source: { type: "text" },
resourceId: {
type: "text",
nullable: true
},
threadId: {
type: "text",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
batchId: {
type: "text",
nullable: true
},
datasetId: {
type: "text",
nullable: true
},
datasetItemId: {
type: "text",
nullable: true
},
createdAt: { type: "timestamp" },
updatedAt: { type: "timestamp" }
};
const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);
/**
* @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.
* @internal
*/
const OLD_SPAN_SCHEMA = {
traceId: {
type: "text",
nullable: false
},
spanId: {
type: "text",
nullable: false
},
parentSpanId: {
type: "text",
nullable: true
},
name: {
type: "text",
nullable: false
},
scope: {
type: "jsonb",
nullable: true
},
spanType: {
type: "text",
nullable: false
},
attributes: {
type: "jsonb",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
links: {
type: "jsonb",
nullable: true
},
input: {
type: "jsonb",
nullable: true
},
output: {
type: "jsonb",
nullable: true
},
error: {
type: "jsonb",
nullable: true
},
startedAt: {
type: "timestamp",
nullable: false
},
endedAt: {
type: "timestamp",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: true
},
isEvent: {
type: "boolean",
nullable: false
}
};
const AGENTS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
visibility: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
favoriteCount: {
type: "integer",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const AGENT_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
agentId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
instructions: {
type: "text",
nullable: false
},
model: {
type: "jsonb",
nullable: false
},
modelList: {
type: "jsonb",
nullable: true
},
tools: {
type: "jsonb",
nullable: true
},
defaultOptions: {
type: "jsonb",
nullable: true
},
workflows: {
type: "jsonb",
nullable: true
},
agents: {
type: "jsonb",
nullable: true
},
integrationTools: {
type: "jsonb",
nullable: true
},
toolProviders: {
type: "jsonb",
nullable: true
},
inputProcessors: {
type: "jsonb",
nullable: true
},
outputProcessors: {
type: "jsonb",
nullable: true
},
memory: {
type: "jsonb",
nullable: true
},
scorers: {
type: "jsonb",
nullable: true
},
mcpClients: {
type: "jsonb",
nullable: true
},
requestContextSchema: {
type: "jsonb",
nullable: true
},
workspace: {
type: "jsonb",
nullable: true
},
skills: {
type: "jsonb",
nullable: true
},
skillsFormat: {
type: "text",
nullable: true
},
durable: {
type: "jsonb",
nullable: true
},
browser: {
type: "jsonb",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const PROMPT_BLOCKS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const PROMPT_BLOCK_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
blockId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
content: {
type: "text",
nullable: false
},
rules: {
type: "jsonb",
nullable: true
},
requestContextSchema: {
type: "jsonb",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const SCORER_DEFINITIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const SCORER_DEFINITION_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
scorerDefinitionId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
type: {
type: "text",
nullable: false
},
model: {
type: "jsonb",
nullable: true
},
instructions: {
type: "text",
nullable: true
},
scoreRange: {
type: "jsonb",
nullable: true
},
presetConfig: {
type: "jsonb",
nullable: true
},
defaultSampling: {
type: "jsonb",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const MCP_CLIENTS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const MCP_CLIENT_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
mcpClientId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
servers: {
type: "jsonb",
nullable: false
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const MCP_SERVERS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const MCP_SERVER_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
mcpServerId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
version: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
instructions: {
type: "text",
nullable: true
},
repository: {
type: "jsonb",
nullable: true
},
releaseDate: {
type: "text",
nullable: true
},
isLatest: {
type: "boolean",
nullable: true
},
packageCanonical: {
type: "text",
nullable: true
},
tools: {
type: "jsonb",
nullable: true
},
agents: {
type: "jsonb",
nullable: true
},
workflows: {
type: "jsonb",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const WORKFLOW_DEFINITIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
description: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
inputSchema: {
type: "jsonb",
nullable: false
},
outputSchema: {
type: "jsonb",
nullable: false
},
stateSchema: {
type: "jsonb",
nullable: true
},
requestContextSchema: {
type: "jsonb",
nullable: true
},
graph: {
type: "jsonb",
nullable: false
},
schedule: {
type: "jsonb",
nullable: true
},
status: {
type: "text",
nullable: false
},
source: {
type: "text",
nullable: false
},
authorId: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const WORKSPACES_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const WORKSPACE_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
workspaceId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
filesystem: {
type: "jsonb",
nullable: true
},
sandbox: {
type: "jsonb",
nullable: true
},
mounts: {
type: "jsonb",
nullable: true
},
search: {
type: "jsonb",
nullable: true
},
skills: {
type: "jsonb",
nullable: true
},
tools: {
type: "jsonb",
nullable: true
},
autoSync: {
type: "boolean",
nullable: true
},
operationTimeout: {
type: "integer",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const SKILLS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
status: {
type: "text",
nullable: false
},
activeVersionId: {
type: "text",
nullable: true
},
authorId: {
type: "text",
nullable: true
},
visibility: {
type: "text",
nullable: true
},
favoriteCount: {
type: "integer",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const FAVORITES_SCHEMA = {
userId: {
type: "text",
nullable: false
},
entityType: {
type: "text",
nullable: false
},
entityId: {
type: "text",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
}
};
/**
* Per-author registry of authorized tool provider connections. Stores a stable
* user-supplied label across agents. Composite primary key on
* (authorId, providerId, connectionId). `scope` buckets identity:
* 'per-author' (default), 'shared' (visible to all callers), or
* 'caller-supplied' (authorId is a host-app end-user id forwarded via request
* context).
*/
const TOOL_PROVIDER_CONNECTIONS_SCHEMA = {
authorId: {
type: "text",
nullable: false
},
providerId: {
type: "text",
nullable: false
},
connectionId: {
type: "text",
nullable: false
},
toolkit: {
type: "text",
nullable: false
},
label: {
type: "text",
nullable: true
},
scope: {
type: "text",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const NOTIFICATIONS_SCHEMA = {
id: {
type: "text",
nullable: false
},
threadId: {
type: "text",
nullable: false
},
source: {
type: "text",
nullable: false
},
kind: {
type: "text",
nullable: false
},
priority: {
type: "text",
nullable: false
},
status: {
type: "text",
nullable: false
},
summary: {
type: "text",
nullable: false
},
payload: {
type: "jsonb",
nullable: true
},
resourceId: {
type: "text",
nullable: true
},
agentId: {
type: "text",
nullable: true
},
sourceId: {
type: "text",
nullable: true
},
dedupeKey: {
type: "text",
nullable: true
},
coalesceKey: {
type: "text",
nullable: true
},
coalescedCount: {
type: "integer",
nullable: false
},
attributes: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
},
deliveredAt: {
type: "timestamp",
nullable: true
},
seenAt: {
type: "timestamp",
nullable: true
},
dismissedAt: {
type: "timestamp",
nullable: true
},
archivedAt: {
type: "timestamp",
nullable: true
},
discardedAt: {
type: "timestamp",
nullable: true
},
deliverAt: {
type: "timestamp",
nullable: true
},
summaryAt: {
type: "timestamp",
nullable: true
},
deliveryReason: {
type: "text",
nullable: true
},
deliveryAttempts: {
type: "integer",
nullable: false
},
lastDeliveryAttemptAt: {
type: "timestamp",
nullable: true
},
lastDeliveryError: {
type: "text",
nullable: true
},
deliveredSignalId: {
type: "text",
nullable: true
},
summarySignalId: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
}
};
const HARNESS_SESSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
ownerId: {
type: "text",
nullable: false
},
resourceId: {
type: "text",
nullable: false
},
threadId: {
type: "text",
nullable: false
},
parentSessionId: {
type: "text",
nullable: true
},
subagentDepth: {
type: "integer",
nullable: true
},
source: {
type: "jsonb",
nullable: true
},
origin: {
type: "text",
nullable: false
},
runtimeCompatibilityGeneration: {
type: "text",
nullable: true
},
modeId: {
type: "text",
nullable: false
},
modelId: {
type: "text",
nullable: false
},
title: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
state: {
type: "jsonb",
nullable: true
},
pending: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
lastActivityAt: {
type: "timestamp",
nullable: false
},
closingAt: {
type: "timestamp",
nullable: true
},
closeDeadlineAt: {
type: "timestamp",
nullable: true
},
closedAt: {
type: "timestamp",
nullable: true
},
deletedAt: {
type: "timestamp",
nullable: true
}
};
const THREAD_STATE_SCHEMA = {
threadId: {
type: "text",
nullable: false
},
type: {
type: "text",
nullable: false
},
value: {
type: "jsonb",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const SKILL_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
skillId: {
type: "text",
nullable: false
},
versionNumber: {
type: "integer",
nullable: false
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: false
},
instructions: {
type: "text",
nullable: false
},
license: {
type: "text",
nullable: true
},
compatibility: {
type: "jsonb",
nullable: true
},
source: {
type: "jsonb",
nullable: true
},
references: {
type: "jsonb",
nullable: true
},
scripts: {
type: "jsonb",
nullable: true
},
assets: {
type: "jsonb",
nullable: true
},
files: {
type: "jsonb",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
tree: {
type: "jsonb",
nullable: true
},
changedFields: {
type: "jsonb",
nullable: true
},
changeMessage: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const SKILL_BLOBS_SCHEMA = {
hash: {
type: "text",
nullable: false,
primaryKey: true
},
content: {
type: "text",
nullable: false
},
size: {
type: "integer",
nullable: false
},
mimeType: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const OBSERVATIONAL_MEMORY_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
lookupKey: {
type: "text",
nullable: false
},
scope: {
type: "text",
nullable: false
},
resourceId: {
type: "text",
nullable: true
},
threadId: {
type: "text",
nullable: true
},
activeObservations: {
type: "text",
nullable: false
},
activeObservationsPendingUpdate: {
type: "text",
nullable: true
},
originType: {
type: "text",
nullable: false
},
config: {
type: "text",
nullable: false
},
generationCount: {
type: "integer",
nullable: false
},
supersededBy: OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS.supersededBy,
lastObservedAt: {
type: "timestamp",
nullable: true
},
lastReflectionAt: {
type: "timestamp",
nullable: true
},
pendingMessageTokens: {
type: "integer",
nullable: false
},
totalTokensObserved: {
type: "integer",
nullable: false
},
observationTokenCount: {
type: "integer",
nullable: false
},
isObserving: {
type: "boolean",
nullable: false
},
isReflecting: {
type: "boolean",
nullable: false
},
observedMessageIds: {
type: "jsonb",
nullable: true
},
observedTimezone: {
type: "text",
nullable: true
},
bufferedObservations: {
type: "text",
nullable: true
},
bufferedObservationTokens: {
type: "integer",
nullable: true
},
bufferedMessageIds: {
type: "jsonb",
nullable: true
},
bufferedReflection: {
type: "text",
nullable: true
},
bufferedReflectionTokens: {
type: "integer",
nullable: true
},
bufferedReflectionInputTokens: {
type: "integer",
nullable: true
},
reflectedObservationLineCount: {
type: "integer",
nullable: true
},
bufferedObservationChunks: {
type: "jsonb",
nullable: true
},
isBufferingObservation: {
type: "boolean",
nullable: false
},
isBufferingReflection: {
type: "boolean",
nullable: false
},
lastBufferedAtTokens: {
type: "integer",
nullable: false
},
lastBufferedAtTime: {
type: "timestamp",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const DATASETS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
name: {
type: "text",
nullable: false
},
description: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
inputSchema: {
type: "jsonb",
nullable: true
},
groundTruthSchema: {
type: "jsonb",
nullable: true
},
requestContextSchema: {
type: "jsonb",
nullable: true
},
tags: {
type: "jsonb",
nullable: true
},
targetType: {
type: "text",
nullable: true
},
targetIds: {
type: "jsonb",
nullable: true
},
scorerIds: {
type: "jsonb",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
candidateKey: {
type: "text",
nullable: true
},
candidateId: {
type: "text",
nullable: true
},
version: {
type: "integer",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const DATASET_ITEMS_SCHEMA = {
id: {
type: "text",
nullable: false
},
datasetId: {
type: "text",
nullable: false,
references: {
table: "mastra_datasets",
column: "id"
}
},
datasetVersion: {
type: "integer",
nullable: false
},
externalId: {
type: "text",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
validTo: {
type: "integer",
nullable: true
},
isDeleted: {
type: "boolean",
nullable: false
},
input: {
type: "jsonb",
nullable: false
},
groundTruth: {
type: "jsonb",
nullable: true
},
requestContext: {
type: "jsonb",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
source: {
type: "jsonb",
nullable: true
},
expectedTrajectory: {
type: "jsonb",
nullable: true
},
toolMocks: {
type: "jsonb",
nullable: true
},
unmockedToolPolicy: {
type: "text",
nullable: true
},
scorerIds: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const DATASET_VERSIONS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
datasetId: {
type: "text",
nullable: false,
references: {
table: "mastra_datasets",
column: "id"
}
},
version: {
type: "integer",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const EXPERIMENTS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
name: {
type: "text",
nullable: true
},
description: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
provenance: {
type: "jsonb",
nullable: true
},
runnerAttestation: {
type: "jsonb",
nullable: true
},
experimentSetId: {
type: "text",
nullable: true
},
comparisonId: {
type: "text",
nullable: true
},
variantId: {
type: "text",
nullable: true
},
trialIndex: {
type: "integer",
nullable: true
},
datasetId: {
type: "text",
nullable: true,
references: {
table: "mastra_datasets",
column: "id"
}
},
datasetVersion: {
type: "integer",
nullable: true
},
targetType: {
type: "text",
nullable: true
},
targetId: {
type: "text",
nullable: true
},
scorerIds: {
type: "jsonb",
nullable: true
},
status: {
type: "text",
nullable: false
},
totalItems: {
type: "integer",
nullable: false
},
succeededCount: {
type: "integer",
nullable: false
},
failedCount: {
type: "integer",
nullable: false
},
skippedCount: {
type: "integer",
nullable: false
},
startedAt: {
type: "timestamp",
nullable: true
},
completedAt: {
type: "timestamp",
nullable: true
},
agentVersion: {
type: "text",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const EXPERIMENT_RESULTS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
experimentId: {
type: "text",
nullable: false,
references: {
table: "mastra_experiments",
column: "id"
}
},
itemId: {
type: "text",
nullable: false,
references: {
table: "mastra_dataset_items",
column: "id"
}
},
itemDatasetVersion: {
type: "integer",
nullable: true
},
input: {
type: "jsonb",
nullable: false
},
output: {
type: "jsonb",
nullable: true
},
groundTruth: {
type: "jsonb",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
error: {
type: "jsonb",
nullable: true
},
startedAt: {
type: "timestamp",
nullable: false
},
completedAt: {
type: "timestamp",
nullable: false
},
retryCount: {
type: "integer",
nullable: false
},
attempt: {
type: "integer",
nullable: true
},
traceId: {
type: "text",
nullable: true
},
status: {
type: "text",
nullable: true
},
tags: {
type: "jsonb",
nullable: true
},
comment: {
type: "text",
nullable: true
},
toolMockReport: {
type: "jsonb",
nullable: true
},
organizationId: {
type: "text",
nullable: true
},
projectId: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_NODES_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
type: {
type: "text",
nullable: false
},
name: {
type: "text",
nullable: false
},
canonicalName: {
type: "text",
nullable: false
},
kind: {
type: "text",
nullable: true
},
content: {
type: "text",
nullable: true
},
description: {
type: "text",
nullable: true
},
scope: {
type: "jsonb",
nullable: false
},
scopeKey: {
type: "text",
nullable: false
},
version: {
type: "integer",
nullable: false
},
mergedInto: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_RECORDS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
node: {
type: "text",
nullable: false
},
text: {
type: "text",
nullable: false
},
scope: {
type: "jsonb",
nullable: false
},
scopeKey: {
type: "text",
nullable: false
},
sourceThreadId: {
type: "text",
nullable: false
},
capturedAt: {
type: "timestamp",
nullable: false
},
when: {
type: "timestamp",
nullable: true
},
maxScope: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
deletedAt: {
type: "timestamp",
nullable: true
},
deletedBy: {
type: "text",
nullable: true
}
};
const KNOWLEDGE_MENTIONS_SCHEMA = {
sourceType: {
type: "text",
nullable: false
},
sourceId: {
type: "text",
nullable: false
},
recordId: {
type: "text",
nullable: false
}
};
/**
* @deprecated Curation cursors were removed and Knowledge no longer creates this table. Kept so adapters built
* against earlier Core versions still resolve the export.
*/
const KNOWLEDGE_CURSORS_SCHEMA = {
sourceThreadId: {
type: "text",
nullable: false
},
agent: {
type: "text",
nullable: false
},
lastKnowledgeId: {
type: "text",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_ACTIVITY_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
action: {
type: "text",
nullable: false
},
recordType: {
type: "text",
nullable: false
},
recordId: {
type: "text",
nullable: false
},
scope: {
type: "jsonb",
nullable: false
},
scopeKey: {
type: "text",
nullable: false
},
sourceThreadId: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
idempotencyKey: {
type: "text",
nullable: false
},
documentId: {
type: "text",
nullable: false
},
documentType: {
type: "text",
nullable: false
},
operation: {
type: "text",
nullable: false
},
scope: {
type: "jsonb",
nullable: false
},
scopeKey: {
type: "text",
nullable: false
},
status: {
type: "text",
nullable: false
},
attempts: {
type: "integer",
nullable: false
},
availableAt: {
type: "timestamp",
nullable: false
},
claimedAt: {
type: "timestamp",
nullable: true
},
claimedBy: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
completedAt: {
type: "timestamp",
nullable: true
}
};
/** Normalized Knowledge v2 node schema plus nullable v1 facade columns. */
const KNOWLEDGE_V2_NODES_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
name: {
type: "text",
nullable: false
},
kind: {
type: "text",
nullable: true
},
isScope: {
type: "boolean",
nullable: false
},
metadata: {
type: "jsonb",
nullable: true
},
version: {
type: "integer",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
},
deletedAt: {
type: "timestamp",
nullable: true
},
deletedBy: {
type: "text",
nullable: true
},
type: {
type: "text",
nullable: true
},
canonicalName: {
type: "text",
nullable: true
},
content: {
type: "text",
nullable: true
},
description: {
type: "text",
nullable: true
},
scope: {
type: "jsonb",
nullable: true
},
scopeKey: {
type: "text",
nullable: true
},
mergedInto: {
type: "text",
nullable: true
}
};
/** Knowledge v2 record schema. Scope rules live in `mastra_knowledge_record_scopes`. */
const KNOWLEDGE_V2_RECORDS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
node: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
text: {
type: "text",
nullable: false
},
metadata: {
type: "jsonb",
nullable: true
},
version: {
type: "integer",
nullable: false
},
capturedAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
},
deletedAt: {
type: "timestamp",
nullable: true
},
deletedBy: {
type: "text",
nullable: true
},
scope: {
type: "jsonb",
nullable: true
},
scopeKey: {
type: "text",
nullable: true
},
sourceThreadId: {
type: "text",
nullable: true
},
when: {
type: "timestamp",
nullable: true
}
};
const KNOWLEDGE_V2_MENTIONS_SCHEMA = {
recordId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_RECORDS,
column: "id"
}
},
targetNodeId: {
type: "text",
nullable: true,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
sourceType: {
type: "text",
nullable: true
},
sourceId: {
type: "text",
nullable: true
}
};
const KNOWLEDGE_NODE_SCOPES_SCHEMA = {
nodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
scopeNodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
addedAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_RECORD_SCOPES_SCHEMA = {
recordId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_RECORDS,
column: "id"
}
},
scopeNodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
addedAt: {
type: "timestamp",
nullable: false
}
};
const KNOWLEDGE_SCOPE_GRANTS_SCHEMA = {
scopeNodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
scopeRefId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
role: {
type: "text",
nullable: false
},
canSuggest: {
type: "boolean",
nullable: true
}
};
const KNOWLEDGE_ACCESS_STATE_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
epoch: {
type: "integer",
nullable: false
},
schemaVersion: {
type: "integer",
nullable: false
}
};
const KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA = {
address: {
type: "text",
nullable: false,
primaryKey: true
},
scopeNodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
}
};
const KNOWLEDGE_NODE_ADDRESSES_SCHEMA = {
source: {
type: "text",
nullable: false
},
address: {
type: "text",
nullable: false
},
nodeId: {
type: "text",
nullable: false,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
}
};
const KNOWLEDGE_IMPORT_STATE_SCHEMA = {
importerId: {
type: "text",
nullable: false
},
binding: {
type: "text",
nullable: false
},
key: {
type: "text",
nullable: false
},
value: {
type: "text",
nullable: false
}
};
const KNOWLEDGE_IMPORT_RUNS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
importerId: {
type: "text",
nullable: false
},
binding: {
type: "text",
nullable: false
},
importKind: {
type: "text",
nullable: false
},
triggerKind: {
type: "text",
nullable: false
},
status: {
type: "text",
nullable: false
},
error: {
type: "text",
nullable: true
},
transcriptThreadId: {
type: "text",
nullable: true
},
traceId: {
type: "text",
nullable: true
},
queuedAt: {
type: "timestamp",
nullable: false
},
startedAt: {
type: "timestamp",
nullable: true
},
completedAt: {
type: "timestamp",
nullable: true
}
};
const KNOWLEDGE_V2_ACTIVITY_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
action: {
type: "text",
nullable: false
},
targetType: {
type: "text",
nullable: true
},
targetId: {
type: "text",
nullable: true
},
contextScopeId: {
type: "text",
nullable: true,
references: {
table: TABLE_KNOWLEDGE_NODES,
column: "id"
}
},
importRunId: {
type: "text",
nullable: true,
references: {
table: TABLE_KNOWLEDGE_IMPORT_RUNS,
column: "id"
}
},
details: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
recordType: {
type: "text",
nullable: true
},
recordId: {
type: "text",
nullable: true
},
scope: {
type: "jsonb",
nullable: true
},
scopeKey: {
type: "text",
nullable: true
},
sourceThreadId: {
type: "text",
nullable: true
}
};
const KNOWLEDGE_PROPOSALS_SCHEMA = {
id: {
type: "text",
nullable: false,
primaryKey: true
},
targetType: {
type: "text",
nullable: false
},
targetId: {
type: "text",
nullable: false
},
action: {
type: "text",
nullable: false
},
changes: {
type: "jsonb",
nullable: false
},
reason: {
type: "text",
nullable: true
},
proposerContextScopeId: {
type: "text",
nullable: false
},
expectedVersion: {
type: "integer",
nullable: false
},
status: {
type: "text",
nullable: false
},
reviewerContextScopeId: {
type: "text",
nullable: true
},
reviewedAt: {
type: "timestamp",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
}
};
/**
* Schema definitions for all core tables.
*/
const TABLE_SCHEMAS = {
[TABLE_WORKFLOW_SNAPSHOT]: {
workflow_name: { type: "text" },
run_id: { type: "text" },
resourceId: {
type: "text",
nullable: true
},
snapshot: { type: "jsonb" },
createdAt: { type: "timestamp" },
updatedAt: { type: "timestamp" }
},
[TABLE_SCORERS]: SCORERS_SCHEMA,
[TABLE_THREADS]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
resourceId: {
type: "text",
nullable: false
},
title: {
type: "text",
nullable: false
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
},
[TABLE_MESSAGES]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
thread_id: {
type: "text",
nullable: false
},
content: {
type: "text",
nullable: false
},
role: {
type: "text",
nullable: false
},
type: {
type: "text",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
resourceId: {
type: "text",
nullable: true
}
},
[TABLE_SPANS]: SPAN_SCHEMA,
[TABLE_TRACES]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
parentSpanId: {
type: "text",
nullable: true
},
name: {
type: "text",
nullable: false
},
traceId: {
type: "text",
nullable: false
},
scope: {
type: "text",
nullable: false
},
kind: {
type: "integer",
nullable: false
},
attributes: {
type: "jsonb",
nullable: true
},
status: {
type: "jsonb",
nullable: true
},
events: {
type: "jsonb",
nullable: true
},
links: {
type: "jsonb",
nullable: true
},
other: {
type: "text",
nullable: true
},
startTime: {
type: "bigint",
nullable: false
},
endTime: {
type: "bigint",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
}
},
[TABLE_RESOURCES]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
workingMemory: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
},
[TABLE_AGENTS]: AGENTS_SCHEMA,
[TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,
[TABLE_PROMPT_BLOCKS]: PROMPT_BLOCKS_SCHEMA,
[TABLE_PROMPT_BLOCK_VERSIONS]: PROMPT_BLOCK_VERSIONS_SCHEMA,
[TABLE_SCORER_DEFINITIONS]: SCORER_DEFINITIONS_SCHEMA,
[TABLE_SCORER_DEFINITION_VERSIONS]: SCORER_DEFINITION_VERSIONS_SCHEMA,
[TABLE_MCP_CLIENTS]: MCP_CLIENTS_SCHEMA,
[TABLE_MCP_CLIENT_VERSIONS]: MCP_CLIENT_VERSIONS_SCHEMA,
[TABLE_MCP_SERVERS]: MCP_SERVERS_SCHEMA,
[TABLE_MCP_SERVER_VERSIONS]: MCP_SERVER_VERSIONS_SCHEMA,
[TABLE_WORKSPACES]: WORKSPACES_SCHEMA,
[TABLE_WORKSPACE_VERSIONS]: WORKSPACE_VERSIONS_SCHEMA,
[TABLE_SKILLS]: SKILLS_SCHEMA,
[TABLE_SKILL_VERSIONS]: SKILL_VERSIONS_SCHEMA,
[TABLE_SKILL_BLOBS]: SKILL_BLOBS_SCHEMA,
[TABLE_DATASETS]: DATASETS_SCHEMA,
[TABLE_DATASET_ITEMS]: DATASET_ITEMS_SCHEMA,
[TABLE_DATASET_VERSIONS]: DATASET_VERSIONS_SCHEMA,
[TABLE_EXPERIMENTS]: EXPERIMENTS_SCHEMA,
[TABLE_EXPERIMENT_RESULTS]: EXPERIMENT_RESULTS_SCHEMA,
[TABLE_FAVORITES]: FAVORITES_SCHEMA,
[TABLE_BACKGROUND_TASKS]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
tool_call_id: {
type: "text",
nullable: false
},
tool_name: {
type: "text",
nullable: false
},
agent_id: {
type: "text",
nullable: false
},
run_id: {
type: "text",
nullable: false
},
thread_id: {
type: "text",
nullable: true
},
resource_id: {
type: "text",
nullable: true
},
status: {
type: "text",
nullable: false
},
args: {
type: "jsonb",
nullable: false
},
result: {
type: "jsonb",
nullable: true
},
error: {
type: "jsonb",
nullable: true
},
suspend_payload: {
type: "jsonb",
nullable: true
},
retry_count: {
type: "integer",
nullable: false
},
max_retries: {
type: "integer",
nullable: false
},
timeout_ms: {
type: "integer",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
startedAt: {
type: "timestamp",
nullable: true
},
suspendedAt: {
type: "timestamp",
nullable: true
},
completedAt: {
type: "timestamp",
nullable: true
},
ownerId: {
type: "text",
nullable: true
},
leaseExpiresAt: {
type: "timestamp",
nullable: true
},
expiresAt: {
type: "timestamp",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
}
},
[TABLE_SCHEDULES]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
target: {
type: "jsonb",
nullable: false
},
cron: {
type: "text",
nullable: false
},
timezone: {
type: "text",
nullable: true
},
status: {
type: "text",
nullable: false
},
next_fire_at: {
type: "bigint",
nullable: false
},
last_fire_at: {
type: "bigint",
nullable: true
},
last_run_id: {
type: "text",
nullable: true
},
created_at: {
type: "bigint",
nullable: false
},
updated_at: {
type: "bigint",
nullable: false
},
metadata: {
type: "jsonb",
nullable: true
},
owner_type: {
type: "text",
nullable: true
},
owner_id: {
type: "text",
nullable: true
},
run_at: {
type: "bigint",
nullable: true
},
end_at: {
type: "bigint",
nullable: true
}
},
[TABLE_SCHEDULE_TRIGGERS]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
schedule_id: {
type: "text",
nullable: false
},
run_id: {
type: "text",
nullable: true
},
scheduled_fire_at: {
type: "bigint",
nullable: false
},
actual_fire_at: {
type: "bigint",
nullable: false
},
outcome: {
type: "text",
nullable: false
},
error: {
type: "text",
nullable: true
},
trigger_kind: {
type: "text",
nullable: false
},
parent_trigger_id: {
type: "text",
nullable: true
},
metadata: {
type: "jsonb",
nullable: true
}
},
[TABLE_CHANNEL_INSTALLATIONS]: {
id: {
type: "text",
nullable: false,
primaryKey: true
},
platform: {
type: "text",
nullable: false
},
agentId: {
type: "text",
nullable: false
},
status: {
type: "text",
nullable: false
},
webhookId: {
type: "text",
nullable: true
},
data: {
type: "jsonb",
nullable: false
},
configHash: {
type: "text",
nullable: true
},
error: {
type: "text",
nullable: true
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
},
[TABLE_CHANNEL_CONFIG]: {
platform: {
type: "text",
nullable: false,
primaryKey: true
},
data: {
type: "jsonb",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
},
[TABLE_TOOL_PROVIDER_CONNECTIONS]: TOOL_PROVIDER_CONNECTIONS_SCHEMA,
[TABLE_NOTIFICATIONS]: NOTIFICATIONS_SCHEMA,
[TABLE_HARNESS_SESSIONS]: HARNESS_SESSIONS_SCHEMA,
[TABLE_THREAD_STATE]: THREAD_STATE_SCHEMA,
[TABLE_WORKFLOW_DEFINITIONS]: WORKFLOW_DEFINITIONS_SCHEMA,
[TABLE_KNOWLEDGE_NODES]: KNOWLEDGE_NODES_SCHEMA,
[TABLE_KNOWLEDGE_RECORDS]: KNOWLEDGE_RECORDS_SCHEMA,
[TABLE_KNOWLEDGE_MENTIONS]: KNOWLEDGE_MENTIONS_SCHEMA,
[TABLE_KNOWLEDGE_ACTIVITY]: KNOWLEDGE_ACTIVITY_SCHEMA,
[TABLE_KNOWLEDGE_SEMANTIC_OUTBOX]: KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA
};
/**
* Table-level config for tables that need composite primary keys or other table-level settings.
* Keyed by table name. Tables not listed here use single-column PKs from their schema.
*/
const TABLE_CONFIGS = {
[TABLE_DATASET_ITEMS]: {
columns: DATASET_ITEMS_SCHEMA,
compositePrimaryKey: ["id", "datasetVersion"]
},
[TABLE_FAVORITES]: {
columns: FAVORITES_SCHEMA,
compositePrimaryKey: [
"userId",
"entityType",
"entityId"
]
},
[TABLE_TOOL_PROVIDER_CONNECTIONS]: {
columns: TOOL_PROVIDER_CONNECTIONS_SCHEMA,
compositePrimaryKey: [
"authorId",
"providerId",
"connectionId"
]
},
[TABLE_NOTIFICATIONS]: {
columns: NOTIFICATIONS_SCHEMA,
compositePrimaryKey: ["threadId", "id"]
},
[TABLE_THREAD_STATE]: {
columns: THREAD_STATE_SCHEMA,
compositePrimaryKey: ["threadId", "type"]
},
[TABLE_KNOWLEDGE_MENTIONS]: {
columns: KNOWLEDGE_MENTIONS_SCHEMA,
compositePrimaryKey: [
"sourceType",
"sourceId",
"recordId"
]
}
};
/**
* Schema for the observational memory table.
* Exported separately as OM is optional and not part of TABLE_NAMES.
*/
const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = { [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA };
const TABLE_WORKFLOW_RUN_OWNERS = "mastra_workflow_run_owners";
const TABLE_MEMORY_RUN_FENCES = "mastra_memory_run_fences";
/**
* Run ownership records for workflows stores that support run fencing.
* `leaseExpiresAt` and `updatedAt` are epoch milliseconds on the database
* clock; `leaseExpiresAt` is null once released. `updatedAt` is refreshed by
* every claim, renewal and release and anchors `workflows.runOwnership`
* retention. A run's first generation is the store clock in epoch
* milliseconds, so a run claimed again after its record was pruned still gets
* a higher generation.
*/
const WORKFLOW_RUN_OWNERS_SCHEMA = {
runId: {
type: "text",
nullable: false,
primaryKey: true
},
generation: {
type: "bigint",
nullable: false
},
ownerId: {
type: "text",
nullable: false
},
leaseExpiresAt: {
type: "bigint",
nullable: true
},
updatedAt: {
type: "bigint",
nullable: false
}
};
/**
* The claim each run's memory writes must carry, for memory stores that support run fencing.
* `retiredAt` is epoch milliseconds on the database clock, set once the
* execution holding the fence settles and cleared when the fence is raised
* again. It anchors `memory.runFences` retention; NULL rows are never pruned.
*/
const MEMORY_RUN_FENCES_SCHEMA = {
runId: {
type: "text",
nullable: false,
primaryKey: true
},
generation: {
type: "bigint",
nullable: false
},
ownerId: {
type: "text",
nullable: false
},
retiredAt: {
type: "bigint",
nullable: true
}
};
/**
* Schemas for the run fencing tables.
* Exported separately because only adapters that support run fencing create them,
* so they are not part of TABLE_NAMES.
*/
const RUN_FENCING_TABLE_SCHEMAS = {
[TABLE_WORKFLOW_RUN_OWNERS]: WORKFLOW_RUN_OWNERS_SCHEMA,
[TABLE_MEMORY_RUN_FENCES]: MEMORY_RUN_FENCES_SCHEMA
};
const TABLE_WORKFLOW_RUNS = "mastra_workflow_runs";
const TABLE_WORKFLOW_RUN_ENTRIES = "mastra_workflow_run_entries";
/**
* Storage v2 run headers: the run's `WorkflowRunHeader` (its `WorkflowRunState` without
* `context` and `value`). `status` and `threadId` are copied out of the snapshot so they
* can be filtered and indexed. `lastSeq` is the highest `seq` the run's entries have used;
* it only increases, across checkpoints too. `startStateSeq` is the state version the run's
* current drive started from (see `StoredWorkflowRunHeader`). `stateShared` is set once another
* run's state builds on this run's state, so a checkpoint keeps the earlier state entries and a
* delete knows to detach the runs built on it. `stateSeq`, `statePatchCount`, `statePatchBytes`
* and `stateBytes` track where the run's state chain stands (see `StoredStateColumns`).
* @experimental
*/
const WORKFLOW_RUNS_SCHEMA = {
workflow_name: {
type: "text",
nullable: false
},
run_id: {
type: "text",
nullable: false
},
resourceId: {
type: "text",
nullable: true
},
threadId: {
type: "text",
nullable: true
},
status: {
type: "text",
nullable: false
},
header: {
type: "jsonb",
nullable: false
},
lastSeq: {
type: "integer",
nullable: false
},
startStateSeq: {
type: "integer",
nullable: false
},
stateShared: {
type: "boolean",
nullable: false
},
stateSeq: {
type: "integer",
nullable: false
},
statePatchCount: {
type: "integer",
nullable: false
},
statePatchBytes: {
type: "integer",
nullable: false
},
stateBytes: {
type: "integer",
nullable: true
},
/** Picked when the run is first stored, kept until it is deleted (see `StoredWorkflowRunHeader`). */
runToken: {
type: "text",
nullable: false
},
createdAt: {
type: "timestamp",
nullable: false
},
updatedAt: {
type: "timestamp",
nullable: false
}
};
/**
* Storage v2 run entries: one step result (`kind: 'step'`) or one state entry (`kind` `state`,
* `state-patch`, `state-base` or `state-draft`, `step_id` null; see `WorkflowRunEntry`) per row,
* ordered by `seq` within a run.
* @experimental
*/
const WORKFLOW_RUN_ENTRIES_SCHEMA = {
workflow_name: {
type: "text",
nullable: false
},
run_id: {
type: "text",
nullable: false
},
seq: {
type: "integer",
nullable: false
},
kind: {
type: "text",
nullable: false
},
step_id: {
type: "text",
nullable: true
},
payload: {
type: "jsonb",
nullable: true
}
};
/**
* Table configs for the storage v2 run tables (`storageVersion: 2`).
* Exported separately because only adapters that support run journals create them,
* so they are not part of TABLE_NAMES.
* @experimental
*/
const WORKFLOW_RUN_JOURNAL_TABLE_CONFIGS = {
[TABLE_WORKFLOW_RUNS]: {
columns: WORKFLOW_RUNS_SCHEMA,
compositePrimaryKey: ["workflow_name", "run_id"]
},
[TABLE_WORKFLOW_RUN_ENTRIES]: {
columns: WORKFLOW_RUN_ENTRIES_SCHEMA,
compositePrimaryKey: [
"workflow_name",
"run_id",
"seq"
]
}
};
export { TABLE_CHANNEL_INSTALLATIONS as $, listTracesLightResponseSchema as $n, TABLE_WORKSPACES as $t, MCP_CLIENTS_SCHEMA as A, computeTraceStatus as An, scoringHookInputSchema as Ar, TABLE_OBSERVATIONAL_MEMORY as At, PROMPT_BLOCK_VERSIONS_SCHEMA as B, getSpansArgsSchema as Bn, TABLE_SKILLS as Bt, KNOWLEDGE_SCOPE_GRANTS_SCHEMA as C, branchesFilterSchema as Cn, extractWorkflowTrajectory as Cr, TABLE_MCP_CLIENTS as Ct, KNOWLEDGE_V2_MENTIONS_SCHEMA as D, buildPreview as Dn, scoreRowDataSchema as Dr, TABLE_MEMORY_RUN_FENCES as Dt, KNOWLEDGE_V2_ACTIVITY_SCHEMA as E, buildInputPreview as En, scoreResultSchema as Er, TABLE_MCP_SERVER_VERSIONS as Et, NOTIFICATIONS_SCHEMA as F, getBranchResponseSchema as Fn, scoringPromptsSchema as Fr, TABLE_SCHEDULE_TRIGGERS as Ft, SKILLS_SCHEMA as G, getTraceLightResponseSchema as Gn, TABLE_THREAD_STATE as Gt, SCORERS_SCHEMA as H, getStringAttribute as Hn, TABLE_SKILL_VERSIONS as Ht, OBSERVATIONAL_MEMORY_SCHEMA as I, getRootSpanArgsSchema as In, scoringSourceSchema as Ir, TABLE_SCHEMAS as It, SPAN_SCHEMA as J, lightSpanRecordSchema as Jn, TABLE_WORKFLOW_DEFINITIONS as Jt, SKILL_BLOBS_SCHEMA as K, getTraceResponseSchema as Kn, TABLE_TOOL_PROVIDER_CONNECTIONS as Kt, OBSERVATIONAL_MEMORY_TABLE_SCHEMA as L, getRootSpanResponseSchema as Ln, scoringValueSchema as Lr, TABLE_SCORERS as Lt, MCP_SERVERS_SCHEMA as M, createSpanRecordSchema as Mn, scoringInputWithExtractStepResultAndAnalyzeStepResultSchema as Mr, TABLE_PROMPT_BLOCK_VERSIONS as Mt, MCP_SERVER_VERSIONS_SCHEMA as N, extractBranchSpans as Nn, scoringInputWithExtractStepResultAndScoreAndReasonSchema as Nr, TABLE_RESOURCES as Nt, KNOWLEDGE_V2_NODES_SCHEMA as O, buildPreviewFromJson as On, scoringEntityTypeSchema as Or, TABLE_MESSAGES as Ot, MEMORY_RUN_FENCES_SCHEMA as P, getBranchArgsSchema as Pn, scoringInputWithExtractStepResultSchema as Pr, TABLE_SCHEDULES as Pt, TABLE_CHANNEL_CONFIG as Q, listTracesArgsSchema as Qn, TABLE_WORKFLOW_SNAPSHOT as Qt, OLD_SPAN_SCHEMA as R, getSpanArgsSchema as Rn, TABLE_SCORER_DEFINITIONS as Rt, KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA as S, batchUpdateSpansArgsSchema as Sn, extractTrajectoryFromTrace as Sr, TABLE_KNOWLEDGE_SEMANTIC_OUTBOX as St, KNOWLEDGE_TABLE_NAMES as T, branchesOrderBySchema as Tn, saveScorePayloadSchema as Tr, TABLE_MCP_SERVERS as Tt, SCORER_DEFINITIONS_SCHEMA as U, getStructureResponseSchema as Un, TABLE_SPANS as Ut, RUN_FENCING_TABLE_SCHEMAS as V, getSpansResponseSchema as Vn, TABLE_SKILL_BLOBS as Vt, SCORER_DEFINITION_VERSIONS_SCHEMA as W, getTraceArgsSchema as Wn, TABLE_THREADS as Wt, TABLE_AGENT_VERSIONS as X, listBranchesResponseSchema as Xn, TABLE_WORKFLOW_RUN_ENTRIES as Xt, TABLE_AGENTS as Y, listBranchesArgsSchema as Yn, TABLE_WORKFLOW_RUNS as Yt, TABLE_BACKGROUND_TASKS as Z, listScoresBySpanResponseSchema as Zn, TABLE_WORKFLOW_RUN_OWNERS as Zt, KNOWLEDGE_NODE_ADDRESSES_SCHEMA as _, INPUT_PREVIEW_MAX_LENGTH as _n, isAppendOnlySince as _r, TABLE_KNOWLEDGE_PROPOSALS as _t, DATASET_VERSIONS_SCHEMA as a, WORKFLOW_RUN_ENTRIES_SCHEMA as an, spanRecordSchema as ar, TABLE_EXPERIMENT_RESULTS as at, KNOWLEDGE_RECORDS_SCHEMA as b, batchDeleteTracesArgsSchema as bn, planReflectionGenerationText as br, TABLE_KNOWLEDGE_SCOPE_ADDRESSES as bt, FAVORITES_SCHEMA as c, WORKSPACES_SCHEMA as cn, toTraceSpans as cr, TABLE_KNOWLEDGE_ACCESS_STATE as ct, KNOWLEDGE_ACTIVITY_SCHEMA as d, STORAGE_VISIBILITY_VALUES as dn, tracesOrderByFieldSchema as dr, TABLE_KNOWLEDGE_IMPORT_RUNS as dt, TABLE_WORKSPACE_VERSIONS as en, listTracesResponseSchema as er, TABLE_CONFIGS as et, KNOWLEDGE_CURSORS_SCHEMA as f, buildStorageSchema as fn, tracesOrderBySchema as fr, TABLE_KNOWLEDGE_IMPORT_STATE as ft, KNOWLEDGE_NODES_SCHEMA as g, BRANCH_SPAN_TYPE_SET as gn, compareObservationalMemoryHeadOrder as gr, TABLE_KNOWLEDGE_NODE_SCOPES as gt, KNOWLEDGE_MENTIONS_SCHEMA as h, BRANCH_SPAN_TYPES as hn, assertActiveObservationsApplied as hr, TABLE_KNOWLEDGE_NODE_ADDRESSES as ht, DATASET_ITEMS_SCHEMA as i, WORKFLOW_RUNS_SCHEMA as in, spanIdsSchema as ir, TABLE_EXPERIMENTS as it, MCP_CLIENT_VERSIONS_SCHEMA as j, createSpanArgsSchema as jn, scoringInputSchema as jr, TABLE_PROMPT_BLOCKS as jt, KNOWLEDGE_V2_RECORDS_SCHEMA as k, buildStoredPreview as kn, scoringExtractStepResultSchema as kr, TABLE_NOTIFICATIONS as kt, HARNESS_SESSIONS_SCHEMA as l, WORKSPACE_VERSIONS_SCHEMA as ln, traceSpanSchema as lr, TABLE_KNOWLEDGE_ACTIVITY as lt, KNOWLEDGE_IMPORT_STATE_SCHEMA as m, BATCH_DELETE_TRACES_MAX_IDS as mn, updateSpanRecordSchema as mr, TABLE_KNOWLEDGE_NODES as mt, AGENT_VERSIONS_SCHEMA as n, TOOL_PROVIDER_CONNECTIONS_SCHEMA as nn, scoreTracesResponseSchema as nr, TABLE_DATASET_ITEMS as nt, EXPERIMENTS_SCHEMA as o, WORKFLOW_RUN_JOURNAL_TABLE_CONFIGS as on, toLightSpanRecord as or, TABLE_FAVORITES as ot, KNOWLEDGE_IMPORT_RUNS_SCHEMA as p, matchesExpectedWorkflowStatus as pn, updateSpanArgsSchema as pr, TABLE_KNOWLEDGE_MENTIONS as pt, SKILL_VERSIONS_SCHEMA as q, isPreviewTruncated as qn, TABLE_TRACES as qt, DATASETS_SCHEMA as r, WORKFLOW_DEFINITIONS_SCHEMA as rn, spanIds as rr, TABLE_DATASET_VERSIONS as rt, EXPERIMENT_RESULTS_SCHEMA as s, WORKFLOW_RUN_OWNERS_SCHEMA as sn, toTraceSpan as sr, TABLE_HARNESS_SESSIONS as st, AGENTS_SCHEMA as t, THREAD_STATE_SCHEMA as tn, scoreTracesRequestSchema as tr, TABLE_DATASETS as tt, KNOWLEDGE_ACCESS_STATE_SCHEMA as u, STORAGE_FAVORITE_ENTITY_TYPES as un, tracesFilterSchema as ur, TABLE_KNOWLEDGE_CURSORS as ut, KNOWLEDGE_NODE_SCOPES_SCHEMA as v, TraceStatus as vn, isBufferedChunkCoveredByCursor as vr, TABLE_KNOWLEDGE_RECORDS as vt, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA as w, branchesOrderByFieldSchema as wn, listScoresResponseSchema as wr, TABLE_MCP_CLIENT_VERSIONS as wt, KNOWLEDGE_RECORD_SCOPES_SCHEMA as x, batchDeleteTracesResponseSchema as xn, extractTrajectory as xr, TABLE_KNOWLEDGE_SCOPE_GRANTS as xt, KNOWLEDGE_PROPOSALS_SCHEMA as y, batchCreateSpansArgsSchema as yn, maxObservationCursor as yr, TABLE_KNOWLEDGE_RECORD_SCOPES as yt, PROMPT_BLOCKS_SCHEMA as z, getSpanResponseSchema as zn, TABLE_SCORER_DEFINITION_VERSIONS as zt };
//# sourceMappingURL=constants-Bkej7sJF.js.map