@mastra/server 1.75.0-alpha.0 → 1.75.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-versions-BA8ug-Iy.js → agent-versions-CTAEDQuT.js} +3 -3
- package/dist/agent-versions-CTAEDQuT.js.map +1 -0
- package/dist/{agent-versions-BNqDvnn0.cjs → agent-versions-RvvNdlZk.cjs} +3 -3
- package/dist/agent-versions-RvvNdlZk.cjs.map +1 -0
- package/dist/{api-schema-manifest-BmraF-WX.js → api-schema-manifest-B0p6nxU1.js} +2 -2
- package/dist/{api-schema-manifest-BmraF-WX.js.map → api-schema-manifest-B0p6nxU1.js.map} +1 -1
- package/dist/{api-schema-manifest-Blh5-4VH.cjs → api-schema-manifest-D9_jxxNw.cjs} +2 -2
- package/dist/{api-schema-manifest-Blh5-4VH.cjs.map → api-schema-manifest-D9_jxxNw.cjs.map} +1 -1
- package/dist/{dist-DH39C5Bz.js → dist-5xXLv6KR.js} +110 -44
- package/dist/{dist-DH39C5Bz.js.map → dist-5xXLv6KR.js.map} +1 -1
- package/dist/{dist-DJ7t3yBx.js → dist-8fx1_bLF.js} +3 -3
- package/dist/{dist-DJ7t3yBx.js.map → dist-8fx1_bLF.js.map} +1 -1
- package/dist/{dist-IDt748Ya.cjs → dist-B6rOIYr_.cjs} +110 -44
- package/dist/{dist-IDt748Ya.cjs.map → dist-B6rOIYr_.cjs.map} +1 -1
- package/dist/{dist-D1rb-p2Y.js → dist-BCTqy9i3.js} +4 -4
- package/dist/{dist-D1rb-p2Y.js.map → dist-BCTqy9i3.js.map} +1 -1
- package/dist/{dist-DO5NHh-t.cjs → dist-Bw2XgCSY.cjs} +3 -3
- package/dist/{dist-DO5NHh-t.cjs.map → dist-Bw2XgCSY.cjs.map} +1 -1
- package/dist/{dist-Dx2Qp8Rj.js → dist-Bz4l8I_x.js} +3 -3
- package/dist/{dist-Dx2Qp8Rj.js.map → dist-Bz4l8I_x.js.map} +1 -1
- package/dist/{dist-DD1mFVAc.js → dist-C5TZXkhS.js} +3 -3
- package/dist/dist-C5TZXkhS.js.map +1 -0
- package/dist/{dist-B0uCWZUF.cjs → dist-CgemVduI.cjs} +4 -4
- package/dist/{dist-B0uCWZUF.cjs.map → dist-CgemVduI.cjs.map} +1 -1
- package/dist/{dist-Bl3UrwJs.js → dist-D1oSHJhK.js} +3 -3
- package/dist/{dist-Bl3UrwJs.js.map → dist-D1oSHJhK.js.map} +1 -1
- package/dist/{dist-vM0zJcP5.cjs → dist-D5O8s1u2.cjs} +3 -3
- package/dist/{dist-vM0zJcP5.cjs.map → dist-D5O8s1u2.cjs.map} +1 -1
- package/dist/{dist-BQ0VOLA9.cjs → dist-D5mpJHHH.cjs} +3 -3
- package/dist/{dist-BQ0VOLA9.cjs.map → dist-D5mpJHHH.cjs.map} +1 -1
- package/dist/{dist-CkFmsB2E.cjs → dist-UACuV_1t.cjs} +3 -3
- package/dist/{dist-CkFmsB2E.cjs.map → dist-UACuV_1t.cjs.map} +1 -1
- package/dist/{dist-DiEECrlS.js → dist-_RnqhYfY.js} +3 -3
- package/dist/{dist-DiEECrlS.js.map → dist-_RnqhYfY.js.map} +1 -1
- package/dist/{dist-C2u5Kqxy.cjs → dist-tYOY8gEs.cjs} +3 -3
- package/dist/dist-tYOY8gEs.cjs.map +1 -0
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/{helpers-8jl_xtug.cjs → helpers-DhvWjBBJ.cjs} +36 -20
- package/dist/helpers-DhvWjBBJ.cjs.map +1 -0
- package/dist/{helpers-610L0lwQ.js → helpers-DudW6a17.js} +36 -20
- package/dist/helpers-DudW6a17.js.map +1 -0
- package/dist/{routes-CcjyQojv.cjs → routes-BuiLQCOQ.cjs} +3 -3
- package/dist/{routes-CcjyQojv.cjs.map → routes-BuiLQCOQ.cjs.map} +1 -1
- package/dist/{routes-Boe1UThy.js → routes-CJygX0-a.js} +3 -3
- package/dist/{routes-Boe1UThy.js.map → routes-CJygX0-a.js.map} +1 -1
- package/dist/{schedules-DTYwAXI_.cjs → schedules-Buunf_MT.cjs} +11 -5
- package/dist/schedules-Buunf_MT.cjs.map +1 -0
- package/dist/{schedules-Cv3CVT2a.js → schedules-OiPV0jLY.js} +11 -5
- package/dist/schedules-OiPV0jLY.js.map +1 -0
- package/dist/{scorer-versions-nip3xSwF.cjs → scorer-versions-BfGNw7Wp.cjs} +2 -2
- package/dist/{scorer-versions-nip3xSwF.cjs.map → scorer-versions-BfGNw7Wp.cjs.map} +1 -1
- package/dist/{scorer-versions-CscApWzu.js → scorer-versions-gXsdWw0V.js} +2 -2
- package/dist/{scorer-versions-CscApWzu.js.map → scorer-versions-gXsdWw0V.js.map} +1 -1
- package/dist/server/auth/helpers.d.ts.map +1 -1
- package/dist/server/auth/index.cjs +1 -1
- package/dist/server/auth/index.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agent-controller.cjs +1 -1
- package/dist/server/handlers/agent-controller.js +1 -1
- package/dist/server/handlers/agent-versions.cjs +1 -1
- package/dist/server/handlers/agent-versions.d.ts +998 -22
- package/dist/server/handlers/agent-versions.d.ts.map +1 -1
- package/dist/server/handlers/agent-versions.js +1 -1
- package/dist/server/handlers/agents.cjs +18 -2
- package/dist/server/handlers/agents.cjs.map +1 -1
- package/dist/server/handlers/agents.d.ts +248 -4
- package/dist/server/handlers/agents.d.ts.map +1 -1
- package/dist/server/handlers/agents.js +18 -2
- package/dist/server/handlers/agents.js.map +1 -1
- package/dist/server/handlers/auth.cjs +1 -1
- package/dist/server/handlers/auth.js +1 -1
- package/dist/server/handlers/conversations.cjs +1 -1
- package/dist/server/handlers/conversations.js +1 -1
- package/dist/server/handlers/logs.cjs +1 -1
- package/dist/server/handlers/logs.js +1 -1
- package/dist/server/handlers/memory.cjs +1 -1
- package/dist/server/handlers/memory.js +1 -1
- package/dist/server/handlers/observability-new-endpoints.d.ts +35 -3
- package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
- package/dist/server/handlers/plans.cjs +1 -1
- package/dist/server/handlers/plans.js +1 -1
- package/dist/server/handlers/responses.cjs +1 -1
- package/dist/server/handlers/responses.js +1 -1
- package/dist/server/handlers/responses.storage.cjs +1 -1
- package/dist/server/handlers/responses.storage.js +1 -1
- package/dist/server/handlers/schedules.cjs +1 -1
- package/dist/server/handlers/schedules.d.ts +26 -13
- package/dist/server/handlers/schedules.d.ts.map +1 -1
- package/dist/server/handlers/schedules.js +1 -1
- package/dist/server/handlers/scorer-versions.cjs +1 -1
- package/dist/server/handlers/scorer-versions.js +1 -1
- package/dist/server/handlers/stored-agent-favorites.cjs +1 -1
- package/dist/server/handlers/stored-agent-favorites.js +1 -1
- package/dist/server/handlers/stored-agents.cjs +1 -1
- package/dist/server/handlers/stored-agents.d.ts +1065 -89
- package/dist/server/handlers/stored-agents.d.ts.map +1 -1
- package/dist/server/handlers/stored-agents.js +1 -1
- package/dist/server/handlers/stored-scorers.cjs +1 -1
- package/dist/server/handlers/stored-scorers.js +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers/tools.cjs +1 -1
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/utils.cjs +2 -1
- package/dist/server/handlers/utils.d.ts +6 -0
- package/dist/server/handlers/utils.d.ts.map +1 -1
- package/dist/server/handlers/utils.js +2 -2
- package/dist/server/handlers/workflow-builder.cjs +1 -1
- package/dist/server/handlers/workflow-builder.js +1 -1
- package/dist/server/handlers/workflows.cjs +1 -1
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/schemas/agent-versions.d.ts +660 -20
- package/dist/server/schemas/agent-versions.d.ts.map +1 -1
- package/dist/server/schemas/index.cjs +5 -4
- package/dist/server/schemas/index.js +5 -5
- package/dist/server/schemas/memory-config.d.ts +130 -0
- package/dist/server/schemas/memory-config.d.ts.map +1 -1
- package/dist/server/schemas/schedules.d.ts +8 -0
- package/dist/server/schemas/schedules.d.ts.map +1 -1
- package/dist/server/schemas/stored-agents.d.ts +1430 -150
- package/dist/server/schemas/stored-agents.d.ts.map +1 -1
- package/dist/server/server-adapter/index.cjs +2 -2
- package/dist/server/server-adapter/index.js +2 -2
- package/dist/server/server-adapter/routes/observability.d.ts +35 -3
- package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
- package/dist/{stored-agents-DTgigNRY.cjs → stored-agents-Dmsel7ey.cjs} +46 -14
- package/dist/stored-agents-Dmsel7ey.cjs.map +1 -0
- package/dist/{stored-agents-CIdYOdK0.js → stored-agents-ts0bWw8l.js} +41 -15
- package/dist/stored-agents-ts0bWw8l.js.map +1 -0
- package/dist/{stored-scorers-CziNmnC8.cjs → stored-scorers-DoW6lYh8.cjs} +2 -2
- package/dist/{stored-scorers-CziNmnC8.cjs.map → stored-scorers-DoW6lYh8.cjs.map} +1 -1
- package/dist/{stored-scorers-DrkDvsU8.js → stored-scorers-DySg7-qS.js} +2 -2
- package/dist/{stored-scorers-DrkDvsU8.js.map → stored-scorers-DySg7-qS.js.map} +1 -1
- package/dist/{utils-aIu3gkhJ.cjs → utils-HqDZJwRc.cjs} +31 -1
- package/dist/utils-HqDZJwRc.cjs.map +1 -0
- package/dist/{utils-KsERfbhc.js → utils-KcHk7C0D.js} +26 -2
- package/dist/utils-KcHk7C0D.js.map +1 -0
- package/dist/{workflow-builder-DTcM8ER3.cjs → workflow-builder-BSjQJCVD.cjs} +2 -2
- package/dist/{workflow-builder-DTcM8ER3.cjs.map → workflow-builder-BSjQJCVD.cjs.map} +1 -1
- package/dist/{workflow-builder-KRSpDol2.js → workflow-builder-DJ48IzXQ.js} +2 -2
- package/dist/{workflow-builder-KRSpDol2.js.map → workflow-builder-DJ48IzXQ.js.map} +1 -1
- package/package.json +6 -6
- package/dist/agent-versions-BA8ug-Iy.js.map +0 -1
- package/dist/agent-versions-BNqDvnn0.cjs.map +0 -1
- package/dist/dist-C2u5Kqxy.cjs.map +0 -1
- package/dist/dist-DD1mFVAc.js.map +0 -1
- package/dist/helpers-610L0lwQ.js.map +0 -1
- package/dist/helpers-8jl_xtug.cjs.map +0 -1
- package/dist/schedules-Cv3CVT2a.js.map +0 -1
- package/dist/schedules-DTYwAXI_.cjs.map +0 -1
- package/dist/stored-agents-CIdYOdK0.js.map +0 -1
- package/dist/stored-agents-DTgigNRY.cjs.map +0 -1
- package/dist/utils-KsERfbhc.js.map +0 -1
- package/dist/utils-aIu3gkhJ.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schedules-Cv3CVT2a.js","names":["z"],"sources":["../src/server/schemas/schedules.ts","../src/server/handlers/schedules.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const scheduleStatusSchema = z.enum(['active', 'paused']);\n\n/** Mirrors the core `AgentSignalType` union. */\nconst signalTypeSchema = z.enum(['user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder']);\n\n/** Attributes rendered onto the signal's XML tag. */\nconst signalAttributesSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n);\n\n/** Behavior + attributes applied when the thread is already streaming. */\nconst ifActiveSchema = z.object({\n behavior: z.enum(['deliver', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n});\n\n/**\n * Behavior + attributes applied when the thread is idle, plus a serializable\n * subset of stream options forwarded to the woken run.\n */\nconst ifIdleSchema = z.object({\n behavior: z.enum(['wake', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n streamOptions: z\n .object({\n requestContext: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n});\n\nexport const workflowRunStatusSchema = z.enum([\n 'running',\n 'success',\n 'failed',\n 'tripwire',\n 'suspended',\n 'waiting',\n 'pending',\n 'canceled',\n 'bailed',\n 'paused',\n 'skipped',\n]);\n\nexport const scheduleRunSummarySchema = z.object({\n status: workflowRunStatusSchema,\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n durationMs: z.number().optional(),\n error: z.string().optional(),\n});\n\n/**\n * Flat agent-schedule view. Persisted as a `Schedule` row with a\n * `target.type === 'agent'` variant; the HTTP surface flattens that\n * representation to the fields a user cares about (cron, prompt, threading,\n * status, lifecycle) without exposing the schedule plumbing. Discriminate\n * from workflow schedules by the presence of `agentId`.\n */\nexport const agentScheduleSchema = z.object({\n id: z.string(),\n agentId: z.string(),\n /** Mirror of the workflow-schedule discriminator — always absent on agent schedules. */\n workflowId: z.undefined().optional(),\n /** Workflow-run summary — never hydrated for agent schedules. */\n lastRun: z.undefined().optional(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n prompt: z.string(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/**\n * Flat workflow-schedule view. Discriminate from agent schedules by the\n * presence of `workflowId`.\n */\nexport const workflowScheduleSchema = z.object({\n id: z.string(),\n workflowId: z.string(),\n /** Mirror of the agent-schedule discriminator — always absent on workflow schedules. */\n agentId: z.undefined().optional(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n lastRun: scheduleRunSummarySchema.optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/** Union of the flat views returned by the unified `/schedules` surface. */\nexport const scheduleSchema = z.union([agentScheduleSchema, workflowScheduleSchema]);\n\nexport const scheduleTriggerOutcomeSchema = z.enum([\n 'published',\n 'succeeded',\n 'delivered',\n 'persisted',\n 'discarded',\n 'skipped',\n 'aborted',\n 'failed',\n // Legacy queue/notification outcomes — no longer written, but trigger rows\n // persisted by older builds may still carry them. Kept readable so the\n // response validator does not reject historical rows. Mirrors the core\n // ScheduleTriggerOutcome union.\n 'acked',\n 'alerted',\n 'deferred',\n 'appended-from-queue',\n 'dropped-stale',\n 'dropped-superseded',\n 'dropped-busy',\n]);\n\nexport const scheduleTriggerKindSchema = z.enum(['schedule-fire', 'queue-drain', 'manual']);\n\nexport const scheduleTriggerResponseSchema = z.object({\n id: z.string().optional(),\n scheduleId: z.string(),\n runId: z.string().nullable(),\n scheduledFireAt: z.number(),\n actualFireAt: z.number(),\n outcome: scheduleTriggerOutcomeSchema,\n error: z.string().optional(),\n triggerKind: scheduleTriggerKindSchema.optional(),\n parentTriggerId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n run: scheduleRunSummarySchema.optional(),\n});\n\nexport const listSchedulesQuerySchema = z.object({\n agentId: z.string().optional(),\n workflowId: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n /** Agent-schedule only: match the target threadId. */\n threadId: z.string().optional(),\n /** Match the schedule's resourceId (agent thread identity or workflow run attribution). */\n resourceId: z.string().optional(),\n /** Agent-schedule only: match the free-form target name. */\n name: z.string().optional(),\n});\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(scheduleSchema),\n});\n\nexport const scheduleIdPathParams = z.object({\n scheduleId: z.string(),\n});\n\n/**\n * Agent variant of the create body — targets an agent by `agentId`. Strict so\n * a body carrying both `agentId` and `workflowId` is rejected as ambiguous\n * instead of silently matching the agent branch of the union.\n */\nconst createAgentScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `agent_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n agentId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n prompt: z.string(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Workflow variant of the create body — targets a workflow by `workflowId`.\n * Strict so ambiguous bodies (both ids) are rejected by the union.\n */\nconst createWorkflowScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `schedule_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n workflowId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Body for POST /schedules. Discriminated by which target id is present:\n * `agentId` creates an agent schedule, `workflowId` a workflow schedule.\n * Both variants are strict, so a body carrying both ids (or unknown keys)\n * fails validation instead of silently dropping fields.\n */\nexport const createScheduleBodySchema = z.union([createAgentScheduleBodySchema, createWorkflowScheduleBodySchema]);\n\n/**\n * Body for PATCH /schedules/:scheduleId — partial update. Fields apply to\n * the matching target type; agent-only fields on a workflow schedule are\n * rejected by the service. An agent schedule's `threadId` / `resourceId` are\n * intentionally not editable; they are part of its identity — to re-target,\n * delete and recreate. A workflow schedule's `resourceId` is only run-attribution\n * metadata (not identity) and may be updated.\n */\nexport const updateScheduleBodySchema = z.object({\n cron: z.string().optional(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Agent-schedule fields\n prompt: z.string().optional(),\n name: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n // Workflow-schedule fields\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n});\n\nexport const deleteScheduleResponseSchema = z.object({\n message: z.string(),\n});\n\n/** Response for POST /schedules/:scheduleId/run. */\nexport const runScheduleResponseSchema = z.object({\n scheduleId: z.string(),\n claimId: z.string(),\n scheduledFireAt: z.number(),\n});\n\nexport const listScheduleTriggersQuerySchema = z.object({\n limit: z.coerce.number().int().positive().optional(),\n fromActualFireAt: z.coerce.number().int().nonnegative().optional(),\n toActualFireAt: z.coerce.number().int().nonnegative().optional(),\n});\n\nexport const listScheduleTriggersResponseSchema = z.object({\n triggers: z.array(scheduleTriggerResponseSchema),\n});\n\nexport type AgentScheduleResponse = z.infer<typeof agentScheduleSchema>;\nexport type WorkflowScheduleResponse = z.infer<typeof workflowScheduleSchema>;\nexport type ScheduleResponse = z.infer<typeof scheduleSchema>;\n","import type { Mastra } from '@mastra/core';\nimport type { AgentSchedule, AnySchedule, WorkflowSchedule } from '@mastra/core/schedules';\nimport type { WorkflowRunState } from '@mastra/core/workflows';\nimport { HTTPException } from '../http-exception';\nimport {\n createScheduleBodySchema,\n deleteScheduleResponseSchema,\n listSchedulesQuerySchema,\n listSchedulesResponseSchema,\n listScheduleTriggersQuerySchema,\n listScheduleTriggersResponseSchema,\n runScheduleResponseSchema,\n scheduleIdPathParams,\n scheduleSchema,\n updateScheduleBodySchema,\n} from '../schemas/schedules';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\ntype RunSummary = {\n status: WorkflowRunState['status'];\n startedAt?: number;\n completedAt?: number;\n durationMs?: number;\n error?: string;\n};\n\nfunction snapshotToRunSummary(run: {\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}): RunSummary | undefined {\n const snapshot = typeof run.snapshot === 'string' ? null : run.snapshot;\n if (!snapshot) return undefined;\n const startedAt = run.createdAt instanceof Date ? run.createdAt.getTime() : undefined;\n const isTerminal =\n snapshot.status === 'success' ||\n snapshot.status === 'failed' ||\n snapshot.status === 'canceled' ||\n snapshot.status === 'bailed' ||\n snapshot.status === 'tripwire';\n const completedAt = isTerminal ? (run.updatedAt instanceof Date ? run.updatedAt.getTime() : undefined) : undefined;\n const durationMs = startedAt !== undefined && completedAt !== undefined ? completedAt - startedAt : undefined;\n return {\n status: snapshot.status,\n startedAt,\n completedAt,\n durationMs,\n error: snapshot.error?.message,\n };\n}\n\nasync function fetchRunSummary(mastra: Mastra, workflowName: string, runId: string): Promise<RunSummary | undefined> {\n try {\n const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n const run = await workflowsStore?.getWorkflowRunById({ runId, workflowName });\n if (!run) return undefined;\n return snapshotToRunSummary(run);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Attach a `lastRun` summary to workflow schedules. Agent schedules pass\n * through unchanged — their `lastRunId` is an agent run, not a workflow run.\n */\nasync function hydrateScheduleResponse(\n mastra: Mastra,\n schedule: AnySchedule,\n): Promise<AgentSchedule | (WorkflowSchedule & { lastRun?: RunSummary })> {\n if (!schedule.workflowId || !schedule.lastRunId) {\n return schedule;\n }\n const lastRun = await fetchRunSummary(mastra, schedule.workflowId, schedule.lastRunId);\n return lastRun ? { ...schedule, lastRun } : schedule;\n}\n\n/**\n * Resolve a schedule by id via `mastra.schedules`. Returns 404 for missing\n * rows so handlers surface a clean HTTP error instead of a service error.\n */\nasync function loadSchedule(mastra: Mastra, scheduleId: string): Promise<AnySchedule> {\n const schedule = await mastra.schedules.get(scheduleId);\n if (!schedule) {\n throw new HTTPException(404, { message: 'Schedule not found' });\n }\n return schedule;\n}\n\nexport const LIST_SCHEDULES_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules',\n responseType: 'json' as const,\n queryParamSchema: listSchedulesQuerySchema,\n responseSchema: listSchedulesResponseSchema,\n summary: 'List schedules',\n description:\n 'Returns all schedules — agent schedules and workflow schedules — optionally filtered by agentId, workflowId, or status. Agent schedules can additionally be filtered by threadId, resourceId, or name.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, workflowId, status, threadId, resourceId, name }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n // Schedules domain not configured — there are no schedules to return.\n return { schedules: [] };\n }\n const schedules = await mastra.schedules.list({ agentId, workflowId, status, threadId, resourceId, name });\n const hydrated = await Promise.all(schedules.map(schedule => hydrateScheduleResponse(mastra, schedule)));\n return { schedules: hydrated };\n },\n});\n\nexport const GET_SCHEDULE_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Get a schedule by ID',\n description: 'Returns a single schedule by its id.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n const schedule = await loadSchedule(mastra, scheduleId);\n return hydrateScheduleResponse(mastra, schedule);\n },\n});\n\nexport const CREATE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules',\n responseType: 'json' as const,\n bodySchema: createScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Create a schedule',\n description:\n 'Creates a new schedule. Pass `agentId` (plus `prompt`) to schedule an agent, or `workflowId` (plus optional `inputData`) to schedule a workflow. Agent schedules get a random `agent_<uuid>` id, workflow schedules a random `schedule_<uuid>` id; pass `id` for a stable slug instead.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, ...body }) => {\n // getAgentById / getWorkflowById throw a MastraError (status 404) when the\n // target is unknown; translate that into a clean HTTP 404 instead of\n // letting it surface as 500.\n if ('workflowId' in body && body.workflowId) {\n try {\n mastra.getWorkflowById(body.workflowId);\n } catch {\n throw new HTTPException(404, { message: `Workflow \"${body.workflowId}\" not found` });\n }\n return await mastra.schedules.create({\n workflowId: body.workflowId,\n cron: body.cron,\n ...(body.id ? { id: body.id } : {}),\n ...(body.timezone ? { timezone: body.timezone } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId ? { resourceId: body.resourceId } : {}),\n ...(body.metadata ? { metadata: body.metadata } : {}),\n });\n }\n const agentBody = body as Extract<typeof body, { agentId: string }>;\n try {\n mastra.getAgentById(agentBody.agentId);\n } catch {\n throw new HTTPException(404, { message: `Agent \"${agentBody.agentId}\" not found` });\n }\n return await mastra.schedules.create({\n agentId: agentBody.agentId,\n cron: agentBody.cron,\n prompt: agentBody.prompt,\n ...(agentBody.id ? { id: agentBody.id } : {}),\n ...(agentBody.name ? { name: agentBody.name } : {}),\n ...(agentBody.timezone ? { timezone: agentBody.timezone } : {}),\n ...(agentBody.threadId ? { threadId: agentBody.threadId } : {}),\n ...(agentBody.resourceId ? { resourceId: agentBody.resourceId } : {}),\n ...(agentBody.signalType ? { signalType: agentBody.signalType } : {}),\n ...(agentBody.tagName ? { tagName: agentBody.tagName } : {}),\n ...(agentBody.attributes ? { attributes: agentBody.attributes } : {}),\n ...(agentBody.ifActive ? { ifActive: agentBody.ifActive } : {}),\n ...(agentBody.ifIdle ? { ifIdle: agentBody.ifIdle } : {}),\n ...(agentBody.providerOptions ? { providerOptions: agentBody.providerOptions } : {}),\n ...(agentBody.metadata ? { metadata: agentBody.metadata } : {}),\n });\n },\n});\n\nexport const UPDATE_SCHEDULE_ROUTE = createRoute({\n method: 'PATCH',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n bodySchema: updateScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Update a schedule',\n description:\n \"Partial update of a schedule. Fields apply to the matching target type; agent-only fields on a workflow schedule are rejected. An agent schedule's `threadId` and `resourceId` are part of its identity and cannot be changed — to re-target, delete and recreate. A workflow schedule's `resourceId` is run-attribution metadata and may be updated. Editing `cron` (or `timezone`) recomputes `nextFireAt`.\",\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, ...body }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.update(scheduleId, {\n ...(body.cron !== undefined ? { cron: body.cron } : {}),\n ...(body.timezone !== undefined ? { timezone: body.timezone } : {}),\n ...(body.status !== undefined ? { status: body.status } : {}),\n ...(body.metadata !== undefined ? { metadata: body.metadata } : {}),\n ...(body.prompt !== undefined ? { prompt: body.prompt } : {}),\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.signalType !== undefined ? { signalType: body.signalType } : {}),\n ...(body.tagName !== undefined ? { tagName: body.tagName } : {}),\n ...(body.attributes !== undefined ? { attributes: body.attributes } : {}),\n ...(body.ifActive !== undefined ? { ifActive: body.ifActive } : {}),\n ...(body.ifIdle !== undefined ? { ifIdle: body.ifIdle } : {}),\n ...(body.providerOptions !== undefined ? { providerOptions: body.providerOptions } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext !== undefined ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId !== undefined ? { resourceId: body.resourceId } : {}),\n });\n },\n});\n\nexport const DELETE_SCHEDULE_ROUTE = createRoute({\n method: 'DELETE',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: deleteScheduleResponseSchema,\n summary: 'Delete a schedule',\n description: 'Permanently deletes the schedule. 404 when the schedule does not exist.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n await mastra.schedules.delete(scheduleId);\n return { message: 'Schedule deleted' };\n },\n});\n\nexport const PAUSE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/pause',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Pause a schedule',\n description:\n 'Marks the schedule as paused. The scheduler tick loop will skip paused schedules. Idempotent — pausing an already-paused schedule returns the current state unchanged. Pause status survives redeploys.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.pause(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RESUME_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/resume',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Resume a paused schedule',\n description:\n 'Marks the schedule as active and recomputes nextFireAt from \"now\" so a long-paused schedule does not fire a backlog. Idempotent — resuming an already-active schedule returns the current state unchanged.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.resume(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RUN_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/run',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: runScheduleResponseSchema,\n summary: 'Fire a schedule now',\n description:\n 'Manually triggers a single schedule fire out-of-band from the cron schedule. Records a trigger row with `triggerKind: \"manual\"`. Does not advance `nextFireAt`.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.run(scheduleId);\n },\n});\n\nexport const LIST_SCHEDULE_TRIGGERS_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId/triggers',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n queryParamSchema: listScheduleTriggersQuerySchema,\n responseSchema: listScheduleTriggersResponseSchema,\n summary: 'List trigger history for a schedule',\n description: 'Returns the audit trail of trigger attempts for a schedule, ordered by actualFireAt descending.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, limit, fromActualFireAt, toActualFireAt }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n return { triggers: [] };\n }\n const schedule = await mastra.schedules.get(scheduleId);\n const triggers = await schedulesStore.listTriggers(schedule?.id ?? scheduleId, {\n limit,\n fromActualFireAt,\n toActualFireAt,\n });\n if (!schedule?.workflowId) {\n return { triggers };\n }\n const workflowName = schedule.workflowId;\n const hydrated = await Promise.all(\n triggers.map(async trigger => {\n if (trigger.outcome !== 'published' || !trigger.runId) return trigger;\n const run = await fetchRunSummary(mastra, workflowName, trigger.runId);\n return run ? { ...trigger, run } : trigger;\n }),\n );\n return { triggers: hydrated };\n },\n});\n"],"mappings":";;;;AAEA,MAAa,uBAAuBA,IAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;;AAG/D,MAAM,mBAAmBA,IAAE,KAAK;CAAC;CAAQ;CAAS;CAAY;CAAgB;CAAgB;AAAiB,CAAC;;AAGhH,MAAM,yBAAyBA,IAAE,OAC/BA,IAAE,OAAO,GACTA,IAAE,MAAM;CAACA,IAAE,OAAO;CAAGA,IAAE,OAAO;CAAGA,IAAE,QAAQ;CAAGA,IAAE,KAAK;AAAC,CAAC,CAAC,CAAC,SAAS,CACpE;;AAGA,MAAM,iBAAiBA,IAAE,OAAO;CAC9B,UAAUA,IAAE,KAAK;EAAC;EAAW;EAAW;CAAS,CAAC,CAAC,CAAC,SAAS;CAC7D,YAAY,uBAAuB,SAAS;AAC9C,CAAC;;;;;AAMD,MAAM,eAAeA,IAAE,OAAO;CAC5B,UAAUA,IAAE,KAAK;EAAC;EAAQ;EAAW;CAAS,CAAC,CAAC,CAAC,SAAS;CAC1D,YAAY,uBAAuB,SAAS;CAC5C,eAAeA,IACZ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AAa,QAAQ,UAAU;EACrC,OAAO,MAAM,OAAO,UAAU,IAAI,UAAU;CAC9C;AACF,CAAC;AAED,MAAa,+BAA+B,YAAY;CACtD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,WAAW;CAClB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,YAAY,OAAO,kBAAkB,qBAAqB;EAClF,MAAM,iBAAiB,MAAM,OAAO,WAAW,CAAC,EAAE,SAAS,WAAW;EACtE,IAAI,CAAC,gBACH,OAAO,EAAE,UAAU,CAAC,EAAE;EAExB,MAAM,WAAW,MAAM,OAAO,UAAU,IAAI,UAAU;EACtD,MAAM,WAAW,MAAM,eAAe,aAAa,UAAU,MAAM,YAAY;GAC7E;GACA;GACA;EACF,CAAC;EACD,IAAI,CAAC,UAAU,YACb,OAAO,EAAE,SAAS;EAEpB,MAAM,eAAe,SAAS;EAQ9B,OAAO,EAAE,UAAU,MAPI,QAAQ,IAC7B,SAAS,IAAI,OAAM,YAAW;GAC5B,IAAI,QAAQ,YAAY,eAAe,CAAC,QAAQ,OAAO,OAAO;GAC9D,MAAM,MAAM,MAAM,gBAAgB,QAAQ,cAAc,QAAQ,KAAK;GACrE,OAAO,MAAM;IAAE,GAAG;IAAS;GAAI,IAAI;EACrC,CAAC,CACH,EAC4B;CAC9B;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schedules-DTYwAXI_.cjs","names":["z","HTTPException","createRoute"],"sources":["../src/server/schemas/schedules.ts","../src/server/handlers/schedules.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const scheduleStatusSchema = z.enum(['active', 'paused']);\n\n/** Mirrors the core `AgentSignalType` union. */\nconst signalTypeSchema = z.enum(['user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder']);\n\n/** Attributes rendered onto the signal's XML tag. */\nconst signalAttributesSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n);\n\n/** Behavior + attributes applied when the thread is already streaming. */\nconst ifActiveSchema = z.object({\n behavior: z.enum(['deliver', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n});\n\n/**\n * Behavior + attributes applied when the thread is idle, plus a serializable\n * subset of stream options forwarded to the woken run.\n */\nconst ifIdleSchema = z.object({\n behavior: z.enum(['wake', 'persist', 'discard']).optional(),\n attributes: signalAttributesSchema.optional(),\n streamOptions: z\n .object({\n requestContext: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n});\n\nexport const workflowRunStatusSchema = z.enum([\n 'running',\n 'success',\n 'failed',\n 'tripwire',\n 'suspended',\n 'waiting',\n 'pending',\n 'canceled',\n 'bailed',\n 'paused',\n 'skipped',\n]);\n\nexport const scheduleRunSummarySchema = z.object({\n status: workflowRunStatusSchema,\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n durationMs: z.number().optional(),\n error: z.string().optional(),\n});\n\n/**\n * Flat agent-schedule view. Persisted as a `Schedule` row with a\n * `target.type === 'agent'` variant; the HTTP surface flattens that\n * representation to the fields a user cares about (cron, prompt, threading,\n * status, lifecycle) without exposing the schedule plumbing. Discriminate\n * from workflow schedules by the presence of `agentId`.\n */\nexport const agentScheduleSchema = z.object({\n id: z.string(),\n agentId: z.string(),\n /** Mirror of the workflow-schedule discriminator — always absent on agent schedules. */\n workflowId: z.undefined().optional(),\n /** Workflow-run summary — never hydrated for agent schedules. */\n lastRun: z.undefined().optional(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n prompt: z.string(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/**\n * Flat workflow-schedule view. Discriminate from agent schedules by the\n * presence of `workflowId`.\n */\nexport const workflowScheduleSchema = z.object({\n id: z.string(),\n workflowId: z.string(),\n /** Mirror of the agent-schedule discriminator — always absent on workflow schedules. */\n agentId: z.undefined().optional(),\n cron: z.string(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema,\n nextFireAt: z.number(),\n lastFireAt: z.number().optional(),\n lastRunId: z.string().optional(),\n lastRun: scheduleRunSummarySchema.optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n});\n\n/** Union of the flat views returned by the unified `/schedules` surface. */\nexport const scheduleSchema = z.union([agentScheduleSchema, workflowScheduleSchema]);\n\nexport const scheduleTriggerOutcomeSchema = z.enum([\n 'published',\n 'succeeded',\n 'delivered',\n 'persisted',\n 'discarded',\n 'skipped',\n 'aborted',\n 'failed',\n // Legacy queue/notification outcomes — no longer written, but trigger rows\n // persisted by older builds may still carry them. Kept readable so the\n // response validator does not reject historical rows. Mirrors the core\n // ScheduleTriggerOutcome union.\n 'acked',\n 'alerted',\n 'deferred',\n 'appended-from-queue',\n 'dropped-stale',\n 'dropped-superseded',\n 'dropped-busy',\n]);\n\nexport const scheduleTriggerKindSchema = z.enum(['schedule-fire', 'queue-drain', 'manual']);\n\nexport const scheduleTriggerResponseSchema = z.object({\n id: z.string().optional(),\n scheduleId: z.string(),\n runId: z.string().nullable(),\n scheduledFireAt: z.number(),\n actualFireAt: z.number(),\n outcome: scheduleTriggerOutcomeSchema,\n error: z.string().optional(),\n triggerKind: scheduleTriggerKindSchema.optional(),\n parentTriggerId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n run: scheduleRunSummarySchema.optional(),\n});\n\nexport const listSchedulesQuerySchema = z.object({\n agentId: z.string().optional(),\n workflowId: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n /** Agent-schedule only: match the target threadId. */\n threadId: z.string().optional(),\n /** Match the schedule's resourceId (agent thread identity or workflow run attribution). */\n resourceId: z.string().optional(),\n /** Agent-schedule only: match the free-form target name. */\n name: z.string().optional(),\n});\n\nexport const listSchedulesResponseSchema = z.object({\n schedules: z.array(scheduleSchema),\n});\n\nexport const scheduleIdPathParams = z.object({\n scheduleId: z.string(),\n});\n\n/**\n * Agent variant of the create body — targets an agent by `agentId`. Strict so\n * a body carrying both `agentId` and `workflowId` is rejected as ambiguous\n * instead of silently matching the agent branch of the union.\n */\nconst createAgentScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `agent_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n agentId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n prompt: z.string(),\n name: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Workflow variant of the create body — targets a workflow by `workflowId`.\n * Strict so ambiguous bodies (both ids) are rejected by the union.\n */\nconst createWorkflowScheduleBodySchema = z.strictObject({\n /** Optional stable id; normalized to `schedule_<slug>`. A random id is generated when omitted. */\n id: z.string().optional(),\n workflowId: z.string().min(1),\n cron: z.string(),\n timezone: z.string().optional(),\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * Body for POST /schedules. Discriminated by which target id is present:\n * `agentId` creates an agent schedule, `workflowId` a workflow schedule.\n * Both variants are strict, so a body carrying both ids (or unknown keys)\n * fails validation instead of silently dropping fields.\n */\nexport const createScheduleBodySchema = z.union([createAgentScheduleBodySchema, createWorkflowScheduleBodySchema]);\n\n/**\n * Body for PATCH /schedules/:scheduleId — partial update. Fields apply to\n * the matching target type; agent-only fields on a workflow schedule are\n * rejected by the service. An agent schedule's `threadId` / `resourceId` are\n * intentionally not editable; they are part of its identity — to re-target,\n * delete and recreate. A workflow schedule's `resourceId` is only run-attribution\n * metadata (not identity) and may be updated.\n */\nexport const updateScheduleBodySchema = z.object({\n cron: z.string().optional(),\n timezone: z.string().optional(),\n status: scheduleStatusSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n // Agent-schedule fields\n prompt: z.string().optional(),\n name: z.string().optional(),\n signalType: signalTypeSchema.optional(),\n tagName: z.string().optional(),\n attributes: signalAttributesSchema.optional(),\n ifActive: ifActiveSchema.optional(),\n ifIdle: ifIdleSchema.optional(),\n providerOptions: z.record(z.string(), z.unknown()).optional(),\n // Workflow-schedule fields\n inputData: z.unknown().optional(),\n initialState: z.unknown().optional(),\n requestContext: z.record(z.string(), z.unknown()).optional(),\n resourceId: z.string().optional(),\n});\n\nexport const deleteScheduleResponseSchema = z.object({\n message: z.string(),\n});\n\n/** Response for POST /schedules/:scheduleId/run. */\nexport const runScheduleResponseSchema = z.object({\n scheduleId: z.string(),\n claimId: z.string(),\n scheduledFireAt: z.number(),\n});\n\nexport const listScheduleTriggersQuerySchema = z.object({\n limit: z.coerce.number().int().positive().optional(),\n fromActualFireAt: z.coerce.number().int().nonnegative().optional(),\n toActualFireAt: z.coerce.number().int().nonnegative().optional(),\n});\n\nexport const listScheduleTriggersResponseSchema = z.object({\n triggers: z.array(scheduleTriggerResponseSchema),\n});\n\nexport type AgentScheduleResponse = z.infer<typeof agentScheduleSchema>;\nexport type WorkflowScheduleResponse = z.infer<typeof workflowScheduleSchema>;\nexport type ScheduleResponse = z.infer<typeof scheduleSchema>;\n","import type { Mastra } from '@mastra/core';\nimport type { AgentSchedule, AnySchedule, WorkflowSchedule } from '@mastra/core/schedules';\nimport type { WorkflowRunState } from '@mastra/core/workflows';\nimport { HTTPException } from '../http-exception';\nimport {\n createScheduleBodySchema,\n deleteScheduleResponseSchema,\n listSchedulesQuerySchema,\n listSchedulesResponseSchema,\n listScheduleTriggersQuerySchema,\n listScheduleTriggersResponseSchema,\n runScheduleResponseSchema,\n scheduleIdPathParams,\n scheduleSchema,\n updateScheduleBodySchema,\n} from '../schemas/schedules';\nimport { createRoute } from '../server-adapter/routes/route-builder';\n\ntype RunSummary = {\n status: WorkflowRunState['status'];\n startedAt?: number;\n completedAt?: number;\n durationMs?: number;\n error?: string;\n};\n\nfunction snapshotToRunSummary(run: {\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}): RunSummary | undefined {\n const snapshot = typeof run.snapshot === 'string' ? null : run.snapshot;\n if (!snapshot) return undefined;\n const startedAt = run.createdAt instanceof Date ? run.createdAt.getTime() : undefined;\n const isTerminal =\n snapshot.status === 'success' ||\n snapshot.status === 'failed' ||\n snapshot.status === 'canceled' ||\n snapshot.status === 'bailed' ||\n snapshot.status === 'tripwire';\n const completedAt = isTerminal ? (run.updatedAt instanceof Date ? run.updatedAt.getTime() : undefined) : undefined;\n const durationMs = startedAt !== undefined && completedAt !== undefined ? completedAt - startedAt : undefined;\n return {\n status: snapshot.status,\n startedAt,\n completedAt,\n durationMs,\n error: snapshot.error?.message,\n };\n}\n\nasync function fetchRunSummary(mastra: Mastra, workflowName: string, runId: string): Promise<RunSummary | undefined> {\n try {\n const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n const run = await workflowsStore?.getWorkflowRunById({ runId, workflowName });\n if (!run) return undefined;\n return snapshotToRunSummary(run);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Attach a `lastRun` summary to workflow schedules. Agent schedules pass\n * through unchanged — their `lastRunId` is an agent run, not a workflow run.\n */\nasync function hydrateScheduleResponse(\n mastra: Mastra,\n schedule: AnySchedule,\n): Promise<AgentSchedule | (WorkflowSchedule & { lastRun?: RunSummary })> {\n if (!schedule.workflowId || !schedule.lastRunId) {\n return schedule;\n }\n const lastRun = await fetchRunSummary(mastra, schedule.workflowId, schedule.lastRunId);\n return lastRun ? { ...schedule, lastRun } : schedule;\n}\n\n/**\n * Resolve a schedule by id via `mastra.schedules`. Returns 404 for missing\n * rows so handlers surface a clean HTTP error instead of a service error.\n */\nasync function loadSchedule(mastra: Mastra, scheduleId: string): Promise<AnySchedule> {\n const schedule = await mastra.schedules.get(scheduleId);\n if (!schedule) {\n throw new HTTPException(404, { message: 'Schedule not found' });\n }\n return schedule;\n}\n\nexport const LIST_SCHEDULES_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules',\n responseType: 'json' as const,\n queryParamSchema: listSchedulesQuerySchema,\n responseSchema: listSchedulesResponseSchema,\n summary: 'List schedules',\n description:\n 'Returns all schedules — agent schedules and workflow schedules — optionally filtered by agentId, workflowId, or status. Agent schedules can additionally be filtered by threadId, resourceId, or name.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, agentId, workflowId, status, threadId, resourceId, name }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n // Schedules domain not configured — there are no schedules to return.\n return { schedules: [] };\n }\n const schedules = await mastra.schedules.list({ agentId, workflowId, status, threadId, resourceId, name });\n const hydrated = await Promise.all(schedules.map(schedule => hydrateScheduleResponse(mastra, schedule)));\n return { schedules: hydrated };\n },\n});\n\nexport const GET_SCHEDULE_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Get a schedule by ID',\n description: 'Returns a single schedule by its id.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n const schedule = await loadSchedule(mastra, scheduleId);\n return hydrateScheduleResponse(mastra, schedule);\n },\n});\n\nexport const CREATE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules',\n responseType: 'json' as const,\n bodySchema: createScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Create a schedule',\n description:\n 'Creates a new schedule. Pass `agentId` (plus `prompt`) to schedule an agent, or `workflowId` (plus optional `inputData`) to schedule a workflow. Agent schedules get a random `agent_<uuid>` id, workflow schedules a random `schedule_<uuid>` id; pass `id` for a stable slug instead.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, ...body }) => {\n // getAgentById / getWorkflowById throw a MastraError (status 404) when the\n // target is unknown; translate that into a clean HTTP 404 instead of\n // letting it surface as 500.\n if ('workflowId' in body && body.workflowId) {\n try {\n mastra.getWorkflowById(body.workflowId);\n } catch {\n throw new HTTPException(404, { message: `Workflow \"${body.workflowId}\" not found` });\n }\n return await mastra.schedules.create({\n workflowId: body.workflowId,\n cron: body.cron,\n ...(body.id ? { id: body.id } : {}),\n ...(body.timezone ? { timezone: body.timezone } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId ? { resourceId: body.resourceId } : {}),\n ...(body.metadata ? { metadata: body.metadata } : {}),\n });\n }\n const agentBody = body as Extract<typeof body, { agentId: string }>;\n try {\n mastra.getAgentById(agentBody.agentId);\n } catch {\n throw new HTTPException(404, { message: `Agent \"${agentBody.agentId}\" not found` });\n }\n return await mastra.schedules.create({\n agentId: agentBody.agentId,\n cron: agentBody.cron,\n prompt: agentBody.prompt,\n ...(agentBody.id ? { id: agentBody.id } : {}),\n ...(agentBody.name ? { name: agentBody.name } : {}),\n ...(agentBody.timezone ? { timezone: agentBody.timezone } : {}),\n ...(agentBody.threadId ? { threadId: agentBody.threadId } : {}),\n ...(agentBody.resourceId ? { resourceId: agentBody.resourceId } : {}),\n ...(agentBody.signalType ? { signalType: agentBody.signalType } : {}),\n ...(agentBody.tagName ? { tagName: agentBody.tagName } : {}),\n ...(agentBody.attributes ? { attributes: agentBody.attributes } : {}),\n ...(agentBody.ifActive ? { ifActive: agentBody.ifActive } : {}),\n ...(agentBody.ifIdle ? { ifIdle: agentBody.ifIdle } : {}),\n ...(agentBody.providerOptions ? { providerOptions: agentBody.providerOptions } : {}),\n ...(agentBody.metadata ? { metadata: agentBody.metadata } : {}),\n });\n },\n});\n\nexport const UPDATE_SCHEDULE_ROUTE = createRoute({\n method: 'PATCH',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n bodySchema: updateScheduleBodySchema,\n responseSchema: scheduleSchema,\n summary: 'Update a schedule',\n description:\n \"Partial update of a schedule. Fields apply to the matching target type; agent-only fields on a workflow schedule are rejected. An agent schedule's `threadId` and `resourceId` are part of its identity and cannot be changed — to re-target, delete and recreate. A workflow schedule's `resourceId` is run-attribution metadata and may be updated. Editing `cron` (or `timezone`) recomputes `nextFireAt`.\",\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, ...body }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.update(scheduleId, {\n ...(body.cron !== undefined ? { cron: body.cron } : {}),\n ...(body.timezone !== undefined ? { timezone: body.timezone } : {}),\n ...(body.status !== undefined ? { status: body.status } : {}),\n ...(body.metadata !== undefined ? { metadata: body.metadata } : {}),\n ...(body.prompt !== undefined ? { prompt: body.prompt } : {}),\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.signalType !== undefined ? { signalType: body.signalType } : {}),\n ...(body.tagName !== undefined ? { tagName: body.tagName } : {}),\n ...(body.attributes !== undefined ? { attributes: body.attributes } : {}),\n ...(body.ifActive !== undefined ? { ifActive: body.ifActive } : {}),\n ...(body.ifIdle !== undefined ? { ifIdle: body.ifIdle } : {}),\n ...(body.providerOptions !== undefined ? { providerOptions: body.providerOptions } : {}),\n ...(body.inputData !== undefined ? { inputData: body.inputData } : {}),\n ...(body.initialState !== undefined ? { initialState: body.initialState } : {}),\n ...(body.requestContext !== undefined ? { requestContext: body.requestContext } : {}),\n ...(body.resourceId !== undefined ? { resourceId: body.resourceId } : {}),\n });\n },\n});\n\nexport const DELETE_SCHEDULE_ROUTE = createRoute({\n method: 'DELETE',\n path: '/schedules/:scheduleId',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: deleteScheduleResponseSchema,\n summary: 'Delete a schedule',\n description: 'Permanently deletes the schedule. 404 when the schedule does not exist.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n await mastra.schedules.delete(scheduleId);\n return { message: 'Schedule deleted' };\n },\n});\n\nexport const PAUSE_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/pause',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Pause a schedule',\n description:\n 'Marks the schedule as paused. The scheduler tick loop will skip paused schedules. Idempotent — pausing an already-paused schedule returns the current state unchanged. Pause status survives redeploys.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.pause(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RESUME_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/resume',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: scheduleSchema,\n summary: 'Resume a paused schedule',\n description:\n 'Marks the schedule as active and recomputes nextFireAt from \"now\" so a long-paused schedule does not fire a backlog. Idempotent — resuming an already-active schedule returns the current state unchanged.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n const updated = await mastra.schedules.resume(scheduleId);\n return hydrateScheduleResponse(mastra, updated);\n },\n});\n\nexport const RUN_SCHEDULE_ROUTE = createRoute({\n method: 'POST',\n path: '/schedules/:scheduleId/run',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n responseSchema: runScheduleResponseSchema,\n summary: 'Fire a schedule now',\n description:\n 'Manually triggers a single schedule fire out-of-band from the cron schedule. Records a trigger row with `triggerKind: \"manual\"`. Does not advance `nextFireAt`.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId }) => {\n await loadSchedule(mastra, scheduleId);\n return await mastra.schedules.run(scheduleId);\n },\n});\n\nexport const LIST_SCHEDULE_TRIGGERS_ROUTE = createRoute({\n method: 'GET',\n path: '/schedules/:scheduleId/triggers',\n responseType: 'json' as const,\n pathParamSchema: scheduleIdPathParams,\n queryParamSchema: listScheduleTriggersQuerySchema,\n responseSchema: listScheduleTriggersResponseSchema,\n summary: 'List trigger history for a schedule',\n description: 'Returns the audit trail of trigger attempts for a schedule, ordered by actualFireAt descending.',\n tags: ['Schedules'],\n requiresAuth: true,\n handler: async ({ mastra, scheduleId, limit, fromActualFireAt, toActualFireAt }) => {\n const schedulesStore = await mastra.getStorage()?.getStore('schedules');\n if (!schedulesStore) {\n return { triggers: [] };\n }\n const schedule = await mastra.schedules.get(scheduleId);\n const triggers = await schedulesStore.listTriggers(schedule?.id ?? scheduleId, {\n limit,\n fromActualFireAt,\n toActualFireAt,\n });\n if (!schedule?.workflowId) {\n return { triggers };\n }\n const workflowName = schedule.workflowId;\n const hydrated = await Promise.all(\n triggers.map(async trigger => {\n if (trigger.outcome !== 'published' || !trigger.runId) return trigger;\n const run = await fetchRunSummary(mastra, workflowName, trigger.runId);\n return run ? { ...trigger, run } : trigger;\n }),\n );\n return { triggers: hydrated };\n },\n});\n"],"mappings":";;;;AAEA,MAAa,uBAAuBA,IAAAA,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC;;AAG/D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AAI,QAAQ,YAAY,eAAe,CAAC,QAAQ,OAAO,OAAO;GAC9D,MAAM,MAAM,MAAM,gBAAgB,QAAQ,cAAc,QAAQ,KAAK;GACrE,OAAO,MAAM;IAAE,GAAG;IAAS;GAAI,IAAI;EACrC,CAAC,CACH,EAC4B;CAC9B;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stored-agents-CIdYOdK0.js","names":["workspaceSnapshotConfigSchema"],"sources":["../src/server/schemas/memory-config.ts","../src/server/schemas/stored-agents.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { lastMessagesSchema, messageHistorySchema } from './message-history';\n\n/**\n * Shared memory configuration schemas for agent storage\n * These schemas match the SerializedMemoryConfig type from @mastra/core\n */\n\n/**\n * Semantic recall configuration for vector-based memory retrieval\n */\nexport const semanticRecallSchema = z.object({\n topK: z.number().describe('Number of semantically similar messages to retrieve'),\n messageRange: z\n .union([\n z.number(),\n z.object({\n before: z.number(),\n after: z.number(),\n }),\n ])\n .describe('Amount of surrounding context to include with each retrieved message'),\n scope: z.enum(['thread', 'resource']).optional().describe('Scope for semantic search queries'),\n threshold: z.number().min(0).max(1).optional().describe('Minimum similarity score threshold'),\n indexName: z.string().optional().describe('Index name for the vector store'),\n});\n\n/**\n * Title generation configuration\n * When stored, the model is serialized as a ModelRouterModelId string (provider/model-name format)\n */\nexport const titleGenerationSchema = z.union([\n z.boolean(),\n z.object({\n model: z\n .string()\n .optional()\n .describe(\"Model ID in format provider/model-name (ModelRouterModelId); defaults to the agent's own model\"),\n instructions: z.string().optional().describe('Custom instructions for title generation'),\n minMessages: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe('Minimum number of thread messages required before a title is generated'),\n emitEvent: z\n .boolean()\n .optional()\n .describe('Emit the generated title as a data-thread-title chunk on the run stream'),\n }),\n]);\n\n/**\n * Observation step configuration for observational memory\n */\nexport const serializedObservationConfigSchema = z.object({\n model: z.string().optional().describe('Observer model ID'),\n messageTokens: z.number().optional().describe('Token threshold that triggers observation'),\n modelSettings: z.record(z.string(), z.unknown()).optional().describe('Model settings (temperature, etc.)'),\n providerOptions: z\n .record(z.string(), z.record(z.string(), z.unknown()).optional())\n .optional()\n .describe('Provider-specific options'),\n maxTokensPerBatch: z.number().optional().describe('Maximum tokens per batch'),\n bufferTokens: z\n .union([z.number(), z.literal(false)])\n .optional()\n .describe('Async buffering interval or false'),\n bufferActivation: z.number().optional().describe('Ratio of buffered observations to activate'),\n blockAfter: z.number().optional().describe('Token threshold for synchronous blocking'),\n});\n\n/**\n * Reflection step configuration for observational memory\n */\nexport const serializedReflectionConfigSchema = z.object({\n model: z.string().optional().describe('Reflector model ID'),\n observationTokens: z.number().optional().describe('Token threshold that triggers reflection'),\n modelSettings: z.record(z.string(), z.unknown()).optional().describe('Model settings (temperature, etc.)'),\n providerOptions: z\n .record(z.string(), z.record(z.string(), z.unknown()).optional())\n .optional()\n .describe('Provider-specific options'),\n blockAfter: z.number().optional().describe('Token threshold for synchronous blocking'),\n bufferActivation: z.number().optional().describe('Ratio for async reflection buffering'),\n});\n\n/**\n * Serialized observational memory configuration\n */\nexport const serializedObservationalMemoryConfigObjectSchema = z.object({\n model: z.string().optional().describe('Model ID for both Observer and Reflector'),\n scope: z.enum(['resource', 'thread']).optional().describe('Memory scope'),\n shareTokenBudget: z.boolean().optional().describe('Share token budget between messages and observations'),\n observation: serializedObservationConfigSchema.optional().describe('Observation step configuration'),\n reflection: serializedReflectionConfigSchema.optional().describe('Reflection step configuration'),\n});\n\nexport const serializedObservationalMemoryConfigSchema = z.union([\n z.boolean(),\n serializedObservationalMemoryConfigObjectSchema,\n]);\n\n/**\n * Serialized memory configuration matching SerializedMemoryConfig from @mastra/core\n *\n * Note: workingMemory and threads are omitted as they are not part of SerializedMemoryConfig\n * @see packages/core/src/memory/types.ts\n */\nexport const serializedMemoryConfigSchema = z\n .object({\n vector: z\n .union([z.string(), z.literal(false)])\n .optional()\n .describe('Vector database identifier or false to disable'),\n options: z\n .object({\n readOnly: z.boolean().optional(),\n lastMessages: lastMessagesSchema.optional(),\n messageHistory: messageHistorySchema.optional(),\n semanticRecall: z.union([z.boolean(), semanticRecallSchema]).optional(),\n generateTitle: titleGenerationSchema.optional(),\n })\n .optional()\n .describe('Memory behavior configuration, excluding workingMemory and threads'),\n embedder: z\n .string()\n .optional()\n .describe('Embedding model ID in the format \"provider/model\" (e.g., \"openai/text-embedding-3-small\")'),\n embedderOptions: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Options to pass to the embedder, omitting telemetry'),\n observationalMemory: serializedObservationalMemoryConfigSchema\n .optional()\n .describe('Serialized observational memory configuration'),\n })\n .refine(\n data => {\n // If semanticRecall is enabled (true or object), both vector and embedder are required\n const semanticRecall = data.options?.semanticRecall;\n const semanticRecallEnabled =\n semanticRecall === true || (typeof semanticRecall === 'object' && semanticRecall !== null);\n\n if (semanticRecallEnabled) {\n // vector must be a string (not false or undefined)\n const hasVector = typeof data.vector === 'string' && data.vector.length > 0;\n // embedder must be defined\n const hasEmbedder = typeof data.embedder === 'string' && data.embedder.length > 0;\n\n return hasVector && hasEmbedder;\n }\n return true;\n },\n {\n message: 'Semantic recall requires both vector and embedder to be configured',\n path: ['options', 'semanticRecall'],\n },\n );\n","import { z } from 'zod/v4';\nimport { paginationInfoSchema, createPagePaginationSchema, statusQuerySchema } from './common';\nimport { defaultOptionsSchema } from './default-options';\nimport { serializedMemoryConfigSchema } from './memory-config';\nimport { ruleGroupSchema } from './rule-group';\nimport { workspaceSnapshotConfigSchema } from './stored-workspaces';\nimport { toolProvidersSchema } from './tool-providers';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\n/**\n * Path parameter for stored agent ID\n */\nexport const storedAgentIdPathParams = z.object({\n storedAgentId: z.string().describe('Unique identifier for the stored agent'),\n});\n\n// ============================================================================\n// Query Parameter Schemas\n// ============================================================================\n\n/**\n * Storage order by configuration\n */\nconst storageOrderBySchema = z.object({\n field: z.enum(['createdAt', 'updatedAt']).optional(),\n direction: z.enum(['ASC', 'DESC']).optional(),\n});\n\nexport { statusQuerySchema };\n\n/**\n * GET /stored/agents - List stored agents\n */\nexport const listStoredAgentsQuerySchema = createPagePaginationSchema(100).extend({\n orderBy: storageOrderBySchema.optional(),\n status: z\n .enum(['draft', 'published', 'archived'])\n .optional()\n .default('published')\n .describe('Filter agents by status (defaults to published)'),\n authorId: z.string().optional().describe('Filter agents by author identifier'),\n visibility: z.enum(['public']).optional().describe('Filter to only public agents'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Filter agents by metadata key-value pairs'),\n favoritedOnly: z\n .stringbool()\n .optional()\n .describe('When true, return only agents favorited by the caller (requires the `favorites` EE feature)'),\n pinFavoritedFor: z\n .string()\n .optional()\n .describe(\n 'When set, treat the given subject (user/role) as the favoriting principal for `favoritedOnly` instead of the caller',\n ),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\n/**\n * Scorer config schema with optional sampling and rules\n */\nconst scorerConfigSchema = z.object({\n description: z.string().optional(),\n sampling: z\n .union([\n z.object({ type: z.literal('none') }),\n z.object({ type: z.literal('ratio'), rate: z.number().min(0).max(1) }),\n ])\n .optional(),\n rules: ruleGroupSchema.optional(),\n});\n\n/**\n * Agent instruction block schema for prompt-block-based instructions.\n */\nconst agentInstructionBlockSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), content: z.string() }),\n z.object({ type: z.literal('prompt_block_ref'), id: z.string() }),\n z.object({ type: z.literal('prompt_block'), content: z.string(), rules: ruleGroupSchema.optional() }),\n]);\n\n/**\n * Creates a schema for a field that can be either a static value or an array of conditional variants.\n * Each variant has a `value` and an optional `rules` (RuleGroup) that determines when it applies.\n */\nfunction conditionalFieldSchema<T extends z.ZodTypeAny>(valueSchema: T) {\n const variantSchema = z.object({\n value: valueSchema,\n rules: ruleGroupSchema.optional(),\n });\n return z.union([valueSchema, z.array(variantSchema)]);\n}\n\n/**\n * Instructions can be a plain string or an array of instruction blocks (text + prompt_block references).\n */\nexport const instructionsSchema = z\n .union([z.string(), z.array(agentInstructionBlockSchema)])\n .describe('System instructions for the agent (string or array of instruction blocks)');\n\n/** Base model config schema (reused across snapshot and response schemas) */\nconst modelConfigSchema = z\n .object({\n provider: z.string().describe('Model provider (e.g., openai, anthropic)'),\n name: z.string().describe('Model name (e.g., gpt-4o, claude-3-opus)'),\n })\n .passthrough();\n\n/** Per-tool config schema */\nconst toolConfigSchema = z.object({ description: z.string().optional(), rules: ruleGroupSchema.optional() });\n\n/** Base tools config schema */\nconst toolsConfigSchema = z.record(z.string(), toolConfigSchema);\n\n/** MCP client tools config schema — specifies which tools to use from an MCP client/server */\nconst mcpClientToolsConfigSchema = z.object({\n tools: z.record(z.string(), toolConfigSchema).optional(),\n});\n\n/** Per-skill config schema */\nconst skillConfigSchema = z.object({\n description: z.string().optional(),\n instructions: z.string().optional(),\n pin: z.string().optional(),\n strategy: z.enum(['latest', 'live']).optional(),\n});\n\n/** Skills config: skill IDs mapped to per-skill config */\nconst skillsConfigSchema = z.record(z.string(), skillConfigSchema);\n\n/** Workspace reference: a stored workspace ID, inline config, or a registered workspace provider */\nconst workspaceRefSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('id'), workspaceId: z.string() }),\n z.object({ type: z.literal('inline'), config: workspaceSnapshotConfigSchema }),\n z.object({\n type: z.literal('provider'),\n provider: z.string().describe('Workspace provider identifier'),\n config: z.record(z.string(), z.unknown()).describe('Provider-specific configuration'),\n }),\n]);\n\n/** Screencast options for streaming browser frames */\nconst screencastOptionsSchema = z.object({\n format: z.enum(['jpeg', 'png']).optional().describe('Image format (default: jpeg)'),\n quality: z.number().min(0).max(100).optional().describe('JPEG quality 0-100 (default: 80)'),\n maxWidth: z.number().optional().describe('Max width in pixels (default: 1280)'),\n maxHeight: z.number().optional().describe('Max height in pixels (default: 720)'),\n everyNthFrame: z.number().optional().describe('Capture every Nth frame (default: 1)'),\n});\n\n/** Browser config: serializable browser configuration for stored agents */\nconst browserConfigSchema = z.object({\n provider: z.string().describe('Browser provider type (e.g., stagehand, playwright)'),\n headless: z.boolean().optional().describe('Run browser in headless mode (default: true)'),\n viewport: z\n .object({\n width: z.number().describe('Viewport width in pixels'),\n height: z.number().describe('Viewport height in pixels'),\n })\n .optional()\n .describe('Browser viewport dimensions'),\n timeout: z.number().optional().describe('Default timeout in milliseconds (default: 10000)'),\n screencast: screencastOptionsSchema.optional().describe('Screencast options for streaming browser frames'),\n});\n\n/** Browser reference: inline browser configuration */\nconst browserRefSchema = z.object({\n type: z.literal('inline'),\n config: browserConfigSchema,\n});\n\n/**\n * Processor phase enum matching ProcessorPhase type\n */\nconst processorPhaseSchema = z.enum([\n 'processInput',\n 'processInputStep',\n 'processOutputStream',\n 'processOutputResult',\n 'processOutputStep',\n 'processToolResult',\n]);\n\n/**\n * A single processor step in a stored processor graph.\n */\nconst processorGraphStepSchema = z.object({\n id: z.string().describe('Unique ID for this step within the graph'),\n providerId: z.string().describe('ProcessorProvider ID that creates this processor'),\n config: z.record(z.string(), z.unknown()).describe('Configuration matching the provider configSchema'),\n enabledPhases: z.array(processorPhaseSchema).min(1).describe('Which processor phases to enable'),\n});\n\n/**\n * Processor graph entry schema.\n * Simplified version of SerializedStepFlowEntry, supporting step, parallel, and conditional.\n *\n * Uses a fixed nesting depth (3 levels) to avoid infinite recursion\n * when converting to JSON Schema / OpenAPI.\n */\n\n/** Depth 3 (leaf): only step entries allowed */\nconst processorGraphEntryDepth3 = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n]);\n\n/** Depth 2: step, parallel, and conditional — children limited to depth 3 */\nconst processorGraphEntryDepth2 = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n z.object({ type: z.literal('parallel'), branches: z.array(z.array(processorGraphEntryDepth3)) }),\n z.object({\n type: z.literal('conditional'),\n conditions: z.array(\n z.object({\n steps: z.array(processorGraphEntryDepth3),\n rules: ruleGroupSchema.optional(),\n }),\n ),\n }),\n]);\n\n/** Depth 1 (top-level): step, parallel, and conditional — children limited to depth 2 */\nconst processorGraphEntrySchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n z.object({ type: z.literal('parallel'), branches: z.array(z.array(processorGraphEntryDepth2)) }),\n z.object({\n type: z.literal('conditional'),\n conditions: z.array(\n z.object({\n steps: z.array(processorGraphEntryDepth2),\n rules: ruleGroupSchema.optional(),\n }),\n ),\n }),\n]);\n\n/**\n * A stored processor graph representing a pipeline of processors.\n */\nconst storedProcessorGraphSchema = z.object({\n steps: z.array(processorGraphEntrySchema).describe('Ordered list of processor graph entries'),\n});\n\n/**\n * Agent snapshot config fields (name, description, instructions, model, tools, etc.)\n * These live in version snapshots, not on the thin agent record.\n *\n * Fields that support conditional variants (StorageConditionalField) can be either\n * a static value OR an array of { value, rules? } variants evaluated at request time.\n */\n/**\n * Serializable durable-execution opt-in. Mirrors `StorageDurableConfig`:\n * `cache`/`pubsub` are live runtime objects and cannot be persisted, so they are\n * not accepted here. Intentionally not a conditional field — durability is\n * decided when the agent is registered, not per request.\n */\nconst durableConfigSchema = z.union([\n z.boolean(),\n z.object({\n maxSteps: z.number().int().positive().optional(),\n cleanupTimeoutMs: z.number().int().nonnegative().optional(),\n }),\n]);\n\nconst snapshotConfigSchema = z.object({\n name: z.string().describe('Name of the agent'),\n description: z.string().optional().describe('Description of the agent'),\n instructions: instructionsSchema,\n model: conditionalFieldSchema(modelConfigSchema).describe(\n 'Model configuration — static value or array of conditional variants',\n ),\n tools: conditionalFieldSchema(toolsConfigSchema)\n .optional()\n .describe('Tool keys mapped to per-tool config — static or conditional'),\n defaultOptions: conditionalFieldSchema(defaultOptionsSchema)\n .optional()\n .describe('Default options for generate/stream calls — static or conditional'),\n workflows: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Workflow keys with optional per-workflow config — static or conditional'),\n agents: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Agent keys with optional per-agent config — static or conditional'),\n integrationTools: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of tool provider IDs to their tool configurations — static or conditional'),\n toolProviders: conditionalFieldSchema(toolProvidersSchema)\n .optional()\n .describe(\n 'Tool provider connections and per-tool config (provider-agnostic). Coexists with the deprecated `integrationTools` field.',\n ),\n mcpClients: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of stored MCP client IDs to their tool configurations — static or conditional'),\n inputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Input processor graph — static or conditional'),\n outputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Output processor graph — static or conditional'),\n memory: conditionalFieldSchema(serializedMemoryConfigSchema)\n .optional()\n .describe('Memory configuration — static or conditional'),\n scorers: conditionalFieldSchema(z.record(z.string(), scorerConfigSchema))\n .optional()\n .describe('Scorer keys with optional sampling config — static or conditional'),\n skills: conditionalFieldSchema(skillsConfigSchema)\n .optional()\n .describe('Skill IDs mapped to per-skill config — static or conditional'),\n workspace: conditionalFieldSchema(workspaceRefSchema)\n .optional()\n .describe('Workspace reference (stored ID or inline config) — static or conditional'),\n browser: z\n .union([conditionalFieldSchema(browserRefSchema), z.boolean(), z.null()])\n .optional()\n .describe('Browser configuration — object config, true (apply default), false/null (disable)'),\n requestContextSchema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('JSON Schema defining valid request context variables for conditional rule evaluation'),\n durable: durableConfigSchema\n .optional()\n .describe(\n 'Opt this agent into durable execution when it is hydrated. Cache and pubsub are inherited from the Mastra instance; without distributed backends durability is process-local. Does not enable automatic recovery — that stays `recovery.durableAgents`.',\n ),\n});\n\n/**\n * Agent metadata fields (authorId, metadata, visibility) that live on the thin agent record.\n */\nconst agentMetadataSchema = z.object({\n authorId: z.string().optional().describe('Author identifier for multi-tenant filtering'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata for the agent'),\n visibility: z\n .enum(['private', 'public'])\n .optional()\n .describe('Agent visibility: private (owner/admin only) or public (any reader)'),\n});\n\n/**\n * Snapshot config schema for create where `model` is optional. When omitted, the\n * builder applies `defaults.model` from `/editor/builder/settings` server-side.\n */\nconst snapshotConfigCreateSchema = snapshotConfigSchema.extend({\n model: conditionalFieldSchema(modelConfigSchema)\n .optional()\n .describe(\n 'Model configuration — static value or array of conditional variants. ' +\n 'When omitted, the builder default model is applied server-side.',\n ),\n});\n\n/**\n * POST /stored/agents - Create stored agent body\n * Flat union of agent-record fields + config fields\n * The id is optional — if not provided, it will be derived from the agent name via slugify.\n */\nexport const createStoredAgentBodySchema = z\n .object({\n id: z.string().optional().describe('Unique identifier for the agent. If not provided, derived from name.'),\n authorId: z.string().optional().describe('Author identifier for multi-tenant filtering'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata for the agent'),\n visibility: z\n .enum(['private', 'public'])\n .optional()\n .describe('Agent visibility: private (owner/admin only) or public (any reader)'),\n autoPublish: z\n .boolean()\n .optional()\n .describe(\n 'Publish the initial version so the agent resolves at status=\"published\". Defaults to true when omitted. ' +\n 'Pass false to stage the agent as an unpublished draft — useful when overriding a code-defined agent, ' +\n 'whose code definition keeps serving traffic until the override is published.',\n ),\n })\n .merge(snapshotConfigCreateSchema);\n\n/**\n * Snapshot config schema for updates where nullable fields (like memory) can be set to null to clear them.\n */\nconst snapshotConfigUpdateSchema = snapshotConfigSchema.extend({\n memory: z\n .union([conditionalFieldSchema(serializedMemoryConfigSchema), z.null()])\n .optional()\n .describe('Memory configuration — static, conditional, or null to disable memory'),\n});\n\n/**\n * PATCH /stored/agents/:storedAgentId - Update stored agent body\n * Optional metadata-level fields + optional config fields\n */\nexport const updateStoredAgentBodySchema = agentMetadataSchema\n .partial()\n .merge(snapshotConfigUpdateSchema.partial())\n .extend({\n changeMessage: z\n .string()\n .trim()\n .max(500)\n .optional()\n .describe('Optional message describing the changes for the auto-created version'),\n autoPublish: z\n .boolean()\n .optional()\n .describe('Immediately activate the auto-created version. Defaults to false when omitted.'),\n });\n\nexport const exportStoredAgentBodySchema = snapshotConfigUpdateSchema.partial();\n\nexport const openStoredAgentChangeRequestBodySchema = exportStoredAgentBodySchema.extend({\n changeMessage: z.string().trim().max(500).optional(),\n userName: z.string().trim().min(1).max(120).optional(),\n inspectOnly: z.boolean().optional(),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\n/**\n * Resolved author object — server-side enrichment of `authorId` against the\n * configured auth provider. Only `id` is required; the other fields mirror\n * what `/auth/me` exposes and are optional because providers may not return\n * every field.\n */\nexport const resolvedAuthorSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n email: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\n/**\n * Stored agent object schema (resolved response: thin record + version config)\n * Represents StorageResolvedAgentType\n */\nexport const storedAgentSchema = z.object({\n // Thin agent record fields\n id: z.string(),\n status: z.string().describe('Agent status: draft or published'),\n activeVersionId: z.string().optional(),\n authorId: z.string().optional(),\n author: resolvedAuthorSchema.optional().describe('Resolved author identity (when an auth provider is configured)'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n visibility: z.enum(['private', 'public']).optional(),\n favoriteCount: z.number().int().nonnegative().optional().describe('Number of users who have favorited this agent'),\n isFavorited: z.boolean().optional().describe('Whether the requesting user has favorited this agent'),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n // Version snapshot config fields (resolved from active version)\n name: z.string().describe('Name of the agent'),\n description: z.string().optional().describe('Description of the agent'),\n instructions: instructionsSchema,\n model: conditionalFieldSchema(modelConfigSchema).describe(\n 'Model configuration — static value or array of conditional variants',\n ),\n tools: conditionalFieldSchema(toolsConfigSchema)\n .optional()\n .describe('Tool keys mapped to per-tool config — static or conditional'),\n defaultOptions: conditionalFieldSchema(defaultOptionsSchema)\n .optional()\n .describe('Default options for generate/stream calls — static or conditional'),\n workflows: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Workflow keys with optional per-workflow config — static or conditional'),\n agents: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Agent keys with optional per-agent config — static or conditional'),\n integrationTools: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of tool provider IDs to their tool configurations — static or conditional'),\n toolProviders: conditionalFieldSchema(toolProvidersSchema)\n .optional()\n .describe(\n 'Tool provider connections and per-tool config (provider-agnostic). Coexists with the deprecated `integrationTools` field.',\n ),\n mcpClients: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of stored MCP client IDs to their tool configurations — static or conditional'),\n inputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Input processor graph — static or conditional'),\n outputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Output processor graph — static or conditional'),\n memory: conditionalFieldSchema(serializedMemoryConfigSchema)\n .optional()\n .describe('Memory configuration — static or conditional'),\n scorers: conditionalFieldSchema(z.record(z.string(), scorerConfigSchema))\n .optional()\n .describe('Scorer keys with optional sampling config — static or conditional'),\n skills: conditionalFieldSchema(skillsConfigSchema)\n .optional()\n .describe('Skill IDs mapped to per-skill config — static or conditional'),\n workspace: conditionalFieldSchema(workspaceRefSchema)\n .optional()\n .describe('Workspace reference (stored ID or inline config) — static or conditional'),\n browser: z\n .union([conditionalFieldSchema(browserRefSchema), z.boolean(), z.null()])\n .optional()\n .describe('Browser configuration — object config, true (apply default), false/null (disable)'),\n requestContextSchema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('JSON Schema defining valid request context variables'),\n durable: durableConfigSchema.optional().describe('Whether this agent is hydrated with durable execution enabled'),\n});\n\n/**\n * Response for GET /stored/agents\n */\nexport const listStoredAgentsResponseSchema = paginationInfoSchema.extend({\n agents: z.array(storedAgentSchema),\n});\n\n/**\n * Response for GET /stored/agents/:storedAgentId\n */\nexport const getStoredAgentResponseSchema = storedAgentSchema;\n\n/**\n * Response for POST /stored/agents\n */\nexport const createStoredAgentResponseSchema = storedAgentSchema;\n\n/**\n * Response for PATCH /stored/agents/:storedAgentId\n *\n * The response can be either:\n * 1. A thin agent record (no version) - only has id, status, dates, etc.\n * 2. A resolved agent (with version) - has all config fields from the version\n *\n * We use a union to handle both cases properly.\n */\nexport const updateStoredAgentResponseSchema = z.union([\n // Thin agent record (no version config)\n z.object({\n id: z.string(),\n status: z.string(),\n activeVersionId: z.string().optional(),\n authorId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n visibility: z.enum(['private', 'public']).optional(),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n }),\n // Resolved agent (thin record + version config)\n storedAgentSchema,\n]);\n\n/**\n * Response for DELETE /stored/agents/:storedAgentId\n */\nexport const deleteStoredAgentResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\n/**\n * Response for GET /stored/agents/:storedAgentId/dependents\n *\n * `dependents` lists caller-readable stored agents whose resolved `agents` map\n * references the target. Includes both public and the caller's own private\n * agents — anything the caller already has read access to.\n * `hiddenCount` aggregates references from agents the caller cannot read\n * (cross-workspace private agents). Only populated when the target agent is\n * public, to avoid leaking cross-workspace structure for private targets.\n */\nexport const getStoredAgentDependentsResponseSchema = z.object({\n dependents: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n }),\n ),\n hiddenCount: z.number().int().nonnegative(),\n});\n\nexport const exportStoredAgentResponseSchema = z.object({\n agentId: z.string(),\n fileName: z.string(),\n content: z.string(),\n config: z.record(z.string(), z.unknown()),\n});\n\nexport const openStoredAgentChangeRequestResponseSchema = z.object({\n id: z.union([z.string(), z.number()]).optional(),\n url: z.string(),\n ref: z.string().optional(),\n});\n\n// ============================================================================\n// Preview Instructions Schemas\n// ============================================================================\n\n/**\n * POST /stored/agents/preview-instructions - Preview resolved instructions\n */\nexport const previewInstructionsBodySchema = z.object({\n blocks: z.array(agentInstructionBlockSchema).describe('Array of instruction blocks to resolve'),\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .describe('Request context for variable interpolation and rule evaluation'),\n});\n\n/**\n * Response for POST /stored/agents/preview-instructions\n */\nexport const previewInstructionsResponseSchema = z.object({\n result: z.string().describe('The resolved instructions string'),\n});\n\n/**\n * Exported for use in agent-versions.ts schemas\n */\nexport {\n snapshotConfigSchema,\n scorerConfigSchema,\n conditionalFieldSchema,\n modelConfigSchema,\n storedProcessorGraphSchema,\n processorGraphStepSchema,\n processorGraphEntrySchema,\n processorPhaseSchema,\n toolConfigSchema,\n toolsConfigSchema,\n};\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,uBAAuB,EAAE,OAAO;CAC3C,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,qDAAqD;CAC/E,cAAc,EACX,MAAM,CACL,EAAE,OAAO,GACT,EAAE,OAAO;EACP,QAAQ,EAAE,OAAO;EACjB,OAAO,EAAE,OAAO;CAClB,CAAC,CACH,CAAC,CAAC,CACD,SAAS,sEAAsE;CAClF,OAAO,EAAE,KAAK,CAAC,UAAU,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,mCAAmC;CAC7F,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,oCAAoC;CAC5F,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,iCAAiC;AAC7E,CAAC;;;;;AAMD,MAAa,wBAAwB,EAAE,MAAM,CAC3C,EAAE,QAAQ,GACV,EAAE,OAAO;CACP,OAAO,EACJ,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,gGAAgG;CAC5G,cAAc,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,0CAA0C;CACvF,aAAa,EACV,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,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AAS,wCAAwC;CAC9F,SAAS,EACN,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAC/B,SAAS,CAAC,CACV,QAAQ,CAAC,CAAC,CAAC,CACX,SAAS,gEAAgE;AAC9E,CAAC;;;;AAKD,MAAa,oCAAoC,EAAE,OAAO,EACxD,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS,kCAAkC,EAChE,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stored-agents-DTgigNRY.cjs","names":["z","lastMessagesSchema","messageHistorySchema","z","createPagePaginationSchema","ruleGroupSchema","workspaceSnapshotConfigSchema","defaultOptionsSchema","toolProvidersSchema","paginationInfoSchema"],"sources":["../src/server/schemas/memory-config.ts","../src/server/schemas/stored-agents.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { lastMessagesSchema, messageHistorySchema } from './message-history';\n\n/**\n * Shared memory configuration schemas for agent storage\n * These schemas match the SerializedMemoryConfig type from @mastra/core\n */\n\n/**\n * Semantic recall configuration for vector-based memory retrieval\n */\nexport const semanticRecallSchema = z.object({\n topK: z.number().describe('Number of semantically similar messages to retrieve'),\n messageRange: z\n .union([\n z.number(),\n z.object({\n before: z.number(),\n after: z.number(),\n }),\n ])\n .describe('Amount of surrounding context to include with each retrieved message'),\n scope: z.enum(['thread', 'resource']).optional().describe('Scope for semantic search queries'),\n threshold: z.number().min(0).max(1).optional().describe('Minimum similarity score threshold'),\n indexName: z.string().optional().describe('Index name for the vector store'),\n});\n\n/**\n * Title generation configuration\n * When stored, the model is serialized as a ModelRouterModelId string (provider/model-name format)\n */\nexport const titleGenerationSchema = z.union([\n z.boolean(),\n z.object({\n model: z\n .string()\n .optional()\n .describe(\"Model ID in format provider/model-name (ModelRouterModelId); defaults to the agent's own model\"),\n instructions: z.string().optional().describe('Custom instructions for title generation'),\n minMessages: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe('Minimum number of thread messages required before a title is generated'),\n emitEvent: z\n .boolean()\n .optional()\n .describe('Emit the generated title as a data-thread-title chunk on the run stream'),\n }),\n]);\n\n/**\n * Observation step configuration for observational memory\n */\nexport const serializedObservationConfigSchema = z.object({\n model: z.string().optional().describe('Observer model ID'),\n messageTokens: z.number().optional().describe('Token threshold that triggers observation'),\n modelSettings: z.record(z.string(), z.unknown()).optional().describe('Model settings (temperature, etc.)'),\n providerOptions: z\n .record(z.string(), z.record(z.string(), z.unknown()).optional())\n .optional()\n .describe('Provider-specific options'),\n maxTokensPerBatch: z.number().optional().describe('Maximum tokens per batch'),\n bufferTokens: z\n .union([z.number(), z.literal(false)])\n .optional()\n .describe('Async buffering interval or false'),\n bufferActivation: z.number().optional().describe('Ratio of buffered observations to activate'),\n blockAfter: z.number().optional().describe('Token threshold for synchronous blocking'),\n});\n\n/**\n * Reflection step configuration for observational memory\n */\nexport const serializedReflectionConfigSchema = z.object({\n model: z.string().optional().describe('Reflector model ID'),\n observationTokens: z.number().optional().describe('Token threshold that triggers reflection'),\n modelSettings: z.record(z.string(), z.unknown()).optional().describe('Model settings (temperature, etc.)'),\n providerOptions: z\n .record(z.string(), z.record(z.string(), z.unknown()).optional())\n .optional()\n .describe('Provider-specific options'),\n blockAfter: z.number().optional().describe('Token threshold for synchronous blocking'),\n bufferActivation: z.number().optional().describe('Ratio for async reflection buffering'),\n});\n\n/**\n * Serialized observational memory configuration\n */\nexport const serializedObservationalMemoryConfigObjectSchema = z.object({\n model: z.string().optional().describe('Model ID for both Observer and Reflector'),\n scope: z.enum(['resource', 'thread']).optional().describe('Memory scope'),\n shareTokenBudget: z.boolean().optional().describe('Share token budget between messages and observations'),\n observation: serializedObservationConfigSchema.optional().describe('Observation step configuration'),\n reflection: serializedReflectionConfigSchema.optional().describe('Reflection step configuration'),\n});\n\nexport const serializedObservationalMemoryConfigSchema = z.union([\n z.boolean(),\n serializedObservationalMemoryConfigObjectSchema,\n]);\n\n/**\n * Serialized memory configuration matching SerializedMemoryConfig from @mastra/core\n *\n * Note: workingMemory and threads are omitted as they are not part of SerializedMemoryConfig\n * @see packages/core/src/memory/types.ts\n */\nexport const serializedMemoryConfigSchema = z\n .object({\n vector: z\n .union([z.string(), z.literal(false)])\n .optional()\n .describe('Vector database identifier or false to disable'),\n options: z\n .object({\n readOnly: z.boolean().optional(),\n lastMessages: lastMessagesSchema.optional(),\n messageHistory: messageHistorySchema.optional(),\n semanticRecall: z.union([z.boolean(), semanticRecallSchema]).optional(),\n generateTitle: titleGenerationSchema.optional(),\n })\n .optional()\n .describe('Memory behavior configuration, excluding workingMemory and threads'),\n embedder: z\n .string()\n .optional()\n .describe('Embedding model ID in the format \"provider/model\" (e.g., \"openai/text-embedding-3-small\")'),\n embedderOptions: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Options to pass to the embedder, omitting telemetry'),\n observationalMemory: serializedObservationalMemoryConfigSchema\n .optional()\n .describe('Serialized observational memory configuration'),\n })\n .refine(\n data => {\n // If semanticRecall is enabled (true or object), both vector and embedder are required\n const semanticRecall = data.options?.semanticRecall;\n const semanticRecallEnabled =\n semanticRecall === true || (typeof semanticRecall === 'object' && semanticRecall !== null);\n\n if (semanticRecallEnabled) {\n // vector must be a string (not false or undefined)\n const hasVector = typeof data.vector === 'string' && data.vector.length > 0;\n // embedder must be defined\n const hasEmbedder = typeof data.embedder === 'string' && data.embedder.length > 0;\n\n return hasVector && hasEmbedder;\n }\n return true;\n },\n {\n message: 'Semantic recall requires both vector and embedder to be configured',\n path: ['options', 'semanticRecall'],\n },\n );\n","import { z } from 'zod/v4';\nimport { paginationInfoSchema, createPagePaginationSchema, statusQuerySchema } from './common';\nimport { defaultOptionsSchema } from './default-options';\nimport { serializedMemoryConfigSchema } from './memory-config';\nimport { ruleGroupSchema } from './rule-group';\nimport { workspaceSnapshotConfigSchema } from './stored-workspaces';\nimport { toolProvidersSchema } from './tool-providers';\n\n// ============================================================================\n// Path Parameter Schemas\n// ============================================================================\n\n/**\n * Path parameter for stored agent ID\n */\nexport const storedAgentIdPathParams = z.object({\n storedAgentId: z.string().describe('Unique identifier for the stored agent'),\n});\n\n// ============================================================================\n// Query Parameter Schemas\n// ============================================================================\n\n/**\n * Storage order by configuration\n */\nconst storageOrderBySchema = z.object({\n field: z.enum(['createdAt', 'updatedAt']).optional(),\n direction: z.enum(['ASC', 'DESC']).optional(),\n});\n\nexport { statusQuerySchema };\n\n/**\n * GET /stored/agents - List stored agents\n */\nexport const listStoredAgentsQuerySchema = createPagePaginationSchema(100).extend({\n orderBy: storageOrderBySchema.optional(),\n status: z\n .enum(['draft', 'published', 'archived'])\n .optional()\n .default('published')\n .describe('Filter agents by status (defaults to published)'),\n authorId: z.string().optional().describe('Filter agents by author identifier'),\n visibility: z.enum(['public']).optional().describe('Filter to only public agents'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Filter agents by metadata key-value pairs'),\n favoritedOnly: z\n .stringbool()\n .optional()\n .describe('When true, return only agents favorited by the caller (requires the `favorites` EE feature)'),\n pinFavoritedFor: z\n .string()\n .optional()\n .describe(\n 'When set, treat the given subject (user/role) as the favoriting principal for `favoritedOnly` instead of the caller',\n ),\n});\n\n// ============================================================================\n// Body Parameter Schemas\n// ============================================================================\n\n/**\n * Scorer config schema with optional sampling and rules\n */\nconst scorerConfigSchema = z.object({\n description: z.string().optional(),\n sampling: z\n .union([\n z.object({ type: z.literal('none') }),\n z.object({ type: z.literal('ratio'), rate: z.number().min(0).max(1) }),\n ])\n .optional(),\n rules: ruleGroupSchema.optional(),\n});\n\n/**\n * Agent instruction block schema for prompt-block-based instructions.\n */\nconst agentInstructionBlockSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), content: z.string() }),\n z.object({ type: z.literal('prompt_block_ref'), id: z.string() }),\n z.object({ type: z.literal('prompt_block'), content: z.string(), rules: ruleGroupSchema.optional() }),\n]);\n\n/**\n * Creates a schema for a field that can be either a static value or an array of conditional variants.\n * Each variant has a `value` and an optional `rules` (RuleGroup) that determines when it applies.\n */\nfunction conditionalFieldSchema<T extends z.ZodTypeAny>(valueSchema: T) {\n const variantSchema = z.object({\n value: valueSchema,\n rules: ruleGroupSchema.optional(),\n });\n return z.union([valueSchema, z.array(variantSchema)]);\n}\n\n/**\n * Instructions can be a plain string or an array of instruction blocks (text + prompt_block references).\n */\nexport const instructionsSchema = z\n .union([z.string(), z.array(agentInstructionBlockSchema)])\n .describe('System instructions for the agent (string or array of instruction blocks)');\n\n/** Base model config schema (reused across snapshot and response schemas) */\nconst modelConfigSchema = z\n .object({\n provider: z.string().describe('Model provider (e.g., openai, anthropic)'),\n name: z.string().describe('Model name (e.g., gpt-4o, claude-3-opus)'),\n })\n .passthrough();\n\n/** Per-tool config schema */\nconst toolConfigSchema = z.object({ description: z.string().optional(), rules: ruleGroupSchema.optional() });\n\n/** Base tools config schema */\nconst toolsConfigSchema = z.record(z.string(), toolConfigSchema);\n\n/** MCP client tools config schema — specifies which tools to use from an MCP client/server */\nconst mcpClientToolsConfigSchema = z.object({\n tools: z.record(z.string(), toolConfigSchema).optional(),\n});\n\n/** Per-skill config schema */\nconst skillConfigSchema = z.object({\n description: z.string().optional(),\n instructions: z.string().optional(),\n pin: z.string().optional(),\n strategy: z.enum(['latest', 'live']).optional(),\n});\n\n/** Skills config: skill IDs mapped to per-skill config */\nconst skillsConfigSchema = z.record(z.string(), skillConfigSchema);\n\n/** Workspace reference: a stored workspace ID, inline config, or a registered workspace provider */\nconst workspaceRefSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('id'), workspaceId: z.string() }),\n z.object({ type: z.literal('inline'), config: workspaceSnapshotConfigSchema }),\n z.object({\n type: z.literal('provider'),\n provider: z.string().describe('Workspace provider identifier'),\n config: z.record(z.string(), z.unknown()).describe('Provider-specific configuration'),\n }),\n]);\n\n/** Screencast options for streaming browser frames */\nconst screencastOptionsSchema = z.object({\n format: z.enum(['jpeg', 'png']).optional().describe('Image format (default: jpeg)'),\n quality: z.number().min(0).max(100).optional().describe('JPEG quality 0-100 (default: 80)'),\n maxWidth: z.number().optional().describe('Max width in pixels (default: 1280)'),\n maxHeight: z.number().optional().describe('Max height in pixels (default: 720)'),\n everyNthFrame: z.number().optional().describe('Capture every Nth frame (default: 1)'),\n});\n\n/** Browser config: serializable browser configuration for stored agents */\nconst browserConfigSchema = z.object({\n provider: z.string().describe('Browser provider type (e.g., stagehand, playwright)'),\n headless: z.boolean().optional().describe('Run browser in headless mode (default: true)'),\n viewport: z\n .object({\n width: z.number().describe('Viewport width in pixels'),\n height: z.number().describe('Viewport height in pixels'),\n })\n .optional()\n .describe('Browser viewport dimensions'),\n timeout: z.number().optional().describe('Default timeout in milliseconds (default: 10000)'),\n screencast: screencastOptionsSchema.optional().describe('Screencast options for streaming browser frames'),\n});\n\n/** Browser reference: inline browser configuration */\nconst browserRefSchema = z.object({\n type: z.literal('inline'),\n config: browserConfigSchema,\n});\n\n/**\n * Processor phase enum matching ProcessorPhase type\n */\nconst processorPhaseSchema = z.enum([\n 'processInput',\n 'processInputStep',\n 'processOutputStream',\n 'processOutputResult',\n 'processOutputStep',\n 'processToolResult',\n]);\n\n/**\n * A single processor step in a stored processor graph.\n */\nconst processorGraphStepSchema = z.object({\n id: z.string().describe('Unique ID for this step within the graph'),\n providerId: z.string().describe('ProcessorProvider ID that creates this processor'),\n config: z.record(z.string(), z.unknown()).describe('Configuration matching the provider configSchema'),\n enabledPhases: z.array(processorPhaseSchema).min(1).describe('Which processor phases to enable'),\n});\n\n/**\n * Processor graph entry schema.\n * Simplified version of SerializedStepFlowEntry, supporting step, parallel, and conditional.\n *\n * Uses a fixed nesting depth (3 levels) to avoid infinite recursion\n * when converting to JSON Schema / OpenAPI.\n */\n\n/** Depth 3 (leaf): only step entries allowed */\nconst processorGraphEntryDepth3 = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n]);\n\n/** Depth 2: step, parallel, and conditional — children limited to depth 3 */\nconst processorGraphEntryDepth2 = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n z.object({ type: z.literal('parallel'), branches: z.array(z.array(processorGraphEntryDepth3)) }),\n z.object({\n type: z.literal('conditional'),\n conditions: z.array(\n z.object({\n steps: z.array(processorGraphEntryDepth3),\n rules: ruleGroupSchema.optional(),\n }),\n ),\n }),\n]);\n\n/** Depth 1 (top-level): step, parallel, and conditional — children limited to depth 2 */\nconst processorGraphEntrySchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('step'), step: processorGraphStepSchema }),\n z.object({ type: z.literal('parallel'), branches: z.array(z.array(processorGraphEntryDepth2)) }),\n z.object({\n type: z.literal('conditional'),\n conditions: z.array(\n z.object({\n steps: z.array(processorGraphEntryDepth2),\n rules: ruleGroupSchema.optional(),\n }),\n ),\n }),\n]);\n\n/**\n * A stored processor graph representing a pipeline of processors.\n */\nconst storedProcessorGraphSchema = z.object({\n steps: z.array(processorGraphEntrySchema).describe('Ordered list of processor graph entries'),\n});\n\n/**\n * Agent snapshot config fields (name, description, instructions, model, tools, etc.)\n * These live in version snapshots, not on the thin agent record.\n *\n * Fields that support conditional variants (StorageConditionalField) can be either\n * a static value OR an array of { value, rules? } variants evaluated at request time.\n */\n/**\n * Serializable durable-execution opt-in. Mirrors `StorageDurableConfig`:\n * `cache`/`pubsub` are live runtime objects and cannot be persisted, so they are\n * not accepted here. Intentionally not a conditional field — durability is\n * decided when the agent is registered, not per request.\n */\nconst durableConfigSchema = z.union([\n z.boolean(),\n z.object({\n maxSteps: z.number().int().positive().optional(),\n cleanupTimeoutMs: z.number().int().nonnegative().optional(),\n }),\n]);\n\nconst snapshotConfigSchema = z.object({\n name: z.string().describe('Name of the agent'),\n description: z.string().optional().describe('Description of the agent'),\n instructions: instructionsSchema,\n model: conditionalFieldSchema(modelConfigSchema).describe(\n 'Model configuration — static value or array of conditional variants',\n ),\n tools: conditionalFieldSchema(toolsConfigSchema)\n .optional()\n .describe('Tool keys mapped to per-tool config — static or conditional'),\n defaultOptions: conditionalFieldSchema(defaultOptionsSchema)\n .optional()\n .describe('Default options for generate/stream calls — static or conditional'),\n workflows: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Workflow keys with optional per-workflow config — static or conditional'),\n agents: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Agent keys with optional per-agent config — static or conditional'),\n integrationTools: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of tool provider IDs to their tool configurations — static or conditional'),\n toolProviders: conditionalFieldSchema(toolProvidersSchema)\n .optional()\n .describe(\n 'Tool provider connections and per-tool config (provider-agnostic). Coexists with the deprecated `integrationTools` field.',\n ),\n mcpClients: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of stored MCP client IDs to their tool configurations — static or conditional'),\n inputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Input processor graph — static or conditional'),\n outputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Output processor graph — static or conditional'),\n memory: conditionalFieldSchema(serializedMemoryConfigSchema)\n .optional()\n .describe('Memory configuration — static or conditional'),\n scorers: conditionalFieldSchema(z.record(z.string(), scorerConfigSchema))\n .optional()\n .describe('Scorer keys with optional sampling config — static or conditional'),\n skills: conditionalFieldSchema(skillsConfigSchema)\n .optional()\n .describe('Skill IDs mapped to per-skill config — static or conditional'),\n workspace: conditionalFieldSchema(workspaceRefSchema)\n .optional()\n .describe('Workspace reference (stored ID or inline config) — static or conditional'),\n browser: z\n .union([conditionalFieldSchema(browserRefSchema), z.boolean(), z.null()])\n .optional()\n .describe('Browser configuration — object config, true (apply default), false/null (disable)'),\n requestContextSchema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('JSON Schema defining valid request context variables for conditional rule evaluation'),\n durable: durableConfigSchema\n .optional()\n .describe(\n 'Opt this agent into durable execution when it is hydrated. Cache and pubsub are inherited from the Mastra instance; without distributed backends durability is process-local. Does not enable automatic recovery — that stays `recovery.durableAgents`.',\n ),\n});\n\n/**\n * Agent metadata fields (authorId, metadata, visibility) that live on the thin agent record.\n */\nconst agentMetadataSchema = z.object({\n authorId: z.string().optional().describe('Author identifier for multi-tenant filtering'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata for the agent'),\n visibility: z\n .enum(['private', 'public'])\n .optional()\n .describe('Agent visibility: private (owner/admin only) or public (any reader)'),\n});\n\n/**\n * Snapshot config schema for create where `model` is optional. When omitted, the\n * builder applies `defaults.model` from `/editor/builder/settings` server-side.\n */\nconst snapshotConfigCreateSchema = snapshotConfigSchema.extend({\n model: conditionalFieldSchema(modelConfigSchema)\n .optional()\n .describe(\n 'Model configuration — static value or array of conditional variants. ' +\n 'When omitted, the builder default model is applied server-side.',\n ),\n});\n\n/**\n * POST /stored/agents - Create stored agent body\n * Flat union of agent-record fields + config fields\n * The id is optional — if not provided, it will be derived from the agent name via slugify.\n */\nexport const createStoredAgentBodySchema = z\n .object({\n id: z.string().optional().describe('Unique identifier for the agent. If not provided, derived from name.'),\n authorId: z.string().optional().describe('Author identifier for multi-tenant filtering'),\n metadata: z.record(z.string(), z.unknown()).optional().describe('Additional metadata for the agent'),\n visibility: z\n .enum(['private', 'public'])\n .optional()\n .describe('Agent visibility: private (owner/admin only) or public (any reader)'),\n autoPublish: z\n .boolean()\n .optional()\n .describe(\n 'Publish the initial version so the agent resolves at status=\"published\". Defaults to true when omitted. ' +\n 'Pass false to stage the agent as an unpublished draft — useful when overriding a code-defined agent, ' +\n 'whose code definition keeps serving traffic until the override is published.',\n ),\n })\n .merge(snapshotConfigCreateSchema);\n\n/**\n * Snapshot config schema for updates where nullable fields (like memory) can be set to null to clear them.\n */\nconst snapshotConfigUpdateSchema = snapshotConfigSchema.extend({\n memory: z\n .union([conditionalFieldSchema(serializedMemoryConfigSchema), z.null()])\n .optional()\n .describe('Memory configuration — static, conditional, or null to disable memory'),\n});\n\n/**\n * PATCH /stored/agents/:storedAgentId - Update stored agent body\n * Optional metadata-level fields + optional config fields\n */\nexport const updateStoredAgentBodySchema = agentMetadataSchema\n .partial()\n .merge(snapshotConfigUpdateSchema.partial())\n .extend({\n changeMessage: z\n .string()\n .trim()\n .max(500)\n .optional()\n .describe('Optional message describing the changes for the auto-created version'),\n autoPublish: z\n .boolean()\n .optional()\n .describe('Immediately activate the auto-created version. Defaults to false when omitted.'),\n });\n\nexport const exportStoredAgentBodySchema = snapshotConfigUpdateSchema.partial();\n\nexport const openStoredAgentChangeRequestBodySchema = exportStoredAgentBodySchema.extend({\n changeMessage: z.string().trim().max(500).optional(),\n userName: z.string().trim().min(1).max(120).optional(),\n inspectOnly: z.boolean().optional(),\n});\n\n// ============================================================================\n// Response Schemas\n// ============================================================================\n\n/**\n * Resolved author object — server-side enrichment of `authorId` against the\n * configured auth provider. Only `id` is required; the other fields mirror\n * what `/auth/me` exposes and are optional because providers may not return\n * every field.\n */\nexport const resolvedAuthorSchema = z.object({\n id: z.string(),\n name: z.string().optional(),\n email: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\n/**\n * Stored agent object schema (resolved response: thin record + version config)\n * Represents StorageResolvedAgentType\n */\nexport const storedAgentSchema = z.object({\n // Thin agent record fields\n id: z.string(),\n status: z.string().describe('Agent status: draft or published'),\n activeVersionId: z.string().optional(),\n authorId: z.string().optional(),\n author: resolvedAuthorSchema.optional().describe('Resolved author identity (when an auth provider is configured)'),\n metadata: z.record(z.string(), z.unknown()).optional(),\n visibility: z.enum(['private', 'public']).optional(),\n favoriteCount: z.number().int().nonnegative().optional().describe('Number of users who have favorited this agent'),\n isFavorited: z.boolean().optional().describe('Whether the requesting user has favorited this agent'),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n // Version snapshot config fields (resolved from active version)\n name: z.string().describe('Name of the agent'),\n description: z.string().optional().describe('Description of the agent'),\n instructions: instructionsSchema,\n model: conditionalFieldSchema(modelConfigSchema).describe(\n 'Model configuration — static value or array of conditional variants',\n ),\n tools: conditionalFieldSchema(toolsConfigSchema)\n .optional()\n .describe('Tool keys mapped to per-tool config — static or conditional'),\n defaultOptions: conditionalFieldSchema(defaultOptionsSchema)\n .optional()\n .describe('Default options for generate/stream calls — static or conditional'),\n workflows: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Workflow keys with optional per-workflow config — static or conditional'),\n agents: conditionalFieldSchema(z.record(z.string(), toolConfigSchema))\n .optional()\n .describe('Agent keys with optional per-agent config — static or conditional'),\n integrationTools: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of tool provider IDs to their tool configurations — static or conditional'),\n toolProviders: conditionalFieldSchema(toolProvidersSchema)\n .optional()\n .describe(\n 'Tool provider connections and per-tool config (provider-agnostic). Coexists with the deprecated `integrationTools` field.',\n ),\n mcpClients: conditionalFieldSchema(z.record(z.string(), mcpClientToolsConfigSchema))\n .optional()\n .describe('Map of stored MCP client IDs to their tool configurations — static or conditional'),\n inputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Input processor graph — static or conditional'),\n outputProcessors: conditionalFieldSchema(storedProcessorGraphSchema)\n .optional()\n .describe('Output processor graph — static or conditional'),\n memory: conditionalFieldSchema(serializedMemoryConfigSchema)\n .optional()\n .describe('Memory configuration — static or conditional'),\n scorers: conditionalFieldSchema(z.record(z.string(), scorerConfigSchema))\n .optional()\n .describe('Scorer keys with optional sampling config — static or conditional'),\n skills: conditionalFieldSchema(skillsConfigSchema)\n .optional()\n .describe('Skill IDs mapped to per-skill config — static or conditional'),\n workspace: conditionalFieldSchema(workspaceRefSchema)\n .optional()\n .describe('Workspace reference (stored ID or inline config) — static or conditional'),\n browser: z\n .union([conditionalFieldSchema(browserRefSchema), z.boolean(), z.null()])\n .optional()\n .describe('Browser configuration — object config, true (apply default), false/null (disable)'),\n requestContextSchema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('JSON Schema defining valid request context variables'),\n durable: durableConfigSchema.optional().describe('Whether this agent is hydrated with durable execution enabled'),\n});\n\n/**\n * Response for GET /stored/agents\n */\nexport const listStoredAgentsResponseSchema = paginationInfoSchema.extend({\n agents: z.array(storedAgentSchema),\n});\n\n/**\n * Response for GET /stored/agents/:storedAgentId\n */\nexport const getStoredAgentResponseSchema = storedAgentSchema;\n\n/**\n * Response for POST /stored/agents\n */\nexport const createStoredAgentResponseSchema = storedAgentSchema;\n\n/**\n * Response for PATCH /stored/agents/:storedAgentId\n *\n * The response can be either:\n * 1. A thin agent record (no version) - only has id, status, dates, etc.\n * 2. A resolved agent (with version) - has all config fields from the version\n *\n * We use a union to handle both cases properly.\n */\nexport const updateStoredAgentResponseSchema = z.union([\n // Thin agent record (no version config)\n z.object({\n id: z.string(),\n status: z.string(),\n activeVersionId: z.string().optional(),\n authorId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n visibility: z.enum(['private', 'public']).optional(),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n }),\n // Resolved agent (thin record + version config)\n storedAgentSchema,\n]);\n\n/**\n * Response for DELETE /stored/agents/:storedAgentId\n */\nexport const deleteStoredAgentResponseSchema = z.object({\n success: z.boolean(),\n message: z.string(),\n});\n\n/**\n * Response for GET /stored/agents/:storedAgentId/dependents\n *\n * `dependents` lists caller-readable stored agents whose resolved `agents` map\n * references the target. Includes both public and the caller's own private\n * agents — anything the caller already has read access to.\n * `hiddenCount` aggregates references from agents the caller cannot read\n * (cross-workspace private agents). Only populated when the target agent is\n * public, to avoid leaking cross-workspace structure for private targets.\n */\nexport const getStoredAgentDependentsResponseSchema = z.object({\n dependents: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n }),\n ),\n hiddenCount: z.number().int().nonnegative(),\n});\n\nexport const exportStoredAgentResponseSchema = z.object({\n agentId: z.string(),\n fileName: z.string(),\n content: z.string(),\n config: z.record(z.string(), z.unknown()),\n});\n\nexport const openStoredAgentChangeRequestResponseSchema = z.object({\n id: z.union([z.string(), z.number()]).optional(),\n url: z.string(),\n ref: z.string().optional(),\n});\n\n// ============================================================================\n// Preview Instructions Schemas\n// ============================================================================\n\n/**\n * POST /stored/agents/preview-instructions - Preview resolved instructions\n */\nexport const previewInstructionsBodySchema = z.object({\n blocks: z.array(agentInstructionBlockSchema).describe('Array of instruction blocks to resolve'),\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .describe('Request context for variable interpolation and rule evaluation'),\n});\n\n/**\n * Response for POST /stored/agents/preview-instructions\n */\nexport const previewInstructionsResponseSchema = z.object({\n result: z.string().describe('The resolved instructions string'),\n});\n\n/**\n * Exported for use in agent-versions.ts schemas\n */\nexport {\n snapshotConfigSchema,\n scorerConfigSchema,\n conditionalFieldSchema,\n modelConfigSchema,\n storedProcessorGraphSchema,\n processorGraphStepSchema,\n processorGraphEntrySchema,\n processorPhaseSchema,\n toolConfigSchema,\n toolsConfigSchema,\n};\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAa,uBAAuBA,OAAAA,EAAE,OAAO;CAC3C,MAAMA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,qDAAqD;CAC/E,cAAcA,OAAAA,EACX,MAAM,CACLA,OAAAA,EAAE,OAAO,GACTA,OAAAA,EAAE,OAAO;EACP,QAAQA,OAAAA,EAAE,OAAO;EACjB,OAAOA,OAAAA,EAAE,OAAO;CAClB,CAAC,CACH,CAAC,CAAC,CACD,SAAS,sEAAsE;CAClF,OAAOA,OAAAA,EAAE,KAAK,CAAC,UAAU,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,mCAAmC;CAC7F,WAAWA,OAAAA,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,oCAAoC;CAC5F,WAAWA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,iCAAiC;AAC7E,CAAC;;;;;AAMD,MAAa,wBAAwBA,OAAAA,EAAE,MAAM,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A,OAAAA,EAAE,OAAO;CACjE,IAAIA,OAAAA,EAAE,MAAM,CAACA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;CAC/C,KAAKA,OAAAA,EAAE,OAAO;CACd,KAAKA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;AAC3B,CAAC;;;;AASD,MAAa,gCAAgCA,OAAAA,EAAE,OAAO;CACpD,QAAQA,OAAAA,EAAE,MAAM,2BAA2B,CAAC,CAAC,SAAS,wCAAwC;CAC9F,SAASA,OAAAA,EACN,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAC/B,SAAS,CAAC,CACV,QAAQ,CAAC,CAAC,CAAC,CACX,SAAS,gEAAgE;AAC9E,CAAC;;;;AAKD,MAAa,oCAAoCA,OAAAA,EAAE,OAAO,EACxD,QAAQA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,kCAAkC,EAChE,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-KsERfbhc.js","names":[],"sources":["../src/server/fga-permissions.ts","../src/server/handlers/utils.ts"],"sourcesContent":["/**\n * Safe re-export of `MastraFGAPermissions` from `@mastra/core/auth/ee`.\n *\n * Why this shim exists:\n * `MastraFGAPermissions` was introduced in `@mastra/core@1.32.0`. Earlier\n * versions of `@mastra/core` ship `@mastra/core/auth/ee` but do not export\n * this constant. A direct named import (`import { MastraFGAPermissions }\n * from '@mastra/core/auth/ee'`) fails at ESM link time when this version\n * of `@mastra/server` is paired with `@mastra/core < 1.32.0`, taking the\n * entire user bundle down before any code runs.\n *\n * A namespace import tolerates missing names — `ns.MissingExport` is just\n * `undefined`, no link-time error. We then expose the permission map.\n *\n * Fallback values:\n * If the consuming `@mastra/core` does not export `MastraFGAPermissions`,\n * we substitute a hardcoded map of the canonical permission strings used\n * by routes in `@mastra/server`. This preserves the explicit RBAC\n * permission overrides those routes already had as string literals in\n * `@mastra/server@1.31.0` (e.g. `requiresPermission: \"agents:execute\"`\n * on `/v1/responses`). Without this fallback, `requiresPermission` would\n * be `undefined` on old core and the auth layer would derive the wrong\n * permission from the route path (e.g. `v1:write` instead of\n * `agents:execute`), breaking RBAC users who upgrade `@mastra/server`\n * but stay on `@mastra/core@1.31.0`.\n *\n * Once the consuming `@mastra/core` is on `1.32.0+` the values are real\n * and behaviour is identical to a direct named import.\n */\n\nimport * as authEE from '@mastra/core/auth/ee';\n\n// Canonical strings for the FGA permission keys actually referenced by\n// `@mastra/server` source. Mirrors `MastraFGAPermissions` in\n// `@mastra/core@1.32.0+` for these specific keys, and matches the string\n// literals previously hardcoded on the same routes in `@mastra/server@1.31.0`.\nconst FALLBACK_PERMISSIONS = {\n AGENTS_CREATE: 'agents:create',\n AGENTS_DELETE: 'agents:delete',\n AGENTS_EXECUTE: 'agents:execute',\n AGENTS_READ: 'agents:read',\n MEMORY_DELETE: 'memory:delete',\n MEMORY_READ: 'memory:read',\n MEMORY_WRITE: 'memory:write',\n TOOLS_EXECUTE: 'tools:execute',\n TOOLS_READ: 'tools:read',\n STORED_WORKFLOWS_READ: 'stored-workflows:read',\n STORED_WORKFLOWS_WRITE: 'stored-workflows:write',\n WORKFLOWS_EXECUTE: 'workflows:execute',\n WORKFLOWS_READ: 'workflows:read',\n} as const;\n\nconst realPermissions = (authEE as any).MastraFGAPermissions;\n\n// Typed as `any` on purpose: consumers of `@mastra/server` may run their\n// typecheck against a `@mastra/core` that doesn't export `MastraFGAPermissions`\n// (anything < 1.32.0). Pinning to the real type would push that name into the\n// emitted `.d.ts` and break downstream typecheck. `any` lets the property\n// accesses (`MastraFGAPermissions.AGENTS_READ`) flow through cleanly on every\n// supported core.\nexport const MastraFGAPermissions: any =\n realPermissions && Object.keys(realPermissions).length > 0 ? realPermissions : FALLBACK_PERMISSIONS;\n","import type { MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, isReservedRequestContextKey } from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n// Validation helper\nexport function validateBody(body: Record<string, unknown>) {\n const errorResponse = Object.entries(body).reduce<Record<string, string>>((acc, [key, value]) => {\n if (!value) {\n acc[key] = `Argument \"${key}\" is required`;\n }\n return acc;\n }, {});\n\n if (Object.keys(errorResponse).length > 0) {\n throw new HTTPException(400, { message: Object.values(errorResponse)[0] });\n }\n}\n\n/**\n * sanitizes the body by removing disallowed keys.\n * @param body body to sanitize\n * @param disallowedKeys keys to remove from the body\n */\nexport function sanitizeBody(body: Record<string, unknown>, disallowedKeys: string[]) {\n for (const key of disallowedKeys) {\n if (key in body) {\n delete body[key];\n }\n }\n}\n\nexport function parsePerPage(\n value: string | undefined,\n defaultValue: number = 100,\n max: number = 1000,\n): number | false {\n const normalized = (value || '').trim().toLowerCase();\n // Handle explicit false to bypass pagination\n if (normalized === 'false') {\n return false;\n }\n const parsed = parseInt(value || String(defaultValue), 10);\n if (isNaN(parsed)) return defaultValue;\n return Math.min(max, Math.max(1, parsed));\n}\n\n/**\n * Parses filter query parameters into a key-value object.\n */\nexport function parseFilters(filters: string | string[] | undefined): Record<string, string> | undefined {\n if (!filters) return undefined;\n\n return Object.fromEntries(\n (Array.isArray(filters) ? filters : [filters]).map((attr: string) => {\n const [key, ...valueParts] = attr.split(':');\n const value = valueParts.join(':'); // ✅ Handles colons in values\n return [key, value];\n }),\n );\n}\n\n/**\n * Merges a body-supplied requestContext into the trusted server RequestContext.\n * The server context is authoritative: reserved keys are skipped and body values\n * only fill keys the server context has not already set.\n */\nexport function mergeBodyRequestContext(serverRequestContext: RequestContext, bodyRequestContext: unknown): void {\n if (!bodyRequestContext || typeof bodyRequestContext !== 'object') {\n return;\n }\n\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n if (serverRequestContext.get(key) === undefined) {\n serverRequestContext.set(key, value);\n }\n }\n}\n\n// ============================================================================\n// Authorization Utilities\n// ============================================================================\n\n/**\n * Gets the effective resourceId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveResourceId(\n requestContext: RequestContext | undefined,\n clientResourceId: string | undefined,\n): string | undefined {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n return contextResourceId || clientResourceId;\n}\n\n/**\n * Returns the resource id resolved from the request context alone (set via\n * `mapUserToResourceId` or the `x-resource-id` header), ignoring any\n * client-provided value. Its presence indicates a resource-scoped caller;\n * its absence indicates a privileged/service context.\n */\nexport function getContextResourceId(requestContext: RequestContext | undefined): string | undefined {\n return requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n}\n\n/**\n * Ensures a memory request has a resolvable resource ID. The body's\n * `memory.resource` is optional so authenticated setups can rely on the\n * server-derived resource ID (MASTRA_RESOURCE_ID_KEY set via mapUserToResourceId).\n * When neither the body nor the request context provides one, reject with a\n * clear 400 instead of failing deep inside agent execution.\n */\nexport function requireEffectiveResourceId(\n effectiveResourceId: string | undefined,\n): asserts effectiveResourceId is string {\n if (!effectiveResourceId) {\n throw new HTTPException(400, {\n message:\n 'A resource ID is required when using memory. Provide memory.resource in the request body, or configure server auth with mapUserToResourceId to derive it from the authenticated user.',\n });\n }\n}\n\n/**\n * Gets the effective threadId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveThreadId(\n requestContext: RequestContext | undefined,\n clientThreadId: string | undefined,\n): string | undefined {\n const contextThreadId = requestContext?.get(MASTRA_THREAD_ID_KEY) as string | undefined;\n return contextThreadId || clientThreadId;\n}\n\n/**\n * Validates that a thread belongs to the specified resourceId.\n * Throws 403 if the thread exists but belongs to a different resource.\n * Threads with no resourceId are accessible to all (shared threads).\n */\nexport async function validateThreadOwnership(\n thread: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (thread && effectiveResourceId && thread.resourceId && thread.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: thread belongs to a different resource' });\n }\n}\n\n/**\n * Validates both coarse resource ownership and fine-grained thread access.\n * FGA enforcement is a no-op when no FGA provider is configured.\n */\nexport async function enforceThreadAccess({\n mastra,\n requestContext,\n threadId,\n thread,\n effectiveResourceId,\n permission = MastraFGAPermissions.MEMORY_READ,\n}: {\n mastra: any;\n requestContext?: RequestContext;\n threadId: string;\n thread?: { resourceId?: string | null } | null;\n effectiveResourceId?: string;\n permission?: MastraFGAPermissionInput;\n}): Promise<void> {\n await validateThreadOwnership(thread, effectiveResourceId);\n\n const fgaProvider = mastra?.getServer?.()?.fga;\n if (!fgaProvider) {\n return;\n }\n\n const user = requestContext?.get('user');\n if (!user || typeof user !== 'object') {\n throw new HTTPException(403, { message: 'FGA authorization denied: authenticated user is required' });\n }\n\n await MastraMemory.checkThreadFGA({\n mastra,\n user: user as { id: string; [key: string]: unknown },\n threadId,\n resourceId: thread?.resourceId ?? effectiveResourceId,\n requestContext,\n permission,\n });\n}\n\n/**\n * Validates that a workflow run belongs to the specified resourceId.\n * Throws 403 if the run exists but belongs to a different resource.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (run && effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,uBAAuB;CAC3B,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,aAAa;CACb,cAAc;CACd,eAAe;CACf,YAAY;CACZ,uBAAuB;CACvB,wBAAwB;CACxB,mBAAmB;CACnB,gBAAgB;AAClB;AAEA,MAAM,kBAAmB,OAAe;AAQxC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3,"file":"utils-aIu3gkhJ.cjs","names":["authEE","HTTPException","isReservedRequestContextKey","MASTRA_RESOURCE_ID_KEY","MastraMemory"],"sources":["../src/server/fga-permissions.ts","../src/server/handlers/utils.ts"],"sourcesContent":["/**\n * Safe re-export of `MastraFGAPermissions` from `@mastra/core/auth/ee`.\n *\n * Why this shim exists:\n * `MastraFGAPermissions` was introduced in `@mastra/core@1.32.0`. Earlier\n * versions of `@mastra/core` ship `@mastra/core/auth/ee` but do not export\n * this constant. A direct named import (`import { MastraFGAPermissions }\n * from '@mastra/core/auth/ee'`) fails at ESM link time when this version\n * of `@mastra/server` is paired with `@mastra/core < 1.32.0`, taking the\n * entire user bundle down before any code runs.\n *\n * A namespace import tolerates missing names — `ns.MissingExport` is just\n * `undefined`, no link-time error. We then expose the permission map.\n *\n * Fallback values:\n * If the consuming `@mastra/core` does not export `MastraFGAPermissions`,\n * we substitute a hardcoded map of the canonical permission strings used\n * by routes in `@mastra/server`. This preserves the explicit RBAC\n * permission overrides those routes already had as string literals in\n * `@mastra/server@1.31.0` (e.g. `requiresPermission: \"agents:execute\"`\n * on `/v1/responses`). Without this fallback, `requiresPermission` would\n * be `undefined` on old core and the auth layer would derive the wrong\n * permission from the route path (e.g. `v1:write` instead of\n * `agents:execute`), breaking RBAC users who upgrade `@mastra/server`\n * but stay on `@mastra/core@1.31.0`.\n *\n * Once the consuming `@mastra/core` is on `1.32.0+` the values are real\n * and behaviour is identical to a direct named import.\n */\n\nimport * as authEE from '@mastra/core/auth/ee';\n\n// Canonical strings for the FGA permission keys actually referenced by\n// `@mastra/server` source. Mirrors `MastraFGAPermissions` in\n// `@mastra/core@1.32.0+` for these specific keys, and matches the string\n// literals previously hardcoded on the same routes in `@mastra/server@1.31.0`.\nconst FALLBACK_PERMISSIONS = {\n AGENTS_CREATE: 'agents:create',\n AGENTS_DELETE: 'agents:delete',\n AGENTS_EXECUTE: 'agents:execute',\n AGENTS_READ: 'agents:read',\n MEMORY_DELETE: 'memory:delete',\n MEMORY_READ: 'memory:read',\n MEMORY_WRITE: 'memory:write',\n TOOLS_EXECUTE: 'tools:execute',\n TOOLS_READ: 'tools:read',\n STORED_WORKFLOWS_READ: 'stored-workflows:read',\n STORED_WORKFLOWS_WRITE: 'stored-workflows:write',\n WORKFLOWS_EXECUTE: 'workflows:execute',\n WORKFLOWS_READ: 'workflows:read',\n} as const;\n\nconst realPermissions = (authEE as any).MastraFGAPermissions;\n\n// Typed as `any` on purpose: consumers of `@mastra/server` may run their\n// typecheck against a `@mastra/core` that doesn't export `MastraFGAPermissions`\n// (anything < 1.32.0). Pinning to the real type would push that name into the\n// emitted `.d.ts` and break downstream typecheck. `any` lets the property\n// accesses (`MastraFGAPermissions.AGENTS_READ`) flow through cleanly on every\n// supported core.\nexport const MastraFGAPermissions: any =\n realPermissions && Object.keys(realPermissions).length > 0 ? realPermissions : FALLBACK_PERMISSIONS;\n","import type { MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { MastraMemory } from '@mastra/core/memory';\nimport { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, isReservedRequestContextKey } from '../constants';\nimport { MastraFGAPermissions } from '../fga-permissions';\nimport { HTTPException } from '../http-exception';\n\n// Validation helper\nexport function validateBody(body: Record<string, unknown>) {\n const errorResponse = Object.entries(body).reduce<Record<string, string>>((acc, [key, value]) => {\n if (!value) {\n acc[key] = `Argument \"${key}\" is required`;\n }\n return acc;\n }, {});\n\n if (Object.keys(errorResponse).length > 0) {\n throw new HTTPException(400, { message: Object.values(errorResponse)[0] });\n }\n}\n\n/**\n * sanitizes the body by removing disallowed keys.\n * @param body body to sanitize\n * @param disallowedKeys keys to remove from the body\n */\nexport function sanitizeBody(body: Record<string, unknown>, disallowedKeys: string[]) {\n for (const key of disallowedKeys) {\n if (key in body) {\n delete body[key];\n }\n }\n}\n\nexport function parsePerPage(\n value: string | undefined,\n defaultValue: number = 100,\n max: number = 1000,\n): number | false {\n const normalized = (value || '').trim().toLowerCase();\n // Handle explicit false to bypass pagination\n if (normalized === 'false') {\n return false;\n }\n const parsed = parseInt(value || String(defaultValue), 10);\n if (isNaN(parsed)) return defaultValue;\n return Math.min(max, Math.max(1, parsed));\n}\n\n/**\n * Parses filter query parameters into a key-value object.\n */\nexport function parseFilters(filters: string | string[] | undefined): Record<string, string> | undefined {\n if (!filters) return undefined;\n\n return Object.fromEntries(\n (Array.isArray(filters) ? filters : [filters]).map((attr: string) => {\n const [key, ...valueParts] = attr.split(':');\n const value = valueParts.join(':'); // ✅ Handles colons in values\n return [key, value];\n }),\n );\n}\n\n/**\n * Merges a body-supplied requestContext into the trusted server RequestContext.\n * The server context is authoritative: reserved keys are skipped and body values\n * only fill keys the server context has not already set.\n */\nexport function mergeBodyRequestContext(serverRequestContext: RequestContext, bodyRequestContext: unknown): void {\n if (!bodyRequestContext || typeof bodyRequestContext !== 'object') {\n return;\n }\n\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n if (serverRequestContext.get(key) === undefined) {\n serverRequestContext.set(key, value);\n }\n }\n}\n\n// ============================================================================\n// Authorization Utilities\n// ============================================================================\n\n/**\n * Gets the effective resourceId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveResourceId(\n requestContext: RequestContext | undefined,\n clientResourceId: string | undefined,\n): string | undefined {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n return contextResourceId || clientResourceId;\n}\n\n/**\n * Returns the resource id resolved from the request context alone (set via\n * `mapUserToResourceId` or the `x-resource-id` header), ignoring any\n * client-provided value. Its presence indicates a resource-scoped caller;\n * its absence indicates a privileged/service context.\n */\nexport function getContextResourceId(requestContext: RequestContext | undefined): string | undefined {\n return requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n}\n\n/**\n * Ensures a memory request has a resolvable resource ID. The body's\n * `memory.resource` is optional so authenticated setups can rely on the\n * server-derived resource ID (MASTRA_RESOURCE_ID_KEY set via mapUserToResourceId).\n * When neither the body nor the request context provides one, reject with a\n * clear 400 instead of failing deep inside agent execution.\n */\nexport function requireEffectiveResourceId(\n effectiveResourceId: string | undefined,\n): asserts effectiveResourceId is string {\n if (!effectiveResourceId) {\n throw new HTTPException(400, {\n message:\n 'A resource ID is required when using memory. Provide memory.resource in the request body, or configure server auth with mapUserToResourceId to derive it from the authenticated user.',\n });\n }\n}\n\n/**\n * Gets the effective threadId, preferring the reserved key from requestContext\n * over client-provided values for security.\n */\nexport function getEffectiveThreadId(\n requestContext: RequestContext | undefined,\n clientThreadId: string | undefined,\n): string | undefined {\n const contextThreadId = requestContext?.get(MASTRA_THREAD_ID_KEY) as string | undefined;\n return contextThreadId || clientThreadId;\n}\n\n/**\n * Validates that a thread belongs to the specified resourceId.\n * Throws 403 if the thread exists but belongs to a different resource.\n * Threads with no resourceId are accessible to all (shared threads).\n */\nexport async function validateThreadOwnership(\n thread: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (thread && effectiveResourceId && thread.resourceId && thread.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: thread belongs to a different resource' });\n }\n}\n\n/**\n * Validates both coarse resource ownership and fine-grained thread access.\n * FGA enforcement is a no-op when no FGA provider is configured.\n */\nexport async function enforceThreadAccess({\n mastra,\n requestContext,\n threadId,\n thread,\n effectiveResourceId,\n permission = MastraFGAPermissions.MEMORY_READ,\n}: {\n mastra: any;\n requestContext?: RequestContext;\n threadId: string;\n thread?: { resourceId?: string | null } | null;\n effectiveResourceId?: string;\n permission?: MastraFGAPermissionInput;\n}): Promise<void> {\n await validateThreadOwnership(thread, effectiveResourceId);\n\n const fgaProvider = mastra?.getServer?.()?.fga;\n if (!fgaProvider) {\n return;\n }\n\n const user = requestContext?.get('user');\n if (!user || typeof user !== 'object') {\n throw new HTTPException(403, { message: 'FGA authorization denied: authenticated user is required' });\n }\n\n await MastraMemory.checkThreadFGA({\n mastra,\n user: user as { id: string; [key: string]: unknown },\n threadId,\n resourceId: thread?.resourceId ?? effectiveResourceId,\n requestContext,\n permission,\n });\n}\n\n/**\n * Validates that a workflow run belongs to the specified resourceId.\n * Throws 403 if the run exists but belongs to a different resource.\n */\nexport async function validateRunOwnership(\n run: { resourceId?: string | null } | null | undefined,\n effectiveResourceId: string | undefined,\n): Promise<void> {\n if (run && effectiveResourceId && run.resourceId && run.resourceId !== effectiveResourceId) {\n throw new HTTPException(403, { message: 'Access denied: workflow run belongs to a different resource' });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,uBAAuB;CAC3B,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,aAAa;CACb,cAAc;CACd,eAAe;CACf,YAAY;CACZ,uBAAuB;CACvB,wBAAwB;CACxB,mBAAmB;CACnB,gBAAgB;AAClB;AAEA,MAAM,kBAAmBA,qBAAe;AAQxC,MAAa,uBACX,mBAAmB,OAAO,KAAK,eAAe,CAAC,CAAC,SAAS,IAAI,kBAAkB;;;ACrDjF,SAAgB,aAAa,MAA+B;CAC1D,MAAM,gBAAgB,OAAO,QAAQ,IAAI,CAAC,CAAC,QAAgC,KAAK,CAAC,KAAK,WAAW;EAC/F,IAAI,CAAC,OACH,IAAI,OAAO,aAAa,IAAI;EAE9B,OAAO;CACT,GAAG,CAAC,CAAC;CAEL,IAAI,OAAO,KAAK,aAAa,CAAC,CAAC,SAAS,GACtC,MAAM,IAAIC,uBAAAA,cAAc,KAAK,EAAE,SAAS,OAAO,OAAO,aAAa,CAAC,CAAC,GAAG,CAAC;AAE7E;;;;;;AAOA,SAAgB,aAAa,MAA+B,gBAA0B;CACpF,KAAK,MAAM,OAAO,gBAChB,IAAI,OAAO,MACT,OAAO,KAAK;AAGlB;AAEA,SAAgB,aACd,OACA,eAAuB,KACvB,MAAc,KACE;CAGhB,KAFoB,SAAS,GAAA,CAA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