@mastra/core
Version:
1 lines • 325 kB
Source Map (JSON)
{"version":3,"file":"constants-w82mEDLt.cjs","names":["z","SpanType","dbTimestamps","paginationInfoSchema","z","SpanType","spanContextFields","metadataField","tagsField","traceIdField","spanIdField","dbTimestamps","truncatePreview","dateRangeSchema","sortDirectionSchema","listModeSchema","paginationArgsSchema","deltaCursorSchema","deltaLimitSchema","refineObservabilityListMode","normalizeObservabilityListArgs","paginationInfoSchema","deltaInfoSchema","organizationIdField","resourceIdField","getZodTypeName","getZodInnerType","zodV4","zodV3"],"sources":["../src/evals/types.ts","../../_internal-core/dist/memory/index.js","../src/storage/domains/observability/tracing.ts","../src/storage/types.ts","../src/storage/constants.ts"],"sourcesContent":["import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod/v4';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { ObservabilityContext } from '../observability';\nimport type { SpanRecord } from '../storage/domains/observability/tracing';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\nimport type { StepResult } from '../workflows/types';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum([\n 'AGENT',\n 'WORKFLOW',\n 'TRAJECTORY',\n 'STEP',\n // Experiment targets emitted as `targetType.toUpperCase()` (scorer/processor runs).\n 'SCORER',\n 'PROCESSOR',\n // Externally executed experiment items (targetType: 'external')\n 'EXTERNAL',\n ...Object.values(SpanType),\n] as [string, string, ...string[]]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n description: z.string(),\n prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n runId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n // Note: observabilityContext is not serializable, so we don't include it in the schema\n // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & Partial<ObservabilityContext>;\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n runId: z.string().optional(),\n scorer: recordSchema,\n input: z.unknown(),\n output: z.unknown(),\n metadata: optionalRecordSchema,\n additionalContext: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema,\n requestContext: optionalRecordSchema,\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Tenancy: organizationId arrives via ObservabilityContext; projectId is scores-specific.\n projectId: z.string().optional(),\n // Note: observabilityContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & Partial<ObservabilityContext>;\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n result: optionalRecordSchema,\n score: scoringValueSchema,\n prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n runId: z.string(), // Required in this context\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultSchema>,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n} & Partial<ObservabilityContext>;\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n} & Partial<ObservabilityContext>;\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> &\n Partial<ObservabilityContext>;\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n id: z.string(),\n scorerId: z.string(),\n entityId: z.string(),\n\n // From ScoringInputWithExtractStepResultAndScoreAndReason\n runId: z.string(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n\n // From ScoringHookInput\n scorer: recordSchema,\n metadata: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema.optional(),\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Multi-tenant scope. `resourceId` is overloaded (memory end-user), so tenancy\n // uses dedicated fields: organizationId (account) + projectId (project scope).\n organizationId: z.string().nullish(),\n projectId: z.string().nullish(),\n // Batch handle shared across all per-trace scores produced by one batch scoring\n // call. `runId` stays per-execution; `batchId` groups the batch.\n batchId: z.string().nullish(),\n // Dataset provenance: links a baseline score back to the curated dataset item it\n // scored, so scores can join to ground truth without re-running the agent.\n datasetId: z.string().nullish(),\n datasetItemId: z.string().nullish(),\n\n // Additional ScoreRowData fields\n preprocessStepResult: optionalRecordSchema,\n preprocessPrompt: z.string().optional(),\n generateScorePrompt: z.string().optional(),\n generateReasonPrompt: z.string().optional(),\n\n // Timestamps\n ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema\n .omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n })\n .extend({\n /**\n * Optional caller-supplied stable id. When provided, storage adapters\n * upsert by this id (latest write wins) instead of inserting a new row\n * with a random id. Used by caller-driven experiments so retried\n * submissions converge on one score row per (experiment, item, attempt,\n * scorer).\n */\n id: z.string().optional(),\n });\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n name: string;\n description: string;\n extract?: ExtractionStepFn;\n analyze: AnalyzeStepFn;\n reason?: ReasonStepFn;\n metadata?: Record<string, any>;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n\n// ============================================================================\n// Trajectory Types — Discriminated Union\n// ============================================================================\n\n/**\n * Base properties shared by all trajectory step types.\n */\nexport type TrajectoryStepBase = {\n /** Name of the tool called, model used, or step executed */\n name: string;\n /** Duration of this step in milliseconds */\n durationMs?: number;\n /** Additional metadata about this step */\n metadata?: Record<string, unknown>;\n /** Nested child steps (e.g., tool calls inside a workflow step, or steps inside an agent run) */\n children?: TrajectoryStep[];\n};\n\n// --- Individual step types ---\n\nexport type ToolCallStep = TrajectoryStepBase & {\n stepType: 'tool_call';\n /** Arguments passed to the tool */\n toolArgs?: Record<string, unknown>;\n /** Result returned by the tool */\n toolResult?: Record<string, unknown>;\n /** Whether the tool call succeeded */\n success?: boolean;\n};\n\nexport type McpToolCallStep = TrajectoryStepBase & {\n stepType: 'mcp_tool_call';\n /** Arguments passed to the MCP tool */\n toolArgs?: Record<string, unknown>;\n /** Result returned by the MCP tool */\n toolResult?: Record<string, unknown>;\n /** The MCP server that handled this tool call */\n mcpServer?: string;\n /** Whether the tool call succeeded */\n success?: boolean;\n};\n\nexport type ProviderToolCallStep = TrajectoryStepBase & {\n stepType: 'provider_tool_call';\n /** Arguments passed to the server-side tool */\n toolArgs?: Record<string, unknown>;\n /** Result returned by the server-side tool */\n toolResult?: Record<string, unknown>;\n /** Whether the tool call succeeded */\n success?: boolean;\n};\n\nexport type ModelGenerationStep = TrajectoryStepBase & {\n stepType: 'model_generation';\n /** The model ID used for generation */\n modelId?: string;\n /** Number of prompt tokens consumed */\n promptTokens?: number;\n /** Number of completion tokens generated */\n completionTokens?: number;\n /** Reason the generation finished (e.g., 'stop', 'tool-calls') */\n finishReason?: string;\n};\n\nexport type AgentRunStep = TrajectoryStepBase & {\n stepType: 'agent_run';\n /** The ID of the agent that was run */\n agentId?: string;\n};\n\nexport type WorkflowStepStep = TrajectoryStepBase & {\n stepType: 'workflow_step';\n /** The step ID within the workflow */\n stepId?: string;\n /** Status of the step (e.g., 'success', 'failed', 'suspended') */\n status?: string;\n /** Output data from the step */\n output?: Record<string, unknown>;\n};\n\nexport type WorkflowRunStep = TrajectoryStepBase & {\n stepType: 'workflow_run';\n /** The ID of the workflow that was run */\n workflowId?: string;\n /** Status of the workflow run */\n status?: string;\n};\n\nexport type WorkflowConditionalStep = TrajectoryStepBase & {\n stepType: 'workflow_conditional';\n /** Number of conditions evaluated */\n conditionCount?: number;\n /** Steps selected by the conditional */\n selectedSteps?: string[];\n};\n\nexport type WorkflowParallelStep = TrajectoryStepBase & {\n stepType: 'workflow_parallel';\n /** Number of parallel branches */\n branchCount?: number;\n /** Steps that ran in parallel */\n parallelSteps?: string[];\n};\n\nexport type WorkflowLoopStep = TrajectoryStepBase & {\n stepType: 'workflow_loop';\n /** Type of loop (e.g., 'dowhile', 'dountil') */\n loopType?: string;\n /** Total number of iterations executed */\n totalIterations?: number;\n};\n\nexport type WorkflowSleepStep = TrajectoryStepBase & {\n stepType: 'workflow_sleep';\n /** Sleep duration in milliseconds */\n sleepDurationMs?: number;\n /** Type of sleep */\n sleepType?: string;\n};\n\nexport type WorkflowWaitEventStep = TrajectoryStepBase & {\n stepType: 'workflow_wait_event';\n /** Name of the event being waited on */\n eventName?: string;\n /** Whether the event was received */\n eventReceived?: boolean;\n};\n\nexport type ProcessorRunStep = TrajectoryStepBase & {\n stepType: 'processor_run';\n /** The ID of the processor that was run */\n processorId?: string;\n};\n\n/**\n * A single step in an agent's or workflow's trajectory.\n * Discriminated union on `stepType` — each variant carries properties specific\n * to that kind of action.\n */\nexport type TrajectoryStep =\n | ToolCallStep\n | McpToolCallStep\n | ProviderToolCallStep\n | ModelGenerationStep\n | AgentRunStep\n | WorkflowStepStep\n | WorkflowRunStep\n | WorkflowConditionalStep\n | WorkflowParallelStep\n | WorkflowLoopStep\n | WorkflowSleepStep\n | WorkflowWaitEventStep\n | ProcessorRunStep;\n\n/**\n * The type of action taken in a trajectory step.\n * Derived from the discriminated union for convenience.\n */\nexport type TrajectoryStepType = TrajectoryStep['stepType'];\n\n/**\n * A complete trajectory: the ordered sequence of steps an agent or workflow took\n * to go from input to output.\n */\nexport type Trajectory = {\n /** Ordered list of steps taken */\n steps: TrajectoryStep[];\n /** Total duration of the full trajectory in milliseconds */\n totalDurationMs?: number;\n /** The raw agent output messages, preserved for scorers that need text context */\n rawOutput?: ScorerRunOutputForAgent;\n /** The raw workflow result, preserved for scorers that need workflow-specific data */\n rawWorkflowResult?: {\n stepResults: Record<string, StepResult<any, any, any, any>>;\n stepExecutionPath?: string[];\n };\n};\n\n/**\n * Configuration for trajectory comparison behavior.\n */\nexport type TrajectoryComparisonOptions = {\n /**\n * How to compare step ordering.\n * - 'strict': exact match (same steps, same order, no extras)\n * - 'relaxed': subsequence match (extra steps OK, order matters)\n * - 'unordered': just check presence (don't care about order)\n * @default 'relaxed'\n */\n ordering?: 'strict' | 'relaxed' | 'unordered';\n /**\n * Whether to allow repeated steps in the trajectory.\n * When false, repeated steps (loops) are penalized.\n * @default true\n */\n allowRepeatedSteps?: boolean;\n};\n\n/**\n * Discriminated union mirroring `TrajectoryStep` — specify a `stepType` for autocomplete\n * on that variant's fields (e.g., `toolArgs` for `tool_call`). All variant-specific fields\n * are optional; only specified fields are used for comparison.\n *\n * Omit `stepType` to match any step by name only.\n *\n * @example\n * ```ts\n * // Match any step named 'search'\n * { name: 'search' }\n *\n * // Match a tool_call with specific args (autocomplete for toolArgs, toolResult, success)\n * { name: 'search', stepType: 'tool_call', toolArgs: { query: 'weather' } }\n *\n * // Match an agent run with nested expectations for its children\n * {\n * name: 'researchAgent',\n * stepType: 'agent_run',\n * children: {\n * ordering: 'unordered',\n * steps: [\n * { name: 'search', stepType: 'tool_call' },\n * { name: 'summarize', stepType: 'tool_call' },\n * ],\n * },\n * }\n * ```\n */\n/**\n * Utility type: derive an expected-step variant from an actual TrajectoryStep variant.\n *\n * - Keeps `name` and `stepType` required (for discriminant narrowing)\n * - Makes all other variant-specific fields optional\n * - Drops `durationMs` and `metadata` (not useful for expectations)\n * - Replaces `children: TrajectoryStep[]` with `children: TrajectoryExpectation`\n */\ntype ToExpected<T extends TrajectoryStep> = Pick<T, 'name' | 'stepType'> &\n Partial<Omit<T, 'name' | 'stepType' | 'children' | 'durationMs' | 'metadata'>> & {\n /** Nested trajectory expectation for this step's children */\n children?: TrajectoryExpectation;\n };\n\n/**\n * Expected step with no specific `stepType` — matches any step by name only.\n * Use this when you don't care about the step type, just the name.\n */\ntype ExpectedGenericStep = {\n /** Step name to match (tool name, agent ID, workflow step name, etc.) */\n name: string;\n /** Must be omitted for generic matching */\n stepType?: undefined;\n /** Nested trajectory expectation for this step's children */\n children?: TrajectoryExpectation;\n};\n\n/**\n * A step expectation for trajectory evaluation.\n *\n * Discriminated union derived from `TrajectoryStep` — when you specify a `stepType`,\n * you get autocomplete for that variant's fields (e.g., `toolArgs` for `tool_call`).\n * Omit `stepType` to match any step by name only.\n *\n * @example\n * ```ts\n * // Name-only matching (any step type)\n * { name: 'search' }\n *\n * // Type-narrowed with autocomplete for toolArgs, toolResult, success\n * { name: 'search', stepType: 'tool_call', toolArgs: { query: 'weather' } }\n *\n * // Nested expectations for a sub-agent\n * {\n * name: 'research-agent',\n * stepType: 'agent_run',\n * children: {\n * ordering: 'unordered',\n * steps: [\n * { name: 'search', stepType: 'tool_call' },\n * { name: 'summarize', stepType: 'tool_call' },\n * ],\n * },\n * }\n * ```\n */\nexport type ExpectedStep =\n | ToExpected<ToolCallStep>\n | ToExpected<McpToolCallStep>\n | ToExpected<ProviderToolCallStep>\n | ToExpected<ModelGenerationStep>\n | ToExpected<AgentRunStep>\n | ToExpected<WorkflowStepStep>\n | ToExpected<WorkflowRunStep>\n | ToExpected<WorkflowConditionalStep>\n | ToExpected<WorkflowParallelStep>\n | ToExpected<WorkflowLoopStep>\n | ToExpected<WorkflowSleepStep>\n | ToExpected<WorkflowWaitEventStep>\n | ToExpected<ProcessorRunStep>\n | ExpectedGenericStep;\n\n/**\n * Full trajectory expectation config for the unified trajectory scorer.\n * Can be set as constructor defaults (agent-level) or per dataset item (prompt-specific).\n * Per-item values override constructor defaults.\n */\nexport type TrajectoryExpectation = {\n // --- Accuracy ---\n\n /** Expected steps for accuracy checking */\n steps?: ExpectedStep[];\n\n /**\n * How to compare step ordering.\n * - 'strict': exact match (same steps, same order, no extras)\n * - 'relaxed': subsequence match (extra steps OK, order matters)\n * - 'unordered': just check presence (don't care about order)\n * @default 'relaxed'\n */\n ordering?: 'strict' | 'relaxed' | 'unordered';\n\n /** Whether to allow repeated steps in accuracy evaluation. @default true */\n allowRepeatedSteps?: boolean;\n\n // --- Efficiency ---\n\n /** Maximum number of steps allowed */\n maxSteps?: number;\n\n /** Maximum total tokens across all model_generation steps */\n maxTotalTokens?: number;\n\n /** Maximum total duration in milliseconds */\n maxTotalDurationMs?: number;\n\n /** Whether to penalize redundant calls (same tool + same args consecutively). @default true */\n noRedundantCalls?: boolean;\n\n // --- Blacklist ---\n\n /** Tool names that should never appear in the trajectory */\n blacklistedTools?: string[];\n\n /** Tool name sequences that should never appear (contiguous subsequences) */\n blacklistedSequences?: string[][];\n\n // --- Tool failure tolerance ---\n\n /** Maximum acceptable retries per tool before penalizing. @default 2 */\n maxRetriesPerTool?: number;\n};\n\n// ============================================================================\n// Trajectory Extraction — Agent\n// ============================================================================\n\n/**\n * Extracts a Trajectory from agent output messages by walking through\n * tool invocations.\n *\n * This is called automatically by `runEvals` when using `AgentScorerConfig.trajectory`\n * scorers — trajectory scorers receive a pre-extracted `Trajectory` as their `output`\n * instead of raw `MastraDBMessage[]`.\n *\n * @param output - The raw agent output messages\n * @returns A Trajectory with ToolCallStep entries extracted from tool invocations\n */\nexport function extractTrajectory(output: ScorerRunOutputForAgent): Trajectory {\n const steps: ToolCallStep[] = [];\n\n for (const message of output) {\n // Native parts retain thrown calls that the legacy array may omit.\n // Merge by call ID while retaining compatible order from both forms.\n const legacy = message?.content?.toolInvocations;\n const fromParts =\n message?.content?.parts\n ?.filter((p): p is Extract<typeof p, { type: 'tool-invocation' }> => p.type === 'tool-invocation')\n .map(p => p.toolInvocation)\n .filter(Boolean) ?? [];\n const partCallIds = new Set(fromParts.map(invocation => invocation.toolCallId).filter(Boolean));\n const legacyInvocations = legacy ?? [];\n const legacyPositions = new Map(legacyInvocations.map((invocation, index) => [invocation?.toolCallId, index]));\n const toolInvocations: typeof fromParts = [];\n let legacyIndex = 0;\n for (const invocation of fromParts) {\n const sharedIndex = invocation.toolCallId ? legacyPositions.get(invocation.toolCallId) : undefined;\n if (sharedIndex !== undefined && sharedIndex >= legacyIndex) {\n // Retain legacy-only calls before their next shared anchor.\n for (; legacyIndex < sharedIndex; legacyIndex++) {\n const previous = legacyInvocations[legacyIndex];\n if (previous && !partCallIds.has(previous.toolCallId)) toolInvocations.push(previous);\n }\n legacyIndex++;\n }\n toolInvocations.push(invocation);\n }\n for (; legacyIndex < legacyInvocations.length; legacyIndex++) {\n const invocation = legacyInvocations[legacyIndex];\n if (invocation && !partCallIds.has(invocation.toolCallId)) toolInvocations.push(invocation);\n }\n if (!toolInvocations?.length) continue;\n\n for (const invocation of toolInvocations) {\n if (\n invocation &&\n invocation.toolName &&\n (invocation.state === 'result' || invocation.state === 'call' || invocation.state === 'output-error')\n ) {\n const toolArgs =\n invocation.args != null && typeof invocation.args === 'object' && !Array.isArray(invocation.args)\n ? (invocation.args as Record<string, unknown>)\n : invocation.args != null\n ? { value: invocation.args }\n : undefined;\n\n const rawResult = invocation.state === 'result' ? invocation.result : undefined;\n const toolResult =\n rawResult != null && typeof rawResult === 'object' && !Array.isArray(rawResult)\n ? (rawResult as Record<string, unknown>)\n : rawResult != null\n ? { value: rawResult }\n : undefined;\n\n steps.push({\n stepType: 'tool_call',\n name: invocation.toolName,\n toolArgs,\n toolResult,\n success: invocation.state === 'result' && invocation.isError !== true,\n });\n }\n }\n }\n\n return { steps, rawOutput: output };\n}\n\n// ============================================================================\n// Trajectory Extraction — Workflow\n// ============================================================================\n\n/**\n * Extracts a Trajectory from workflow step results.\n *\n * Converts the `stepResults` record (and optional `stepExecutionPath` ordering)\n * into a flat list of `WorkflowStepStep` entries. Each step captures its status,\n * output, and timing.\n *\n * This is called automatically by `runEvals` when using `WorkflowScorerConfig.trajectory`\n * scorers.\n *\n * @param stepResults - The workflow step results record\n * @param stepExecutionPath - Optional ordered list of step IDs for execution ordering\n * @returns A Trajectory with WorkflowStepStep entries\n */\nexport function extractWorkflowTrajectory(\n stepResults: Record<string, StepResult<any, any, any, any>>,\n stepExecutionPath?: string[],\n): Trajectory {\n const steps: WorkflowStepStep[] = [];\n\n // Use stepExecutionPath ordering when available, fall back to stepResults keys\n const stepIds = stepExecutionPath ?? Object.keys(stepResults);\n\n let totalStartedAt: number | undefined;\n let totalEndedAt: number | undefined;\n\n for (const stepId of stepIds) {\n const result = stepResults[stepId];\n if (!result) continue;\n\n // Track overall timing\n if (result.startedAt != null) {\n if (totalStartedAt == null || result.startedAt < totalStartedAt) {\n totalStartedAt = result.startedAt;\n }\n }\n\n const endedAt = 'endedAt' in result ? (result as { endedAt?: number }).endedAt : undefined;\n if (endedAt != null) {\n if (totalEndedAt == null || endedAt > totalEndedAt) {\n totalEndedAt = endedAt;\n }\n }\n\n const durationMs = result.startedAt != null && endedAt != null ? endedAt - result.startedAt : undefined;\n\n const output =\n 'output' in result && result.output != null && typeof result.output === 'object' && !Array.isArray(result.output)\n ? (result.output as Record<string, unknown>)\n : 'output' in result && result.output != null\n ? { value: result.output }\n : undefined;\n\n steps.push({\n stepType: 'workflow_step',\n name: stepId,\n stepId,\n status: result.status,\n output,\n durationMs,\n metadata: result.metadata as Record<string, unknown> | undefined,\n });\n }\n\n const totalDurationMs = totalStartedAt != null && totalEndedAt != null ? totalEndedAt - totalStartedAt : undefined;\n\n return {\n steps,\n totalDurationMs,\n rawWorkflowResult: { stepResults, stepExecutionPath },\n };\n}\n\n// ============================================================================\n// Trajectory Extraction — From Trace (Hierarchical)\n// ============================================================================\n\n/**\n * Span types that are considered noise and should be skipped during\n * trace-to-trajectory conversion (internal implementation details, not\n * meaningful trajectory steps).\n */\nconst SKIPPED_SPAN_TYPES = new Set([\n SpanType.SCORER_RUN,\n SpanType.SCORER_STEP,\n SpanType.GENERIC,\n // Retained for traces recorded before skill spans moved to SKILL_ACTION.\n // SKILL_ACTION is deliberately NOT skipped: it now also covers the skill\n // tools (activate/search/read), which are model-initiated trajectory steps\n // and were never skipped when they were WORKSPACE_ACTION spans.\n SpanType.SKILL_RESOLUTION,\n SpanType.MODEL_STEP,\n SpanType.MODEL_INFERENCE,\n SpanType.MODEL_CHUNK,\n SpanType.WORKFLOW_CONDITIONAL_EVAL,\n]);\n\ntype SpanTreeNode = {\n span: SpanRecord;\n children: SpanTreeNode[];\n};\n\n/**\n * Converts a `SpanTreeNode` to `TrajectoryStep` entries.\n *\n * Returns an array because a skipped span promotes its children into the\n * parent's list rather than dropping them entirely.\n */\nfunction spanToTrajectorySteps(node: SpanTreeNode): TrajectoryStep[] {\n const { span, children: childNodes } = node;\n\n if (SKIPPED_SPAN_TYPES.has(span.spanType)) {\n // Promote children of skipped spans so their subtree is preserved\n return childNodes.flatMap(spanToTrajectorySteps);\n }\n\n const durationMs =\n span.endedAt != null && span.startedAt != null ? span.endedAt.getTime() - span.startedAt.getTime() : undefined;\n\n const childSteps = childNodes.flatMap(spanToTrajectorySteps);\n\n const base: TrajectoryStepBase = {\n name: span.name,\n durationMs,\n metadata: span.metadata as Record<string, unknown> | undefined,\n ...(childSteps.length > 0 ? { children: childSteps } : {}),\n };\n\n const attrs = (span.attributes ?? {}) as Record<string, unknown>;\n\n switch (span.spanType) {\n case SpanType.TOOL_CALL: {\n const toolArgs = toRecordOrUndefined(span.input);\n const toolResult = toRecordOrUndefined(span.output);\n return [\n {\n ...base,\n stepType: 'tool_call' as const,\n name: span.entityId ?? span.entityName ?? span.name,\n toolArgs,\n toolResult,\n success: typeof attrs.success === 'boolean' ? attrs.success : undefined,\n },\n ];\n }\n\n case SpanType.MCP_TOOL_CALL: {\n const toolArgs = toRecordOrUndefined(span.input);\n const toolResult = toRecordOrUndefined(span.output);\n return [\n {\n ...base,\n stepType: 'mcp_tool_call' as const,\n name: span.entityId ?? span.entityName ?? span.name,\n toolArgs,\n toolResult,\n mcpServer: typeof attrs.mcpServer === 'string' ? attrs.mcpServer : undefined,\n success: typeof attrs.success === 'boolean' ? attrs.success : undefined,\n },\n ];\n }\n\n case SpanType.PROVIDER_TOOL_CALL: {\n const toolArgs = toRecordOrUndefined(span.input);\n const toolResult = toRecordOrUndefined(span.output);\n return [\n {\n ...base,\n stepType: 'provider_tool_call' as const,\n name: span.entityId ?? span.entityName ?? span.name,\n toolArgs,\n toolResult,\n success: typeof attrs.success === 'boolean' ? attrs.success : undefined,\n },\n ];\n }\n\n case SpanType.MODEL_GENERATION: {\n const usage = attrs.usage as { inputTokens?: number; outputTokens?: number } | undefined;\n return [\n {\n ...base,\n stepType: 'model_generation' as const,\n modelId: typeof attrs.model === 'string' ? attrs.model : undefined,\n promptTokens: usage?.inputTokens,\n completionTokens: usage?.outputTokens,\n finishReason: typeof attrs.finishReason === 'string' ? attrs.finishReason : undefined,\n },\n ];\n }\n\n case SpanType.AGENT_RUN:\n return [{ ...base, stepType: 'agent_run' as const, agentId: span.entityId ?? undefined }];\n\n case SpanType.WORKFLOW_RUN:\n return [{ ...base, stepType: 'workflow_run' as const, workflowId: span.entityId ?? undefined }];\n\n case SpanType.WORKFLOW_STEP: {\n const output = toRecordOrUndefined(span.output);\n return [{ ...base, stepType: 'workflow_step' as const, stepId: span.name, output }];\n }\n\n case SpanType.WORKFLOW_CONDITIONAL:\n return [{ ...base, stepType: 'workflow_conditional' as const }];\n\n case SpanType.WORKFLOW_PARALLEL:\n return [{ ...base, stepType: 'workflow_parallel' as const }];\n\n case SpanType.WORKFLOW_LOOP:\n return [{ ...base, stepType: 'workflow_loop' as const }];\n\n case SpanType.WORKFLOW_SLEEP:\n return [{ ...base, stepType: 'workflow_sleep' as const }];\n\n case SpanType.WORKFLOW_WAIT_EVENT:\n return [{ ...base, stepType: 'workflow_wait_event' as const }];\n\n case SpanType.PROCESSOR_RUN:\n return [{ ...base, stepType: 'processor_run' as const }];\n\n default:\n // Unknown span type — promote children if any\n return childSteps;\n }\n}\n\n/**\n * Safely converts a value to `Record<string, unknown>` or returns undefined.\n */\nfunction toRecordOrUndefined(value: unknown): Record<string, unknown> | undefined {\n if (value == null) return undefined;\n if (typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n return { value };\n}\n\n/**\n * Extracts a hierarchical Trajectory from trace spans (as returned by the\n * observability store's `getTrace()`).\n *\n * Builds a parent-child tree from `parentSpanId` references, then recursively\n * converts each span to the appropriate `TrajectoryStep` discriminated union\n * type with nested `children`.\n *\n * Noise spans (`generic`, `model_step`, `model_chunk`, `workflow_conditional_eval`)\n * are automatically skipped.\n *\n * This is used by `runEvals` when storage is available to produce richer,\n * hierarchical trajectories that include nested agent runs, tool calls, and\n * model generations inside workflow or agent steps.\n *\n * @param spans - Flat array of span records from `getTrace().spans`\n * @param rootSpanId - Optional span ID to use as root. If omitted, spans with\n * no parent are used as roots.\n * @returns A Trajectory with hierarchical TrajectoryStep entries\n *\n * @example\n * ```ts\n * const trace = await observabilityStore.getTrace({ traceId });\n * const trajectory = extractTrajectoryFromTrace(trace.spans, workflowSpanId);\n * ```\n */\nexport function extractTrajectoryFromTrace(spans: SpanRecord[], rootSpanId?: string): Trajectory {\n if (spans.length === 0) {\n return { steps: [] };\n }\n\n // Build lookup map\n const nodeMap = new Map<string, SpanTreeNode>();\n for (const span of spans) {\n nodeMap.set(span.spanId, { span, children: [] });\n }\n\n // Attach children to parents\n const roots: SpanTreeNode[] = [];\n for (const span of spans) {\n const node = nodeMap.get(span.spanId)!;\n if (span.parentSpanId && nodeMap.has(span.parentSpanId)) {\n nodeMap.get(span.parentSpanId)!.children.push(node);\n } else {\n roots.push(node);\n }\n }\n\n // Sort children by start time\n for (const node of nodeMap.values()) {\n node.children.sort((a, b) => a.span.startedAt.getTime() - b.span.startedAt.getTime());\n }\n\n // Find the root to start from\n let targetRoots: SpanTreeNode[];\n if (rootSpanId) {\n const rootNode = nodeMap.get(rootSpanId);\n targetRoots = rootNode ? [rootNode] : roots;\n } else {\n targetRoots = roots;\n }\n\n // If the target is a single root span (e.g., a workflow_run or agent_run),\n // convert its children directly as the trajectory steps (the root itself\n // is the \"container\", not a step in the trajectory)\n let stepsToConvert: SpanTreeNode[];\n if (targetRoots.length === 1) {\n const root = targetRoots[0]!;\n // If root is a container span type, use its children as trajectory steps\n const containerTypes = new Set([SpanType.WORKFLOW_RUN, SpanType.AGENT_RUN]);\n if (containerTypes.has(root.span.spanType)) {\n stepsToConvert = root.children;\n } else {\n stepsToConvert = targetRoots;\n }\n } else {\n stepsToConvert = targetRoots;\n }\n\n const steps = stepsToConvert.flatMap(spanToTrajectorySteps);\n\n // Calculate total duration from the root span(s)\n let totalDurationMs: number | undefined;\n if (targetRoots.length === 1) {\n const root = targetRoots[0]!.span;\n if (root.endedAt && root.startedAt) {\n totalDurationMs = root.endedAt.getTime() - root.startedAt.getTime();\n }\n }\n\n return { steps, totalDurationMs };\n}\n","// src/memory/index.ts\n/**\n* Shared rules for observational memory lifecycle writes. Every storage adapter applies\n* these inside its own atomic section (lock, transaction, or conditional update), so the\n* decisions are identical across adapters.\n*/\n/**\n* Observational memory columns that lifecycle writes depend on. Storage adapters merge these\n* into the table schema they get from `@mastra/core`, so the columns exist even when the\n* installed core predates them.\n*/\nconst OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS = { supersededBy: {\n\ttype: \"text\",\n\tnullable: true\n} };\n/** `schema` plus {@link OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS}; `undefined` when `schema` is. */\nfunction withObservationalMemoryLifecycleColumns(schema) {\n\treturn schema ? {\n\t\t...schema,\n\t\t...OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS\n\t} : void 0;\n}\n/**\n* Canonical head order: `generationCount DESC, createdAt ASC, id ASC`.\n* Returns a negative number when `a` sorts before `b` (i.e. `a` is the better head candidate).\n*/\nfunction compareObservationalMemoryHeadOrder(a, b) {\n\tif (a.generationCount !== b.generationCount) return b.generationCount - a.generationCount;\n\tconst at = new Date(a.createdAt).getTime();\n\tconst bt = new Date(b.createdAt).getTime();\n\tif (at !== bt) return at - bt;\n\treturn a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n/**\n* A buffered chunk stores `lastObservedAt = max message time + 1ms`. It is wholly covered\n* (every message it observed is already at or before the cursor) iff\n* `cursor >= chunk.lastObservedAt - 1ms`.\n*/\nfunction isBufferedChunkCoveredByCursor(chunkLastObservedAt, cursor) {\n\tif (!cursor) return false;\n\treturn new Date(cursor).getTime() >= new Date(chunkLastObservedAt).getTime() - 1;\n}\n/** The later of two cursors; `undefined` only when both are absent. */\nfunction maxObservationCursor(a, b) {\n\tif (!a) return b ? new Date(b) : void 0;\n\tif (!b) return new Date(a);\n\treturn new Date(Math.max(new Date(a).getTime(), new Date(b).getTime()));\n}\n/**\n* Decide the new generation's text when a reflection built from `snapshot` commits against\n* the stored record.\n*\n* - Stored text equals the snapshot: the reflection replaces it.\n* - Stored text extends the snapshot (activation only appends): the appended tail is kept\n* after the reflection, and its tokens are added.\n* - Anything else (a non-append rewrite): `null` — the reflection must not be applied.\n*/\nfunction planReflectionGenerationText(input) {\n\tconst stored = input.storedObservations ?? \"\";\n\tconst snapshot = input.snapshotObservations ?? \"\";\n\tif (stored === snapshot) return {\n\t\tmode: \"equal\",\n\t\tobservations: input.reflection,\n\t\ttokenCount: input.tokenCount\n\t};\n\tif (!stored.startsWith(snapshot)) return null;\n\tconst tail = stored.slice(snapshot.length).trimStart();\n\tif (!tail.trim()) return {\n\t\tmode: \"equal\",\n\t\tobservations: input.reflection,\n\t\ttokenCount: input.tokenCount\n\t};\n\treturn {\n\t\tmode: \"append\",\n\t\tobservations: input.reflection ? `${input.reflection}\\n\\n${tail}` : tail,\n\t\ttokenCount: input.tokenCount + Math.max(0, (input.storedObservationTokenCount ?? 0) - (input.snapshotObservationTokenCount ?? 0))\n\t};\n}\n/**\n* Backs `updateActiveObservations` in adapters that implement `commitActiveObservations`.\n* Callers of `updateActiveObservations` (which resolves `void`) can't see a commit result, so a\n* write that was not applied throws instead of resolving as if it had committed.\n*/\nfunction assertActiveObservationsApplied(result, id) {\n\tif (result.applied) return;\n\tthrow 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`);\n}\n/**\n* Whether the stored text can still accept a reflection built from `snapshot`\n* (equal, or only appended to since).\n*/\nfunction isAppendOnlySince(storedObservations, snapshotObservations) {\n\tconst stored = storedObservations ?? \"\";\n\tconst snapshot = snapshotObservations ?? \"\";\n\treturn stored === snapshot || stored.startsWith(snapshot);\n}\nexport { OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS, assertActiveObservationsApplied, compareObservationalMemoryHeadOrder, isAppendOnlySince, isBufferedChunkCoveredByCursor, maxObservationCursor, planReflectionGenerationText, withObservationalMemoryLifecycleColumns };\n\n//# sourceMappingURL=index.js.map","import { z } from 'zod/v4';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { PREVIEW_MAX_LENGTH, truncatePreview } from '../../../observability/span-previews';\nimport { SpanType } from '../../../observability/types';\nimport type { SpanInput, SpanOutput, SpanTypeMap } from '../../../observability/types';\nimport {\n deltaLimitSchema,\n deltaInfoSchema,\n spanContextFields,\n dateRangeSchema,\n dbTimestamps,\n deltaCursorSchema,\n listModeSchema,\n metadataField,\n normalizeObservabilityListArgs,\n paginationArgsSchema,\n paginationInfoSchema,\n refineObservabilityListMode,\n sortDirectionSchema,\n organizationIdField,\n resourceIdField,\n tagsField,\n traceIdField,\n spanIdField,\n} from '../shared';\n\nexport { traceIdField, spanIdField };\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z\n .record(z.string(), z.unknown())\n .describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Derived status of a trace, computed from the root span's error and endedAt fields. */\nexport enum TraceStatus {\n SUCCESS = 'success',\n ERROR = 'error',\n RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n .preprocess(v => {\n // Handle string \"true\"/\"false\" from query params correctly\n // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n if (v === 'true') return true;\n if (v === 'false') return false;\n return v;\n }, z.boolean())\n .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Built from spanContextFields plus span-specific metadata/tags.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n ...spanContextFields,\n metadata: metadataField.nullish(),\n tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n traceId: traceIdField,\n spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Shared fields\n parentSpanId: parentSpanIdField.nullish(),\n ...sharedFields,\n\n // Experimentation\n experimentId: z.string().nullish().describe('Experiment or eval run identifier'),\n\n // Additional span-specific nullish fields\n attributes: attributesField.nullish(),\n links: linksField.nullish(),\n input: inputField.nullish(),\n output: outputField.nullish(),\n error: errorField.nullish(),\n endedAt: endedAtField.nullish(),\n requestContext: z.record(z.string(), z.unknown()).nullish().describe('Request context data'),\n\n // Short text previews of input / output / error (see `buildPreview`). When a written span\n // carries them (e.g. built upstream by an exporter), stores that keep previews store these,\n // cut to the shared format, instead of building their own.\n inputPreview: z.string().nullish().describe('Short text preview of the span input'),\n outputPreview: z.string().nullish().describe('Short text preview of the span output'),\n errorPreview: z.string().nullish().describe('Short text preview of the span error'),\n\n // Derived from `attributes.completionStartTime` when an exporter builds the record, so stores\n // persist it without computing it themselves.\n timeToFirstChunkMs: z\n .number()\n .nullish()\n .describe('Milliseconds from span start to the first streamed chunk; null when the span never streamed one'),\n\n // Native span fields. Copied from the exported span as supplied; a value the producer did not\n // set is stored as null, never derived on write. On read, `getSpan` / `getTrace` fall back to\n // the `attributes` strings for `model` and `provider` when the column is null, matching trace\n // queries and span-query results, which use the same fallback. Span-query filters read only the\n // columns. `outcome` / `stopReason` values follow the shared outcome contract and are not\n // validated here.\n externalParentSpanId: z\n .string()\n .nullish()\n .describe('Immediate parent span owned by an external tracing system; null when Mastra owns the parent'),\n resumedFromSpanId: z\n .string()\n .nullish()\n .describe('Span id of the initial invocation a resumed execution continues; null on the initial execution'),\n model: z.string().nullish().describe('Model identity for this span, where applicable'),\n provider: z.string().nullish().describe('Provider paired with model'),\n outcome: z.string().nullish().describe('How this execution ended; null while it is still running'),\n stopReason: z.string().nullish().describe('Machine-readable cause of stopping, when known'),\n stopReasonContext: z\n .record(z.string(), z.unknown())\n .nullish()\n .describe('Structured details behind stopReason, such as the limit that was hit; null when unknown'),\n timeToFirstTokenMs: z\n .number()\n .nullish()\n .describe('Milliseconds from the model call to the first token received; null when unknown'),\n errorCount: z.number().int().nullish().describe('Failures originating directly on this span; null when unknown'),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Span record exactly as the schema stores it: payload fields are untyped. */\ntype StoredSpanRecord = z.infer<typeof spanRecordSchema>;\n\n/**\n * Stored span record narrowed to one span type: `attributes`, `input` and\n * `output` carry the shapes core records for that type. A union of span types\n * gives a union of records, so `spanType` keeps discriminating after the\n * guard.\n */\nexport type TypedSpanRecord<TType extends SpanType> = TType extends SpanType\n ? Omit<StoredSpanRecord, 'spanType' | 'attributes' | 'input' | 'output'> & {\n spanType: TType;\n attributes?: (SpanTypeMap[TType] & Record<string, unknown>) | null;\n input?: SpanInput<TType> | null;\n output?: SpanOutput<TType> | null;\n }\n : never;\n\n/**\n * Complete span record as stored in the database.\n *\n * Without a type argument this is the stored record as-is. Narrow `TType` to\n * get a `TypedSpanRecord`. The schema itself stays permissive, so this is a\n * read-side view only; narrow with `isSpanRecordOfType` from\n * `@mastra/core/observability`.\n */\nexport type SpanRecord<TType extends SpanType = SpanType> = SpanType extends TType\n ? StoredSpanRecord\n : TypedSpanRecord<TType>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: { error?: unknown; endedAt?: Date | string | null }): TraceStatus {\n if (span.error != null) return TraceStatus.ERROR;\n if (span.endedAt == null) return TraceStatus.RUNNING;\n return TraceStatus.SUCCESS;\n}\n\n/**\n * A string attribute of a span, or null when unset or not a string.\n * Model-call spans keep `model` and `provider` in `attributes`; the native\n * columns of the same name fall back to it for rows written before the\n * columns existed, since those rows are never backfilled.\n */\nexport function getStringAttribute(attributes: unknown, key: string): string | null {\n const value = (attributes as Record<string, unknown> | null | undefined)?.[key];\n return typeof value === 'string' ? value : null;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n .extend({\n status: traceStatusField,\n })\n .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n return {\n ...span,\n status: computeTraceStatus(span),\n };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n .object({\n span: createSpanRecordSchema,\n })\n .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n .object({\n records: z.array(createSpanRecordSchema),\n })\n .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n })\n .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getSpans (batch) operation arguments.\n *\n * Fetches multiple spans in a trace by spanId in one call. Used to power the\n * progressive-disclosure path in {@link getBranchArgsSchema}: walk the\n * lightweight {@link getStructureResponseSchema} to find which spanIds belong\n * to a branch, then fetch only those with full data instead of pulling the\n * entire trace.\n */\nexport const getSpansArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanIds: z.array(spanIdField.min(1)).min(1).describe('Span IDs to fetch within the trace'),\n })\n .describe('Arguments for batch-fetching spans by spanId within a trace');\n\n/** Arguments for batch-fetching spans by spanId */\nexport type GetSpansArgs = z.infer<typeof getSpansArgsSchema>;\n\n/** Response schema for getSpans operation */\nexport const getSpansResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing the requested spans (order is not guaranteed) */\nexport type GetSpansResponse = z.infer<typeof getSpansResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\n/** Alias for GetTraceResponse -- a trace with all its spans. */\nexport type TraceRecord = GetTraceResponse;\n\n/**\n * Schema for getBranch operation arguments.\n *\n * Returns the subtree rooted at `spanId`. When `depth` is omitted the full\n * descendant subtree is returned; with a finite `depth` only that many levels\n * below the anchor are returned (depth: 0 → only the anchor span; depth: 1 →\n * anchor plus immediate children; etc).\n */\nexport const getBranchArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n depth: z.coerce\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Maximum descendant levels below the anchor span (omit for full subtree)'),\n })\n .describe('Arguments for getting a span branch (subtree rooted at a span)');\n\n/** Arguments for retrieving the subtree rooted at a span */\nexport type GetBranchArgs = z.input<typeof getBranchArgsSchema>;\n\n/**\n * Response schema for getBranch operation. Mirrors getTrace -- a flat list of\n * spans, traversal-agnostic. The anchor span is included as the first matching\n * span; callers reconstruct the tree via parentSpanId.\n */\nexport const getBranchResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing the subtree rooted at a span */\nexport type GetBranchResponse = z.infer<typeof getBranchResponseSchema>;\n\n/**\n * Extracts the subtree rooted at `anchorSpanId` from a flat list of trace\n * spans. The anchor itself is included as the first element; descendants are\n * walked via `parentSpanId` and returned sorted by `startedAt` ascending after\n * the anchor. When `maxDepth` is provided, only that many levels of\n * descendants are returned (anchor counts as depth 0).\n *\n * Cycles in `parentSpanId` (which shouldn't happen in well-formed traces but\n * could surface from corrupted data) are handled by tracking visited spanIds\n * and skipping any span seen during this walk.\n *\n * Returns an empty array if the anchor isn't in the input.\n *\n * Generic over the span shape so it works on both full {@link SpanRecord}\n * lists (e.g. result of `getTrace`) and lightweight skeletons (result of\n * `getStructure`).\n */\nexport function extractBranchSpans<\n T extends { spanId: string; parentSpanId?: string | null | undefined; startedAt: Date },\n>(spans: T[], anchorSpanId: string, maxDepth?: number): T[] {\n const anchor = spans.find(s => s.spanId === anchorSpanId);\n if (!anchor) return [];\n\n // Build parentSpanId → children index for O(1) descent.\n const childrenByParent = new Map<string, T[]>();\n for (const span of spans) {\n if (span.parentSpanId == null) continue;\n const bucket = childrenByParent.get(span.parentSpanId);\n if (bucket) {\n bucket.push(span);\n } else {\n childrenByParent.set(span.parentSpanId, [span]);\n }\n }\n\n const visited = new Set<string>([anchor.spanId]);\n const descendants: T[] = [];\n // BFS so depth bounding is straightforward; visited set prevents\n // infinite loops on malformed (cyclic) parent chains.\n let frontier: T[] = [anchor];\n let depth = 0;\n while (frontier.length > 0) {\n if (maxDepth != null && depth >= maxDepth) break;\n const next: T[] = [];\n for (const span of frontier) {\n const children = childrenByParent.get(span.spanId);\n if (!children) continue;\n for (const child of children) {\n if (visited.has(child.spanId)) continue;\n visited.add(child.spanId);\n descendants.push(child);\n next.push(child);\n }\n }\n frontier = next;\n depth++;\n }\n\n // Sort descendants by startedAt; keep the anchor at index 0 regardless of\n // whether some descendant happens to have an earlier startedAt (clock skew,\n // out-of-order isEvent spans, etc).\n descendants.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n return [anchor, ...descendants];\n}\n\n// ============================================================================\n// Lightweight Span & Trace Schemas (for timeline rendering)\n// ============================================================================\n\nexport { PREVIEW_MAX_LENGTH } from '../../../observability/span-previews';\n\n/** @deprecated Use {@link PREVIEW_MAX_LENGTH}. */\nexport const INPUT_PREVIEW_MAX_LENGTH = PREVIEW_MAX_LENGTH;\n\nconst inputPreviewField = z.string().describe('Short text preview of the span input');\nconst outputPreviewField = z.string().describe('Short text preview of the span output');\nconst errorPreviewField = z.string().describe('Short text preview of the span error');\n\ntype PreviewMessage = { role?: unknown; content?: unknown };\n\nfunction isMessage(value: unknown): value is PreviewMessage {\n return value != null && typeof value === 'object' && typeof (value as PreviewMessage).role === 'string';\n}\n\n/** A message list is a bare array or a `messages` array whose elements carry a string `role`. */\nfunction extractMessages(value: unknown): PreviewMessage[] | null {\n const list =\n value && typeof value === 'object' && !Array.isArray(value) && 'messages' in value\n ? (value as { messages: unknown }).messages\n : value;\n return Array.isArray(list) && list.some(isMessage) ? list : null;\n}\n\nfunction textFromContent(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .map(part => {\n if (typeof part === 'string') return part;\n if (part && typeof part === 'object' && (part as { type?: unknown }).type === 'text') {\n const text = (part as { text?: unknown }).text;\n return typeof text === 'string' ? text : '';\n }\n return '';\n })\n .filter(Boolean)\n .join(' ');\n}\n\n/**\n * Preview of an agent signal recorded as a run's input (`agent.sendSignal()`): a user signal previews\n * as its text, any other signal as its text labelled by what it is (`Skill <name>: …`, `<tag>: …`).\n */\nfunction signalText(value: object): string | null {\n const signal = value as Record<string, unknown>;\n if (signal.__isCreatedSignal !== true || !('contents' in signal)) return null;\n const text = textFromContent(signal.contents).trim();\n const type = signal.type;\n if (type === 'user' || type === 'user-message') return text || null;\n\n const attributes = signal.attributes as Record<string, unknown> | undefined;\n const tagName = typeof signal.tagName === 'string' ? signal.tagName : undefined;\n const label =\n tagName === 'skill' && typeof attributes?.name === 'string'\n ? `Skill ${attributes.name}`\n : (tagName ?? (typeof type === 'string' ? type : 'signal'));\n return text ? `${label}: ${text}` : label;\n}\n\nfunction lastMessageText(messages: PreviewMessage[], accept: (role: string) => boolean): string | null {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (!isMessage(message) || !accept(message.role as string)) continue;\n const text = textFromContent(message.content).trim();\n if (text) return text;\n }\n return null;\n}\n\nfunction textField(value: object): string | null {\n for (const key of ['text', 'message'] as const) {\n const field = (value as Record<string, unknown>)[key];\n if (typeof field === 'string' && field.trim()) return field;\n }\n return null;\n}\n\n/**\n * Short text preview of a decoded span payload (`input`, `output` or `error`), at most\n * {@link PREVIEW_MAX_LENGTH} characters plus `…` when cut. Returns `null` when there is nothing\n * to preview.\n *\n * - A string previews as itself.\n * - A message list (a bare array, or a `messages` array, of objects with a string `role`)\n * previews as the last user message's text, else the last non-system message's text.\n * - An agent signal (a run started by `agent.sendSignal()`) previews as its contents; a non-user\n * signal is labelled by its tag, or `Skill <name>` for a skill.\n * - An object with a non-blank `text` or `message` string previews as that string.\n * - Anything else previews as its compact JSON.\n *\n * `serialized` is the value's JSON text when the caller already has it, so the compact-JSON\n * case does not serialize it twice. Writers call this on the value they store; readers of a\n * stored JSON column call {@link buildPreviewFromJson}, so both produce the same preview.\n */\nexport function buildPreview(value: unknown, serialized?: string | null): string | null {\n return previewOf(value, serialized, PREVIEW_MAX_LENGTH);\n}\n\nfunction previewOf(value: unknown, serialized: string | null | undefined, maxLength: number): string | null {\n if (value == null) return null;\n if (typeof value === 'string') return truncatePreview(value, maxLength);\n\n const messages = extractMessages(value);\n if (messages) {\n const text =\n lastMessageText(messages, role => role === 'user') ?? lastMessageText(messages, role => role !== 'system');\n return text == null ? null : truncatePreview(text, maxLength);\n }\n\n if (typeof value === 'object' && !Array.isArray(value)) {\n const text = signalText(value) ?? textField(value);\n if (text != null) return truncatePreview(text, maxLength);\n }\n\n return truncatePreview(serialized ?? JSON.stringify(value) ?? '', maxLength);\n}\n\n/**\n * Preview of a stored JSON payload column. Stores always write valid JSON, so text that does not\n * parse previews as blank rather than as a guess at a sliced document.\n */\nexport function buildPreviewFromJson(json: string | null | undefined): string | null {\n return previewOfJson(json, PREVIEW_MAX_LENGTH);\n}\n\nfunction previewOfJson(json: string | null | undefined, maxLength: number): string | null {\n if (json == null || !json.trim()) return null;\n let value: unknown;\n try {\n value = JSON.parse(json);\n } catch {\n return null;\n }\n return previewOf(value, json, maxLength);\n}\n\n/**\n * The preview a store writes for one payload: an upstream preview when the span record carries\n * a string (including an intentionally empty one), otherwise one built from the payload. Both are capped the same way, at\n * {@link PREVIEW_MAX_LENGTH} characters plus `…`, so an exporter can't store an unbounded preview.\n * `''` means there is nothing to preview.\n */\nexport function buildStoredPreview(\n upstream: string | null | undefined,\n value: unknown,\n serialized?: string | null,\n): string {\n if (upstream != null) return truncatePreview(upstream) ?? '';\n return buildPreview(value, serialized) ?? '';\n}\n\n/**\n * Whether a preview built by {@link buildPreview} was cut. A cut preview is the first\n * {@link PREVIEW_MAX_LENGTH} characters plus `…`, or one character fewer plus `…` when the cut\n * would split a surrogate pair; an uncut one is at most {@link PREVIEW_MAX_LENGTH} characters.\n * An uncut text of exactly {@link PREVIEW_MAX_LENGTH} characters that itself ends in `…` reads as\n * cut, which is the one case the preview alone cannot tell apart.\n */\nexport function isPreviewTruncated(preview: string | null | undefined): boolean {\n if (!preview) return false;\n return preview.endsWith('…') && (preview.length === PREVIEW_MAX_LENGTH || preview.length === PREVIEW_MAX_LENGTH + 1);\n}\n\n/**\n * @deprecated Use {@link buildPreview} (decoded values) or {@link buildPreviewFromJson} (stored\n * JSON text). Kept for callers of the old trace-list preview; it now uses the shared preview\n * format, so a message list previews as its last user message rather than every user message\n * joined with ` | `.\n *\n * Accepts a decoded value or a JSON string. A string that looks like a JSON document or a\n * JSON-encoded scalar is parsed first; an unparseable JSON document previews as empty.\n * `maxLength` caps the preview at that many characters plus `…`, as before.\n */\nexport function buildInputPreview(input: unknown, maxLength = PREVIEW_MAX_LENGTH): string | undefined {\n if (input == null) return undefined;\n if (typeof input === 'string') {\n const trimmed = input.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) return previewOfJson(trimmed, maxLength) ?? undefined;\n if (trimmed.startsWith('\"')) {\n try {\n return previewOf(JSON.parse(trimmed), undefined, maxLength) ?? undefined;\n } catch {\n // Not valid JSON — treat as plain text below.\n }\n }\n }\n return previewOf(input, undefined, maxLength) ?? undefined;\n}\n\n/** Stored preview when the record carries one (`''` means none), else one built from the value. */\nfunction lightPreview(stored: string | null | undefined, value: unknown): string | null {\n return stored == null ? buildPreview(value) : stored.trim() || null;\n}\n\n/**\n * Projects a full span record down to the lightweight row a trace list renders,\n * with `inputPreview` / `outputPreview` / `errorPreview`: the stored previews when the record\n * carries them, otherwise built from `input` / `output` / `error` with {@link buildPreview}.\n *\n * This is the read-time fallback. Backends that can project inside the query should\n * do so instead — that is what keeps the blob columns off the read path — but every\n * backend can serve a correct lightweight list through this.\n */\nexport function toLightSpanRecord(span: SpanRecord): LightSpanRecord {\n return {\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n spanType: span.spanType,\n isEvent: span.isEvent,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n error: span.error,\n status: computeTraceStatus(span),\n entityType: span.entityType,\n entityId: span.entityId,\n entityName: span.entityName,\n threadId: span.threadId,\n resourceId: span.resourceId,\n metadata: span.metadata,\n inputPreview: lightPreview(span.inputPreview, span.input),\n outputPreview: lightPreview(span.outputPreview, span.output),\n errorPreview: lightPreview(span.errorPreview, span.error),\n createdAt: span.createdAt,\n updatedAt: span.updatedAt,\n };\n}\n\n/**\n * Lightweight span record containing only the fields trace lists and timelines render.\n * Excludes heavy fields: input, output, attributes, tags, links.\n * This keeps the per-span payload a small fraction of a full span record's.\n */\nexport const lightSpanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Nullish fields needed for timeline/status\n parentSpanId: parentSpanIdField.nullish(),\n endedAt: endedAtField.nullish(),\n error: errorField.nullish(),\n\n // Computed status, so trace lists can render their status column.\n // Nullable AND optional: rows from stores/APIs that predate the field\n // may omit it entirely, and they must still validate.\n status: traceStatusField.nullable().optional(),\n\n // Entity context (needed by TraceSummaryDescription on root span)\n entityType: spanContextFields.entityType,\n entityId: spanContextFields.entityId,\n entityName: spanContextFields.entityName,\n\n // Memory context, so trace lists can render their Thread ID / Resource ID columns.\n // Nullable and optional for rows that predate the fields.\n threadId: spanContextFields.threadId.nullable(),\n resourceId: spanContextFields.resourceId.nullable(),\n\n // Span metadata, so user-configured metadata columns can render on the light list.\n // Nullable and optional for rows that predate the field.\n metadata: metadataField.nullable().optional(),\n\n // Short text previews of `input` / `output` / `error`, so trace lists can render their\n // preview columns without transferring the whole payload. See `buildPreview`. Nullable\n // and optional for rows that predate the fields.\n inputPreview: inputPreviewField.nullable().optional(),\n outputPreview: outputPreviewField.nullable().optional(),\n errorPreview: errorPreviewField.nullable().optional(),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Lightweight span record for trace lists and timelines (excludes input, output, attributes, tags, links)');\n\n/** Lightweight span record for timeline rendering */\nexport type LightSpanRecord = z.infer<typeof lightSpanRecordSchema>;\n\n/**\n * Response schema for getStructure operation.\n * Returns a trace with lightweight spans (only fields needed for timeline).\n */\nexport const getStructureResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(lightSpanRecordSchema),\n});\n\n/** Response containing a trace with lightweight spans for timeline rendering */\nexport type GetStructureResponse = z.infer<typeof getStructureResponseSchema>;\n\n/** @deprecated Use {@link getStructureResponseSchema} instead. */\nexport const getTraceLightResponseSchema = getStructureResponseSchema;\n/** @deprecated Use {@link GetStructureResponse} instead. */\nexport type GetTraceLightResponse = GetStructureResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n .object({\n // Date range filters\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Span type filter\n spanType: spanTypeField.optional(),\n\n // Identifier filter (matches the root span's trace identifier)\n traceId: traceIdField.optional().describe('Filter by trace ID (matches root span)'),\n\n // Shared fields\n ...sharedFields,\n\n // Filter-specific derived status fields\n status: traceStatusField.optional(),\n hasChildError: hasChildErrorField.optional(),\n })\n .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n .object({\n field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n .object({\n mode: listModeSchema.optional(),\n filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.optional(),\n orderBy: tracesOrderBySchema.optional(),\n after: deltaCursorSchema.optional(),\n limit: deltaLimitSchema,\n })\n .strict()\n .superRefine(refineObservabilityListMode)\n .transform(value =>\n normalizeObservabilityListArgs<z.output<typeof tracesFilterSchema>, z.output<typeof tracesOrderBySchema>>(value, {\n orderBy: { field: 'startedAt', direction: 'DESC' } as const,\n }),\n )\n .describe('Arguments for listing traces.');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n pagination: paginationInfoSchema.optional(),\n delta: deltaInfoSchema.optional(),\n deltaCursor: deltaCursorSchema.optional(),\n spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status. Trace delta mode returns only new trace rows. */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/** Schema for listTracesLight operation response */\nexport const listTracesLightResponseSchema = z.object({\n pagination: paginationInfoSchema.optional(),\n delta: deltaInfoSchema.optional(),\n deltaCursor: deltaCursorSchema.optional(),\n spans: z.array(lightSpanRecordSchema),\n});\n\n/** Response containing paginated lightweight root spans. Delta mode returns only new trace rows. */\nexport type ListTracesLightResponse = z.infer<typeof listTracesLightResponseSchema>;\n\n// ============================================================================\n// Trace branches (anchor spans surfaced as listable rows, including non-root)\n// ============================================================================\n\n/**\n * Span types that anchor a listable trace branch -- the spans a user thinks\n * about when looking for a specific run (agent/workflow/tool/etc.),\n * regardless of whether the entity ran as the root of its trace or nested\n * under a parent. Each row in {@link listBranchesArgsSchema} corresponds to\n * one such anchor span; the subtree below it is fetched via\n * {@link getBranchArgsSchema}.\n *\n * Excludes sub-operation spans (model_step, workflow_step, scorer_step,\n * memory_operation, rag_*, etc.) which are internal to a containing branch\n * rather than separately listable.\n */\nexport const BRANCH_SPAN_TYPES = [\n SpanType.AGENT_RUN,\n SpanType.WORKFLOW_RUN,\n SpanType.PROCESSOR_RUN,\n SpanType.SCORER_RUN,\n SpanType.RAG_INGESTION,\n SpanType.TOOL_CALL,\n SpanType.MCP_TOOL_CALL,\n SpanType.MCP_SERVER_REQUEST,\n SpanType.PROVIDER_TOOL_CALL,\n] as const satisfies readonly SpanType[];\n\n/** Set form of {@link BRANCH_SPAN_TYPES} for fast membership checks. */\nexport const BRANCH_SPAN_TYPE_SET: ReadonlySet<SpanType> = new Set(BRANCH_SPAN_TYPES);\n\n/** Schema for filtering branch anchor spans in list queries. */\nexport const branchesFilterSchema = z\n .object({\n // Date range filters apply to the branch anchor span itself\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Narrow within the branch span-type set; if omitted, all of them match\n spanType: spanTypeField.optional(),\n\n // Identifier filters\n traceId: traceIdField.optional().describe('Filter by parent trace ID'),\n\n // Per-span context fields (apply to the anchor span, not the trace root)\n ...sharedFields,\n\n // Derived status filter (computed from this anchor's own error/endedAt)\n status: traceStatusField.optional(),\n })\n .describe('Filters for querying trace branches');\n\nexport const branchesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\nexport const branchesOrderBySchema = z\n .object({\n field: branchesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing trace branches.\n *\n * Each row is a single branch anchor span ({@link BRANCH_SPAN_TYPES}),\n * including ones nested under a different root entity. Use this when you\n * want every run of a given agent/processor/tool regardless of how it was\n * triggered. Use {@link listTracesArgsSchema} when you want one row per\n * trace, and {@link getBranchArgsSchema} to expand a single branch into its\n * subtree.\n */\nexport const listBranchesArgsSchema = z\n .object({\n mode: listModeSchema.optional(),\n filters: branchesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.optional(),\n orderBy: branchesOrderBySchema.optional(),\n after: deltaCursorSchema.optional(),\n limit: deltaLimitSchema,\n })\n .strict()\n .superRefine(refineObservabilityListMode)\n .transform(value =>\n normalizeObservabilityListArgs<z.output<typeof branchesFilterSchema>, z.output<typeof branchesOrderBySchema>>(\n value,\n {\n orderBy: { field: 'startedAt', direction: 'DESC' } as const,\n },\n ),\n )\n .describe('Arguments for listing trace branches.');\n\n/** Arguments for listing branches with optional filters, pagination, and ordering */\nexport type ListBranchesArgs = z.input<typeof listBranchesArgsSchema>;\n\n/**\n * Schema for listBranches operation response. Each row is a single branch\n * anchor span -- repeated runs of the same entity within one parent trace\n * surface as separate rows.\n */\nexport const listBranchesResponseSchema = z.object({\n pagination: paginationInfoSchema.optional(),\n delta: deltaInfoSchema.optional(),\n deltaCursor: deltaCursorSchema.optional(),\n branches: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated branch anchor spans with computed status. Branch delta mode returns only new branch rows. */\nexport type ListBranchesResponse = z.infer<typeof listBranchesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n .object({\n spanId: spanIdField,\n traceId: traceIdField,\n updates: updateSpanRecordSchema.partial(),\n })\n .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n .object({\n records: z.array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField,\n updates: updateSpanRecordSchema.partial(),\n }),\n ),\n })\n .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/** Result of a conditional batch span update: the spans whose rows were changed. */\nexport interface BatchUpdateUnendedSpansResponse {\n updated: Array<{ traceId: string; spanId: string }>;\n}\n\n/** Maximum number of trace IDs accepted by a single batch delete request. */\nexport const BATCH_DELETE_TRACES_MAX_IDS = 1000;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z\n .array(traceIdField)\n .max(BATCH_DELETE_TRACES_MAX_IDS)\n .describe(`Trace IDs to delete (maximum ${BATCH_DELETE_TRACES_MAX_IDS})`),\n organizationId: organizationIdField\n .optional()\n .describe('Optional tenant scope: only delete rows belonging to this organization'),\n resourceId: resourceIdField\n .optional()\n .describe('Optional tenant scope: only delete rows belonging to this resource'),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n/** Schema for batchDeleteTraces route response */\nexport const batchDeleteTracesResponseSchema = z\n .object({\n success: z.literal(true),\n })\n .describe('Response for batch deleting traces');\n\n/** Response for batch deleting traces */\nexport type BatchDeleteTracesResponse = z.infer<typeof batchDeleteTracesResponseSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n scorerName: z.string().min(1),\n targets: z\n .array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField.optional(),\n }),\n )\n .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n status: z.string(),\n message: z.string(),\n traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod/v4';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig, ScoringSource } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport type { ProcessorPhase } from '../processor-provider';\nimport { getZodInnerType, getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n page: number;\n perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n type: StorageColumnType;\n primaryKey?: boolean;\n nullable?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\n\nexport interface StorageTableConfig {\n columns: Record<string, StorageColumn>;\n compositePrimaryKey?: string[];\n}\nexport interface WorkflowRuns {\n runs: WorkflowRun[];\n total: number;\n}\n\nexport interface StorageWorkflowRun {\n workflow_name: string;\n run_id: string;\n resourceId?: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}\nexport interface WorkflowRun {\n workflowName: string;\n runId: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n resourceId?: string;\n /**\n * Set to 2 for runs stored as a header plus entries. Absent for v1 runs.\n * @experimental\n */\n storageVersion?: 2;\n}\n\nexport type PaginationInfo = {\n total: number;\n page: number;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When `false`, all matching records are returned in a single response.\n */\n perPage: number | false;\n hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\nexport type StorageMetadataFilterValue = string | number | boolean | null;\n\nexport type StorageMetadataFilter = Record<string, StorageMetadataFilterValue>;\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n include?: {\n id: string;\n threadId?: string;\n withPreviousMessages?: number;\n withNextMessages?: number;\n }[];\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 40 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n filter?: {\n dateRange?: {\n start?: Date;\n end?: Date;\n /**\n * When true, excludes the start date from results (uses > instead of >=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n startExclusive?: boolean;\n /**\n * When true, excludes the end date from results (uses < instead of <=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n endExclusive?: boolean;\n };\n /**\n * Filter messages by shallow scalar metadata key-value pairs from message content metadata.\n * All specified key-value pairs must match with exact type equality (AND logic).\n * Keys must start with a letter or underscore, contain only letters, numbers, and underscores,\n * be at most 128 characters, and cannot be `__proto__`, `prototype`, or `constructor`.\n */\n metadata?: StorageMetadataFilter;\n };\n orderBy?: StorageOrderBy<'createdAt'>;\n /**\n * Whether to compute the total count of matching messages.\n *\n * Defaults to `true` to preserve Studio pagination, which relies on `total`.\n * Callers that only need a bounded window of recent messages (e.g. agent\n * last-N reads) can pass `false` so the store skips the `COUNT(*)` work and\n * derives `hasMore` from a single extra row. When `false`, `total` is not a\n * reliable count and should not be used for pagination math.\n */\n includeTotal?: boolean;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n /**\n * Thread ID(s) to query messages from.\n */\n threadId: string | string[];\n /**\n * Optional resource ID to further filter messages within the thread(s).\n */\n resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n /**\n * Resource ID to query ALL messages for the resource across all threads.\n */\n resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When undefined, returns all workflow runs without pagination.\n * When both perPage and page are provided, pagination is applied.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * When both perPage and page are provided, pagination is applied.\n * When either is undefined, all results are returned.\n */\n page?: number;\n resourceId?: string;\n /**\n * Best-effort narrowing filter on the thread id embedded in the snapshot JSON.\n *\n * Unlike `resourceId`, the thread id is not a column — it lives inside the\n * snapshot at one of two locations (see `getSnapshotMemoryInfo` in\n * `domains/workflows/snapshot-memory-info.ts` for the canonical extraction):\n * 1. agentic-loop: `context.<suspended step>.suspendPayload.__streamState.messageList.memoryInfo.threadId`\n * 2. durable loop: `context.input.messageListState.memoryInfo.threadId`\n *\n * Adapters MAY ignore this field entirely (returning a superset), but MUST\n * NOT exclude rows the canonical extraction would match. Callers must\n * re-verify the thread id on returned rows; most adapters currently ignore\n * the field and only jsonb/json-capable stores (e.g. pg, libsql) push it down.\n */\n threadId?: string;\n status?: WorkflowRunStatus;\n /**\n * When true, callers only need run metadata. Adapters MAY reduce each run's\n * snapshot to `{ status, timestamp, parentWorkflow?: { workflowId, runId } }`\n * to avoid loading the full snapshot. A reduced snapshot has no `context` or\n * any other snapshot field, and leaves out `status` or `timestamp` when the\n * run has none. `parentWorkflow` is present only when the run's parent has\n * both IDs, and is never `null`. Every other run field is unchanged.\n * Adapters that ignore this return full snapshots; every adapter that\n * supports run fencing reduces them.\n */\n summary?: boolean;\n};\n\nexport type StorageListThreadsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter options for querying threads.\n */\n filter?: {\n /**\n * Filter threads by resource ID.\n */\n resourceId?: string;\n /**\n * Filter threads by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n /** ID of the thread this was cloned from */\n sourceThreadId: string;\n /** Timestamp when the clone was created */\n clonedAt: Date;\n /** ID of the last message included in the clone (if messages were copied) */\n lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n /** ID of the thread to clone */\n sourceThreadId: string;\n /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n newThreadId?: string;\n /** Resource ID for the new thread (defaults to source thread's resourceId) */\n resourceId?: string;\n /** Title for the new cloned thread */\n title?: string;\n /** Additional metadata to merge with clone metadata */\n metadata?: Record<string, unknown>;\n /** Options for filtering which messages to include */\n options?: {\n /** Maximum number of messages to copy (from most recent) */\n messageLimit?: number;\n /** Filter messages by date range or specific IDs */\n messageFilter?: {\n /** Only include messages created on or after this date */\n startDate?: Date;\n /** Only include messages created on or before this date */\n endDate?: Date;\n /** Only include messages with these specific IDs */\n messageIds?: string[];\n };\n };\n};\n\n/**\n * Output from copying a thread. Message payloads are copied inside the store and\n * never returned; only the id mapping is produced.\n */\nexport type StorageCopyThreadOutput = {\n /** The newly created thread */\n thread: StorageThreadType;\n /** Map from source message IDs to copied message IDs (used for OM remapping) */\n messageIdMap?: Record<string, string>;\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = StorageCopyThreadOutput & {\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n id: string;\n thread_id: string;\n content: string;\n role: string;\n type: string;\n createdAt: Date;\n resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n orderBy?: ThreadOrderBy;\n sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Per-tool configuration stored in agent snapshots.\n * Allows overriding the tool description for this specific agent.\n */\nexport interface StorageToolConfig {\n /** Custom description override for this tool in this agent context */\n description?: string;\n /** Conditional rules for when this tool should be available */\n rules?: RuleGroup;\n}\n\n/**\n * Per-MCP-client tool configuration stored in agent snapshots.\n * Specifies which tools from an MCP client are enabled and their overrides.\n * An empty `tools` map (`{}`) includes all tools from the MCP client/server.\n * When `tools` is omitted, no tools are included.\n */\nexport interface StorageMCPClientToolsConfig {\n /** `{}` includes all tools from the source; when omitted, no tools are included. */\n tools?: Record<string, StorageToolConfig>;\n}\n\n/**\n * One pinned connection on a tool provider config (per-agent snapshot).\n * Adapter-native `connectionId` is the join key into the\n * `mastra_tool_provider_connections` storage table.\n */\nexport interface StorageToolProviderConfigConnection {\n kind: 'author' | 'invoker' | 'platform';\n connectionId: string;\n toolkit: string;\n label?: string;\n scope?: StorageToolProviderConnectionScope;\n}\n\n/**\n * Per-tool metadata (toolkit + optional description override) for a tool\n * provider's selected tools.\n */\nexport interface StorageToolProviderToolMeta {\n toolkit?: string;\n description?: string;\n}\n\n/**\n * Stored shape for one tool provider's configuration on one agent.\n * Keyed by tool slug for `tools` and by toolkit slug for `connections`.\n */\nexport interface StorageToolProviderConfig {\n tools: Record<string, StorageToolProviderToolMeta>;\n connections: Record<string, StorageToolProviderConfigConnection[]>;\n}\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n /** Custom description override for this scorer in this agent context */\n description?: string;\n /** Sampling configuration for this scorer */\n sampling?: ScoringSamplingConfig;\n /** Conditional rules for when this scorer should be active */\n rules?: RuleGroup;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider: string;\n /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n name: string;\n /** Temperature for generation */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Frequency penalty */\n frequencyPenalty?: number;\n /** Presence penalty */\n presencePenalty?: number;\n /** Maximum completion tokens */\n maxCompletionTokens?: number;\n /** Additional provider-specific options */\n [key: string]: unknown;\n}\n\n/** Serializable model fallback entry stored in agent snapshots. */\nexport interface StorageModelListEntry {\n id: string;\n provider: string;\n modelId: string;\n enabled: boolean;\n maxRetries: number;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n AgentExecutionOptionsBase<any>,\n // Callback functions\n | 'onStepFinish'\n | 'onFinish'\n | 'onChunk'\n | 'onError'\n | 'onAbort'\n | 'prepareStep'\n // Runtime objects\n | 'abortSignal'\n | 'requestContext'\n | 'tracingContext'\n // Functions and processor instances\n | 'inputProcessors'\n | 'outputProcessors'\n | 'clientTools'\n | 'scorers'\n | 'toolsets'\n // Complex types\n | 'context' // ModelMessage includes complex content types (images, files)\n | 'memory' // AgentMemoryOption might contain runtime memory instances\n | 'instructions' // SystemMessage can be arrays or complex message objects\n | 'system' // SystemMessage can be arrays or complex message objects\n | 'stopWhen' // StopCondition is a complex union type from AI SDK\n | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n | 'requireToolApproval' // can be a function at runtime; stored options must be serializable\n> & {\n /**\n * Stored agents only support a boolean here. Function-based approval policies are runtime-only\n * and cannot be serialized, so they are intentionally excluded from stored default options.\n */\n requireToolApproval?: boolean;\n};\n\n/**\n * A conditional variant: a value paired with an optional RuleGroup.\n * When rules are present, the value is only used if rules evaluate to true against the request context.\n * When rules are absent, the variant acts as the default/fallback.\n */\nexport interface StorageConditionalVariant<T> {\n value: T;\n rules?: RuleGroup;\n}\n\n/**\n * A field that can be either a static value or an array of conditional variants.\n * When an array of variants, all matching variants accumulate:\n * arrays are concatenated and objects are shallow-merged.\n * A variant with no rules always matches (acts as the default/base).\n */\nexport type StorageConditionalField<T> = T | StorageConditionalVariant<T>[];\n\n/**\n * Serializable subset of `AgentDurableOption` that can be persisted on a stored\n * agent version snapshot. `cache` and `pubsub` are live runtime objects and are\n * intentionally excluded — they are inherited from the Mastra instance at\n * hydration time. This controls resumable streams, not durable execution.\n */\nexport type StorageDurableConfig =\n | boolean\n | {\n /** Auto-cleanup timer for durable stream state (ms). `0` disables cleanup. */\n cleanupTimeoutMs?: number;\n };\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n /** Display name of the agent */\n name: string;\n /** Purpose description */\n description?: string;\n /** System instructions/prompt — plain string for backward compatibility, or array of instruction blocks */\n instructions: string | AgentInstructionBlock[];\n /** Model configuration (provider, name, etc.) — static or conditional on request context */\n model: StorageConditionalField<StorageModelConfig>;\n /** Ordered model fallback list owned by Studio for opted-in code agents. */\n modelList?: StorageModelListEntry[];\n /** Tool keys with optional per-tool config — static or conditional on request context */\n tools?: StorageConditionalField<Record<string, StorageToolConfig>>;\n /** Default options for generate/stream calls — static or conditional on request context */\n defaultOptions?: StorageConditionalField<StorageDefaultOptions>;\n /** Workflow keys with optional per-workflow config — static or conditional on request context */\n workflows?: StorageConditionalField<Record<string, StorageToolConfig>>;\n /** Agent keys with optional per-agent config — static or conditional on request context */\n agents?: StorageConditionalField<Record<string, StorageToolConfig>>;\n /**\n * Map of tool provider IDs to their tool configurations.\n * Keys are provider IDs (e.g., \"composio\"), values configure which tools from that provider to include.\n * Static or conditional on request context.\n */\n integrationTools?: StorageConditionalField<Record<string, StorageMCPClientToolsConfig>>;\n /**\n * Tool provider configs keyed by provider id (e.g. `'composio'`).\n * Each config selects tool slugs and pins per-toolkit connections.\n * Static or conditional on request context.\n */\n toolProviders?: StorageConditionalField<Record<string, StorageToolProviderConfig>>;\n /** Processor graph for input processing — static or conditional on request context */\n inputProcessors?: StorageConditionalField<StoredProcessorGraph>;\n /** Processor graph for output processing — static or conditional on request context */\n outputProcessors?: StorageConditionalField<StoredProcessorGraph>;\n /** Memory reference (registered memory id) or inline config — static or conditional on request context */\n memory?: StorageConditionalField<StorageMemoryRef>;\n /** Scorer keys with optional sampling config — static or conditional on request context */\n scorers?: StorageConditionalField<Record<string, StorageScorerConfig>>;\n /** Map of stored MCP client IDs to their tool configurations — static or conditional on request context */\n mcpClients?: StorageConditionalField<Record<string, StorageMCPClientToolsConfig>>;\n /** Workspace reference — ID of a stored workspace or inline config — static or conditional on request context */\n workspace?: StorageConditionalField<StorageWorkspaceRef>;\n /** Browser reference — inline browser config — static or conditional on request context */\n browser?: StorageConditionalField<StorageBrowserRef>;\n /** Skill entity IDs with optional per-skill overrides — static or conditional on request context */\n skills?: StorageConditionalField<Record<string, StorageSkillConfig>>;\n /** Skill format for system message injection (default: 'xml') */\n skillsFormat?: 'xml' | 'json' | 'markdown';\n /**\n * Opt the hydrated agent into durable execution. Serializable subset of\n * `AgentDurableOption` — `cache`/`pubsub` are live objects and stay code-level.\n * Not conditional: durability is decided at registration time, not per request.\n */\n durable?: StorageDurableConfig;\n /** JSON Schema for validating request context values. Stored as JSON Schema since Zod is not serializable. */\n requestContextSchema?: Record<string, unknown>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\n/**\n * Visibility of a stored agent.\n * - `private`: only the owner (or admins) can read the record.\n * - `public`: any authenticated caller with `agents:read` can read the record.\n */\nexport type StorageVisibility = 'private' | 'public';\n\nexport const STORAGE_VISIBILITY_VALUES = ['private', 'public'] as const satisfies readonly StorageVisibility[];\n\nexport interface StorageAgentType {\n /** Unique, immutable identifier */\n id: string;\n /** Agent status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /**\n * Visibility of the stored agent. `private` limits access to the owner / admins;\n * `public` allows any authenticated caller with `agents:read` to read.\n * May be undefined for legacy records created before visibility was introduced.\n */\n visibility?: StorageVisibility;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /**\n * Denormalized count of favorites on this agent. Maintained by the favorites\n * storage domain. Optional; treat undefined as 0 for legacy rows.\n */\n favoriteCount?: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType &\n StorageAgentSnapshotType & {\n /** The version ID that was resolved (populated by resolveEntity) */\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n /** Unique identifier for the agent */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Visibility of the stored agent (defaults to 'private' when an authorId is set) */\n visibility?: StorageVisibility;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n *\n * Memory can be set to `null` to explicitly disable/remove memory from the agent.\n */\nexport type StorageUpdateAgentInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Visibility of the stored agent */\n visibility?: StorageVisibility;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Agent status: 'draft' or 'published' */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<Omit<StorageAgentSnapshotType, 'memory' | 'browser'>> & {\n /** Memory configuration object (static or conditional), or null to disable memory */\n memory?: StorageConditionalField<StorageMemoryRef> | null;\n /** Browser configuration (inline ref), or null to disable browser */\n browser?: StorageConditionalField<StorageBrowserRef> | null;\n };\n\nexport type StorageListAgentsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter agents by author identifier (indexed for fast lookups).\n * Only agents with matching authorId will be returned.\n */\n authorId?: string;\n /**\n * Filter agents by visibility (exact match).\n */\n visibility?: StorageVisibility;\n /**\n * Filter agents by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Filter agents by status.\n * Defaults to 'published' if not specified.\n */\n status?: 'draft' | 'published' | 'archived';\n /**\n * Restrict results to this set of agent IDs. Used by the favorites feature\n * to fetch a specific subset of favorited agents. When provided as an\n * empty array, the result is empty.\n */\n entityIds?: string[];\n /**\n * When set, agents favorited by this user are returned first, ordered\n * by `(is_favorited DESC, <existing orderBy>, id ASC)` over the full\n * candidate set before pagination. Implementations that don't support\n * favorited-first sort treat this as undefined.\n */\n pinFavoritedFor?: string;\n /**\n * When true, only agents favorited by `pinFavoritedFor` are returned.\n * Requires `pinFavoritedFor` to be set. SQL backends collapse this into\n * the same JOIN used for favorited-first sort.\n */\n favoritedOnly?: boolean;\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n agents: StorageResolvedAgentType[];\n};\n\n// ============================================\n// Prompt Block Storage Types\n// ============================================\n\n/** Instruction block discriminated union, stored in agent snapshots */\nexport type AgentInstructionBlock =\n | { type: 'text'; content: string }\n | { type: 'prompt_block_ref'; id: string; rules?: RuleGroup }\n | { type: 'prompt_block'; content: string; rules?: RuleGroup };\n\n/** Condition operators for rule evaluation */\nexport type ConditionOperator =\n | 'equals'\n | 'not_equals'\n | 'contains'\n | 'not_contains'\n | 'greater_than'\n | 'less_than'\n | 'greater_than_or_equal'\n | 'less_than_or_equal'\n | 'in'\n | 'not_in'\n | 'exists'\n | 'not_exists';\n\n/** Leaf rule: evaluates a single condition against a context field */\nexport interface Rule {\n field: string;\n operator: ConditionOperator;\n value?: unknown;\n}\n\n/**\n * Rule group with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost groups (depth 2) may only contain leaf Rules.\n * Mid-level groups (depth 1) may contain Rules or depth-2 groups.\n * Top-level groups (depth 0, exported as `RuleGroup`) may contain Rules or depth-1 groups.\n */\nexport interface RuleGroupDepth2 {\n operator: 'AND' | 'OR';\n conditions: Rule[];\n}\n\nexport interface RuleGroupDepth1 {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth2)[];\n}\n\nexport interface RuleGroup {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth1)[];\n}\n\n// ============================================================================\n// Stored Processor Graph Types\n// ============================================================================\n\n/**\n * A single processor step in a stored processor graph.\n * Each step references a ProcessorProvider by ID and stores its configuration.\n */\nexport interface ProcessorGraphStep {\n /** Unique ID for this step within the graph */\n id: string;\n /** The ProcessorProvider ID that created this processor */\n providerId: string;\n /** Configuration matching the provider's configSchema, validated at creation time */\n config: Record<string, unknown>;\n /** Which processor phases to enable (subset of the provider's availablePhases) */\n enabledPhases: ProcessorPhase[];\n}\n\n/**\n * Processor graph entry and condition types with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost entries (depth 3) may only be step entries.\n * Mid-level entries (depth 2) may contain step, parallel, or conditional — children limited to depth 3.\n * Top-level entries (depth 1, exported as `ProcessorGraphEntry`) may contain step, parallel, or conditional — children limited to depth 2.\n */\n\n/** Depth 3 (leaf): only step entries allowed */\nexport type ProcessorGraphEntryDepth3 = { type: 'step'; step: ProcessorGraphStep };\n\n/** Condition at depth 2 — children are depth 3 entries */\nexport interface ProcessorGraphConditionDepth2 {\n steps: ProcessorGraphEntryDepth3[];\n rules?: RuleGroup;\n}\n\n/** Depth 2: step, parallel, and conditional — children limited to depth 3 */\nexport type ProcessorGraphEntryDepth2 =\n | { type: 'step'; step: ProcessorGraphStep }\n | { type: 'parallel'; branches: ProcessorGraphEntryDepth3[][] }\n | { type: 'conditional'; conditions: ProcessorGraphConditionDepth2[] };\n\n/** Condition at depth 1 — children are depth 2 entries */\nexport interface ProcessorGraphCondition {\n /** The steps to execute if this condition's rules match */\n steps: ProcessorGraphEntryDepth2[];\n /** Rules to evaluate against the previous step's output. If absent, this is the default branch. */\n rules?: RuleGroup;\n}\n\n/** Depth 1 (top-level): step, parallel, and conditional — children limited to depth 2 */\nexport type ProcessorGraphEntry =\n | { type: 'step'; step: ProcessorGraphStep }\n | { type: 'parallel'; branches: ProcessorGraphEntryDepth2[][] }\n | { type: 'conditional'; conditions: ProcessorGraphCondition[] };\n\n/**\n * A stored processor graph representing a pipeline of processors.\n * The entries are ordered: sequential flow is array order, with parallel/conditional branching.\n */\nexport interface StoredProcessorGraph {\n steps: ProcessorGraphEntry[];\n}\n\n/**\n * Thin prompt block record (metadata only).\n * All configuration lives in version snapshots (StoragePromptBlockSnapshotType).\n */\nexport interface StoragePromptBlockType {\n /** Unique identifier */\n id: string;\n /** Block status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Prompt block version snapshot containing the content fields.\n * These fields live exclusively in version snapshot rows.\n */\nexport interface StoragePromptBlockSnapshotType {\n /** Display name of the prompt block */\n name: string;\n /** Purpose description */\n description?: string;\n /** Template content with {{variable}} interpolation */\n content: string;\n /** Rules for conditional inclusion */\n rules?: RuleGroup;\n /** JSON Schema for validating request context values. Defines available variables for {{variableName}} interpolation and conditions. */\n requestContextSchema?: Record<string, unknown>;\n}\n\n/** Resolved prompt block: thin record merged with active version snapshot */\nexport type StorageResolvedPromptBlockType = StoragePromptBlockType &\n StoragePromptBlockSnapshotType & {\n resolvedVersionId?: string;\n };\n\n/** Input for creating a new prompt block */\nexport type StorageCreatePromptBlockInput = {\n /** Unique identifier for the prompt block */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n} & StoragePromptBlockSnapshotType;\n\n/** Input for updating a prompt block */\nexport type StorageUpdatePromptBlockInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Block status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StoragePromptBlockSnapshotType>;\n\nexport type StorageListPromptBlocksInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter prompt blocks by author identifier.\n */\n authorId?: string;\n /**\n * Filter prompt blocks by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Filter prompt blocks by status.\n * Defaults to 'published' if not specified.\n */\n status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin prompt block records */\nexport type StorageListPromptBlocksOutput = PaginationInfo & {\n promptBlocks: StoragePromptBlockType[];\n};\n\n/** Paginated list output for resolved prompt blocks */\nexport type StorageListPromptBlocksResolvedOutput = PaginationInfo & {\n promptBlocks: StorageResolvedPromptBlockType[];\n};\n\n// ============================================\n// Stored Scorer Types\n// ============================================\n\n/**\n * Scorer type discriminator.\n * - 'llm-judge': Custom LLM-as-judge scorer with user-provided instructions\n * - Preset types: Built-in scorers from @mastra/evals (e.g., 'bias', 'toxicity', 'faithfulness')\n */\nexport type StoredScorerType =\n | 'llm-judge'\n | 'answer-relevancy'\n | 'answer-similarity'\n | 'bias'\n | 'context-precision'\n | 'context-relevance'\n | 'faithfulness'\n | 'hallucination'\n | 'noise-sensitivity'\n | 'prompt-alignment'\n | 'tool-call-accuracy'\n | 'toxicity';\n\n/**\n * Stored scorer version snapshot containing ALL scorer configuration fields.\n * These fields live exclusively in version snapshot rows, not on the scorer record.\n */\nexport interface StorageScorerDefinitionSnapshotType {\n /** Display name of the scorer */\n name: string;\n /** Purpose description */\n description?: string;\n /** Scorer type — determines how the scorer is instantiated at runtime */\n type: StoredScorerType;\n /** Model configuration — used for LLM judge; for presets, overrides the default model */\n model?: StorageModelConfig;\n /** System instructions for the judge LLM (used when type === 'llm-judge') */\n instructions?: string;\n /** Score range configuration (used when type === 'llm-judge') */\n scoreRange?: {\n /** Minimum score value (default: 0) */\n min?: number;\n /** Maximum score value (default: 1) */\n max?: number;\n };\n /** Serializable config options for preset scorers (e.g., { scale: 10, context: [...] }) */\n presetConfig?: Record<string, unknown>;\n /** Default sampling configuration */\n defaultSampling?: ScoringSamplingConfig;\n}\n\n/**\n * Thin stored scorer record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageScorerDefinitionSnapshotType).\n */\nexport interface StorageScorerDefinitionType {\n /** Unique, immutable identifier */\n id: string;\n /** Scorer status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Organization identifier for multi-tenant scoping */\n organizationId?: string;\n /** Project identifier for multi-tenant scoping */\n projectId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved stored scorer type that combines the thin record with version snapshot config.\n * Returned by getScorerDefinitionByIdResolved and listScorerDefinitionsResolved.\n */\nexport type StorageResolvedScorerDefinitionType = StorageScorerDefinitionType &\n StorageScorerDefinitionSnapshotType & {\n /** The version ID that was resolved (populated by resolveEntity) */\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new stored scorer. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateScorerDefinitionInput = {\n /** Unique identifier for the scorer */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Organization identifier for multi-tenant scoping */\n organizationId?: string;\n /** Project identifier for multi-tenant scoping */\n projectId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n} & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for updating a stored scorer. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateScorerDefinitionInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Scorer status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageScorerDefinitionSnapshotType>;\n\nexport type StorageListScorerDefinitionsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter scorers by author identifier.\n */\n authorId?: string;\n /**\n * Filter scorers by organization identifier (multi-tenant scoping).\n */\n organizationId?: string;\n /**\n * Filter scorers by project identifier (multi-tenant scoping).\n */\n projectId?: string;\n /**\n * Filter scorers by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Filter scorers by status.\n * Defaults to 'published' if not specified.\n */\n status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored scorer records */\nexport type StorageListScorerDefinitionsOutput = PaginationInfo & {\n scorerDefinitions: StorageScorerDefinitionType[];\n};\n\n/** Paginated list output for resolved stored scorers */\nexport type StorageListScorerDefinitionsResolvedOutput = PaginationInfo & {\n scorerDefinitions: StorageResolvedScorerDefinitionType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n name: string;\n table: string;\n columns: string[];\n unique?: boolean;\n concurrent?: boolean;\n /**\n * SQL WHERE clause for creating partial indexes.\n * @internal Reserved for internal use only. Callers must pre-validate this value.\n * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n * is concatenated directly into the SQL. Any user-facing usage must validate input.\n */\n where?: string;\n method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n opclass?: string; // Operator class for GIN/GIST indexes\n storage?: Record<string, any>; // Storage parameters\n tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n name: string;\n table: string;\n columns: string[];\n unique: boolean;\n size: string;\n definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n scans: number; // Number of index scans\n tuples_read: number; // Number of tuples read\n tuples_fetched: number; // Number of tuples fetched\n last_used?: Date; // Last time index was used\n method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * A chunk of buffered observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\nexport interface BufferedObservationChunk {\n /** Unique identifier for this chunk */\n id: string;\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were last observed */\n lastObservedAt: Date;\n /** When this chunk was created */\n createdAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n /** Optional thread title from observer output */\n threadTitle?: string;\n /** Values extracted during this buffered observation cycle. */\n extractedValues?: Record<string, unknown>;\n /** Extractor failures from this buffered observation cycle. */\n extractionFailures?: Array<{ slug: string; error: string }>;\n}\n\n/**\n * Input for creating a new buffered observation chunk.\n */\nexport interface BufferedObservationChunkInput {\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were observed */\n lastObservedAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n /** Optional thread title from observer output */\n threadTitle?: string;\n /** Values extracted during this buffered observation cycle. */\n extractedValues?: Record<string, unknown>;\n /** Extractor failures from this buffered observation cycle. */\n extractionFailures?: Array<{ slug: string; error: string }>;\n}\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\n\n/** Options for filtering observational memory history queries. */\nexport interface ObservationalMemoryHistoryOptions {\n /** Only return records created at or after this date */\n from?: Date;\n /** Only return records created at or before this date */\n to?: Date;\n /** Number of records to skip after filtering and ordering (for pagination) */\n offset?: number;\n /** Match the literal canonical `<observation-group id=\"...\"` prefix in active or buffered observations. */\n groupId?: string;\n /** Only return generations strictly before this generation count. */\n beforeGeneration?: number;\n /** Only return generations strictly after this generation count. */\n afterGeneration?: number;\n /** Generation ordering. Defaults to DESC (newest first). */\n sortDirection?: 'ASC' | 'DESC';\n /** Only return the record with this ID, if it belongs to the requested thread or resource. */\n recordId?: string;\n}\n\nexport interface ObservationalMemoryRecord {\n // Identity\n /** Unique record ID */\n id: string;\n /** Memory scope - thread or resource */\n scope: ObservationalMemoryScope;\n /** Thread ID (null for resource scope) */\n threadId: string | null;\n /** Resource ID (always present) */\n resourceId: string;\n\n // Timestamps (top-level for easy querying)\n /** When this record was created */\n createdAt: Date;\n /** When this record was last updated */\n updatedAt: Date;\n /**\n * Single cursor for message loading - when we last observed ANY thread for this resource.\n * Undefined means no observations have been made yet (all messages are \"unobserved\").\n */\n lastObservedAt?: Date;\n\n // Generation tracking\n /** How this record was created */\n originType: ObservationalMemoryOriginType;\n /** Generation counter - incremented each time a reflection creates a new record */\n generationCount: number;\n /**\n * Liveness marker. `null`/absent means this record is live (it is the head for its\n * thread or resource). When a reflection creates the next generation, this record's\n * `supersededBy` is set to the successor's id in the same atomic step, and it is never\n * cleared. A superseded record is frozen: lifecycle writes aimed at it are redirected\n * to the head or rejected, never applied to it.\n */\n supersededBy?: string | null;\n\n // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n * For thread scope: Plain observation text.\n */\n activeObservations: string;\n /**\n * Array of buffered observation chunks waiting to be activated.\n * Each chunk represents observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\n bufferedObservationChunks?: BufferedObservationChunk[];\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Observations waiting to be activated (async buffering)\n */\n bufferedObservations?: string;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Token count of buffered observations\n */\n bufferedObservationTokens?: number;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Message IDs being processed in async buffering\n */\n bufferedMessageIds?: string[];\n /** Reflection waiting to be swapped in (async buffering) */\n bufferedReflection?: string;\n /** Token count of buffered reflection (post-compression output) */\n bufferedReflectionTokens?: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n bufferedReflectionInputTokens?: number;\n /**\n * The number of lines in activeObservations that were reflected on\n * when the buffered reflection was created. Used at activation time\n * to separate reflected vs unreflected observations.\n */\n reflectedObservationLineCount?: number;\n\n /**\n * Message IDs observed in the current generation.\n * Used as a safeguard against re-observation if timestamp filtering fails.\n * Reset on reflection (new generation starts fresh).\n */\n observedMessageIds?: string[];\n\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Stored for debugging and auditing observation dates.\n * Example: \"America/Los_Angeles\", \"Europe/London\"\n */\n observedTimezone?: string;\n\n // Token tracking\n /** Running total of all tokens observed */\n totalTokensObserved: number;\n /** Current size of active observations */\n observationTokenCount: number;\n /** Accumulated tokens from pending (unobserved) messages across sessions */\n pendingMessageTokens: number;\n\n // State flags\n /** Is a reflection currently in progress? */\n isReflecting: boolean;\n /** Is observation currently in progress? */\n isObserving: boolean;\n /** Is async observation buffering currently in progress? */\n isBufferingObservation: boolean;\n /** Is async reflection buffering currently in progress? */\n isBufferingReflection: boolean;\n /**\n * The pending message token count at which the last async observation buffer was triggered.\n * Used to determine when the next bufferTokens interval is crossed.\n * Persisted so new instances (created per request) can pick up where the last left off.\n */\n lastBufferedAtTokens: number;\n /**\n * Timestamp cursor for buffered messages.\n * Set to the max message timestamp (+1ms) of the last successfully buffered chunk.\n * Used to filter out already-buffered messages when starting the next buffer.\n * Reset on activation.\n */\n lastBufferedAtTime: Date | null;\n\n // Configuration\n /** Current configuration (stored as JSON) */\n config: Record<string, unknown>;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n threadId: string | null;\n resourceId: string;\n scope: ObservationalMemoryScope;\n config: Record<string, unknown>;\n /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n id: string;\n observations: string;\n tokenCount: number;\n /** Timestamp when these observations were created (for cursor-based message loading) */\n lastObservedAt: Date;\n /**\n * IDs of messages that were observed in this cycle.\n * Stored in record metadata as a safeguard against re-observation on process restart.\n * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n */\n observedMessageIds?: string[];\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n */\n observedTimezone?: string;\n /**\n * The `activeObservations` text this commit was composed from. When provided, the\n * write is applied only if the stored text still equals it exactly; otherwise nothing\n * is written and the result is `{ applied: false, reason: 'conflict' }`. When omitted,\n * the write is last-write-wins.\n */\n expectedActiveObservations?: string;\n}\n\nexport type { UpdateActiveObservationsResult } from '@internal/core/memory';\n\n/**\n * Input for updating buffered observations.\n * Used when async buffering is enabled via `bufferTokens` config.\n * Adds a new chunk to the bufferedObservationChunks array.\n */\nexport interface UpdateBufferedObservationsInput {\n id: string;\n /** The observation chunk to add to the buffer */\n chunk: BufferedObservationChunkInput;\n /** Timestamp cursor for the last buffered message boundary. Set to max message timestamp + 1ms. */\n lastBufferedAtTime?: Date;\n}\n\nexport type { UpdateBufferedObservationsResult } from '@internal/core/memory';\n\n/**\n * Input for swapping buffered observations to active.\n * Supports partial activation via `activationRatio`.\n */\nexport interface SwapBufferedToActiveInput {\n id: string;\n /**\n * Normalized ratio (0-1) controlling how much context to activate.\n * `1 - activationRatio` is the fraction of the threshold to keep as raw messages.\n * Target tokens to remove = `currentPendingTokens - messageTokensThreshold * (1 - activationRatio)`.\n * Chunks are selected by boundary, biased over the target (to ensure remaining context stays at or below the retention floor).\n *\n * Note: this is always a ratio. The caller resolves absolute `bufferActivation` values (> 1)\n * into the equivalent ratio before passing to the storage layer.\n */\n activationRatio: number;\n /**\n * The message token threshold (e.g., observation.messageTokens config value).\n * Used with `activationRatio` to compute the retention floor.\n */\n messageTokensThreshold: number;\n /**\n * Current total pending message tokens in the context window.\n * Used to compute how many tokens need to be removed to reach the retention floor.\n */\n currentPendingTokens: number;\n /**\n * When true, prefer removing more chunks (above `blockAfter`), while still respecting\n * the minimum remaining tokens safeguard (min(1000, retention floor)).\n */\n forceMaxActivation?: boolean;\n /**\n * Optional timestamp to use as lastObservedAt after swap.\n * If not provided, the adapter will use the lastObservedAt from the latest activated chunk.\n */\n lastObservedAt?: Date;\n /**\n * Refreshed buffered chunks with up-to-date messageTokens.\n * When provided, the storage layer uses these instead of the persisted chunks\n * for activation boundary selection, so stale token weights don't cause\n * over- or under-activation.\n */\n bufferedChunks?: BufferedObservationChunk[];\n}\n\n/**\n * Result from swapping buffered observations to active.\n * Contains info about what was activated for UI feedback.\n */\nexport interface SwapBufferedToActiveResult {\n /** Number of chunks that were activated */\n chunksActivated: number;\n /** Total message tokens from activated chunks (context cleared) */\n messageTokensActivated: number;\n /** Total observation tokens from activated chunks */\n observationTokensActivated: number;\n /** Total messages from activated chunks */\n messagesActivated: number;\n /** CycleIds of the activated chunks (for linking UI markers) */\n activatedCycleIds: string[];\n /** All message IDs from activated chunks (for removing from context) */\n activatedMessageIds: string[];\n /** Concatenated observations from activated chunks (for UI display) */\n observations?: string;\n /** Per-chunk breakdown for individual UI markers */\n perChunk?: Array<{\n cycleId: string;\n messageTokens: number;\n observationTokens: number;\n messageCount: number;\n observations: string;\n }>;\n /** Suggested continuation from the most recent activated chunk (if any) */\n suggestedContinuation?: string;\n /** Current task from the most recent activated chunk (if any) */\n currentTask?: string;\n /**\n * True when the target record was superseded by a newer generation. Nothing was\n * written and nothing was activated; the caller should re-read the head and retry.\n */\n retired?: boolean;\n}\n\n/**\n * Input for updating buffered reflection.\n * Used when async reflection buffering is enabled via `bufferTokens` config.\n */\nexport interface UpdateBufferedReflectionInput {\n id: string;\n reflection: string;\n /** Token count of the buffered reflection (post-compression output) */\n tokenCount: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n inputTokenCount: number;\n /**\n * The number of lines in activeObservations at the time of reflection.\n * Used at activation time to know which observations were already reflected on.\n */\n reflectedObservationLineCount: number;\n}\n\n/**\n * Input for swapping buffered reflection to active (creates new generation).\n * Uses the stored `reflectedObservationLineCount` to determine which observations\n * were already reflected on, replaces those with the buffered reflection,\n * and appends any unreflected observations that were added after the reflection started.\n */\nexport interface SwapBufferedReflectionToActiveInput {\n currentRecord: ObservationalMemoryRecord;\n /**\n * Token count for the combined new activeObservations (bufferedReflection + unreflected).\n * Computed by the processor using its token counter before calling the adapter.\n */\n tokenCount: number;\n /**\n * Id for the new generation. When provided, the caller can tell whether its reflection\n * was applied: it was iff the returned record's id equals `newRecordId`. If\n * `currentRecord` was already superseded, nothing is created and the head is returned.\n */\n newRecordId?: string;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one).\n *\n * The new generation is built from the **stored** state of `currentRecord.id`, not from the\n * snapshot: buffered observation chunks are moved to it (in order), and the cursor, buffering\n * markers, flags, and counters are carried over. If observations were appended to the stored\n * text after the snapshot was taken (activation), they are kept after the reflection. If the\n * stored text was rewritten in any other way, nothing is created and the stored record is\n * returned. If `currentRecord` was superseded, nothing is created and the head is returned.\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\n /**\n * Id for the new generation. When provided, the caller can tell whether its reflection\n * was applied: it was iff the returned record's id equals `newRecordId`.\n */\n newRecordId?: string;\n}\n\n/**\n * Input for updating the config of an existing observational memory record.\n * The provided config is deep-merged into the record's existing config.\n */\nexport interface UpdateObservationalMemoryConfigInput {\n id: string;\n config: Record<string, unknown>;\n}\n\n// ============================================\n// MCP Client Storage Types\n// ============================================\n\n/**\n * Serializable MCP server transport definition for storage.\n * Only includes fields that can be safely serialized to JSON.\n * Non-serializable fields (fetch, authProvider, logger, etc.) must be\n * provided via code-defined MCP clients.\n */\nexport interface StorageMCPServerConfig {\n /** Transport type discriminator */\n type: 'stdio' | 'http';\n /** Command to execute (stdio transport) */\n command?: string;\n /** Arguments to pass to the command (stdio transport) */\n args?: string[];\n /** Environment variables for the subprocess (stdio transport) */\n env?: Record<string, string>;\n /** URL of the MCP server endpoint (http transport) — stored as string */\n url?: string;\n /** Timeout in milliseconds for server operations */\n timeout?: number;\n /**\n * Optional tool selection/filtering at the server level.\n * When provided, only tools listed here are exposed by this server.\n * When omitted, all tools from the server are exposed.\n */\n tools?: Record<string, StorageToolConfig>;\n}\n\n/**\n * MCP client version snapshot containing ALL configuration fields.\n * These fields live exclusively in version snapshot rows, not on the MCP client record.\n */\nexport interface StorageMCPClientSnapshotType {\n /** Display name of the MCP client configuration */\n name: string;\n /** Purpose description */\n description?: string;\n /** MCP servers keyed by server name */\n servers: Record<string, StorageMCPServerConfig>;\n}\n\n/**\n * Thin stored MCP client record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageMCPClientSnapshotType).\n */\nexport interface StorageMCPClientType {\n /** Unique, immutable identifier */\n id: string;\n /** Client status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to mcp_client_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP client */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved stored MCP client type that combines the thin record with version snapshot config.\n * Returned by getMCPClientByIdResolved and listMCPClientsResolved.\n */\nexport type StorageResolvedMCPClientType = StorageMCPClientType &\n StorageMCPClientSnapshotType & {\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new stored MCP client. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateMCPClientInput = {\n /** Unique identifier for the MCP client */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP client */\n metadata?: Record<string, unknown>;\n} & StorageMCPClientSnapshotType;\n\n/**\n * Input for updating a stored MCP client. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateMCPClientInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP client */\n metadata?: Record<string, unknown>;\n /** FK to mcp_client_versions.id - the currently active version */\n activeVersionId?: string;\n /** Client status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageMCPClientSnapshotType>;\n\nexport type StorageListMCPClientsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter MCP clients by author identifier.\n */\n authorId?: string;\n /**\n * Filter MCP clients by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Filter MCP clients by status.\n * Defaults to 'published' if not specified.\n */\n status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored MCP client records */\nexport type StorageListMCPClientsOutput = PaginationInfo & {\n mcpClients: StorageMCPClientType[];\n};\n\n/** Paginated list output for resolved stored MCP clients */\nexport type StorageListMCPClientsResolvedOutput = PaginationInfo & {\n mcpClients: StorageResolvedMCPClientType[];\n};\n\n// ============================================\n// MCP Server Storage Types\n// ============================================\n\n/**\n * MCP server version snapshot containing ALL configuration fields.\n * These fields live exclusively in version snapshot rows, not on the MCP server record.\n *\n * Serializable metadata from MCPServerConfig. Non-serializable fields (tools, agents, workflows)\n * are stored as reference keys and resolved at hydration time.\n */\nexport interface StorageMCPServerSnapshotType {\n /** Display name of the MCP server */\n name: string;\n /** Semantic version string */\n version: string;\n /** Purpose description */\n description?: string;\n /** Instructions describing how to use the server */\n instructions?: string;\n /** Repository information for the server's source code */\n repository?: {\n url: string;\n type?: string;\n directory?: string;\n };\n /** Release date of this server version (ISO 8601 string) */\n releaseDate?: string;\n /** Whether this version is the latest available */\n isLatest?: boolean;\n /** Canonical packaging format (e.g., 'npm', 'docker', 'pypi', 'crates') */\n packageCanonical?: string;\n /**\n * Tool keys to include on this MCP server.\n * Keys are tool IDs registered in Mastra, values provide optional config overrides.\n */\n tools?: Record<string, StorageToolConfig>;\n /**\n * Agent keys to expose as tools on this MCP server.\n * Keys are agent IDs registered in Mastra, values provide optional config overrides.\n */\n agents?: Record<string, StorageToolConfig>;\n /**\n * Workflow keys to expose as tools on this MCP server.\n * Keys are workflow IDs registered in Mastra, values provide optional config overrides.\n */\n workflows?: Record<string, StorageToolConfig>;\n}\n\n/**\n * Thin stored MCP server record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageMCPServerSnapshotType).\n */\nexport interface StorageMCPServerType {\n /** Unique, immutable identifier */\n id: string;\n /** Server status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to mcp_server_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP server */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved stored MCP server type that combines the thin record with version snapshot config.\n * Returned by getMCPServerByIdResolved and listMCPServersResolved.\n */\nexport type StorageResolvedMCPServerType = StorageMCPServerType &\n StorageMCPServerSnapshotType & {\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new stored MCP server. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateMCPServerInput = {\n /** Unique identifier for the MCP server */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP server */\n metadata?: Record<string, unknown>;\n} & StorageMCPServerSnapshotType;\n\n/**\n * Input for updating a stored MCP server. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateMCPServerInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the MCP server */\n metadata?: Record<string, unknown>;\n /** FK to mcp_server_versions.id - the currently active version */\n activeVersionId?: string;\n /** Server status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageMCPServerSnapshotType>;\n\nexport type StorageListMCPServersInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter MCP servers by author identifier.\n */\n authorId?: string;\n /**\n * Filter MCP servers by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Filter MCP servers by status.\n * Defaults to 'published' if not specified.\n */\n status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored MCP server records */\nexport type StorageListMCPServersOutput = PaginationInfo & {\n mcpServers: StorageMCPServerType[];\n};\n\n/** Paginated list output for resolved stored MCP servers */\nexport type StorageListMCPServersResolvedOutput = PaginationInfo & {\n mcpServers: StorageResolvedMCPServerType[];\n};\n\n// ============================================\n// Workspace Storage Types\n// ============================================\n\n/**\n * Serializable filesystem configuration for storage.\n * References a provider type string that the editor resolves at hydration time.\n */\nexport interface StorageFilesystemConfig {\n /** Provider type identifier (e.g., 's3', 'gcs', 'local') — resolved by the editor's filesystem registry */\n provider: string;\n /** Provider-specific configuration (bucket, basePath, etc.) */\n config: Record<string, unknown>;\n /** Whether the filesystem is read-only */\n readOnly?: boolean;\n}\n\n/**\n * Serializable sandbox configuration for storage.\n * References a provider type string that the editor resolves at hydration time.\n */\nexport interface StorageSandboxConfig {\n /** Provider type identifier (e.g., 'e2b') — resolved by the editor's sandbox registry */\n provider: string;\n /** Provider-specific configuration */\n config: Record<string, unknown>;\n}\n\n/**\n * Serializable search configuration for storage.\n * References vector store and embedder by provider/name rather than runtime instances.\n */\nexport interface StorageSearchConfig {\n /** Vector store provider identifier (e.g., 'pg', 'pinecone') */\n vectorProvider?: string;\n /** Vector store provider-specific configuration */\n vectorConfig?: Record<string, unknown>;\n /** Embedder provider identifier (e.g., 'openai', 'fastembed') */\n embedderProvider?: string;\n /** Embedder model name */\n embedderModel?: string;\n /** Embedder provider-specific configuration */\n embedderConfig?: Record<string, unknown>;\n /** BM25 keyword search config — true for defaults, or object for custom params */\n bm25?: boolean | { k1?: number; b?: number };\n /** Custom index name for the vector store */\n searchIndexName?: string;\n /** Paths to auto-index on init */\n autoIndexPaths?: string[];\n}\n\n/**\n * Serializable per-tool configuration for workspace tools.\n */\nexport interface StorageWorkspaceToolConfig {\n /** Whether the tool is enabled (default: true) */\n enabled?: boolean;\n /** Whether the tool requires user approval before execution (default: false) */\n requireApproval?: boolean;\n /** For write tools: require reading a file before writing to it */\n requireReadBeforeWrite?: boolean;\n}\n\n/**\n * Serializable workspace tools configuration for storage.\n */\nexport interface StorageWorkspaceToolsConfig {\n /** Default: whether all tools are enabled (default: true) */\n enabled?: boolean;\n /** Default: whether all tools require user approval (default: false) */\n requireApproval?: boolean;\n /** Per-tool overrides, keyed by workspace tool name */\n tools?: Record<string, StorageWorkspaceToolConfig>;\n}\n\n/**\n * Workspace version snapshot type containing ALL workspace configuration fields.\n * These fields live exclusively in version snapshot rows, not on the workspace record.\n */\nexport interface StorageWorkspaceSnapshotType {\n /** Display name of the workspace */\n name: string;\n /** Purpose description */\n description?: string;\n /** Primary filesystem configuration */\n filesystem?: StorageFilesystemConfig;\n /** Sandbox configuration */\n sandbox?: StorageSandboxConfig;\n /** Mounted filesystems keyed by mount path */\n mounts?: Record<string, StorageFilesystemConfig>;\n /** Search configuration (vector, embedder, BM25) */\n search?: StorageSearchConfig;\n /** Skill entity IDs assigned to this workspace */\n skills?: string[];\n /** Workspace tool configuration */\n tools?: StorageWorkspaceToolsConfig;\n /** Auto-sync between fs and sandbox (default: false) */\n autoSync?: boolean;\n /** Timeout for individual operations in milliseconds */\n operationTimeout?: number;\n}\n\n/**\n * Thin workspace record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageWorkspaceSnapshotType).\n */\nexport interface StorageWorkspaceType {\n /** Unique, immutable identifier */\n id: string;\n /** Workspace status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to workspace_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the workspace */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved workspace type that combines the thin record with version snapshot config.\n * Returned by getWorkspaceByIdResolved and listWorkspacesResolved.\n */\nexport type StorageResolvedWorkspaceType = StorageWorkspaceType &\n StorageWorkspaceSnapshotType & {\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new workspace. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateWorkspaceInput = {\n /** Unique identifier for the workspace */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the workspace */\n metadata?: Record<string, unknown>;\n} & StorageWorkspaceSnapshotType;\n\n/**\n * Input for updating a workspace. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateWorkspaceInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the workspace */\n metadata?: Record<string, unknown>;\n /** FK to workspace_versions.id - the currently active version */\n activeVersionId?: string;\n /** Workspace status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageWorkspaceSnapshotType>;\n\nexport type StorageListWorkspacesInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter workspaces by author identifier.\n */\n authorId?: string;\n /**\n * Filter workspaces by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin workspace records */\nexport type StorageListWorkspacesOutput = PaginationInfo & {\n workspaces: StorageWorkspaceType[];\n};\n\n/** Paginated list output for resolved workspaces */\nexport type StorageListWorkspacesResolvedOutput = PaginationInfo & {\n workspaces: StorageResolvedWorkspaceType[];\n};\n\n// ============================================\n// Skill Storage Types\n// ============================================\n\n/**\n * Serializable content source for skill storage.\n * Mirrors the runtime ContentSource but stored as plain JSON.\n */\nexport type StorageContentSource =\n | { type: 'external'; packagePath: string }\n | { type: 'local'; projectPath: string }\n | { type: 'managed'; mastraPath: string };\n\n/**\n * A node in the skill file tree (folder or file with inline content).\n * Used for round-tripping the full file structure through the UI.\n */\nexport interface StorageSkillFileNode {\n id?: string;\n name: string;\n type: 'file' | 'folder';\n content?: string;\n children?: StorageSkillFileNode[];\n}\n\n/**\n * Skill version snapshot type containing ALL skill definition fields.\n * These fields live exclusively in version snapshot rows, not on the skill record.\n */\nexport interface StorageSkillSnapshotType {\n /** Skill name (1-64 chars, lowercase, hyphens only) */\n name: string;\n /** Description of what the skill does and when to use it */\n description: string;\n /** Markdown instructions from SKILL.md body */\n instructions: string;\n /** Optional license identifier */\n license?: string;\n /** Optional compatibility requirements */\n compatibility?: unknown;\n /** Source of the skill */\n source?: StorageContentSource;\n /** List of reference file paths */\n references?: string[];\n /** List of script file paths */\n scripts?: string[];\n /** List of asset file paths */\n assets?: string[];\n /** Optional arbitrary metadata */\n metadata?: Record<string, unknown>;\n /** Full file tree structure (folders, files with content) for round-tripping in the UI */\n files?: StorageSkillFileNode[];\n /** Content-addressable file tree manifest for this skill version */\n tree?: SkillVersionTree;\n}\n\n/**\n * Thin skill record type containing only metadata fields.\n * All definition content lives in version snapshots (StorageSkillSnapshotType).\n */\nexport interface StorageSkillType {\n /** Unique, immutable identifier */\n id: string;\n /** Skill status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to skill_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /**\n * Access control: 'private' = only owner/admins, 'public' = anyone.\n * May be undefined for legacy records created before visibility was introduced.\n */\n visibility?: StorageVisibility;\n /**\n * Denormalized count of favorites on this skill. Maintained by the favorites\n * storage domain. Optional; treat undefined as 0 for legacy rows.\n */\n favoriteCount?: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved skill type that combines the thin record with version snapshot content.\n * Returned by getSkillByIdResolved and listSkillsResolved.\n */\nexport type StorageResolvedSkillType = StorageSkillType &\n StorageSkillSnapshotType & {\n resolvedVersionId?: string;\n };\n\n/**\n * Input for creating a new skill. Flat union of thin record fields\n * and initial content (used to create version 1).\n */\nexport type StorageCreateSkillInput = {\n /** Unique identifier for the skill */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Access control visibility */\n visibility?: StorageVisibility;\n} & StorageSkillSnapshotType;\n\n/**\n * Input for updating a skill. Includes metadata-level fields and optional content fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateSkillInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Access control visibility */\n visibility?: StorageVisibility;\n /** FK to skill_versions.id - the currently active version */\n activeVersionId?: string;\n /** Skill status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageSkillSnapshotType>;\n\nexport type StorageListSkillsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter skills by author identifier.\n */\n authorId?: string;\n /**\n * Filter skills by visibility (exact match).\n */\n visibility?: StorageVisibility;\n /**\n * Filter skills by status (exact match).\n */\n status?: StorageSkillType['status'];\n /**\n * Filter skills by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n /**\n * Restrict results to this set of skill IDs. Used by the favorites feature\n * to fetch a specific subset of favorited skills. When provided as an\n * empty array, the result is empty.\n */\n entityIds?: string[];\n /**\n * When set, skills favorited by this user are returned first, ordered\n * by `(is_favorited DESC, <existing orderBy>, id ASC)` over the full\n * candidate set before pagination. Implementations that don't support\n * favorited-first sort treat this as undefined.\n */\n pinFavoritedFor?: string;\n /**\n * When true, only skills favorited by `pinFavoritedFor` are returned.\n * Requires `pinFavoritedFor` to be set. SQL backends collapse this into\n * the same JOIN used for favorited-first sort.\n */\n favoritedOnly?: boolean;\n};\n\n/** Paginated list output for thin skill records */\nexport type StorageListSkillsOutput = PaginationInfo & {\n skills: StorageSkillType[];\n};\n\n/** Paginated list output for resolved skills */\nexport type StorageListSkillsResolvedOutput = PaginationInfo & {\n skills: StorageResolvedSkillType[];\n};\n\n/**\n * Per-skill configuration stored in agent snapshots.\n * Allows overriding skill description and instructions for a specific agent context.\n */\nexport interface StorageSkillConfig {\n /** Custom description override for this skill in this agent context */\n description?: string;\n /** Custom instructions override for this skill in this agent context */\n instructions?: string;\n /** Pin to a specific version ID. Takes precedence over strategy. */\n pin?: string;\n /** Resolution strategy: 'latest' = latest published version, 'live' = read from filesystem */\n strategy?: 'latest' | 'live';\n}\n\n/**\n * A single entry in a skill version's file tree manifest.\n * Maps a file path to its content-addressable blob hash.\n */\nexport interface SkillVersionTreeEntry {\n /** SHA-256 hash of the file content (content-addressable key) */\n blobHash: string;\n /** File size in bytes */\n size: number;\n /** Optional MIME type */\n mimeType?: string;\n /**\n * Content encoding used in the blob store.\n * - 'utf-8' (default): content stored as UTF-8 text\n * - 'base64': content stored as base64-encoded string (for binary files like images)\n */\n encoding?: 'utf-8' | 'base64';\n}\n\n/**\n * Complete file tree manifest for a skill version.\n * Maps relative file paths to their blob entries.\n * This is stored as JSONB on the skill version row.\n *\n * Example:\n * {\n * \"SKILL.md\": { blobHash: \"abc123...\", size: 1024, mimeType: \"text/markdown\" },\n * \"references/api.md\": { blobHash: \"def456...\", size: 512, mimeType: \"text/markdown\" },\n * \"scripts/setup.sh\": { blobHash: \"ghi789...\", size: 256, mimeType: \"text/x-shellscript\" }\n * }\n */\nexport interface SkillVersionTree {\n entries: Record<string, SkillVersionTreeEntry>;\n}\n\n/**\n * A stored blob entry in the content-addressable blob store.\n */\nexport interface StorageBlobEntry {\n /** SHA-256 hash of the content (primary key) */\n hash: string;\n /** The file content (text) */\n content: string;\n /** File size in bytes */\n size: number;\n /** Optional MIME type */\n mimeType?: string;\n /** When the blob was first stored */\n createdAt: Date;\n}\n\n/**\n * Workspace reference configuration stored in agent snapshots.\n * Can reference a stored workspace by ID, provide inline workspace config,\n * or name a registered workspace provider to build the entire workspace.\n */\nexport type StorageWorkspaceRef =\n | { type: 'id'; workspaceId: string }\n | { type: 'inline'; config: StorageWorkspaceSnapshotType }\n | { type: 'provider'; provider: string; config: Record<string, unknown> };\n\n/**\n * Memory reference configuration stored in agent snapshots.\n * - `{ type: 'id', memoryId }` references a Memory instance registered on Mastra\n * (looked up by registry key first, then by the instance's own id).\n * - `{ type: 'inline', config }` builds a new Memory from serialized config.\n * - An untagged `SerializedMemoryConfig` is the legacy inline form and behaves like `inline`.\n */\nexport type StorageMemoryRef =\n | { type: 'id'; memoryId: string }\n | { type: 'inline'; config: SerializedMemoryConfig }\n | SerializedMemoryConfig;\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult<any, any, any, any>;\n error?: SerializedError;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n activePaths?: Array<number>;\n activeStepsPath?: Record<string, number[]>;\n /**\n * Tracing context for span continuity during suspend/resume.\n * Persisted when workflow suspends to enable linking resumed spans\n * as children of the original suspended span.\n */\n tracingContext?: {\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n };\n /** When an agent resume claimed this suspended run. See `WorkflowRunState.resumeClaimedAt`. */\n resumeClaimedAt?: number;\n /** The claim an agent resume started under a run-ownership lease. See `WorkflowRunState.resumeLeasedClaimAt`. */\n resumeLeasedClaimAt?: number;\n /** What an agent resume claims this run with. See `WorkflowRunState.resumeClaimIntent`. */\n resumeClaimIntent?: WorkflowRunState['resumeClaimIntent'];\n /**\n * Optional compare-and-set guard. When provided, the update is applied only if the\n * persisted snapshot's status matches one of these values. Otherwise the update is a\n * no-op and `updateWorkflowState` resolves to `undefined`.\n *\n * This is only enforced atomically by stores that report `supportsConcurrentUpdates()`,\n * because those stores load and write the snapshot inside a single critical section.\n * Stores without concurrent update support apply it on a best-effort basis.\n *\n * This field is a guard only: it is never merged into the persisted snapshot.\n */\n expectedStatus?: WorkflowRunStatus | WorkflowRunStatus[];\n}\n\n/**\n * Returns true when a snapshot's current status satisfies an `expectedStatus` guard.\n * Stores call this inside their `updateWorkflowState` critical section.\n */\nexport function matchesExpectedWorkflowStatus(\n currentStatus: WorkflowRunStatus | undefined,\n expectedStatus: UpdateWorkflowStateOptions['expectedStatus'],\n): boolean {\n if (expectedStatus === undefined) return true;\n const expected = Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus];\n return currentStatus !== undefined && expected.includes(currentStatus);\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n while (true) {\n const typeName = getZodTypeName(current);\n if (!typeName) break;\n\n if (typeName === 'ZodNullable' || typeName === 'ZodOptional') {\n nullable = true;\n }\n\n const inner = getZodInnerType(current, typeName);\n if (!inner) break;\n current = inner;\n }\n\n return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks with {kind: \"...\"} objects\n * Zod 4 uses _zod.def.checks with {def: {check: \"...\", format: \"...\"}} objects\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n // Zod 4 structure: checks have def.check instead of kind\n if ('_zod' in schema) {\n const zodV4 = schema as { _zod?: { def?: { checks?: unknown[] } } };\n const checks = zodV4._zod?.def?.checks;\n\n if (checks && Array.isArray(checks)) {\n return checks.map((check: unknown) => {\n // Type guard for Zod v4 check structure\n if (\n typeof check === 'object' &&\n check !== null &&\n 'def' in check &&\n typeof check.def === 'object' &&\n check.def !== null\n ) {\n const def = check.def as Record<string, unknown>;\n\n // For number checks in Zod 4, format:\"safeint\" means int()\n if (def.check === 'number_format' && def.format === 'safeint') {\n return { kind: 'int' };\n }\n\n // For string checks in Zod 4, check type is the format name\n if (def.check === 'string_format' && typeof def.format === 'string') {\n return { kind: def.format }; // e.g., \"uuid\", \"email\", etc.\n }\n\n // Generic mapping: use the check type as kind\n return { kind: typeof def.check === 'string' ? def.check : 'unknown' };\n }\n\n return { kind: 'unknown' };\n });\n }\n }\n\n // Zod 3 structure: checks already have kind property\n if ('_def' in schema) {\n const zodV3 = schema as { _def?: { checks?: Array<{ kind: string }> } };\n const checks = zodV3._def?.checks;\n\n if (checks && Array.isArray(checks)) {\n return checks;\n }\n }\n\n return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n const typeName = getZodTypeName(schema);\n\n if (typeName === 'ZodString') {\n // Check for UUID validation\n const checks = getZodChecks(schema);\n if (checks.some(c => c.kind === 'uuid')) {\n return 'uuid';\n }\n return 'text';\n }\n if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n return 'text';\n }\n if (typeName === 'ZodNumber') {\n // Check for integer validation\n const checks = getZodChecks(schema);\n return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n }\n // Both ZodBigInt (v3) and ZodBigint (v4) should map to bigint\n if (typeName === 'ZodBigInt' || typeName === 'ZodBigint') {\n return 'bigint';\n }\n if (typeName === 'ZodDate') {\n return 'timestamp';\n }\n if (typeName === 'ZodBoolean') {\n return 'boolean';\n }\n // fall back for objects/records/unknown\n return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n const shape = zObject.shape;\n const result: Record<string, StorageColumn> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n result[key] = {\n type: zodToStorageType(base),\n nullable,\n };\n }\n\n return result as Record<keyof Shape & string, StorageColumn>;\n}\n\n// ============================================\n// Browser Configuration Types\n// ============================================\n\n/**\n * Browser configuration stored in agent snapshots.\n *\n * Only stable, declarative configuration is persisted here. Runtime/security\n * concerns (cdpUrl, scope, profile, executablePath) belong in the BrowserProvider\n * registration where they're set per-instance via `createBrowser`.\n *\n * Runtime-only options (onLaunch, onClose, cdpUrl as function) are never stored.\n */\nexport interface StorageBrowserConfig {\n /** Provider type identifier (e.g., 'stagehand', 'playwright') — resolved by the editor's browser registry */\n provider: string;\n\n /**\n * Whether to run the browser in headless mode (no visible UI).\n * @default true\n */\n headless?: boolean;\n\n /**\n * Browser viewport dimensions.\n * Controls the size of the browser window and how websites render.\n */\n viewport?: {\n width: number;\n height: number;\n };\n\n /**\n * Default timeout in milliseconds for browser operations.\n * @default 10000 (10 seconds)\n */\n timeout?: number;\n\n /**\n * Screencast options for streaming browser frames.\n */\n screencast?: {\n /** Image format (default: 'jpeg') */\n format?: 'jpeg' | 'png';\n /** JPEG quality 0-100 (default: 80) */\n quality?: number;\n /** Max width in pixels (default: 1280) */\n maxWidth?: number;\n /** Max height in pixels (default: 720) */\n maxHeight?: number;\n /** Capture every Nth frame (default: 1) */\n everyNthFrame?: number;\n };\n}\n\n/**\n * Browser reference configuration stored in agent snapshots.\n * Provides inline browser config that the editor resolves at hydration time.\n */\nexport type StorageBrowserRef = { type: 'inline'; config: StorageBrowserConfig };\n\n// ============================================\n// Dataset Types\n// ============================================\n\nexport type TargetType = 'agent' | 'workflow' | 'scorer' | 'processor';\n\nexport interface DatasetRecord {\n id: string;\n name: string;\n description?: string;\n metadata?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n groundTruthSchema?: Record<string, unknown>;\n requestContextSchema?: Record<string, unknown>;\n tags?: string[] | null;\n targetType?: TargetType | null;\n targetIds?: string[] | null;\n scorerIds?: string[] | null;\n /** Multi-tenant organization/account scope. */\n organizationId?: string | null;\n /** Platform project scope. Pairs with {@link DatasetRecord.organizationId} to form the dataset's tenancy bucket. */\n projectId?: string | null;\n /** Recurring-problem fingerprint (e.g. detector-emitted candidate key). */\n candidateKey?: string | null;\n /** Incident-specific identifier minted by the detector. */\n candidateId?: string | null;\n version: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface DatasetItemSource {\n type: 'csv' | 'json' | 'trace' | 'llm' | 'experiment-result' | 'candidate-screener';\n referenceId?: string;\n}\n\n/**\n * A single static tool mock authored on a dataset item (output-only in v1).\n * Structurally mirrors `ItemToolMock` in the experiment engine; kept local here\n * to avoid a storage→datasets import cycle.\n */\nexport interface DatasetItemToolMock {\n toolName: string;\n args: Record<string, unknown>;\n output: unknown;\n /** Argument matching mode. `strict` (default) deep-equals args; `ignore` matches on toolName only. */\n matchArgs?: 'strict' | 'ignore';\n}\n\n/**\n * Diagnostic receipt for tool-mock usage on a single experiment result.\n * Structurally mirrors `ToolMockReport` in the experiment engine.\n */\nexport type DatasetUnmockedToolPolicy = 'allow' | 'deny';\n\nexport interface DatasetToolMockReport {\n served: { mockIndex: number; toolName: string; args: unknown }[];\n unconsumed: { mockIndex: number; toolName: string; args: unknown }[];\n liveCalls: { toolName: string; args: unknown }[];\n failure?: {\n code: 'TOOL_MOCK_MISMATCH' | 'TOOL_MOCK_EXHAUSTED' | 'TOOL_MOCK_NOT_DECLARED';\n toolName: string;\n args: unknown;\n };\n}\n\nexport interface DatasetItem {\n id: string;\n datasetId: string;\n datasetVersion: number;\n /** Caller-defined, dataset-local logical identity. Immutable after insertion. */\n externalId?: string | null;\n /** Inherited from the parent dataset at insert time. */\n organizationId?: string | null;\n /** Inherited from the parent dataset at insert time. */\n projectId?: string | null;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n toolMocks?: DatasetItemToolMock[] | null;\n unmockedToolPolicy?: DatasetUnmockedToolPolicy | null;\n scorerIds?: string[] | null;\n requestContext?: Record<string, unknown> | null;\n metadata?: Record<string, unknown> | null;\n source?: DatasetItemSource | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface DatasetItemRow {\n id: string;\n datasetId: string;\n datasetVersion: number;\n /** Caller-defined, dataset-local logical identity. Immutable across SCD-2 history. */\n externalId?: string | null;\n /** Inherited from the parent dataset at insert time. */\n organizationId?: string | null;\n /** Inherited from the parent dataset at insert time. */\n projectId?: string | null;\n validTo: number | null;\n isDeleted: boolean;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n toolMocks?: DatasetItemToolMock[] | null;\n unmockedToolPolicy?: DatasetUnmockedToolPolicy | null;\n scorerIds?: string[] | null;\n requestContext?: Record<string, unknown> | null;\n metadata?: Record<string, unknown> | null;\n source?: DatasetItemSource | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface DatasetVersion {\n id: string;\n datasetId: string;\n version: number;\n createdAt: Date;\n}\n\n// Dataset CRUD Input/Output Types\n\nexport interface CreateDatasetInput {\n /**\n * Optional caller-defined durable identity. When provided, storage adapters atomically create\n * the dataset or return the compatible dataset that already owns this ID.\n */\n id?: string;\n name: string;\n description?: string;\n metadata?: Record<string, unknown>;\n inputSchema?: Record<string, unknown> | null;\n groundTruthSchema?: Record<string, unknown> | null;\n requestContextSchema?: Record<string, unknown> | null;\n /**\n * Discriminator for the target this dataset's items will be replayed against.\n * Optional because a dataset can exist purely as a collection of items\n * (e.g. emitted by a detector for a target kind OSS doesn't yet know how to\n * run). Datasets created without a {@link TargetType} are **not\n * experiment-eligible**: the experiment runner requires a non-null\n * {@link CreateExperimentInput.targetType} to resolve an executor, so a\n * downstream consumer must either set this on create or refuse to run an\n * experiment against the dataset.\n */\n targetType?: TargetType;\n targetIds?: string[];\n scorerIds?: string[];\n /**\n * Multi-tenant organization/account scope. Stamped onto every item inserted into this dataset.\n * Immutable after create — items inherit this from the parent dataset on every write, so changing\n * it later would corrupt SCD-2 tombstone history. Intentionally absent from {@link UpdateDatasetInput}.\n */\n organizationId?: string | null;\n /**\n * Platform project scope. Stamped onto every item inserted into this dataset.\n * Pairs with {@link CreateDatasetInput.organizationId} to form the (organizationId, projectId)\n * tenancy bucket. Immutable after create — see {@link CreateDatasetInput.organizationId}.\n */\n projectId?: string | null;\n /**\n * Recurring-problem fingerprint (e.g. detector-emitted candidate key).\n * Immutable after create — pairs with {@link CreateDatasetInput.candidateId} to identify\n * the dataset's source incident and must not drift over the dataset's lifetime.\n */\n candidateKey?: string | null;\n /**\n * Incident-specific identifier minted by the detector.\n * Immutable after create — see {@link CreateDatasetInput.candidateKey}.\n */\n candidateId?: string | null;\n}\n\n/**\n * Update input for a dataset. Tenancy ({@link CreateDatasetInput.organizationId},\n * {@link CreateDatasetInput.projectId}) and candidate identity\n * ({@link CreateDatasetInput.candidateKey}, {@link CreateDatasetInput.candidateId})\n * are intentionally omitted from the payload: they are set once at create time and must\n * remain immutable so item SCD-2 history (which inherits these fields per-write from the\n * parent dataset) stays consistent across the dataset's lifetime.\n *\n * The optional `filters` field is a *read scope*, not a payload update — when provided,\n * the update is only applied if the target dataset row also matches the tenancy filters.\n * Callers that know the tenant should pass this to prevent cross-tenant updates via a\n * leaked dataset ID.\n */\nexport interface UpdateDatasetInput {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n inputSchema?: Record<string, unknown> | null;\n groundTruthSchema?: Record<string, unknown> | null;\n requestContextSchema?: Record<string, unknown> | null;\n tags?: string[] | null;\n targetType?: TargetType | null;\n targetIds?: string[] | null;\n scorerIds?: string[] | null;\n /** Tenancy read-scope. When set, the update only applies if the row matches; otherwise it is treated as NOT_FOUND. */\n filters?: DatasetTenancyFilters;\n}\n\n/**\n * The mutable, user-supplied payload portion of a dataset item.\n *\n * Identity (`id`, `datasetId`) and storage-managed audit fields (`datasetVersion`,\n * `organizationId`, `projectId`, `createdAt`, `updatedAt`) live on {@link DatasetItem}\n * and are not part of the payload.\n *\n * Used as the base shape for {@link AddDatasetItemInput} and\n * {@link BatchInsertItemsInput.items}, and (as `Partial<…>`) for\n * {@link UpdateDatasetItemInput}.\n */\nexport interface DatasetItemPayload {\n /**\n * Optional caller-defined identity scoped to this dataset. Reusing an identity\n * with the originally accepted payload is idempotent; incompatible reuse fails.\n */\n externalId?: string;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n toolMocks?: DatasetItemToolMock[];\n /** Overrides the experiment's handling of tool calls not declared in `toolMocks`. */\n unmockedToolPolicy?: DatasetUnmockedToolPolicy;\n scorerIds?: string[];\n requestContext?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n source?: DatasetItemSource;\n}\n\nexport interface AddDatasetItemInput extends DatasetItemPayload {\n datasetId: string;\n /**\n * Tenancy read-scope for the parent dataset. When set, the insert is rejected\n * (NOT_FOUND) if the parent dataset row does not match the tenancy filters —\n * prevents adding items to a dataset in another tenant via a leaked datasetId.\n */\n filters?: DatasetTenancyFilters;\n}\n\n/**\n * Update input for a dataset item. All payload fields are optional; only the\n * provided fields are patched.\n *\n * The optional `filters` field is a tenancy read-scope for the parent dataset;\n * see {@link AddDatasetItemInput.filters}.\n */\nexport interface UpdateDatasetItemInput extends Partial<Omit<DatasetItemPayload, 'externalId' | 'scorerIds'>> {\n id: string;\n datasetId: string;\n scorerIds?: string[] | null;\n filters?: DatasetTenancyFilters;\n}\n\nexport interface DatasetItemIdentityConflictDetail {\n index: number;\n externalId: string;\n existingItemId: string;\n reason: 'payload_mismatch' | 'deleted';\n}\n\n/**\n * Delete input for a single dataset item. The optional `filters` field is a\n * tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}.\n */\nexport interface DeleteDatasetItemInput {\n id: string;\n datasetId: string;\n filters?: DatasetTenancyFilters;\n}\n\n/**\n * Permanently scrubs user-supplied content from every SCD-2 row for an item\n * and from experiment results that reference it, while retaining identity and\n * versioning skeletons for referential integrity and reproducibility.\n */\nexport interface PurgeDatasetItemInput {\n id: string;\n datasetId: string;\n filters?: DatasetTenancyFilters;\n}\n\nexport interface DatasetTenancyFilters {\n organizationId?: string;\n projectId?: string;\n}\n\nexport interface ListDatasetsFilters extends DatasetTenancyFilters {\n candidateKey?: string;\n candidateId?: string;\n /**\n * Filter by dataset target type (agent | workflow | scorer | processor).\n */\n targetType?: TargetType;\n /**\n * Filter to datasets whose `targetIds` intersect this list. A dataset\n * matches if any of its targetIds is in this array. An empty array is\n * treated as \"no filter\" (matches all datasets), not \"match none\".\n */\n targetIds?: string[];\n /**\n * Only return datasets with these IDs. Unlike `targetIds`, an empty array\n * matches no datasets.\n */\n datasetIds?: string[];\n /**\n * Substring match on dataset `name`, case-insensitive.\n */\n name?: string;\n}\n\nexport type DatasetOrderByField = 'createdAt' | 'updatedAt' | 'name';\nexport type DatasetItemOrderByField = 'createdAt' | 'updatedAt';\nexport type ExperimentOrderByField = 'createdAt' | 'status';\nexport type ExperimentResultOrderByField = 'startedAt' | 'createdAt';\n\nexport interface ListOrderBy<TField extends string> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ListDatasetsInput {\n pagination: StoragePagination;\n filters?: ListDatasetsFilters;\n /** Sort order. Defaults to `createdAt DESC`. Ties are broken by `id ASC`. */\n orderBy?: ListOrderBy<DatasetOrderByField>;\n}\n\nexport interface ListDatasetsOutput {\n datasets: DatasetRecord[];\n pagination: PaginationInfo;\n}\n\nexport interface ListDatasetItemsInput {\n datasetId: string;\n version?: number;\n search?: string;\n pagination: StoragePagination;\n filters?: DatasetTenancyFilters;\n /** Sort order. Defaults to `createdAt DESC`. Ties are broken by `id ASC`. */\n orderBy?: ListOrderBy<DatasetItemOrderByField>;\n}\n\nexport interface ListDatasetItemsOutput {\n items: DatasetItem[];\n pagination: PaginationInfo;\n}\n\nexport interface ListDatasetVersionsInput {\n datasetId: string;\n pagination: StoragePagination;\n}\n\nexport interface ListDatasetVersionsOutput {\n versions: DatasetVersion[];\n pagination: PaginationInfo;\n}\n\nexport interface BatchInsertItemsInput {\n datasetId: string;\n items: DatasetItemPayload[];\n /** Tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}. */\n filters?: DatasetTenancyFilters;\n}\n\nexport interface BatchDeleteItemsInput {\n datasetId: string;\n itemIds: string[];\n /** Tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}. */\n filters?: DatasetTenancyFilters;\n}\n\n// ============================================\n// Experiment Types (Dataset Experiments)\n// ============================================\n\nexport type ExperimentStatus = 'pending' | 'running' | 'completed' | 'failed';\n\n/**\n * Caller-provided information describing the source of an experiment execution.\n *\n * A typical mapping is source system, source-owned identifier, and revision. For\n * example, `source: 'github'`, `sourceId: 'mastra-ai/mastra'`, and\n * `sourceVersion: '<commit-sha>'`. These values are persisted as unverified\n * caller claims; use {@link ExperimentRunnerAttestation} for trusted\n * runner-generated execution identity.\n *\n * Provenance is assigned when an experiment is created and cannot be changed\n * through the experiment update contract.\n */\nexport interface ExperimentProvenance {\n /** Source system or source kind, such as `github`, `ci`, or `local`. */\n source?: string;\n /** Stable identifier owned by the source, such as a repository or benchmark definition. */\n sourceId?: string;\n /** Revision of the source, such as a commit SHA, release version, or configuration digest. */\n sourceVersion?: string;\n /** Additional caller-defined source context. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Caller-defined dimensions used to group related experiment executions.\n *\n * For a study comparing baseline and candidate variants across repeated trials:\n * - `experimentSetId` identifies the overall study and is shared by every related run.\n * - `comparisonId` identifies one controlled comparison within the study and is\n * shared by all variants and trials in that comparison.\n * - `variantId` identifies an alternative within the comparison, such as\n * `baseline` or `candidate`.\n * - `trialIndex` is the zero-based repetition index for that variant.\n *\n * The natural caller-defined identity is\n * `(experimentSetId, comparisonId, variantId, trialIndex)`. Mastra does not\n * enforce uniqueness or require every dimension, so callers own identifier scope\n * and consistency. Grouping is assigned when an experiment is created and cannot\n * be changed through the experiment update contract.\n *\n * @example\n * ```ts\n * const sharedGrouping = {\n * experimentSetId: 'support-agent-benchmark',\n * comparisonId: 'prompt-v1-vs-v2',\n * };\n *\n * const runs = [\n * { ...sharedGrouping, variantId: 'baseline', trialIndex: 0 },\n * { ...sharedGrouping, variantId: 'baseline', trialIndex: 1 },\n * { ...sharedGrouping, variantId: 'candidate', trialIndex: 0 },\n * { ...sharedGrouping, variantId: 'candidate', trialIndex: 1 },\n * ];\n * ```\n */\nexport interface ExperimentGrouping {\n /** Overall study or benchmark campaign identifier. */\n experimentSetId?: string;\n /** Controlled comparison identifier within the experiment set. */\n comparisonId?: string;\n /** Alternative identifier within the comparison. */\n variantId?: string;\n /** Zero-based repetition index for the variant. */\n trialIndex?: number;\n}\n\n/** Trusted runner-generated execution identity. Not accepted by caller-facing run APIs. */\nexport interface ExperimentRunnerAttestation {\n runnerId: string;\n invocationId: string;\n runnerVersion?: string;\n}\n\nexport interface Experiment {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n provenance?: ExperimentProvenance | null;\n runnerAttestation?: ExperimentRunnerAttestation | null;\n experimentSetId?: string | null;\n comparisonId?: string | null;\n variantId?: string | null;\n trialIndex?: number | null;\n datasetId: string | null;\n datasetVersion: number | null;\n /**\n * The kind of executor this experiment runs against (agent / workflow / scorer / processor).\n *\n * `null` for caller-driven ingestion experiments: the caller executes items\n * itself and submits results, so there is no registered target to resolve.\n * Runner-owned and item-run experiments always carry a non-null target.\n */\n targetType: TargetType | null;\n targetId: string | null;\n /**\n * Run-level scorer IDs pinned at create time for caller-driven experiments.\n * Acts as the highest-priority scorer source when Mastra executes items\n * (`runExperimentItem`), mirroring the runner's `scorers` option. `null`\n * falls through to item-level then dataset-level scorer IDs.\n */\n scorerIds?: string[] | null;\n status: ExperimentStatus;\n totalItems: number;\n succeededCount: number;\n failedCount: number;\n skippedCount: number;\n agentVersion?: string | null;\n /** Multi-tenant organization/account scope. Hydrated from the parent dataset on create. */\n organizationId?: string | null;\n /** Platform project scope. Pairs with {@link Experiment.organizationId} to form the experiment's tenancy bucket. */\n projectId?: string | null;\n startedAt: Date | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type ExperimentResultStatus = 'needs-review' | 'reviewed' | 'complete';\n\nexport interface ExperimentResult {\n id: string;\n experimentId: string;\n itemId: string;\n itemDatasetVersion: number | null;\n input: unknown;\n output: unknown | null;\n groundTruth: unknown | null;\n metadata: Record<string, unknown> | null;\n error: { message: string; stack?: string; code?: string } | null;\n startedAt: Date;\n completedAt: Date;\n retryCount: number;\n /**\n * Zero-based repetition index for this item within the experiment. Part of\n * the natural result identity `(experimentId, itemId, attempt)` used by\n * {@link ExperimentsStorage.upsertExperimentResult} so external runners can\n * retry submissions safely (retries converge on one row) while repeated\n * trials use distinct attempt values on purpose.\n */\n attempt: number;\n traceId: string | null;\n status: ExperimentResultStatus | null;\n tags: string[] | null;\n comment?: string | null;\n toolMockReport?: DatasetToolMockReport | null;\n /** Multi-tenant organization/account scope. Denormalized from the parent experiment for efficient tenancy-scoped queries. */\n organizationId?: string | null;\n /** Platform project scope. Pairs with {@link ExperimentResult.organizationId} to form the result's tenancy bucket. */\n projectId?: string | null;\n createdAt: Date;\n}\n\nexport interface UpdateExperimentResultInput {\n id: string;\n /** When provided, the update will only succeed if the result belongs to this experiment */\n experimentId?: string;\n status?: ExperimentResultStatus | null;\n tags?: string[] | null;\n comment?: string | null;\n}\n\nexport interface CreateExperimentInput {\n id?: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n provenance?: ExperimentProvenance;\n runnerAttestation?: ExperimentRunnerAttestation;\n experimentSetId?: string;\n comparisonId?: string;\n variantId?: string;\n trialIndex?: number;\n datasetId: string | null;\n datasetVersion: number | null;\n agentVersion?: string;\n /**\n * Discriminator for the target this experiment runs against. `null` for\n * caller-driven ingestion experiments where the caller owns execution and\n * submits results; non-null whenever Mastra executes items (runner loop or\n * per-item `runExperimentItem`).\n */\n targetType: TargetType | null;\n targetId: string | null;\n /** Run-level scorer IDs pinned at create time. See {@link Experiment.scorerIds}. */\n scorerIds?: string[] | null;\n totalItems: number;\n /**\n * Multi-tenant organization/account scope. Should be hydrated from the parent\n * dataset on create so experiments inherit their dataset's tenancy bucket.\n */\n organizationId?: string | null;\n /**\n * Platform project scope. Pairs with {@link CreateExperimentInput.organizationId}\n * to form the (organizationId, projectId) tenancy bucket. Hydrated from the\n * parent dataset on create.\n */\n projectId?: string | null;\n}\n\nexport interface UpdateExperimentInput {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n status?: ExperimentStatus;\n totalItems?: number;\n succeededCount?: number;\n failedCount?: number;\n skippedCount?: number;\n startedAt?: Date;\n completedAt?: Date;\n}\n\nexport interface AddExperimentResultInput {\n id?: string;\n experimentId: string;\n itemId: string;\n itemDatasetVersion: number | null;\n input: unknown;\n output: unknown | null;\n groundTruth: unknown | null;\n metadata?: Record<string, unknown> | null;\n error: { message: string; stack?: string; code?: string } | null;\n startedAt: Date;\n completedAt: Date;\n retryCount: number;\n /**\n * Zero-based repetition index. Defaults to `0`. See\n * {@link ExperimentResult.attempt} for the identity contract.\n */\n attempt?: number;\n traceId?: string | null;\n status?: ExperimentResultStatus | null;\n tags?: string[] | null;\n /**\n * Tool mock diagnostics for this item run. `null`/`undefined` both mean \"no\n * report\" (the item ran without tool mocks). A present report means the item\n * ran with mocks — see `served`/`unconsumed`/`liveCalls`/`failure`.\n */\n toolMockReport?: DatasetToolMockReport | null;\n /** Multi-tenant organization/account scope. Should be hydrated from the parent experiment on insert. */\n organizationId?: string | null;\n /** Platform project scope. Hydrated from the parent experiment on insert. */\n projectId?: string | null;\n}\n\n/**\n * Input for {@link ExperimentsStorage.upsertExperimentResult}. Identical to\n * {@link AddExperimentResultInput} minus the caller-supplied `id`: the row is\n * identified by the natural key `(experimentId, itemId, attempt)` instead.\n * Submitting the same key twice converges on a single row (last write wins),\n * which makes retried external submissions idempotent.\n */\nexport type UpsertExperimentResultInput = Omit<AddExperimentResultInput, 'id'>;\n\n/**\n * Multi-tenant scoping filters for experiment queries. Mirrors\n * {@link DatasetTenancyFilters} so the experiments domain can be queried\n * within a tenancy bucket using the same shape.\n */\nexport interface ExperimentTenancyFilters {\n organizationId?: string;\n projectId?: string;\n}\n\n/**\n * Multi-tenant scoping filters for score queries. Mirrors\n * {@link DatasetTenancyFilters} so the scores domain can be queried\n * within a tenancy bucket using the same shape.\n */\nexport interface ScoreTenancyFilters {\n organizationId?: string;\n projectId?: string;\n}\n\nexport interface ListScoresByScorerIdInput {\n scorerId: string;\n pagination: StoragePagination;\n entityId?: string;\n entityType?: string;\n source?: ScoringSource;\n filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresByRunIdInput {\n runId: string;\n pagination: StoragePagination;\n filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresByEntityIdInput {\n entityId: string;\n entityType: string;\n pagination: StoragePagination;\n filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresBySpanInput {\n traceId: string;\n spanId: string;\n pagination: StoragePagination;\n filters?: ScoreTenancyFilters;\n}\n\nexport interface ListExperimentsInput {\n datasetId?: string;\n targetType?: TargetType;\n targetId?: string;\n agentVersion?: string;\n status?: ExperimentStatus;\n experimentSetId?: string;\n comparisonId?: string;\n variantId?: string;\n trialIndex?: number;\n /** Multi-tenant scoping filters. See {@link ExperimentTenancyFilters}. */\n filters?: ExperimentTenancyFilters;\n pagination: StoragePagination;\n /** Sort order. Defaults to `createdAt DESC`. Ties are broken by `id ASC`. */\n orderBy?: ListOrderBy<ExperimentOrderByField>;\n}\n\nexport interface ListExperimentsOutput {\n experiments: Experiment[];\n pagination: PaginationInfo;\n}\n\nexport interface ListExperimentResultsInput {\n experimentId: string;\n traceId?: string;\n status?: ExperimentResultStatus;\n /** Return only results that have *all* of these tags. Empty/undefined disables the filter. */\n tags?: string[];\n /** Multi-tenant scoping filters. See {@link ExperimentTenancyFilters}. */\n filters?: ExperimentTenancyFilters;\n pagination: StoragePagination;\n /** Sort order. Defaults to `startedAt ASC` (execution order). Ties are broken by `id ASC`. */\n orderBy?: ListOrderBy<ExperimentResultOrderByField>;\n}\n\nexport interface ListExperimentResultsOutput {\n results: ExperimentResult[];\n pagination: PaginationInfo;\n}\n\nexport interface ExperimentReviewCounts {\n experimentId: string;\n total: number;\n needsReview: number;\n reviewed: number;\n complete: number;\n}\n\n// ============================================\n// Favorites Storage Types\n// ============================================\n\n/**\n * Entity types that can be favorited.\n * Currently agents and skills; extend here when other entities opt in.\n */\nexport type StorageFavoriteEntityType = 'agent' | 'skill';\n\nexport const STORAGE_FAVORITE_ENTITY_TYPES = ['agent', 'skill'] as const satisfies readonly StorageFavoriteEntityType[];\n\n/**\n * A single favorite row: one user favoriting one entity. Composite primary key is\n * `(userId, entityType, entityId)`. Idempotent — re-favoriting is a no-op.\n */\nexport interface StorageFavoriteType {\n /** Caller identifier (matches authorId conventions used elsewhere). */\n userId: string;\n /** Type of entity being favorited. */\n entityType: StorageFavoriteEntityType;\n /** ID of the entity being favorited. */\n entityId: string;\n /** Timestamp the favorite was created. */\n createdAt: Date;\n}\n\n/** Identifier for a favorite row, used by lookup and delete operations. */\nexport type StorageFavoriteKey = {\n userId: string;\n entityType: StorageFavoriteEntityType;\n entityId: string;\n};\n\n/**\n * Input to look up which entities in a candidate set are favorited by a given\n * user. Used to annotate list responses without N+1 queries.\n */\nexport type StorageIsFavoritedBatchInput = {\n userId: string;\n entityType: StorageFavoriteEntityType;\n entityIds: string[];\n};\n\n/** Input to list all entity IDs favorited by a given user, optionally scoped by entity type. */\nexport type StorageListFavoritesInput = {\n userId: string;\n entityType: StorageFavoriteEntityType;\n};\n\n/**\n * Input to remove all favorites for a given entity. Called by hard-delete handlers\n * so favorite rows do not orphan the deleted entity.\n */\nexport type StorageDeleteFavoritesForEntityInput = {\n entityType: StorageFavoriteEntityType;\n entityId: string;\n};\n\n/** Identity bucketing for a persisted tool provider connection row. */\nexport type StorageToolProviderConnectionScope = 'shared' | 'per-author' | 'caller-supplied';\n\n/**\n * A persisted tool provider connection row. Stores a per-author, provider-agnostic\n * label so the UI can surface a stable name (e.g. \"Work Gmail\") for the same\n * `connectionId` across agents. Unique on `(authorId, providerId, connectionId)`.\n */\nexport interface StorageToolProviderConnection {\n /**\n * Author/owner the connection belongs to. `'default'` when auth is disabled.\n * Set to the shared bucket id when `scope === 'shared'`. When\n * `scope === 'caller-supplied'`, this is a host-app end-user identifier\n * forwarded via request context.\n */\n authorId: string;\n /** Tool provider id, e.g. `'composio'`. */\n providerId: string;\n /** Toolkit slug, e.g. `'gmail'`. */\n toolkit: string;\n /** Adapter-native connection identifier (e.g. Composio `ca_...`). */\n connectionId: string;\n /** User-supplied display label. `null` when the user hasn't named it yet. */\n label: string | null;\n /**\n * Identity bucketing. `'per-author'` is the default; `'shared'` makes the\n * row visible to all callers regardless of resolved authorId; `'caller-supplied'`\n * means `authorId` is a host-app end-user identifier forwarded via request context.\n */\n scope: StorageToolProviderConnectionScope;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Input to upsert a tool provider connection row. Idempotent on `(authorId, providerId, connectionId)`. */\nexport type StorageUpsertToolProviderConnectionInput = {\n authorId: string;\n providerId: string;\n toolkit: string;\n connectionId: string;\n label: string | null;\n /** Defaults to `'per-author'` when omitted. */\n scope?: StorageToolProviderConnectionScope;\n};\n\n/** Lookup key for a single tool provider connection row. */\nexport type StorageToolProviderConnectionKey = {\n authorId: string;\n providerId: string;\n connectionId: string;\n};\n\n/** Input for listing tool provider connections, optionally scoped by author/provider/toolkit. */\nexport type StorageListToolProviderConnectionsInput = {\n /** Omit to list across all authors (admin cross-author listing). */\n authorId?: string;\n providerId?: string;\n toolkit?: string;\n /** Optional scope filter. Omit to list rows of any scope. */\n scope?: StorageToolProviderConnectionScope;\n};\n\n/** Input for deleting a single tool provider connection row. */\nexport type StorageDeleteToolProviderConnectionInput = {\n authorId: string;\n providerId: string;\n connectionId: string;\n};\n","import { OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS } from '@internal/core/memory';\nimport { spanRecordSchema } from './domains/observability';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn, StorageTableConfig } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\nexport const TABLE_PROMPT_BLOCKS = 'mastra_prompt_blocks';\nexport const TABLE_PROMPT_BLOCK_VERSIONS = 'mastra_prompt_block_versions';\nexport const TABLE_SCORER_DEFINITIONS = 'mastra_scorer_definitions';\nexport const TABLE_SCORER_DEFINITION_VERSIONS = 'mastra_scorer_definition_versions';\nexport const TABLE_MCP_CLIENTS = 'mastra_mcp_clients';\nexport const TABLE_MCP_CLIENT_VERSIONS = 'mastra_mcp_client_versions';\nexport const TABLE_MCP_SERVERS = 'mastra_mcp_servers';\nexport const TABLE_MCP_SERVER_VERSIONS = 'mastra_mcp_server_versions';\nexport const TABLE_WORKSPACES = 'mastra_workspaces';\nexport const TABLE_WORKSPACE_VERSIONS = 'mastra_workspace_versions';\nexport const TABLE_SKILLS = 'mastra_skills';\nexport const TABLE_SKILL_VERSIONS = 'mastra_skill_versions';\nexport const TABLE_SKILL_BLOBS = 'mastra_skill_blobs';\nexport const TABLE_FAVORITES = 'mastra_favorites';\n\n// Dataset tables\nexport const TABLE_DATASETS = 'mastra_datasets';\nexport const TABLE_DATASET_ITEMS = 'mastra_dataset_items';\nexport const TABLE_DATASET_VERSIONS = 'mastra_dataset_versions';\n\n// Experiment tables\nexport const TABLE_EXPERIMENTS = 'mastra_experiments';\nexport const TABLE_EXPERIMENT_RESULTS = 'mastra_experiment_results';\nexport const TABLE_BACKGROUND_TASKS = 'mastra_background_tasks';\n\n// Schedules tables\nexport const TABLE_SCHEDULES = 'mastra_schedules';\nexport const TABLE_SCHEDULE_TRIGGERS = 'mastra_schedule_triggers';\n\n// Static workflow definitions (chat-built / studio-saved workflows)\nexport const TABLE_WORKFLOW_DEFINITIONS = 'mastra_workflow_definitions';\n\n// Channel tables\nexport const TABLE_CHANNEL_INSTALLATIONS = 'mastra_channel_installations';\nexport const TABLE_CHANNEL_CONFIG = 'mastra_channel_config';\n\n// Tool provider connections\nexport const TABLE_TOOL_PROVIDER_CONNECTIONS = 'mastra_tool_provider_connections';\n\n// Notifications\nexport const TABLE_NOTIFICATIONS = 'mastra_notifications';\n\n// Harness sessions\nexport const TABLE_HARNESS_SESSIONS = 'mastra_harness_sessions';\n\n// Thread state (per-thread, per-type durable state; e.g. the task list)\nexport const TABLE_THREAD_STATE = 'mastra_thread_state';\n\n// Knowledge store tables\nexport const TABLE_KNOWLEDGE_NODES = 'mastra_knowledge_nodes';\nexport const TABLE_KNOWLEDGE_RECORDS = 'mastra_knowledge_records';\nexport const TABLE_KNOWLEDGE_MENTIONS = 'mastra_knowledge_mentions';\n/**\n * @deprecated Curation cursors were removed and Knowledge no longer creates this table. Kept so adapters built\n * against earlier Core versions still resolve the export.\n */\nexport const TABLE_KNOWLEDGE_CURSORS = 'mastra_knowledge_cursors';\nexport const TABLE_KNOWLEDGE_ACTIVITY = 'mastra_knowledge_activity';\nexport const TABLE_KNOWLEDGE_SEMANTIC_OUTBOX = 'mastra_knowledge_semantic_outbox';\nexport const TABLE_KNOWLEDGE_NODE_SCOPES = 'mastra_knowledge_node_scopes';\nexport const TABLE_KNOWLEDGE_RECORD_SCOPES = 'mastra_knowledge_record_scopes';\nexport const TABLE_KNOWLEDGE_SCOPE_GRANTS = 'mastra_knowledge_scope_grants';\nexport const TABLE_KNOWLEDGE_ACCESS_STATE = 'mastra_knowledge_access_state';\nexport const TABLE_KNOWLEDGE_SCOPE_ADDRESSES = 'mastra_knowledge_scope_addresses';\nexport const TABLE_KNOWLEDGE_NODE_ADDRESSES = 'mastra_knowledge_node_addresses';\nexport const TABLE_KNOWLEDGE_IMPORT_STATE = 'mastra_knowledge_import_state';\nexport const TABLE_KNOWLEDGE_IMPORT_RUNS = 'mastra_knowledge_import_runs';\nexport const TABLE_KNOWLEDGE_PROPOSALS = 'mastra_knowledge_proposals';\n\n/** Physical tables owned by one Knowledge domain. Explicit reset may target only this list. */\nexport const KNOWLEDGE_TABLE_NAMES = [\n TABLE_KNOWLEDGE_NODES,\n TABLE_KNOWLEDGE_RECORDS,\n TABLE_KNOWLEDGE_MENTIONS,\n TABLE_KNOWLEDGE_ACTIVITY,\n TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,\n TABLE_KNOWLEDGE_NODE_SCOPES,\n TABLE_KNOWLEDGE_RECORD_SCOPES,\n TABLE_KNOWLEDGE_SCOPE_GRANTS,\n TABLE_KNOWLEDGE_ACCESS_STATE,\n TABLE_KNOWLEDGE_SCOPE_ADDRESSES,\n TABLE_KNOWLEDGE_NODE_ADDRESSES,\n TABLE_KNOWLEDGE_IMPORT_STATE,\n TABLE_KNOWLEDGE_IMPORT_RUNS,\n TABLE_KNOWLEDGE_PROPOSALS,\n] as const;\nexport type KNOWLEDGE_TABLE_NAME = (typeof KNOWLEDGE_TABLE_NAMES)[number];\n\n/** Union of all core table name constants. */\nexport type TABLE_NAMES =\n | typeof TABLE_WORKFLOW_SNAPSHOT\n | typeof TABLE_MESSAGES\n | typeof TABLE_THREADS\n | typeof TABLE_TRACES\n | typeof TABLE_RESOURCES\n | typeof TABLE_SCORERS\n | typeof TABLE_SPANS\n | typeof TABLE_AGENTS\n | typeof TABLE_AGENT_VERSIONS\n | typeof TABLE_PROMPT_BLOCKS\n | typeof TABLE_PROMPT_BLOCK_VERSIONS\n | typeof TABLE_SCORER_DEFINITIONS\n | typeof TABLE_SCORER_DEFINITION_VERSIONS\n | typeof TABLE_MCP_CLIENTS\n | typeof TABLE_MCP_CLIENT_VERSIONS\n | typeof TABLE_MCP_SERVERS\n | typeof TABLE_MCP_SERVER_VERSIONS\n | typeof TABLE_WORKSPACES\n | typeof TABLE_WORKSPACE_VERSIONS\n | typeof TABLE_SKILLS\n | typeof TABLE_SKILL_VERSIONS\n | typeof TABLE_SKILL_BLOBS\n | typeof TABLE_DATASETS\n | typeof TABLE_DATASET_ITEMS\n | typeof TABLE_DATASET_VERSIONS\n | typeof TABLE_EXPERIMENTS\n | typeof TABLE_EXPERIMENT_RESULTS\n | typeof TABLE_BACKGROUND_TASKS\n | typeof TABLE_FAVORITES\n | typeof TABLE_SCHEDULES\n | typeof TABLE_SCHEDULE_TRIGGERS\n | typeof TABLE_CHANNEL_INSTALLATIONS\n | typeof TABLE_CHANNEL_CONFIG\n | typeof TABLE_TOOL_PROVIDER_CONNECTIONS\n | typeof TABLE_NOTIFICATIONS\n | typeof TABLE_HARNESS_SESSIONS\n | typeof TABLE_THREAD_STATE\n | typeof TABLE_WORKFLOW_DEFINITIONS\n | typeof TABLE_KNOWLEDGE_NODES\n | typeof TABLE_KNOWLEDGE_RECORDS\n | typeof TABLE_KNOWLEDGE_MENTIONS\n | typeof TABLE_KNOWLEDGE_ACTIVITY\n | typeof TABLE_KNOWLEDGE_SEMANTIC_OUTBOX;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerId: { type: 'text' },\n traceId: { type: 'text', nullable: true },\n spanId: { type: 'text', nullable: true },\n runId: { type: 'text' },\n scorer: { type: 'jsonb' },\n preprocessStepResult: { type: 'jsonb', nullable: true },\n extractStepResult: { type: 'jsonb', nullable: true },\n analyzeStepResult: { type: 'jsonb', nullable: true },\n score: { type: 'float' },\n reason: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n preprocessPrompt: { type: 'text', nullable: true },\n extractPrompt: { type: 'text', nullable: true },\n generateScorePrompt: { type: 'text', nullable: true },\n generateReasonPrompt: { type: 'text', nullable: true },\n analyzePrompt: { type: 'text', nullable: true },\n\n // Deprecated\n reasonPrompt: { type: 'text', nullable: true },\n input: { type: 'jsonb' },\n output: { type: 'jsonb' }, // MESSAGE OUTPUT\n additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n /**\n * Things you can evaluate\n */\n entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entityId: { type: 'text', nullable: true },\n source: { type: 'text' },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n // Batch handle: groups all per-trace scores produced by one batch scoring call.\n // Each score keeps its own per-execution `runId`; `batchId` is shared across the batch.\n batchId: { type: 'text', nullable: true },\n // Dataset provenance: which curated dataset item this score was produced against.\n // Lets baseline scores join back to dataset items (ground truth) without re-running.\n datasetId: { type: 'text', nullable: true },\n datasetItemId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp' },\n updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n // Composite primary key of traceId and spanId\n traceId: { type: 'text', nullable: false },\n spanId: { type: 'text', nullable: false },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n attributes: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n input: { type: 'jsonb', nullable: true },\n output: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false }, // When the span started\n endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft' or 'published'\n activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n visibility: { type: 'text', nullable: true }, // 'private' | 'public' | null (legacy)\n metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n favoriteCount: { type: 'integer', nullable: true }, // Denormalised count of favorites for this agent\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n agentId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n // Agent config fields\n name: { type: 'text', nullable: false }, // Agent display name\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: false },\n model: { type: 'jsonb', nullable: false },\n modelList: { type: 'jsonb', nullable: true },\n tools: { type: 'jsonb', nullable: true },\n defaultOptions: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n integrationTools: { type: 'jsonb', nullable: true },\n toolProviders: { type: 'jsonb', nullable: true },\n inputProcessors: { type: 'jsonb', nullable: true },\n outputProcessors: { type: 'jsonb', nullable: true },\n memory: { type: 'jsonb', nullable: true },\n scorers: { type: 'jsonb', nullable: true },\n mcpClients: { type: 'jsonb', nullable: true },\n requestContextSchema: { type: 'jsonb', nullable: true },\n workspace: { type: 'jsonb', nullable: true },\n skills: { type: 'jsonb', nullable: true },\n skillsFormat: { type: 'text', nullable: true },\n durable: { type: 'jsonb', nullable: true },\n browser: { type: 'jsonb', nullable: true },\n // Version metadata\n changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCKS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to prompt_block_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCK_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n blockId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n content: { type: 'text', nullable: false },\n rules: { type: 'jsonb', nullable: true },\n requestContextSchema: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to scorer_definition_versions.id\n authorId: { type: 'text', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITION_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerDefinitionId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n type: { type: 'text', nullable: false }, // 'llm-judge', 'bias', 'toxicity', etc.\n model: { type: 'jsonb', nullable: true },\n instructions: { type: 'text', nullable: true },\n scoreRange: { type: 'jsonb', nullable: true },\n presetConfig: { type: 'jsonb', nullable: true },\n defaultSampling: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_CLIENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to mcp_client_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_CLIENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n mcpClientId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n servers: { type: 'jsonb', nullable: false },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_SERVERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to mcp_server_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_SERVER_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n mcpServerId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n version: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: true },\n repository: { type: 'jsonb', nullable: true },\n releaseDate: { type: 'text', nullable: true },\n isLatest: { type: 'boolean', nullable: true },\n packageCanonical: { type: 'text', nullable: true },\n tools: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const WORKFLOW_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n description: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n inputSchema: { type: 'jsonb', nullable: false },\n outputSchema: { type: 'jsonb', nullable: false },\n stateSchema: { type: 'jsonb', nullable: true },\n requestContextSchema: { type: 'jsonb', nullable: true },\n graph: { type: 'jsonb', nullable: false },\n schedule: { type: 'jsonb', nullable: true },\n status: { type: 'text', nullable: false }, // 'active' | 'archived'\n source: { type: 'text', nullable: false }, // always 'storage' for now\n authorId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const WORKSPACES_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to workspace_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const WORKSPACE_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n workspaceId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n filesystem: { type: 'jsonb', nullable: true },\n sandbox: { type: 'jsonb', nullable: true },\n mounts: { type: 'jsonb', nullable: true },\n search: { type: 'jsonb', nullable: true },\n skills: { type: 'jsonb', nullable: true },\n tools: { type: 'jsonb', nullable: true },\n autoSync: { type: 'boolean', nullable: true },\n operationTimeout: { type: 'integer', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILLS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to skill_versions.id\n authorId: { type: 'text', nullable: true },\n visibility: { type: 'text', nullable: true }, // 'private' | 'public' | null (legacy)\n favoriteCount: { type: 'integer', nullable: true }, // Denormalised count of favorites for this skill\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const FAVORITES_SCHEMA: Record<string, StorageColumn> = {\n userId: { type: 'text', nullable: false },\n entityType: { type: 'text', nullable: false }, // 'agent' | 'skill'\n entityId: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Per-author registry of authorized tool provider connections. Stores a stable\n * user-supplied label across agents. Composite primary key on\n * (authorId, providerId, connectionId). `scope` buckets identity:\n * 'per-author' (default), 'shared' (visible to all callers), or\n * 'caller-supplied' (authorId is a host-app end-user id forwarded via request\n * context).\n */\nexport const TOOL_PROVIDER_CONNECTIONS_SCHEMA: Record<string, StorageColumn> = {\n authorId: { type: 'text', nullable: false },\n providerId: { type: 'text', nullable: false },\n connectionId: { type: 'text', nullable: false },\n toolkit: { type: 'text', nullable: false },\n label: { type: 'text', nullable: true },\n scope: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const NOTIFICATIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false },\n threadId: { type: 'text', nullable: false },\n source: { type: 'text', nullable: false },\n kind: { type: 'text', nullable: false },\n priority: { type: 'text', nullable: false },\n status: { type: 'text', nullable: false },\n summary: { type: 'text', nullable: false },\n payload: { type: 'jsonb', nullable: true },\n resourceId: { type: 'text', nullable: true },\n agentId: { type: 'text', nullable: true },\n sourceId: { type: 'text', nullable: true },\n dedupeKey: { type: 'text', nullable: true },\n coalesceKey: { type: 'text', nullable: true },\n coalescedCount: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n deliveredAt: { type: 'timestamp', nullable: true },\n seenAt: { type: 'timestamp', nullable: true },\n dismissedAt: { type: 'timestamp', nullable: true },\n archivedAt: { type: 'timestamp', nullable: true },\n discardedAt: { type: 'timestamp', nullable: true },\n deliverAt: { type: 'timestamp', nullable: true },\n summaryAt: { type: 'timestamp', nullable: true },\n deliveryReason: { type: 'text', nullable: true },\n deliveryAttempts: { type: 'integer', nullable: false },\n lastDeliveryAttemptAt: { type: 'timestamp', nullable: true },\n lastDeliveryError: { type: 'text', nullable: true },\n deliveredSignalId: { type: 'text', nullable: true },\n summarySignalId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n};\n\nexport const HARNESS_SESSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n ownerId: { type: 'text', nullable: false },\n resourceId: { type: 'text', nullable: false },\n threadId: { type: 'text', nullable: false },\n parentSessionId: { type: 'text', nullable: true },\n subagentDepth: { type: 'integer', nullable: true },\n source: { type: 'jsonb', nullable: true },\n origin: { type: 'text', nullable: false },\n runtimeCompatibilityGeneration: { type: 'text', nullable: true },\n modeId: { type: 'text', nullable: false },\n modelId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n state: { type: 'jsonb', nullable: true },\n pending: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n lastActivityAt: { type: 'timestamp', nullable: false },\n closingAt: { type: 'timestamp', nullable: true },\n closeDeadlineAt: { type: 'timestamp', nullable: true },\n closedAt: { type: 'timestamp', nullable: true },\n deletedAt: { type: 'timestamp', nullable: true },\n};\n\nexport const THREAD_STATE_SCHEMA: Record<string, StorageColumn> = {\n threadId: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n value: { type: 'jsonb', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILL_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n skillId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: false },\n instructions: { type: 'text', nullable: false },\n license: { type: 'text', nullable: true },\n compatibility: { type: 'jsonb', nullable: true },\n source: { type: 'jsonb', nullable: true },\n references: { type: 'jsonb', nullable: true },\n scripts: { type: 'jsonb', nullable: true },\n assets: { type: 'jsonb', nullable: true },\n files: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n tree: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILL_BLOBS_SCHEMA: Record<string, StorageColumn> = {\n hash: { type: 'text', nullable: false, primaryKey: true },\n content: { type: 'text', nullable: false },\n size: { type: 'integer', nullable: false },\n mimeType: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n config: { type: 'text', nullable: false }, // JSON object\n generationCount: { type: 'integer', nullable: false },\n supersededBy: OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS.supersededBy,\n lastObservedAt: { type: 'timestamp', nullable: true },\n lastReflectionAt: { type: 'timestamp', nullable: true },\n pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n isObserving: { type: 'boolean', nullable: false },\n isReflecting: { type: 'boolean', nullable: false },\n observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n // Async buffering columns\n bufferedObservations: { type: 'text', nullable: true }, // JSON string of buffered observation content\n bufferedObservationTokens: { type: 'integer', nullable: true }, // Token count of buffered observations\n bufferedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs in the buffer\n bufferedReflection: { type: 'text', nullable: true }, // JSON string of buffered reflection content\n bufferedReflectionTokens: { type: 'integer', nullable: true }, // Token count of buffered reflection (post-compression)\n bufferedReflectionInputTokens: { type: 'integer', nullable: true }, // Token count of observations fed to reflector (pre-compression)\n reflectedObservationLineCount: { type: 'integer', nullable: true }, // Number of observation lines that were reflected on during async buffering\n bufferedObservationChunks: { type: 'jsonb', nullable: true }, // JSON array of BufferedObservationChunk objects\n isBufferingObservation: { type: 'boolean', nullable: false },\n isBufferingReflection: { type: 'boolean', nullable: false },\n lastBufferedAtTokens: { type: 'integer', nullable: false },\n lastBufferedAtTime: { type: 'timestamp', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n// Dataset schemas\nexport const DATASETS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n inputSchema: { type: 'jsonb', nullable: true },\n groundTruthSchema: { type: 'jsonb', nullable: true },\n requestContextSchema: { type: 'jsonb', nullable: true },\n tags: { type: 'jsonb', nullable: true },\n targetType: { type: 'text', nullable: true },\n targetIds: { type: 'jsonb', nullable: true },\n scorerIds: { type: 'jsonb', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n candidateKey: { type: 'text', nullable: true },\n candidateId: { type: 'text', nullable: true },\n version: { type: 'integer', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const DATASET_ITEMS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false },\n datasetId: { type: 'text', nullable: false, references: { table: 'mastra_datasets', column: 'id' } },\n datasetVersion: { type: 'integer', nullable: false },\n externalId: { type: 'text', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n validTo: { type: 'integer', nullable: true },\n isDeleted: { type: 'boolean', nullable: false },\n input: { type: 'jsonb', nullable: false },\n groundTruth: { type: 'jsonb', nullable: true },\n requestContext: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n source: { type: 'jsonb', nullable: true },\n expectedTrajectory: { type: 'jsonb', nullable: true },\n toolMocks: { type: 'jsonb', nullable: true },\n unmockedToolPolicy: { type: 'text', nullable: true },\n scorerIds: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const DATASET_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n datasetId: { type: 'text', nullable: false, references: { table: 'mastra_datasets', column: 'id' } },\n version: { type: 'integer', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\n// Experiment schemas\nexport const EXPERIMENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n name: { type: 'text', nullable: true },\n description: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n provenance: { type: 'jsonb', nullable: true },\n runnerAttestation: { type: 'jsonb', nullable: true },\n experimentSetId: { type: 'text', nullable: true },\n comparisonId: { type: 'text', nullable: true },\n variantId: { type: 'text', nullable: true },\n trialIndex: { type: 'integer', nullable: true },\n datasetId: { type: 'text', nullable: true, references: { table: 'mastra_datasets', column: 'id' } },\n datasetVersion: { type: 'integer', nullable: true },\n // Nullable: caller-driven ingestion experiments have no registered target.\n targetType: { type: 'text', nullable: true },\n targetId: { type: 'text', nullable: true },\n // Run-level scorer IDs pinned at create time for caller-driven experiments.\n scorerIds: { type: 'jsonb', nullable: true },\n status: { type: 'text', nullable: false },\n totalItems: { type: 'integer', nullable: false },\n succeededCount: { type: 'integer', nullable: false },\n failedCount: { type: 'integer', nullable: false },\n skippedCount: { type: 'integer', nullable: false },\n startedAt: { type: 'timestamp', nullable: true },\n completedAt: { type: 'timestamp', nullable: true },\n agentVersion: { type: 'text', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const EXPERIMENT_RESULTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n experimentId: { type: 'text', nullable: false, references: { table: 'mastra_experiments', column: 'id' } },\n itemId: { type: 'text', nullable: false, references: { table: 'mastra_dataset_items', column: 'id' } },\n itemDatasetVersion: { type: 'integer', nullable: true },\n input: { type: 'jsonb', nullable: false },\n output: { type: 'jsonb', nullable: true },\n groundTruth: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false },\n completedAt: { type: 'timestamp', nullable: false },\n retryCount: { type: 'integer', nullable: false },\n // Nullable for backwards compatibility with pre-existing rows; readers treat NULL as 0.\n attempt: { type: 'integer', nullable: true },\n traceId: { type: 'text', nullable: true },\n status: { type: 'text', nullable: true },\n tags: { type: 'jsonb', nullable: true },\n comment: { type: 'text', nullable: true },\n toolMockReport: { type: 'jsonb', nullable: true },\n organizationId: { type: 'text', nullable: true },\n projectId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_NODES_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n type: { type: 'text', nullable: false },\n name: { type: 'text', nullable: false },\n canonicalName: { type: 'text', nullable: false },\n kind: { type: 'text', nullable: true },\n content: { type: 'text', nullable: true },\n description: { type: 'text', nullable: true },\n scope: { type: 'jsonb', nullable: false },\n scopeKey: { type: 'text', nullable: false },\n version: { type: 'integer', nullable: false },\n mergedInto: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_RECORDS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n node: { type: 'text', nullable: false },\n text: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: false },\n scopeKey: { type: 'text', nullable: false },\n sourceThreadId: { type: 'text', nullable: false },\n capturedAt: { type: 'timestamp', nullable: false },\n when: { type: 'timestamp', nullable: true },\n maxScope: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n deletedAt: { type: 'timestamp', nullable: true },\n deletedBy: { type: 'text', nullable: true },\n};\n\nexport const KNOWLEDGE_MENTIONS_SCHEMA: Record<string, StorageColumn> = {\n sourceType: { type: 'text', nullable: false },\n sourceId: { type: 'text', nullable: false },\n recordId: { type: 'text', nullable: false },\n};\n\n/**\n * @deprecated Curation cursors were removed and Knowledge no longer creates this table. Kept so adapters built\n * against earlier Core versions still resolve the export.\n */\nexport const KNOWLEDGE_CURSORS_SCHEMA: Record<string, StorageColumn> = {\n sourceThreadId: { type: 'text', nullable: false },\n agent: { type: 'text', nullable: false },\n lastKnowledgeId: { type: 'text', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_ACTIVITY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n action: { type: 'text', nullable: false },\n recordType: { type: 'text', nullable: false },\n recordId: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: false },\n scopeKey: { type: 'text', nullable: false },\n sourceThreadId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n idempotencyKey: { type: 'text', nullable: false },\n documentId: { type: 'text', nullable: false },\n documentType: { type: 'text', nullable: false },\n operation: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: false },\n scopeKey: { type: 'text', nullable: false },\n status: { type: 'text', nullable: false },\n attempts: { type: 'integer', nullable: false },\n availableAt: { type: 'timestamp', nullable: false },\n claimedAt: { type: 'timestamp', nullable: true },\n claimedBy: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n completedAt: { type: 'timestamp', nullable: true },\n};\n\n/** Normalized Knowledge v2 node schema plus nullable v1 facade columns. */\nexport const KNOWLEDGE_V2_NODES_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n name: { type: 'text', nullable: false },\n kind: { type: 'text', nullable: true },\n isScope: { type: 'boolean', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n version: { type: 'integer', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n deletedAt: { type: 'timestamp', nullable: true },\n deletedBy: { type: 'text', nullable: true },\n type: { type: 'text', nullable: true },\n canonicalName: { type: 'text', nullable: true },\n content: { type: 'text', nullable: true },\n description: { type: 'text', nullable: true },\n scope: { type: 'jsonb', nullable: true },\n scopeKey: { type: 'text', nullable: true },\n mergedInto: { type: 'text', nullable: true },\n};\n\n/** Knowledge v2 record schema. Scope rules live in `mastra_knowledge_record_scopes`. */\nexport const KNOWLEDGE_V2_RECORDS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n node: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n text: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n version: { type: 'integer', nullable: false },\n capturedAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n deletedAt: { type: 'timestamp', nullable: true },\n deletedBy: { type: 'text', nullable: true },\n scope: { type: 'jsonb', nullable: true },\n scopeKey: { type: 'text', nullable: true },\n sourceThreadId: { type: 'text', nullable: true },\n when: { type: 'timestamp', nullable: true },\n};\n\nexport const KNOWLEDGE_V2_MENTIONS_SCHEMA: Record<string, StorageColumn> = {\n recordId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_RECORDS, column: 'id' } },\n targetNodeId: { type: 'text', nullable: true, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n sourceType: { type: 'text', nullable: true },\n sourceId: { type: 'text', nullable: true },\n};\n\nexport const KNOWLEDGE_NODE_SCOPES_SCHEMA: Record<string, StorageColumn> = {\n nodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n scopeNodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n addedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_RECORD_SCOPES_SCHEMA: Record<string, StorageColumn> = {\n recordId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_RECORDS, column: 'id' } },\n scopeNodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n addedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const KNOWLEDGE_SCOPE_GRANTS_SCHEMA: Record<string, StorageColumn> = {\n scopeNodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n scopeRefId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n role: { type: 'text', nullable: false },\n canSuggest: { type: 'boolean', nullable: true },\n};\n\nexport const KNOWLEDGE_ACCESS_STATE_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n epoch: { type: 'integer', nullable: false },\n schemaVersion: { type: 'integer', nullable: false },\n};\n\nexport const KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA: Record<string, StorageColumn> = {\n address: { type: 'text', nullable: false, primaryKey: true },\n scopeNodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n};\n\nexport const KNOWLEDGE_NODE_ADDRESSES_SCHEMA: Record<string, StorageColumn> = {\n source: { type: 'text', nullable: false },\n address: { type: 'text', nullable: false },\n nodeId: { type: 'text', nullable: false, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n};\n\nexport const KNOWLEDGE_IMPORT_STATE_SCHEMA: Record<string, StorageColumn> = {\n importerId: { type: 'text', nullable: false },\n binding: { type: 'text', nullable: false },\n key: { type: 'text', nullable: false },\n value: { type: 'text', nullable: false },\n};\n\nexport const KNOWLEDGE_IMPORT_RUNS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n importerId: { type: 'text', nullable: false },\n binding: { type: 'text', nullable: false },\n importKind: { type: 'text', nullable: false },\n triggerKind: { type: 'text', nullable: false },\n status: { type: 'text', nullable: false },\n error: { type: 'text', nullable: true },\n transcriptThreadId: { type: 'text', nullable: true },\n traceId: { type: 'text', nullable: true },\n queuedAt: { type: 'timestamp', nullable: false },\n startedAt: { type: 'timestamp', nullable: true },\n completedAt: { type: 'timestamp', nullable: true },\n};\n\nexport const KNOWLEDGE_V2_ACTIVITY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n action: { type: 'text', nullable: false },\n targetType: { type: 'text', nullable: true },\n targetId: { type: 'text', nullable: true },\n contextScopeId: { type: 'text', nullable: true, references: { table: TABLE_KNOWLEDGE_NODES, column: 'id' } },\n importRunId: { type: 'text', nullable: true, references: { table: TABLE_KNOWLEDGE_IMPORT_RUNS, column: 'id' } },\n details: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n recordType: { type: 'text', nullable: true },\n recordId: { type: 'text', nullable: true },\n scope: { type: 'jsonb', nullable: true },\n scopeKey: { type: 'text', nullable: true },\n sourceThreadId: { type: 'text', nullable: true },\n};\n\nexport const KNOWLEDGE_PROPOSALS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n targetType: { type: 'text', nullable: false },\n targetId: { type: 'text', nullable: false },\n action: { type: 'text', nullable: false },\n changes: { type: 'jsonb', nullable: false },\n reason: { type: 'text', nullable: true },\n proposerContextScopeId: { type: 'text', nullable: false },\n expectedVersion: { type: 'integer', nullable: false },\n status: { type: 'text', nullable: false },\n reviewerContextScopeId: { type: 'text', nullable: true },\n reviewedAt: { type: 'timestamp', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n [TABLE_WORKFLOW_SNAPSHOT]: {\n workflow_name: {\n type: 'text',\n },\n run_id: {\n type: 'text',\n },\n resourceId: { type: 'text', nullable: true },\n snapshot: {\n type: 'jsonb',\n },\n createdAt: {\n type: 'timestamp',\n },\n updatedAt: {\n type: 'timestamp',\n },\n },\n [TABLE_SCORERS]: SCORERS_SCHEMA,\n [TABLE_THREADS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n resourceId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_MESSAGES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n thread_id: { type: 'text', nullable: false },\n content: { type: 'text', nullable: false },\n role: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n resourceId: { type: 'text', nullable: true },\n },\n [TABLE_SPANS]: SPAN_SCHEMA,\n [TABLE_TRACES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n traceId: { type: 'text', nullable: false },\n scope: { type: 'text', nullable: false },\n kind: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n status: { type: 'jsonb', nullable: true },\n events: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n other: { type: 'text', nullable: true },\n startTime: { type: 'bigint', nullable: false },\n endTime: { type: 'bigint', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_RESOURCES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n workingMemory: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_AGENTS]: AGENTS_SCHEMA,\n [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n [TABLE_PROMPT_BLOCKS]: PROMPT_BLOCKS_SCHEMA,\n [TABLE_PROMPT_BLOCK_VERSIONS]: PROMPT_BLOCK_VERSIONS_SCHEMA,\n [TABLE_SCORER_DEFINITIONS]: SCORER_DEFINITIONS_SCHEMA,\n [TABLE_SCORER_DEFINITION_VERSIONS]: SCORER_DEFINITION_VERSIONS_SCHEMA,\n [TABLE_MCP_CLIENTS]: MCP_CLIENTS_SCHEMA,\n [TABLE_MCP_CLIENT_VERSIONS]: MCP_CLIENT_VERSIONS_SCHEMA,\n [TABLE_MCP_SERVERS]: MCP_SERVERS_SCHEMA,\n [TABLE_MCP_SERVER_VERSIONS]: MCP_SERVER_VERSIONS_SCHEMA,\n [TABLE_WORKSPACES]: WORKSPACES_SCHEMA,\n [TABLE_WORKSPACE_VERSIONS]: WORKSPACE_VERSIONS_SCHEMA,\n [TABLE_SKILLS]: SKILLS_SCHEMA,\n [TABLE_SKILL_VERSIONS]: SKILL_VERSIONS_SCHEMA,\n [TABLE_SKILL_BLOBS]: SKILL_BLOBS_SCHEMA,\n [TABLE_DATASETS]: DATASETS_SCHEMA,\n [TABLE_DATASET_ITEMS]: DATASET_ITEMS_SCHEMA,\n [TABLE_DATASET_VERSIONS]: DATASET_VERSIONS_SCHEMA,\n [TABLE_EXPERIMENTS]: EXPERIMENTS_SCHEMA,\n [TABLE_EXPERIMENT_RESULTS]: EXPERIMENT_RESULTS_SCHEMA,\n [TABLE_FAVORITES]: FAVORITES_SCHEMA,\n [TABLE_BACKGROUND_TASKS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n tool_call_id: { type: 'text', nullable: false },\n tool_name: { type: 'text', nullable: false },\n agent_id: { type: 'text', nullable: false },\n run_id: { type: 'text', nullable: false },\n thread_id: { type: 'text', nullable: true },\n resource_id: { type: 'text', nullable: true },\n status: { type: 'text', nullable: false },\n args: { type: 'jsonb', nullable: false },\n result: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n suspend_payload: { type: 'jsonb', nullable: true },\n retry_count: { type: 'integer', nullable: false },\n max_retries: { type: 'integer', nullable: false },\n timeout_ms: { type: 'integer', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n startedAt: { type: 'timestamp', nullable: true },\n suspendedAt: { type: 'timestamp', nullable: true },\n completedAt: { type: 'timestamp', nullable: true },\n ownerId: { type: 'text', nullable: true },\n leaseExpiresAt: { type: 'timestamp', nullable: true },\n expiresAt: { type: 'timestamp', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n },\n [TABLE_SCHEDULES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n target: { type: 'jsonb', nullable: false },\n cron: { type: 'text', nullable: false },\n timezone: { type: 'text', nullable: true },\n status: { type: 'text', nullable: false },\n next_fire_at: { type: 'bigint', nullable: false },\n last_fire_at: { type: 'bigint', nullable: true },\n last_run_id: { type: 'text', nullable: true },\n created_at: { type: 'bigint', nullable: false },\n updated_at: { type: 'bigint', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n owner_type: { type: 'text', nullable: true },\n owner_id: { type: 'text', nullable: true },\n run_at: { type: 'bigint', nullable: true },\n end_at: { type: 'bigint', nullable: true },\n },\n [TABLE_SCHEDULE_TRIGGERS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n schedule_id: { type: 'text', nullable: false },\n run_id: { type: 'text', nullable: true },\n scheduled_fire_at: { type: 'bigint', nullable: false },\n actual_fire_at: { type: 'bigint', nullable: false },\n outcome: { type: 'text', nullable: false },\n error: { type: 'text', nullable: true },\n trigger_kind: { type: 'text', nullable: false },\n parent_trigger_id: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n },\n [TABLE_CHANNEL_INSTALLATIONS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n platform: { type: 'text', nullable: false },\n agentId: { type: 'text', nullable: false },\n status: { type: 'text', nullable: false },\n webhookId: { type: 'text', nullable: true },\n data: { type: 'jsonb', nullable: false },\n configHash: { type: 'text', nullable: true },\n error: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_CHANNEL_CONFIG]: {\n platform: { type: 'text', nullable: false, primaryKey: true },\n data: { type: 'jsonb', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_TOOL_PROVIDER_CONNECTIONS]: TOOL_PROVIDER_CONNECTIONS_SCHEMA,\n [TABLE_NOTIFICATIONS]: NOTIFICATIONS_SCHEMA,\n [TABLE_HARNESS_SESSIONS]: HARNESS_SESSIONS_SCHEMA,\n [TABLE_THREAD_STATE]: THREAD_STATE_SCHEMA,\n [TABLE_WORKFLOW_DEFINITIONS]: WORKFLOW_DEFINITIONS_SCHEMA,\n [TABLE_KNOWLEDGE_NODES]: KNOWLEDGE_NODES_SCHEMA,\n [TABLE_KNOWLEDGE_RECORDS]: KNOWLEDGE_RECORDS_SCHEMA,\n [TABLE_KNOWLEDGE_MENTIONS]: KNOWLEDGE_MENTIONS_SCHEMA,\n [TABLE_KNOWLEDGE_ACTIVITY]: KNOWLEDGE_ACTIVITY_SCHEMA,\n [TABLE_KNOWLEDGE_SEMANTIC_OUTBOX]: KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA,\n};\n\n/**\n * Table-level config for tables that need composite primary keys or other table-level settings.\n * Keyed by table name. Tables not listed here use single-column PKs from their schema.\n */\nexport const TABLE_CONFIGS: Partial<Record<TABLE_NAMES, StorageTableConfig>> = {\n [TABLE_DATASET_ITEMS]: { columns: DATASET_ITEMS_SCHEMA, compositePrimaryKey: ['id', 'datasetVersion'] },\n [TABLE_FAVORITES]: { columns: FAVORITES_SCHEMA, compositePrimaryKey: ['userId', 'entityType', 'entityId'] },\n [TABLE_TOOL_PROVIDER_CONNECTIONS]: {\n columns: TOOL_PROVIDER_CONNECTIONS_SCHEMA,\n compositePrimaryKey: ['authorId', 'providerId', 'connectionId'],\n },\n [TABLE_NOTIFICATIONS]: { columns: NOTIFICATIONS_SCHEMA, compositePrimaryKey: ['threadId', 'id'] },\n [TABLE_THREAD_STATE]: { columns: THREAD_STATE_SCHEMA, compositePrimaryKey: ['threadId', 'type'] },\n [TABLE_KNOWLEDGE_MENTIONS]: {\n columns: KNOWLEDGE_MENTIONS_SCHEMA,\n compositePrimaryKey: ['sourceType', 'sourceId', 'recordId'],\n },\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n\nexport const TABLE_WORKFLOW_RUN_OWNERS = 'mastra_workflow_run_owners';\nexport const TABLE_MEMORY_RUN_FENCES = 'mastra_memory_run_fences';\n\n/**\n * Run ownership records for workflows stores that support run fencing.\n * `leaseExpiresAt` and `updatedAt` are epoch milliseconds on the database\n * clock; `leaseExpiresAt` is null once released. `updatedAt` is refreshed by\n * every claim, renewal and release and anchors `workflows.runOwnership`\n * retention. A run's first generation is the store clock in epoch\n * milliseconds, so a run claimed again after its record was pruned still gets\n * a higher generation.\n */\nexport const WORKFLOW_RUN_OWNERS_SCHEMA: Record<string, StorageColumn> = {\n runId: { type: 'text', nullable: false, primaryKey: true },\n generation: { type: 'bigint', nullable: false },\n ownerId: { type: 'text', nullable: false },\n leaseExpiresAt: { type: 'bigint', nullable: true },\n updatedAt: { type: 'bigint', nullable: false },\n};\n\n/**\n * The claim each run's memory writes must carry, for memory stores that support run fencing.\n * `retiredAt` is epoch milliseconds on the database clock, set once the\n * execution holding the fence settles and cleared when the fence is raised\n * again. It anchors `memory.runFences` retention; NULL rows are never pruned.\n */\nexport const MEMORY_RUN_FENCES_SCHEMA: Record<string, StorageColumn> = {\n runId: { type: 'text', nullable: false, primaryKey: true },\n generation: { type: 'bigint', nullable: false },\n ownerId: { type: 'text', nullable: false },\n retiredAt: { type: 'bigint', nullable: true },\n};\n\n/**\n * Schemas for the run fencing tables.\n * Exported separately because only adapters that support run fencing create them,\n * so they are not part of TABLE_NAMES.\n */\nexport const RUN_FENCING_TABLE_SCHEMAS = {\n [TABLE_WORKFLOW_RUN_OWNERS]: WORKFLOW_RUN_OWNERS_SCHEMA,\n [TABLE_MEMORY_RUN_FENCES]: MEMORY_RUN_FENCES_SCHEMA,\n};\n\nexport const TABLE_WORKFLOW_RUNS = 'mastra_workflow_runs';\nexport const TABLE_WORKFLOW_RUN_ENTRIES = 'mastra_workflow_run_entries';\n\n/**\n * Storage v2 run headers: the run's `WorkflowRunHeader` (its `WorkflowRunState` without\n * `context` and `value`). `status` and `threadId` are copied out of the snapshot so they\n * can be filtered and indexed. `lastSeq` is the highest `seq` the run's entries have used;\n * it only increases, across checkpoints too. `startStateSeq` is the state version the run's\n * current drive started from (see `StoredWorkflowRunHeader`). `stateShared` is set once another\n * run's state builds on this run's state, so a checkpoint keeps the earlier state entries and a\n * delete knows to detach the runs built on it. `stateSeq`, `statePatchCount`, `statePatchBytes`\n * and `stateBytes` track where the run's state chain stands (see `StoredStateColumns`).\n * @experimental\n */\nexport const WORKFLOW_RUNS_SCHEMA: Record<string, StorageColumn> = {\n workflow_name: { type: 'text', nullable: false },\n run_id: { type: 'text', nullable: false },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n status: { type: 'text', nullable: false },\n header: { type: 'jsonb', nullable: false },\n lastSeq: { type: 'integer', nullable: false },\n startStateSeq: { type: 'integer', nullable: false },\n stateShared: { type: 'boolean', nullable: false },\n stateSeq: { type: 'integer', nullable: false },\n statePatchCount: { type: 'integer', nullable: false },\n statePatchBytes: { type: 'integer', nullable: false },\n stateBytes: { type: 'integer', nullable: true },\n /** Picked when the run is first stored, kept until it is deleted (see `StoredWorkflowRunHeader`). */\n runToken: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Storage v2 run entries: one step result (`kind: 'step'`) or one state entry (`kind` `state`,\n * `state-patch`, `state-base` or `state-draft`, `step_id` null; see `WorkflowRunEntry`) per row,\n * ordered by `seq` within a run.\n * @experimental\n */\nexport const WORKFLOW_RUN_ENTRIES_SCHEMA: Record<string, StorageColumn> = {\n workflow_name: { type: 'text', nullable: false },\n run_id: { type: 'text', nullable: false },\n seq: { type: 'integer', nullable: false },\n kind: { type: 'text', nullable: false },\n step_id: { type: 'text', nullable: true },\n payload: { type: 'jsonb', nullable: true },\n};\n\n/**\n * Table configs for the storage v2 run tables (`storageVersion: 2`).\n * Exported separately because only adapters that support run journals create them,\n * so they are not part of TABLE_NAMES.\n * @experimental\n */\nexport const WORKFLOW_RUN_JOURNAL_TABLE_CONFIGS = {\n [TABLE_WORKFLOW_RUNS]: { columns: WORKFLOW_RUNS_SCHEMA, compositePrimaryKey: ['workflow_name', 'run_id'] },\n [TABLE_WORKFLOW_RUN_ENTRIES]: {\n columns: WORKFLOW_RUN_ENTRIES_SCHEMA,\n compositePrimaryKey: ['workflow_name', 'run_id', 'seq'],\n },\n} satisfies Record<string, StorageTableConfig>;\n"],"mappings":";;;;;;AAmBA,MAAa,sBAAsBA,OAAAA,EAAE,KAAK,CAAC,QAAQ,MAAM,CAAC;AAI1D,MAAa,0BAA0BA,OAAAA,EAAE,KAAK;CAC5C;CACA;CACA;CACA;CAEA;CACA;CAEA;CACA,GAAG,OAAO,OAAOC,cAAAA,QAAQ;AAC3B,CAAkC;AAQlC,MAAa,uBA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