{"version":3,"sources":["../src/evals/types.ts","../src/storage/domains/observability/tracing.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","SpanType","dbTimestamps","paginationInfoSchema","TraceStatus","spanContextFields","metadataField","tagsField","traceIdField","spanIdField","dateRangeSchema","sortDirectionSchema","listModeSchema","paginationArgsSchema","deltaCursorSchema","deltaLimitSchema","refineObservabilityListMode","normalizeObservabilityListArgs","deltaInfoSchema","getZodTypeName","getZodInnerType"],"mappings":";;;;;;AAmBO,IAAM,sBAAsBA,IAAA,CAAE,IAAA,CAAK,CAAC,MAAA,EAAQ,MAAM,CAAC;AAInD,IAAM,uBAAA,GAA0BA,KAAE,IAAA,CAAK;AAAA,EAC5C,OAAA;AAAA,EACA,UAAA;AAAA,EACA,YAAA;AAAA,EACA,MAAA;AAAA,EACA,GAAG,MAAA,CAAO,MAAA,CAAOC,0BAAQ;AAC3B,CAAkC;AAQ3B,IAAM,oBAAA,GAAuBD,KAAE,MAAA,CAAO;AAAA,EAC3C,WAAA,EAAaA,KAAE,MAAA,EAAO;AAAA,EACtB,MAAA,EAAQA,KAAE,MAAA;AACZ,CAAC;AASD,IAAM,YAAA,GAAeA,KAAE,MAAA,CAAOA,IAAA,CAAE,QAAO,EAAGA,IAAA,CAAE,SAAS,CAAA;AAGrD,IAAM,oBAAA,GAAuB,aAAa,QAAA,EAAS;AAM5C,IAAM,kBAAA,GAAqBA,KAAE,MAAA,CAAO;AAAA,EACzC,KAAA,EAAOA,IAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,KAAA,EAAOA,IAAA,CAAE,OAAA,EAAQ,CAAE,QAAA,EAAS;AAAA,EAC5B,MAAA,EAAQA,KAAE,OAAA,EAAQ;AAAA,EAClB,iBAAA,EAAmB,oBAAA;AAAA,EACnB,cAAA,EAAgB;AAAA;AAAA;AAGlB,CAAC;AAQM,IAAM,sBAAA,GAAyBA,KAAE,MAAA,CAAO;AAAA,EAC7C,KAAA,EAAOA,IAAA,C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A;AAAA,EACnC,CAAC,mBAAmB,GAAG,oBAAA;AAAA,EACvB,CAAC,sBAAsB,GAAG,uBAAA;AAAA,EAC1B,CAAC,kBAAkB,GAAG;AACxB;AAMO,IAAM,aAAA,GAAkE;AAAA,EAC7E,CAAC,mBAAmB,GAAG,EAAE,OAAA,EAAS,sBAAsB,mBAAA,EAAqB,CAAC,IAAA,EAAM,gBAAgB,CAAA,EAAE;AAAA,EACtG,CAAC,eAAe,GAAG,EAAE,OAAA,EAAS,gBAAA,EAAkB,mBAAA,EAAqB,CAAC,QAAA,EAAU,YAAA,EAAc,UAAU,CAAA,EAAE;AAAA,EAC1G,CAAC,+BAA+B,GAAG;AAAA,IACjC,OAAA,EAAS,gCAAA;AAAA,IACT,mBAAA,EAAqB,CAAC,UAAA,EAAY,YAAA,EAAc,cAAc;AAAA,GAChE;AAAA,EACA,CAAC,mBAAmB,GAAG,EAAE,OAAA,EAAS,sBAAsB,mBAAA,EAAqB,CAAC,UAAA,EAAY,IAAI,CAAA,EAAE;AAAA,EAChG,CAAC,kBAAkB,GAAG,EAAE,OAAA,EAAS,qBAAqB,mBAAA,EAAqB,CAAC,UAAA,EAAY,MAAM,CAAA;AAChG;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-QYKNPGZG.cjs","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;\n\nexport const scoringEntityTypeSchema = z.enum([\n 'AGENT',\n 'WORKFLOW',\n 'TRAJECTORY',\n 'STEP',\n ...Object.values(SpanType),\n] as [string, string, ...string[]]);\n\nexport type ScoringEntityType = z.infer;\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;\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 & Partial;\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 // Note: observabilityContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer & Partial;\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer;\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;\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 = Omit<\n z.infer,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n} & Partial;\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult = Omit<\n z.infer,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n} & Partial;\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;\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\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;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer;\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;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise;\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;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record;\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;\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;\n /** Result returned by the tool */\n toolResult?: Record;\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;\n /** Result returned by the MCP tool */\n toolResult?: Record;\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 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;\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 | 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>;\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 = Pick &\n Partial> & {\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\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\n | ToExpected\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 // Prefer the legacy toolInvocations array when present; fall back to\n // V2 content.parts for messages that only store tool calls there.\n const legacy = message?.content?.toolInvocations;\n const fromParts = legacy\n ? undefined\n : message?.content?.parts\n ?.filter((p): p is Extract => p.type === 'tool-invocation')\n .map(p => p.toolInvocation);\n const toolInvocations = legacy ?? fromParts;\n if (!toolInvocations?.length) continue;\n\n for (const invocation of toolInvocations) {\n if (invocation && invocation.toolName && (invocation.state === 'result' || invocation.state === 'call')) {\n const toolArgs =\n invocation.args != null && typeof invocation.args === 'object' && !Array.isArray(invocation.args)\n ? (invocation.args as Record)\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)\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',\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>,\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)\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 | 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 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 | undefined,\n ...(childSteps.length > 0 ? { children: childSteps } : {}),\n };\n\n const attrs = (span.attributes ?? {}) as Record;\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 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 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.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` or returns undefined.\n */\nfunction toRecordOrUndefined(value: unknown): Record | undefined {\n if (value == null) return undefined;\n if (typeof value === 'object' && !Array.isArray(value)) {\n return value as Record;\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();\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","import { z } from 'zod/v4';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } 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 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 = (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;\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 // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer;\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/** 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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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();\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([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\n/**\n * Lightweight span record containing only the fields needed for timeline rendering.\n * Excludes heavy fields: input, output, attributes, metadata, tags, links.\n * This reduces per-span payload from ~17KB to ~370 bytes (~97% reduction).\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 // Entity context (needed by TraceKeysAndValues on root span)\n entityType: spanContextFields.entityType,\n entityId: spanContextFields.entityId,\n entityName: spanContextFields.entityName,\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe(\n 'Lightweight span record for timeline rendering (excludes input, output, attributes, metadata, tags, links)',\n );\n\n/** Lightweight span record for timeline rendering */\nexport type LightSpanRecord = z.infer;\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;\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>(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;\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;\n\n/** Schema for listTracesLight operation response */\nexport const listTracesLightResponseSchema = z.object({\n pagination: paginationInfoSchema,\n spans: z.array(lightSpanRecordSchema),\n});\n\n/** Response containing paginated lightweight root spans */\nexport type ListTracesLightResponse = z.infer;\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] 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 = 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>(\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;\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;\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;\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;\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;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z.array(traceIdField),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer;\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;\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;\n","import type { z } from 'zod/v4';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } 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;\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\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\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 orderBy?: StorageOrderBy<'createdAt'>;\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 status?: WorkflowRunStatus;\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;\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;\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 cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n /** The newly created cloned thread */\n thread: StorageThreadType;\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n /** Map from source message IDs to cloned message IDs (used for OM remapping) */\n messageIdMap?: Record;\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record;\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 {\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 * When `tools` is omitted, all tools from the MCP client/server are included.\n */\nexport interface StorageMCPClientToolsConfig {\n /** When omitted, all tools from the source are included. */\n tools?: Record;\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;\n connections: Record;\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/**\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,\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 {\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 | StorageConditionalVariant[];\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;\n /** Tool keys with optional per-tool config — static or conditional on request context */\n tools?: StorageConditionalField>;\n /** Default options for generate/stream calls — static or conditional on request context */\n defaultOptions?: StorageConditionalField;\n /** Workflow keys with optional per-workflow config — static or conditional on request context */\n workflows?: StorageConditionalField>;\n /** Agent keys with optional per-agent config — static or conditional on request context */\n agents?: StorageConditionalField>;\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>;\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>;\n /** Processor graph for input processing — static or conditional on request context */\n inputProcessors?: StorageConditionalField;\n /** Processor graph for output processing — static or conditional on request context */\n outputProcessors?: StorageConditionalField;\n /** Memory configuration object — static or conditional on request context */\n memory?: StorageConditionalField;\n /** Scorer keys with optional sampling config — static or conditional on request context */\n scorers?: StorageConditionalField>;\n /** Map of stored MCP client IDs to their tool configurations — static or conditional on request context */\n mcpClients?: StorageConditionalField>;\n /** Workspace reference — ID of a stored workspace or inline config — static or conditional on request context */\n workspace?: StorageConditionalField;\n /** Browser reference — inline browser config — static or conditional on request context */\n browser?: StorageConditionalField;\n /** Skill entity IDs with optional per-skill overrides — static or conditional on request context */\n skills?: StorageConditionalField>;\n /** Skill format for system message injection (default: 'xml') */\n skillsFormat?: 'xml' | 'json' | 'markdown';\n /** JSON Schema for validating request context values. Stored as JSON Schema since Zod is not serializable. */\n requestContextSchema?: Record;\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;\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;\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;\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> & {\n /** Memory configuration object (static or conditional), or null to disable memory */\n memory?: StorageConditionalField | null;\n /** Browser configuration (inline ref), or null to disable browser */\n browser?: StorageConditionalField | 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;\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, , 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 }\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;\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;\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;\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;\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;\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Block status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial;\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;\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;\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 /** Additional metadata for the scorer */\n metadata?: Record;\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 /** Additional metadata for the scorer */\n metadata?: Record;\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;\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Scorer status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial;\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 metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record;\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; // 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}\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}\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 (for pagination) */\n offset?: number;\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 // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains ... 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;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record;\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;\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\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\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\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\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\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;\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;\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;\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;\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;\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;\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;\n /** FK to mcp_client_versions.id - the currently active version */\n activeVersionId?: string;\n /** Client status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial;\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;\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;\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;\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;\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;\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;\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;\n /** FK to mcp_server_versions.id - the currently active version */\n activeVersionId?: string;\n /** Server status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial;\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;\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;\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;\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;\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;\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;\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;\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;\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;\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;\n /** FK to workspace_versions.id - the currently active version */\n activeVersionId?: string;\n /** Workspace status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial;\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;\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;\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;\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;\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, , 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;\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 or provide inline workspace config.\n */\nexport type StorageWorkspaceRef =\n | { type: 'id'; workspaceId: string }\n | { type: 'inline'; config: StorageWorkspaceSnapshotType };\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult;\n error?: SerializedError;\n suspendedPaths?: Record;\n waitingPaths?: Record;\n resumeLabels?: Record;\n activePaths?: Array;\n activeStepsPath?: Record;\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}\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;\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(\n zObject: z.ZodObject,\n): Record {\n const shape = zObject.shape;\n const result: Record = {};\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;\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;\n inputSchema?: Record;\n groundTruthSchema?: Record;\n requestContextSchema?: Record;\n tags?: string[] | null;\n targetType?: TargetType | null;\n targetIds?: string[] | null;\n scorerIds?: string[] | null;\n version: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface DatasetItemSource {\n type: 'csv' | 'json' | 'trace' | 'llm' | 'experiment-result';\n referenceId?: string;\n}\n\nexport interface DatasetItem {\n id: string;\n datasetId: string;\n datasetVersion: number;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n requestContext?: Record;\n metadata?: Record;\n source?: DatasetItemSource;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface DatasetItemRow {\n id: string;\n datasetId: string;\n datasetVersion: number;\n validTo: number | null;\n isDeleted: boolean;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n requestContext?: Record;\n metadata?: Record;\n source?: DatasetItemSource;\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 name: string;\n description?: string;\n metadata?: Record;\n inputSchema?: Record | null;\n groundTruthSchema?: Record | null;\n requestContextSchema?: Record | null;\n targetType?: TargetType;\n targetIds?: string[];\n scorerIds?: string[];\n}\n\nexport interface UpdateDatasetInput {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record;\n inputSchema?: Record | null;\n groundTruthSchema?: Record | null;\n requestContextSchema?: Record | null;\n tags?: string[] | null;\n targetType?: TargetType | null;\n targetIds?: string[] | null;\n scorerIds?: string[] | null;\n}\n\nexport interface AddDatasetItemInput {\n datasetId: string;\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n requestContext?: Record;\n metadata?: Record;\n source?: DatasetItemSource;\n}\n\nexport interface UpdateDatasetItemInput {\n id: string;\n datasetId: string;\n input?: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n requestContext?: Record;\n metadata?: Record;\n source?: DatasetItemSource;\n}\n\nexport interface ListDatasetsInput {\n pagination: StoragePagination;\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}\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: Array<{\n input: unknown;\n groundTruth?: unknown;\n expectedTrajectory?: unknown;\n requestContext?: Record;\n metadata?: Record;\n source?: DatasetItemSource;\n }>;\n}\n\nexport interface BatchDeleteItemsInput {\n datasetId: string;\n itemIds: string[];\n}\n\n// ============================================\n// Experiment Types (Dataset Experiments)\n// ============================================\n\nexport type ExperimentStatus = 'pending' | 'running' | 'completed' | 'failed';\n\nexport interface Experiment {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record;\n datasetId: string | null;\n datasetVersion: number | null;\n targetType: TargetType;\n targetId: string;\n status: ExperimentStatus;\n totalItems: number;\n succeededCount: number;\n failedCount: number;\n skippedCount: number;\n agentVersion?: 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 error: { message: string; stack?: string; code?: string } | null;\n startedAt: Date;\n completedAt: Date;\n retryCount: number;\n traceId: string | null;\n status: ExperimentResultStatus | null;\n tags: 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}\n\nexport interface CreateExperimentInput {\n id?: string;\n name?: string;\n description?: string;\n metadata?: Record;\n datasetId: string | null;\n datasetVersion: number | null;\n agentVersion?: string;\n targetType: TargetType;\n targetId: string;\n totalItems: number;\n}\n\nexport interface UpdateExperimentInput {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record;\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 error: { message: string; stack?: string; code?: string } | null;\n startedAt: Date;\n completedAt: Date;\n retryCount: number;\n traceId?: string | null;\n status?: ExperimentResultStatus | null;\n tags?: string[] | null;\n}\n\nexport interface ListExperimentsInput {\n datasetId?: string;\n targetType?: TargetType;\n targetId?: string;\n agentVersion?: string;\n status?: ExperimentStatus;\n pagination: StoragePagination;\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 pagination: StoragePagination;\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 { 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// 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/** 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\nexport const SCORERS_SCHEMA: Record = {\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 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 = {\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 = {\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 = {\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 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 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 = {\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 = {\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 = {\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 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 = {\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 = {\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 = {\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 = {\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 = {\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 WORKSPACES_SCHEMA: Record = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 = {\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 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 = {\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 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 = {\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 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 createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const DATASET_VERSIONS_SCHEMA: Record = {\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 = {\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 datasetId: { type: 'text', nullable: true, references: { table: 'mastra_datasets', column: 'id' } },\n datasetVersion: { type: 'integer', nullable: true },\n targetType: { type: 'text', nullable: false },\n targetId: { type: 'text', nullable: false },\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 createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const EXPERIMENT_RESULTS_SCHEMA: Record = {\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 error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false },\n completedAt: { type: 'timestamp', nullable: false },\n retryCount: { type: 'integer', nullable: false },\n traceId: { type: 'text', nullable: true },\n status: { type: 'text', nullable: true },\n tags: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record> = {\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 },\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 },\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};\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> = {\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};\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"]}