@mastra/server 1.78.0-alpha.4 → 1.78.0-alpha.6
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/{agents-CKSEPpk1.cjs → agents-D9vpLghy.cjs} +8 -1
- package/dist/{agents-CKSEPpk1.cjs.map → agents-D9vpLghy.cjs.map} +1 -1
- package/dist/{agents-CW_JJZOf.js → agents-DNWDET4U.js} +3 -2
- package/dist/{agents-CW_JJZOf.js.map → agents-DNWDET4U.js.map} +1 -1
- package/dist/{api-schema-manifest-7Mkcahcz.cjs → api-schema-manifest-CmnpeFqd.cjs} +2 -2
- package/dist/{api-schema-manifest-7Mkcahcz.cjs.map → api-schema-manifest-CmnpeFqd.cjs.map} +1 -1
- package/dist/{api-schema-manifest-BSc3N7kx.js → api-schema-manifest-D8dn-tBo.js} +2 -2
- package/dist/{api-schema-manifest-BSc3N7kx.js.map → api-schema-manifest-D8dn-tBo.js.map} +1 -1
- package/dist/{background-tasks-Cu89GYC6.cjs → background-tasks-CP6TSFhc.cjs} +2 -2
- package/dist/{background-tasks-Cu89GYC6.cjs.map → background-tasks-CP6TSFhc.cjs.map} +1 -1
- package/dist/{background-tasks-_e2S8LLH.js → background-tasks-Clbud7G4.js} +2 -2
- package/dist/{background-tasks-_e2S8LLH.js.map → background-tasks-Clbud7G4.js.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-guides-mcp-authentication-authorization.md +10 -1
- package/dist/docs/references/docs-server-middleware.md +4 -0
- package/dist/docs/references/reference-server-routes.md +17 -6
- package/dist/{editor-builder-CmUsqdZq.cjs → editor-builder-BOmAPurW.cjs} +2 -2
- package/dist/{editor-builder-CmUsqdZq.cjs.map → editor-builder-BOmAPurW.cjs.map} +1 -1
- package/dist/{editor-builder-DHXbVwxu.js → editor-builder-CeLVu_FT.js} +2 -2
- package/dist/{editor-builder-DHXbVwxu.js.map → editor-builder-CeLVu_FT.js.map} +1 -1
- package/dist/{editor-builder-CYkaYf6-.js → editor-builder-DHqCWGd2.js} +2 -2
- package/dist/{editor-builder-CYkaYf6-.js.map → editor-builder-DHqCWGd2.js.map} +1 -1
- package/dist/{editor-builder-BtcTQbAC.cjs → editor-builder-DqHKoEDx.cjs} +2 -2
- package/dist/{editor-builder-BtcTQbAC.cjs.map → editor-builder-DqHKoEDx.cjs.map} +1 -1
- package/dist/{routes-BOpfBZw5.cjs → routes-BwzE4nnm.cjs} +6 -5
- package/dist/routes-BwzE4nnm.cjs.map +1 -0
- package/dist/{routes-CccVLchZ.js → routes-DlbTsFpA.js} +7 -6
- package/dist/routes-DlbTsFpA.js.map +1 -0
- package/dist/{schedules-6XpznRPz.js → schedules-BRdVmFYi.js} +2 -2
- package/dist/{schedules-6XpznRPz.js.map → schedules-BRdVmFYi.js.map} +1 -1
- package/dist/{schedules-BiqVrJH7.cjs → schedules-DvLXX2nW.cjs} +2 -2
- package/dist/{schedules-BiqVrJH7.cjs.map → schedules-DvLXX2nW.cjs.map} +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/agents.cjs +39 -10
- package/dist/server/handlers/agents.cjs.map +1 -1
- package/dist/server/handlers/agents.d.ts +2113 -0
- package/dist/server/handlers/agents.d.ts.map +1 -1
- package/dist/server/handlers/agents.js +39 -11
- package/dist/server/handlers/agents.js.map +1 -1
- package/dist/server/handlers/background-tasks.cjs +1 -1
- package/dist/server/handlers/background-tasks.js +1 -1
- package/dist/server/handlers/conversations.cjs +1 -1
- package/dist/server/handlers/conversations.js +1 -1
- package/dist/server/handlers/editor-builder.cjs +1 -1
- package/dist/server/handlers/editor-builder.js +1 -1
- package/dist/server/handlers/favorites-enrichment.cjs +1 -1
- package/dist/server/handlers/favorites-enrichment.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/plans.cjs +2 -2
- package/dist/server/handlers/plans.js +2 -2
- 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.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.js +1 -1
- package/dist/server/handlers/stored-skill-favorites.cjs +1 -1
- package/dist/server/handlers/stored-skill-favorites.js +1 -1
- package/dist/server/handlers/stored-skills.cjs +1 -1
- package/dist/server/handlers/stored-skills.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 +2 -2
- package/dist/server/handlers/tools.js +2 -2
- package/dist/server/handlers/utils.cjs +1 -1
- package/dist/server/handlers/utils.d.ts +14 -3
- package/dist/server/handlers/utils.d.ts.map +1 -1
- package/dist/server/handlers/utils.js +1 -1
- package/dist/server/handlers/workflow-builder.cjs +1 -1
- package/dist/server/handlers/workflow-builder.js +1 -1
- package/dist/server/handlers/workflows.cjs +37 -20
- package/dist/server/handlers/workflows.cjs.map +1 -1
- package/dist/server/handlers/workflows.d.ts.map +1 -1
- package/dist/server/handlers/workflows.js +37 -20
- package/dist/server/handlers/workflows.js.map +1 -1
- package/dist/server/schemas/agents.d.ts +199 -0
- package/dist/server/schemas/agents.d.ts.map +1 -1
- package/dist/server/schemas/index.cjs +3 -2
- package/dist/server/schemas/index.js +3 -3
- package/dist/server/server-adapter/index.cjs +1 -1
- package/dist/server/server-adapter/index.js +1 -1
- package/dist/server/server-adapter/routes/agents.d.ts +2 -1
- package/dist/server/server-adapter/routes/agents.d.ts.map +1 -1
- package/dist/{utils-BF2Kbju4.cjs → utils-DdGLbkOl.cjs} +21 -5
- package/dist/{utils-BF2Kbju4.cjs.map → utils-DdGLbkOl.cjs.map} +1 -1
- package/dist/{utils-GVYTDbr2.js → utils-mIFmRM_j.js} +21 -5
- package/dist/{utils-GVYTDbr2.js.map → utils-mIFmRM_j.js.map} +1 -1
- package/dist/{workflow-builder-UVflLOfv.cjs → workflow-builder-BM6Nen0q.cjs} +4 -4
- package/dist/{workflow-builder-UVflLOfv.cjs.map → workflow-builder-BM6Nen0q.cjs.map} +1 -1
- package/dist/{workflow-builder-U2jFH8o7.js → workflow-builder-BnKKH8iT.js} +4 -4
- package/dist/{workflow-builder-U2jFH8o7.js.map → workflow-builder-BnKKH8iT.js.map} +1 -1
- package/package.json +6 -6
- package/dist/routes-BOpfBZw5.cjs.map +0 -1
- package/dist/routes-CccVLchZ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-tasks-Cu89GYC6.cjs","names":["z","paginationNumber","getContextResourceId","HTTPException","createRoute"],"sources":["../src/server/schemas/background-tasks.ts","../src/server/handlers/background-tasks.ts"],"sourcesContent":["import { z } from 'zod';\nimport { paginationNumber } from './common';\n\nexport const backgroundTaskStatusSchema = z.enum([\n 'pending',\n 'running',\n 'suspended',\n 'completed',\n 'failed',\n 'cancelled',\n 'timed_out',\n]);\n\nexport const backgroundTaskStreamQuerySchema = z.object({\n agentId: z.string().optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n taskId: z.string().optional(),\n});\n\nexport const backgroundTaskDateColumnSchema = z.enum(['createdAt', 'startedAt', 'suspendedAt', 'completedAt']);\n\nexport const listBackgroundTasksQuerySchema = z.object({\n agentId: z.string().optional(),\n status: backgroundTaskStatusSchema.optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n toolName: z.string().optional(),\n toolCallId: z.string().optional(),\n fromDate: z.coerce.date().optional(),\n toDate: z.coerce.date().optional(),\n dateFilterBy: backgroundTaskDateColumnSchema.optional(),\n orderBy: backgroundTaskDateColumnSchema.optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n page: paginationNumber().optional(),\n perPage: paginationNumber().optional(),\n});\n\nexport const backgroundTaskIdPathParams = z.object({\n backgroundTaskId: z.string(),\n});\n\nexport const backgroundTaskResponseSchema = z.object({\n id: z.string(),\n status: backgroundTaskStatusSchema,\n toolName: z.string(),\n toolCallId: z.string(),\n args: z.record(z.string(), z.unknown()),\n agentId: z.string(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n runId: z.string(),\n result: z.unknown().optional(),\n error: z.object({ message: z.string(), stack: z.string().optional() }).optional(),\n createdAt: z.date(),\n startedAt: z.date().optional(),\n completedAt: z.date().optional(),\n retryCount: z.number(),\n maxRetries: z.number(),\n timeoutMs: z.number(),\n suspendPayload: z.unknown().optional(),\n});\n\nexport const listBackgroundTaskResponseSchema = z.object({\n tasks: z.array(backgroundTaskResponseSchema),\n total: z.number(),\n});\n\nexport const backgroundTaskStreamResponseSchema = z.unknown();\n","import { HTTPException } from '../http-exception';\nimport {\n backgroundTaskResponseSchema,\n backgroundTaskStreamQuerySchema,\n backgroundTaskStreamResponseSchema,\n listBackgroundTaskResponseSchema,\n listBackgroundTasksQuerySchema,\n backgroundTaskIdPathParams,\n} from '../schemas/background-tasks';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { getContextResourceId } from './utils';\n\n/**\n * Resolves the resource filter for a background-task request. A resource-scoped caller\n * is pinned to its own resource and may not request another one; a privileged caller\n * (no resource in the request context) keeps the client-provided filter.\n */\nfunction resolveResourceScope(\n requestContext: Parameters<typeof getContextResourceId>[0],\n clientResourceId: string | undefined,\n): { resourceId: string | undefined; scoped: boolean } {\n const contextResourceId = getContextResourceId(requestContext);\n if (contextResourceId === undefined) return { resourceId: clientResourceId, scoped: false };\n // An empty resource id must not be mistaken for a privileged (unscoped) caller, and\n // storage filters ignore empty strings, so it cannot be scoped safely either.\n if (contextResourceId === '') {\n throw new HTTPException(403, { message: 'Access denied: authenticated resourceId is empty' });\n }\n if (clientResourceId !== undefined && clientResourceId !== contextResourceId) {\n throw new HTTPException(403, { message: 'Access denied: resourceId does not match the authenticated resource' });\n }\n return { resourceId: contextResourceId, scoped: true };\n}\n\nexport const BACKGROUND_TASK_STREAM_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n queryParamSchema: backgroundTaskStreamQuerySchema,\n responseSchema: backgroundTaskStreamResponseSchema,\n summary: 'Stream background task events via SSE',\n description: 'Real-time Server-Sent Events stream of background task completion/failure events.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({\n mastra,\n agentId,\n runId,\n threadId,\n resourceId: clientResourceId,\n taskId,\n abortSignal,\n requestContext,\n }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, clientResourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks are not enabled — return an empty stream that stays\n // open until the client disconnects. This avoids spamming the logs with\n // false-positive errors when clients (e.g. the studio UI) optimistically\n // subscribe to the stream.\n return new ReadableStream({\n start(controller) {\n abortSignal?.addEventListener('abort', () => {\n try {\n controller.close();\n } catch {\n // Already closed\n }\n });\n },\n });\n }\n\n return bgManager.stream({ agentId, runId, threadId, resourceId, taskId, abortSignal, allResources: !scoped });\n },\n});\n\nexport const LIST_BACKGROUND_TASKS_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks',\n responseType: 'json' as const,\n queryParamSchema: listBackgroundTasksQuerySchema,\n responseSchema: listBackgroundTaskResponseSchema,\n summary: 'List background tasks',\n description: 'Returns background tasks filtered by status, agent, run, etc.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, ...params }) => {\n const { resourceId } = resolveResourceScope(requestContext, params.resourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — there are no tasks to return.\n return { tasks: [], total: 0 };\n }\n\n return bgManager.listTasks({ ...params, resourceId });\n },\n});\n\nexport const GET_BACKGROUND_TASK_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/:backgroundTaskId',\n responseType: 'json' as const,\n pathParamSchema: backgroundTaskIdPathParams,\n responseSchema: backgroundTaskResponseSchema,\n summary: 'Get a background task by ID',\n description: 'Returns a background task by ID.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, backgroundTaskId, requestContext }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, undefined);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — the task can't exist.\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n\n const task = await bgManager.getTask(backgroundTaskId);\n // Report another resource's task as missing so its existence is not disclosed.\n if (!task || (scoped && task.resourceId !== resourceId)) {\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n return task;\n },\n});\n"],"mappings":";;;;;;AAGA,MAAa,6BAA6BA,IAAAA,EAAE,KAAK;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkCA,IAAAA,EAAE,OAAO;CACtD,SAASA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;AAC9B,CAAC;AAED,MAAa,iCAAiCA,IAAAA,EAAE,KAAK;CAAC;CAAa;CAAa;CAAe;AAAa,CAAC;AAE7G,MAAa,iCAAiCA,IAAAA,EAAE,OAAO;CACrD,SAASA,IAAAA,EAAE,OAAO,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MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAEvE,OAAO;CACT;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"background-tasks-CP6TSFhc.cjs","names":["z","paginationNumber","getContextResourceId","HTTPException","createRoute"],"sources":["../src/server/schemas/background-tasks.ts","../src/server/handlers/background-tasks.ts"],"sourcesContent":["import { z } from 'zod';\nimport { paginationNumber } from './common';\n\nexport const backgroundTaskStatusSchema = z.enum([\n 'pending',\n 'running',\n 'suspended',\n 'completed',\n 'failed',\n 'cancelled',\n 'timed_out',\n]);\n\nexport const backgroundTaskStreamQuerySchema = z.object({\n agentId: z.string().optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n taskId: z.string().optional(),\n});\n\nexport const backgroundTaskDateColumnSchema = z.enum(['createdAt', 'startedAt', 'suspendedAt', 'completedAt']);\n\nexport const listBackgroundTasksQuerySchema = z.object({\n agentId: z.string().optional(),\n status: backgroundTaskStatusSchema.optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n toolName: z.string().optional(),\n toolCallId: z.string().optional(),\n fromDate: z.coerce.date().optional(),\n toDate: z.coerce.date().optional(),\n dateFilterBy: backgroundTaskDateColumnSchema.optional(),\n orderBy: backgroundTaskDateColumnSchema.optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n page: paginationNumber().optional(),\n perPage: paginationNumber().optional(),\n});\n\nexport const backgroundTaskIdPathParams = z.object({\n backgroundTaskId: z.string(),\n});\n\nexport const backgroundTaskResponseSchema = z.object({\n id: z.string(),\n status: backgroundTaskStatusSchema,\n toolName: z.string(),\n toolCallId: z.string(),\n args: z.record(z.string(), z.unknown()),\n agentId: z.string(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n runId: z.string(),\n result: z.unknown().optional(),\n error: z.object({ message: z.string(), stack: z.string().optional() }).optional(),\n createdAt: z.date(),\n startedAt: z.date().optional(),\n completedAt: z.date().optional(),\n retryCount: z.number(),\n maxRetries: z.number(),\n timeoutMs: z.number(),\n suspendPayload: z.unknown().optional(),\n});\n\nexport const listBackgroundTaskResponseSchema = z.object({\n tasks: z.array(backgroundTaskResponseSchema),\n total: z.number(),\n});\n\nexport const backgroundTaskStreamResponseSchema = z.unknown();\n","import { HTTPException } from '../http-exception';\nimport {\n backgroundTaskResponseSchema,\n backgroundTaskStreamQuerySchema,\n backgroundTaskStreamResponseSchema,\n listBackgroundTaskResponseSchema,\n listBackgroundTasksQuerySchema,\n backgroundTaskIdPathParams,\n} from '../schemas/background-tasks';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { getContextResourceId } from './utils';\n\n/**\n * Resolves the resource filter for a background-task request. A resource-scoped caller\n * is pinned to its own resource and may not request another one; a privileged caller\n * (no resource in the request context) keeps the client-provided filter.\n */\nfunction resolveResourceScope(\n requestContext: Parameters<typeof getContextResourceId>[0],\n clientResourceId: string | undefined,\n): { resourceId: string | undefined; scoped: boolean } {\n const contextResourceId = getContextResourceId(requestContext);\n if (contextResourceId === undefined) return { resourceId: clientResourceId, scoped: false };\n // An empty resource id must not be mistaken for a privileged (unscoped) caller, and\n // storage filters ignore empty strings, so it cannot be scoped safely either.\n if (contextResourceId === '') {\n throw new HTTPException(403, { message: 'Access denied: authenticated resourceId is empty' });\n }\n if (clientResourceId !== undefined && clientResourceId !== contextResourceId) {\n throw new HTTPException(403, { message: 'Access denied: resourceId does not match the authenticated resource' });\n }\n return { resourceId: contextResourceId, scoped: true };\n}\n\nexport const BACKGROUND_TASK_STREAM_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n queryParamSchema: backgroundTaskStreamQuerySchema,\n responseSchema: backgroundTaskStreamResponseSchema,\n summary: 'Stream background task events via SSE',\n description: 'Real-time Server-Sent Events stream of background task completion/failure events.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({\n mastra,\n agentId,\n runId,\n threadId,\n resourceId: clientResourceId,\n taskId,\n abortSignal,\n requestContext,\n }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, clientResourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks are not enabled — return an empty stream that stays\n // open until the client disconnects. This avoids spamming the logs with\n // false-positive errors when clients (e.g. the studio UI) optimistically\n // subscribe to the stream.\n return new ReadableStream({\n start(controller) {\n abortSignal?.addEventListener('abort', () => {\n try {\n controller.close();\n } catch {\n // Already closed\n }\n });\n },\n });\n }\n\n return bgManager.stream({ agentId, runId, threadId, resourceId, taskId, abortSignal, allResources: !scoped });\n },\n});\n\nexport const LIST_BACKGROUND_TASKS_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks',\n responseType: 'json' as const,\n queryParamSchema: listBackgroundTasksQuerySchema,\n responseSchema: listBackgroundTaskResponseSchema,\n summary: 'List background tasks',\n description: 'Returns background tasks filtered by status, agent, run, etc.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, ...params }) => {\n const { resourceId } = resolveResourceScope(requestContext, params.resourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — there are no tasks to return.\n return { tasks: [], total: 0 };\n }\n\n return bgManager.listTasks({ ...params, resourceId });\n },\n});\n\nexport const GET_BACKGROUND_TASK_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/:backgroundTaskId',\n responseType: 'json' as const,\n pathParamSchema: backgroundTaskIdPathParams,\n responseSchema: backgroundTaskResponseSchema,\n summary: 'Get a background task by ID',\n description: 'Returns a background task by ID.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, backgroundTaskId, requestContext }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, undefined);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — the task can't exist.\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n\n const task = await bgManager.getTask(backgroundTaskId);\n // Report another resource's task as missing so its existence is not disclosed.\n if (!task || (scoped && task.resourceId !== resourceId)) {\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n return task;\n },\n});\n"],"mappings":";;;;;;AAGA,MAAa,6BAA6BA,IAAAA,EAAE,KAAK;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkCA,IAAAA,EAAE,OAAO;CACtD,SAASA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;AAC9B,CAAC;AAED,MAAa,iCAAiCA,IAAAA,EAAE,KAAK;CAAC;CAAa;CAAa;CAAe;AAAa,CAAC;AAE7G,MAAa,iCAAiCA,IAAAA,EAAE,OAAO;CACrD,SAASA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,QAAQ,2BAA2B,SAAS;CAC5C,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAAA,EAAE,OAAO,KAAK,CAAC,CAAC,SAAS;CACnC,QAAQA,IAAAA,EAAE,OAAO,KAAK,CAAC,CAAC,SAAS;CACjC,cAAc,+BAA+B,SAAS;CACtD,SAAS,+BAA+B,SAAS;CACjD,gBAAgBA,IAAAA,EAAE,KAAK,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,SA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;EACxD,MAAM,EAAE,eAAe,qBAAqB,gBAAgB,OAAO,UAAU;EAC7E,MAAM,YAAY,OAAO;EACzB,IAAI,CAAC,WAEH,OAAO;GAAE,OAAO,CAAC;GAAG,OAAO;EAAE;EAG/B,OAAO,UAAU,UAAU;GAAE,GAAG;GAAQ;EAAW,CAAC;CACtD;AACF,CAAC;AAED,MAAa,4BAA4BA,sBAAAA,YAAY;CACnD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,kBAAkB;CACzB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,kBAAkB,qBAAqB;EAC/D,MAAM,EAAE,YAAY,WAAW,qBAAqB,gBAAgB,KAAA,CAAS;EAC7E,MAAM,YAAY,OAAO;EACzB,IAAI,CAAC,WAEH,MAAM,IAAID,uBAAAA,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAGvE,MAAM,OAAO,MAAM,UAAU,QAAQ,gBAAgB;EAErD,IAAI,CAAC,QAAS,UAAU,KAAK,eAAe,YAC1C,MAAM,IAAIA,uBAAAA,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAEvE,OAAO;CACT;AACF,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as HTTPException } from "./http-exception-CyfxZB6W.js";
|
|
2
2
|
import { c as paginationNumber } from "./common-Y30XtCyr.js";
|
|
3
3
|
import { n as createRoute } from "./route-builder-lBil8Cvo.js";
|
|
4
|
-
import { n as getContextResourceId } from "./utils-
|
|
4
|
+
import { n as getContextResourceId } from "./utils-mIFmRM_j.js";
|
|
5
5
|
import { z as z$1 } from "zod";
|
|
6
6
|
//#region src/server/schemas/background-tasks.ts
|
|
7
7
|
const backgroundTaskStatusSchema = z$1.enum([
|
|
@@ -168,4 +168,4 @@ const GET_BACKGROUND_TASK_ROUTE = createRoute({
|
|
|
168
168
|
//#endregion
|
|
169
169
|
export { GET_BACKGROUND_TASK_ROUTE as n, LIST_BACKGROUND_TASKS_ROUTE as r, BACKGROUND_TASK_STREAM_ROUTE as t };
|
|
170
170
|
|
|
171
|
-
//# sourceMappingURL=background-tasks-
|
|
171
|
+
//# sourceMappingURL=background-tasks-Clbud7G4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-tasks-_e2S8LLH.js","names":["z"],"sources":["../src/server/schemas/background-tasks.ts","../src/server/handlers/background-tasks.ts"],"sourcesContent":["import { z } from 'zod';\nimport { paginationNumber } from './common';\n\nexport const backgroundTaskStatusSchema = z.enum([\n 'pending',\n 'running',\n 'suspended',\n 'completed',\n 'failed',\n 'cancelled',\n 'timed_out',\n]);\n\nexport const backgroundTaskStreamQuerySchema = z.object({\n agentId: z.string().optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n taskId: z.string().optional(),\n});\n\nexport const backgroundTaskDateColumnSchema = z.enum(['createdAt', 'startedAt', 'suspendedAt', 'completedAt']);\n\nexport const listBackgroundTasksQuerySchema = z.object({\n agentId: z.string().optional(),\n status: backgroundTaskStatusSchema.optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n toolName: z.string().optional(),\n toolCallId: z.string().optional(),\n fromDate: z.coerce.date().optional(),\n toDate: z.coerce.date().optional(),\n dateFilterBy: backgroundTaskDateColumnSchema.optional(),\n orderBy: backgroundTaskDateColumnSchema.optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n page: paginationNumber().optional(),\n perPage: paginationNumber().optional(),\n});\n\nexport const backgroundTaskIdPathParams = z.object({\n backgroundTaskId: z.string(),\n});\n\nexport const backgroundTaskResponseSchema = z.object({\n id: z.string(),\n status: backgroundTaskStatusSchema,\n toolName: z.string(),\n toolCallId: z.string(),\n args: z.record(z.string(), z.unknown()),\n agentId: z.string(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n runId: z.string(),\n result: z.unknown().optional(),\n error: z.object({ message: z.string(), stack: z.string().optional() }).optional(),\n createdAt: z.date(),\n startedAt: z.date().optional(),\n completedAt: z.date().optional(),\n retryCount: z.number(),\n maxRetries: z.number(),\n timeoutMs: z.number(),\n suspendPayload: z.unknown().optional(),\n});\n\nexport const listBackgroundTaskResponseSchema = z.object({\n tasks: z.array(backgroundTaskResponseSchema),\n total: z.number(),\n});\n\nexport const backgroundTaskStreamResponseSchema = z.unknown();\n","import { HTTPException } from '../http-exception';\nimport {\n backgroundTaskResponseSchema,\n backgroundTaskStreamQuerySchema,\n backgroundTaskStreamResponseSchema,\n listBackgroundTaskResponseSchema,\n listBackgroundTasksQuerySchema,\n backgroundTaskIdPathParams,\n} from '../schemas/background-tasks';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { getContextResourceId } from './utils';\n\n/**\n * Resolves the resource filter for a background-task request. A resource-scoped caller\n * is pinned to its own resource and may not request another one; a privileged caller\n * (no resource in the request context) keeps the client-provided filter.\n */\nfunction resolveResourceScope(\n requestContext: Parameters<typeof getContextResourceId>[0],\n clientResourceId: string | undefined,\n): { resourceId: string | undefined; scoped: boolean } {\n const contextResourceId = getContextResourceId(requestContext);\n if (contextResourceId === undefined) return { resourceId: clientResourceId, scoped: false };\n // An empty resource id must not be mistaken for a privileged (unscoped) caller, and\n // storage filters ignore empty strings, so it cannot be scoped safely either.\n if (contextResourceId === '') {\n throw new HTTPException(403, { message: 'Access denied: authenticated resourceId is empty' });\n }\n if (clientResourceId !== undefined && clientResourceId !== contextResourceId) {\n throw new HTTPException(403, { message: 'Access denied: resourceId does not match the authenticated resource' });\n }\n return { resourceId: contextResourceId, scoped: true };\n}\n\nexport const BACKGROUND_TASK_STREAM_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n queryParamSchema: backgroundTaskStreamQuerySchema,\n responseSchema: backgroundTaskStreamResponseSchema,\n summary: 'Stream background task events via SSE',\n description: 'Real-time Server-Sent Events stream of background task completion/failure events.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({\n mastra,\n agentId,\n runId,\n threadId,\n resourceId: clientResourceId,\n taskId,\n abortSignal,\n requestContext,\n }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, clientResourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks are not enabled — return an empty stream that stays\n // open until the client disconnects. This avoids spamming the logs with\n // false-positive errors when clients (e.g. the studio UI) optimistically\n // subscribe to the stream.\n return new ReadableStream({\n start(controller) {\n abortSignal?.addEventListener('abort', () => {\n try {\n controller.close();\n } catch {\n // Already closed\n }\n });\n },\n });\n }\n\n return bgManager.stream({ agentId, runId, threadId, resourceId, taskId, abortSignal, allResources: !scoped });\n },\n});\n\nexport const LIST_BACKGROUND_TASKS_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks',\n responseType: 'json' as const,\n queryParamSchema: listBackgroundTasksQuerySchema,\n responseSchema: listBackgroundTaskResponseSchema,\n summary: 'List background tasks',\n description: 'Returns background tasks filtered by status, agent, run, etc.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, ...params }) => {\n const { resourceId } = resolveResourceScope(requestContext, params.resourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — there are no tasks to return.\n return { tasks: [], total: 0 };\n }\n\n return bgManager.listTasks({ ...params, resourceId });\n },\n});\n\nexport const GET_BACKGROUND_TASK_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/:backgroundTaskId',\n responseType: 'json' as const,\n pathParamSchema: backgroundTaskIdPathParams,\n responseSchema: backgroundTaskResponseSchema,\n summary: 'Get a background task by ID',\n description: 'Returns a background task by ID.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, backgroundTaskId, requestContext }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, undefined);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — the task can't exist.\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n\n const task = await bgManager.getTask(backgroundTaskId);\n // Report another resource's task as missing so its existence is not disclosed.\n if (!task || (scoped && task.resourceId !== resourceId)) {\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n return task;\n },\n});\n"],"mappings":";;;;;;AAGA,MAAa,6BAA6BA,IAAE,KAAK;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkCA,IAAE,OAAO;CACtD,SAASA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,OAAOA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQA,IAAE,OAAO,CAAC,CAAC,SAAS;AAC9B,CAAC;AAED,MAAa,iCAAiCA,IAAE,KAAK;CAAC;CAAa;CAAa;CAAe;AAAa,CAAC;AAE7G,MAAa,iCAAiCA,IAAE,OAAO;CACrD,SAASA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,QAAQ,2BAA2B,SAAS;CAC5C,OAAOA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAE,OAAO,KAAK,CAAC,CAAC,SAAS;CACnC,QAAQA,IAAE,OAAO,KAAK,CAAC,CAAC,SAAS;CACjC,cAAc,+BAA+B,SAAS;CACtD,SAAS,+BAA+B,SAAS;CACjD,gBAAgBA,IAAE,KAAK,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS;CACjD,MAAM,iBAAiB,CAAC,CAAC,SAAS;CAClC,SAAS,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CACT,aAAa;CACb,MAAM,CAAC,kBAAkB;CACzB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,kBAAkB,qBAAqB;EAC/D,MAAM,EAAE,YAAY,WAAW,qBAAqB,gBAAgB,KAAA,CAAS;EAC7E,MAAM,YAAY,OAAO;EACzB,IAAI,CAAC,WAEH,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAGvE,MAAM,OAAO,MAAM,UAAU,QAAQ,gBAAgB;EAErD,IAAI,CAAC,QAAS,UAAU,KAAK,eAAe,YAC1C,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAEvE,OAAO;CACT;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"background-tasks-Clbud7G4.js","names":["z"],"sources":["../src/server/schemas/background-tasks.ts","../src/server/handlers/background-tasks.ts"],"sourcesContent":["import { z } from 'zod';\nimport { paginationNumber } from './common';\n\nexport const backgroundTaskStatusSchema = z.enum([\n 'pending',\n 'running',\n 'suspended',\n 'completed',\n 'failed',\n 'cancelled',\n 'timed_out',\n]);\n\nexport const backgroundTaskStreamQuerySchema = z.object({\n agentId: z.string().optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n taskId: z.string().optional(),\n});\n\nexport const backgroundTaskDateColumnSchema = z.enum(['createdAt', 'startedAt', 'suspendedAt', 'completedAt']);\n\nexport const listBackgroundTasksQuerySchema = z.object({\n agentId: z.string().optional(),\n status: backgroundTaskStatusSchema.optional(),\n runId: z.string().optional(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n toolName: z.string().optional(),\n toolCallId: z.string().optional(),\n fromDate: z.coerce.date().optional(),\n toDate: z.coerce.date().optional(),\n dateFilterBy: backgroundTaskDateColumnSchema.optional(),\n orderBy: backgroundTaskDateColumnSchema.optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n page: paginationNumber().optional(),\n perPage: paginationNumber().optional(),\n});\n\nexport const backgroundTaskIdPathParams = z.object({\n backgroundTaskId: z.string(),\n});\n\nexport const backgroundTaskResponseSchema = z.object({\n id: z.string(),\n status: backgroundTaskStatusSchema,\n toolName: z.string(),\n toolCallId: z.string(),\n args: z.record(z.string(), z.unknown()),\n agentId: z.string(),\n threadId: z.string().optional(),\n resourceId: z.string().optional(),\n runId: z.string(),\n result: z.unknown().optional(),\n error: z.object({ message: z.string(), stack: z.string().optional() }).optional(),\n createdAt: z.date(),\n startedAt: z.date().optional(),\n completedAt: z.date().optional(),\n retryCount: z.number(),\n maxRetries: z.number(),\n timeoutMs: z.number(),\n suspendPayload: z.unknown().optional(),\n});\n\nexport const listBackgroundTaskResponseSchema = z.object({\n tasks: z.array(backgroundTaskResponseSchema),\n total: z.number(),\n});\n\nexport const backgroundTaskStreamResponseSchema = z.unknown();\n","import { HTTPException } from '../http-exception';\nimport {\n backgroundTaskResponseSchema,\n backgroundTaskStreamQuerySchema,\n backgroundTaskStreamResponseSchema,\n listBackgroundTaskResponseSchema,\n listBackgroundTasksQuerySchema,\n backgroundTaskIdPathParams,\n} from '../schemas/background-tasks';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { getContextResourceId } from './utils';\n\n/**\n * Resolves the resource filter for a background-task request. A resource-scoped caller\n * is pinned to its own resource and may not request another one; a privileged caller\n * (no resource in the request context) keeps the client-provided filter.\n */\nfunction resolveResourceScope(\n requestContext: Parameters<typeof getContextResourceId>[0],\n clientResourceId: string | undefined,\n): { resourceId: string | undefined; scoped: boolean } {\n const contextResourceId = getContextResourceId(requestContext);\n if (contextResourceId === undefined) return { resourceId: clientResourceId, scoped: false };\n // An empty resource id must not be mistaken for a privileged (unscoped) caller, and\n // storage filters ignore empty strings, so it cannot be scoped safely either.\n if (contextResourceId === '') {\n throw new HTTPException(403, { message: 'Access denied: authenticated resourceId is empty' });\n }\n if (clientResourceId !== undefined && clientResourceId !== contextResourceId) {\n throw new HTTPException(403, { message: 'Access denied: resourceId does not match the authenticated resource' });\n }\n return { resourceId: contextResourceId, scoped: true };\n}\n\nexport const BACKGROUND_TASK_STREAM_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/stream',\n responseType: 'stream' as const,\n streamFormat: 'sse' as const,\n queryParamSchema: backgroundTaskStreamQuerySchema,\n responseSchema: backgroundTaskStreamResponseSchema,\n summary: 'Stream background task events via SSE',\n description: 'Real-time Server-Sent Events stream of background task completion/failure events.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({\n mastra,\n agentId,\n runId,\n threadId,\n resourceId: clientResourceId,\n taskId,\n abortSignal,\n requestContext,\n }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, clientResourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks are not enabled — return an empty stream that stays\n // open until the client disconnects. This avoids spamming the logs with\n // false-positive errors when clients (e.g. the studio UI) optimistically\n // subscribe to the stream.\n return new ReadableStream({\n start(controller) {\n abortSignal?.addEventListener('abort', () => {\n try {\n controller.close();\n } catch {\n // Already closed\n }\n });\n },\n });\n }\n\n return bgManager.stream({ agentId, runId, threadId, resourceId, taskId, abortSignal, allResources: !scoped });\n },\n});\n\nexport const LIST_BACKGROUND_TASKS_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks',\n responseType: 'json' as const,\n queryParamSchema: listBackgroundTasksQuerySchema,\n responseSchema: listBackgroundTaskResponseSchema,\n summary: 'List background tasks',\n description: 'Returns background tasks filtered by status, agent, run, etc.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, requestContext, ...params }) => {\n const { resourceId } = resolveResourceScope(requestContext, params.resourceId);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — there are no tasks to return.\n return { tasks: [], total: 0 };\n }\n\n return bgManager.listTasks({ ...params, resourceId });\n },\n});\n\nexport const GET_BACKGROUND_TASK_ROUTE = createRoute({\n method: 'GET',\n path: '/background-tasks/:backgroundTaskId',\n responseType: 'json' as const,\n pathParamSchema: backgroundTaskIdPathParams,\n responseSchema: backgroundTaskResponseSchema,\n summary: 'Get a background task by ID',\n description: 'Returns a background task by ID.',\n tags: ['Background Tasks'],\n requiresAuth: true,\n handler: async ({ mastra, backgroundTaskId, requestContext }) => {\n const { resourceId, scoped } = resolveResourceScope(requestContext, undefined);\n const bgManager = mastra.backgroundTaskManager;\n if (!bgManager) {\n // Background tasks not enabled — the task can't exist.\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n\n const task = await bgManager.getTask(backgroundTaskId);\n // Report another resource's task as missing so its existence is not disclosed.\n if (!task || (scoped && task.resourceId !== resourceId)) {\n throw new HTTPException(404, { message: 'Background task not found' });\n }\n return task;\n },\n});\n"],"mappings":";;;;;;AAGA,MAAa,6BAA6BA,IAAE,KAAK;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkCA,IAAE,OAAO;CACtD,SAASA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,OAAOA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAAQA,IAAE,OAAO,CAAC,CAAC,SAAS;AAC9B,CAAC;AAED,MAAa,iCAAiCA,IAAE,KAAK;CAAC;CAAa;CAAa;CAAe;AAAa,CAAC;AAE7G,MAAa,iCAAiCA,IAAE,OAAO;CACrD,SAASA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,QAAQ,2BAA2B,SAAS;CAC5C,OAAOA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,YAAYA,IAAE,OAAO,CAAC,CAAC,SAAS;CAChC,UAAUA,IAAE,OAAO,KAAK,CAAC,CAA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AI,CAAC,WAEH,OAAO;GAAE,OAAO,CAAC;GAAG,OAAO;EAAE;EAG/B,OAAO,UAAU,UAAU;GAAE,GAAG;GAAQ;EAAW,CAAC;CACtD;AACF,CAAC;AAED,MAAa,4BAA4B,YAAY;CACnD,QAAQ;CACR,MAAM;CACN,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,SAAS;CACT,aAAa;CACb,MAAM,CAAC,kBAAkB;CACzB,cAAc;CACd,SAAS,OAAO,EAAE,QAAQ,kBAAkB,qBAAqB;EAC/D,MAAM,EAAE,YAAY,WAAW,qBAAqB,gBAAgB,KAAA,CAAS;EAC7E,MAAM,YAAY,OAAO;EACzB,IAAI,CAAC,WAEH,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAGvE,MAAM,OAAO,MAAM,UAAU,QAAQ,gBAAgB;EAErD,IAAI,CAAC,QAAS,UAAU,KAAK,eAAe,YAC1C,MAAM,IAAI,cAAc,KAAK,EAAE,SAAS,4BAA4B,CAAC;EAEvE,OAAO;CACT;AACF,CAAC"}
|
package/dist/docs/SKILL.md
CHANGED
|
@@ -93,6 +93,14 @@ Configure validation appropriate to your issuer, including audience and expiry c
|
|
|
93
93
|
|
|
94
94
|
Protecting Mastra routes with `server.auth` and providing interoperable OAuth discovery are different tasks. Don't assume configuring one supplies the other.
|
|
95
95
|
|
|
96
|
+
### Routes Mastra registers for an MCP server
|
|
97
|
+
|
|
98
|
+
Alongside the MCP transport, Mastra registers REST routes used by Studio to list servers, inspect tools, execute tools, and read resources. See the [MCP routes reference](https://mastra.ai/reference/server/routes) for the full list. These paths use the default `/api` prefix.
|
|
99
|
+
|
|
100
|
+
The `POST /api/mcp/:serverId/tools/:toolId/execute` route calls `executeTool()` directly, without a protocol client. With a Mastra FGA provider configured, `MCPServer.executeTool()` enforces tool execution permission using the user in `requestContext`. The REST tool list also filters tools through FGA. These permission checks don't replace route authentication.
|
|
101
|
+
|
|
102
|
+
Built-in authentication for these routes depends on `server.auth`. Without it, `requiresAuth: true` doesn't enforce authentication. Custom middleware that checks only the `/mcp` or `/sse` transport paths leaves the REST routes open. If you use custom middleware instead of `server.auth`, default-deny `/api/mcp/*` and allow access only after authentication.
|
|
103
|
+
|
|
96
104
|
### Pass verified identity to tools
|
|
97
105
|
|
|
98
106
|
When a Mastra server handles an MCP request, its auth bridge preserves an existing `req.auth`. Otherwise, it uses `server.mcpOptions.setRequestAuth` when configured, or builds `authInfo` from the request context. With the default bridge, the authenticated user is available in `authInfo.extra.user`.
|
|
@@ -121,9 +129,10 @@ Keep access tokens, refresh tokens, and service credentials outside model-visibl
|
|
|
121
129
|
|
|
122
130
|
- [ ] **Validate tokens:** Configure validation for your issuer, including audience and expiry checks, and confirm an unvalidated token is rejected.
|
|
123
131
|
- [ ] **Challenge missing tokens:** Confirm every protected server path returns `401` without a bearer token.
|
|
132
|
+
- [ ] **Protect MCP REST routes:** If you don't use `server.auth`, confirm `/api/mcp/:serverId/tools*`, `/api/mcp/:serverId/resources*`, and `/api/mcp/v0/servers*` aren't reachable without authentication. Use your configured API prefix if it differs from `/api`.
|
|
124
133
|
- [ ] **Isolate users:** Confirm one user's provider, connection, and stored credentials aren't reused for another user.
|
|
125
134
|
- [ ] **Bind credentials to the issuer:** Confirm registration and tokens aren't reused when the authorization server changes.
|
|
126
|
-
- [ ] **Deny unauthorized operations:** Confirm a caller without permission is denied `tools/call`, including for a tool it never listed.
|
|
135
|
+
- [ ] **Deny unauthorized operations:** Confirm a caller without permission is denied both `tools/call` and `POST /api/mcp/:serverId/tools/:toolId/execute`, including for a tool it never listed.
|
|
127
136
|
- [ ] **Scope records to the caller:** Confirm record lookups resolve the tenant from trusted server context rather than tool arguments.
|
|
128
137
|
- [ ] **Keep tokens at their audience:** Confirm upstream calls use separate credentials and never forward the MCP token.
|
|
129
138
|
- [ ] **Keep secrets out of model data:** Confirm tokens and credentials stay out of instructions, tool arguments, and tool results.
|
|
@@ -86,6 +86,10 @@ Generated servers pass `server.apiPrefix` to the Hono adapter's [`prefix` constr
|
|
|
86
86
|
|
|
87
87
|
This approach can't block routes declared public with `requiresAuth: false`, because Mastra skips user middleware for those routes. With a non-Hono server adapter, register equivalent middleware through the server framework instead.
|
|
88
88
|
|
|
89
|
+
During `mastra dev`, inspect the full built-in route list, including MCP routes, in the [OpenAPI specification](http://localhost:4111/api/openapi.json). See the [server overview](https://mastra.ai/docs/server/overview) for API exploration and production settings.
|
|
90
|
+
|
|
91
|
+
If you use middleware for authentication without `server.auth`, prefer default-deny middleware that authenticates requests before allowing access, rather than enumerating protected paths. Include the full API prefix so REST routes alongside MCP transports are covered.
|
|
92
|
+
|
|
89
93
|
### Using `RequestContext`
|
|
90
94
|
|
|
91
95
|
You can populate `RequestContext` in a runtime server middleware by extracting information from the request. In this example, the `temperature-unit` is set based on the Cloudflare `CF-IPCountry` header to ensure responses match the user's locale.
|
|
@@ -16,6 +16,7 @@ Server adapters register these routes when you call `server.init()`. All routes
|
|
|
16
16
|
| `POST` | `/api/agents/:agentId/stream` | Stream agent response |
|
|
17
17
|
| `POST` | `/api/agents/:agentId/send-message` | Send a user message to an active or idle thread |
|
|
18
18
|
| `POST` | `/api/agents/:agentId/queue-message` | Queue a user message for the next thread turn |
|
|
19
|
+
| `POST` | `/api/agents/:agentId/queue-signal` | Queue a typed signal for the next thread turn |
|
|
19
20
|
| `POST` | `/api/agents/:agentId/signals` | Send a lower-level signal to an active or idle thread |
|
|
20
21
|
| `POST` | `/api/agents/:agentId/threads/subscribe` | Subscribe to a thread stream |
|
|
21
22
|
| `POST` | `/api/agents/:agentId/threads/abort` | Abort a thread, optionally clearing pending signals |
|
|
@@ -83,6 +84,8 @@ GET /api/agents/my-agent?versionId=abc123
|
|
|
83
84
|
|
|
84
85
|
Use `POST /api/agents/:agentId/send-message` to send a user message to the active agent loop or wake an idle thread. Use `POST /api/agents/:agentId/queue-message` when the active run should finish before Mastra starts a follow-up run.
|
|
85
86
|
|
|
87
|
+
To queue a typed signal with the same ordering, use `POST /api/agents/:agentId/queue-signal` with a `signal` field in place of `message`. The `signal` field takes the same shape as `POST /api/agents/:agentId/signals`.
|
|
88
|
+
|
|
86
89
|
Both routes accept the same request body:
|
|
87
90
|
|
|
88
91
|
```typescript
|
|
@@ -542,12 +545,20 @@ Returns the persisted experiment result row.
|
|
|
542
545
|
|
|
543
546
|
## MCP
|
|
544
547
|
|
|
545
|
-
| Method | Path
|
|
546
|
-
| ------ |
|
|
547
|
-
| `GET` | `/api/mcp/servers`
|
|
548
|
-
| `GET` | `/api/mcp/servers/:
|
|
549
|
-
| `
|
|
550
|
-
| `GET` | `/api/mcp/:serverId/
|
|
548
|
+
| Method | Path | Description |
|
|
549
|
+
| ------ | ------------------------------------------ | ------------------------ |
|
|
550
|
+
| `GET` | `/api/mcp/v0/servers` | List MCP servers |
|
|
551
|
+
| `GET` | `/api/mcp/v0/servers/:id` | Get server details |
|
|
552
|
+
| `GET` | `/api/mcp/:serverId/tools` | List server tools |
|
|
553
|
+
| `GET` | `/api/mcp/:serverId/tools/:toolId` | Get tool details |
|
|
554
|
+
| `POST` | `/api/mcp/:serverId/tools/:toolId/execute` | Execute a tool |
|
|
555
|
+
| `GET` | `/api/mcp/:serverId/resources` | List server resources |
|
|
556
|
+
| `POST` | `/api/mcp/:serverId/resources/read` | Read a resource |
|
|
557
|
+
| `ALL` | `/api/mcp/:serverId/mcp` | MCP HTTP transport |
|
|
558
|
+
| `ALL` | `/api/mcp/:serverId/sse` | Legacy MCP SSE transport |
|
|
559
|
+
| `POST` | `/api/mcp/:serverId/messages` | Legacy MCP SSE messages |
|
|
560
|
+
|
|
561
|
+
All MCP routes declare `requiresAuth: true`. Authentication is enforced only when `server.auth` is configured. Paths use the default `/api` prefix. The legacy SSE routes return `404` for MCP v2 servers.
|
|
551
562
|
|
|
552
563
|
## Responses API
|
|
553
564
|
|
|
@@ -2,7 +2,7 @@ const require_http_exception = require("./http-exception-CKDHupKw.cjs");
|
|
|
2
2
|
const require_route_builder = require("./route-builder-2yrD15TL.cjs");
|
|
3
3
|
const require_server_handlers_error = require("./server/handlers/error.cjs");
|
|
4
4
|
const require_server_handlers_agents = require("./server/handlers/agents.cjs");
|
|
5
|
-
const require_editor_builder = require("./editor-builder-
|
|
5
|
+
const require_editor_builder = require("./editor-builder-DqHKoEDx.cjs");
|
|
6
6
|
//#region src/server/utils/resolve-builder-model-policy.ts
|
|
7
7
|
/**
|
|
8
8
|
* Server-side wrapper around `builderToModelPolicy`.
|
|
@@ -364,4 +364,4 @@ Object.defineProperty(exports, "requireBuilderFeature", {
|
|
|
364
364
|
}
|
|
365
365
|
});
|
|
366
366
|
|
|
367
|
-
//# sourceMappingURL=editor-builder-
|
|
367
|
+
//# sourceMappingURL=editor-builder-BOmAPurW.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor-builder-CmUsqdZq.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAA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,"file":"editor-builder-BOmAPurW.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI,CAAC,UAAU,OAAO,OAAO,mBAAmB,YAAY,OAAO;CACnE,IAAI,CAAC,OAAO,0BAA0B,GAAG,OAAO;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe;CAC5C,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,OAAO;CACzC,MAAM,WAAW,QAAQ,cAAc,CAAC,EAAE;CAC1C,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,SAASA,uBAAAA,oBAAoB,UAAU,QAAQ;CACrD,OAAO,OAAO,UAAU,OAAO,OAAO;AACxC;;;;;;AAOA,eAAsB,wBAAwB,QAAgB,SAAgD;CAE5G,QAAO,MADgB,uBAAuB,MAAM,EAAA,GAClC,aAAa;AACjC;;;;;;AAOA,eAAsB,sBAAsB,QAAgB,SAA6C;CACvG,IAAI,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gBAAgB,YAAY,YAAY,gBAAgB,WAAW,YAAY,gBAAgB,UACjG,gBAAgB,QAAQ,SACzB,CAAC;IACP,YAAY;KACV,MAAM,cAAc,QAAQ;KAC5B,aAAa,cAAc,eAAe;KAC1C,MAAM,gBAAgB,QAAQ,qBAAqB,UAAU,QAAQ;KACrE,QAAQ,qBAAqB,UAAU;KACvC,YAAY,CAAC,CAAC;KACd,eAAe,CAAC,CAAC;KACjB,YAAY,CAAC,CAAC;KACd,oBAAoB,gBAAgB,UAAU;KAC9C,iBAAiB,gBAAgB,OAAO;KACxC,QAAQ,CACN,GAAG,iBAAiB,gBAAgB,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,cAAc,MAAM;KAAM,EAAE,GACjG,GAAG,iBAAiB,aAAa,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
@@ -2,7 +2,7 @@ import { t as HTTPException } from "./http-exception-CyfxZB6W.js";
|
|
|
2
2
|
import { n as createRoute } from "./route-builder-lBil8Cvo.js";
|
|
3
3
|
import { handleError } from "./server/handlers/error.js";
|
|
4
4
|
import { buildProvidersList } from "./server/handlers/agents.js";
|
|
5
|
-
import { i as builderAvailableModelsResponseSchema, l as infrastructureStatusResponseSchema, n as agentFeaturesSchema, s as builderSettingsResponseSchema } from "./editor-builder-
|
|
5
|
+
import { i as builderAvailableModelsResponseSchema, l as infrastructureStatusResponseSchema, n as agentFeaturesSchema, s as builderSettingsResponseSchema } from "./editor-builder-DHqCWGd2.js";
|
|
6
6
|
//#region src/server/utils/resolve-builder-model-policy.ts
|
|
7
7
|
/**
|
|
8
8
|
* Server-side wrapper around `builderToModelPolicy`.
|
|
@@ -335,4 +335,4 @@ const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({
|
|
|
335
335
|
//#endregion
|
|
336
336
|
export { requireBuilderFeature as a, isBuilderFeatureEnabled as i, GET_EDITOR_BUILDER_SETTINGS_ROUTE as n, GET_INFRASTRUCTURE_STATUS_ROUTE as r, GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE as t };
|
|
337
337
|
|
|
338
|
-
//# sourceMappingURL=editor-builder-
|
|
338
|
+
//# sourceMappingURL=editor-builder-CeLVu_FT.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor-builder-DHXbVwxu.js","names":[],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI,CAAC,UAAU,OAAO,OAAO,mBAAmB,YAAY,OAAO;CACnE,IAAI,CAAC,OAAO,0BAA0B,GAAG,OAAO;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe;CAC5C,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,OAAO;CACzC,MAAM,WAAW,QAAQ,cAAc,CAAC,EAAE;CAC1C,IAAI,CA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B,UAAU,WAAW,gBAAgB;IAC1E,MAAM,mBACJ,OAAO,gBAAgB,eAAe,YACtC,gBAAgB,cAChB,YAAY,gBAAgB,aACvB,gBAAgB,WAAW,SAC5B,CAAC;IACP,MAAM,gBACJ,OAAO,gBAAgB,YAAY,YAAY,gBAAgB,WAAW,YAAY,gBAAgB,UACjG,gBAAgB,QAAQ,SACzB,CAAC;IACP,YAAY;KACV,MAAM,cAAc,QAAQ;KAC5B,aAAa,cAAc,eAAe;KAC1C,MAAM,gBAAgB,QAAQ,qBAAqB,UAAU,QAAQ;KACrE,QAAQ,qBAAqB,UAAU;KACvC,YAAY,CAAC,CAAC;KACd,eAAe,CAAC,CAAC;KACjB,YAAY,CAAC,CAAC;KACd,oBAAoB,gBAAgB,UAAU;KAC9C,iBAAiB,gBAAgB,OAAO;KACxC,QAAQ,CACN,GAAG,iBAAiB,gBAAgB,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,cAAc,MAAM;KAAM,EAAE,GACjG,GAAG,iBAAiB,aAAa,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"editor-builder-CeLVu_FT.js","names":[],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GA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AC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAO,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as providerSchema } from "./agents-
|
|
1
|
+
import { j as providerSchema } from "./agents-DNWDET4U.js";
|
|
2
2
|
import { z } from "zod/v4";
|
|
3
3
|
//#region src/server/schemas/editor-builder.ts
|
|
4
4
|
/**
|
|
@@ -191,4 +191,4 @@ const builderAvailableModelsResponseSchema = z.object({ providers: z.array(provi
|
|
|
191
191
|
//#endregion
|
|
192
192
|
export { builderModelPolicySchema as a, defaultModelEntrySchema as c, providerModelEntrySchema as d, builderAvailableModelsResponseSchema as i, infrastructureStatusResponseSchema as l, agentFeaturesSchema as n, builderPickerSchema as o, agentModelsSchema as r, builderSettingsResponseSchema as s, agentConfigurationSchema as t, pickerAllowlistSchema as u };
|
|
193
193
|
|
|
194
|
-
//# sourceMappingURL=editor-builder-
|
|
194
|
+
//# sourceMappingURL=editor-builder-DHqCWGd2.js.map
|